diff --git a/README.md b/README.md index 36904f8..c8ffdea 100644 --- a/README.md +++ b/README.md @@ -258,6 +258,14 @@ Rundmails und Erinnerungen werden per SMTP verschickt. Konfiguriert wird das üb Lokal fängt [Mailpit](http://localhost:8025) alle Mails ab, es wird nichts an echte Adressen verschickt. +**Blockweiser Versand:** Rundmails gehen nicht mehr in einem einzigen Request raus (das +lief bei ~150 Empfängern in die Zeitlimits des Shared Hosts). Der Versand wird in Blöcken +von 10 Mails aus dem Browser angestoßen (`action=batch`, Fortschritt in der Session), der +Admin sieht eine Fortschrittsanzeige. Bricht der Request ab, bleibt der Rest in der +Session erhalten und ist auf der Rundmail-Übersicht über „Versand fortsetzen“ wieder +aufrufbar – ein Cron-Job ist dafür nicht nötig. Der Protokolleintrag entsteht erst nach +dem letzten Block, deshalb nach einem Abbruch immer erst fortsetzen statt neu senden. + ## Erinnerungsmails (Cron-Job) Spieler mit fehlenden Tipps oder fehlendem Joker bekommen automatisch eine Erinnerung. Ausgelöst wird das über eine von außen erreichbare Web-Route, die ein Cron-Job auf einem beliebigen Rechner aufruft: diff --git a/docs/code-map.md b/docs/code-map.md index 08b6f19..500729f 100644 --- a/docs/code-map.md +++ b/docs/code-map.md @@ -10,13 +10,13 @@ Diese Datei ersetzt die Erkundung. Erst hier nachschlagen, dann gezielt mit Abschnitt zu lesen. `docs/legacy/` ist absichtlich ausgeblendet (siehe `.ignore`); dort liegt der alte Laravel-Stand. -Umfang: 11436 Zeilen in 66 Dateien. +Umfang: 11504 Zeilen in 66 Dateien. ## Einstiegspunkte | Datei | Zeilen | Zweck | |---|---|---| -| `tippspiel/public/index.php` | 1206 | Front-Controller; Routing ist eine if/elseif-Kette auf `?page=` | +| `tippspiel/public/index.php` | 1289 | Front-Controller; Routing ist eine if/elseif-Kette auf `?page=` | | `tippspiel/src/autoload.php` | 26 | PSR-4-artiger Autoloader für `App\` | | `tools/schema.sql` | 204 | Schema der neuen DB (Tabellen, Indizes) | | `tippspiel/public/sw.js` | 114 | Service Worker für Web-Push | @@ -49,11 +49,11 @@ Umfang: 11436 Zeilen in 66 Dateien. | `admin_seasons` | Admin | `admin/seasons` | 586 | | `admin_rounds` | Admin | `admin/rounds` | 696 | | `admin_roundmails` | Admin | `admin/roundmails` | 804 | -| `admin_users` | Admin | `admin/users` | 871 | -| `round` | Login | `round` | 975 | -| `ranking` | Login | `ranking` | 1034 | -| `questions` | Login | `questions` | 1099 | -| `home` | Login | `home` | 1162 | +| `admin_users` | Admin | `admin/users` | 954 | +| `round` | Login | `round` | 1058 | +| `ranking` | Login | `ranking` | 1117 | +| `questions` | Login | `questions` | 1182 | +| `home` | Login | `home` | 1245 | Alle übrigen Pfade laufen auf `home` bzw. 404. Reihenfolge und Bedingungen stehen in `tippspiel/public/index.php`. `(Fallback)` markiert Seiten eines @@ -70,7 +70,7 @@ ohne View. | `tippspiel/src/Core/ErrorHandler.php` | 75 | Globale Fehlerbehandlung: Log + lesbare Fehlerseite statt leerem 500 | `register()`, `handleException($e)`, `handleFatal()`, `render()` | | `tippspiel/src/Core/ErrorLog.php` | 52 | PHP-Fehlerdatei außerhalb des Web-Roots, Rotation bei 5 MB | `path()`, `rotateIfNeeded($maxBytes)` | | `tippspiel/src/Core/Iban.php` | 51 | IBAN normalisieren und prüfen | `normalize($value)`, `isValid($value)` | -| `tippspiel/src/Core/Mailer.php` | 159 | Minimaler SMTP-Client ohne externe Abhängigkeiten | `send($recipients, $subject, $html, $replyTo)` | +| `tippspiel/src/Core/Mailer.php` | 167 | Minimaler SMTP-Client ohne externe Abhängigkeiten | `send($recipients, $subject, $html, $replyTo, …)` | | `tippspiel/src/Core/ResultFetcher.php` | 535 | Ergebnisse von openligadb und API-Football holen und eintragen | `openligadb($apply, $check)`, `apifootball($apply, $check)` | | `tippspiel/src/Core/WebPush.php` | 446 | Web-Push (VAPID, RFC 8291) ohne externe Abhängigkeiten | `isConfigured()`, `publicKey()`, `subject()`, `isValidEndpoint($endpoint)`, `isValidKeyMaterial($p256dh, $auth)`, `send($subscription, $payload)`, `encrypt($payload, $p256dh, $auth, $salt, …)` | @@ -100,7 +100,7 @@ ohne View. | `tippspiel/src/Views/admin/accounts.php` | 108 | Konto- und Ausschüttungsübersicht | | `tippspiel/src/Views/admin/fetcher_activity.php` | 64 | Protokoll des Ergebnis-Fetchers | | `tippspiel/src/Views/admin/message.php` | 34 | Mitteilung an alle Spieler setzen | -| `tippspiel/src/Views/admin/roundmails.php` | 212 | Rundmails verfassen und versenden | +| `tippspiel/src/Views/admin/roundmails.php` | 272 | Rundmails verfassen und versenden | | `tippspiel/src/Views/admin/rounds.php` | 206 | Spiele und Ergebnisse eintragen | | `tippspiel/src/Views/admin/seasons.php` | 217 | Saisons verwalten | | `tippspiel/src/Views/admin/users.php` | 190 | Benutzer verwalten (inkl. Tipp-/Joker-Lücken) | diff --git a/tippspiel/public/index.php b/tippspiel/public/index.php index 08e12db..3607c8e 100644 --- a/tippspiel/public/index.php +++ b/tippspiel/public/index.php @@ -805,6 +805,81 @@ if ($page === 'reminder') { Auth::requireLogin(); Auth::requireAdmin(); + // Versand erfolgt blockweise aus dem Browser: Ein Request verschickt nur + // BATCH_SIZE Mails. So bleibt jeder Aufruf deutlich unter den Zeitlimits + // des Shared Hosts, und ein Abbruch verliert höchstens einen Block. + $jobKey = 'roundmail_job'; + $batchSize = 10; + + if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'batch') { + @set_time_limit(120); + ignore_user_abort(true); + $wantsJson = ($_POST['format'] ?? '') === 'json'; + $job = $_SESSION[$jobKey] ?? null; + + if (!$job) { + if ($wantsJson) { + header('Content-Type: application/json'); + echo json_encode(['done' => true, 'redirect' => '/index.php?page=admin_roundmails']); + exit; + } + header('Location: /index.php?page=admin_roundmails'); + exit; + } + + $batch = array_splice($job['queue'], 0, $batchSize); + $error = null; + try { + Mailer::send($batch, $job['topic'], $job['html'], $job['reply_to'], + function ($email, $ok) use (&$job, $jobKey) { + $job[$ok ? 'sent' : 'failed'][] = $email; + $_SESSION[$jobKey] = $job; + // Fortschritt sofort sichern: bricht der Request ab, ist er erhalten + session_write_close(); + session_start(); + }); + } catch (\Throwable $e) { + // Der Block gilt als nicht versendet und wird beim nächsten Aufruf wiederholt + $job['queue'] = array_merge($batch, $job['queue']); + $error = $e->getMessage(); + } + + $total = count($job['queue']) + count($job['sent']) + count($job['failed']); + $done = empty($job['queue']); + $redirect = '/index.php?page=admin_roundmails'; + + if ($done) { + if (!empty($job['sent'])) { + Roundmail::create((int)$job['user_id'], $job['sent'], $job['topic'], $job['html'], (int)$job['season_id']); + } + $_SESSION['admin_message'] = 'Mail an ' . count($job['sent']) . ' Empfänger versendet.'; + if (!empty($job['failed'])) { + $_SESSION['admin_error'] = 'Nicht zustellbar: ' . implode(', ', $job['failed']); + } + unset($_SESSION[$jobKey]); + } else { + $_SESSION[$jobKey] = $job; + $redirect = '/index.php?page=admin_roundmails&send=1'; + } + + if ($wantsJson) { + header('Content-Type: application/json'); + echo json_encode([ + 'done' => $done, + 'sent' => count($job['sent']), + 'failed' => count($job['failed']), + 'total' => $total, + 'remaining' => count($job['queue']), + 'error' => $error, + 'redirect' => $redirect, + ]); + exit; + } + + header('Location: ' . $redirect); + exit; + } + if ($_SERVER['REQUEST_METHOD'] === 'POST') { $redirect = '/index.php?page=admin_roundmails'; try { @@ -823,17 +898,18 @@ if ($page === 'reminder') { $sender = Auth::user(); $currentSeason = Season::getViewSeason(); - $html = Roundmail::textToHtml($text); - $failed = Mailer::send($recipients['valid'], $topic, $html, $sender['email'] ?? null); - $sent = array_values(array_diff($recipients['valid'], $failed)); - if (!empty($sent)) { - Roundmail::create((int)$sender['id'], $sent, $topic, $html, $currentSeason ? (int)$currentSeason['id'] : 0); - } - - $_SESSION['admin_message'] = 'Mail an ' . count($sent) . ' Empfänger versendet.'; - if (!empty($failed)) { - $_SESSION['admin_error'] = 'Nicht zustellbar: ' . implode(', ', $failed); - } + $_SESSION[$jobKey] = [ + 'user_id' => (int)$sender['id'], + 'reply_to' => $sender['email'] ?? null, + 'topic' => $topic, + 'html' => Roundmail::textToHtml($text), + 'season_id' => $currentSeason ? (int)$currentSeason['id'] : 0, + 'queue' => array_values($recipients['valid']), + 'sent' => [], + 'failed' => [], + ]; + $_SESSION['admin_message'] = 'Versand läuft: ' . count($recipients['valid']) . ' Empfänger.'; + $redirect = '/index.php?page=admin_roundmails&send=1'; } catch (\Throwable $e) { $_SESSION['admin_error'] = 'Fehler: ' . $e->getMessage(); $_SESSION['admin_form'] = $_POST; @@ -852,6 +928,13 @@ if ($page === 'reminder') { $compose = isset($_GET['new']); $excludeReminders = ($_GET['hide_reminders'] ?? '') === '1'; + // Offener Versand aus einer früheren Sitzung (Abbruch, Timeout, Browser zu) + $sendJob = $_SESSION[$jobKey] ?? null; + $sending = isset($_GET['send']) && $sendJob; + if ($sending) { + $sendTotal = count($sendJob['queue']) + count($sendJob['sent']) + count($sendJob['failed']); + } + if ($compose) { $currentSeason = Season::getViewSeason(); $tippableRound = $currentSeason ? Round::getFirstTippable($currentSeason['id']) : null; @@ -859,7 +942,7 @@ if ($page === 'reminder') { $baseUrl = rtrim(getenv('APP_URL') ?: ((!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost')), '/'); $tippLink = $baseUrl . '/'; $mailConfigured = (bool)getenv('SMTP_HOST'); - } elseif (!$viewMail) { + } elseif (!$viewMail && !$sending) { $perPage = 20; $totalMails = Roundmail::count($excludeReminders); $totalPages = max(1, (int)ceil($totalMails / $perPage)); diff --git a/tippspiel/src/Core/Mailer.php b/tippspiel/src/Core/Mailer.php index 4493d61..b984a30 100644 --- a/tippspiel/src/Core/Mailer.php +++ b/tippspiel/src/Core/Mailer.php @@ -20,10 +20,12 @@ class Mailer { * @param string $subject * @param string $html * @param string|null $replyTo + * @param callable|null $onEach Wird nach jedem Empfänger mit ($email, $ok) aufgerufen, + * damit der Aufrufer den Fortschritt sofort sichern kann * @return string[] Empfänger, an die nicht versendet werden konnte * @throws \Exception bei Verbindungs- oder Anmeldefehlern */ - public static function send(array $recipients, $subject, $html, $replyTo = null) { + public static function send(array $recipients, $subject, $html, $replyTo = null, ?callable $onEach = null) { $mailer = new self(); $mailer->connect(); @@ -32,8 +34,14 @@ class Mailer { foreach ($recipients as $to) { try { $mailer->sendOne($to, $subject, $html, $replyTo); + if ($onEach) { + $onEach($to, true); + } } catch (\Exception $e) { $failed[] = $to; + if ($onEach) { + $onEach($to, false); + } $mailer->command('RSET', [250]); } } diff --git a/tippspiel/src/Views/admin/roundmails.php b/tippspiel/src/Views/admin/roundmails.php index 57e5d79..44139ae 100644 --- a/tippspiel/src/Views/admin/roundmails.php +++ b/tippspiel/src/Views/admin/roundmails.php @@ -83,6 +83,58 @@ $reminderParam = ($excludeReminders ?? false) ? '&hide_reminders=1' : ''; }); + + +

Mail wird versendet

+

von Empfängern versendet …

+ +

+

Der Versand läuft blockweise (10 Mails pro Anfrage), damit der Server nicht in ein Zeitlimit läuft. + Fenster bitte offen lassen. Ein Abbruch ist unschädlich: Der offene Rest lässt sich auf der Übersicht fortsetzen.

+ + + +

Zur Übersicht (Versand pausieren)

+ + +

@@ -100,6 +152,14 @@ $reminderParam = ($excludeReminders ?? false) ? '&hide_reminders=1' : '';

Neue Mail schreiben

+ +

+ Ein Versand ist noch offen: versendet, + offen. + Versand fortsetzen +

+ +