Debian Codegraph @

lib/3rdParty/composer/webklex/php-imap/src/Header.php

raw symbols SCIP
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\Decoder\DecoderInterface;
18 use Webklex\PHPIMAP\Exceptions\DecoderNotFoundException;
19 use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
20 use Webklex\PHPIMAP\Exceptions\MethodNotFoundException;
21 use Webklex\PHPIMAP\Exceptions\SpoofingAttemptDetectedException;
22
23 /**
24 * Class Header
25 *
26 * @package Webklex\PHPIMAP
27 */
28 class Header {
29
30 /**
31 * Raw header
32 *
33 * @var string $raw
34 */
35 public string $raw = "";
36
37 /**
38 * Attribute holder
39 *
40 * @var Attribute[]|array $attributes
41 */
42 protected array $attributes = [];
43
44 /**
45 * Config holder
46 *
47 * @var Config $config
48 */
49 protected Config $config;
50
51 /**
52 * Config holder
53 *
54 * @var array $options
55 */
56 protected array $options = [];
57
58 /**
59 * Decoder instance
60 *
61 * @var DecoderInterface $decoder
62 */
63 protected DecoderInterface $decoder;
64
65 /**
66 * Header constructor.
67 * @param Config $config
68 * @param string $raw_header
69 *
70 * @throws InvalidMessageDateException
71 * @throws DecoderNotFoundException
72 */
73 public function __construct(string $raw_header, Config $config) {
74 $this->decoder = $config->getDecoder("header");
75 $this->raw = $raw_header;
76 $this->config = $config;
77 $this->options = $this->config->get('options');
78 $this->parse();
79 }
80
81 /**
82 * Call dynamic attribute setter and getter methods
83 * @param string $method
84 * @param array $arguments
85 *
86 * @return Attribute|mixed
87 * @throws MethodNotFoundException
88 */
89 public function __call(string $method, array $arguments) {
90 if (strtolower(substr($method, 0, 3)) === 'get') {
91 $name = preg_replace('/(.)(?=[A-Z])/u', '$1_', substr(strtolower($method), 3));
92
93 if (in_array($name, array_keys($this->attributes))) {
94 return $this->attributes[$name];
95 }
96
97 }
98
99 throw new MethodNotFoundException("Method " . self::class . '::' . $method . '() is not supported');
100 }
101
102 /**
103 * Magic getter
104 * @param $name
105 *
106 * @return Attribute|null
107 */
108 public function __get($name) {
109 return $this->get($name);
110 }
111
112 /**
113 * Get a specific header attribute
114 * @param $name
115 *
116 * @return Attribute
117 */
118 public function get($name): Attribute {
119 $name = str_replace(["-", " "], "_", strtolower($name));
120 if (isset($this->attributes[$name])) {
121 return $this->attributes[$name];
122 }
123
124 return new Attribute($name);
125 }
126
127 /**
128 * Check if a specific attribute exists
129 * @param string $name
130 *
131 * @return bool
132 */
133 public function has(string $name): bool {
134 $name = str_replace(["-", " "], "_", strtolower($name));
135 return isset($this->attributes[$name]);
136 }
137
138 /**
139 * Set a specific attribute
140 * @param string $name
141 * @param array|mixed $value
142 * @param boolean $strict
143 *
144 * @return Attribute|array
145 */
146 public function set(string $name, mixed $value, bool $strict = false): Attribute|array {
147 if (isset($this->attributes[$name]) && $strict === false) {
148 $this->attributes[$name]->add($value, true);
149 } else {
150 $this->attributes[$name] = new Attribute($name, $value);
151 }
152
153 return $this->attributes[$name];
154 }
155
156 /**
157 * Perform a regex match all on the raw header and return the first result
158 * @param $pattern
159 *
160 * @return mixed|null
161 */
162 public function find($pattern): mixed {
163 if (preg_match_all($pattern, $this->raw, $matches)) {
164 if (isset($matches[1])) {
165 if (count($matches[1]) > 0) {
166 return $matches[1][0];
167 }
168 }
169 }
170 return null;
171 }
172
173 /**
174 * Try to find a boundary if possible
175 *
176 * @return string|null
177 */
178 public function getBoundary(): ?string {
179 $regex = $this->options["boundary"] ?? "/boundary=(.*?(?=;)|(.*))/i";
180 $boundary = $this->find($regex);
181
182 if ($boundary === null) {
183 return null;
184 }
185
186 return $this->clearBoundaryString($boundary);
187 }
188
189 /**
190 * Remove all unwanted chars from a given boundary
191 * @param string $str
192 *
193 * @return string
194 */
195 private function clearBoundaryString(string $str): string {
196 return str_replace(['"', '\r', '\n', "\n", "\r", ";", "\s"], "", $str);
197 }
198
199 /**
200 * Parse the raw headers
201 *
202 * @throws InvalidMessageDateException
203 * @throws SpoofingAttemptDetectedException
204 */
205 protected function parse(): void {
206 $header = $this->rfc822_parse_headers($this->raw);
207
208 $this->extractAddresses($header);
209
210 if (property_exists($header, 'subject')) {
211 $this->set("subject", $this->decoder->decode($header->subject));
212 }
213 if (property_exists($header, 'references')) {
214 $this->set("references", array_map(function($item) {
215 return str_replace(['<', '>'], '', $item);
216 }, explode(" ", $header->references)));
217 }
218 if (property_exists($header, 'message_id')) {
219 $this->set("message_id", str_replace(['<', '>'], '', $header->message_id));
220 }
221 if (property_exists($header, 'in_reply_to')) {
222 $this->set("in_reply_to", str_replace(['<', '>'], '', $header->in_reply_to));
223 }
224
225 $this->parseDate($header);
226 foreach ($header as $key => $value) {
227 $key = trim(rtrim(strtolower($key)));
228 if (!isset($this->attributes[$key])) {
229 $this->set($key, $value);
230 }
231 }
232
233 $this->extractHeaderExtensions();
234 $this->findPriority();
235
236 if($this->config->get('security.detect_spoofing', true)) {
237 // Detect spoofing
238 $this->detectSpoofing();
239 }
240 }
241
242 /**
243 * Parse mail headers from a string
244 * @link https://php.net/manual/en/function.imap-rfc822-parse-headers.php
245 * @param $raw_headers
246 *
247 * @return object
248 */
249 public function rfc822_parse_headers($raw_headers): object {
250 $headers = [];
251 $imap_headers = [];
252 if (extension_loaded('imap') && $this->options["rfc822"]) {
253 $raw_imap_headers = (array)\imap_rfc822_parse_headers($raw_headers);
254 foreach ($raw_imap_headers as $key => $values) {
255 $key = strtolower(str_replace("-", "_", $key));
256 $imap_headers[$key] = $values;
257 }
258 }
259 $lines = explode("\r\n", preg_replace("/\r\n\s/", ' ', $raw_headers));
260 $prev_header = null;
261 foreach ($lines as $line) {
262 if (str_starts_with($line, "\n")) {
263 $line = substr($line, 1);
264 }
265
266 if (str_starts_with($line, "\t")) {
267 $line = substr($line, 1);
268 $line = trim(rtrim($line));
269 if ($prev_header !== null) {
270 $headers[$prev_header][] = $line;
271 }
272 } elseif (str_starts_with($line, " ")) {
273 $line = substr($line, 1);
274 $line = trim(rtrim($line));
275 if ($prev_header !== null) {
276 if (!isset($headers[$prev_header])) {
277 $headers[$prev_header] = "";
278 }
279 if (is_array($headers[$prev_header])) {
280 $headers[$prev_header][] = $line;
281 } else {
282 $headers[$prev_header] .= $line;
283 }
284 }
285 } else {
286 if (($pos = strpos($line, ":")) > 0) {
287 $key = trim(rtrim(strtolower(substr($line, 0, $pos))));
288 $key = strtolower(str_replace("-", "_", $key));
289
290 $value = trim(rtrim(substr($line, $pos + 1)));
291 if (isset($headers[$key])) {
292 $headers[$key][] = $value;
293 } else {
294 $headers[$key] = [$value];
295 }
296 $prev_header = $key;
297 }
298 }
299 }
300
301 foreach ($headers as $key => $values) {
302 if (isset($imap_headers[$key])) {
303 continue;
304 }
305 $value = null;
306 switch ((string)$key) {
307 case 'from':
308 case 'to':
309 case 'cc':
310 case 'bcc':
311 case 'reply_to':
312 case 'sender':
313 $value = $this->decodeAddresses($values);
314 $headers[$key . "address"] = implode(", ", $values);
315 break;
316 case 'subject':
317 $value = implode(" ", $values);
318 break;
319 default:
320 if (is_array($values)) {
321 foreach ($values as $k => $v) {
322 if ($v == "") {
323 unset($values[$k]);
324 }
325 }
326 $available_values = count($values);
327 if ($available_values === 1) {
328 $value = array_pop($values);
329 } elseif ($available_values === 2) {
330 $value = implode(" ", $values);
331 } elseif ($available_values > 2) {
332 $value = array_values($values);
333 } else {
334 $value = "";
335 }
336 }
337 break;
338 }
339 $headers[$key] = $value;
340 }
341
342 return (object)array_merge($headers, $imap_headers);
343 }
344
345 /**
346 * Try to extract the priority from a given raw header string
347 */
348 private function findPriority(): void {
349 $priority = $this->get("x_priority");
350
351 $priority = match ((int)"$priority") {
352 IMAP::MESSAGE_PRIORITY_HIGHEST => IMAP::MESSAGE_PRIORITY_HIGHEST,
353 IMAP::MESSAGE_PRIORITY_HIGH => IMAP::MESSAGE_PRIORITY_HIGH,
354 IMAP::MESSAGE_PRIORITY_NORMAL => IMAP::MESSAGE_PRIORITY_NORMAL,
355 IMAP::MESSAGE_PRIORITY_LOW => IMAP::MESSAGE_PRIORITY_LOW,
356 IMAP::MESSAGE_PRIORITY_LOWEST => IMAP::MESSAGE_PRIORITY_LOWEST,
357 default => IMAP::MESSAGE_PRIORITY_UNKNOWN,
358 };
359
360 $this->set("priority", $priority);
361 }
362
363 /**
364 * Extract a given part as address array from a given header
365 * @param $values
366 *
367 * @return array
368 */
369 private function decodeAddresses($values): array {
370 $addresses = [];
371
372 if (extension_loaded('mailparse') && $this->options["rfc822"]) {
373 foreach ($values as $address) {
374 foreach (\mailparse_rfc822_parse_addresses($address) as $parsed_address) {
375 if (isset($parsed_address['address'])) {
376 $mail_address = explode('@', $parsed_address['address']);
377 if (count($mail_address) == 2) {
378 $addresses[] = (object)[
379 "personal" => $parsed_address['display'] ?? '',
380 "mailbox" => $mail_address[0],
381 "host" => $mail_address[1],
382 ];
383 }
384 }
385 }
386 }
387
388 return $addresses;
389 }
390
391 foreach ($values as $address) {
392 foreach (preg_split('/, ?(?=(?:[^"]*"[^"]*")*[^"]*$)/', $address) as $split_address) {
393 $split_address = trim(rtrim($split_address));
394
395 if (strpos($split_address, ",") == strlen($split_address) - 1) {
396 $split_address = substr($split_address, 0, -1);
397 }
398 if (preg_match(
399 '/^(?:(?P<name>.+)\s)?(?(name)<|<?)(?P<email>[^\s]+?)(?(name)>|>?)$/',
400 $split_address,
401 $matches
402 )) {
403 $name = trim(rtrim($matches["name"]));
404 $email = trim(rtrim($matches["email"]));
405 list($mailbox, $host) = array_pad(explode("@", $email), 2, null);
406 $addresses[] = (object)[
407 "personal" => $name,
408 "mailbox" => $mailbox,
409 "host" => $host,
410 ];
411 }elseif (preg_match(
412 '/^((?P<name>.+)<)(?P<email>[^<]+?)>$/',
413 $split_address,
414 $matches
415 )) {
416 $name = trim(rtrim($matches["name"]));
417 if(str_starts_with($name, "\"") && str_ends_with($name, "\"")) {
418 $name = substr($name, 1, -1);
419 }elseif(str_starts_with($name, "'") && str_ends_with($name, "'")) {
420 $name = substr($name, 1, -1);
421 }
422 $email = trim(rtrim($matches["email"]));
423 list($mailbox, $host) = array_pad(explode("@", $email), 2, null);
424 $addresses[] = (object)[
425 "personal" => $name,
426 "mailbox" => $mailbox,
427 "host" => $host,
428 ];
429 }
430 }
431 }
432
433 return $addresses;
434 }
435
436 /**
437 * Extract a given part as address array from a given header
438 * @param object $header
439 */
440 private function extractAddresses(object $header): void {
441 foreach (['from', 'to', 'cc', 'bcc', 'reply_to', 'sender', 'return_path', 'envelope_from', 'envelope_to', 'delivered_to'] as $key) {
442 if (property_exists($header, $key)) {
443 $this->set($key, $this->parseAddresses($header->$key));
444 }
445 }
446 }
447
448 /**
449 * Parse Addresses
450 * @param $list
451 *
452 * @return array
453 */
454 private function parseAddresses($list): array {
455 $addresses = [];
456
457 if (is_array($list) === false) {
458 if(is_string($list)) {
459 if (preg_match(
460 '/^(?:(?P<name>.+)\s)?(?(name)<|<?)(?P<email>[^\s]+?)(?(name)>|>?)$/',
461 $list,
462 $matches
463 )) {
464 $name = trim(rtrim($matches["name"]));
465 $email = trim(rtrim($matches["email"]));
466 list($mailbox, $host) = array_pad(explode("@", $email), 2, null);
467 if($mailbox === ">") { // Fix trailing ">" in malformed mailboxes
468 $mailbox = "";
469 }
470 if($name === "" && $mailbox === "" && $host === "") {
471 return $addresses;
472 }
473 $list = [
474 (object)[
475 "personal" => $name,
476 "mailbox" => $mailbox,
477 "host" => $host,
478 ]
479 ];
480 }elseif (preg_match(
481 '/^((?P<name>.+)<)(?P<email>[^<]+?)>$/',
482 $list,
483 $matches
484 )) {
485 $name = trim(rtrim($matches["name"]));
486 $email = trim(rtrim($matches["email"]));
487 if(str_starts_with($name, "\"") && str_ends_with($name, "\"")) {
488 $name = substr($name, 1, -1);
489 }elseif(str_starts_with($name, "'") && str_ends_with($name, "'")) {
490 $name = substr($name, 1, -1);
491 }
492 list($mailbox, $host) = array_pad(explode("@", $email), 2, null);
493 if($mailbox === ">") { // Fix trailing ">" in malformed mailboxes
494 $mailbox = "";
495 }
496 if($name === "" && $mailbox === "" && $host === "") {
497 return $addresses;
498 }
499 $list = [
500 (object)[
501 "personal" => $name,
502 "mailbox" => $mailbox,
503 "host" => $host,
504 ]
505 ];
506 }else{
507 return $addresses;
508 }
509 }else{
510 return $addresses;
511 }
512 }
513
514 foreach ($list as $item) {
515 $address = (object)$item;
516
517 if (!property_exists($address, 'mailbox')) {
518 $address->mailbox = false;
519 }
520 if (!property_exists($address, 'host')) {
521 $address->host = false;
522 }
523 if (!property_exists($address, 'personal')) {
524 $address->personal = false;
525 } else {
526 $personal_slices = explode(" ", $address->personal);
527 $address->personal = "";
528 foreach ($personal_slices as $slice) {
529 $personalParts = $this->decoder->mimeHeaderDecode($slice);
530
531 $personal = '';
532 foreach ($personalParts as $p) {
533 $personal .= $this->decoder->convertEncoding($p->text, $this->decoder->getEncoding($p));
534 }
535
536 if (str_starts_with($personal, "'")) {
537 $personal = str_replace("'", "", $personal);
538 }
539 $personal = $this->decoder->decode($personal);
540 $address->personal .= $personal . " ";
541 }
542 $address->personal = trim(rtrim($address->personal));
543 }
544
545 if ($address->host == ".SYNTAX-ERROR.") {
546 $address->host = "";
547 }elseif ($address->host == "UNKNOWN") {
548 $address->host = "";
549 }
550 if ($address->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS") {
551 $address->mailbox = "";
552 }elseif ($address->mailbox == "MISSING_MAILBOX_TERMINATOR") {
553 $address->mailbox = "";
554 }
555
556 $addresses[] = new Address($address);
557 }
558
559 return $addresses;
560 }
561
562 /**
563 * Search and extract potential header extensions
564 */
565 private function extractHeaderExtensions(): void {
566 foreach ($this->attributes as $key => $value) {
567 if (is_array($value)) {
568 $value = implode(", ", $value);
569 } else {
570 $value = (string)$value;
571 }
572 // Only parse strings and don't parse any attributes like the user-agent
573 if (!in_array($key, ["user-agent", "subject", "received"])) {
574 if (str_contains($value, ";") && str_contains($value, "=")) {
575 $_attributes = $this->read_attribute($value);
576 foreach($_attributes as $_key => $_value) {
577 if($_value === "") {
578 $this->set($key, $_key);
579 }
580 if (!isset($this->attributes[$_key])) {
581 $this->set($_key, $_value);
582 }
583 }
584 }
585 }
586 }
587 }
588
589 /**
590 * Read a given attribute string
591 * - this isn't pretty, but it works - feel free to improve :)
592 * @param string $raw_attribute
593 * @return array
594 */
595 private function read_attribute(string $raw_attribute): array {
596 $attributes = [];
597 $key = '';
598 $value = '';
599 $inside_word = false;
600 $inside_key = true;
601 $escaped = false;
602 foreach (str_split($raw_attribute) as $char) {
603 if($escaped) {
604 $escaped = false;
605 continue;
606 }
607 if($inside_word) {
608 if($char === '\\') {
609 $escaped = true;
610 }elseif($char === "\"" && $value !== "") {
611 $inside_word = false;
612 }else{
613 $value .= $char;
614 }
615 }else{
616 if($inside_key) {
617 if($char === '"') {
618 $inside_word = true;
619 }elseif($char === ';'){
620 $attributes[$key] = $value;
621 $key = '';
622 $value = '';
623 $inside_key = true;
624 }elseif($char === '=') {
625 $inside_key = false;
626 }else{
627 $key .= $char;
628 }
629 }else{
630 if($char === '"' && $value === "") {
631 $inside_word = true;
632 }elseif($char === ';'){
633 $attributes[$key] = $value;
634 $key = '';
635 $value = '';
636 $inside_key = true;
637 }else{
638 $value .= $char;
639 }
640 }
641 }
642 }
643 $attributes[$key] = $value;
644 $result = [];
645
646 foreach($attributes as $key => $value) {
647 if (($pos = strpos($key, "*")) !== false) {
648 $key = substr($key, 0, $pos);
649 }
650 $key = trim(rtrim(strtolower($key)));
651
652 if(!isset($result[$key])) {
653 $result[$key] = "";
654 }
655 $value = trim(rtrim(str_replace(["\r", "\n"], "", $value)));
656 if(str_starts_with($value, "\"") && str_ends_with($value, "\"")) {
657 $value = substr($value, 1, -1);
658 }
659 $result[$key] .= $value;
660 }
661 return $result;
662 }
663
664 /**
665 * Exception handling for invalid dates
666 *
667 * Known bad and "invalid" formats:
668 * ^ Datetime ^ Problem ^ Cause
669 * | Mon, 20 Nov 2017 20:31:31 +0800 (GMT+8:00) | Double timezone specification | A Windows feature
670 * | Thu, 8 Nov 2018 08:54:58 -0200 (-02) |
671 * | | and invalid timezone (max 6 char) |
672 * | 04 Jan 2018 10:12:47 UT | Missing letter "C" | Unknown
673 * | Thu, 31 May 2018 18:15:00 +0800 (added by) | Non-standard details added by the | Unknown
674 * | | mail server |
675 * | Sat, 31 Aug 2013 20:08:23 +0580 | Invalid timezone | PHPMailer bug https://sourceforge.net/p/phpmailer/mailman/message/6132703/
676 * | Mi., 23 Apr. 2025 09:48:37 +0200 (MESZ) | Non-standard localized format | Aqua Mail S/MIME implementation
677 *
678 * Please report any new invalid timestamps to [#45](https://github.com/Webklex/php-imap/issues)
679 *
680 * @param object $header
681 *
682 * @throws InvalidMessageDateException
683 */
684 private function parseDate(object $header): void {
685
686 if (property_exists($header, 'date')) {
687 $date = $header->date;
688
689 if (preg_match('/\+0580/', $date)) {
690 $date = str_replace('+0580', '+0530', $date);
691 }
692
693 $date = trim(rtrim($date));
694 try {
695 if (str_contains($date, '&nbsp;')) {
696 $date = str_replace('&nbsp;', ' ', $date);
697 }
698 if (str_contains($date, ' UT ')) {
699 $date = str_replace(' UT ', ' UTC ', $date);
700 }
701 $parsed_date = Carbon::parse($date);
702 } catch (\Exception $e) {
703 switch (true) {
704 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:
705 $date = Carbon::createFromFormat("Y.m.d-H.i.s", $date);
706 break;
707 case preg_match('/([0-9]{2} [A-Z]{3} [0-9]{4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} [+-][0-9]{1,4} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} [+-][0-9]{1,4})+$/i', $date) > 0:
708 $parts = explode(' ', $date);
709 array_splice($parts, -2);
710 $date = implode(' ', $parts);
711 break;
712 case preg_match('/([A-Z]{2,4}\,\ [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:
713 $array = explode(',', $date);
714 array_shift($array);
715 $date = Carbon::createFromFormat("d M Y H:i:s O", trim(implode(',', $array)));
716 break;
717 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:
718 case preg_match('/([A-Z]{2,3}\,\ [0-9]{1,2}\ [A-Z]{2,3}\ ([0-9]{2}|[0-9]{4})\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ UT)+$/i', $date) > 0:
719 $date .= 'C';
720 break;
721 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:
722 $date = str_replace(',', '', $date);
723 break;
724 // match case for: Di., 15 Feb. 2022 06:52:44 +0100 (MEZ)/Di., 15 Feb. 2022 06:52:44 +0100 (MEZ) and Mi., 23 Apr. 2025 09:48:37 +0200 (MESZ)
725 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}\ \([A-Z]{3,4}\))(\/([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}\ \([A-Z]{3,4}\))+)?$/i', $date) > 0:
726 $dates = explode('/', $date);
727 $date = array_shift($dates);
728 $array = explode(',', $date);
729 array_shift($array);
730 $date = trim(implode(',', $array));
731 $array = explode(' ', $date);
732 array_pop($array);
733 $date = trim(implode(' ', $array));
734 $date = Carbon::createFromFormat("d M. Y H:i:s O", $date);
735 break;
736 // match case for: fr., 25 nov. 2022 06:27:14 +0100/fr., 25 nov. 2022 06:27:14 +0100
737 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})\/([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:
738 $dates = explode('/', $date);
739 $date = array_shift($dates);
740 $array = explode(',', $date);
741 array_shift($array);
742 $date = trim(implode(',', $array));
743 $date = Carbon::createFromFormat("d M. Y H:i:s O", $date);
744 break;
745 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:
746 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:
747 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:
748 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:
749 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:
750 $array = explode('(', $date);
751 $array = array_reverse($array);
752 $date = trim(array_pop($array));
753 break;
754 }
755 try {
756 $parsed_date = Carbon::parse($date);
757 } catch (\Exception $_e) {
758 if (!isset($this->options["fallback_date"])) {
759 throw new InvalidMessageDateException("Invalid message date. ID:" . $this->get("message_id") . " Date:" . $header->date . "/" . $date, 1100, $e);
760 } else {
761 $parsed_date = Carbon::parse($this->options["fallback_date"]);
762 }
763 }
764 }
765
766 $this->set("date", $parsed_date);
767 }
768 }
769
770 /**
771 * Get all available attributes
772 *
773 * @return array
774 */
775 public function getAttributes(): array {
776 return $this->attributes;
777 }
778
779 /**
780 * Set all header attributes
781 * @param array $attributes
782 *
783 * @return Header
784 */
785 public function setAttributes(array $attributes): Header {
786 $this->attributes = $attributes;
787 return $this;
788 }
789
790 /**
791 * Set the configuration used for parsing a raw header
792 * @param array $config
793 *
794 * @return Header
795 */
796 public function setOptions(array $config): Header {
797 $this->options = $config;
798 return $this;
799 }
800
801 /**
802 * Get the configuration used for parsing a raw header
803 *
804 * @return array
805 */
806 public function getOptions(): array {
807 return $this->options;
808 }
809
810 /**
811 * Set the configuration used for parsing a raw header
812 * @param Config $config
813 *
814 * @return Header
815 */
816 public function setConfig(Config $config): Header {
817 $this->config = $config;
818 return $this;
819 }
820
821 /**
822 * Get the configuration used for parsing a raw header
823 *
824 * @return Config
825 */
826 public function getConfig(): Config {
827 return $this->config;
828 }
829
830 /**
831 * Get the decoder instance
832 *
833 * @return DecoderInterface
834 */
835 public function getDecoder(): DecoderInterface {
836 return $this->decoder;
837 }
838
839 /**
840 * Set the decoder instance
841 * @param DecoderInterface $decoder
842 *
843 * @return $this
844 */
845 public function setDecoder(DecoderInterface $decoder): static {
846 $this->decoder = $decoder;
847 return $this;
848 }
849
850 /**
851 * Detect spoofing by checking the from, reply_to, return_path, sender and envelope_from headers
852 * @throws SpoofingAttemptDetectedException
853 */
854 private function detectSpoofing(): void {
855 $header_keys = ["from", "reply_to", "return_path", "sender", "envelope_from"];
856 $potential_senders = [];
857 foreach($header_keys as $key) {
858 $header = $this->get($key);
859 foreach ($header->toArray() as $address) {
860 $potential_senders[] = $address->mailbox . "@" . $address->host;
861 }
862 }
863 if(count($potential_senders) > 1) {
864 $this->set("spoofed", true);
865 if($this->config->get('security.detect_spoofing_exception', false)) {
866 throw new SpoofingAttemptDetectedException("Potential spoofing detected. Message ID: " . $this->get("message_id") . " Senders: " . implode(", ", $potential_senders));
867 }
868 }
869 }
870
871 }