-
Notifications
You must be signed in to change notification settings - Fork 499
/
Message.php
1282 lines (1140 loc) · 36.1 KB
/
Message.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
/*
* File: Message.php
* Category: -
* Author: M. Goldenbaum
* Created: 19.01.17 22:21
* Updated: -
*
* Description:
* -
*/
namespace Webklex\IMAP;
use Carbon\Carbon;
use Webklex\IMAP\Support\AttachmentCollection;
use Webklex\IMAP\Support\FlagCollection;
/**
* Class Message.
*/
class Message
{
/**
* Client instance.
*
* @var Client
*/
private $client = Client::class;
/**
* U ID.
*
* @var int
*/
public $uid = '';
/**
* Fetch body options.
*
* @var int
*/
public $fetch_options = null;
/**
* Fetch body options.
*
* @var bool
*/
public $fetch_body = null;
/**
* Fetch attachments options.
*
* @var bool
*/
public $fetch_attachment = null;
/**
* Fetch flags options.
*
* @var bool
*/
public $fetch_flags = null;
/**
* @var int
*/
public $msglist = 1;
/**
* @var int
*/
public $msgn = null;
/**
* @var string
*/
public $header = null;
/**
* @var null|object
*/
public $header_info = null;
/** @var null|string $raw_body */
public $raw_body = null;
/**
* Message header components.
*
* @var string
* @var mixed $message_no
* @var string $subject
* @var mixed $references
* @var mixed $date
* @var array $from
* @var array $to
* @var array $cc
* @var array $bcc
* @var array $reply_to
* @var string $in_reply_to
* @var array $sender
* @var array $flags
* @var array $priority
*/
public $message_id = '';
public $message_no = null;
public $subject = '';
public $references = null;
public $date = null;
public $from = [];
public $to = [];
public $cc = [];
public $bcc = [];
public $reply_to = [];
public $in_reply_to = '';
public $sender = [];
public $priority = 0;
/**
* Message body components.
*
* @var array
* @var AttachmentCollection|array $attachments
* @var FlagCollection|array $flags
*/
public $bodies = [];
public $attachments = [];
public $flags = [];
/**
* Message const.
*
* @const integer TYPE_TEXT
* @const integer TYPE_MULTIPART
*
* @const integer ENC_7BIT
* @const integer ENC_8BIT
* @const integer ENC_BINARY
* @const integer ENC_BASE64
* @const integer ENC_QUOTED_PRINTABLE
* @const integer ENC_OTHER
*/
const TYPE_TEXT = 0;
const TYPE_MULTIPART = 1;
const ENC_7BIT = 0;
const ENC_8BIT = 1;
const ENC_BINARY = 2;
const ENC_BASE64 = 3;
const ENC_QUOTED_PRINTABLE = 4;
const ENC_OTHER = 5;
const PRIORITY_UNKNOWN = 0;
const PRIORITY_HIGHEST = 1;
const PRIORITY_HIGH = 2;
const PRIORITY_NORMAL = 3;
const PRIORITY_LOW = 4;
const PRIORITY_LOWEST = 5;
/**
* Message constructor.
*
* @param int $uid
* @param int|null $msglist
* @param Client $client
* @param int|null $fetch_options
* @param bool $fetch_body
* @param bool $fetch_attachment
* @param bool $fetch_flags
*
* @throws Exceptions\ConnectionFailedException
*/
public function __construct($uid, $msglist, Client $client, $fetch_options = null, $fetch_body = false, $fetch_attachment = false, $fetch_flags = false)
{
$this->setFetchOption($fetch_options);
$this->setFetchBodyOption($fetch_body);
$this->setFetchAttachmentOption($fetch_attachment);
$this->setFetchFlagsOption($fetch_flags);
$this->attachments = AttachmentCollection::make([]);
$this->flags = FlagCollection::make([]);
$this->msglist = $msglist;
$this->client = $client;
$this->uid = ($this->fetch_options == FT_UID) ? $uid : $uid;
$this->msgn = ($this->fetch_options == FT_UID) ? imap_msgno($this->client->getConnection(), $uid) : $uid;
$this->parseHeader();
if ($this->getFetchFlagsOption() === true) {
$this->parseFlags();
}
if ($this->getFetchBodyOption() === true) {
$this->parseBody();
}
}
/**
* Copy the current Messages to a mailbox.
*
* @param $mailbox
* @param int $options
*
* @throws Exceptions\ConnectionFailedException
*
* @return bool
*/
public function copy($mailbox, $options = 0)
{
return imap_mail_copy($this->client->getConnection(), $this->msglist, $mailbox, $options);
}
/**
* Move the current Messages to a mailbox.
*
* @param $mailbox
* @param int $options
*
* @throws Exceptions\ConnectionFailedException
*
* @return bool
*/
public function move($mailbox, $options = 0)
{
return imap_mail_move($this->client->getConnection(), $this->msglist, $mailbox, $options);
}
/**
* Check if the Message has a text body.
*
* @return bool
*/
public function hasTextBody()
{
return isset($this->bodies['text']);
}
/**
* Get the Message text body.
*
* @return mixed
*/
public function getTextBody()
{
if (!isset($this->bodies['text'])) {
return false;
}
return $this->bodies['text']->content;
}
/**
* Check if the Message has a html body.
*
* @return bool
*/
public function hasHTMLBody()
{
return isset($this->bodies['html']);
}
/**
* Get the Message html body.
*
* @var bool
*
* @return mixed
*/
public function getHTMLBody($replaceImages = false)
{
if (!isset($this->bodies['html'])) {
return false;
}
$body = $this->bodies['html']->content;
if ($replaceImages) {
$this->attachments->each(function ($oAttachment) use (&$body) {
if ($oAttachment->id && isset($oAttachment->img_src)) {
$body = str_replace('cid:'.$oAttachment->id, $oAttachment->img_src, $body);
}
});
}
return $body;
}
/**
* Parse all defined headers.
*
* @throws Exceptions\ConnectionFailedException
*
* @return void
*/
private function parseHeader()
{
$this->header = $header = imap_fetchheader($this->client->getConnection(), $this->uid, FT_UID);
if ($this->header) {
$header = imap_rfc822_parse_headers($this->header);
}
if (preg_match('/x\-priority\:.*([0-9]{1,2})/i', $this->header, $priority)) {
$priority = isset($priority[1]) ? (int) $priority[1] : 0;
switch ($priority) {
case self::PRIORITY_HIGHEST:
$this->priority = self::PRIORITY_HIGHEST;
break;
case self::PRIORITY_HIGH:
$this->priority = self::PRIORITY_HIGH;
break;
case self::PRIORITY_NORMAL:
$this->priority = self::PRIORITY_NORMAL;
break;
case self::PRIORITY_LOW:
$this->priority = self::PRIORITY_LOW;
break;
case self::PRIORITY_LOWEST:
$this->priority = self::PRIORITY_LOWEST;
break;
default:
$this->priority = self::PRIORITY_UNKNOWN;
break;
}
}
if (property_exists($header, 'subject')) {
$this->subject = \imap_utf8($header->subject);
if (\Str::startsWith(mb_strtolower($this->subject), '=?utf-8?')) {
// https://bugs.php.net/bug.php?id=68821
$this->subject = preg_replace_callback('/(=\?[^\?]+\?Q\?)([^\?]+)(\?=)/i', function($matches) {
return $matches[1] . str_replace('_', '=20', $matches[2]) . $matches[3];
}, $header->subject);
$this->subject = mb_decode_mimeheader($this->subject);
}
}
if (property_exists($header, 'date')) {
$date = $header->date;
/*
* Exception handling for invalid dates
*
* Currently known invalid formats:
* ^ Datetime ^ Problem ^ Cause
* | Mon, 20 Nov 2017 20:31:31 +0800 (GMT+8:00) | Double timezone specification | A Windows feature
* | Thu, 8 Nov 2018 08:54:58 -0200 (-02) |
* | | and invalid timezone (max 6 char) |
* | 04 Jan 2018 10:12:47 UT | Missing letter "C" | Unknown
* | Thu, 31 May 2018 18:15:00 +0800 (added by) | Non-standard details added by the | Unknown
* | | mail server |
* | Sat, 31 Aug 2013 20:08:23 +0580 | Invalid timezone | PHPMailer bug https://sourceforge.net/p/phpmailer/mailman/message/6132703/
*
* Please report any new invalid timestamps to [#45](https://github.com/Webklex/laravel-imap/issues/45)
*/
// try {
// $this->date = Carbon::parse($date);
// } catch (\Exception $e) {
// switch (true) {
// case preg_match('/([A-Z]{2,3}\,\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ [\-|\+][0-9]{4}\ \(.*)\)+$/i', $date) > 0:
// case preg_match('/([0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{2,4}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}\ [A-Z]{2}\ \-[0-9]{2}\:[0-9]{2}\ \([A-Z]{2,3}\ \-[0-9]{2}:[0-9]{2}\))+$/i', $date) > 0:
// $array = explode('(', $date);
// $array = array_reverse($array);
// $date = trim(array_pop($array));
// break;
// case preg_match('/([0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ UT)+$/i', $date) > 0:
// $date .= 'C';
// break;
// }
// $date = preg_replace('/[<>]/', '', $date);
// try {
// $this->date = Carbon::parse($date);
// } catch (\Exception $e) {
// \Helper::logException($e, '[Webklex\IMAP\Message]');
// }
// }
if (preg_match('/\+0580/', $date)) {
$date = str_replace('+0580', '+0530', $date);
}
$date = trim(rtrim($date));
$date = preg_replace('/[<>]/', '', $date);
$date = str_replace('_', ' ', $date);
try {
$this->date = Carbon::parse($date);
} catch (\Exception $e) {
switch (true) {
case preg_match('/([0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ UT)+$/i', $date) > 0:
case preg_match('/([A-Z]{2,3}\,\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ UT)+$/i', $date) > 0:
$date .= 'C';
break;
case preg_match('/([A-Z]{2,3}[\,|\ \,]\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}.*)+$/i', $date) > 0:
case preg_match('/([A-Z]{2,3}\,\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ [\-|\+][0-9]{4}\ \(.*)\)+$/i', $date) > 0:
case preg_match('/([A-Z]{2,3}\, \ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ [\-|\+][0-9]{4}\ \(.*)\)+$/i', $date) > 0:
case preg_match('/([0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{2,4}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}\ [A-Z]{2}\ \-[0-9]{2}\:[0-9]{2}\ \([A-Z]{2,3}\ \-[0-9]{2}:[0-9]{2}\))+$/i', $date) > 0:
$array = explode('(', $date);
$array = array_reverse($array);
$date = trim(array_pop($array));
break;
}
try {
$this->date = Carbon::parse($date);
} catch (\Exception $_e) {
$this->date = Carbon::now();
// No need to write this to log.
// https://github.com/freescout-helpdesk/freescout/issues/2734
//
// \Helper::logException($_e, '[Webklex\IMAP\Message]');
// \Helper::logExceptionToActivityLog($_e,
// \App\ActivityLog::NAME_EMAILS_FETCHING,
// \App\ActivityLog::DESCRIPTION_EMAILS_FETCHING_ERROR
// );
//throw new InvalidMessageDateException("Invalid message date. ID:".$this->getMessageId(), 1000, $e);
}
}
}
if (property_exists($header, 'from')) {
$this->from = $this->parseAddresses($header->from);
}
if (property_exists($header, 'to')) {
$this->to = $this->parseAddresses($header->to);
}
if (property_exists($header, 'cc')) {
$this->cc = $this->parseAddresses($header->cc);
}
if (property_exists($header, 'bcc')) {
$this->bcc = $this->parseAddresses($header->bcc);
}
if (property_exists($header, 'references')) {
$this->references = $header->references;
}
if (property_exists($header, 'reply_to')) {
$this->reply_to = $this->parseAddresses($header->reply_to);
}
if (property_exists($header, 'in_reply_to')) {
$this->in_reply_to = str_replace(['<', '>'], '', $header->in_reply_to);
}
if (property_exists($header, 'sender')) {
$this->sender = $this->parseAddresses($header->sender);
}
if (property_exists($header, 'message_id')) {
$this->message_id = str_replace(['<', '>'], '', $header->message_id);
}
if (property_exists($header, 'Msgno')) {
$messageNo = (int) trim($header->Msgno);
$this->message_no = ($this->fetch_options == FT_UID) ? $messageNo : imap_msgno($this->client->getConnection(), $messageNo);
} else {
$this->message_no = imap_msgno($this->client->getConnection(), $this->getUid());
}
}
/**
* Parse additional flags.
*
* @throws Exceptions\ConnectionFailedException
*
* @return void
*/
private function parseFlags()
{
$flags = imap_fetch_overview($this->client->getConnection(), $this->uid, FT_UID);
if (is_array($flags) && isset($flags[0])) {
if (property_exists($flags[0], 'recent')) {
$this->flags->put('recent', $flags[0]->recent);
}
if (property_exists($flags[0], 'flagged')) {
$this->flags->put('flagged', $flags[0]->flagged);
}
if (property_exists($flags[0], 'answered')) {
$this->flags->put('answered', $flags[0]->answered);
}
if (property_exists($flags[0], 'deleted')) {
$this->flags->put('deleted', $flags[0]->deleted);
}
if (property_exists($flags[0], 'seen')) {
$this->flags->put('seen', $flags[0]->seen);
}
if (property_exists($flags[0], 'draft')) {
$this->flags->put('draft', $flags[0]->draft);
}
}
}
/**
* Get the current Message header info.
*
* @throws Exceptions\ConnectionFailedException
*
* @return object
*/
public function getHeaderInfo()
{
if ($this->header_info == null) {
$this->header_info =
$this->header_info = imap_headerinfo($this->client->getConnection(), $this->getMessageNo());
}
return $this->header_info;
}
/**
* Parse Addresses.
*
* @param $list
*
* @return array
*/
private function parseAddresses($list)
{
$addresses = [];
foreach ($list as $item) {
$address = (object) $item;
if (!property_exists($address, 'mailbox')) {
$address->mailbox = false;
}
if (!property_exists($address, 'host')) {
$address->host = false;
}
if (!property_exists($address, 'personal')) {
$address->personal = false;
}
$personalParts = imap_mime_header_decode($address->personal);
if (!is_array($personalParts)) {
$p = new \stdClass();
$p->text = $address->personal;
$personalParts = [
$p
];
}
$address->personal = '';
foreach ($personalParts as $p) {
//$address->personal .= $p->text;
$encoding = (property_exists($p, 'charset')) ? $p->charset : $this->getEncoding($p->text);
$address->personal .= $this->convertEncoding($p->text, $encoding);
}
$address->mail = ($address->mailbox && $address->host) ? $address->mailbox.'@'.$address->host : false;
$address->full = ($address->personal) ? $address->personal.' <'.$address->mail.'>' : $address->mail;
$addresses[] = $address;
}
return $addresses;
}
/**
* Parse the Message body.
*
* @throws Exceptions\ConnectionFailedException
*
* @return $this
*/
public function parseBody()
{
$structure = imap_fetchstructure($this->client->getConnection(), $this->uid, FT_UID);
if (property_exists($structure, 'parts')) {
$parts = $structure->parts;
foreach ($parts as $part) {
foreach ($part->parameters as $parameter) {
if ($parameter->attribute == 'charset') {
$encoding = $parameter->value;
$parameter->value = preg_replace('/Content-Transfer-Encoding/', '', $encoding);
}
}
}
}
$this->fetchStructure($structure);
return $this;
}
/**
* Fetch the Message structure.
*
* @param $structure
* @param mixed $partNumber
*
* @throws Exceptions\ConnectionFailedException
*/
private function fetchStructure($structure, $partNumber = null)
{
if ($structure->type == self::TYPE_TEXT &&
# FreeScout #320
#($structure->ifdisposition == 0 ||
# ($structure->ifdisposition == 1 && !isset($structure->parts) && $partNumber == null)
#)
(empty($structure->disposition) || strtolower($structure->disposition) != 'attachment')
) {
// FreeScout improvement
/*if (strtolower($structure->subtype) == 'plain' || strtolower($structure->subtype) == 'csv') {
if (!$partNumber) {
$partNumber = 1;
}
$encoding = $this->getEncoding($structure);
$content = imap_fetchbody($this->client->getConnection(), $this->uid, $partNumber, $this->fetch_options | FT_UID);
$content = $this->decodeString($content, $structure->encoding);
$content = $this->convertEncoding($content, $encoding);
$body = new \stdClass();
$body->type = 'text';
$body->content = $content;
$this->bodies['text'] = $body;
$this->fetchAttachment($structure, $partNumber);
} elseif (strtolower($structure->subtype) == 'html') {
if (!$partNumber) {
$partNumber = 1;
}
$encoding = $this->getEncoding($structure);
$content = imap_fetchbody($this->client->getConnection(), $this->uid, $partNumber, $this->fetch_options | FT_UID);
$content = $this->decodeString($content, $structure->encoding);
$content = $this->convertEncoding($content, $encoding);
$body = new \stdClass();
$body->type = 'html';
$body->content = $content;
$this->bodies['html'] = $body;
}*/
if (strtolower($structure->subtype) == 'html') {
if (!$partNumber) {
$partNumber = 1;
}
$encoding = $this->getEncoding($structure);
$content = imap_fetchbody($this->client->getConnection(), $this->uid, $partNumber, $this->fetch_options | FT_UID);
$content = $this->decodeString($content, $structure->encoding);
$content = $this->convertEncoding($content, $encoding);
// FreeScout #381
// Some messages (for exaple Apple Mail) may have multiple HTML parts.
if (empty($this->bodies['html'])) {
$body = new \stdClass();
$body->type = 'html';
$body->content = $content;
$this->bodies['html'] = $body;
} else {
$this->bodies['html']->content .= $content;
}
} else {
// PLAIN.
if (!$partNumber) {
$partNumber = 1;
}
$encoding = $this->getEncoding($structure);
$content = imap_fetchbody($this->client->getConnection(), $this->uid, $partNumber, $this->fetch_options | FT_UID);
$content = $this->decodeString($content, $structure->encoding);
$content = $this->convertEncoding($content, $encoding);
if (empty($this->bodies['text'])) {
$body = new \stdClass();
$body->type = 'text';
$body->content = $content;
$this->bodies['text'] = $body;
} else {
$this->bodies['text']->content .= $content;
}
$this->fetchAttachment($structure, $partNumber);
}
} elseif ($structure->type == self::TYPE_MULTIPART) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = '';
if ($partNumber) {
$prefix = $partNumber.'.';
}
$this->fetchStructure($subStruct, $prefix.($index + 1));
}
} else {
if ($this->getFetchAttachmentOption() === true) {
$this->fetchAttachment($structure, $partNumber);
}
}
}
/**
* Fetch the Message attachment.
*
* @param object $structure
* @param mixed $partNumber
*
* @throws Exceptions\ConnectionFailedException
*/
protected function fetchAttachment($structure, $partNumber)
{
$oAttachment = new Attachment($this, $structure, $partNumber);
if ($oAttachment->getName() !== null) {
if ($oAttachment->getId() !== null) {
$this->attachments->put($oAttachment->getId(), $oAttachment);
} else {
$this->attachments->push($oAttachment);
}
}
}
/**
* Fail proof setter for $fetch_option.
*
* @param $option
*
* @return $this
*/
public function setFetchOption($option)
{
if (is_int($option) === true) {
$this->fetch_options = $option;
} elseif (is_null($option) === true) {
$config = config('imap.options.fetch', FT_UID);
$this->fetch_options = is_int($config) ? $config : 1;
}
return $this;
}
/**
* Fail proof setter for $fetch_body.
*
* @param $option
*
* @return $this
*/
public function setFetchBodyOption($option)
{
if (is_bool($option)) {
$this->fetch_body = $option;
} elseif (is_null($option)) {
$config = config('imap.options.fetch_body', true);
$this->fetch_body = is_bool($config) ? $config : true;
}
return $this;
}
/**
* Fail proof setter for $fetch_attachment.
*
* @param $option
*
* @return $this
*/
public function setFetchAttachmentOption($option)
{
if (is_bool($option)) {
$this->fetch_attachment = $option;
} elseif (is_null($option)) {
$config = config('imap.options.fetch_attachment', true);
$this->fetch_attachment = is_bool($config) ? $config : true;
}
return $this;
}
/**
* Fail proof setter for $fetch_flags.
*
* @param $option
*
* @return $this
*/
public function setFetchFlagsOption($option)
{
if (is_bool($option)) {
$this->fetch_flags = $option;
} elseif (is_null($option)) {
$config = config('imap.options.fetch_flags', true);
$this->fetch_flags = is_bool($config) ? $config : true;
}
return $this;
}
/**
* Decode a given string.
*
* @param $string
* @param $encoding
*
* @return string
*/
public function decodeString($string, $encoding)
{
switch ($encoding) {
case self::ENC_7BIT:
return $string;
case self::ENC_8BIT:
return quoted_printable_decode(imap_8bit($string));
case self::ENC_BINARY:
return imap_base64(imap_binary($string));
case self::ENC_BASE64:
return imap_base64($string);
case self::ENC_QUOTED_PRINTABLE:
return quoted_printable_decode($string);
case self::ENC_OTHER:
return $string;
default:
return $string;
}
}
/**
* Convert the encoding.
*
* @param $str
* @param string $from
* @param string $to
*
* @return mixed|string
*/
public function convertEncoding($str, $from = 'ISO-8859-2', $to = 'UTF-8')
{
// FreeScout fix
// We don't need to do convertEncoding() if charset is ASCII (us-ascii):
// ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded
// https://stackoverflow.com/a/11303410
//
// us-ascii is the same as ASCII:
// ASCII is the traditional name for the encoding system; the Internet Assigned Numbers Authority (IANA)
// prefers the updated name US-ASCII, which clarifies that this system was developed in the US and
// based on the typographical symbols predominantly in use there.
// https://en.wikipedia.org/wiki/ASCII
//
// convertEncoding() function basically means convertToUtf8(), so when we convert ASCII string into UTF-8 it gets broken.
if (strtolower($from) == 'us-ascii' && $to == 'UTF-8') {
return $str;
}
try {
try {
if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') {
// FreeScout #351
return iconv($from, $to, $str);
} else {
if (!$from) {
return mb_convert_encoding($str, $to);
}
return mb_convert_encoding($str, $to, $from);
}
} catch (\Exception $e) {
// FreeScout #360
if (strstr($from, '-')) {
$from = str_replace('-', '', $from);
return $this->convertEncoding($str, $from, $to);
} else {
// No need to log this error.
// \Helper::logException($e, '[Webklex\IMAP\Message]');
// \Helper::logExceptionToActivityLog($e,
// \App\ActivityLog::NAME_EMAILS_FETCHING,
// \App\ActivityLog::DESCRIPTION_EMAILS_FETCHING_ERROR
// );
return $str;
}
}
} catch (\Throwable $e) {
if (strstr($from, '-')) {
$from = str_replace('-', '', $from);
return $this->convertEncoding($str, $from, $to);
} else {
return $str;
}
}
}
/**
* Get the encoding of a given abject.
*
* @param object|string $structure
*
* @return string
*/
public function getEncoding($structure)
{
if (property_exists($structure, 'parameters')) {
foreach ($structure->parameters as $parameter) {
if (strtolower($parameter->attribute) == 'charset') {
return EncodingAliases::get($parameter->value);
}
}
} elseif (is_string($structure) === true) {
return mb_detect_encoding($structure);
}
return 'UTF-8';
}
/**
* Find the folder containing this message.
*
* @param null|Folder $folder where to start searching from (top-level inbox by default)
*
* @throws Exceptions\ConnectionFailedException
*
* @return null|Folder
*/
public function getContainingFolder(Folder $folder = null)
{
$folder = $folder ?: $this->client->getFolders()->first();
$this->client->checkConnection();
// Try finding the message by uid in the current folder
$client = new Client();
$client->openFolder($folder);
$uidMatches = imap_fetch_overview($client->getConnection(), $this->uid, FT_UID);
$uidMatch = count($uidMatches)
? new self($uidMatches[0]->uid, $uidMatches[0]->msgno, $client)
: null;
$client->disconnect();
// imap_fetch_overview() on a parent folder will return the matching message
// even when the message is in a child folder so we need to recursively
// search the children
foreach ($folder->children as $child) {
$childFolder = $this->getContainingFolder($child);
if ($childFolder) {
return $childFolder;
}
}
// before returning the parent
if ($this->is($uidMatch)) {
return $folder;
}
// or signalling that the message was not found in any folder
}
/**
* Move the Message into an other Folder.
*
* @param string $mailbox
*
* @throws Exceptions\ConnectionFailedException
*
* @return bool
*/
public function moveToFolder($mailbox = 'INBOX')
{
$this->client->createFolder($mailbox);
return imap_mail_move($this->client->getConnection(), $this->uid, $mailbox, CP_UID);
}
/**
* Delete the current Message.
*
* @param bool $expunge
*
* @throws Exceptions\ConnectionFailedException
*
* @return bool
*/
public function delete($expunge = true)
{
$status = imap_delete($this->client->getConnection(), $this->uid, FT_UID);
if ($expunge) {
$this->client->expunge();
}
return $status;
}
/**
* Restore a deleted Message.
*
* @param bool $expunge
*
* @throws Exceptions\ConnectionFailedException
*
* @return bool
*/
public function restore($expunge = true)
{
$status = imap_undelete($this->client->getConnection(), $this->uid, FT_UID);