- MailboxReader::folder(): „Posteingang“, „Inbox“ oder leer → INBOX (so heißt der Posteingang auf dem IMAP-Server); andere Namen ohne Beachtung der Groß-/Kleinschreibung; unbekannter Ordner → Meldung mit den vorhandenen Ordnern statt „Call to a member function query() on null“. Gilt für Portal-Abruf, vollständigen Abruf und „Postfach prüfen“. - Verschlüsselung: Platzhalter „Standard (SSL)“ statt eines zweiten „SSL“; Hinweis am Ordnerfeld. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
219 lines
8.3 KiB
PHP
219 lines
8.3 KiB
PHP
<?php
|
||
|
||
namespace App\Channels\Mail;
|
||
|
||
use App\Channels\ChannelSyncException;
|
||
use App\Support\Settings;
|
||
use Carbon\CarbonImmutable;
|
||
use Illuminate\Support\Facades\Cache;
|
||
use Throwable;
|
||
use Webklex\PHPIMAP\Client;
|
||
use Webklex\PHPIMAP\ClientManager;
|
||
use Webklex\PHPIMAP\Folder;
|
||
use Webklex\PHPIMAP\Message;
|
||
|
||
/**
|
||
* Reads recent e-mails of the given senders from the configured IMAP mailbox without marking them as read.
|
||
* Works without the PHP imap extension.
|
||
*/
|
||
class MailboxReader
|
||
{
|
||
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
|
||
|
||
/**
|
||
* The state of one landlord's mailbox. Without the landlord in the key, two landlords would report
|
||
* each other's last success and alerts would be raised for the wrong one.
|
||
*/
|
||
public static function key(string $base): string
|
||
{
|
||
return $base.':'.(Settings::tenant()?->id ?? 0);
|
||
}
|
||
|
||
public const LAST_ERROR_KEY = 'mailbox:last_error';
|
||
|
||
/**
|
||
* The mailbox of the current landlord. Each landlord reads their own; an empty one means the fast path
|
||
* is off for them.
|
||
*
|
||
* @return array<string, mixed>|null
|
||
*/
|
||
public static function configuration(): ?array
|
||
{
|
||
return Settings::tenant()?->mailbox();
|
||
}
|
||
|
||
public static function isConfigured(): bool
|
||
{
|
||
return self::configuration() !== null;
|
||
}
|
||
|
||
/**
|
||
* @param list<string> $senders addresses or domains
|
||
* @return list<PortalMail>
|
||
*
|
||
* @throws ChannelSyncException
|
||
*/
|
||
public function fetch(array $senders): array
|
||
{
|
||
$config = self::configuration();
|
||
|
||
if ($config === null) {
|
||
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
|
||
}
|
||
|
||
try {
|
||
$client = (new ClientManager)->make([
|
||
'host' => $config['host'],
|
||
'port' => $config['port'],
|
||
'encryption' => $config['encryption'],
|
||
'validate_cert' => true,
|
||
'username' => $config['username'],
|
||
'password' => $config['password'],
|
||
'protocol' => 'imap',
|
||
]);
|
||
$client->connect();
|
||
$folder = self::folder($client, $config['folder']);
|
||
|
||
$mails = [];
|
||
foreach ($senders as $sender) {
|
||
$messages = $folder->query()
|
||
->whereSince(CarbonImmutable::today()->subDays($config['lookback_days']))
|
||
->whereFrom($sender)
|
||
->leaveUnread()
|
||
->get();
|
||
|
||
foreach ($messages as $message) {
|
||
$mails[] = $this->toPortalMail($message);
|
||
}
|
||
}
|
||
|
||
$client->disconnect();
|
||
} catch (Throwable $exception) {
|
||
Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage());
|
||
|
||
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
|
||
}
|
||
|
||
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
|
||
Cache::forget(self::key(self::LAST_ERROR_KEY));
|
||
|
||
return $mails;
|
||
}
|
||
|
||
/**
|
||
* Every message of the last days (v0.11 inbox, mailbox mode "full"), left unread. Deduplication happens when the
|
||
* messages are stored.
|
||
*
|
||
* @return list<PortalMail>
|
||
*
|
||
* @throws ChannelSyncException
|
||
*/
|
||
public function fetchAll(): array
|
||
{
|
||
$config = self::configuration();
|
||
if ($config === null) {
|
||
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
|
||
}
|
||
|
||
try {
|
||
$client = (new ClientManager)->make([
|
||
'host' => $config['host'], 'port' => $config['port'], 'encryption' => $config['encryption'], 'validate_cert' => true,
|
||
'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap',
|
||
]);
|
||
$client->connect();
|
||
$messages = self::folder($client, $config['folder'])->query()
|
||
->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3)))
|
||
->leaveUnread()
|
||
->get();
|
||
$mails = [];
|
||
foreach ($messages as $message) {
|
||
$mails[] = $this->toPortalMail($message);
|
||
}
|
||
$client->disconnect();
|
||
} catch (Throwable $exception) {
|
||
Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage());
|
||
|
||
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
|
||
}
|
||
|
||
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
|
||
Cache::forget(self::key(self::LAST_ERROR_KEY));
|
||
|
||
return $mails;
|
||
}
|
||
|
||
/**
|
||
* Connects with the given connection data and counts the messages of the last days (check on System › Betrieb).
|
||
* Nothing is read, marked or stored.
|
||
*
|
||
* @param array{host: string, port: int, encryption: string, username: string, password: ?string, folder: string} $config
|
||
*
|
||
* @throws ChannelSyncException
|
||
*/
|
||
public function probe(array $config): int
|
||
{
|
||
try {
|
||
$client = (new ClientManager)->make([
|
||
'host' => $config['host'], 'port' => $config['port'], 'encryption' => $config['encryption'], 'validate_cert' => true,
|
||
'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap',
|
||
]);
|
||
$client->connect();
|
||
$count = self::folder($client, $config['folder'])->query()
|
||
->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3)))
|
||
->leaveUnread()->setFetchBody(false)->count();
|
||
$client->disconnect();
|
||
} catch (Throwable $exception) {
|
||
throw new ChannelSyncException('Postfach nicht erreichbar: '.$exception->getMessage(), previous: $exception);
|
||
}
|
||
|
||
return (int) $count;
|
||
}
|
||
|
||
/**
|
||
* The folder to read. The inbox is called "INBOX" on the IMAP server, whatever the provider's web mail shows
|
||
* ("Posteingang", "Inbox"); other names match regardless of case. An unknown name names the existing folders.
|
||
*
|
||
* @throws ChannelSyncException
|
||
*/
|
||
public static function folder(Client $client, ?string $name): Folder
|
||
{
|
||
$name = trim((string) $name);
|
||
$wanted = $name === '' || in_array(mb_strtolower($name), ['inbox', 'posteingang'], true) ? 'INBOX' : $name;
|
||
|
||
$folders = $client->getFolders(false);
|
||
$folder = $folders->first(fn (Folder $folder): bool => $folder->path === $wanted)
|
||
?? $folders->first(fn (Folder $folder): bool => mb_strtolower($folder->path) === mb_strtolower($wanted) || mb_strtolower($folder->name) === mb_strtolower($wanted));
|
||
|
||
if ($folder === null) {
|
||
throw new ChannelSyncException('Ordner „'.$name.'“ gibt es in diesem Postfach nicht. Vorhanden: '.$folders->map(fn (Folder $folder): string => $folder->path)->implode(', ').' (der Posteingang heißt „INBOX“).');
|
||
}
|
||
|
||
return $folder;
|
||
}
|
||
|
||
private function toPortalMail(Message $message): PortalMail
|
||
{
|
||
$text = $message->getTextBody();
|
||
if (trim($text) === '') {
|
||
$text = strip_tags(preg_replace('#<(br|p|div|tr|li)[^>]*>#i', "\n", $message->getHTMLBody()));
|
||
}
|
||
|
||
$from = $message->getFrom()->first();
|
||
$date = $message->getDate()->first();
|
||
|
||
$references = preg_split('/\s+/', trim((string) $message->getReferences()?->first())) ?: [];
|
||
|
||
return new PortalMail(
|
||
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
|
||
from: (string) ($from->mail ?? ''),
|
||
subject: (string) $message->getSubject()->first(),
|
||
text: $text,
|
||
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
|
||
inReplyTo: ($reply = trim((string) $message->getInReplyTo()?->first())) !== '' ? $reply : null,
|
||
references: array_values(array_filter($references)),
|
||
to: collect($message->getTo()?->all() ?? [])->map(fn ($address): string => mb_strtolower((string) ($address->mail ?? '')))->filter()->values()->all(),
|
||
fromName: filled($from->personal ?? null) ? (string) $from->personal : null,
|
||
);
|
||
}
|
||
}
|