forked from Webklex/php-imap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Message.php
executable file
·1739 lines (1549 loc) · 50.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\PHPIMAP;
use Exception;
use ReflectionClass;
use ReflectionException;
use Webklex\PHPIMAP\Exceptions\AuthFailedException;
use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
use Webklex\PHPIMAP\Exceptions\EventNotFoundException;
use Webklex\PHPIMAP\Exceptions\FolderFetchingException;
use Webklex\PHPIMAP\Exceptions\GetMessagesFailedException;
use Webklex\PHPIMAP\Exceptions\ImapBadRequestException;
use Webklex\PHPIMAP\Exceptions\ImapServerErrorException;
use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
use Webklex\PHPIMAP\Exceptions\MaskNotFoundException;
use Webklex\PHPIMAP\Exceptions\MessageContentFetchingException;
use Webklex\PHPIMAP\Exceptions\MessageFlagException;
use Webklex\PHPIMAP\Exceptions\MessageHeaderFetchingException;
use Webklex\PHPIMAP\Exceptions\MessageNotFoundException;
use Webklex\PHPIMAP\Exceptions\MessageSizeFetchingException;
use Webklex\PHPIMAP\Exceptions\MethodNotFoundException;
use Webklex\PHPIMAP\Exceptions\ResponseException;
use Webklex\PHPIMAP\Exceptions\RuntimeException;
use Webklex\PHPIMAP\Support\AttachmentCollection;
use Webklex\PHPIMAP\Support\FlagCollection;
use Webklex\PHPIMAP\Support\Masks\MessageMask;
use Illuminate\Support\Str;
use Webklex\PHPIMAP\Support\MessageCollection;
use Webklex\PHPIMAP\Traits\HasEvents;
/**
* Class Message
*
* @package Webklex\PHPIMAP
*
* @property integer msglist
* @property integer uid
* @property integer msgn
* @property integer size
* @property Attribute subject
* @property Attribute message_id
* @property Attribute message_no
* @property Attribute references
* @property Attribute date
* @property Attribute from
* @property Attribute to
* @property Attribute cc
* @property Attribute bcc
* @property Attribute reply_to
* @property Attribute in_reply_to
* @property Attribute sender
*
* @method integer getMsglist()
* @method integer setMsglist($msglist)
* @method integer getUid()
* @method integer getMsgn()
* @method integer getSize()
* @method Attribute getPriority()
* @method Attribute getSubject()
* @method Attribute getMessageId()
* @method Attribute getMessageNo()
* @method Attribute getReferences()
* @method Attribute getDate()
* @method Attribute getFrom()
* @method Attribute getTo()
* @method Attribute getCc()
* @method Attribute getBcc()
* @method Attribute getReplyTo()
* @method Attribute getInReplyTo()
* @method Attribute getSender()
*/
class Message {
use HasEvents;
/**
* Client instance
*
* @var ?Client
*/
private ?Client $client;
/**
* Default mask
*
* @var string $mask
*/
protected string $mask = MessageMask::class;
/**
* Used options
*
* @var array $options
*/
protected array $options = [];
/**
* All library configs
*
* @var Config $config
*/
protected Config $config;
/**
* Attribute holder
*
* @var Attribute[]|array $attributes
*/
protected array $attributes = [];
/**
* The message folder path
*
* @var string $folder_path
*/
protected string $folder_path;
/**
* Fetch body options
*
* @var ?integer
*/
public ?int $fetch_options = null;
/**
* @var integer
*/
protected int $sequence = IMAP::NIL;
/**
* Fetch body options
*
* @var bool
*/
public bool $fetch_body = true;
/**
* Fetch flags options
*
* @var bool
*/
public bool $fetch_flags = true;
/**
* @var ?Header $header
*/
public ?Header $header = null;
/**
* Raw message body
*
* @var string $raw_body
*/
protected string $raw_body = "";
/**
* Message structure
*
* @var ?Structure $structure
*/
protected ?Structure $structure = null;
/**
* Message body components
*
* @var array $bodies
*/
public array $bodies = [];
/** @var AttachmentCollection $attachments */
public AttachmentCollection $attachments;
/** @var FlagCollection $flags */
public FlagCollection $flags;
/**
* A list of all available and supported flags
*
* @var ?array $available_flags
*/
private ?array $available_flags = null;
/**
* Message constructor.
* @param integer $uid
* @param integer|null $msglist
* @param Client $client
* @param integer|null $fetch_options
* @param boolean $fetch_body
* @param boolean $fetch_flags
* @param integer|null $sequence
*
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws EventNotFoundException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws InvalidMessageDateException
* @throws MessageContentFetchingException
* @throws MessageFlagException
* @throws MessageHeaderFetchingException
* @throws RuntimeException
* @throws ResponseException
*/
public function __construct(int $uid, ?int $msglist, Client $client, int $fetch_options = null, bool $fetch_body = false, bool $fetch_flags = false, int $sequence = null) {
$this->boot($client->getConfig());
$default_mask = $client->getDefaultMessageMask();
if ($default_mask != null) {
$this->mask = $default_mask;
}
$this->events["message"] = $client->getDefaultEvents("message");
$this->events["flag"] = $client->getDefaultEvents("flag");
$this->folder_path = $client->getFolderPath();
$this->setSequence($sequence);
$this->setFetchOption($fetch_options);
$this->setFetchBodyOption($fetch_body);
$this->setFetchFlagsOption($fetch_flags);
$this->client = $client;
$this->client->openFolder($this->folder_path);
$this->setSequenceId($uid, $msglist);
if ($this->fetch_options == IMAP::FT_PEEK) {
$this->parseFlags();
}
$this->parseHeader();
if ($this->getFetchBodyOption() === true) {
$this->parseBody();
}
if ($this->getFetchFlagsOption() === true && $this->fetch_options !== IMAP::FT_PEEK) {
$this->parseFlags();
}
}
/**
* Create a new instance without fetching the message header and providing them raw instead
* @param int $uid
* @param int|null $msglist
* @param Client $client
* @param string $raw_header
* @param string $raw_body
* @param array $raw_flags
* @param null $fetch_options
* @param null $sequence
*
* @return Message
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws EventNotFoundException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws InvalidMessageDateException
* @throws MessageContentFetchingException
* @throws MessageFlagException
* @throws ReflectionException
* @throws RuntimeException
* @throws ResponseException
*/
public static function make(int $uid, ?int $msglist, Client $client, string $raw_header, string $raw_body, array $raw_flags, $fetch_options = null, $sequence = null): Message {
$reflection = new ReflectionClass(self::class);
/** @var Message $instance */
$instance = $reflection->newInstanceWithoutConstructor();
$instance->boot($client->getConfig());
$default_mask = $client->getDefaultMessageMask();
if ($default_mask != null) {
$instance->setMask($default_mask);
}
$instance->setEvents([
"message" => $client->getDefaultEvents("message"),
"flag" => $client->getDefaultEvents("flag"),
]);
$instance->setFolderPath($client->getFolderPath());
$instance->setSequence($sequence);
$instance->setFetchOption($fetch_options);
$instance->setClient($client);
$instance->setSequenceId($uid, $msglist);
$instance->parseRawHeader($raw_header);
$instance->parseRawFlags($raw_flags);
$instance->parseRawBody($raw_body);
$instance->peek();
return $instance;
}
/**
* Create a new message instance by reading and loading a file or remote location
* @param string $filename
* @param ?Config $config
*
* @return Message
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws InvalidMessageDateException
* @throws MaskNotFoundException
* @throws MessageContentFetchingException
* @throws ReflectionException
* @throws ResponseException
* @throws RuntimeException
*/
public static function fromFile(string $filename, Config $config = null): Message {
$blob = file_get_contents($filename);
if ($blob === false) {
throw new RuntimeException("Unable to read file");
}
return self::fromString($blob, $config);
}
/**
* Create a new message instance by reading and loading a string
* @param string $blob
* @param ?Config $config
*
* @return Message
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws InvalidMessageDateException
* @throws MaskNotFoundException
* @throws MessageContentFetchingException
* @throws ReflectionException
* @throws ResponseException
* @throws RuntimeException
*/
public static function fromString(string $blob, Config $config = null): Message {
$reflection = new ReflectionClass(self::class);
/** @var Message $instance */
$instance = $reflection->newInstanceWithoutConstructor();
$instance->boot($config);
$default_mask = $instance->getConfig()->getMask("message");
if($default_mask != ""){
$instance->setMask($default_mask);
}else{
throw new MaskNotFoundException("Unknown message mask provided");
}
if(!str_contains($blob, "\r\n")){
$blob = str_replace("\n", "\r\n", $blob);
}
$raw_header = substr($blob, 0, strpos($blob, "\r\n\r\n"));
$raw_body = substr($blob, strlen($raw_header)+4);
$instance->parseRawHeader($raw_header);
$instance->parseRawBody($raw_body);
$instance->setUid(0);
return $instance;
}
/**
* Boot a new instance
* @param ?Config $config
*/
public function boot(Config $config = null): void {
$this->attributes = [];
$this->client = null;
$this->config = $config ?? Config::make();
$this->options = $this->config->get('options');
$this->available_flags = $this->config->get('flags');
$this->attachments = AttachmentCollection::make();
$this->flags = FlagCollection::make();
}
/**
* Call dynamic attribute setter and getter methods
* @param string $method
* @param array $arguments
*
* @return mixed
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws MessageNotFoundException
* @throws MethodNotFoundException
* @throws MessageSizeFetchingException
* @throws RuntimeException
* @throws ResponseException
*/
public function __call(string $method, array $arguments) {
if (strtolower(substr($method, 0, 3)) === 'get') {
$name = Str::snake(substr($method, 3));
return $this->get($name);
} elseif (strtolower(substr($method, 0, 3)) === 'set') {
$name = Str::snake(substr($method, 3));
if (in_array($name, array_keys($this->attributes))) {
return $this->__set($name, array_pop($arguments));
}
}
throw new MethodNotFoundException("Method " . self::class . '::' . $method . '() is not supported');
}
/**
* Magic setter
* @param $name
* @param $value
*
* @return mixed
*/
public function __set($name, $value) {
$this->attributes[$name] = $value;
return $this->attributes[$name];
}
/**
* Magic getter
* @param $name
*
* @return Attribute|mixed|null
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws MessageNotFoundException
* @throws MessageSizeFetchingException
* @throws RuntimeException
* @throws ResponseException
*/
public function __get($name) {
return $this->get($name);
}
/**
* Get an available message or message header attribute
* @param $name
*
* @return Attribute|mixed|null
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws MessageNotFoundException
* @throws RuntimeException
* @throws ResponseException
* @throws MessageSizeFetchingException
*/
public function get($name): mixed {
if (isset($this->attributes[$name]) && $this->attributes[$name] !== null) {
return $this->attributes[$name];
}
switch ($name){
case "uid":
$this->attributes[$name] = $this->client->getConnection()->getUid($this->msgn)->validate()->integer();
return $this->attributes[$name];
case "msgn":
$this->attributes[$name] = $this->client->getConnection()->getMessageNumber($this->uid)->validate()->integer();
return $this->attributes[$name];
case "size":
if (!isset($this->attributes[$name])) {
$this->fetchSize();
}
return $this->attributes[$name];
}
return $this->header->get($name);
}
/**
* Check if the Message has a text body
*
* @return bool
*/
public function hasTextBody(): bool {
return isset($this->bodies['text']) && $this->bodies['text'] !== "";
}
/**
* Get the Message text body
*
* @return string
*/
public function getTextBody(): string {
if (!isset($this->bodies['text'])) {
return "";
}
return $this->bodies['text'];
}
/**
* Check if the Message has a html body
*
* @return bool
*/
public function hasHTMLBody(): bool {
return isset($this->bodies['html']) && $this->bodies['html'] !== "";
}
/**
* Get the Message html body
*
* @return string
*/
public function getHTMLBody(): string {
if (!isset($this->bodies['html'])) {
return "";
}
return $this->bodies['html'];
}
/**
* Parse all defined headers
*
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws InvalidMessageDateException
* @throws MessageHeaderFetchingException
* @throws ResponseException
*/
private function parseHeader(): void {
$sequence_id = $this->getSequenceId();
$headers = $this->client->getConnection()->headers([$sequence_id], "RFC822", $this->sequence)->validatedData();
if (!isset($headers[$sequence_id])) {
throw new MessageHeaderFetchingException("no headers found", 0);
}
$this->parseRawHeader($headers[$sequence_id]);
}
/**
* @param string $raw_header
*
* @throws InvalidMessageDateException
*/
public function parseRawHeader(string $raw_header): void {
$this->header = new Header($raw_header, $this->getConfig());
}
/**
* Parse additional raw flags
* @param array $raw_flags
*/
public function parseRawFlags(array $raw_flags): void {
$this->flags = FlagCollection::make();
foreach ($raw_flags as $flag) {
if (str_starts_with($flag, "\\")) {
$flag = substr($flag, 1);
}
$flag_key = strtolower($flag);
if ($this->available_flags === null || in_array($flag_key, $this->available_flags)) {
$this->flags->put($flag_key, $flag);
}
}
}
/**
* Parse additional flags
*
* @return void
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws MessageFlagException
* @throws RuntimeException
* @throws ResponseException
*/
private function parseFlags(): void {
$this->client->openFolder($this->folder_path);
$this->flags = FlagCollection::make();
$sequence_id = $this->getSequenceId();
try {
$flags = $this->client->getConnection()->flags([$sequence_id], $this->sequence)->validatedData();
} catch (Exceptions\RuntimeException $e) {
throw new MessageFlagException("flag could not be fetched", 0, $e);
}
if (isset($flags[$sequence_id])) {
$this->parseRawFlags($flags[$sequence_id]);
}
}
/**
* Parse the Message body
*
* @return Message
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws EventNotFoundException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws InvalidMessageDateException
* @throws MessageContentFetchingException
* @throws MessageFlagException
* @throws RuntimeException
* @throws ResponseException
*/
public function parseBody(): Message {
$this->client->openFolder($this->folder_path);
$sequence_id = $this->getSequenceId();
try {
$contents = $this->client->getConnection()->content([$sequence_id], "RFC822", $this->sequence)->validatedData();
} catch (Exceptions\RuntimeException $e) {
throw new MessageContentFetchingException("failed to fetch content", 0, $e);
}
if (!isset($contents[$sequence_id])) {
throw new MessageContentFetchingException("no content found", 0);
}
$content = $contents[$sequence_id];
$body = $this->parseRawBody($content);
$this->peek();
return $body;
}
/**
* Fetches the size for this message.
*
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws MessageSizeFetchingException
* @throws ResponseException
* @throws RuntimeException
*/
private function fetchSize(): void {
$sequence_id = $this->getSequenceId();
$sizes = $this->client->getConnection()->sizes([$sequence_id], $this->sequence)->validatedData();
if (!isset($sizes[$sequence_id])) {
throw new MessageSizeFetchingException("sizes did not set an array entry for the supplied sequence_id", 0);
}
$this->attributes["size"] = $sizes[$sequence_id];
}
/**
* Handle auto "Seen" flag handling
*
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws EventNotFoundException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws MessageFlagException
* @throws RuntimeException
* @throws ResponseException
*/
public function peek(): void {
if ($this->fetch_options == IMAP::FT_PEEK) {
if ($this->getFlags()->get("seen") == null) {
$this->unsetFlag("Seen");
}
} elseif ($this->getFlags()->get("seen") == null) {
$this->setFlag("Seen");
}
}
/**
* Parse a given message body
* @param string $raw_body
*
* @return Message
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws InvalidMessageDateException
* @throws MessageContentFetchingException
* @throws RuntimeException
* @throws ResponseException
*/
public function parseRawBody(string $raw_body): Message {
$this->structure = new Structure($raw_body, $this->header);
$this->fetchStructure($this->structure);
return $this;
}
/**
* Fetch the Message structure
* @param Structure $structure
*
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws ResponseException
*/
private function fetchStructure(Structure $structure): void {
$this->client?->openFolder($this->folder_path);
foreach ($structure->parts as $part) {
$this->fetchPart($part);
}
}
/**
* Fetch a given part
* @param Part $part
*/
private function fetchPart(Part $part): void {
if ($part->isAttachment()) {
$this->fetchAttachment($part);
} else {
$encoding = $this->getEncoding($part);
$content = $this->decodeString($part->content, $part->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);
}
$this->addBody($part->subtype ?? '', $content);
}
}
/**
* Add a body to the message
* @param string $subtype
* @param string $content
*
* @return void
*/
protected function addBody(string $subtype, string $content): void {
$subtype = strtolower($subtype);
$subtype = $subtype == "plain" || $subtype == "" ? "text" : $subtype;
if (isset($this->bodies[$subtype]) && $this->bodies[$subtype] !== null && $this->bodies[$subtype] !== "") {
if ($content !== "") {
$this->bodies[$subtype] .= "\n".$content;
}
} else {
$this->bodies[$subtype] = $content;
}
}
/**
* Fetch the Message attachment
* @param Part $part
*/
protected function fetchAttachment(Part $part): void {
$oAttachment = new Attachment($this, $part);
if ($oAttachment->getSize() > 0) {
if ($oAttachment->getId() !== null && $this->attachments->offsetExists($oAttachment->getId())) {
$this->attachments->put($oAttachment->getId(), $oAttachment);
} else {
$this->attachments->push($oAttachment);
}
}
}
/**
* Fail proof setter for $fetch_option
* @param $option
*
* @return Message
*/
public function setFetchOption($option): Message {
if (is_long($option) === true) {
$this->fetch_options = $option;
} elseif (is_null($option) === true) {
$config = $this->config->get('options.fetch', IMAP::FT_UID);
$this->fetch_options = is_long($config) ? $config : 1;
}
return $this;
}
/**
* Set the sequence type
* @param int|null $sequence
*
* @return Message
*/
public function setSequence(?int $sequence): Message {
if (is_long($sequence)) {
$this->sequence = $sequence;
} elseif (is_null($sequence)) {
$config = $this->config->get('options.sequence', IMAP::ST_MSGN);
$this->sequence = is_long($config) ? $config : IMAP::ST_MSGN;
}
return $this;
}
/**
* Fail proof setter for $fetch_body
* @param $option
*
* @return Message
*/
public function setFetchBodyOption($option): Message {
if (is_bool($option)) {
$this->fetch_body = $option;
} elseif (is_null($option)) {
$config = $this->config->get('options.fetch_body', true);
$this->fetch_body = is_bool($config) ? $config : true;
}
return $this;
}
/**
* Fail proof setter for $fetch_flags
* @param $option
*
* @return Message
*/
public function setFetchFlagsOption($option): Message {
if (is_bool($option)) {
$this->fetch_flags = $option;
} elseif (is_null($option)) {
$config = $this->config->get('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): string {
switch ($encoding) {
case IMAP::MESSAGE_ENC_BINARY:
if (extension_loaded('imap')) {
return base64_decode(\imap_binary($string));
}
return base64_decode($string);
case IMAP::MESSAGE_ENC_BASE64:
return base64_decode($string);
case IMAP::MESSAGE_ENC_QUOTED_PRINTABLE:
return quoted_printable_decode($string);
case IMAP::MESSAGE_ENC_8BIT:
case IMAP::MESSAGE_ENC_7BIT:
case IMAP::MESSAGE_ENC_OTHER:
default:
return $string;
}
}
/**
* Convert the encoding
* @param $str
* @param string $from
* @param string $to
*
* @return mixed|string
*/
public function convertEncoding($str, string $from = "ISO-8859-2", string $to = "UTF-8"): mixed {
$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') && !EncodingAliases::isUtf7($from) && !EncodingAliases::isUtf7($to)) {
try {
return iconv($from, $to.'//IGNORE', $str);
} catch (Exception) {
return @iconv($from, $to, $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(object|string $structure): string {
if (property_exists($structure, 'parameters')) {
foreach ($structure->parameters as $parameter) {
if (strtolower($parameter->attribute) == "charset") {
return EncodingAliases::get($parameter->value, "ISO-8859-2");
}
}
} elseif (property_exists($structure, 'charset')) {
return EncodingAliases::get($structure->charset, "ISO-8859-2");
} elseif (is_string($structure) === true) {
return EncodingAliases::detectEncoding($structure);
}
return 'UTF-8';
}
/**
* Get the messages folder
*
* @return ?Folder
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws FolderFetchingException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws ResponseException
*/
public function getFolder(): ?Folder {
return $this->client->getFolderByPath($this->folder_path);
}
/**
* Create a message thread based on the current message
* @param Folder|null $sent_folder
* @param MessageCollection|null $thread
* @param Folder|null $folder
*
* @return MessageCollection
* @throws AuthFailedException
* @throws ConnectionFailedException
* @throws FolderFetchingException
* @throws GetMessagesFailedException
* @throws ImapBadRequestException
* @throws ImapServerErrorException
* @throws RuntimeException
* @throws ResponseException
*/
public function thread(Folder $sent_folder = null, MessageCollection &$thread = null, Folder $folder = null): MessageCollection {
$thread = $thread ?: MessageCollection::make();
$folder = $folder ?: $this->getFolder();
$sent_folder = $sent_folder ?: $this->client->getFolderByPath($this->config->get("options.common_folders.sent", "INBOX/Sent"));
/** @var Message $message */
foreach ($thread as $message) {
if ($message->message_id->first() == $this->message_id->first()) {
return $thread;
}
}
$thread->push($this);