forked from ynpatil/boloNashik
/
InboundEmail.php
2064 lines (1793 loc) · 66.1 KB
/
InboundEmail.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Public License Version
* 1.1.3 ("License"); You may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* The Original Code is: SugarCRM Open Source
* The Initial Developer of the Original Code is SugarCRM, Inc.
* Portions created by SugarCRM are Copyright (C) 2004-2006 SugarCRM, Inc.;
* All Rights Reserved.
* Contributor(s): ______________________________________.
********************************************************************************/
/*********************************************************************************
* $Id: InboundEmail.php,v 1.126.2.1 2006/09/11 23:29:58 awu Exp $
* Description: TODO: To be written.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
function this_callback($str) {
foreach($str as $match) {
$ret .= chr(hexdec(str_replace("%","",$match)));
}
return $ret;
}
class InboundEmail extends SugarBean {
// module specific
var $conn;
// fields
var $id;
var $deleted;
var $date_entered;
var $date_modified;
var $modified_user_id;
var $created_by;
var $created_by_name;
var $modified_by_name;
var $name;
var $status;
var $server_url;
var $email_user;
var $email_password;
var $port;
var $service;
var $mailbox;
var $delete_seen;
var $mailbox_type;
var $template_id;
var $stored_options;
var $group_id;
// default attributes
var $transferEncoding = array( 0 => '7BIT',
1 => '8BIT',
2 => 'BINARY',
3 => 'BASE64',
4 => 'QUOTED-PRINTABLE',
5 => 'OTHER');
// object attributes
var $serverConnectString;
var $disable_row_level_security = true;
var $InboundEmailCachePath = 'cache/modules/InboundEmail';
var $InboundEmailCacheFile = 'InboundEmail.cache.php';
var $object_name = 'InboundEmail';
var $module_dir = 'InboundEmail';
var $table_name = 'inbound_email';
var $new_schema = true;
var $process_save_dates = true;
var $order_by;
var $db;
var $dbManager;
var $field_defs;
var $column_fields;
var $required_fields = array('name' => 'name',
'server_url' => 'server_url',
'mailbox' => 'mailbox',
'user' => 'user',
'port' => 'port',);
// custom ListView attributes
var $mailbox_type_name;
// service attributes
var $tls;
var $ca;
var $ssl;
var $protocol;
/**
* Sole constructor
*/
function InboundEmail() {
parent::SugarBean();
if(function_exists("imap_timeout")) {
/*
* 1: Open
* 2: Read
* 3: Write
* 4: Close
*/
imap_timeout(1, 60);
imap_timeout(2, 60);
imap_timeout(3, 60);
}
}
/**
* retrieves I-E bean
* @param string id
* @return object Bean
*/
function retrieve($id) {
$ret = parent::retrieve($id);
$this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
return $ret;
}
/**
* wraps SugarBean->save()
* @param string ID of saved bean
*/
function save($check_notify=false) {
$this->email_password = blowfishEncode(blowfishGetKey('InboundEmail'), $this->email_password);
return parent::save($check_notify);
}
/**
* soft deletes a User's personal inbox
* @param string id I-E id
* @param string user_name User name of User in focus, NOT current_user
* @return bool True on success
*/
function deletePersonalEmailAccount($id, $user_name) {
$q = "SELECT ie.id FROM inbound_email ie LEFT JOIN users u ON ie.group_id = u.id WHERE u.user_name = '{$user_name}'";
$r = $this->db->query($q);
while($a = $this->db->fetchByAssoc($r)) {
if(!empty($a) && $a['id'] == $id) {
$this->retrieve($id);
$this->deleted = 1;
$this->save();
return true;
}
}
return false;
}
/**
* Saves Personal Inbox settings for Users
* @return boolean true on success, false on fail
*/
function savePersonalEmailAccount($userId = '', $userName = '') {
global $current_user;
if(!empty($userId)) {
$groupId = $userId;
} elseif(isset($_REQUEST['group_id'])) {
$groupId = $_REQUEST['group_id'];
} else {
return false;
}
if(isset($_REQUEST['ie_id']) && !empty($_REQUEST['ie_id'])) {
$this->retrieve($_REQUEST['ie_id']);
}
if(!empty($_REQUEST['ie_name'])) {
if(strpos($_REQUEST['ie_name'], 'personal.')) {
$ie_name = $_REQUEST['ie_name'];
} else {
$ie_name = 'personal.'.$_REQUEST['ie_name'];
}
} elseif(!empty($userName)) {
$ie_name = 'personal.'.$userName;
}
$this->name = $ie_name;
$this->group_id = $groupId;
$this->status = $_REQUEST['ie_status'];
$this->server_url = $_REQUEST['server_url'];
$this->email_user = $_REQUEST['email_user'];
$this->email_password = $_REQUEST['email_password'];
$this->port = $_REQUEST['port'];
$this->protocol = $_REQUEST['protocol'];
$this->mailbox = $_REQUEST['mailbox'];
$this->mailbox_type = 'pick'; // forcing this
if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) { $useSsl = true; }
else $useSsl = false;
$this->service = '::::::::::';
$id = $this->save(); // saving here to prevent user from having to re-enter all the info in case of error
$this->retrieve($id);
$this->protocol = $_REQUEST['protocol']; // need to set this again since we safe the "service" string to empty explode values
$opts = $this->findOptimumSettings($useSsl);
if(isset($opts['serial']) && !empty($opts['serial'])) {
$this->service = $opts['serial'];
if(isset($_REQUEST['mark_read']) && $_REQUEST['mark_read'] == 1) {
$this->delete_seen = 0;
} else {
$this->delete_seen = 1;
}
// handle stored_options serialization
if(isset($_REQUEST['only_since']) && $_REQUEST['only_since'] == 1) {
$onlySince = true;
} else {
$onlySince = false;
}
$stored_options = array();
$stored_options['from_name'] = $_REQUEST['mail_fromname'];
$stored_options['from_addr'] = $_REQUEST['mail_fromaddress'];
$stored_options['only_since'] = $onlySince;
$stored_options['filter_domain'] = '';
$this->stored_options = base64_encode(serialize($stored_options));
$this->save();
return true;
} else {
// could not find opts, no save
$GLOBALS['log']->debug('-----> InboundEmail could not find optimums for User: '.$ie_name);
return false;
}
}
/**
* Determines if this instance of I-E is for a Group Inbox or Personal Inbox
*/
function handleIsPersonal() {
$qp = 'SELECT users.id, users.user_name FROM users WHERE users.is_group = 0 AND users.deleted = 0 AND users.status = \'active\' AND users.id = \''.$this->group_id.'\'';
$rp = $this->db->query($qp);
$personalBox = array();
while($ap = $this->db->fetchByAssoc($rp)) {
$personalBox[] = array($ap['id'], $ap['user_name']);
}
if(count($personalBox) > 0) {
return true;
} else {
return false;
}
}
function getUserNameFromGroupId() {
$r = $this->db->query('SELECT users.user_name FROM users WHERE deleted=0 AND id=\''.$this->group_id.'\'');
while($a = $this->db->fetchByAssoc($r)) {
return $a['user_name'];
}
return '';
}
/**
* Programatically determines best-case settings for imap_open()
*/
function findOptimumSettings($useSsl=false, $user='', $pass='', $server='', $port='', $prot='', $mailbox='') {
global $mod_strings;
$serviceArr = array();
$returnService = array();
$badService = array();
$goodService = array();
$errorArr = array();
$retArray = array( 'good' => $goodService,
'bad' => $badService,
'err' => $errorArr);
if(!function_exists('imap_open')) {
$retArray['err'][0] = $mod_strings['ERR_NO_IMAP'];
return $retArray;
}
imap_errors(); // clearing error stack
error_reporting(0); // turn off notices from IMAP
if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) {
$useSsl = true;
}
$exServ = explode('::', $this->service);
$service = '/'.$exServ[1];
$nonSsl = array('none' => '', // try default nothing
'secure' => '/secure', // for POP3 servers that force CRAM-MD5
'notls' => '/notls',
'notls-secure' => '/notls/secure',
'nocert' => '/novalidate-cert',
'nocert-secure' => '/novalidate-cert/secure',
'both' => '/notls/novalidate-cert',
'both-secure' => '/notls/novalidate-cert/secure',
);
$ssl = array( 'ssl-none' => '/ssl',
'ssl-secure' => '/ssl/secure',
'ssl-notls' => '/ssl/notls',
'ssl-notls-secure' => '/ssl/notls/secure',
'ssl-nocert' => '/ssl/novalidate-cert',
'ssl-nocert-secure' => '/ssl/novalidate-cert/secure',
'ssl-both-off' => '/ssl/notls/novalidate-cert',
'ssl-both-off-secure' => '/ssl/notls/novalidate-cert/secure',
'ssl-tls' => '/ssl/tls',
'ssl-tls-secure' => '/ssl/tls/secure',
'ssl-cert' => '/ssl/validate-cert',
'ssl-cert-secure' => '/ssl/validate-cert/secure',
'ssl-both-on' => '/ssl/tls/validate-cert',
'ssl-both-on-secure' => '/ssl/tls/validate-cert/secure',
);
if(isset($user) && !empty($user) && isset($pass) && !empty($pass)) {
$this->email_password = $pass;
$this->email_user = $user;
$this->server_url = $server;
$this->port = $port;
$this->protocol = $prot;
$this->mailbox = $mailbox;
}
// in case we flip from IMAP to POP3
if($this->protocol == 'pop3') $this->mailbox = 'INBOX';
if($useSsl == true) {
//$ssl = array_merge($ssl, $nonSsl);
foreach($ssl as $k => $service) {
$returnService[$k] = 'foo'.$service;
$serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$this->mailbox;
}
} else {
foreach($nonSsl as $k => $service) {
$returnService[$k] = 'foo'.$service;
$serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$this->mailbox;
}
}
$GLOBALS['log']->debug('---------------STARTING FINDOPTIMUMS LOOP----------------');
$l = 1;
$login = $this->email_user;
$passw = $this->email_password;
foreach($serviceArr as $k => $serviceTest) {
$errors = '';
$alerts = '';
$GLOBALS['log']->debug($l.': I-E testing string: '.$serviceTest);
// open the connection and try the test string
$this->conn = imap_open($serviceTest, $login, $passw);
if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
if($errors == 'Too many login failures' || $errors == '[CLOSED] IMAP connection broken (server response)') { // login failure means don't bother trying the rest
$GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.']');
$retArray['err'][$k] = $mod_strings['ERR_BAD_LOGIN_PASSWORD'];
$retArray['bad'][$k] = $serviceTest;
$GLOBALS['log']->fatal($l.': I-E ERROR: $ie->findOptimums() failed due to bad user credentials for user login: '.$this->email_user);
return $retArray;
} elseif($errors == 'Mailbox is empty') { // false positive
$GLOBALS['log']->debug($l.': I-E found good connect, but empty mailbox using ['.$serviceTest.']');
$retArray['good'][$k] = $returnService[$k];
} else {
$GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.'] - error: '.$errors);
$retArray['err'][$k] = $errors;
$retArray['bad'][$k] = $serviceTest;
}
} else {
$GLOBALS['log']->debug($l.': I-E found good connect using ['.$serviceTest.']');
$retArray['good'][$k] = $returnService[$k];
}
if(is_resource($this->conn)) {
if(!imap_close($this->conn)) $GLOBALS['log']->fatal('imap_close() failed!');
}
$GLOBALS['log']->debug($l.': I-E clearing error and alert stacks.');
imap_errors(); // clear stacks
imap_alerts();
$l++;
}
$GLOBALS['log']->debug('---------------end FINDOPTIMUMS LOOP----------------');
//_pp($goodService); _pp($errorArr); _pp($badService);
if(!empty($retArray['good'])) {
$newTls = '';
$newCert = '';
$newSsl = '';
$newNotls = '';
$newNovalidate_cert = '';
$good = array_pop($retArray['good']); // get most complete string
$exGood = explode('/', $good);
foreach($exGood as $v) {
switch($v) {
case 'ssl':
$newSsl = 'ssl';
break;
case 'tls':
$newTls = 'tls';
break;
case 'notls':
$newNotls = 'notls';
break;
case 'cert':
$newCert = 'validate-cert';
break;
case 'novalidate-cert':
$newNovalidate_cert = 'novalidate-cert';
break;
case 'secure':
$secure = 'secure';
break;
}
}
// $tls.'::'.$cert.'::'.$ssl.'::'.$protocol.'::'.$novalidate_cert.'::'.$notls;
$goodStr['serial'] = $newTls.'::'.$newCert.'::'.$newSsl.'::'.$this->protocol.'::'.$newNovalidate_cert.'::'.$newNotls.'::'.$secure;
$goodStr['service'] = $good;
return $goodStr;
} else {
return false;
}
}
/**
* Checks for duplicate Group User names when creating a new one at save()
* @return GUID returns GUID of Group User if user_name match is
* found
* @return boolean false if NO DUPE IS FOUND
*/
function groupUserDupeCheck() {
$q = "SELECT u.id FROM users u WHERE u.deleted=0 AND u.is_group=1 AND u.user_name = '".$this->name."'";
$r = $this->db->query($q);
$uid = '';
while($a = $this->db->fetchByAssoc($r)) {
$uid = $a['id'];
}
if(strlen($uid) > 0) {
return $uid;
} else {
return false;
}
}
function getGroupsWithSelectOptions() {
$r = $this->db->query('SELECT id, user_name FROM users WHERE users.is_group = 1 AND deleted = 0');
if(is_resource($r)) {
$groupKeys = array();
$groupVals = array();
while($a = $this->db->fetchByAssoc($r)) {
$groupKeys[$a['id']] = $a['user_name'];
}
$selectOptions = get_select_options_with_id_separate_key($groupKeys, $groupKeys, $this->group_id);
return $selectOptions;
} else {
return false;
}
}
/**
* handles auto-responses to inbound emails
*
* @param object email Email passed as reference
*/
function handleAutoresponse(&$email, &$contactAddr) {
if($this->template_id) {
$GLOBALS['log']->debug('found auto-reply template id - prefilling and mailing response');
if($this->getAutoreplyStatus($contactAddr)
&& $this->checkOutOfOffice($email->name)
&& $this->checkFilterDomain($email)) { // if we haven't sent this guy 10 replies in 24hours
if(!empty($this->stored_options)) {
$storedOptions = unserialize(base64_decode($this->stored_options));
}
// get FROM NAME
if(!empty($storedOptions['from_name'])) {
$from_name = $storedOptions['from_name'];
$GLOBALS['log']->debug('got from_name from storedOptions: '.$from_name);
} else { // use system default
$rName = $this->db->query('SELECT value FROM config WHERE name = \'fromname\'');
if(is_resource($rName)) {
$aName = $this->db->fetchByAssoc($rName);
}
if(!empty($aName['value'])) {
$from_name = $aName['value'];
} else {
$from_name = '';
}
}
// get FROM ADDRESS
if(!empty($storedOptions['from_addr'])) {
$from_addr = $storedOptions['from_addr'];
} else {
$rAddr = $this->db->query('SELECT value FROM config WHERE name = \'fromaddress\'');
if(is_resource($rAddr)) {
$aAddr = $this->db->fetchByAssoc($rAddr);
}
if(!empty($aAddr['value'])) {
$from_addr = $aAddr['value'];
} else {
$from_addr = '';
}
}
// handle to: address, prefer reply-to
if(!empty($email->reply_to_email)) {
$to[0]['email'] = $email->reply_to_email;
} else {
$to[0]['email'] = $email->from_addr;
}
// handle to name: address, prefer reply-to
if(!empty($email->reply_to_name)) {
$to[0]['display'] = $email->reply_to_name;
} elseif(!empty($email->from_name)) {
$to[0]['display'] = $email->from_name;
}
if(!class_exists('EmailTemplate')) {
require_once('modules/EmailTemplates/EmailTemplate.php');
}
$et = new EmailTemplate();
$et->retrieve($this->template_id);
if(empty($et->subject)) { $et->subject = ''; }
if(empty($et->body)) { $et->body = ''; }
if(empty($et->body_html)) { $et->body_html = ''; }
$reply = new Email();
$reply->type = 'out';
$reply->to_addrs = $to[0]['email'];
$reply->to_addrs_arr = $to;
$reply->cc_addrs_arr = array();
$reply->bcc_addrs_arr = array();
$reply->from_name = $from_name;
$reply->from_addr = $from_addr;
$reply->name = $et->subject;
$reply->description = $et->body;
$reply->description_html = $et->body_html;
$GLOBALS['log']->debug('saving and sending auto-reply email');
//$reply->save(); // don't save the actual email.
$reply->send();
$this->setAutoreplyStatus($contactAddr);
} else {
$GLOBALS['log']->debug('InboundEmail: auto-reply threshold reached for email ('.$contactAddr.') - not sending auto-reply');
}
}
}
/**
* handles functionality specific to the Mailbox type (Cases, bounced
* campaigns, etc.)
*
* @param object email Email object passed as a reference
* @param object header Header object generated by imap_headerinfo();
*/
function handleMailboxType(&$email, &$header) {
switch($this->mailbox_type) {
case 'support':
if(!class_exists('aCase')) {
require_once('modules/Cases/Case.php');
}
$c = new aCase();
$GLOBALS['log']->debug('looking for a case for '.$email->name);
if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
$c->retrieve($caseId);
$c->load_relationship('emails');
$c->emails->add($email->id);
$email->retrieve($email->id);
$email->parent_type = "Cases";
$email->parent_id = $caseId;
$email->save();
$GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
}
break;
case 'bug':
break;
case 'info':
// do something with this?
break;
case 'sales':
// do something with leads? we don't have an email_leads table
break;
case 'task':
// do something?
break;
case 'bounce':
require_once('modules/Campaigns/ProcessBouncedEmails.php');
campaign_process_bounced_emails($email, $header);
break;
case 'pick': // do all except bounce handling
require_once('modules/Cases/Case.php');
$c = new aCase();
$GLOBALS['log']->debug('looking for a case for '.$email->name);
if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
$c->retrieve($caseId);
$c->load_relationship('emails');
$c->emails->add($email->id);
$email->retrieve($email->id);
$email->parent_type = "Cases";
$email->parent_id = $caseId;
$email->save();
$GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
}
break;
}
}
/**
* handles linking contacts, accounts, etc. to an email
*
* @param object Email bean to be linked against
* @return string contactAddr is the email address of the sender
*/
function handleLinking(&$email) {
// link email to an User if emails match TO addr
if($userIds = $this->getRelatedId($email->to_addrs, 'users')) {
// link the user to the email
$email->load_relationship('users');
$email->users->add($userIds);
}
// link email to a Contact, Lead, or Account if the emails match
// give precedence to REPLY-TO above FROM
if(!empty($email->reply_to_email)) {
$contactAddr = $email->reply_to_email;
} else {
$contactAddr = $email->from_addr;
}
if($leadIds = $this->getRelatedId($contactAddr, 'leads')) {
$email->load_relationship('leads');
$email->leads->add($leadIds);
if(!class_exists('Lead')) {
require_once('modules/Leads/Lead.php');
}
foreach($leadIds as $leadId) {
$lead = new Lead();
$lead->retrieve($leadId);
$lead->load_relationship('emails');
$lead->emails->add($email->id);
}
}
if($contactIds = $this->getRelatedId($contactAddr, 'contacts')) {
// link the contact to the email
$email->load_relationship('contacts');
$email->contacts->add($contactIds);
}
if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
// link the account to the email
$email->load_relationship('accounts');
$email->accounts->add($accountIds);
if(!class_exists('Account')) {
require_once('modules/Accounts/Account.php');
}
foreach($accountIds as $accountId) {
$acct = new Account();
$acct->retrieve($accountId);
$acct->load_relationship('emails');
$acct->account_emails->add($email->id);
}
}
return $contactAddr;
}
/**
* takes a breadcrumb and returns the encoding at that level
* @param string bc the breadcrumb string in format (1.1.1)
* @param array parts the root level parts array
* @return int retInt Int key to transfer encoding (see handleTranserEncoding())
*/
function getEncodingFromBreadCrumb($bc, $parts) {
if(strstr($bc,'.')) {
$exBc = explode('.', $bc);
} else {
$exBc[0] = $bc;
}
$depth = count($exBc);
for($i=0; $i<$depth; $i++) {
$tempObj[$i] = $parts[($exBc[$i]-1)];
$retInt = imap_utf8($tempObj[$i]->encoding);
if(!empty($tempObj[$i]->parts)) {
$parts = $tempObj[$i]->parts;
}
}
return $retInt;
}
/**
* retrieves the charset for a given part of an email body
*
* @param string bc target part of the message in format (1.1.1)
* @param array parts 1 level above ROOT array of Objects representing a multipart body
* @return string charset name
*/
function getCharsetFromBreadCrumb($bc, $parts) {
if(strstr($bc,'.')) {
$exBc = explode('.', $bc);
} else {
$exBc[0] = $bc;
}
foreach($exBc as $crumb) {
$tempObj = $parts[$crumb-1];
if(is_array($tempObj->parts)) {
$parts = $tempObj->parts;
}
}
// now we have the tempObj at the end of the breadCrumb trail
//$GLOBALS['log']->fatal(print_r(debug_backtrace(), true));
if($tempObj->ifparameters) {
foreach($tempObj->parameters as $param) {
if($param->attribute == 'charset') {
return $param->value;
}
}
}
return 'default';
}
/**
* returns the HTML text part of a multi-part message
*
* @param int msgNo the relative message number for the monitored mailbox
* @param string $type the type of text processed, either 'PLAIN' or 'HTML'
* @return string UTF-8 encoded version of the requested message text
*/
function getMessageText($msgNo, $type, $structure, $fullHeader) {
$msgPart = '';
$bc = $this->buildBreadCrumbs($structure->parts, $type);
if(!empty($bc)) { // multi-part
$msgPartRaw = imap_fetchbody($this->conn, $msgNo, $bc);
$enc = $this->getEncodingFromBreadCrumb($bc, $structure->parts);
$charset = $this->getCharsetFromBreadCrumb($bc, $structure->parts);
$msgPart = $this->handleTranserEncoding($msgPartRaw, $enc);
$msgPart = $this->handleCharsetTranslation($msgPart, $charset);
/*
_pp('bc: '.$bc);
_pp("enc: ".$enc);
_pp("charset: ".$charset);
_pp("msgPart: ".$msgPart);
_pp('xfer-encoding: '.$this->transfer_encoding);
_ppd($structure->parts);
*/
return $msgPart;
} else { // either PLAIN message type (flowed) or b0rk3d RFC
// make sure we're working on valid data here.
if($structure->subtype != $type) {
return '';
}
$decodedHeader = $this->decodeHeader($fullHeader);
//_pp($fullHeader);
//_ppd($decodedHeader);
// now get actual body contents
$text = imap_body($this->conn, $msgNo);
// handle transfer encoding (usually mb-char for text portions)
if(isset($decodedHeader['Content-Transfer-Encoding'])) {
$flip = array_flip($this->transferEncoding);
$text = $this->handleTranserEncoding($text, $flip[strtoupper($decodedHeader['Content-Transfer-Encoding'])]);
}
$msgPart = $this->handleCharsetTranslation($text, $decodedHeader['Content-Type']['charset']);
//_ppl($msgPart);
return $msgPart;
} // end else clause
}
/**
* decodes raw header information and passes back an associative array with
* the important elements key'd by name
* @param header string the raw header
* @return decodedHeader array the associative array
*/
function decodeHeader($fullHeader) {
$decodedHeader = array();
$exHeaders = explode("\r", $fullHeader);
$quotes = array('"', "'");
foreach($exHeaders as $lineNum => $head) {
$key = '';
$key = trim(substr($head, 0, strpos($head, ':')));
$value = '';
$value = trim(substr($head, (strpos($head, ':') + 1), strlen($head)));
// handle content-type section in headers
if($key == 'Content-Type' && strpos($value, ';')) { // ";" means something follows related to (such as Charset)
/* Outlook can't fucking follow RFC if someone PAID them to do it...
oh wait, someone paid them NOT to do it. */
$semiColPos = mb_strpos($value, ';');
$strLenVal = mb_strlen($value);
if(($semiColPos + 4) >= $strLenVal) {
// the charset="[something]" is on the next line
$value .= str_replace($quotes, "", trim($exHeaders[$lineNum+1]));
}
$newValue = array();
$exValue = explode(';', $value);
$newValue['type'] = $exValue[0];
for($i=1; $i<count($exValue); $i++) {
$exContent = explode('=', $exValue[$i]);
$newValue[trim($exContent[0])] = trim($exContent[1]);
}
$value = $newValue;
}
if(!empty($key) && !empty($value)) {
$decodedHeader[$key] = $value;
}
}
// cn: bug 3332 and others probably
// if(isset($decodedHeader['Content-Type']) && ($decodedHeader['Content-Type']['charset'] == '') {
//
// /*
//
// reset($exHeaders);
// $bad = array('"', "'");
// foreach($exHeaders as $line) {
// $line = trim($line);
// if(strpos($line, 'charset=') !== false) {
// $line = str_replace('charset=', "", $line);
// $line = str_replace($bad, "#", $line);
// $match = preg_split('/#/', $line, -1, PREG_SPLIT_NO_EMPTY);
// }
// }
// $decodedHeader['Content-Type']['charset'] = $match[0];
// }
return $decodedHeader;
}
/**
* handles translating message text from orignal encoding into UTF-8
*
* @param string text test to be re-encoded
* @param string charset original character set
* @return string utf8 re-encoded text
*/
function handleCharsetTranslation($text, $charset) {
if(empty($charset)) {
$GLOBALS['log']->fatal("***ERROR: InboundEmail::handleCharsetTranslation() called without a \$charset!");
$GLOBALS['log']->fatal("***STACKTRACE: ".print_r(debug_backtrace(), true));
return $text;
}
// typical headers have no charset - let destination pick (since it's all ASCII anyways)
if($charset == 'default' || $charset == 'UTF-8') {
return $text;
}
if(function_exists('mb_convert_encoding')) {
$GLOBALS['log']->debug('handleCharsetTranslation is using [ mb_convert_encoding() ] to translate encoding to UTF-8 from '.$charset);
return mb_convert_encoding($text, 'UTF-8', $charset);
} elseif(function_exists('iconv')) { // oh please, oh please, oh please!
$GLOBALS['log']->debug('handleCharsetTranslation is using [ iconv() ] to translate encoding.');
return iconv($charset, 'UTF-8', $text);
} else {
$GLOBALS['log']->debug('handleCharsetTranslation is using [ SugarPHP Code ] to translate encoding.');
return $text;
}
}
/**
* Builds up the "breadcrumb" trail that imap_fetchbody() uses to return
* parts of an email message, including attachments and inline images
* @param $parts array of objects
* @param $subtype what type of trail to return? HTML? Plain? binaries?
* @param $breadcrumb text trail to build up
*/
function buildBreadCrumbs($parts, $subtype, $breadcrumb = '0') {
//_pp('buildBreadCrumbs building for '.$subtype.' with BC at '.$breadcrumb);
// loop through available parts in the array
foreach($parts as $k => $part) {
// mark passage through level
$thisBc = ($k+1);
// if this is not the first time through, start building the map
if($breadcrumb != 0) {
$thisBc = $breadcrumb.'.'.$thisBc;
}
// found a multi-part/mixed 'part' - keep digging
if($part->type == 1 && ($part->subtype == 'ALTERNATIVE' || $part->subtype == 'MIXED')) {
//_pp('in loop: going deeper with subtype: '.$part->subtype.' $k is: '.$k);
$thisBc = $this->buildBreadCrumbs($part->parts, $subtype, $thisBc);
return $thisBc;
} elseif($part->subtype == $subtype) { // found the subtype we want, return the breadcrumb value
//_pp('found '.$subtype.' bc! returning: '.$thisBc);
return $thisBc;
} else {
//_pp('found '.$part->subtype.' instead');
}
}
}
/**
* Takes a PHP imap_* object's to/from/cc/bcc address field and converts it
* to a standard string that SugarCRM expects
* @param $arr an array of email address objects
*/
function convertImapToSugarEmailAddress($arr) {
if(is_array($arr)) {
$addr = '';
foreach($arr as $key => $obj) {
$addr .= $obj->mailbox.'@'.$obj->host.', ';
}
// strip last comma
return substr_replace($addr,'',-2,-1);
}
}
/**
* tries to figure out what character set a given filename is using and
* decode based on that
*
* @param string name Name of attachment
* @return string decoded name
*/
function handleEncodedFilename($name) {
$imapDecode = imap_mime_header_decode($name);
/******************************
$imapDecode => stdClass Object
(
[charset] => utf-8
[text] => wählen.php
)
OR
$imapDecode => stdClass Object
(
[charset] => default
[text] => UTF-8''%E3%83%8F%E3%82%99%E3%82%A4%E3%82%AA%E3%82%AF%E3%82%99%E3%83%A9%E3%83%95%E3%82%A3%E3%83%BC.txt
)
*******************************/
if($imapDecode[0]->charset != 'default') { // mime-header encoded charset
$encoding = $imapDecode[0]->charset;
$name = $imapDecode[0]->text; // encoded in that charset
} else {
/* encoded filenames are formatted as [encoding]''[filename] */
if(strpos($name, "''") !== false) {
$encoding = substr($name, 0, strpos($name, "'"));
while(strpos($name, "'") !== false) {
$name = trim(substr($name, (strpos($name, "'")+1), strlen($name)));
}
}
$name = urldecode($name);
}