-
Notifications
You must be signed in to change notification settings - Fork 510
/
FetchEmails.php
1625 lines (1407 loc) · 63.7 KB
/
FetchEmails.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
namespace App\Console\Commands;
use App\Attachment;
use App\Conversation;
use App\Customer;
use App\Email;
use App\Events\ConversationCustomerChanged;
use App\Events\CustomerCreatedConversation;
use App\Events\CustomerReplied;
use App\Events\UserReplied;
use App\Mailbox;
use App\Misc\Mail;
use App\Option;
use App\SendLog;
use App\Subscription;
use App\Thread;
use App\User;
use Illuminate\Console\Command;
//use Webklex\IMAP\Client;
class FetchEmails extends Command
{
const FWD_AS_CUSTOMER_COMMAND = '@fwd';
const MAX_SLEEP = 500000;
/**
* The name and signature of the console command.
*
* --identifier parameter is used to kill fetch-emails command running for too long.
*
* @var string
*/
protected $signature = 'freescout:fetch-emails {--days=3} {--unseen=1} {--debug=0} {--identifier=dummy} {--mailboxes=0}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Fetch emails from mailboxes addresses';
/**
* Current mailbox.
*
* Used to process emails sent to multiple mailboxes.
*/
public $mailbox;
/**
* Used to process emails sent to multiple mailboxes.
*/
public $mailboxes;
public $extra_import = [];
/**
* Page size when requesting emails from mail server.
*/
const PAGE_SIZE = 300;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$now = time();
$successfully = true;
$debug = $this->option('debug');
Option::set('fetch_emails_last_run', $now);
if ($debug) {
\Config::set('imap.options.debug', true);
}
$this->line('['.date('Y-m-d H:i:s').'] Fetching '.($this->option('unseen') ? 'UNREAD' : 'ALL').' emails for the last '.$this->option('days').' days.');
if (Mailbox::getInProtocols() === Mailbox::$in_protocols) {
$this->mailboxes = Mailbox::get();
} else {
// Get active mailboxes with the default in_protocols
$this->mailboxes = Mailbox::whereIn('in_protocol', array_keys(Mailbox::$in_protocols))->get();
}
// https://github.com/freescout-helpdesk/freescout/issues/2563
// Add small delay between connections to avoid blocking by mail servers,
// especially when there many mailboxes.
// Microseconds: 1 second = 1 000 000 microseconds.
$sleep = 20000;
// Fetches specific mailboxes only, in case the corresponding id is greater than zero.
$mailboxIds = array_filter(
array_map(
'intval',
explode(',', $this->option('mailboxes'))
),
function ($mailboxId) {
return $mailboxId > 0;
}
);
foreach ($this->mailboxes as $mailbox) {
if (!$mailbox->isInActive()) {
continue;
}
if ($mailboxIds !== [] && !in_array($mailbox->id, $mailboxIds, true)) {
continue;
}
$sleep += 20000;
if ($sleep > self::MAX_SLEEP) {
$sleep = self::MAX_SLEEP;
}
$this->info('['.date('Y-m-d H:i:s').'] Mailbox: '.$mailbox->name);
$this->mailbox = $mailbox;
$this->extra_import = [];
$debug_log = '';
try {
$debug_log = $this->executeFetch($mailbox, $debug);
} catch (\Exception $e) {
// If mail server starts to block the connection
// (when there are many mailboxes for example),
// we increase connection sleep time and retry after sleep.
// https://github.com/freescout-help-desk/freescout/issues/4227
if (trim($e->getMessage()) == 'connection setup failed') {
$sleep += 500000;
usleep(self::MAX_SLEEP);
try {
$debug_log = $this->executeFetch($mailbox, $debug);
} catch (\Exception $e) {
$successfully = false;
$this->logError('Error: '.$e->getMessage().'; File: '.$e->getFile().' ('.$e->getLine().')').')';
}
} else {
$successfully = false;
$this->logError('Error: '.$e->getMessage().'; File: '.$e->getFile().' ('.$e->getLine().')').')';
}
}
if ($debug && $debug_log) {
$this->line($debug_log);
}
// Import emails sent to several mailboxes at once.
if (count($this->extra_import)) {
$this->line('['.date('Y-m-d H:i:s').'] Importing emails sent to several mailboxes at once: '.count($this->extra_import));
foreach ($this->extra_import as $i => $extra_import) {
$this->line('['.date('Y-m-d H:i:s').'] '.($i+1).') '.$extra_import['message']->getSubject());
$this->processMessage($extra_import['message'], $extra_import['message_id'], $extra_import['mailbox'], [], true);
}
}
usleep($sleep);
}
if ($successfully && count($this->mailboxes)) {
Option::set('fetch_emails_last_successful_run', $now);
}
// Middleware Terminate handler is not launched for commands,
// so we need to run processing subscription events manually
Subscription::processEvents();
$this->info('['.date('Y-m-d H:i:s').'] Fetching finished');
$this->extra_import = [];
$this->mailbox = null;
$this->mailboxes = [];
}
public function executeFetch($mailbox, $debug)
{
$debug_log = '';
if ($debug) {
ob_start();
}
$this->fetch($mailbox);
if ($debug) {
$debug_log = ob_get_contents();
ob_end_clean();
}
return $debug_log;
}
public function fetch($mailbox)
{
$no_charset = false;
$client = \MailHelper::getMailboxClient($mailbox);
// Connect to the Server.
try {
$client->connect();
} catch (\Exception $e) {
$error = $e->getMessage();
// POP3 uses LegacyProtocol.php
// https://github.com/freescout-helpdesk/freescout/issues/4060
if ($error && \Str::startsWith($error, 'Mailbox is empty')) {
$this->line('['.date('Y-m-d H:i:s').'] Fetched: 0');
return;
} else {
throw $e;
}
}
$folders = [];
// Fetch emails from custom IMAP folders.
//if ($mailbox->in_protocol == Mailbox::IN_PROTOCOL_IMAP) {
$imap_folders = $mailbox->getInImapFolders();
foreach ($imap_folders as $folder_name) {
$folder = null;
try {
$folder = \MailHelper::getImapFolder($client, $folder_name);
} catch (\Exception $e) {
// Just log error and continue.
$this->error('['.date('Y-m-d H:i:s').'] IMAP folder not found on the mail server: '.$folder_name);
}
if ($folder) {
$folders[] = $folder;
} else {
$this->line('['.date('Y-m-d H:i:s').'] IMAP folder not found on the mail server: '.$folder_name);
}
}
// try {
// //$folders = $client->getFolders();
// } catch (\Exception $e) {
// // Do nothing
// }
$unseen = \Eventy::filter('fetch_emails.unseen', $this->option('unseen'), $mailbox);
if ($unseen != $this->option('unseen')) {
$this->line('['.date('Y-m-d H:i:s').'] Fetching: '.($unseen ? 'UNREAD' : 'ALL'));
}
$page_size = (int)config('app.fetching_bunch_size');
foreach ($folders as $folder) {
$this->line('['.date('Y-m-d H:i:s').'] Folder: '.($folder->full_name ?? $folder->name));
// Requesting emails by bunches allows to fetch large amounts of emails
// without problems with memory.
$page = 0;
do {
// Get messages.
$last_error = '';
$messages = collect([]);
try {
$messages_query = $folder->query()->since(now()->subDays($this->option('days')))->leaveUnread();
if ($unseen) {
$messages_query->unseen();
}
if ($no_charset) {
$messages_query->setCharset(null);
}
$messages_query->limit($page_size, $page);
$messages = $messages_query->get();
if (method_exists($client, 'getLastError')) {
$last_error = $client->getLastError();
}
} catch (\Exception $e) {
$last_error = $e->getMessage().'; File: '.$e->getFile().' ('.$e->getLine().')'.')';
}
if ($last_error && stristr($last_error, 'The specified charset is not supported')) {
$errors_count = count($client->getErrors());
// Solution for MS mailboxes.
// https://github.com/freescout-helpdesk/freescout/issues/176
$messages_query = $folder->query()->since(now()->subDays($this->option('days')))->leaveUnread()->setCharset(null);
if ($unseen) {
$messages_query->unseen();
}
$messages = $messages_query->get();
$no_charset = true;
if (count($client->getErrors()) > $errors_count) {
$last_error = $client->getLastError();
} else {
$last_error = null;
}
}
if ($last_error && !\Str::startsWith($last_error, 'Mailbox is empty')) {
// Throw exception for INBOX only
if ($folder->name == 'INBOX' && !$messages) {
throw new \Exception($last_error, 1);
} else {
$this->error('['.date('Y-m-d H:i:s').'] '.$last_error);
$this->logError('Folder: '.$folder->name.'; Error: '.$last_error);
}
}
$this->line('['.date('Y-m-d H:i:s').'] Fetched: '.count($messages));
$message_index = 1;
// We have to sort messages manually, as they can be in non-chronological order
$messages = $this->sortMessage($messages);
foreach ($messages as $message_id => $message) {
$this->line('['.date('Y-m-d H:i:s').'] '.$message_index.') '.$message->getSubject());
$message_index++;
$dest_mailbox = \Eventy::filter('fetch_emails.mailbox_to_save_message', $mailbox, $folder);
$this->processMessage($message, $message_id, $dest_mailbox, $this->mailboxes);
}
$page++;
} while (count($messages) == $page_size);
}
$client->disconnect();
}
public function processMessage($message, $message_id, $mailbox, $mailboxes, $extra = false)
{
try {
// From - $from is the plain text email.
$from = $message->getReplyTo();
if (!$from
// https://github.com/freescout-helpdesk/freescout/issues/3101
|| !($reply_to = $this->formatEmailList($from))
|| empty($reply_to[0])
|| preg_match('/^.+@unknown$/', $reply_to[0])
) {
$from = $message->getFrom();
}
// https://github.com/freescout-helpdesk/freescout/issues/2833
/*else {
// If this is an auto-responder do not use Reply-To as sender email.
// https://github.com/freescout-helpdesk/freescout/issues/2826
$headers = $this->headerToStr($message->getHeader());
if (\MailHelper::isAutoResponder($headers)) {
$from = $message->getFrom();
}
}*/
if ($from) {
$from = $this->formatEmailList($from);
}
if (!$from) {
$this->logError('From is empty');
$this->setSeen($message, $mailbox);
return;
} else {
$from = $from[0];
}
// Message-ID can be empty.
// https://stackoverflow.com/questions/8513165/php-imap-do-emails-have-to-have-a-messageid
if (!$message_id) {
// Generate artificial Message-ID.
$message_id = \MailHelper::generateMessageId($from, $message->getRawBody());
$this->line('['.date('Y-m-d H:i:s').'] Message-ID is empty, generated artificial Message-ID: '.$message_id);
}
$duplicate_message_id = false;
// Special hack to allow threading into conversations Jira messages.
// https://github.com/freescout-helpdesk/freescout/issues/2927
//
// Jira does not properly populate Reference / In-Reply-To headers.
// When Jira sends a reply the In-Reply-To header is set to:
// JIRA.$\{issue-id}.$\{issue-created-date-millis}@$\{host}
//
// If we see the first message of a ticket we change the Message-ID,
// so all follow-ups in the ticket are nicely threaded.
$jira_message_id = preg_replace('/^(JIRA\.\d+\.\d+)\..*(@Atlassian.JIRA)/', '\1\2', $message_id);
if ($jira_message_id != $message_id) {
if (!Thread::where('message_id', $jira_message_id)->exists()) {
$message_id = $jira_message_id;
}
}
if (!$extra) {
$duplicate_message_id = Thread::where('message_id', $message_id)->first();
}
// Mailbox has been mentioned in Bcc.
if (!$extra && $duplicate_message_id) {
$recipients = array_merge(
$this->formatEmailList($message->getTo()),
$this->formatEmailList($message->getCc())
);
if (!in_array(Email::sanitizeEmail($mailbox->email), $recipients)
// Make sure that previous email has been imported into other mailbox.
&& $duplicate_message_id->conversation
&& $duplicate_message_id->conversation->mailbox_id != $mailbox->id
) {
$extra = true;
$duplicate_message_id = null;
}
}
// Gnerate artificial Message-ID if importing same email into several mailboxes.
if ($extra) {
// Generate artificial Message-ID.
$message_id = \MailHelper::generateMessageId(strstr($message_id, '@') ? $message_id : $from, $mailbox->id.$message_id);
$this->line('['.date('Y-m-d H:i:s').'] Generated artificial Message-ID: '.$message_id);
}
// Check if message already fetched.
if ($duplicate_message_id) {
$this->line('['.date('Y-m-d H:i:s').'] Message with such Message-ID has been fetched before: '.$message_id);
$this->setSeen($message, $mailbox);
return;
}
// Detect prev thread
$is_reply = false;
$prev_thread = null;
$user_id = null;
$user = null; // for user reply only
$message_from_customer = true;
$in_reply_to = trim($message->getInReplyTo() ?? '', '<>');
$references = $message->getReferences();
$attachments = $message->getAttachments();
$html_body = '';
// Is it a bounce message
$is_bounce = false;
// Determine previous Message-ID
$prev_message_ids = array();
if ($references && !is_array($references)) {
$references = array_filter(preg_split('/[, <>]/', $references));
}
if ($in_reply_to) {
$prev_message_ids[] = $in_reply_to;
}
if ($references) {
// Find non-empty references
if (is_array($references)) {
foreach ($references as $reference) {
if (!empty(trim($reference))) {
$prev_message_ids[] = trim($reference);
}
}
}
}
// Some mail service providers change Message-ID of the outgoing email,
// so we are passing Message-ID in marker in body.
$reply_prefixes = [
\MailHelper::MESSAGE_ID_PREFIX_NOTIFICATION,
\MailHelper::MESSAGE_ID_PREFIX_REPLY_TO_CUSTOMER,
\MailHelper::MESSAGE_ID_PREFIX_AUTO_REPLY,
];
// Try to get previous message ID from marker in body.
$html_body = $message->getHTMLBody(false);
$marker_message_id = \MailHelper::fetchMessageMarkerValue($html_body);
if ($marker_message_id) {
$prev_message_ids[] = $marker_message_id;
}
// Bounce detection.
$bounced_message_id = null;
if ($message->hasAttachments()) {
// Detect bounce by attachment.
// Check all attachments.
foreach ($attachments as $attachment) {
if (!empty(Attachment::$types[$attachment->getType()]) && Attachment::$types[$attachment->getType()] == Attachment::TYPE_MESSAGE
) {
if (
// Checking the name will lead to mistakes if someone attaches a file with such name.
// Dashes are converted to space.
//in_array(strtoupper($attachment->getName()), ['RFC822', 'DELIVERY STATUS', 'DELIVERY STATUS NOTIFICATION', 'UNDELIVERED MESSAGE'])
preg_match('/delivery-status/', strtolower($attachment->content_type))
// 7.3.1 The Message/rfc822 (primary) subtype. A Content-Type of "message/rfc822" indicates that the body contains an encapsulated message, with the syntax of an RFC 822 message
//|| $attachment->content_type == 'message/rfc822'
) {
$is_bounce = true;
$this->line('['.date('Y-m-d H:i:s').'] Bounce detected by attachment content-type: '.$attachment->content_type);
// Try to get Message-ID of the original email.
if (!$bounced_message_id) {
//print_r(\MailHelper::parseHeaders($attachment->getContent()));
$bounced_message_id = \MailHelper::getHeader($attachment->getContent(), 'message_id');
}
}
}
}
}
$message_header = $this->headerToStr($message->getHeader());
// Check Content-Type header.
if (!$is_bounce && $message_header) {
if (\MailHelper::detectBounceByHeaders($message_header)) {
$is_bounce = true;
}
}
// Check message's From field.
if (!$is_bounce) {
if ($message->getFrom()) {
$original_from = $this->formatEmailList($message->getFrom());
$original_from = $original_from[0];
$is_bounce = preg_match('/^mailer\-daemon@/i', $original_from);
if ($is_bounce) {
$this->line('['.date('Y-m-d H:i:s').'] Bounce detected by From header: '.$original_from);
}
}
}
// Check Return-Path header
if (!$is_bounce && preg_match("/^Return\-Path: <>/i", $message_header)) {
$this->line('['.date('Y-m-d H:i:s').'] Bounce detected by Return-Path header.');
$is_bounce = true;
}
if ($is_bounce && !$bounced_message_id) {
foreach ($attachments as $attachment_msg) {
// 7.3.1 The Message/rfc822 (primary) subtype. A Content-Type of "message/rfc822" indicates that the body contains an encapsulated message, with the syntax of an RFC 822 message
if ($attachment_msg->content_type == 'message/rfc822') {
$bounced_message_id = \MailHelper::getHeader($attachment_msg->getContent(), 'message_id');
if ($bounced_message_id) {
break;
}
}
}
}
# Try to get the thread traversing the possible prev_message_ids
foreach ($prev_message_ids as $prev_message_id) {
// Is it a message from Customer or User replied to the notification
preg_match('/^'.\MailHelper::MESSAGE_ID_PREFIX_NOTIFICATION."\-(\d+)\-(\d+)\-/", $prev_message_id, $m);
if (!$is_bounce && !empty($m[1]) && !empty($m[2])) {
// Reply from User to the notification
$prev_thread = Thread::find($m[1]);
$user_id = $m[2];
$user = User::find($user_id);
$message_from_customer = false;
$is_reply = true;
if (!$user) {
$this->logError('User not found: '.$user_id);
$this->setSeen($message, $mailbox);
return;
}
// Skip auto-replies sent to the email notification on behalf of a user.
// https://github.com/freescout-helpdesk/freescout/issues/4035
if (\MailHelper::isAutoResponder($message_header)) {
$this->logError('Skipping an auto-reply to the email notification');
$this->setSeen($message, $mailbox);
return;
}
$this->line('['.date('Y-m-d H:i:s').'] Message from: User');
} else {
// Message from Customer or User replied to his reply to notification
$this->line('['.date('Y-m-d H:i:s').'] Message from: Customer');
if (!$is_bounce) {
if ($prev_message_id) {
$prev_thread_id = '';
// Customer replied to the email from user
preg_match('/^'.\MailHelper::MESSAGE_ID_PREFIX_REPLY_TO_CUSTOMER."\-(\d+)\-([a-z0-9]+)@/", $prev_message_id, $m);
// Simply checking thread_id from message_id was causing an issue when
// customer was sending a message from FreeScout - the message was
// connected to the wrong conversation.
if (!empty($m[1]) && !empty($m[2])) {
$message_id_hash = $m[2];
if (strlen($message_id_hash) == 16) {
if ($message_id_hash == \MailHelper::getMessageIdHash($m[1])) {
$prev_thread_id = $m[1];
}
} else {
// Backward compatibility.
$prev_thread_id = $m[1];
}
}
// Customer replied to the auto reply
if (!$prev_thread_id) {
preg_match('/^'.\MailHelper::MESSAGE_ID_PREFIX_AUTO_REPLY."\-(\d+)\-([a-z0-9]+)@/", $prev_message_id, $m);
if (!empty($m[1]) && !empty($m[2])) {
$message_id_hash = $m[2];
if (strlen($message_id_hash) == 16) {
if ($message_id_hash == \MailHelper::getMessageIdHash($m[1])) {
$prev_thread_id = $m[1];
}
} else {
// Backward compatibility.
$prev_thread_id = $m[1];
}
}
}
if ($prev_thread_id) {
$prev_thread = Thread::find($prev_thread_id);
} else {
// Customer replied to his own message
$prev_thread = Thread::where('message_id', $prev_message_id)->first();
}
// Reply from user to his reply to the notification
if (!$prev_thread
&& ($prev_thread = Thread::where('message_id', $prev_message_id)->first())
&& $prev_thread->created_by_user_id
&& $prev_thread->created_by_user->hasEmail($from)
) {
$user_id = $user->id;
$message_from_customer = false;
$is_reply = true;
}
}
}
}
# If a thread is found, we keep it and break
if (!empty($prev_thread)) {
$is_reply = true;
break;
}
}
// Make sure that prev_thread belongs to the current mailbox.
// Problems may arise when forwarding conversation for example.
//
// For replies to email notifications it's allowed to have prev_thread in
// another mailbox as conversation can be moved.
// https://github.com/freescout-helpdesk/freescout/issues/3455
if ($prev_thread && $message_from_customer) {
if ($prev_thread->conversation->mailbox_id != $mailbox->id) {
// https://github.com/freescout-helpdesk/freescout/issues/2807
// Behaviour of email sent to multiple mailboxes:
// If a user from either mailbox replies, then a new conversation is created
// in the other mailbox with another new conversation ID.
//
// Try to get thread by generated message ID.
if ($in_reply_to) {
$prev_thread = Thread::where('message_id', \MailHelper::generateMessageId($in_reply_to, $mailbox->id.$in_reply_to))->first();
if (!$prev_thread) {
$prev_thread = null;
$is_reply = false;
}
} else {
$prev_thread = null;
$is_reply = false;
}
}
}
// Get body
if (!$html_body) {
// Get body and do not replace :cid with images base64
$html_body = $message->getHTMLBody(false);
}
$is_html = true;
if ($html_body) {
$body = $html_body;
} else {
$is_html = false;
$body = $message->getTextBody() ?? '';
$body = htmlspecialchars($body);
}
// We have to fetch absolutely all emails, even with empty body.
// if (!$body) {
// $this->logError('Message body is empty');
// $this->setSeen($message, $mailbox);
// continue;
// }
// Webklex/php-imap returns object instead of a string.
$subject = $message->getSubject()."";
// Convert subject encoding
if (preg_match('/=\?[a-z\d-]+\?[BQ]\?.*\?=/i', $subject)) {
$subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
}
$to = $this->formatEmailList($message->getTo());
$cc = $this->formatEmailList($message->getCc());
// It will always return an empty value as it's Bcc.
$bcc = $this->formatEmailList($message->getBcc());
// If existing user forwarded customer's email to the mailbox
// we are creating a new conversation as if it was sent by the customer.
if (// Some mail clients to not add "In-Reply-To" header when forwarding emails.
// https://github.com/freescout-help-desk/freescout/issues/4348
//$in_reply_to
// We should use body here, as entire HTML may contain
// email looking things.
//&& ($fwd_body = $html_body ?: $message->getTextBody())
$body
//&& preg_match("/^(".implode('|', \MailHelper::$fwd_prefixes)."):(.*)/i", $subject, $m)
// F:, FW:, FWD:, WG:, De:
&& preg_match("/^[[:alpha:]]{1,3}:(.*)/i", $subject, $m)
// It can be just "Fwd:"
//&& !empty($m[1])
&& !$user_id && !$is_reply && !$prev_thread
// Only if the email has been sent to one mailbox.
&& count($to) == 1 && count($cc) == 0
// We need to replace also any potential <style></style> tags.
&& preg_match("/^[\s]*".self::FWD_AS_CUSTOMER_COMMAND."/su", strtolower(trim(\Helper::stripTags($body))))
) {
// Try to get "From:" from body.
$original_sender = $this->getOriginalSenderFromFwd($body);
if ($original_sender) {
// Check if sender is the existing user.
$sender_is_user = User::nonDeleted()->where('email', $from)->exists();
if ($sender_is_user) {
// Substitute sender.
$from = $original_sender;
$subject = trim($m[1] ?? $subject);
$message_from_customer = true;
// Remove @fwd from body.
$body = trim(preg_replace("/".self::FWD_AS_CUSTOMER_COMMAND."([\s<]+)/su", '$1', $body));
}
}
}
// separateReply() function may distort original HTML if email
// is mentioned as <[email protected]> and it will interpret it as a tag.
// https://github.com/freescout-helpdesk/freescout/issues/4036
$body = $this->separateReply($body, $is_html, $is_reply, !$message_from_customer, (($message_from_customer && $prev_thread) ? $prev_thread->getMessageId($mailbox) : ''));
// Create customers
$emails = array_merge(
$this->attrToArray($message->getFrom()),
$this->attrToArray($message->getReplyTo()),
$this->attrToArray($message->getTo()),
$this->attrToArray($message->getCc()),
// It will always return an empty value as it's Bcc.
$this->attrToArray($message->getBcc())
);
$this->createCustomers($emails, $mailbox->getEmails());
$date = $this->attrToDate($message->getDate());
if ($date) {
$app_timezone = config('app.timezone');
if ($app_timezone) {
$date->setTimezone($app_timezone);
}
}
$now = now();
if (!$date || $date->greaterThan($now)) {
$date = $now;
}
$data = \Eventy::filter('fetch_emails.data_to_save', [
'mailbox' => $mailbox,
'message_id' => $message_id,
'prev_thread' => $prev_thread,
'from' => $from,
'to' => $to,
'cc' => $cc,
'bcc' => $bcc,
'subject' => $subject,
'body' => $body,
'attachments' => $attachments,
'message' => $message,
'is_bounce' => $is_bounce,
'message_from_customer' => $message_from_customer,
'user' => $user,
'date' => $date,
]);
$new_thread = null;
if ($message_from_customer) {
// We should import the message into other mailboxes even if previous thread is set.
// https://github.com/freescout-helpdesk/freescout/issues/3473
//if (!$data['prev_thread']) {
// Maybe this email need to be imported also into other mailbox.
$recipient_emails = array_unique($this->formatEmailList(array_merge(
$this->attrToArray($message->getTo()),
$this->attrToArray($message->getCc()),
// It will always return an empty value as it's Bcc.
$this->attrToArray($message->getBcc())
)));
if (count($mailboxes) && count($recipient_emails) > 1) {
foreach ($mailboxes as $check_mailbox) {
if ($check_mailbox->id == $mailbox->id) {
continue;
}
if (!$check_mailbox->isInActive()) {
continue;
}
foreach ($recipient_emails as $recipient_email) {
// No need to check mailbox aliases.
if (\App\Email::sanitizeEmail($check_mailbox->email) == $recipient_email) {
$this->extra_import[] = [
'mailbox' => $check_mailbox,
'message' => $message,
'message_id' => $message_id,
];
break;
}
}
}
}
//}
if (\Eventy::filter('fetch_emails.should_save_thread', true, $data) !== false) {
// SendAutoReply listener will check bounce flag and will not send an auto reply if this is an auto responder.
$new_thread = $this->saveCustomerThread($mailbox, $data['message_id'], $data['prev_thread'], $data['from'], $data['to'], $data['cc'], $data['bcc'], $data['subject'], $data['body'], $data['attachments'], $data['message']->getHeader(), $data['date']);
} else {
$this->line('['.date('Y-m-d H:i:s').'] Hook fetch_emails.should_save_thread returned false. Skipping message.');
$this->setSeen($message, $mailbox);
return;
}
} else {
// Check if From is the same as user's email.
// If not we send an email with information to the sender.
if (!$user->hasEmail($from)) {
$this->logError("Sender address {$from} does not match ".$user->getFullName()." user email: ".$user->email.". Add ".$user->email." to user's Alternate Emails in the users's profile to allow the user reply from this address.");
$this->setSeen($message, $mailbox);
// Send "Unable to process your update email" to user
\App\Jobs\SendEmailReplyError::dispatch($from, $user, $mailbox)->onQueue('emails');
return;
}
// Save user thread only if there prev_thread is set.
// https://github.com/freescout-helpdesk/freescout/issues/3455
if (!$prev_thread) {
$this->logError("Support agent's reply to the email notification could not be processed as previous thread could not be determined.");
$this->setSeen($message, $mailbox);
return;
}
if (\Eventy::filter('fetch_emails.should_save_thread', true, $data) !== false) {
$new_thread = $this->saveUserThread($data['mailbox'], $data['message_id'], $data['prev_thread'], $data['user'], $data['from'], $data['to'], $data['cc'], $data['bcc'], $data['body'], $data['attachments'], $data['message']->getHeader(), $data['date']);
} else {
$this->line('['.date('Y-m-d H:i:s').'] Hook fetch_emails.should_save_thread returned false. Skipping message.');
$this->setSeen($message, $mailbox);
return;
}
}
if ($new_thread) {
$this->setSeen($message, $mailbox);
$this->line('['.date('Y-m-d H:i:s').'] Thread successfully created: '.$new_thread->id);
// If it was a bounce message, save bounce data.
if ($message_from_customer && $is_bounce) {
$this->saveBounceData($new_thread, $bounced_message_id, $from);
}
} else {
$this->logError('Error occurred processing message');
}
} catch (\Exception $e) {
$this->setSeen($message, $mailbox);
$this->logError(\Helper::formatException($e));
}
}
// Try to get "From:" from body.
public function getOriginalSenderFromFwd($body)
{
// https://github.com/freescout-helpdesk/freescout/issues/2672
$body = preg_replace("/[\"']cid:/", '!', $body);
// Cut out the command, otherwise it will be recognized as an email.
$body = preg_replace("/".self::FWD_AS_CUSTOMER_COMMAND."([\s<]+)/isu", '$1', $body);
// Looks like email texts may appear in attributes:
// https://github.com/freescout-helpdesk/freescout/issues/276
// - :[email protected]
// - <[email protected]>
// - <[email protected]>
preg_match("/[\"'<:;]([^\"'<:;!@\s]+@[^\"'>:&@\s]+)[\"'>:&]/", $body, $b);
$email = $b[1] ?? '';
// https://github.com/freescout-helpdesk/freescout/issues/2517
$email = preg_replace("#.*<(.*)>.*#", "$1", $email);
return Email::sanitizeEmail($email);
}
public function saveBounceData($new_thread, $bounced_message_id, $from)
{
// Try to find bounced thread by Message-ID.
$bounced_thread = null;
if ($bounced_message_id) {
$prefixes = [
\MailHelper::MESSAGE_ID_PREFIX_REPLY_TO_CUSTOMER,
\MailHelper::MESSAGE_ID_PREFIX_AUTO_REPLY,
];
preg_match('/^('.implode('|', $prefixes).')\-(\d+)\-/', $bounced_message_id, $matches);
if (!empty($matches[2])) {
$bounced_thread = Thread::find($matches[2]);
}
}
$status_data = [
'is_bounce' => true,
];
if ($bounced_thread) {
$status_data['bounce_for_thread'] = $bounced_thread->id;
$status_data['bounce_for_conversation'] = $bounced_thread->conversation_id;
}
$new_thread->updateSendStatusData($status_data);
$new_thread->save();
// Update status of the original message and create log record.
if ($bounced_thread) {
$bounced_thread->send_status = SendLog::STATUS_DELIVERY_ERROR;
$status_data = [
'bounced_by_thread' => $new_thread->id,
'bounced_by_conversation' => $new_thread->conversation_id,
// todo.
// 'bounce_info' => [
// ]
];
$bounced_thread->updateSendStatusData($status_data);
$bounced_thread->save();
// Bounces can be soft and hard, for now log both as STATUS_DELIVERY_ERROR.
SendLog::log($bounced_thread->id, null, $from, SendLog::MAIL_TYPE_EMAIL_TO_CUSTOMER, SendLog::STATUS_DELIVERY_ERROR, $bounced_thread->created_by_customer_id, null, 'Message bounced');
}
}
public function logError($message)
{
$this->error('['.date('Y-m-d H:i:s').'] '.$message);
$mailbox_name = '';
if ($this->mailbox) {
$mailbox_name = $this->mailbox->name;
}
try {
activity()
->withProperties([
'error' => $message,
'mailbox' => $mailbox_name,
])
->useLog(\App\ActivityLog::NAME_EMAILS_FETCHING)
->log(\App\ActivityLog::DESCRIPTION_EMAILS_FETCHING_ERROR);
} catch (\Exception $e) {
// Do nothing
}
}
/**
* Save email from customer as thread.
*/
public function saveCustomerThread($mailbox, $message_id, $prev_thread, $from, $to, $cc, $bcc, $subject, $body, $attachments, $headers, $date)
{
// Fetch date & time setting.
$use_mail_date_on_fetching = config('app.use_mail_date_on_fetching');
// Find conversation.
$new = false;