From a19cd8339ee25e2ab7c590e63c41810508660ff3 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Mon, 16 Nov 2026 12:46:12 +0100 Subject: [PATCH] Add poll expiry, reminder mail and polls admin CLI Polls are deleted POLL_RETENTION_DAYS (default 90) after creation by the cron job `bin/cake polls cleanup`. POLL_REMINDER_DAYS (default 14) before that the owner gets a one-time reminder mail (expiry_reminded_at). New commands: polls list, show (admin link only with --link), delete, remind, cleanup. The expiry date is shown in the creation mail and the dashboard. Docs: README, AGENTS.md, .env.example. Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 15 +- README.md | 24 +++ config/.env.example | 4 + ...61116120000_AddExpiryRemindedAtToPolls.php | 36 ++++ config/app.php | 7 + src/Command/PollsCleanupCommand.php | 79 ++++++++ src/Command/PollsCommand.php | 118 +++++++++++ src/Command/PollsDeleteCommand.php | 68 +++++++ src/Command/PollsListCommand.php | 104 ++++++++++ src/Command/PollsRemindCommand.php | 93 +++++++++ src/Command/PollsShowCommand.php | 85 ++++++++ src/Mailer/PollMailer.php | 19 ++ src/Model/Entity/Poll.php | 49 +++++ src/Model/Table/PollsTable.php | 40 ++++ templates/Admin/index.php | 3 + templates/email/html/admin_link.php | 3 + templates/email/html/expiry_reminder.php | 17 ++ templates/email/text/admin_link.php | 5 + templates/email/text/expiry_reminder.php | 24 +++ tests/TestCase/Command/PollsCommandsTest.php | 184 ++++++++++++++++++ 20 files changed, 976 insertions(+), 1 deletion(-) create mode 100644 config/Migrations/20261116120000_AddExpiryRemindedAtToPolls.php create mode 100644 src/Command/PollsCleanupCommand.php create mode 100644 src/Command/PollsCommand.php create mode 100644 src/Command/PollsDeleteCommand.php create mode 100644 src/Command/PollsListCommand.php create mode 100644 src/Command/PollsRemindCommand.php create mode 100644 src/Command/PollsShowCommand.php create mode 100644 templates/email/html/expiry_reminder.php create mode 100644 templates/email/text/expiry_reminder.php create mode 100644 tests/TestCase/Command/PollsCommandsTest.php diff --git a/AGENTS.md b/AGENTS.md index 88095b3..72482a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ E-Mail anlegen, kein Login, Verwaltung über einen geheimen Admin-Link, Teilnahm | Coding Standard | `vendor/bin/phpcs` / Autofix `vendor/bin/phpcbf` | | Neue Migration | `bin/cake bake migration NameDerMigration` | | Verwaiste Folienbilder löschen | `bin/cake images_cleanup [--dry-run]` | +| Umfragen verwalten (Admin-CLI) | `bin/cake polls list\|show\|delete\|remind\|cleanup` (siehe „Ablauf von Umfragen“) | **Vor jedem Commit:** `vendor/bin/phpunit` und `vendor/bin/phpcs` müssen grün sein (Warnungen zur Zeilenlänge bei langen deutschen Texten sind ok). @@ -65,6 +66,7 @@ src/ EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control ErrorController Fehlerseiten (Templates unter templates/Error, Layout `error`) Command/ImagesCleanupCommand `images_cleanup`: Bilddateien ohne Folie entfernen (idempotent) + Command/Polls*Command `polls list|show|delete|remind|cleanup` (Basis `PollsCommand`: Suche per id/Code, Links, Löschen) Mailer/ PollMailer (adminLink, recovery; `sendSafely()` loggt Transportfehler statt zu werfen), Transport/FileTransport (lokal) Middleware/ HostHeaderMiddleware: prüft in Produktion den Host gegen APP_FULL_BASE_URL; SecurityHeadersMiddleware (äußerste Schicht): CSP mit Nonce, Framing, nosniff, Referrer-/Permissions-Policy @@ -94,7 +96,8 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures - `polls`: `title`, `email`, `admin_token_hash` (sha256), `admin_token_encrypted` (Security::encrypt), `join_code` (6 Zeichen, ohne 0/O/1/I/L), `current_slide_id`, `is_active`, - `last_admin_access` (höchstens alle 10 min aktualisiert, Grundlage für ein künftiges Aufräumen alter Umfragen), + `last_admin_access` (höchstens alle 10 min aktualisiert, nur Anzeige in `polls list|show`), + `expiry_reminded_at` (Erinnerungsmail vor dem Ablauf verschickt, siehe „Ablauf von Umfragen“), `embed_key` (Einbett-Schlüssel), `embed_seen_at` (letztes Lebenszeichen der eingebetteten Live-Folie), `paused_slide_id` (Folie vor der Pause), `comment_speed` (Tempo der Skala-Kommentare in Prozent, Standard 100) - `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube|qa|order`), `question`, `description`, `position`, @@ -330,6 +333,16 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures **Buttons mit Bestätigung** nutzen `Form->postButton()` + `data-confirm` (CakePHPs `postLink`/`confirm` erzeugt ein Inline-`onclick`, das die CSP blockiert); das JS fragt per `window.confirm()` vor dem Absenden. Tests: `AdminFragmentTest.php`. +- **Ablauf von Umfragen** (`Plenario.retention.days` = `POLL_RETENTION_DAYS`, Standard 90, 0 = nie): berechnet, nicht gespeichert: + `Poll::expiresAt()` = `created` + Tage (feste Laufzeit, Nutzung verlängert nichts); Finder `PollsTable::findExpired()`. + **Erinnerung** (`Plenario.retention.reminderDays` = `POLL_REMINDER_DAYS`, Standard 14, 0 = aus, effektiv höchstens Laufzeit − 1: + `Poll::reminderLeadDays()`): `polls remind` mailt einmal pro Umfrage (`PollMailer::expiryReminder()`, mit Admin-Link; Finder + `findReminderDue()` = Erinnerungsfenster, noch nicht abgelaufen, `expiry_reminded_at` leer; Marker erst nach erfolgreichem Versand, + sonst nächster Lauf erneut). Ablaufdatum steht auch in der Anlege-Mail und im Dashboard (Karte „Sicherheit“). + Aufräumen per Cron: `bin/cake polls cleanup` (erst `remind`, dann idempotent löschen über `PollsTable::delete()` samt + Folien/Bildern, danach `images_cleanup`; `--dry-run`). `last_admin_access` fließt nicht mehr ein. `polls show --link` + ist die einzige Stelle, die den Admin-Link ausgibt (nie in `list`). Tests: `PollsCommandsTest.php` (leert vorher alle Umfragen). + ### Neuen Folientyp hinzufügen (Checkliste) 0. Bilder: `Slide::supportsImage()` entscheidet, ob der Typ ein Bild tragen kann (Standard ja). diff --git a/README.md b/README.md index 2e9fadf..3197802 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,8 @@ haben Vorrang vor der Datei. | `SHOW_ADMIN_LINK_AFTER_CREATE` | Nur für Entwicklung | | `THROTTLE_CREATE_PER_HOUR`, `THROTTLE_RECOVER_PER_HOUR` | Umfragen bzw. Wiederherstellungs-Mails pro IP und Stunde (0 = aus) | | `THROTTLE_VOTES_PER_MINUTE` | Antworten pro IP und Minute (0 = aus). Hoch lassen: Oft teilt sich ein ganzer Saal eine IP | +| `POLL_RETENTION_DAYS` | Umfragen werden so viele Tage nach dem Anlegen vom Cronjob gelöscht (Standard 90, 0 = nie) | +| `POLL_REMINDER_DAYS` | So viele Tage vorher bekommt der Besitzer eine Erinnerungsmail (Standard 14, 0 = keine, muss kleiner als die Laufzeit sein) | | `POLL_INTERVAL_MS` | Aktualisierungsintervall der Live-Ansichten | | `EMBED_HEARTBEAT_SECONDS`, `EMBED_TIMEOUT_SECONDS` | Eingebettete Folien: Lebenszeichen-Intervall und Zeit bis zur automatischen Pause | | `EMBED_FRAME_ANCESTORS` | Welche Seiten Folien einbetten dürfen (CSP `frame-ancestors`), z. B. `https://*.canva.com`; `*` = alle | @@ -247,6 +249,28 @@ entfernt `bin/cake images_cleanup` (`--dry-run` zeigt sie nur an). Bei Updates: Code aktualisieren, `composer install --no-dev`, Migrationen und `cache clear_all` wiederholen. +### Umfragen verwalten und aufräumen (CLI) + +| Befehl | Zweck | +|---|---| +| `bin/cake polls list [--expired] [--email=text] [--sort=created\|activity\|title]` | Umfragen mit E-Mail, Ablaufdatum und Erinnerung | +| `bin/cake polls show [--link]` | Details; mit `--link` auch der geheime Admin-Link (nur auf Wunsch) | +| `bin/cake polls delete [--yes]` | Eine Umfrage samt Folien, Antworten und Bildern löschen (fragt nach) | +| `bin/cake polls remind [--dry-run]` | Erinnerungsmails für bald ablaufende Umfragen (je Umfrage einmal) | +| `bin/cake polls cleanup [--dry-run]` | Der Cronjob: erst erinnern, dann abgelaufene Umfragen löschen, danach verwaiste Bilddateien | + +Eine Umfrage läuft `POLL_RETENTION_DAYS` Tage (Standard 90) nach dem Anlegen ab und wird dann gelöscht, unabhängig davon, +wie oft sie genutzt wurde. `POLL_REMINDER_DAYS` Tage vorher (Standard 14, 0 = keine Erinnerung) bekommt der Besitzer +einmalig eine Mail mit Ablaufdatum und Admin-Link, um die Ergebnisse als PDF zu sichern. Das Ablaufdatum steht außerdem in +der Anlege-Mail und im Dashboard (Karte „Sicherheit“). Es wird berechnet, eine Änderung der Einstellung gilt also sofort +für alle Umfragen. Ein einziger Cronjob erledigt Erinnern und Löschen (täglich 3:17 Uhr): + +``` +17 3 * * * cd /pfad/zu/plenario && php bin/cake.php polls cleanup --quiet +``` + +Vorher mit `polls cleanup --dry-run` prüfen, was gelöscht würde. Im Container: `docker compose exec plenario bin/cake polls cleanup`. + ## Automatisches Deployment (Gitea Actions) [.gitea/workflows/ci.yml](.gitea/workflows/ci.yml) testet jeden Push (PHPUnit + phpcs). diff --git a/config/.env.example b/config/.env.example index 8a54a1d..63171be 100644 --- a/config/.env.example +++ b/config/.env.example @@ -41,6 +41,10 @@ THROTTLE_CREATE_PER_HOUR=10 THROTTLE_RECOVER_PER_HOUR=5 # Max. answers per IP and minute (0 = unlimited). Keep it high: a whole audience may share one Wi-Fi/IP. THROTTLE_VOTES_PER_MINUTE=600 +# Polls are deleted this many days after their creation by the cron job `bin/cake polls cleanup` +# (0 = never expire). The owner gets a reminder mail POLL_REMINDER_DAYS before (0 = no reminder). +POLL_RETENTION_DAYS=90 +POLL_REMINDER_DAYS=14 # How often presenter and participant pages poll for updates (ms) POLL_INTERVAL_MS=2000 # Slide images: directory (default data/uploads; in containers e.g. /data/uploads), largest upload in MB diff --git a/config/Migrations/20261116120000_AddExpiryRemindedAtToPolls.php b/config/Migrations/20261116120000_AddExpiryRemindedAtToPolls.php new file mode 100644 index 0000000..efc3344 --- /dev/null +++ b/config/Migrations/20261116120000_AddExpiryRemindedAtToPolls.php @@ -0,0 +1,36 @@ +table('polls'); + if (!$table->hasColumn('expiry_reminded_at')) { + $table->addColumn('expiry_reminded_at', 'datetime', [ + 'null' => true, + 'default' => null, + 'after' => 'last_admin_access', + ])->update(); + } + } + + /** + * @return void + */ + public function down(): void + { + $table = $this->table('polls'); + if ($table->hasColumn('expiry_reminded_at')) { + $table->removeColumn('expiry_reminded_at')->update(); + } + } +} diff --git a/config/app.php b/config/app.php index 1fae32f..df0194d 100644 --- a/config/app.php +++ b/config/app.php @@ -49,6 +49,13 @@ return [ // Answers (incl. word cloud entries and upvotes) per IP and minute; a whole audience may share one IP. 'votesPerMinute' => (int)env('THROTTLE_VOTES_PER_MINUTE', 600), ], + // Polls are deleted this many days after their creation by `bin/cake polls cleanup` (cron). + // 0 = never expire. + 'retention' => [ + 'days' => (int)env('POLL_RETENTION_DAYS', 90), + // The owner gets a reminder mail this many days before (0 = no reminder, must be < days). + 'reminderDays' => (int)env('POLL_REMINDER_DAYS', 14), + ], 'pollIntervalMs' => (int)env('POLL_INTERVAL_MS', 2000), // Slide images (see \App\Service\ImageService): scaled and re-encoded as WebP, stored outside webroot. 'images' => [ diff --git a/src/Command/PollsCleanupCommand.php b/src/Command/PollsCleanupCommand.php new file mode 100644 index 0000000..9c5dba8 --- /dev/null +++ b/src/Command/PollsCleanupCommand.php @@ -0,0 +1,79 @@ +setDescription(__('Der Cronjob: erinnert Besitzer bald ablaufender Umfragen, löscht abgelaufene und danach verwaiste Bilddateien.')) + ->addOption('dry-run', [ + 'help' => __('Nur anzeigen, nichts löschen.'), + 'boolean' => true, + ]); + } + + /** + * @param \Cake\Console\Arguments $args Arguments + * @param \Cake\Console\ConsoleIo $io Console + * @return int + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + if ((int)Configure::read('Plenario.retention.days', 90) <= 0) { + $io->out(__('Umfragen laufen nie ab (POLL_RETENTION_DAYS=0), nichts zu tun.')); + + return static::CODE_SUCCESS; + } + + // Reminder first, so owners hear about it before the deletion (idempotent: once per poll). + $remind = $this->executeCommand(PollsRemindCommand::class, $args->getOption('dry-run') ? ['--dry-run'] : [], $io); + + /** @var list<\App\Model\Entity\Poll> $expired */ + $expired = $this->polls()->find('expired')->orderBy(['Polls.id' => 'ASC'])->all()->toList(); + + if ($args->getOption('dry-run')) { + foreach ($expired as $poll) { + $io->out(__('Abgelaufen: #{0} {1} ({2}), seit {3}', $poll->id, $poll->title, $poll->email, $this->formatDate($poll->expiresAt()))); + } + $io->success(__('{0} abgelaufene Umfrage(n) gefunden (nichts gelöscht).', count($expired))); + + return static::CODE_SUCCESS; + } + + $deleted = $this->deletePolls($expired, $io); + $io->success(__('{0} abgelaufene Umfrage(n) gelöscht.', $deleted)); + + // Sweep image files a crash may have left behind (cheap, idempotent). + $this->executeCommand(ImagesCleanupCommand::class, [], $io); + + return $deleted === count($expired) && $remind === static::CODE_SUCCESS ? static::CODE_SUCCESS : static::CODE_ERROR; + } +} diff --git a/src/Command/PollsCommand.php b/src/Command/PollsCommand.php new file mode 100644 index 0000000..6814da2 --- /dev/null +++ b/src/Command/PollsCommand.php @@ -0,0 +1,118 @@ +fetchTable('Polls'); + + return $polls; + } + + /** + * Finds a poll by numeric id or join code ("K7P2QX", "k7p-2qx"). + * + * @param string $reference Id or join code + * @return \App\Model\Entity\Poll|null + */ + protected function findPoll(string $reference): ?Poll + { + $reference = trim($reference); + if ($reference !== '' && ctype_digit($reference)) { + $poll = $this->polls()->find()->where(['Polls.id' => (int)$reference])->first(); + if ($poll !== null) { + /** @var \App\Model\Entity\Poll $poll */ + return $poll; + } + } + + /** @var \App\Model\Entity\Poll|null $poll */ + $poll = $this->polls()->find('byJoinCode', code: $reference)->first(); + + return $poll; + } + + /** + * Absolute admin link (contains the secret token: show it only on explicit request). + * + * @param \App\Model\Entity\Poll $poll Poll + * @return string|null Null if the token cannot be decrypted (e.g. SECURITY_SALT changed) + */ + protected function adminLink(Poll $poll): ?string + { + $token = $this->polls()->decryptToken($poll); + + return $token === null ? null : Router::url(['_name' => 'admin', 'token' => $token], true); + } + + /** + * @param \App\Model\Entity\Poll $poll Poll + * @return string Absolute participant link + */ + protected function joinLink(Poll $poll): string + { + return Router::url(['_name' => 'participate', 'code' => $poll->join_code], true); + } + + /** + * @param \Cake\I18n\DateTime|null $date Date + * @return string "2026-11-16 14:30" in the server's time zone, "-" if empty + */ + protected function formatDate(?DateTime $date): string + { + return $date === null ? '-' : $date->format('Y-m-d H:i'); + } + + /** + * @param \App\Model\Entity\Poll $poll Poll + * @return string Expiry date, with a marker once it has passed + */ + protected function formatExpiry(Poll $poll): string + { + $expires = $poll->expiresAt(); + if ($expires === null) { + return __('nie'); + } + + return $this->formatDate($expires) . ($expires->isPast() ? ' ' . __('(abgelaufen)') : ''); + } + + /** + * Deletes polls including slides, answers and images, one transaction per poll. + * + * @param iterable<\App\Model\Entity\Poll> $polls Polls + * @param \Cake\Console\ConsoleIo $io Console + * @return int Number of deleted polls + */ + protected function deletePolls(iterable $polls, ConsoleIo $io): int + { + $deleted = 0; + foreach ($polls as $poll) { + if ($this->polls()->delete($poll)) { + $deleted++; + $io->out(__('Gelöscht: #{0} {1} ({2})', $poll->id, $poll->title, $poll->email)); + } else { + $io->err(__('Konnte #{0} nicht löschen.', $poll->id)); + } + } + + return $deleted; + } +} diff --git a/src/Command/PollsDeleteCommand.php b/src/Command/PollsDeleteCommand.php new file mode 100644 index 0000000..1f14ee0 --- /dev/null +++ b/src/Command/PollsDeleteCommand.php @@ -0,0 +1,68 @@ + [--yes] + */ +class PollsDeleteCommand extends PollsCommand +{ + /** + * @return string + */ + public static function defaultName(): string + { + return 'polls delete'; + } + + /** + * @param \Cake\Console\ConsoleOptionParser $parser Parser + * @return \Cake\Console\ConsoleOptionParser + */ + protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser + { + return $parser + ->setDescription(__('Löscht Umfragen endgültig, samt Folien, Antworten und Bildern.')) + ->addArgument('poll', [ + 'help' => __('ID oder Beitrittscode der Umfrage.'), + 'required' => true, + ]) + ->addOption('yes', [ + 'short' => 'y', + 'help' => __('Ohne Rückfrage löschen.'), + 'boolean' => true, + ]); + } + + /** + * @param \Cake\Console\Arguments $args Arguments + * @param \Cake\Console\ConsoleIo $io Console + * @return int + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + $reference = (string)$args->getArgument('poll'); + $poll = $this->findPoll($reference); + if ($poll === null) { + $io->err(__('Umfrage "{0}" nicht gefunden.', $reference)); + + return static::CODE_ERROR; + } + + $io->out(__('#{0} {1} ({2}), angelegt {3}', $poll->id, $poll->title, $poll->email, $this->formatDate($poll->created))); + if (!$args->getOption('yes') && $io->askChoice(__('Diese Umfrage endgültig löschen?'), ['y', 'n'], 'n') !== 'y') { + $io->out(__('Abgebrochen.')); + + return static::CODE_ERROR; + } + + return $this->deletePolls([$poll], $io) === 1 ? static::CODE_SUCCESS : static::CODE_ERROR; + } +} diff --git a/src/Command/PollsListCommand.php b/src/Command/PollsListCommand.php new file mode 100644 index 0000000..4878d32 --- /dev/null +++ b/src/Command/PollsListCommand.php @@ -0,0 +1,104 @@ +] [--sort=created|activity|title] + */ +class PollsListCommand extends PollsCommand +{ + /** + * @return string + */ + public static function defaultName(): string + { + return 'polls list'; + } + + /** + * @param \Cake\Console\ConsoleOptionParser $parser Parser + * @return \Cake\Console\ConsoleOptionParser + */ + protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser + { + return $parser + ->setDescription(__('Zeigt alle Umfragen mit E-Mail-Adresse, Ablaufdatum und Erinnerung.')) + ->addOption('expired', [ + 'help' => __('Nur abgelaufene Umfragen.'), + 'boolean' => true, + ]) + ->addOption('email', [ + 'help' => __('Nur Umfragen, deren E-Mail-Adresse diesen Text enthält.'), + ]) + ->addOption('sort', [ + 'help' => __('Sortierung (aufsteigend).'), + 'default' => 'created', + 'choices' => ['created', 'activity', 'title'], + ]); + } + + /** + * @param \Cake\Console\Arguments $args Arguments + * @param \Cake\Console\ConsoleIo $io Console + * @return int + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + $query = $this->polls()->find() + ->select([ + 'Polls.id', 'Polls.title', 'Polls.email', 'Polls.join_code', 'Polls.current_slide_id', + 'Polls.paused_slide_id', 'Polls.last_admin_access', 'Polls.expiry_reminded_at', 'Polls.created', + ]) + ->orderBy(['Polls.id' => 'ASC']); + if ($args->getOption('expired')) { + $query->find('expired'); + } + $email = $args->getOption('email'); + if (is_string($email) && $email !== '') { + $query->where(['Polls.email LIKE' => '%' . addcslashes(strtolower($email), '%_\\') . '%']); + } + + /** @var list<\App\Model\Entity\Poll> $polls */ + $polls = $query->all()->toList(); + $sort = (string)$args->getOption('sort'); + if ($sort !== 'created') { + usort($polls, fn($a, $b): int => match ($sort) { + 'activity' => ($a->last_admin_access ?? $a->created) <=> ($b->last_admin_access ?? $b->created), + default => strcasecmp($a->title, $b->title), + }); + } + + if ($polls === []) { + $io->out(__('Keine Umfragen gefunden.')); + + return static::CODE_SUCCESS; + } + + $rows = [[__('ID'), __('Code'), __('Titel'), __('E-Mail'), __('Angelegt'), __('Letzter Admin-Besuch'), __('Läuft ab'), __('Erinnert')]]; + foreach ($polls as $poll) { + $rows[] = [ + (string)$poll->id, + $poll->join_code, + mb_strimwidth($poll->title, 0, 40, '…'), + $poll->email, + $this->formatDate($poll->created), + $this->formatDate($poll->last_admin_access), + $this->formatExpiry($poll), + $this->formatDate($poll->expiry_reminded_at), + ]; + } + $io->helper('Table')->output($rows); + + $expired = count(array_filter($polls, fn($poll): bool => $poll->isExpired())); + $io->out(__('{0} Umfrage(n), davon {1} abgelaufen.', count($polls), $expired)); + + return static::CODE_SUCCESS; + } +} diff --git a/src/Command/PollsRemindCommand.php b/src/Command/PollsRemindCommand.php new file mode 100644 index 0000000..526943c --- /dev/null +++ b/src/Command/PollsRemindCommand.php @@ -0,0 +1,93 @@ +setDescription(__('Erinnert Besitzer per E-Mail, bevor ihre Umfrage automatisch gelöscht wird.')) + ->addOption('dry-run', [ + 'help' => __('Nur anzeigen, nichts verschicken.'), + 'boolean' => true, + ]); + } + + /** + * @param \Cake\Console\Arguments $args Arguments + * @param \Cake\Console\ConsoleIo $io Console + * @return int + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + if (Poll::reminderLeadDays() === 0) { + $io->out(__('Erinnerungen sind aus (POLL_REMINDER_DAYS=0 oder Umfragen laufen nie ab).')); + + return static::CODE_SUCCESS; + } + + $dryRun = (bool)$args->getOption('dry-run'); + /** @var list<\App\Model\Entity\Poll> $due */ + $due = $this->polls()->find('reminderDue')->orderBy(['Polls.id' => 'ASC'])->all()->toList(); + + $sent = 0; + $failed = 0; + foreach ($due as $poll) { + $label = __('#{0} {1} ({2}), läuft ab {3}', $poll->id, $poll->title, $poll->email, $this->formatDate($poll->expiresAt())); + if ($dryRun) { + $io->out(__('Würde erinnern: {0}', $label)); + continue; + } + + $adminUrl = $this->adminLink($poll); + if ($adminUrl === null) { + $io->err(__('Admin-Link nicht entschlüsselbar, keine Erinnerung: {0}', $label)); + $failed++; + continue; + } + if (!(new PollMailer())->sendSafely('expiryReminder', [$poll, $adminUrl])) { + $io->err(__('E-Mail fehlgeschlagen: {0}', $label)); + $failed++; + continue; + } + // Only the marker column; the poll may have been changed meanwhile. + $this->polls()->updateAll(['expiry_reminded_at' => DateTime::now()], ['id' => $poll->id]); + $io->out(__('Erinnert: {0}', $label)); + $sent++; + } + + $io->success($dryRun + ? __('{0} Erinnerung(en) wären fällig (nichts verschickt).', count($due)) + : __('{0} Erinnerung(en) verschickt, {1} fehlgeschlagen.', $sent, $failed)); + + return $failed === 0 ? static::CODE_SUCCESS : static::CODE_ERROR; + } +} diff --git a/src/Command/PollsShowCommand.php b/src/Command/PollsShowCommand.php new file mode 100644 index 0000000..00cec45 --- /dev/null +++ b/src/Command/PollsShowCommand.php @@ -0,0 +1,85 @@ + [--link] + */ +class PollsShowCommand extends PollsCommand +{ + /** + * @return string + */ + public static function defaultName(): string + { + return 'polls show'; + } + + /** + * @param \Cake\Console\ConsoleOptionParser $parser Parser + * @return \Cake\Console\ConsoleOptionParser + */ + protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser + { + return $parser + ->setDescription(__('Zeigt Details einer Umfrage, auf Wunsch mit dem geheimen Admin-Link.')) + ->addArgument('poll', [ + 'help' => __('ID oder Beitrittscode der Umfrage.'), + 'required' => true, + ]) + ->addOption('link', [ + 'help' => __('Auch den Admin-Link ausgeben (enthält das geheime Token!).'), + 'boolean' => true, + ]); + } + + /** + * @param \Cake\Console\Arguments $args Arguments + * @param \Cake\Console\ConsoleIo $io Console + * @return int + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + $poll = $this->findPoll((string)$args->getArgument('poll')); + if ($poll === null) { + $io->err(__('Umfrage nicht gefunden.')); + + return static::CODE_ERROR; + } + + $slides = $this->fetchTable('Slides')->find()->where(['poll_id' => $poll->id])->count(); + $io->out([ + __('ID: {0}', $poll->id), + __('Titel: {0}', $poll->title), + __('E-Mail: {0}', $poll->email), + __('Beitrittscode: {0}', $poll->join_code), + __('Teilnahme-Link: {0}', $this->joinLink($poll)), + __('Folien: {0}', $slides), + __('Angelegt: {0}', $this->formatDate($poll->created)), + __('Letzter Besuch: {0}', $this->formatDate($poll->last_admin_access)), + __('Läuft ab: {0}', $this->formatExpiry($poll)), + __('Erinnerung: {0}', $poll->expiry_reminded_at === null ? __('nicht verschickt') : $this->formatDate($poll->expiry_reminded_at)), + ]); + + if ($args->getOption('link')) { + $link = $this->adminLink($poll); + if ($link === null) { + $io->err(__('Der Admin-Link lässt sich nicht entschlüsseln (SECURITY_SALT geändert?).')); + + return static::CODE_ERROR; + } + $io->out(__('Admin-Link: {0}', $link)); + } else { + $io->out(__('Admin-Link: (mit --link anzeigen)')); + } + + return static::CODE_SUCCESS; + } +} diff --git a/src/Mailer/PollMailer.php b/src/Mailer/PollMailer.php index a892706..50b201b 100644 --- a/src/Mailer/PollMailer.php +++ b/src/Mailer/PollMailer.php @@ -53,6 +53,25 @@ class PollMailer extends Mailer ->setTemplate('admin_link'); } + /** + * Reminder shortly before the poll is deleted automatically (sent once, by `polls remind`). + * + * @param \App\Model\Entity\Poll $poll Poll + * @param string $adminUrl Absolute admin URL (contains the token) + * @return void + */ + public function expiryReminder(Poll $poll, string $adminUrl): void + { + $expires = $poll->expiresAt(); + $this + ->setTo($poll->email) + ->setSubject(__('Deine Umfrage „{0}“ wird bald gelöscht', $poll->title)) + ->setEmailFormat('both') + ->setViewVars(compact('poll', 'adminUrl', 'expires')) + ->viewBuilder() + ->setTemplate('expiry_reminder'); + } + /** * Recovery mail listing all admin links of an e-mail address. * diff --git a/src/Model/Entity/Poll.php b/src/Model/Entity/Poll.php index 6790b0e..8bb56f1 100644 --- a/src/Model/Entity/Poll.php +++ b/src/Model/Entity/Poll.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace App\Model\Entity; +use Cake\Core\Configure; use Cake\I18n\DateTime; use Cake\ORM\Entity; @@ -20,6 +21,7 @@ use Cake\ORM\Entity; * @property bool $is_active * @property int $comment_speed Speed of rotating scale comments in percent, see COMMENT_SPEEDS * @property \Cake\I18n\DateTime|null $last_admin_access + * @property \Cake\I18n\DateTime|null $expiry_reminded_at When the reminder before the expiry was mailed * @property \Cake\I18n\DateTime $created * @property \Cake\I18n\DateTime $modified * @property array<\App\Model\Entity\Slide> $slides @@ -69,6 +71,53 @@ class Poll extends Entity return trim(chunk_split($this->join_code, 3, ' ')); } + /** + * Polls live `Plenario.retention.days` days from their creation, then `bin/cake polls cleanup` + * deletes them (a reminder mail goes out beforehand, see reminderAt()). Computed, not stored: + * changing the setting applies to all polls at once. + * + * @return \Cake\I18n\DateTime|null Null if polls never expire (setting 0) + */ + public function expiresAt(): ?DateTime + { + $days = (int)Configure::read('Plenario.retention.days', 90); + + return $days > 0 ? $this->created->addDays($days) : null; + } + + /** + * @return int Days before the expiry date the reminder goes out (0 = no reminder). Always shorter than the + * lifetime, otherwise the reminder would be due the moment a poll is created. + */ + public static function reminderLeadDays(): int + { + $days = (int)Configure::read('Plenario.retention.days', 90); + $lead = (int)Configure::read('Plenario.retention.reminderDays', 14); + + return $days > 0 ? max(0, min($lead, $days - 1)) : 0; + } + + /** + * @return \Cake\I18n\DateTime|null When the reminder becomes due, null without expiry or reminder + */ + public function reminderAt(): ?DateTime + { + $expires = $this->expiresAt(); + $lead = static::reminderLeadDays(); + + return $expires === null || $lead === 0 ? null : $expires->subDays($lead); + } + + /** + * @return bool Past its expiry date + */ + public function isExpired(): bool + { + $expires = $this->expiresAt(); + + return $expires !== null && $expires->isPast(); + } + /** * Shows a slide to the participants (from PlenarIO itself: no embed timeout). * diff --git a/src/Model/Table/PollsTable.php b/src/Model/Table/PollsTable.php index 1270ec7..83e45ef 100644 --- a/src/Model/Table/PollsTable.php +++ b/src/Model/Table/PollsTable.php @@ -9,6 +9,7 @@ use ArrayObject; use Cake\Core\Configure; use Cake\Datasource\EntityInterface; use Cake\Event\EventInterface; +use Cake\I18n\DateTime; use Cake\ORM\Query\SelectQuery; use Cake\ORM\RulesChecker; use Cake\ORM\Table; @@ -276,6 +277,45 @@ class PollsTable extends Table return $query->where(['Polls.join_code' => static::normalizeJoinCode($code)]); } + /** + * Polls past their expiry date (created + retention, see Poll::expiresAt()); none if the retention is 0. + * + * @param \Cake\ORM\Query\SelectQuery $query Query + * @return \Cake\ORM\Query\SelectQuery + */ + public function findExpired(SelectQuery $query): SelectQuery + { + $days = (int)Configure::read('Plenario.retention.days', 90); + if ($days <= 0) { + return $query->where('1 = 0'); + } + + return $query->where(['Polls.created <' => DateTime::now()->subDays($days)]); + } + + /** + * Polls whose reminder is due and not yet sent: inside the last `reminderDays` before the expiry, + * but not expired yet (then it is too late, they are deleted). + * + * @param \Cake\ORM\Query\SelectQuery $query Query + * @return \Cake\ORM\Query\SelectQuery + */ + public function findReminderDue(SelectQuery $query): SelectQuery + { + $lead = Poll::reminderLeadDays(); + if ($lead === 0) { + return $query->where('1 = 0'); + } + $days = (int)Configure::read('Plenario.retention.days', 90); + $now = DateTime::now(); + + return $query->where([ + 'Polls.expiry_reminded_at IS' => null, + 'Polls.created <=' => $now->subDays($days - $lead), + 'Polls.created >=' => $now->subDays($days), + ]); + } + /** * @param \Cake\ORM\Query\SelectQuery $query Query * @param string $key Embed key diff --git a/templates/Admin/index.php b/templates/Admin/index.php index 8ed9832..44fcc3c 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -289,6 +289,9 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-

+ expiresAt() !== null) : ?> +

expiresAt()->i18nFormat('dd.MM.yyyy'))) ?>

+

Form->postButton(__('Neuen Admin-Link erzeugen'), $url('admin:rotate'), [ 'class' => 'button button--small', diff --git a/templates/email/html/admin_link.php b/templates/email/html/admin_link.php index 688a9c9..876d99a 100644 --- a/templates/email/html/admin_link.php +++ b/templates/email/html/admin_link.php @@ -14,4 +14,7 @@

{1}.', '' . h($joinUrl) . '', h($poll->formattedJoinCode())) ?>

+expiresAt() !== null) : ?> +

expiresAt()->format('d.m.Y'))) ?>

+

diff --git a/templates/email/html/expiry_reminder.php b/templates/email/html/expiry_reminder.php new file mode 100644 index 0000000..515d0e8 --- /dev/null +++ b/templates/email/html/expiry_reminder.php @@ -0,0 +1,17 @@ + +

+

{0} wird am {1} automatisch gelöscht, einschließlich aller Folien, Antworten und Bilder.', h($poll->title), h($expires->format('d.m.Y'))) ?>

+

+

+ +

+

+

+

diff --git a/templates/email/text/admin_link.php b/templates/email/text/admin_link.php index 3312c53..4d16890 100644 --- a/templates/email/text/admin_link.php +++ b/templates/email/text/admin_link.php @@ -21,4 +21,9 @@ formattedJoinCode()) ?> +expiresAt() !== null) : ?> +expiresAt()->format('d.m.Y')) ?> + + + diff --git a/templates/email/text/expiry_reminder.php b/templates/email/text/expiry_reminder.php new file mode 100644 index 0000000..ce6e82d --- /dev/null +++ b/templates/email/text/expiry_reminder.php @@ -0,0 +1,24 @@ + + + + +title, $expires->format('d.m.Y')) ?> + + + + + + + + + + + + diff --git a/tests/TestCase/Command/PollsCommandsTest.php b/tests/TestCase/Command/PollsCommandsTest.php new file mode 100644 index 0000000..18a82b1 --- /dev/null +++ b/tests/TestCase/Command/PollsCommandsTest.php @@ -0,0 +1,184 @@ +slidesTable()->deleteAll('1 = 1'); + $this->pollsTable()->deleteAll('1 = 1'); + } + + /** + * @param int $id Poll id + * @param int $days Age of the poll in days + */ + private function age(int $id, int $days): void + { + $this->pollsTable()->updateAll(['created' => DateTime::now()->subDays($days)], ['id' => $id]); + } + + public function testExpiryCountsFromCreationNotFromAdminVisits(): void + { + [$poll] = $this->createPoll(); + $this->assertSame($poll->created->addDays(90)->format('Y-m-d'), $poll->expiresAt()->format('Y-m-d')); + $this->assertSame($poll->created->addDays(76)->format('Y-m-d'), $poll->reminderAt()->format('Y-m-d')); + + $this->age($poll->id, 91); + // A visit in the admin area changes nothing. + $this->pollsTable()->updateAll(['last_admin_access' => DateTime::now()], ['id' => $poll->id]); + $this->assertTrue($this->pollsTable()->get($poll->id)->isExpired()); + } + + public function testSettingsAreRespected(): void + { + [$poll] = $this->createPoll(); + $this->age($poll->id, 1000); + + Configure::write('Plenario.retention.days', 0); + $this->assertNull($this->pollsTable()->get($poll->id)->expiresAt()); + $this->assertSame(0, $this->pollsTable()->find('expired')->count()); + $this->assertSame(0, $this->pollsTable()->find('reminderDue')->count()); + + // The reminder lead is always shorter than the lifetime. + Configure::write('Plenario.retention.days', 10); + Configure::write('Plenario.retention.reminderDays', 30); + $this->assertSame(9, $poll::reminderLeadDays()); + } + + public function testListShowsOwnerAndExpiredFilter(): void + { + [$old] = $this->createPoll('Alte Umfrage', 'alt@example.org'); + $this->createPoll('Neue Umfrage', 'neu@example.org'); + $this->age($old->id, 120); + + $this->exec('polls list'); + $this->assertExitSuccess(); + $this->assertOutputContains('alt@example.org'); + $this->assertOutputContains('neu@example.org'); + $this->assertOutputContains('(abgelaufen)'); + + $this->exec('polls list --expired'); + $this->assertOutputContains('alt@example.org'); + $this->assertOutputNotContains('neu@example.org'); + + $this->exec('polls list --email=NEU@'); + $this->assertOutputContains('neu@example.org'); + $this->assertOutputNotContains('alt@example.org'); + } + + public function testShowPrintsAdminLinkOnlyOnRequest(): void + { + [$poll, $token] = $this->createPoll('Titel', 'owner@example.org'); + + $this->exec('polls show ' . $poll->join_code); + $this->assertExitSuccess(); + $this->assertOutputContains('owner@example.org'); + $this->assertOutputNotContains($token); + + $this->exec('polls show ' . $poll->id . ' --link'); + $this->assertExitSuccess(); + $this->assertOutputContains('https://plenario.test/admin/' . $token); + + $this->exec('polls show 99999'); + $this->assertExitError(); + } + + public function testDeleteRemovesPollWithSlides(): void + { + [$poll] = $this->createPoll(); + $this->createSlide($poll); + + $this->exec('polls delete ' . $poll->id . ' --yes'); + $this->assertExitSuccess(); + $this->assertSame(0, $this->pollsTable()->find()->where(['id' => $poll->id])->count()); + $this->assertSame(0, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + + // Again: unknown poll is an error, nothing else happens. + $this->exec('polls delete ' . $poll->id . ' --yes'); + $this->assertExitError(); + } + + public function testReminderGoesOutOnceInTheLastDaysBeforeExpiry(): void + { + [$young, $youngToken] = $this->createPoll('Jung', 'jung@example.org'); + [$due, $dueToken] = $this->createPoll('Bald weg', 'bald@example.org'); + [$gone] = $this->createPoll('Abgelaufen', 'weg@example.org'); + $this->age($young->id, 75); + $this->age($due->id, 77); + $this->age($gone->id, 91); + + $this->exec('polls remind --dry-run'); + $this->assertExitSuccess(); + $this->assertOutputContains('bald@example.org'); + $this->assertOutputNotContains('jung@example.org'); + $this->assertOutputNotContains('weg@example.org'); + $this->assertNull($this->pollsTable()->get($due->id)->expiry_reminded_at); + + $this->exec('polls remind'); + $this->assertExitSuccess(); + $this->assertOutputContains('1 Erinnerung(en) verschickt'); + $this->assertNotNull($this->pollsTable()->get($due->id)->expiry_reminded_at); + $this->assertNull($this->pollsTable()->get($young->id)->expiry_reminded_at); + + // Second run: nothing more to send. + $this->exec('polls remind'); + $this->assertOutputContains('0 Erinnerung(en) verschickt'); + + // Reminder switched off. + Configure::write('Plenario.retention.reminderDays', 0); + $this->age($young->id, 80); + $this->exec('polls remind'); + $this->assertOutputContains('Erinnerungen sind aus'); + $this->assertNull($this->pollsTable()->get($young->id)->expiry_reminded_at); + $this->assertNotEmpty($youngToken . $dueToken); + } + + public function testCleanupRemindsThenDeletesOnlyExpiredPollsAndIsIdempotent(): void + { + [$old] = $this->createPoll('Alt'); + [$soon] = $this->createPoll('Bald'); + [$fresh] = $this->createPoll('Frisch'); + $this->createSlide($old); + $this->age($old->id, 91); + $this->age($soon->id, 80); + $this->age($fresh->id, 10); + + $this->exec('polls cleanup --dry-run'); + $this->assertExitSuccess(); + $this->assertSame(3, $this->pollsTable()->find()->count()); + $this->assertNull($this->pollsTable()->get($soon->id)->expiry_reminded_at); + + $this->exec('polls cleanup'); + $this->assertExitSuccess(); + $this->assertEqualsCanonicalizing( + [$soon->id, $fresh->id], + $this->pollsTable()->find()->all()->extract('id')->toList(), + ); + $this->assertNotNull($this->pollsTable()->get($soon->id)->expiry_reminded_at); + $this->assertSame(0, $this->slidesTable()->find()->where(['poll_id' => $old->id])->count()); + + $this->exec('polls cleanup'); + $this->assertExitSuccess(); + $this->assertSame(2, $this->pollsTable()->find()->count()); + } +}