-
-
Notifications
You must be signed in to change notification settings - Fork 182
/
Message.php
1243 lines (1078 loc) · 37.5 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 Illuminate\Support\Str;
use Webklex\IMAP\Events\MessageDeletedEvent;
use Webklex\IMAP\Events\MessageMovedEvent;
use Webklex\IMAP\Events\MessageRestoredEvent;
use Webklex\IMAP\Exceptions\InvalidMessageDateException;
use Webklex\IMAP\Exceptions\MaskNotFoundException;
use Webklex\IMAP\Exceptions\MethodNotFoundException;
use Webklex\IMAP\Support\AttachmentCollection;
use Webklex\IMAP\Support\FlagCollection;
use Webklex\IMAP\Support\Masks\MessageMask;
/**
* Class Message
*
* @package Webklex\IMAP
*
* @property integer msglist
* @property integer uid
* @property integer msgn
* @property integer priority
* @property string subject
* @property string message_id
* @property string message_no
* @property string references
* @property carbon date
* @property array from
* @property array to
* @property array cc
* @property array bcc
* @property array reply_to
* @property array in_reply_to
* @property array sender
*
* @method integer getMsglist()
* @method integer setMsglist(integer $msglist)
* @method integer getUid()
* @method integer setUid(integer $uid)
* @method integer getMsgn()
* @method integer setMsgn(integer $msgn)
* @method integer getPriority()
* @method integer setPriority(integer $priority)
* @method string getSubject()
* @method string setSubject(string $subject)
* @method string getMessageId()
* @method string setMessageId(string $message_id)
* @method string getMessageNo()
* @method string setMessageNo(string $message_no)
* @method string getReferences()
* @method string setReferences(string $references)
* @method carbon getDate()
* @method carbon setDate(carbon $date)
* @method array getFrom()
* @method array setFrom(array $from)
* @method array getTo()
* @method array setTo(array $to)
* @method array getCc()
* @method array setCc(array $cc)
* @method array getBcc()
* @method array setBcc(array $bcc)
* @method array getReplyTo()
* @method array setReplyTo(array $reply_to)
* @method array getInReplyTo()
* @method array setInReplyTo(array $in_reply_to)
* @method array getSender()
* @method array setSender(array $sender)
*/
class Message {
/**
* Client instance
*
* @var Client
*/
private $client = Client::class;
/**
* Default mask
* @var string $mask
*/
protected $mask = MessageMask::class;
/** @var array $config */
protected $config = [];
/** @var array $attributes */
protected $attributes = [
'message_id' => '',
'message_no' => null,
'subject' => '',
'references' => null,
'date' => null,
'from' => [],
'to' => [],
'cc' => [],
'bcc' => [],
'reply_to' => [],
'in_reply_to' => '',
'sender' => [],
'priority' => 0,
];
/**
* The message folder path
*
* @var string $folder_path
*/
protected $folder_path;
/**
* Fetch body options
*
* @var integer
*/
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 string $header
*/
public $header = null;
/**
* @var null|object $header_info
*/
public $header_info = null;
/** @var null|string $raw_body */
public $raw_body = null;
/** @var null $structure */
protected $structure = null;
/**
* Message body components
*
* @var array $bodies
* @var AttachmentCollection|array $attachments
* @var FlagCollection|array $flags
*/
public $bodies = [];
public $attachments = [];
public $flags = [];
/**
* A list of all available and supported flags
*
* @var array $available_flags
*/
private $available_flags = ['recent', 'flagged', 'answered', 'deleted', 'seen', 'draft'];
/**
* Message constructor.
*
* @param integer $uid
* @param integer|null $msglist
* @param Client $client
* @param integer|null $fetch_options
* @param boolean $fetch_body
* @param boolean $fetch_attachment
* @param boolean $fetch_flags
*
* @throws Exceptions\ConnectionFailedException
* @throws InvalidMessageDateException
*/
public function __construct($uid, $msglist, Client $client, $fetch_options = null, $fetch_body = false, $fetch_attachment = false, $fetch_flags = false) {
$default_mask = $client->getDefaultMessageMask();
if($default_mask != null) {
$this->mask = $default_mask;
}
$this->folder_path = $client->getFolderPath();
$this->config = config('imap.options');
$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 == IMAP::FT_UID) ? $uid : $uid;
$this->msgn = ($this->fetch_options == IMAP::FT_UID) ? \imap_msgno($this->client->getConnection(), $uid) : $uid;
$this->parseHeader();
if ($this->getFetchFlagsOption() === true) {
$this->parseFlags();
}
if ($this->getFetchBodyOption() === true) {
$this->parseBody();
}
}
/**
* Call dynamic attribute setter and getter methods
* @param string $method
* @param array $arguments
*
* @return mixed
* @throws MethodNotFoundException
*/
public function __call($method, $arguments) {
if(strtolower(substr($method, 0, 3)) === 'get') {
$name = Str::snake(substr($method, 3));
if(in_array($name, array_keys($this->attributes))) {
return $this->attributes[$name];
}
}elseif (strtolower(substr($method, 0, 3)) === 'set') {
$name = Str::snake(substr($method, 3));
if(in_array($name, array_keys($this->attributes))) {
$this->attributes[$name] = array_pop($arguments);
return $this->attributes[$name];
}
}
throw new MethodNotFoundException("Method ".self::class.'::'.$method.'() is not supported');
}
/**
* @param $name
* @param $value
*
* @return mixed
*/
public function __set($name, $value) {
$this->attributes[$name] = $value;
return $this->attributes[$name];
}
/**
* @param $name
*
* @return mixed|null
*/
public function __get($name) {
if(isset($this->attributes[$name])) {
return $this->attributes[$name];
}
return null;
}
/**
* Copy the current Messages to a mailbox
*
* @param $mailbox
* @param int $options
*
* @return bool
* @throws Exceptions\ConnectionFailedException
*/
public function copy($mailbox, $options = 0) {
$this->client->openFolder($this->folder_path);
return \imap_mail_copy($this->client->getConnection(), $this->uid, $mailbox, IMAP::CP_UID);
}
/**
* Move the current Messages to a mailbox
*
* @param $mailbox
* @param int $options
*
* @return bool
* @throws Exceptions\ConnectionFailedException
*/
public function move($mailbox, $options = 0) {
$this->client->openFolder($this->folder_path);
return \imap_mail_move($this->client->getConnection(), $this->uid, $mailbox, IMAP::CP_UID);
}
/**
* 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
* If $replaceImages is callable it should expect string $body as first parameter, $oAttachment as second and return
* the resulting $body.
*
* @var bool|callable $replaceImages
*
* @return string|null
*
* @deprecated 1.4.0:2.0.0 No longer needed. Use AttachmentMask::getImageSrc() instead
*/
public function getHTMLBody($replaceImages = false) {
if (!isset($this->bodies['html'])) {
return null;
}
$body = $this->bodies['html']->content;
if ($replaceImages !== false) {
$this->attachments->each(function($oAttachment) use(&$body, $replaceImages) {
/** @var Attachment $oAttachment */
if(is_callable($replaceImages)) {
$body = $replaceImages($body, $oAttachment);
}elseif(is_string($replaceImages)) {
call_user_func($replaceImages, [$body, $oAttachment]);
}else{
if ($oAttachment->id && $oAttachment->getImgSrc() != null) {
$body = str_replace('cid:'.$oAttachment->id, $oAttachment->getImgSrc(), $body);
}
}
});
}
return $body;
}
/**
* Parse all defined headers
*
* @return void
* @throws Exceptions\ConnectionFailedException
* @throws InvalidMessageDateException
*/
private function parseHeader() {
$this->client->openFolder($this->folder_path);
$this->header = $header = \imap_fetchheader($this->client->getConnection(), $this->uid, IMAP::FT_UID);
$this->priority = $this->extractPriority($this->header);
if ($this->header) {
$header = \imap_rfc822_parse_headers($this->header);
}
if (property_exists($header, 'subject')) {
if($this->config['decoder']['message']['subject'] === 'utf-8') {
$this->subject = \imap_utf8($header->subject);
}elseif($this->config['decoder']['message']['subject'] === 'iconv') {
$this->subject = iconv_mime_decode($header->subject);
}else{
$this->subject = mb_decode_mimeheader($header->subject);
}
}
foreach(['from', 'to', 'cc', 'bcc', 'reply_to', 'sender'] as $part){
$this->extractHeaderAddressPart($header, $part);
}
if (property_exists($header, 'references')) {
$this->references = $header->references;
}
if (property_exists($header, 'in_reply_to')) {
$this->in_reply_to = str_replace(['<', '>'], '', $header->in_reply_to);
}
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 == IMAP::FT_UID) ? $messageNo : \imap_msgno($this->client->getConnection(), $messageNo);
} else {
$this->message_no = \imap_msgno($this->client->getConnection(), $this->getUid());
}
$this->date = $this->parseDate($header);
}
/**
* Try to extract the priority from a given raw header string
* @param string $header
*
* @return int|null
*/
private function extractPriority($header) {
if(preg_match('/x\-priority\:.*([0-9]{1,2})/i', $header, $priority)){
$priority = isset($priority[1]) ? (int) $priority[1] : 0;
switch($priority){
case IMAP::MESSAGE_PRIORITY_HIGHEST;
$priority = IMAP::MESSAGE_PRIORITY_HIGHEST;
break;
case IMAP::MESSAGE_PRIORITY_HIGH;
$priority = IMAP::MESSAGE_PRIORITY_HIGH;
break;
case IMAP::MESSAGE_PRIORITY_NORMAL;
$priority = IMAP::MESSAGE_PRIORITY_NORMAL;
break;
case IMAP::MESSAGE_PRIORITY_LOW;
$priority = IMAP::MESSAGE_PRIORITY_LOW;
break;
case IMAP::MESSAGE_PRIORITY_LOWEST;
$priority = IMAP::MESSAGE_PRIORITY_LOWEST;
break;
default:
$priority = IMAP::MESSAGE_PRIORITY_UNKNOWN;
break;
}
}
return $priority;
}
/**
* 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)
*
* @param object $header
*
* @return Carbon|null
* @throws InvalidMessageDateException
*/
private function parseDate($header) {
$parsed_date = null;
if (property_exists($header, 'date')) {
$date = $header->date;
if(preg_match('/\+0580/', $date)) {
$date = str_replace('+0580', '+0530', $date);
}
$date = trim(rtrim($date));
try {
$parsed_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}\ \+[0-9]{2,4}\ \(\+[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}.*)+$/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{
$parsed_date = Carbon::parse($date);
} catch (\Exception $_e) {
throw new InvalidMessageDateException("Invalid message date. ID:".$this->getMessageId(), 1000, $e);
}
}
}
return $parsed_date;
}
/**
* Parse additional flags
*
* @return void
* @throws Exceptions\ConnectionFailedException
*/
private function parseFlags() {
$this->flags = FlagCollection::make([]);
$this->client->openFolder($this->folder_path);
$flags = \imap_fetch_overview($this->client->getConnection(), $this->uid, IMAP::FT_UID);
if (is_array($flags) && isset($flags[0])) {
foreach($this->available_flags as $flag) {
$this->parseFlag($flags, $flag);
}
}
}
/**
* Extract a possible flag information from a given array
* @param array $flags
* @param string $flag
*/
private function parseFlag($flags, $flag) {
$flag = strtolower($flag);
if (property_exists($flags[0], strtoupper($flag))) {
$this->flags->put($flag, $flags[0]->{strtoupper($flag)});
} elseif (property_exists($flags[0], ucfirst($flag))) {
$this->flags->put($flag, $flags[0]->{ucfirst($flag)});
} elseif (property_exists($flags[0], $flag)) {
$this->flags->put($flag, $flags[0]->$flag);
}
}
/**
* Get the current Message header info
*
* @return object
* @throws Exceptions\ConnectionFailedException
*/
public function getHeaderInfo() {
if ($this->header_info == null) {
$this->client->openFolder($this->folder_path);
$this->header_info = \imap_headerinfo($this->client->getConnection(), $this->getMessageNo());
}
return $this->header_info;
}
/**
* Extract a given part as address array from a given header
* @param object $header
* @param string $part
*/
private function extractHeaderAddressPart($header, $part) {
if (property_exists($header, $part)) {
$this->$part = $this->parseAddresses($header->$part);
}
}
/**
* 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;
} else {
$personalParts = \imap_mime_header_decode($address->personal);
if(is_array($personalParts)) {
$address->personal = '';
foreach ($personalParts as $p) {
$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
*
* @return $this
* @throws Exceptions\ConnectionFailedException
*/
public function parseBody() {
$this->client->openFolder($this->folder_path);
$this->structure = \imap_fetchstructure($this->client->getConnection(), $this->uid, IMAP::FT_UID);
if(property_exists($this->structure, 'parts')){
$parts = $this->structure->parts;
foreach ($parts as $part) {
foreach ($part->parameters as $parameter) {
if($parameter->attribute == "charset") {
$encoding = $parameter->value;
$encoding = preg_replace('/Content-Transfer-Encoding/', '', $encoding);
$encoding = preg_replace('/iso-8859-8-i/', 'iso-8859-8', $encoding);
$parameter->value = $encoding;
}
}
}
}
$this->fetchStructure($this->structure);
return $this;
}
/**
* Fetch the Message structure
*
* @param $structure
* @param mixed $partNumber
*
* @throws Exceptions\ConnectionFailedException
*/
private function fetchStructure($structure, $partNumber = null) {
$this->client->openFolder($this->folder_path);
if ($structure->type == IMAP::MESSAGE_TYPE_TEXT &&
(empty($structure->disposition) || strtolower($structure->disposition) != 'attachment')
) {
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 | IMAP::FT_UID);
$content = $this->decodeString($content, $structure->encoding);
// 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 ($encoding != 'us-ascii') {
$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 | IMAP::FT_UID);
$content = $this->decodeString($content, $structure->encoding);
if ($encoding != 'us-ascii') {
$content = $this->convertEncoding($content, $encoding);
}
$body = new \stdClass;
$body->type = "html";
$body->content = $content;
$this->bodies['html'] = $body;
} elseif ($structure->ifdisposition == 1 && strtolower($structure->disposition) == 'attachment') {
if ($this->getFetchAttachmentOption() === true) {
$this->fetchAttachment($structure, $partNumber);
}
}
} elseif ($structure->type == IMAP::MESSAGE_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_long($option) === true) {
$this->fetch_options = $option;
} elseif (is_null($option) === true) {
$config = config('imap.options.fetch', IMAP::FT_UID);
$this->fetch_options = is_long($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 IMAP::MESSAGE_ENC_7BIT:
return $string;
case IMAP::MESSAGE_ENC_8BIT:
return quoted_printable_decode(\imap_8bit($string));
case IMAP::MESSAGE_ENC_BINARY:
return \imap_binary($string);
case IMAP::MESSAGE_ENC_BASE64:
return \imap_base64($string);
case IMAP::MESSAGE_ENC_QUOTED_PRINTABLE:
return quoted_printable_decode($string);
case IMAP::MESSAGE_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") {
$from = EncodingAliases::get($from);
$to = EncodingAliases::get($to);
if ($from === $to) {
return $str;
}
// 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;
}
if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') {
return @iconv($from, $to.'//IGNORE', $str);
} else {
if (!$from) {
return mb_convert_encoding($str, $to);
}
return mb_convert_encoding($str, $to, $from);
}
}
/**
* 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)
*
* @return mixed|null|Folder
* @throws Exceptions\ConnectionFailedException
* @throws Exceptions\MailboxFetchingException
* @throws InvalidMessageDateException
* @throws MaskNotFoundException
*/
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->path);
$uidMatches = \imap_fetch_overview($client->getConnection(), $this->uid, IMAP::FT_UID);
$uidMatch = count($uidMatches)
? new Message($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
return null;
}
public function getFolder(){
return $this->client->getFolder($this->folder_path);
}
/**
* Move the Message into an other Folder
* @param string $mailbox
* @param bool $expunge
* @param bool $create_folder
*
* @return null|Message
* @throws Exceptions\ConnectionFailedException
* @throws InvalidMessageDateException
*/
public function moveToFolder($mailbox = 'INBOX', $expunge = false, $create_folder = true) {
if($create_folder) $this->client->createFolder($mailbox, true);
$target_folder = $this->client->getFolder($mailbox);
$target_status = $target_folder->getStatus(IMAP::SA_ALL);
$this->client->openFolder($this->folder_path);
$status = \imap_mail_move($this->client->getConnection(), $this->uid, $mailbox, IMAP::CP_UID);
if($status === true){
if($expunge) $this->client->expunge();