Files
fewo-stommer/app/Channels/Mail/MailboxReader.php
T
LarsandClaude Opus 5.5 3a039e5c50
Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m10s
v0.11: Angebot wartet sichtbar auf Pflichtangaben; Postfach prüfen; Eingangsmails am Vorgang
- Vorgang: „Angebot prüfen und senden“ wird erst angeboten, wenn alle
  Pflichtangaben da sind („erst wenn alle Angaben da sind“); ebenso wartet
  „Buchungswunsch bestätigen?“. Die harte Sperre in SendOffer, AutoOffer
  und DecideBookingWish bestand bereits; jetzt stimmt auch die Anzeige.
- System › Betrieb: „Postfach prüfen“ (Verbindung, Anzahl Nachrichten der
  letzten Tage, nichts wird gelesen oder markiert) und Stand des Abrufs.
- Posteingang zeigt letzten erfolgreichen Abruf und letzten Fehler.
- Vorgang: neuer Bereich „Eingegangene E-Mails“ mit Lesen und Erkanntem;
  „Mailverlauf“ heißt jetzt „Gesendete E-Mails“.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:03:11 +01:00

195 lines
7.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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\ClientManager;
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 = $client->getFolderByPath($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 = $client->getFolderByPath($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 = $client->getFolderByPath($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;
}
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,
);
}
}