Completed
Push — master ( 872ca7...4d0bad )
by Malte
01:49
created

Header::__call()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 11
rs 10
cc 3
nc 3
nop 2
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 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
     * Header constructor.
57
     * @param $raw_header
58
     *
59
     * @throws InvalidMessageDateException
60
     */
61
    public function __construct($raw_header) {
62
        $this->raw = $raw_header;
63
        $this->config = ClientManager::get('options');
64
        $this->parse();
65
    }
66
67
    /**
68
     * Call dynamic attribute setter and getter methods
69
     * @param string $method
70
     * @param array $arguments
71
     *
72
     * @return mixed
73
     * @throws MethodNotFoundException
74
     */
75
    public function __call($method, $arguments) {
76
        if(strtolower(substr($method, 0, 3)) === 'get') {
77
            $name = preg_replace('/(.)(?=[A-Z])/u', '$1_', substr(strtolower($method), 3));
78
79
            if(in_array($name, array_keys($this->attributes))) {
80
                return $this->attributes[$name];
81
            }
82
83
        }
84
85
        throw new MethodNotFoundException("Method ".self::class.'::'.$method.'() is not supported');
86
    }
87
88
    /**
89
     * Magic getter
90
     * @param $name
91
     *
92
     * @return mixed|null
93
     */
94
    public function __get($name) {
95
        return $this->get($name);
96
    }
97
98
    /**
99
     * Get a specific header attribute
100
     * @param $name
101
     *
102
     * @return mixed|null
103
     */
104
    public function get($name) {
105
        if(isset($this->attributes[$name])) {
106
            return $this->attributes[$name];
107
        }
108
109
        return null;
110
    }
111
112
    /**
113
     * Perform a regex match all on the raw header and return the first result
114
     * @param $pattern
115
     *
116
     * @return mixed|null
117
     */
118
    public function find($pattern) {
119
        if (preg_match_all($pattern, $this->raw, $matches)) {
120
            if (isset($matches[1])) {
121
                if(count($matches[1]) > 0) {
122
                    return $matches[1][0];
123
                }
124
            }
125
        }
126
        return null;
127
    }
128
129
    /**
130
     * Parse the raw headers
131
     *
132
     * @throws InvalidMessageDateException
133
     */
134
    protected function parse(){
135
        $header = $this->rfc822_parse_headers($this->raw);
136
137
        $this->extractAddresses($header);
138
139
        if (property_exists($header, 'subject')) {
140
            $this->attributes["subject"] = $this->decode($header->subject);
141
        }
142
        if (property_exists($header, 'references')) {
143
            $this->attributes["references"] = $this->decode($header->references);
144
        }
145
        if (property_exists($header, 'message_id')) {
146
            $this->attributes["message_id"] = str_replace(['<', '>'], '', $header->message_id);
147
        }
148
149
        $this->parseDate($header);
150
        foreach ($header as $key => $value) {
151
            $key = trim(rtrim(strtolower($key)));
152
            if(!isset($this->attributes[$key])){
153
                $this->attributes[$key] = $value;
154
            }
155
        }
156
157
        $this->extractHeaderExtensions();
158
        $this->findPriority();
159
    }
160
161
    /**
162
     * Parse mail headers from a string
163
     * @link https://php.net/manual/en/function.imap-rfc822-parse-headers.php
164
     * @param $raw_headers
165
     *
166
     * @return object
167
     */
168
    public function rfc822_parse_headers($raw_headers){
169
        $headers = [];
170
        $imap_headers = [];
171
        if (extension_loaded('imap')) {
172
            $imap_headers = (array) \imap_rfc822_parse_headers($this->raw);
173
        }
174
175
        $lines = explode("\r\n", $raw_headers);
176
        $prev_header = null;
177
        foreach($lines as $line) {
178
            if (substr($line, 0, 1) === "\t") {
179
                $line = substr($line, 2);
180
                if ($prev_header !== null) {
181
                    $headers[$prev_header][] = $line;
182
                }
183
            }else{
184
                if (($pos = strpos($line, ":")) > 0) {
185
                    $key = strtolower(substr($line, 0, $pos));
186
                    $value = trim(rtrim(strtolower(substr($line, $pos + 1))));
187
                    $headers[$key] = [$value];
188
                    $prev_header = $key;
189
                }
190
            }
191
        }
192
193
        foreach($headers as $key => $values) {
194
            if (isset($imap_headers[$key])) continue;
195
            $value = null;
196
            switch($key){
197
                case 'from':
198
                case 'to':
199
                case 'cc':
200
                case 'bcc':
201
                case 'reply_to':
202
                case 'sender':
203
                    $value = $this->decodeAddresses($values);
204
                    $headers[$key."address"] = implode(", ", $values);
205
                    break;
206
                default:
207
                    $value = isset($values[0]) ? $values[0] : $value;
208
                    break;
209
            }
210
            $headers[$key] = $value;
211
        }
212
213
        return (object) array_merge($headers, $imap_headers);
214
    }
215
216
    /**
217
     * Decode MIME header elements
218
     * @link https://php.net/manual/en/function.imap-mime-header-decode.php
219
     * @param string $text The MIME text
220
     *
221
     * @return array The decoded elements are returned in an array of objects, where each
222
     * object has two properties, charset and text.
223
     */
224
    public function mime_header_decode($text){
225
        if (extension_loaded('imap')) {
226
            return \imap_mime_header_decode($text);
227
        }
228
        $charset = $this->getEncoding($text);
229
        return [(object)[
230
            "charset" => $charset,
231
            "text" => $this->convertEncoding($text, $charset)
232
        ]];
233
    }
234
235
    /**
236
     * Check if a given pair of strings has ben decoded
237
     * @param $encoded
238
     * @param $decoded
239
     *
240
     * @return bool
241
     */
242
    private function notDecoded($encoded, $decoded) {
243
        return 0 === strpos($decoded, '=?')
244
            && strlen($decoded) - 2 === strpos($decoded, '?=')
245
            && false !== strpos($encoded, $decoded);
246
    }
247
248
    /**
249
     * Convert the encoding
250
     * @param $str
251
     * @param string $from
252
     * @param string $to
253
     *
254
     * @return mixed|string
255
     */
256
    public function convertEncoding($str, $from = "ISO-8859-2", $to = "UTF-8") {
257
258
        $from = EncodingAliases::get($from, $this->fallback_encoding);
259
        $to = EncodingAliases::get($to, $this->fallback_encoding);
260
261
        if ($from === $to) {
262
            return $str;
263
        }
264
265
        // We don't need to do convertEncoding() if charset is ASCII (us-ascii):
266
        //     ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded
267
        //     https://stackoverflow.com/a/11303410
268
        //
269
        // us-ascii is the same as ASCII:
270
        //     ASCII is the traditional name for the encoding system; the Internet Assigned Numbers Authority (IANA)
271
        //     prefers the updated name US-ASCII, which clarifies that this system was developed in the US and
272
        //     based on the typographical symbols predominantly in use there.
273
        //     https://en.wikipedia.org/wiki/ASCII
274
        //
275
        // convertEncoding() function basically means convertToUtf8(), so when we convert ASCII string into UTF-8 it gets broken.
276
        if (strtolower($from) == 'us-ascii' && $to == 'UTF-8') {
277
            return $str;
278
        }
279
280
        try {
281
            if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') {
282
                return iconv($from, $to, $str);
283
            } else {
284
                if (!$from) {
285
                    return mb_convert_encoding($str, $to);
286
                }
287
                return mb_convert_encoding($str, $to, $from);
288
            }
289
        } catch (\Exception $e) {
290
            if (strstr($from, '-')) {
291
                $from = str_replace('-', '', $from);
292
                return $this->convertEncoding($str, $from, $to);
293
            } else {
294
                return $str;
295
            }
296
        }
297
    }
298
299
    /**
300
     * Get the encoding of a given abject
301
     * @param object|string $structure
302
     *
303
     * @return string
304
     */
305
    public function getEncoding($structure) {
306
        if (property_exists($structure, 'parameters')) {
307
            foreach ($structure->parameters as $parameter) {
308
                if (strtolower($parameter->attribute) == "charset") {
309
                    return EncodingAliases::get($parameter->value, $this->fallback_encoding);
310
                }
311
            }
312
        }elseif (property_exists($structure, 'charset')) {
313
            return EncodingAliases::get($structure->charset, $this->fallback_encoding);
314
        }elseif (is_string($structure) === true){
315
            return mb_detect_encoding($structure);
316
        }
317
318
        return $this->fallback_encoding;
319
    }
320
321
    /**
322
     * Try to decode a specific header
323
     * @param $value
324
     *
325
     * @return string|null
326
     */
327
    private function decode($value) {
328
        $original_value = $value;
329
        $decoder = $this->config['decoder']['message'];
330
331
        if ($value !== null) {
332
            if($decoder === 'utf-8' && extension_loaded('imap')) {
333
                $value = \imap_utf8($value);
334
                if (strpos(strtolower($value), '=?utf-8?') === 0) {
335
                    $value = mb_decode_mimeheader($value);
336
                }
337
                if ($this->notDecoded($original_value, $value)) {
338
                    $decoded_value = $this->mime_header_decode($value);
339
                    if (count($decoded_value) > 0) {
340
                        if(property_exists($decoded_value[0], "text")) {
341
                            $value = $decoded_value[0]->text;
342
                        }
343
                    }
344
                }
345
            }elseif($decoder === 'iconv') {
346
                $value = iconv_mime_decode($value);
347
            }else{
348
                $value = mb_decode_mimeheader($value);
349
            }
350
351
            if (strpos(strtolower($value), '=?utf-8?') === 0) {
352
                $value = mb_decode_mimeheader($value);
353
            }
354
355
            if ($this->notDecoded($original_value, $value)) {
356
                $value = $this->convertEncoding($original_value, $this->getEncoding($original_value));
357
            }
358
        }
359
360
        return $value;
361
    }
362
363
    /**
364
     * Try to extract the priority from a given raw header string
365
     */
366
    private function findPriority() {
367
        if(($priority = $this->get("x-priority")) === null) return;
368
        switch($priority){
369
            case IMAP::MESSAGE_PRIORITY_HIGHEST;
370
                $priority = IMAP::MESSAGE_PRIORITY_HIGHEST;
371
                break;
372
            case IMAP::MESSAGE_PRIORITY_HIGH;
373
                $priority = IMAP::MESSAGE_PRIORITY_HIGH;
374
                break;
375
            case IMAP::MESSAGE_PRIORITY_NORMAL;
376
                $priority = IMAP::MESSAGE_PRIORITY_NORMAL;
377
                break;
378
            case IMAP::MESSAGE_PRIORITY_LOW;
379
                $priority = IMAP::MESSAGE_PRIORITY_LOW;
380
                break;
381
            case IMAP::MESSAGE_PRIORITY_LOWEST;
382
                $priority = IMAP::MESSAGE_PRIORITY_LOWEST;
383
                break;
384
            default:
385
                $priority = IMAP::MESSAGE_PRIORITY_UNKNOWN;
386
                break;
387
        }
388
389
        $this->attributes["priority"] = $priority;
390
    }
391
392
    /**
393
     * Extract a given part as address array from a given header
394
     * @param $values
395
     *
396
     * @return array
397
     */
398
    private function decodeAddresses($values) {
399
        $addresses = [];
400
        foreach($values as $address) {
401
            if (preg_match(
402
                '/^(?:(?P<name>.+)\s)?(?(name)<|<?)(?P<email>[^\s]+?)(?(name)>|>?)$/',
403
                $address,
404
                $matches
405
            )){
406
                $name = trim(rtrim($matches["name"]));
407
                $email = trim(rtrim($matches["email"]));
408
                list($mailbox, $host) = explode("@", $email);
409
                $addresses[] = (object) [
410
                    "personal" => $name,
411
                    "mailbox" => $mailbox,
412
                    "host" => $host,
413
                ];
414
            }
415
        }
416
        return $addresses;
417
    }
418
419
    /**
420
     * Extract a given part as address array from a given header
421
     * @param object $header
422
     */
423
    private function extractAddresses($header) {
424
        foreach(['from', 'to', 'cc', 'bcc', 'reply_to', 'sender', 'in_reply_to'] as $key){
425
            if (property_exists($header, $key)) {
426
                $this->attributes[$key] = $this->parseAddresses($header->$key);
427
            }
428
        }
429
    }
430
431
    /**
432
     * Parse Addresses
433
     * @param $list
434
     *
435
     * @return array
436
     */
437
    private function parseAddresses($list) {
438
        $addresses = [];
439
440
        foreach ($list as $item) {
441
            $address = (object) $item;
442
443
            if (!property_exists($address, 'mailbox')) {
444
                $address->mailbox = false;
445
            }
446
            if (!property_exists($address, 'host')) {
447
                $address->host = false;
448
            }
449
            if (!property_exists($address, 'personal')) {
450
                $address->personal = false;
451
            } else {
452
                $personalParts = $this->mime_header_decode($address->personal);
453
454
                if(is_array($personalParts)) {
455
                    $address->personal = '';
456
                    foreach ($personalParts as $p) {
457
                        $address->personal .= $this->convertEncoding($p->text, $this->getEncoding($p));
458
                    }
459
                }
460
            }
461
462
            $address->mail = ($address->mailbox && $address->host) ? $address->mailbox.'@'.$address->host : false;
463
            $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

463
            $address->full = ($address->personal) ? $address->personal.' <'./** @scrutinizer ignore-type */ $address->mail.'>' : $address->mail;
Loading history...
464
465
            $addresses[] = $address;
466
        }
467
468
        return $addresses;
469
    }
470
471
    /**
472
     * Search and extract potential header extensions
473
     */
474
    private function extractHeaderExtensions(){
475
        foreach ($this->attributes as $key => $value) {
476
            if (is_string($value) === true) {
477
                if (($pos = strpos($value, ";")) !== false){
478
                    $original = substr($value, 0, $pos);
479
                    $this->attributes[$key] = trim(rtrim($original));
480
                    $extensions = explode(";", substr($value, $pos + 1));
481
                    foreach($extensions as $extension) {
482
                        if (($pos = strpos($extension, "=")) !== false){
483
                            $key = substr($extension, 0, $pos);
484
                            $value = substr($extension, $pos + 1);
485
                            $value = str_replace('"', "", $value);
486
                            $this->attributes[trim(rtrim(strtolower($key)))] = trim(rtrim($value));
487
                        }
488
                    }
489
                }
490
            }
491
        }
492
    }
493
494
    /**
495
     * Exception handling for invalid dates
496
     *
497
     * Currently known invalid formats:
498
     * ^ Datetime                                   ^ Problem                           ^ Cause
499
     * | Mon, 20 Nov 2017 20:31:31 +0800 (GMT+8:00) | Double timezone specification     | A Windows feature
500
     * | Thu, 8 Nov 2018 08:54:58 -0200 (-02)       |
501
     * |                                            | and invalid timezone (max 6 char) |
502
     * | 04 Jan 2018 10:12:47 UT                    | Missing letter "C"                | Unknown
503
     * | Thu, 31 May 2018 18:15:00 +0800 (added by) | Non-standard details added by the | Unknown
504
     * |                                            | mail server                       |
505
     * | Sat, 31 Aug 2013 20:08:23 +0580            | Invalid timezone                  | PHPMailer bug https://sourceforge.net/p/phpmailer/mailman/message/6132703/
506
     *
507
     * Please report any new invalid timestamps to [#45](https://github.com/Webklex/php-imap/issues)
508
     *
509
     * @param object $header
510
     *
511
     * @throws InvalidMessageDateException
512
     */
513
    private function parseDate($header) {
514
515
        if (property_exists($header, 'date')) {
516
            $parsed_date = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $parsed_date is dead and can be removed.
Loading history...
517
            $date = $header->date;
518
519
            if(preg_match('/\+0580/', $date)) {
520
                $date = str_replace('+0580', '+0530', $date);
521
            }
522
523
            $date = trim(rtrim($date));
524
            try {
525
                $parsed_date = Carbon::parse($date);
526
            } catch (\Exception $e) {
527
                switch (true) {
528
                    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:
529
                    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:
530
                        $date .= 'C';
531
                        break;
532
                    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:
533
                    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:
534
                    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:
535
                    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:
536
                    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:
537
                        $array = explode('(', $date);
538
                        $array = array_reverse($array);
539
                        $date = trim(array_pop($array));
540
                        break;
541
                }
542
                try{
543
                    $parsed_date = Carbon::parse($date);
544
                } catch (\Exception $_e) {
545
                    throw new InvalidMessageDateException("Invalid message date. ID:".$this->get("message_id"), 1100, $e);
546
                }
547
            }
548
549
            $this->attributes["date"] = $parsed_date;
550
        }
551
    }
552
553
    /**
554
     * Get all available attributes
555
     *
556
     * @return array
557
     */
558
    public function getAttributes() {
559
        return $this->attributes;
560
    }
561
562
}