Header::getEncoding()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 10
c 2
b 0
f 1
dl 0
loc 15
rs 8.8333
cc 7
nc 6
nop 1
1
<?php
2
/*
3
* File: Header.php
4
* Category: -
5
* Author: M.Goldenbaum
6
* Created: 17.09.20 20:38
7
* Updated: -
8
*
9
* Description:
10
*  -
11
*/
12
13
namespace Webklex\PHPIMAP;
14
15
16
use Carbon\Carbon;
17
use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
18
use Webklex\PHPIMAP\Exceptions\MethodNotFoundException;
19
20
/**
21
 * Class Header
22
 *
23
 * @package Webklex\PHPIMAP
24
 */
25
class Header {
26
27
    /**
28
     * Raw header
29
     *
30
     * @var string $raw
31
     */
32
    public $raw = "";
33
34
    /**
35
     * Attribute holder
36
     *
37
     * @var Attribute[]|array $attributes
38
     */
39
    protected $attributes = [];
40
41
    /**
42
     * Config holder
43
     *
44
     * @var array $config
45
     */
46
    protected $config = [];
47
48
    /**
49
     * Fallback Encoding
50
     *
51
     * @var string
52
     */
53
    public $fallback_encoding = 'UTF-8';
54
55
    /**
56
     * Convert parsed values to attributes
57
     *
58
     * @var bool
59
     */
60
    protected $attributize = false;
61
62
    /**
63
     * Header constructor.
64
     * @param string $raw_header
65
     * @param boolean $attributize
66
     *
67
     * @throws InvalidMessageDateException
68
     */
69
    public function __construct(string $raw_header, bool $attributize = true) {
70
        $this->raw = $raw_header;
71
        $this->config = ClientManager::get('options');
72
        $this->attributize = $attributize;
73
        $this->parse();
74
    }
75
76
    /**
77
     * Call dynamic attribute setter and getter methods
78
     * @param string $method
79
     * @param array $arguments
80
     *
81
     * @return Attribute|mixed
82
     * @throws MethodNotFoundException
83
     */
84
    public function __call(string $method, array $arguments) {
85
        if (strtolower(substr($method, 0, 3)) === 'get') {
86
            $name = preg_replace('/(.)(?=[A-Z])/u', '$1_', substr(strtolower($method), 3));
87
88
            if (in_array($name, array_keys($this->attributes))) {
89
                return $this->attributes[$name];
90
            }
91
92
        }
93
94
        throw new MethodNotFoundException("Method " . self::class . '::' . $method . '() is not supported');
95
    }
96
97
    /**
98
     * Magic getter
99
     * @param $name
100
     *
101
     * @return Attribute|null
102
     */
103
    public function __get($name) {
104
        return $this->get($name);
105
    }
106
107
    /**
108
     * Get a specific header attribute
109
     * @param $name
110
     *
111
     * @return Attribute|mixed
112
     */
113
    public function get($name) {
114
        if (isset($this->attributes[$name])) {
115
            return $this->attributes[$name];
116
        }
117
118
        return null;
119
    }
120
121
    /**
122
     * Set a specific attribute
123
     * @param string $name
124
     * @param array|mixed $value
125
     * @param boolean $strict
126
     *
127
     * @return Attribute
128
     */
129
    public function set(string $name, $value, bool $strict = false) {
130
        if (isset($this->attributes[$name]) && $strict === false) {
131
            if ($this->attributize) {
132
                $this->attributes[$name]->add($value, true);
133
            } else {
134
                if (isset($this->attributes[$name])) {
135
                    if (!is_array($this->attributes[$name])) {
136
                        $this->attributes[$name] = [$this->attributes[$name], $value];
137
                    } else {
138
                        $this->attributes[$name][] = $value;
139
                    }
140
                } else {
141
                    $this->attributes[$name] = $value;
142
                }
143
            }
144
        } elseif (!$this->attributize) {
145
            $this->attributes[$name] = $value;
146
        } else {
147
            $this->attributes[$name] = new Attribute($name, $value);
148
        }
149
150
        return $this->attributes[$name];
151
    }
152
153
    /**
154
     * Perform a regex match all on the raw header and return the first result
155
     * @param $pattern
156
     *
157
     * @return mixed|null
158
     */
159
    public function find($pattern) {
160
        if (preg_match_all($pattern, $this->raw, $matches)) {
161
            if (isset($matches[1])) {
162
                if (count($matches[1]) > 0) {
163
                    return $matches[1][0];
164
                }
165
            }
166
        }
167
        return null;
168
    }
169
170
    /**
171
     * Try to find a boundary if possible
172
     *
173
     * @return string|null
174
     */
175
    public function getBoundary() {
176
        $regex = $this->config["boundary"] ?? "/boundary=(.*?(?=;)|(.*))/i";
177
        $boundary = $this->find($regex);
178
179
        if ($boundary === null) {
180
            return null;
181
        }
182
183
        return $this->clearBoundaryString($boundary);
184
    }
185
186
    /**
187
     * Remove all unwanted chars from a given boundary
188
     * @param string $str
189
     *
190
     * @return string
191
     */
192
    private function clearBoundaryString(string $str): string {
193
        return str_replace(['"', '\r', '\n', "\n", "\r", ";", "\s"], "", $str);
194
    }
195
196
    /**
197
     * Parse the raw headers
198
     *
199
     * @throws InvalidMessageDateException
200
     */
201
    protected function parse() {
202
        $header = $this->rfc822_parse_headers($this->raw);
203
204
        $this->extractAddresses($header);
205
206
        if (property_exists($header, 'subject')) {
207
            $this->set("subject", $this->decode($header->subject));
208
        }
209
        if (property_exists($header, 'references')) {
210
            $this->set("references", $this->decode($header->references));
211
        }
212
        if (property_exists($header, 'message_id')) {
213
            $this->set("message_id", str_replace(['<', '>'], '', $header->message_id));
214
        }
215
216
        $this->parseDate($header);
217
        foreach ($header as $key => $value) {
218
            $key = trim(rtrim(strtolower($key)));
219
            if (!isset($this->attributes[$key])) {
220
                $this->set($key, $value);
221
            }
222
        }
223
224
        $this->extractHeaderExtensions();
225
        $this->findPriority();
226
    }
227
228
    /**
229
     * Parse mail headers from a string
230
     * @link https://php.net/manual/en/function.imap-rfc822-parse-headers.php
231
     * @param $raw_headers
232
     *
233
     * @return object
234
     */
235
    public function rfc822_parse_headers($raw_headers) {
236
        $headers = [];
237
        $imap_headers = [];
238
        if (extension_loaded('imap') && $this->config["rfc822"]) {
239
            $raw_imap_headers = (array)\imap_rfc822_parse_headers($this->raw);
240
            foreach ($raw_imap_headers as $key => $values) {
241
                $key = str_replace("-", "_", $key);
242
                $imap_headers[$key] = $values;
243
            }
244
        }
245
        $lines = explode("\r\n", preg_replace("/\r\n\s/", ' ', $raw_headers));
246
        $prev_header = null;
247
        foreach ($lines as $line) {
248
            if (substr($line, 0, 1) === "\n") {
249
                $line = substr($line, 1);
250
            }
251
252
            if (substr($line, 0, 1) === "\t") {
253
                $line = substr($line, 1);
254
                $line = trim(rtrim($line));
255
                if ($prev_header !== null) {
256
                    $headers[$prev_header][] = $line;
257
                }
258
            } elseif (substr($line, 0, 1) === " ") {
259
                $line = substr($line, 1);
260
                $line = trim(rtrim($line));
261
                if ($prev_header !== null) {
262
                    if (!isset($headers[$prev_header])) {
263
                        $headers[$prev_header] = "";
264
                    }
265
                    if (is_array($headers[$prev_header])) {
266
                        $headers[$prev_header][] = $line;
267
                    } else {
268
                        $headers[$prev_header] .= $line;
269
                    }
270
                }
271
            } else {
272
                if (($pos = strpos($line, ":")) > 0) {
273
                    $key = trim(rtrim(strtolower(substr($line, 0, $pos))));
274
                    $key = str_replace("-", "_", $key);
275
276
                    $value = trim(rtrim(substr($line, $pos + 1)));
277
                    if (isset($headers[$key])) {
278
                        $headers[$key][] = $value;
279
                    } else {
280
                        $headers[$key] = [$value];
281
                    }
282
                    $prev_header = $key;
283
                }
284
            }
285
        }
286
287
        foreach ($headers as $key => $values) {
288
            if (isset($imap_headers[$key])) continue;
289
            $value = null;
290
            switch ($key) {
291
                case 'from':
292
                case 'to':
293
                case 'cc':
294
                case 'bcc':
295
                case 'reply_to':
296
                case 'sender':
297
                    $value = $this->decodeAddresses($values);
298
                    $headers[$key . "address"] = implode(", ", $values);
299
                    break;
300
                case 'subject':
301
                    $value = implode(" ", $values);
302
                    break;
303
                default:
304
                    if (is_array($values)) {
305
                        foreach ($values as $k => $v) {
306
                            if ($v == "") {
307
                                unset($values[$k]);
308
                            }
309
                        }
310
                        $available_values = count($values);
311
                        if ($available_values === 1) {
312
                            $value = array_pop($values);
313
                        } elseif ($available_values === 2) {
314
                            $value = implode(" ", $values);
315
                        } elseif ($available_values > 2) {
316
                            $value = array_values($values);
317
                        } else {
318
                            $value = "";
319
                        }
320
                    }
321
                    break;
322
            }
323
            $headers[$key] = $value;
324
        }
325
326
        return (object)array_merge($headers, $imap_headers);
327
    }
328
329
    /**
330
     * Decode MIME header elements
331
     * @link https://php.net/manual/en/function.imap-mime-header-decode.php
332
     * @param string $text The MIME text
333
     *
334
     * @return array The decoded elements are returned in an array of objects, where each
335
     * object has two properties, charset and text.
336
     */
337
    public function mime_header_decode(string $text): array {
338
        if (extension_loaded('imap')) {
339
            $result = \imap_mime_header_decode($text);
340
            return is_array($result) ? $result : [];
0 ignored issues
show
introduced by
The condition is_array($result) is always true.
Loading history...
341
        }
342
        $charset = $this->getEncoding($text);
343
        return [(object)[
344
            "charset" => $charset,
345
            "text"    => $this->convertEncoding($text, $charset)
346
        ]];
347
    }
348
349
    /**
350
     * Check if a given pair of strings has been decoded
351
     * @param $encoded
352
     * @param $decoded
353
     *
354
     * @return bool
355
     */
356
    private function notDecoded($encoded, $decoded): bool {
357
        return 0 === strpos($decoded, '=?')
358
            && strlen($decoded) - 2 === strpos($decoded, '?=')
359
            && false !== strpos($encoded, $decoded);
360
    }
361
362
    /**
363
     * Convert the encoding
364
     * @param $str
365
     * @param string $from
366
     * @param string $to
367
     *
368
     * @return mixed|string
369
     */
370
    public function convertEncoding($str, $from = "ISO-8859-2", $to = "UTF-8") {
371
372
        $from = EncodingAliases::get($from, $this->fallback_encoding);
373
        $to = EncodingAliases::get($to, $this->fallback_encoding);
374
375
        if ($from === $to) {
376
            return $str;
377
        }
378
379
        // We don't need to do convertEncoding() if charset is ASCII (us-ascii):
380
        //     ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded
381
        //     https://stackoverflow.com/a/11303410
382
        //
383
        // us-ascii is the same as ASCII:
384
        //     ASCII is the traditional name for the encoding system; the Internet Assigned Numbers Authority (IANA)
385
        //     prefers the updated name US-ASCII, which clarifies that this system was developed in the US and
386
        //     based on the typographical symbols predominantly in use there.
387
        //     https://en.wikipedia.org/wiki/ASCII
388
        //
389
        // convertEncoding() function basically means convertToUtf8(), so when we convert ASCII string into UTF-8 it gets broken.
390
        if (strtolower($from) == 'us-ascii' && $to == 'UTF-8') {
391
            return $str;
392
        }
393
394
        try {
395
            if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') {
396
                return iconv($from, $to, $str);
397
            } else {
398
                if (!$from) {
399
                    return mb_convert_encoding($str, $to);
400
                }
401
                return mb_convert_encoding($str, $to, $from);
402
            }
403
        } catch (\Exception $e) {
404
            if (strstr($from, '-')) {
405
                $from = str_replace('-', '', $from);
406
                return $this->convertEncoding($str, $from, $to);
407
            } else {
408
                return $str;
409
            }
410
        }
411
    }
412
413
    /**
414
     * Get the encoding of a given abject
415
     * @param object|string $structure
416
     *
417
     * @return string
418
     */
419
    public function getEncoding($structure): string {
420
        if (property_exists($structure, 'parameters')) {
421
            foreach ($structure->parameters as $parameter) {
422
                if (strtolower($parameter->attribute) == "charset") {
423
                    return EncodingAliases::get($parameter->value, $this->fallback_encoding);
424
                }
425
            }
426
        } elseif (property_exists($structure, 'charset')) {
427
            return EncodingAliases::get($structure->charset, $this->fallback_encoding);
428
        } elseif (is_string($structure) === true) {
429
            $result = mb_detect_encoding($structure);
430
            return $result === false ? $this->fallback_encoding : $result;
431
        }
432
433
        return $this->fallback_encoding;
434
    }
435
436
    /**
437
     * Test if a given value is utf-8 encoded
438
     * @param $value
439
     *
440
     * @return bool
441
     */
442
    private function is_uft8($value): bool {
443
        return strpos(strtolower($value), '=?utf-8?') === 0;
444
    }
445
446
    /**
447
     * Try to decode a specific header
448
     * @param mixed $value
449
     *
450
     * @return mixed
451
     */
452
    private function decode($value) {
453
        if (is_array($value)) {
454
            return $this->decodeArray($value);
455
        }
456
        $original_value = $value;
457
        $decoder = $this->config['decoder']['message'];
458
459
        if ($value !== null) {
460
            $is_utf8_base = $this->is_uft8($value);
461
462
            if ($decoder === 'utf-8' && extension_loaded('imap')) {
463
                $value = \imap_utf8($value);
464
                $is_utf8_base = $this->is_uft8($value);
465
                if ($is_utf8_base) {
466
                    $value = mb_decode_mimeheader($value);
467
                }
468
                if ($this->notDecoded($original_value, $value)) {
469
                    $decoded_value = $this->mime_header_decode($value);
470
                    if (count($decoded_value) > 0) {
471
                        if (property_exists($decoded_value[0], "text")) {
472
                            $value = $decoded_value[0]->text;
473
                        }
474
                    }
475
                }
476
            } elseif ($decoder === 'iconv' && $is_utf8_base) {
477
                $value = iconv_mime_decode($value);
478
            } elseif ($is_utf8_base) {
479
                $value = mb_decode_mimeheader($value);
480
            }
481
482
            if ($this->is_uft8($value)) {
483
                $value = mb_decode_mimeheader($value);
484
            }
485
486
            if ($this->notDecoded($original_value, $value)) {
487
                $value = $this->convertEncoding($original_value, $this->getEncoding($original_value));
488
            }
489
        }
490
491
        return $value;
492
    }
493
494
    /**
495
     * Decode a given array
496
     * @param array $values
497
     *
498
     * @return array
499
     */
500
    private function decodeArray(array $values): array {
501
        foreach ($values as $key => $value) {
502
            $values[$key] = $this->decode($value);
503
        }
504
        return $values;
505
    }
506
507
    /**
508
     * Try to extract the priority from a given raw header string
509
     */
510
    private function findPriority() {
511
        if (($priority = $this->get("x_priority")) === null) return;
512
        switch ((int)"$priority") {
513
            case IMAP::MESSAGE_PRIORITY_HIGHEST;
514
                $priority = IMAP::MESSAGE_PRIORITY_HIGHEST;
515
                break;
516
            case IMAP::MESSAGE_PRIORITY_HIGH;
517
                $priority = IMAP::MESSAGE_PRIORITY_HIGH;
518
                break;
519
            case IMAP::MESSAGE_PRIORITY_NORMAL;
520
                $priority = IMAP::MESSAGE_PRIORITY_NORMAL;
521
                break;
522
            case IMAP::MESSAGE_PRIORITY_LOW;
523
                $priority = IMAP::MESSAGE_PRIORITY_LOW;
524
                break;
525
            case IMAP::MESSAGE_PRIORITY_LOWEST;
526
                $priority = IMAP::MESSAGE_PRIORITY_LOWEST;
527
                break;
528
            default:
529
                $priority = IMAP::MESSAGE_PRIORITY_UNKNOWN;
530
                break;
531
        }
532
533
        $this->set("priority", $priority);
534
    }
535
536
    /**
537
     * Extract a given part as address array from a given header
538
     * @param $values
539
     *
540
     * @return array
541
     */
542
    private function decodeAddresses($values): array {
543
        $addresses = [];
544
545
        if (extension_loaded('mailparse') && $this->config["rfc822"]) {
546
            foreach ($values as $address) {
547
                foreach (\mailparse_rfc822_parse_addresses($address) as $parsed_address) {
548
                    if (isset($parsed_address['address'])) {
549
                        $mail_address = explode('@', $parsed_address['address']);
550
                        if (count($mail_address) == 2) {
551
                            $addresses[] = (object)[
552
                                "personal" => $parsed_address['display'] ?? '',
553
                                "mailbox"  => $mail_address[0],
554
                                "host"     => $mail_address[1],
555
                            ];
556
                        }
557
                    }
558
                }
559
            }
560
561
            return $addresses;
562
        }
563
564
        foreach ($values as $address) {
565
            foreach (preg_split('/, (?=(?:[^"]*"[^"]*")*[^"]*$)/', $address) as $split_address) {
566
                $split_address = trim(rtrim($split_address));
567
568
                if (strpos($split_address, ",") == strlen($split_address) - 1) {
569
                    $split_address = substr($split_address, 0, -1);
570
                }
571
                if (preg_match(
572
                    '/^(?:(?P<name>.+)\s)?(?(name)<|<?)(?P<email>[^\s]+?)(?(name)>|>?)$/',
573
                    $split_address,
574
                    $matches
575
                )) {
576
                    $name = trim(rtrim($matches["name"]));
577
                    $email = trim(rtrim($matches["email"]));
578
                    list($mailbox, $host) = array_pad(explode("@", $email), 2, null);
579
                    $addresses[] = (object)[
580
                        "personal" => $name,
581
                        "mailbox"  => $mailbox,
582
                        "host"     => $host,
583
                    ];
584
                }
585
            }
586
        }
587
588
        return $addresses;
589
    }
590
591
    /**
592
     * Extract a given part as address array from a given header
593
     * @param object $header
594
     */
595
    private function extractAddresses($header) {
596
        foreach (['from', 'to', 'cc', 'bcc', 'reply_to', 'sender'] as $key) {
597
            if (property_exists($header, $key)) {
598
                $this->set($key, $this->parseAddresses($header->$key));
599
            }
600
        }
601
    }
602
603
    /**
604
     * Parse Addresses
605
     * @param $list
606
     *
607
     * @return array
608
     */
609
    private function parseAddresses($list): array {
610
        $addresses = [];
611
612
        if (is_array($list) === false) {
613
            return $addresses;
614
        }
615
616
        foreach ($list as $item) {
617
            $address = (object)$item;
618
619
            if (!property_exists($address, 'mailbox')) {
620
                $address->mailbox = false;
621
            }
622
            if (!property_exists($address, 'host')) {
623
                $address->host = false;
624
            }
625
            if (!property_exists($address, 'personal')) {
626
                $address->personal = false;
627
            } else {
628
                $personalParts = $this->mime_header_decode($address->personal);
629
630
                if (is_array($personalParts)) {
631
                    $address->personal = '';
632
                    foreach ($personalParts as $p) {
633
                        $address->personal .= $this->convertEncoding($p->text, $this->getEncoding($p));
634
                    }
635
                }
636
637
                if (strpos($address->personal, "'") === 0) {
638
                    $address->personal = str_replace("'", "", $address->personal);
639
                }
640
            }
641
642
            $address->mail = ($address->mailbox && $address->host) ? $address->mailbox . '@' . $address->host : false;
643
            $address->full = ($address->personal) ? $address->personal . ' <' . $address->mail . '>' : $address->mail;
0 ignored issues
show
Bug introduced by
Are you sure $address->mail of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

643
            $address->full = ($address->personal) ? $address->personal . ' <' . /** @scrutinizer ignore-type */ $address->mail . '>' : $address->mail;
Loading history...
644
645
            $addresses[] = new Address($address);
646
        }
647
648
        return $addresses;
649
    }
650
651
    /**
652
     * Search and extract potential header extensions
653
     */
654
    private function extractHeaderExtensions() {
655
        foreach ($this->attributes as $key => $value) {
656
            if (is_array($value)) {
657
                $value = implode(", ", $value);
658
            } else {
659
                $value = (string)$value;
660
            }
661
            // Only parse strings and don't parse any attributes like the user-agent
662
            if (($key == "user_agent") === false) {
663
                if (($pos = strpos($value, ";")) !== false) {
664
                    $original = substr($value, 0, $pos);
665
                    $this->set($key, trim(rtrim($original)), true);
666
667
                    // Get all potential extensions
668
                    $extensions = explode(";", substr($value, $pos + 1));
669
                    foreach ($extensions as $extension) {
670
                        if (($pos = strpos($extension, "=")) !== false) {
671
                            $key = substr($extension, 0, $pos);
672
                            $key = trim(rtrim(strtolower($key)));
673
674
                            if (isset($this->attributes[$key]) === false) {
675
                                $value = substr($extension, $pos + 1);
676
                                $value = str_replace('"', "", $value);
677
                                $value = trim(rtrim($value));
678
679
                                $this->set($key, $value);
680
                            }
681
                        }
682
                    }
683
                }
684
            }
685
        }
686
    }
687
688
    /**
689
     * Exception handling for invalid dates
690
     *
691
     * Currently known invalid formats:
692
     * ^ Datetime                                   ^ Problem                           ^ Cause
693
     * | Mon, 20 Nov 2017 20:31:31 +0800 (GMT+8:00) | Double timezone specification     | A Windows feature
694
     * | Thu, 8 Nov 2018 08:54:58 -0200 (-02)       |
695
     * |                                            | and invalid timezone (max 6 char) |
696
     * | 04 Jan 2018 10:12:47 UT                    | Missing letter "C"                | Unknown
697
     * | Thu, 31 May 2018 18:15:00 +0800 (added by) | Non-standard details added by the | Unknown
698
     * |                                            | mail server                       |
699
     * | Sat, 31 Aug 2013 20:08:23 +0580            | Invalid timezone                  | PHPMailer bug https://sourceforge.net/p/phpmailer/mailman/message/6132703/
700
     *
701
     * Please report any new invalid timestamps to [#45](https://github.com/Webklex/php-imap/issues)
702
     *
703
     * @param object $header
704
     *
705
     * @throws InvalidMessageDateException
706
     */
707
    private function parseDate($header) {
708
709
        if (property_exists($header, 'date')) {
710
            $date = $header->date;
711
712
            if (preg_match('/\+0580/', $date)) {
713
                $date = str_replace('+0580', '+0530', $date);
714
            }
715
716
            $date = trim(rtrim($date));
717
            try {
718
                if(strpos($date, '&nbsp;') !== false){
719
                    $date = str_replace('&nbsp;', ' ', $date);
720
                }
721
                $parsed_date = Carbon::parse($date);
722
            } catch (\Exception $e) {
723
                switch (true) {
724
                    case preg_match('/([0-9]{4}\.[0-9]{1,2}\.[0-9]{1,2}\-[0-9]{1,2}\.[0-9]{1,2}.[0-9]{1,2})+$/i', $date) > 0:
725
                        $date = Carbon::createFromFormat("Y.m.d-H.i.s", $date);
726
                        break;
727
                    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:
728
                    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:
729
                        $date .= 'C';
730
                        break;
731
                    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:
732
                        $date = str_replace(',', '', $date);
733
                    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:
734
                    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:
735
                    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:
736
                    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:
737
                    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:
738
                        $array = explode('(', $date);
739
                        $array = array_reverse($array);
740
                        $date = trim(array_pop($array));
741
                        break;
742
                }
743
                try {
744
                    $parsed_date = Carbon::parse($date);
745
                } catch (\Exception $_e) {
746
                    if (!isset($this->config["fallback_date"])) {
747
                        throw new InvalidMessageDateException("Invalid message date. ID:" . $this->get("message_id") . " Date:" . $header->date . "/" . $date, 1100, $e);
748
                    } else {
749
                        $parsed_date = Carbon::parse($this->config["fallback_date"]);
750
                    }
751
                }
752
            }
753
754
            $this->set("date", $parsed_date);
755
        }
756
    }
757
758
    /**
759
     * Get all available attributes
760
     *
761
     * @return array
762
     */
763
    public function getAttributes(): array {
764
        return $this->attributes;
765
    }
766
767
}
768