|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpList\Core\Domain\Messaging\Service; |
| 6 | + |
| 7 | +use PhpList\Core\Domain\Subscription\Service\Manager\SubscriberManager; |
| 8 | + |
| 9 | +class MessageParser |
| 10 | +{ |
| 11 | + public function __construct( |
| 12 | + private readonly SubscriberManager $subscriberManager, |
| 13 | + ) { |
| 14 | + } |
| 15 | + public function decodeBody(string $header, string $body): string |
| 16 | + { |
| 17 | + $transferEncoding = ''; |
| 18 | + if (preg_match('/Content-Transfer-Encoding: ([\w-]+)/i', $header, $regs)) { |
| 19 | + $transferEncoding = strtolower($regs[1]); |
| 20 | + } |
| 21 | + |
| 22 | + return match ($transferEncoding) { |
| 23 | + 'quoted-printable' => quoted_printable_decode($body), |
| 24 | + 'base64' => base64_decode($body) ?: '', |
| 25 | + default => $body, |
| 26 | + }; |
| 27 | + } |
| 28 | + |
| 29 | + public function findMessageId(string $text): ?string |
| 30 | + { |
| 31 | + if (preg_match('/(?:X-MessageId|X-Message): (.*)\r\n/iU', $text, $match)) { |
| 32 | + return trim($match[1]); |
| 33 | + } |
| 34 | + |
| 35 | + return null; |
| 36 | + } |
| 37 | + |
| 38 | + public function findUserId(string $text): ?int |
| 39 | + { |
| 40 | + // Try X-ListMember / X-User first |
| 41 | + if (preg_match('/(?:X-ListMember|X-User): (.*)\r\n/iU', $text, $match)) { |
| 42 | + $user = trim($match[1]); |
| 43 | + if (str_contains($user, '@')) { |
| 44 | + return $this->subscriberManager->getSubscriberByEmail($user)?->getId(); |
| 45 | + } elseif (preg_match('/^\d+$/', $user)) { |
| 46 | + return (int)$user; |
| 47 | + } elseif ($user !== '') { |
| 48 | + return $this->subscriberManager->getSubscriberByEmail($user)?->getId(); |
| 49 | + } |
| 50 | + } |
| 51 | + // Fallback: parse any email in the body and see if it is a subscriber |
| 52 | + if (preg_match_all('/[._a-zA-Z0-9-]+@[.a-zA-Z0-9-]+/', $text, $regs)) { |
| 53 | + foreach ($regs[0] as $email) { |
| 54 | + $id = $this->subscriberManager->getSubscriberByEmail($email)?->getId(); |
| 55 | + if ($id) { |
| 56 | + return $id; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return null; |
| 62 | + } |
| 63 | +} |
0 commit comments