Completed
Push — master ( bbfee2...cd9168 )
by Malte
02:04
created

Message::parseBody()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 12
c 3
b 1
f 0
dl 0
loc 18
rs 9.8666
cc 3
nc 3
nop 0
1
<?php
2
/*
3
* File:     Message.php
4
* Category: -
5
* Author:   M. Goldenbaum
6
* Created:  19.01.17 22:21
7
* Updated:  -
8
*
9
* Description:
10
*  -
11
*/
12
13
namespace Webklex\PHPIMAP;
14
15
use Carbon\Carbon;
16
use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
17
use Webklex\PHPIMAP\Exceptions\MaskNotFoundException;
18
use Webklex\PHPIMAP\Exceptions\MessageContentFetchingException;
19
use Webklex\PHPIMAP\Exceptions\MessageFlagException;
20
use Webklex\PHPIMAP\Exceptions\MessageHeaderFetchingException;
21
use Webklex\PHPIMAP\Exceptions\MethodNotFoundException;
22
use Webklex\PHPIMAP\Support\AttachmentCollection;
23
use Webklex\PHPIMAP\Support\FlagCollection;
24
use Webklex\PHPIMAP\Support\Masks\MessageMask;
25
use Illuminate\Support\Str;
26
use Webklex\PHPIMAP\Support\MessageCollection;
27
use Webklex\PHPIMAP\Traits\HasEvents;
28
29
/**
30
 * Class Message
31
 *
32
 * @package Webklex\PHPIMAP
33
 *
34
 * @property integer msglist
35
 * @property integer uid
36
 * @property integer msgn
37
 * @property string subject
38
 * @property string message_id
39
 * @property string message_no
40
 * @property string references
41
 * @property carbon date
42
 * @property array from
43
 * @property array to
44
 * @property array cc
45
 * @property array bcc
46
 * @property array reply_to
47
 * @property array in_reply_to
48
 * @property array sender
49
 *
50
 * @method integer getMsglist()
51
 * @method integer setMsglist(integer $msglist)
52
 * @method integer getUid()
53
 * @method integer getMsgn()
54
 * @method integer getPriority()
55
 * @method integer setPriority(integer $priority)
56
 * @method string getSubject()
57
 * @method string setSubject(string $subject)
58
 * @method string getMessageId()
59
 * @method string setMessageId(string $message_id)
60
 * @method string getMessageNo()
61
 * @method string setMessageNo(string $message_no)
62
 * @method string getReferences()
63
 * @method string setReferences(string $references)
64
 * @method carbon getDate()
65
 * @method carbon setDate(carbon $date)
66
 * @method array getFrom()
67
 * @method array setFrom(array $from)
68
 * @method array getTo()
69
 * @method array setTo(array $to)
70
 * @method array getCc()
71
 * @method array setCc(array $cc)
72
 * @method array getBcc()
73
 * @method array setBcc(array $bcc)
74
 * @method array getReplyTo()
75
 * @method array setReplyTo(array $reply_to)
76
 * @method array getInReplyTo()
77
 * @method array setInReplyTo(array $in_reply_to)
78
 * @method array getSender()
79
 * @method array setSender(array $sender)
80
 */
81
class Message {
82
    use HasEvents;
83
84
    /**
85
     * Client instance
86
     *
87
     * @var Client
88
     */
89
    private $client = Client::class;
90
91
    /**
92
     * Default mask
93
     *
94
     * @var string $mask
95
     */
96
    protected $mask = MessageMask::class;
97
98
    /**
99
     * Used config
100
     *
101
     * @var array $config
102
     */
103
    protected $config = [];
104
105
    /**
106
     * Attribute holder
107
     *
108
     * @var array $attributes
109
     */
110
    protected $attributes = [
111
        'message_no' => null,
112
    ];
113
114
    /**
115
     * The message folder path
116
     *
117
     * @var string $folder_path
118
     */
119
    protected $folder_path;
120
121
    /**
122
     * Fetch body options
123
     *
124
     * @var integer
125
     */
126
    public $fetch_options = null;
127
128
    /**
129
     * @var integer
130
     */
131
    protected $sequence = IMAP::NIL;
132
133
    /**
134
     * Fetch body options
135
     *
136
     * @var bool
137
     */
138
    public $fetch_body = null;
139
140
    /**
141
     * Fetch flags options
142
     *
143
     * @var bool
144
     */
145
    public $fetch_flags = null;
146
147
    /**
148
     * @var Header $header
149
     */
150
    public $header = null;
151
152
    /**
153
     * Raw message body
154
     *
155
     * @var null|string $raw_body
156
     */
157
    public $raw_body = null;
158
159
    /**
160
     * Message structure
161
     *
162
     * @var Structure $structure
163
     */
164
    protected $structure = null;
165
166
    /**
167
     * Message body components
168
     *
169
     * @var array   $bodies
170
     * @var AttachmentCollection|array $attachments
171
     * @var FlagCollection|array       $flags
172
     */
173
    public $bodies = [];
174
    public $attachments = [];
175
    public $flags = [];
176
177
    /**
178
     * A list of all available and supported flags
179
     *
180
     * @var array $available_flags
181
     */
182
    private $available_flags = null;
183
184
    /**
185
     * Message constructor.
186
     * @param integer $uid
187
     * @param integer|null $msglist
188
     * @param Client $client
189
     * @param integer|null $fetch_options
190
     * @param boolean $fetch_body
191
     * @param boolean $fetch_flags
192
     * @param integer $sequence
193
     *
194
     * @throws Exceptions\ConnectionFailedException
195
     * @throws InvalidMessageDateException
196
     * @throws Exceptions\RuntimeException
197
     * @throws MessageHeaderFetchingException
198
     * @throws MessageContentFetchingException
199
     * @throws Exceptions\EventNotFoundException
200
     * @throws MessageFlagException
201
     */
202
    public function __construct($uid, $msglist, Client $client, $fetch_options = null, $fetch_body = false, $fetch_flags = false, $sequence = null) {
203
204
        $default_mask = $client->getDefaultMessageMask();
205
        if($default_mask != null) {
206
            $this->mask = $default_mask;
207
        }
208
        $this->events["message"] = $client->getDefaultEvents("message");
209
        $this->events["flag"] = $client->getDefaultEvents("flag");
210
211
        $this->folder_path = $client->getFolderPath();
0 ignored issues
show
Documentation Bug introduced by
It seems like $client->getFolderPath() of type Webklex\PHPIMAP\Folder is incompatible with the declared type string of property $folder_path.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
212
213
        $this->config = ClientManager::get('options');
214
        $this->available_flags = ClientManager::get('flags');
215
216
        $this->setSequence($sequence);
217
        $this->setFetchOption($fetch_options);
218
        $this->setFetchBodyOption($fetch_body);
219
        $this->setFetchFlagsOption($fetch_flags);
220
221
        $this->attachments = AttachmentCollection::make([]);
222
        $this->flags = FlagCollection::make([]);
223
224
        $this->client = $client;
225
        $this->client->openFolder($this->folder_path);
0 ignored issues
show
Bug introduced by
$this->folder_path of type Webklex\PHPIMAP\Folder is incompatible with the type string expected by parameter $folder of Webklex\PHPIMAP\Client::openFolder(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

225
        $this->client->openFolder(/** @scrutinizer ignore-type */ $this->folder_path);
Loading history...
226
227
        if ($this->sequence === IMAP::ST_UID) {
228
            $this->uid = $uid;
229
            $this->msgn = $this->client->getConnection()->getMessageNumber($this->uid);
0 ignored issues
show
Bug introduced by
The method getMessageNumber() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

229
            $this->msgn = $this->client->getConnection()->/** @scrutinizer ignore-call */ getMessageNumber($this->uid);
Loading history...
230
        }else{
231
            $this->msgn = $uid;
232
            $this->uid = $this->client->getConnection()->getUid($this->msgn);
0 ignored issues
show
Bug introduced by
The method getUid() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

232
            $this->uid = $this->client->getConnection()->/** @scrutinizer ignore-call */ getUid($this->msgn);
Loading history...
233
        }
234
        $this->msglist = $msglist;
235
236
        if ($this->fetch_options == IMAP::FT_PEEK) {
237
            $this->parseFlags();
238
        }
239
240
        $this->parseHeader();
241
242
        if ($this->getFetchBodyOption() === true) {
243
            $this->parseBody();
244
        }
245
246
        if ($this->getFetchFlagsOption() === true && $this->fetch_options !== IMAP::FT_PEEK) {
247
            $this->parseFlags();
248
        }
249
    }
250
251
    /**
252
     * Create a new instance without fetching the message header and providing them raw instead
253
     * @param int $uid
254
     * @param int|null $msglist
255
     * @param Client $client
256
     * @param string $raw_header
257
     * @param string $raw_body
258
     * @param string $raw_flags
259
     * @param null $fetch_options
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fetch_options is correct as it would always require null to be passed?
Loading history...
260
     * @param null $sequence
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $sequence is correct as it would always require null to be passed?
Loading history...
261
     *
262
     * @return Message
263
     * @throws Exceptions\ConnectionFailedException
264
     * @throws Exceptions\EventNotFoundException
265
     * @throws InvalidMessageDateException
266
     * @throws MessageContentFetchingException
267
     * @throws \ReflectionException
268
     * @throws MessageFlagException
269
     * @throws Exceptions\RuntimeException
270
     */
271
    public static function make($uid, $msglist, Client $client, $raw_header, $raw_body, $raw_flags, $fetch_options = null, $sequence = null){
272
        $reflection = new \ReflectionClass(self::class);
273
        /** @var self $instance */
274
        $instance = $reflection->newInstanceWithoutConstructor();
275
276
        $default_mask = $client->getDefaultMessageMask();
277
        if($default_mask != null) {
278
            $instance->setMask($default_mask);
279
        }
280
        $instance->setEvents([
281
            "message" => $client->getDefaultEvents("message"),
282
            "flag" => $client->getDefaultEvents("flag"),
283
        ]);
284
        $instance->setFolderPath($client->getFolderPath());
285
        $instance->setConfig(ClientManager::get('options'));
286
        $instance->setAvailableFlags(ClientManager::get('flags'));
287
        $instance->setSequence($sequence);
288
        $instance->setFetchOption($fetch_options);
289
290
        $instance->setAttachments(AttachmentCollection::make([]));
291
292
        $instance->setClient($client);
293
294
        if ($instance->getSequence() === IMAP::ST_UID) {
295
            $instance->setUid($uid);
296
            $instance->setMsglist($msglist);
297
        }else{
298
            $instance->setMsgn($uid, $msglist);
0 ignored issues
show
Bug introduced by
It seems like $msglist can also be of type integer; however, parameter $msglist of Webklex\PHPIMAP\Message::setMsgn() does only seem to accept null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

298
            $instance->setMsgn($uid, /** @scrutinizer ignore-type */ $msglist);
Loading history...
299
        }
300
301
        $instance->parseRawHeader($raw_header);
302
        $instance->parseRawFlags($raw_flags);
303
        $instance->parseRawBody($raw_body);
304
        $instance->peek();
305
306
        return $instance;
307
    }
308
309
    /**
310
     * Call dynamic attribute setter and getter methods
311
     * @param string $method
312
     * @param array $arguments
313
     *
314
     * @return mixed
315
     * @throws MethodNotFoundException
316
     */
317
    public function __call($method, $arguments) {
318
        if(strtolower(substr($method, 0, 3)) === 'get') {
319
            $name = Str::snake(substr($method, 3));
320
            return $this->get($name);
321
        }elseif (strtolower(substr($method, 0, 3)) === 'set') {
322
            $name = Str::snake(substr($method, 3));
323
324
            if(in_array($name, array_keys($this->attributes))) {
325
                return $this->__set($name, array_pop($arguments));
326
            }
327
328
        }
329
330
        throw new MethodNotFoundException("Method ".self::class.'::'.$method.'() is not supported');
331
    }
332
333
    /**
334
     * Magic setter
335
     * @param $name
336
     * @param $value
337
     *
338
     * @return mixed
339
     */
340
    public function __set($name, $value) {
341
        $this->attributes[$name] = $value;
342
343
        return $this->attributes[$name];
344
    }
345
346
    /**
347
     * Magic getter
348
     * @param $name
349
     *
350
     * @return mixed|null
351
     */
352
    public function __get($name) {
353
        return $this->get($name);
354
    }
355
356
    /**
357
     * Get an available message or message header attribute
358
     * @param $name
359
     *
360
     * @return mixed|null
361
     */
362
    public function get($name) {
363
        if(isset($this->attributes[$name])) {
364
            return $this->attributes[$name];
365
        }
366
367
        return $this->header->get($name);
368
    }
369
370
    /**
371
     * Check if the Message has a text body
372
     *
373
     * @return bool
374
     */
375
    public function hasTextBody() {
376
        return isset($this->bodies['text']);
377
    }
378
379
    /**
380
     * Get the Message text body
381
     *
382
     * @return mixed
383
     */
384
    public function getTextBody() {
385
        if (!isset($this->bodies['text'])) {
386
            return null;
387
        }
388
389
        return $this->bodies['text'];
390
    }
391
392
    /**
393
     * Check if the Message has a html body
394
     *
395
     * @return bool
396
     */
397
    public function hasHTMLBody() {
398
        return isset($this->bodies['html']);
399
    }
400
401
    /**
402
     * Get the Message html body
403
     *
404
     * @return string|null
405
     */
406
    public function getHTMLBody() {
407
        if (!isset($this->bodies['html'])) {
408
            return null;
409
        }
410
411
        return $this->bodies['html'];
412
    }
413
414
    /**
415
     * Parse all defined headers
416
     *
417
     * @throws Exceptions\ConnectionFailedException
418
     * @throws Exceptions\RuntimeException
419
     * @throws InvalidMessageDateException
420
     * @throws MessageHeaderFetchingException
421
     */
422
    private function parseHeader() {
423
        $sequence_id = $this->getSequenceId();
424
        $headers = $this->client->getConnection()->headers([$sequence_id], "RFC822", $this->sequence === IMAP::ST_UID);
0 ignored issues
show
Bug introduced by
The method headers() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

424
        $headers = $this->client->getConnection()->/** @scrutinizer ignore-call */ headers([$sequence_id], "RFC822", $this->sequence === IMAP::ST_UID);
Loading history...
425
        if (!isset($headers[$sequence_id])) {
426
            throw new MessageHeaderFetchingException("no headers found", 0);
427
        }
428
429
        $this->parseRawHeader($headers[$sequence_id]);
430
    }
431
432
    /**
433
     * @param string $raw_header
434
     *
435
     * @throws InvalidMessageDateException
436
     */
437
    public function parseRawHeader($raw_header){
438
        $this->header = new Header($raw_header);
439
    }
440
441
    /**
442
     * Parse additional raw flags
443
     * @param $raw_flags
444
     */
445
    public function parseRawFlags($raw_flags) {
446
        $this->flags = FlagCollection::make([]);
447
448
        foreach($raw_flags as $flag) {
449
            if (strpos($flag, "\\") === 0){
450
                $flag = substr($flag, 1);
451
            }
452
            $flag_key = strtolower($flag);
453
            if (in_array($flag_key, $this->available_flags) || $this->available_flags === null) {
454
                $this->flags->put($flag_key, $flag);
455
            }
456
        }
457
    }
458
459
    /**
460
     * Parse additional flags
461
     *
462
     * @return void
463
     * @throws Exceptions\ConnectionFailedException
464
     * @throws MessageFlagException
465
     */
466
    private function parseFlags() {
467
        $this->client->openFolder($this->folder_path);
468
        $this->flags = FlagCollection::make([]);
469
470
        $sequence_id = $this->getSequenceId();
471
        try {
472
            $flags = $this->client->getConnection()->flags([$sequence_id], $this->sequence === IMAP::ST_UID);
0 ignored issues
show
Bug introduced by
The method flags() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

472
            $flags = $this->client->getConnection()->/** @scrutinizer ignore-call */ flags([$sequence_id], $this->sequence === IMAP::ST_UID);
Loading history...
473
        } catch (Exceptions\RuntimeException $e) {
474
            throw new MessageFlagException("flag could not be fetched", 0, $e);
475
        }
476
477
        if (isset($flags[$sequence_id])) {
478
            $this->parseRawFlags($flags[$sequence_id]);
479
        }
480
    }
481
482
    /**
483
     * Parse the Message body
484
     *
485
     * @return $this
486
     * @throws Exceptions\ConnectionFailedException
487
     * @throws Exceptions\MessageContentFetchingException
488
     * @throws InvalidMessageDateException
489
     * @throws Exceptions\EventNotFoundException
490
     * @throws MessageFlagException
491
     */
492
    public function parseBody() {
493
        $this->client->openFolder($this->folder_path);
494
495
        $sequence_id = $this->getSequenceId();
496
        try {
497
            $contents = $this->client->getConnection()->content([$sequence_id], "RFC822", $this->sequence === IMAP::ST_UID);
0 ignored issues
show
Bug introduced by
The method content() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

497
            $contents = $this->client->getConnection()->/** @scrutinizer ignore-call */ content([$sequence_id], "RFC822", $this->sequence === IMAP::ST_UID);
Loading history...
498
        } catch (Exceptions\RuntimeException $e) {
499
            throw new MessageContentFetchingException("failed to fetch content", 0);
500
        }
501
        if (!isset($contents[$sequence_id])) {
502
            throw new MessageContentFetchingException("no content found", 0);
503
        }
504
        $content = $contents[$sequence_id];
505
506
        $body = $this->parseRawBody($content);
507
        $this->peek();
508
509
        return $body;
510
    }
511
512
    /**
513
     * Handle auto "Seen" flag handling
514
     *
515
     * @throws Exceptions\ConnectionFailedException
516
     * @throws Exceptions\EventNotFoundException
517
     * @throws MessageFlagException
518
     */
519
    public function peek(){
520
        if ($this->fetch_options == IMAP::FT_PEEK) {
521
            if ($this->getFlags()->get("seen") == null) {
522
                $this->unsetFlag("Seen");
523
            }
524
        }elseif ($this->getFlags()->get("seen") != null) {
525
            $this->setFlag("Seen");
526
        }
527
    }
528
529
    /**
530
     * Parse a given message body
531
     * @param string $raw_body
532
     *
533
     * @return $this
534
     * @throws Exceptions\ConnectionFailedException
535
     * @throws InvalidMessageDateException
536
     * @throws MessageContentFetchingException
537
     */
538
    public function parseRawBody($raw_body) {
539
        $this->structure = new Structure($raw_body, $this->header);
540
        $this->fetchStructure($this->structure);
541
542
        return $this;
543
    }
544
545
    /**
546
     * Fetch the Message structure
547
     * @param $structure
548
     *
549
     * @throws Exceptions\ConnectionFailedException
550
     */
551
    private function fetchStructure($structure) {
552
        $this->client->openFolder($this->folder_path);
553
554
        foreach ($structure->parts as $part) {
555
            $this->fetchPart($part);
556
        }
557
    }
558
559
    /**
560
     * Fetch a given part
561
     * @param Part $part
562
     */
563
    private function fetchPart(Part $part) {
564
        if ($part->isAttachment()) {
565
            $this->fetchAttachment($part);
566
        }else{
567
            $encoding = $this->getEncoding($part);
568
569
            $content = $this->decodeString($part->content, $part->encoding);
570
571
            // We don't need to do convertEncoding() if charset is ASCII (us-ascii):
572
            //     ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded
573
            //     https://stackoverflow.com/a/11303410
574
            //
575
            // us-ascii is the same as ASCII:
576
            //     ASCII is the traditional name for the encoding system; the Internet Assigned Numbers Authority (IANA)
577
            //     prefers the updated name US-ASCII, which clarifies that this system was developed in the US and
578
            //     based on the typographical symbols predominantly in use there.
579
            //     https://en.wikipedia.org/wiki/ASCII
580
            //
581
            // convertEncoding() function basically means convertToUtf8(), so when we convert ASCII string into UTF-8 it gets broken.
582
            if ($encoding != 'us-ascii') {
583
                $content = $this->convertEncoding($content, $encoding);
584
            }
585
586
            $subtype = strtolower($part->subtype);
587
            $subtype = $subtype == "plain" || $subtype == "" ? "text" : $subtype;
588
589
            $this->bodies[$subtype] = $content;
590
        }
591
    }
592
593
    /**
594
     * Fetch the Message attachment
595
     * @param Part $part
596
     */
597
    protected function fetchAttachment($part) {
598
        $oAttachment = new Attachment($this, $part);
599
600
        if ($oAttachment->getName() !== null && $oAttachment->getSize() > 0) {
601
            if ($oAttachment->getId() !== null) {
0 ignored issues
show
introduced by
The condition $oAttachment->getId() !== null is always true.
Loading history...
602
                $this->attachments->put($oAttachment->getId(), $oAttachment);
603
            } else {
604
                $this->attachments->push($oAttachment);
605
            }
606
        }
607
    }
608
609
    /**
610
     * Fail proof setter for $fetch_option
611
     * @param $option
612
     *
613
     * @return $this
614
     */
615
    public function setFetchOption($option) {
616
        if (is_long($option) === true) {
617
            $this->fetch_options = $option;
618
        } elseif (is_null($option) === true) {
619
            $config = ClientManager::get('options.fetch', IMAP::FT_UID);
620
            $this->fetch_options = is_long($config) ? $config : 1;
621
        }
622
623
        return $this;
624
    }
625
626
    /**
627
     * Set the sequence type
628
     * @param int $sequence
629
     *
630
     * @return $this
631
     */
632
    public function setSequence($sequence) {
633
        if (is_long($sequence)) {
0 ignored issues
show
introduced by
The condition is_long($sequence) is always true.
Loading history...
634
            $this->sequence = $sequence;
635
        } elseif (is_null($sequence)) {
636
            $config = ClientManager::get('options.sequence', IMAP::ST_MSGN);
637
            $this->sequence = is_long($config) ? $config : IMAP::ST_MSGN;
638
        }
639
640
        return $this;
641
    }
642
643
    /**
644
     * Fail proof setter for $fetch_body
645
     * @param $option
646
     *
647
     * @return $this
648
     */
649
    public function setFetchBodyOption($option) {
650
        if (is_bool($option)) {
651
            $this->fetch_body = $option;
652
        } elseif (is_null($option)) {
653
            $config = ClientManager::get('options.fetch_body', true);
654
            $this->fetch_body = is_bool($config) ? $config : true;
655
        }
656
657
        return $this;
658
    }
659
660
    /**
661
     * Fail proof setter for $fetch_flags
662
     * @param $option
663
     *
664
     * @return $this
665
     */
666
    public function setFetchFlagsOption($option) {
667
        if (is_bool($option)) {
668
            $this->fetch_flags = $option;
669
        } elseif (is_null($option)) {
670
            $config = ClientManager::get('options.fetch_flags', true);
671
            $this->fetch_flags = is_bool($config) ? $config : true;
672
        }
673
674
        return $this;
675
    }
676
677
    /**
678
     * Decode a given string
679
     * @param $string
680
     * @param $encoding
681
     *
682
     * @return string
683
     */
684
    public function decodeString($string, $encoding) {
685
        switch ($encoding) {
686
            case IMAP::MESSAGE_ENC_BINARY:
687
                if (extension_loaded('imap')) {
688
                    return base64_decode(\imap_binary($string));
689
                }
690
                return base64_decode($string);
691
            case IMAP::MESSAGE_ENC_BASE64:
692
                return base64_decode($string);
693
            case IMAP::MESSAGE_ENC_8BIT:
694
            case IMAP::MESSAGE_ENC_QUOTED_PRINTABLE:
695
                return quoted_printable_decode($string);
696
            case IMAP::MESSAGE_ENC_7BIT:
697
            case IMAP::MESSAGE_ENC_OTHER:
698
            default:
699
                return $string;
700
        }
701
    }
702
703
    /**
704
     * Convert the encoding
705
     * @param $str
706
     * @param string $from
707
     * @param string $to
708
     *
709
     * @return mixed|string
710
     */
711
    public function convertEncoding($str, $from = "ISO-8859-2", $to = "UTF-8") {
712
713
        $from = EncodingAliases::get($from);
714
        $to = EncodingAliases::get($to);
715
716
        if ($from === $to) {
717
            return $str;
718
        }
719
720
        // We don't need to do convertEncoding() if charset is ASCII (us-ascii):
721
        //     ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded
722
        //     https://stackoverflow.com/a/11303410
723
        //
724
        // us-ascii is the same as ASCII:
725
        //     ASCII is the traditional name for the encoding system; the Internet Assigned Numbers Authority (IANA)
726
        //     prefers the updated name US-ASCII, which clarifies that this system was developed in the US and
727
        //     based on the typographical symbols predominantly in use there.
728
        //     https://en.wikipedia.org/wiki/ASCII
729
        //
730
        // convertEncoding() function basically means convertToUtf8(), so when we convert ASCII string into UTF-8 it gets broken.
731
        if (strtolower($from) == 'us-ascii' && $to == 'UTF-8') {
732
            return $str;
733
        }
734
735
        if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') {
736
            return @iconv($from, $to.'//IGNORE', $str);
737
        } else {
738
            if (!$from) {
739
                return mb_convert_encoding($str, $to);
740
            }
741
            return mb_convert_encoding($str, $to, $from);
742
        }
743
    }
744
745
    /**
746
     * Get the encoding of a given abject
747
     * @param object|string $structure
748
     *
749
     * @return string
750
     */
751
    public function getEncoding($structure) {
752
        if (property_exists($structure, 'parameters')) {
753
            foreach ($structure->parameters as $parameter) {
754
                if (strtolower($parameter->attribute) == "charset") {
755
                    return EncodingAliases::get($parameter->value);
756
                }
757
            }
758
        }elseif (property_exists($structure, 'charset')){
759
            return EncodingAliases::get($structure->charset);
760
        }elseif (is_string($structure) === true){
761
            return mb_detect_encoding($structure);
762
        }
763
764
        return 'UTF-8';
765
    }
766
767
    /**
768
     * Get the messages folder
769
     *
770
     * @return mixed
771
     * @throws Exceptions\ConnectionFailedException
772
     * @throws Exceptions\FolderFetchingException
773
     */
774
    public function getFolder(){
775
        return $this->client->getFolder($this->folder_path);
776
    }
777
778
    /**
779
     * Create a message thread based on the current message
780
     * @param Folder|null $sent_folder
781
     * @param MessageCollection|null $thread
782
     * @param Folder|null $folder
783
     *
784
     * @return MessageCollection|null
785
     * @throws Exceptions\ConnectionFailedException
786
     * @throws Exceptions\FolderFetchingException
787
     * @throws Exceptions\GetMessagesFailedException
788
     */
789
    public function thread($sent_folder = null, &$thread = null, $folder = null){
790
        $thread = $thread ? $thread : MessageCollection::make([]);
791
        $folder = $folder ? $folder :  $this->getFolder();
792
        $sent_folder = $sent_folder ? $sent_folder : $this->client->getFolder(ClientManager::get("options.common_folders.sent", "INBOX/Sent"));
793
794
        /** @var Message $message */
795
        foreach($thread as $message) {
796
            if ($message->message_id == $this->message_id) {
797
                return $thread;
798
            }
799
        }
800
        $thread->push($this);
801
802
        $folder->query()->inReplyTo($this->message_id)
803
            ->setFetchBody($this->getFetchBodyOption())
804
            ->leaveUnread()->get()->each(function($message) use(&$thread, $folder, $sent_folder){
805
            /** @var Message $message */
806
            $message->thread($sent_folder, $thread, $folder);
807
        });
808
        $sent_folder->query()->inReplyTo($this->message_id)
809
            ->setFetchBody($this->getFetchBodyOption())
810
            ->leaveUnread()->get()->each(function($message) use(&$thread, $folder, $sent_folder){
811
            /** @var Message $message */
812
                $message->thread($sent_folder, $thread, $folder);
813
        });
814
815
        if (is_array($this->in_reply_to)) {
0 ignored issues
show
introduced by
The condition is_array($this->in_reply_to) is always true.
Loading history...
816
            foreach($this->in_reply_to as $in_reply_to) {
817
                $folder->query()->messageId($in_reply_to)
818
                    ->setFetchBody($this->getFetchBodyOption())
819
                    ->leaveUnread()->get()->each(function($message) use(&$thread, $folder, $sent_folder){
820
                    /** @var Message $message */
821
                        $message->thread($sent_folder, $thread, $folder);
822
                });
823
                $sent_folder->query()->messageId($in_reply_to)
824
                    ->setFetchBody($this->getFetchBodyOption())
825
                    ->leaveUnread()->get()->each(function($message) use(&$thread, $folder, $sent_folder){
826
                    /** @var Message $message */
827
                        $message->thread($sent_folder, $thread, $folder);
828
                });
829
            }
830
        }
831
832
        return $thread;
833
    }
834
835
    /**
836
     * Copy the current Messages to a mailbox
837
     * @param string $folder_path
838
     * @param boolean $expunge
839
     *
840
     * @return null|Message
841
     * @throws Exceptions\ConnectionFailedException
842
     * @throws Exceptions\FolderFetchingException
843
     * @throws Exceptions\RuntimeException
844
     * @throws InvalidMessageDateException
845
     * @throws MessageContentFetchingException
846
     * @throws MessageHeaderFetchingException
847
     * @throws Exceptions\EventNotFoundException
848
     */
849
    public function copy($folder_path, $expunge = false) {
850
        $this->client->openFolder($folder_path);
851
        $status = $this->client->getConnection()->examineFolder($folder_path);
0 ignored issues
show
Bug introduced by
The method examineFolder() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

851
        $status = $this->client->getConnection()->/** @scrutinizer ignore-call */ examineFolder($folder_path);
Loading history...
852
853
        if (isset($status["uidnext"])) {
854
            $next_uid = $status["uidnext"];
855
856
            /** @var Folder $folder */
857
            $folder = $this->client->getFolder($folder_path);
858
859
            $this->client->openFolder($this->folder_path);
860
            if ($this->client->getConnection()->copyMessage($folder->path, $this->getSequenceId(), null, $this->sequence === IMAP::ST_UID) == true) {
0 ignored issues
show
Bug introduced by
The method copyMessage() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

860
            if ($this->client->getConnection()->/** @scrutinizer ignore-call */ copyMessage($folder->path, $this->getSequenceId(), null, $this->sequence === IMAP::ST_UID) == true) {
Loading history...
861
                if($expunge) $this->client->expunge();
862
863
                $this->client->openFolder($folder->path);
864
865
                if ($this->sequence === IMAP::ST_UID) {
866
                    $sequence_id = $next_uid;
867
                }else{
868
                    $sequence_id = $this->client->getConnection()->getMessageNumber($next_uid);
869
                }
870
871
                $message = $folder->query()->getMessage($sequence_id, null, $this->sequence);
872
                $event = $this->getEvent("message", "copied");
873
                $event::dispatch($this, $message);
874
875
                return $message;
876
            }
877
        }
878
879
        return null;
880
    }
881
882
    /**
883
     * Move the current Messages to a mailbox
884
     * @param string $folder_path
885
     * @param boolean $expunge
886
     *
887
     * @return Message|null
888
     * @throws Exceptions\ConnectionFailedException
889
     * @throws Exceptions\FolderFetchingException
890
     * @throws Exceptions\RuntimeException
891
     * @throws InvalidMessageDateException
892
     * @throws MessageContentFetchingException
893
     * @throws MessageHeaderFetchingException
894
     * @throws Exceptions\EventNotFoundException
895
     */
896
    public function move($folder_path, $expunge = false) {
897
        $this->client->openFolder($folder_path);
898
        $status = $this->client->getConnection()->examineFolder($folder_path);
899
900
        if (isset($status["uidnext"])) {
901
            $next_uid = $status["uidnext"];
902
903
            /** @var Folder $folder */
904
            $folder = $this->client->getFolder($folder_path);
905
906
            $this->client->openFolder($this->folder_path);
907
            if ($this->client->getConnection()->moveMessage($folder->path, $this->getSequenceId(), null, $this->sequence === IMAP::ST_UID) == true) {
0 ignored issues
show
Bug introduced by
The method moveMessage() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

907
            if ($this->client->getConnection()->/** @scrutinizer ignore-call */ moveMessage($folder->path, $this->getSequenceId(), null, $this->sequence === IMAP::ST_UID) == true) {
Loading history...
908
                if($expunge) $this->client->expunge();
909
910
                $this->client->openFolder($folder->path);
911
912
                if ($this->sequence === IMAP::ST_UID) {
913
                    $sequence_id = $next_uid;
914
                }else{
915
                    $sequence_id = $this->client->getConnection()->getMessageNumber($next_uid);
916
                }
917
918
                $message = $folder->query()->getMessage($sequence_id, null, $this->sequence);
919
                $event = $this->getEvent("message", "moved");
920
                $event::dispatch($this, $message);
921
922
                return $message;
923
            }
924
        }
925
926
        return null;
927
    }
928
929
    /**
930
     * Delete the current Message
931
     * @param bool $expunge
932
     *
933
     * @return bool
934
     * @throws Exceptions\ConnectionFailedException
935
     * @throws Exceptions\EventNotFoundException
936
     * @throws MessageFlagException
937
     */
938
    public function delete($expunge = true) {
939
        $status = $this->setFlag("Deleted");
940
        if($expunge) $this->client->expunge();
941
942
        $event = $this->getEvent("message", "deleted");
943
        $event::dispatch($this);
944
945
        return $status;
946
    }
947
948
    /**
949
     * Restore a deleted Message
950
     * @param boolean $expunge
951
     *
952
     * @return bool
953
     * @throws Exceptions\ConnectionFailedException
954
     * @throws Exceptions\EventNotFoundException
955
     * @throws MessageFlagException
956
     */
957
    public function restore($expunge = true) {
958
        $status = $this->unsetFlag("Deleted");
959
        if($expunge) $this->client->expunge();
960
961
        $event = $this->getEvent("message", "restored");
962
        $event::dispatch($this);
963
964
        return $status;
965
    }
966
967
    /**
968
     * Set a given flag
969
     * @param string|array $flag
970
     *
971
     * @return bool
972
     * @throws Exceptions\ConnectionFailedException
973
     * @throws MessageFlagException
974
     * @throws Exceptions\EventNotFoundException
975
     */
976
    public function setFlag($flag) {
977
        $this->client->openFolder($this->folder_path);
978
        $flag = "\\".trim(is_array($flag) ? implode(" \\", $flag) : $flag);
979
        $sequence_id = $this->getSequenceId();
980
        try {
981
            $status = $this->client->getConnection()->store([$flag], $sequence_id, $sequence_id, "+", true, $this->sequence === IMAP::ST_UID);
0 ignored issues
show
Bug introduced by
The method store() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. Since it exists in all sub-types, consider adding an abstract or default implementation to Webklex\PHPIMAP\Connection\Protocols\Protocol. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

981
            $status = $this->client->getConnection()->/** @scrutinizer ignore-call */ store([$flag], $sequence_id, $sequence_id, "+", true, $this->sequence === IMAP::ST_UID);
Loading history...
982
        } catch (Exceptions\RuntimeException $e) {
983
            throw new MessageFlagException("flag could not be set", 0, $e);
984
        }
985
        $this->parseFlags();
986
987
        $event = $this->getEvent("flag", "new");
988
        $event::dispatch($this, $flag);
989
990
        return $status;
991
    }
992
993
    /**
994
     * Unset a given flag
995
     * @param string|array $flag
996
     *
997
     * @return bool
998
     * @throws Exceptions\ConnectionFailedException
999
     * @throws Exceptions\EventNotFoundException
1000
     * @throws MessageFlagException
1001
     */
1002
    public function unsetFlag($flag) {
1003
        $this->client->openFolder($this->folder_path);
1004
1005
        $flag = "\\".trim(is_array($flag) ? implode(" \\", $flag) : $flag);
1006
        $sequence_id = $this->getSequenceId();
1007
        try {
1008
            $status = $this->client->getConnection()->store([$flag], $sequence_id, $sequence_id, "-", true, $this->sequence === IMAP::ST_UID);
1009
        } catch (Exceptions\RuntimeException $e) {
1010
            throw new MessageFlagException("flag could not be removed", 0, $e);
1011
        }
1012
        $this->parseFlags();
1013
1014
        $event = $this->getEvent("flag", "deleted");
1015
        $event::dispatch($this, $flag);
1016
1017
        return $status;
1018
    }
1019
1020
    /**
1021
     * Set a given flag
1022
     * @param string|array $flag
1023
     *
1024
     * @return bool
1025
     * @throws Exceptions\ConnectionFailedException
1026
     * @throws MessageFlagException
1027
     * @throws Exceptions\EventNotFoundException
1028
     */
1029
    public function addFlag($flag) {
1030
        return $this->setFlag($flag);
1031
    }
1032
1033
    /**
1034
     * Unset a given flag
1035
     * @param string|array $flag
1036
     *
1037
     * @return bool
1038
     * @throws Exceptions\ConnectionFailedException
1039
     * @throws Exceptions\EventNotFoundException
1040
     * @throws MessageFlagException
1041
     */
1042
    public function removeFlag($flag) {
1043
        return $this->unsetFlag($flag);
1044
    }
1045
1046
    /**
1047
     * Get all message attachments.
1048
     *
1049
     * @return AttachmentCollection
1050
     */
1051
    public function getAttachments() {
1052
        return $this->attachments;
1053
    }
1054
1055
    /**
1056
     * Get all message attachments.
1057
     *
1058
     * @return AttachmentCollection
1059
     */
1060
    public function attachments(){
1061
        return $this->getAttachments();
1062
    }
1063
1064
    /**
1065
     * Checks if there are any attachments present
1066
     *
1067
     * @return boolean
1068
     */
1069
    public function hasAttachments() {
1070
        return $this->attachments->isEmpty() === false;
1071
    }
1072
1073
    /**
1074
     * Get the raw body
1075
     *
1076
     * @return string
1077
     * @throws Exceptions\ConnectionFailedException
1078
     */
1079
    public function getRawBody() {
1080
        if ($this->raw_body === null) {
1081
            $this->client->openFolder($this->folder_path);
1082
1083
            $this->raw_body = $this->structure->raw;
1084
        }
1085
1086
        return $this->raw_body;
1087
    }
1088
1089
    /**
1090
     * Get the message header
1091
     *
1092
     * @return Header
1093
     */
1094
    public function getHeader() {
1095
        return $this->header;
1096
    }
1097
1098
    /**
1099
     * Get the current client
1100
     *
1101
     * @return Client
1102
     */
1103
    public function getClient() {
1104
        return $this->client;
1105
    }
1106
1107
    /**
1108
     * Get the used fetch option
1109
     *
1110
     * @return integer
1111
     */
1112
    public function getFetchOptions() {
1113
        return $this->fetch_options;
1114
    }
1115
1116
    /**
1117
     * Get the used fetch body option
1118
     *
1119
     * @return boolean
1120
     */
1121
    public function getFetchBodyOption() {
1122
        return $this->fetch_body;
1123
    }
1124
1125
    /**
1126
     * Get the used fetch flags option
1127
     *
1128
     * @return boolean
1129
     */
1130
    public function getFetchFlagsOption() {
1131
        return $this->fetch_flags;
1132
    }
1133
1134
    /**
1135
     * Get all available bodies
1136
     *
1137
     * @return array
1138
     */
1139
    public function getBodies() {
1140
        return $this->bodies;
1141
    }
1142
1143
    /**
1144
     * Get all set flags
1145
     *
1146
     * @return FlagCollection
1147
     */
1148
    public function getFlags() {
1149
        return $this->flags;
1150
    }
1151
1152
    /**
1153
     * Get all set flags
1154
     *
1155
     * @return FlagCollection
1156
     */
1157
    public function flags(){
1158
        return $this->getFlags();
1159
    }
1160
1161
    /**
1162
     * Get the fetched structure
1163
     *
1164
     * @return Structure|null
1165
     */
1166
    public function getStructure(){
1167
        return $this->structure;
1168
    }
1169
1170
    /**
1171
     * Check if a message matches an other by comparing basic attributes
1172
     *
1173
     * @param  null|Message $message
1174
     * @return boolean
1175
     */
1176
    public function is(Message $message = null) {
1177
        if (is_null($message)) {
1178
            return false;
1179
        }
1180
1181
        return $this->uid == $message->uid
1182
            && $this->message_id == $message->message_id
1183
            && $this->subject == $message->subject
1184
            && $this->date->eq($message->date);
1185
    }
1186
1187
    /**
1188
     * Get all message attributes
1189
     *
1190
     * @return array
1191
     */
1192
    public function getAttributes(){
1193
        return array_merge($this->attributes, $this->header->getAttributes());
1194
    }
1195
1196
    /**
1197
     * Set the message mask
1198
     * @param $mask
1199
     *
1200
     * @return $this
1201
     */
1202
    public function setMask($mask){
1203
        if(class_exists($mask)){
1204
            $this->mask = $mask;
1205
        }
1206
1207
        return $this;
1208
    }
1209
1210
    /**
1211
     * Get the used message mask
1212
     *
1213
     * @return string
1214
     */
1215
    public function getMask(){
1216
        return $this->mask;
1217
    }
1218
1219
    /**
1220
     * Get a masked instance by providing a mask name
1221
     * @param string|null $mask
1222
     *
1223
     * @return mixed
1224
     * @throws MaskNotFoundException
1225
     */
1226
    public function mask($mask = null){
1227
        $mask = $mask !== null ? $mask : $this->mask;
1228
        if(class_exists($mask)){
1229
            return new $mask($this);
1230
        }
1231
1232
        throw new MaskNotFoundException("Unknown mask provided: ".$mask);
1233
    }
1234
1235
    /**
1236
     * Set the message path aka folder path
1237
     * @param $folder_path
1238
     *
1239
     * @return $this
1240
     */
1241
    public function setFolderPath($folder_path){
1242
        $this->folder_path = $folder_path;
1243
1244
        return $this;
1245
    }
1246
1247
    /**
1248
     * Set the config
1249
     * @param $config
1250
     *
1251
     * @return $this
1252
     */
1253
    public function setConfig($config){
1254
        $this->config = $config;
1255
1256
        return $this;
1257
    }
1258
1259
    /**
1260
     * Set the available flags
1261
     * @param $available_flags
1262
     *
1263
     * @return $this
1264
     */
1265
    public function setAvailableFlags($available_flags){
1266
        $this->available_flags = $available_flags;
1267
1268
        return $this;
1269
    }
1270
1271
    /**
1272
     * Set the attachment collection
1273
     * @param $attachments
1274
     *
1275
     * @return $this
1276
     */
1277
    public function setAttachments($attachments){
1278
        $this->attachments = $attachments;
1279
1280
        return $this;
1281
    }
1282
1283
    /**
1284
     * Set the flag collection
1285
     * @param $flags
1286
     *
1287
     * @return $this
1288
     */
1289
    public function setFlags($flags){
1290
        $this->flags = $flags;
1291
1292
        return $this;
1293
    }
1294
1295
    /**
1296
     * Set the client
1297
     * @param $client
1298
     *
1299
     * @throws Exceptions\ConnectionFailedException
1300
     * @return $this
1301
     */
1302
    public function setClient($client){
1303
        $this->client = $client;
1304
        $this->client->openFolder($this->folder_path);
1305
1306
        return $this;
1307
    }
1308
1309
    /**
1310
     * Set the message number
1311
     * @param int $uid
1312
     *
1313
     * @throws Exceptions\ConnectionFailedException
1314
     * @throws Exceptions\RuntimeException
1315
     * @return $this
1316
     */
1317
    public function setUid($uid){
1318
        $this->uid = $uid;
1319
        $this->msgn = $this->client->getConnection()->getMessageNumber($this->uid);
1320
        $this->msglist = null;
1321
1322
        return $this;
1323
    }
1324
1325
    /**
1326
     * Set the message number
1327
     * @param $msgn
1328
     * @param null $msglist
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $msglist is correct as it would always require null to be passed?
Loading history...
1329
     *
1330
     * @throws Exceptions\ConnectionFailedException
1331
     * @throws Exceptions\RuntimeException
1332
     * @return $this
1333
     */
1334
    public function setMsgn($msgn, $msglist = null){
1335
        $this->msgn = $msgn;
1336
        $this->msglist = $msglist;
1337
        $this->uid = $this->client->getConnection()->getUid($this->msgn);
1338
1339
        return $this;
1340
    }
1341
1342
    /**
1343
     * Get the current sequence type
1344
     *
1345
     * @return int
1346
     */
1347
    public function getSequence(){
1348
        return $this->sequence;
1349
    }
1350
1351
    /**
1352
     * Set the sequence type
1353
     *
1354
     * @return int
1355
     */
1356
    public function getSequenceId(){
1357
        return $this->sequence === IMAP::ST_UID ? $this->uid : $this->msgn;
1358
    }
1359
}
1360