rpg-westreiche/westreiche_website/app/mailer.php

393 lines
14 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
declare(strict_types=1);
/**
* Westreiche – minimaler SMTP-Client (ohne Composer, ohne externe Dienste).
*
* Verschickt reine Text-Mails über den Hetzner-Mailserver: STARTTLS auf Port
* 587 oder SSL auf 465, Anmeldung per AUTH PLAIN/LOGIN. Konfiguriert wird der
* Abschnitt 'mail' in app/config.local.php; die Werte stammen aus MAIL_* in
* credentials.txt (siehe tools/deploy_app.sh).
*
* Ist dort nichts hinterlegt, gilt der Versand als nicht eingerichtet:
* mail_ready() liefert false, die App zeigt den Einladungslink wie bisher zum
* Kopieren an.
*/
/** SMTP-Mindestclient: EHLO/STARTTLS/AUTH/DATA, alles andere übernimmt der Aufrufer. */
final class WsSmtp
{
/** @var resource|null */
private $socket = null;
/** @var array<string,string> */
private array $features = [];
private string $lastError = '';
public function __construct(
private string $host,
private int $port,
private string $secure,
private float $timeout = 15.0,
) {
}
public function connect(): void
{
$socket = $this->open($this->host);
if ($socket === false) {
// Manche Netze haben kein IPv6, der Name liefert aber eine AAAA-Adresse:
// zweiter Versuch über die IPv4-Adresse, Zertifikat bleibt an den Namen gebunden.
$ipv4 = gethostbyname($this->host);
if ($ipv4 !== $this->host && filter_var($ipv4, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
$socket = $this->open($ipv4);
}
}
if ($socket === false) {
throw new RuntimeException(sprintf('SMTP-Verbindung zu %s:%d fehlgeschlagen (%s)', $this->host, $this->port, $this->lastError !== '' ? $this->lastError : 'Grund unbekannt'));
}
stream_set_timeout($socket, (int) max(1, (int) ceil($this->timeout)));
$this->socket = $socket;
$this->expect(220);
$this->ehlo();
if ($this->secure === 'tls') {
if (!array_key_exists('starttls', $this->features)) {
throw new RuntimeException('Server bietet kein STARTTLS an.');
}
$this->cmd('STARTTLS', 220);
$ok = @stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
if ($ok !== true) {
throw new RuntimeException('TLS-Aushandlung fehlgeschlagen (Zertifikat oder Protokoll).');
}
$this->ehlo();
}
}
public function authenticate(string $user, string $password): void {
$mechanisms = strtoupper($this->features['auth'] ?? '');
if (str_contains($mechanisms, 'PLAIN')) {
$this->cmd('AUTH PLAIN ' . base64_encode("\0" . $user . "\0" . $password), 235);
return;
}
if (str_contains($mechanisms, 'LOGIN')) {
$this->cmd('AUTH LOGIN', 334);
$this->cmd(base64_encode($user), 334);
$this->cmd(base64_encode($password), 235);
return;
}
throw new RuntimeException('Server bietet weder AUTH PLAIN noch AUTH LOGIN an.');
}
public function sendMail(string $from, string $to, string $raw): void
{
$this->cmd('MAIL FROM:<' . $from . '>', 250);
$this->cmd('RCPT TO:<' . $to . '>', 250);
$this->cmd('DATA', 354);
// Dot-Stuffing nach RFC 5321: eine Zeile, die mit "." beginnt, wird verdoppelt.
$stuffed = preg_replace('/^\./m', '..', str_replace(["\r\n", "\r"], "\n", $raw));
$this->writeRaw(str_replace("\n", "\r\n", (string) $stuffed) . "\r\n.\r\n");
$this->expect(250);
}
/** @return resource */
private function context()
{
return stream_context_create(['ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'peer_name' => $this->host,
'SNI_enabled' => true,
'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
]]);
}
/** @return resource|false */
private function open(string $target)
{
$scheme = $this->secure === 'ssl' ? 'ssl' : 'tcp';
$errno = 0;
$errstr = '';
$socket = @stream_socket_client(
$scheme . '://' . $target . ':' . $this->port,
$errno,
$errstr,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->context()
);
if ($socket === false) {
$this->lastError = $errstr !== '' ? $errstr : 'Fehler ' . $errno;
return false;
}
return $socket;
}
public function quit(): void
{
if ($this->socket === null) {
return;
}
try {
@fwrite($this->socket, "QUIT\r\n");
} catch (Throwable) {
// Abschluss ist nicht kritisch.
}
@fclose($this->socket);
$this->socket = null;
}
private function ehlo(): void
{
$name = gethostname();
$response = $this->cmd('EHLO ' . ($name !== false && $name !== '' ? $name : 'localhost'), 250);
$this->features = [];
foreach (array_slice($response, 1) as $line) {
$parts = preg_split('/[\s=]+/', trim($line), 2);
if (!is_array($parts) || $parts[0] === '') {
continue;
}
$this->features[strtolower($parts[0])] = $parts[1] ?? '';
}
if (!array_key_exists('auth', $this->features)) {
// Manche Server liefern "AUTH=LOGIN PLAIN" – oben bereits normalisiert.
$this->features['auth'] = $this->features['auth'] ?? '';
}
}
/** @return list<string> Antwortzeilen ohne Statuscode */
private function cmd(string $line, int $expected): array
{
$this->writeRaw($line . "\r\n");
return $this->expect($expected);
}
/** @return list<string> */
private function expect(int $expected): array
{
[$code, $lines] = $this->read();
if ($code !== $expected) {
throw new RuntimeException(sprintf('SMTP-Dialog: Code %d statt %d (%s)', $code, $expected, implode(' ', $lines)));
}
return $lines;
}
/** @return array{0:int,1:list<string>} */
private function read(): array
{
if ($this->socket === null) {
throw new RuntimeException('Keine SMTP-Verbindung.');
}
$lines = [];
while (true) {
$line = fgets($this->socket, 2048);
if ($line === false) {
throw new RuntimeException('SMTP-Antwort blieb aus (Zeitüberschreitung).');
}
$line = rtrim($line, "\r\n");
if (preg_match('/^(\d{3})([ -])(.*)$/', $line, $m) !== 1) {
throw new RuntimeException('Unerwartete SMTP-Antwort: ' . substr($line, 0, 80));
}
$lines[] = $m[3];
if ($m[2] === ' ') {
return [(int) $m[1], $lines];
}
}
}
private function writeRaw(string $data): void
{
if ($this->socket === null) {
throw new RuntimeException('Keine SMTP-Verbindung.');
}
$remaining = $data;
while ($remaining !== '') {
$written = @fwrite($this->socket, $remaining);
if ($written === false || $written === 0) {
throw new RuntimeException('Schreiben auf die SMTP-Verbindung fehlgeschlagen.');
}
$remaining = substr($remaining, $written);
}
}
}
/** @return array<string,mixed> */
function mail_settings(): array
{
$mail = config('mail', []);
return is_array($mail) ? $mail : [];
}
/** Ist der Versand eingerichtet und vollständig konfiguriert? */
function mail_ready(): bool
{
$settings = mail_settings();
return trim((string) ($settings['host'] ?? '')) !== ''
&& trim((string) ($settings['from'] ?? '')) !== ''
&& trim((string) ($settings['user'] ?? '')) !== ''
&& (string) ($settings['password'] ?? '') !== '';
}
function mail_log(string $message): void
{
error_log('Westreiche-Mail: ' . $message);
}
/** Kodiert einen Header-Wert als RFC-2047-Wort (mit Folding für lange Betreffs). */
function mail_encode_header(string $value): string
{
if (preg_match('/^[\x20-\x7E]*$/', $value) === 1) {
return $value;
}
$encoded = base64_encode($value);
$words = str_split($encoded, 60);
return implode("\r\n ", array_map(static fn (string $chunk): string => '=?UTF-8?B?' . $chunk . '?=', $words));
}
function mail_display_name(string $name): string
{
if ($name === '') {
return '';
}
if (preg_match('/^[\x20-\x7E]+$/', $name) === 1) {
return '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], $name) . '"';
}
return mail_encode_header($name);
}
/** Baut die vollständige Nachricht (Header + base64-Textkörper) mit CRLF-Zeilen. */
function mail_build(string $from, string $fromName, string $to, string $subject, string $text): string
{
$address = (string) substr((string) strrchr($from, '@'), 1);
$domain = $address !== '' ? $address : 'zauberturm.de';
$name = mail_display_name($fromName);
$headers = [
'Date: ' . date('r'),
'From: ' . ($name !== '' ? $name . ' <' . $from . '>' : $from),
'To: ' . $to,
'Subject: ' . mail_encode_header($subject),
'Message-ID: <' . bin2hex(random_bytes(12)) . '@' . $domain . '>',
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: base64',
'X-Mailer: Westreiche Charakterverwaltung',
];
$normalized = str_replace(["\r\n", "\r"], "\n", $text);
$body = rtrim(chunk_split(base64_encode($normalized), 76, "\r\n"), "\r\n");
return implode("\r\n", $headers) . "\r\n\r\n" . $body;
}
/** Verschickt eine reine Textmail; wirft bei Fehlern RuntimeException. */
function mail_send(string $to, string $subject, string $text): void
{
if (!mail_ready()) {
throw new RuntimeException('Mailversand ist nicht eingerichtet.');
}
if (filter_var($to, FILTER_VALIDATE_EMAIL) === false) {
throw new RuntimeException('Ungültige Empfängeradresse: ' . $to);
}
$settings = mail_settings();
$secure = strtolower(trim((string) ($settings['secure'] ?? 'tls')));
if (!in_array($secure, ['tls', 'ssl'], true)) {
$secure = 'tls';
}
$port = (int) ($settings['port'] ?? 0);
$from = trim((string) $settings['from']);
$client = new WsSmtp(
trim((string) $settings['host']),
$port > 0 ? $port : ($secure === 'ssl' ? 465 : 587),
$secure,
(float) ($settings['timeout'] ?? 15)
);
try {
$client->connect();
$client->authenticate(trim((string) $settings['user']), (string) $settings['password']);
$client->sendMail(
$from,
$to,
mail_build($from, trim((string) ($settings['from_name'] ?? '')), $to, $subject, $text)
);
} finally {
$client->quit();
}
}
/** Text der Einladungsmail (auch für Passwort-Zurücksetzen passend). */
function mail_invite_text(array $user, array $invite): string
{
$name = trim((string) ($user['display_name'] ?? ''));
if ($name === '') {
$name = trim((string) ($user['username'] ?? ''));
}
$salutation = $name !== '' ? 'Hallo ' . $name . ',' : 'Hallo,';
$base = rtrim((string) config('app.public_url', ''), '/');
$path = rtrim((string) config('app.base_path', ''), '/');
$start = $base . ($path !== '' && !str_ends_with($base, $path) ? $path : '');
$expires = (new DateTimeImmutable((string) $invite['expires_at'], new DateTimeZone('UTC')))
->setTimezone(new DateTimeZone('Europe/Berlin'))
->format('d.m.Y H:i');
return implode("\n", [
$salutation,
'',
'für dich gibt es einen Zugang zur Westreiche-Chronik, dem Charakterverwalter',
'unserer Runde: ' . $start . '/',
'',
'Bitte vergib dein Passwort über diesen Link – er ist einmal verwendbar und',
'gültig bis ' . $expires . ' Uhr:',
'',
$invite['url'],
'',
'Danach kannst du dich mit deinem Benutzernamen oder dieser Adresse anmelden.',
'Wenn du nichts davon erwartest, ignoriere die Nachricht – ohne den Link',
'lässt sich nichts ändern.',
'',
'Mögen die Sterne günstig stehen',
'die Chronik der Zauberturm-Runde',
]);
}
/**
* Verschickt die Einladung, wenn möglich, und liefert den Status für die
* Rückmeldung im Admin-Formular.
*
* @return array{sent:bool, to:string|null, reason:string}
*/
function mail_invite_result(array $user, array $invite): array
{
if (!mail_ready()) {
return ['sent' => false, 'to' => null, 'reason' => 'not_configured'];
}
$to = trim((string) ($user['email'] ?? ''));
if ($to === '') {
return ['sent' => false, 'to' => null, 'reason' => 'no_address'];
}
try {
mail_send($to, 'Dein Zugang zur Westreiche-Chronik', mail_invite_text($user, $invite));
return ['sent' => true, 'to' => $to, 'reason' => 'ok'];
} catch (Throwable $error) {
mail_log('Einladung an ' . $to . ' fehlgeschlagen: ' . $error->getMessage());
return ['sent' => false, 'to' => $to, 'reason' => 'error'];
}
}
/** Zusatz für die Flash-Meldung nach dem Erzeugen einer Einladung. */
function mail_invite_note(array $result): string
{
if (($result['sent'] ?? false) === true) {
return ' Einladung per E-Mail an ' . (string) $result['to'] . ' gesendet.';
}
return match ($result['reason'] ?? '') {
'no_address' => ' Keine E-Mail-Adresse hinterlegt – Link bitte kopieren und weitergeben.',
'error' => ' E-Mail-Versand fehlgeschlagen – Link bitte kopieren und weitergeben.',
default => '',
};
}