Fix/atomic votes #34
No files matched your search
@@ -51,6 +51,7 @@ config/
|
||||
Migrations/ Schema (einzige Quelle der Wahrheit, auch für Tests)
|
||||
src/
|
||||
Captcha/ CaptchaInterface + NoCaptcha / MathCaptcha / RecaptchaCaptcha, CaptchaFactory
|
||||
Error/RedactingErrorLogger maskiert Admin-Token und Embed-Key in allen Log-Einträgen (`Error.logger` in app.php)
|
||||
Controller/
|
||||
HomeController Startseite, Anlegen (/create), Bestätigung, Join, Recover
|
||||
AdminAppController Basis für /admin/{token}: löst Poll über Token-Hash auf (404 sonst), setzt Privacy-Header
|
||||
@@ -59,7 +60,9 @@ src/
|
||||
YouTube-Link prüfen (`youtubeCheck`, JSON)
|
||||
ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid
|
||||
EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control
|
||||
ErrorController Fehlerseiten (Templates unter templates/Error, Layout `error`)
|
||||
Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal)
|
||||
Middleware/ HostHeaderMiddleware: prüft in Produktion den Host gegen APP_FULL_BASE_URL
|
||||
Model/ Polls → Slides → SlideOptions, Slides → Responses
|
||||
Service/
|
||||
VoteService Validiert + speichert Antworten (alle Abstimmungsregeln hier)
|
||||
@@ -83,7 +86,8 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
|
||||
### Datenmodell
|
||||
|
||||
- `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`, `show_results_to_participants` (ungenutzt, Altlast),
|
||||
`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),
|
||||
`embed_key` (Einbett-Schlüssel), `embed_seen_at` (letztes Lebenszeichen der eingebetteten Live-Folie),
|
||||
`paused_slide_id` (Folie vor der Pause)
|
||||
- `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube|qa|order`), `question`, `description`, `position`,
|
||||
@@ -101,7 +105,8 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
|
||||
### Zentrale Regeln (nicht versehentlich brechen)
|
||||
|
||||
- **Kein Login.** Zugriff auf die Verwaltung = Besitz des Tokens in der URL `/admin/{token}`.
|
||||
Token nie loggen, nie in JSON ausgeben, nie als Referrer leaken (`Referrer-Policy: no-referrer`).
|
||||
Token nie loggen (Fehler-Logs maskiert `RedactingErrorLogger` automatisch; eigene `Log::…`-Aufrufe nie mit URL/Token),
|
||||
nie in JSON ausgeben, nie als Referrer leaken (`Referrer-Policy: no-referrer`).
|
||||
Lookup immer über `PollsTable::hashToken()` / Finder `byAdminToken`.
|
||||
- Admin-Aktionen müssen **immer** auf `$this->poll` eingeschränkt sein (z. B. `SlidesController::loadSlide()`
|
||||
prüft `poll_id`). Neue Admin-Controller von `AdminAppController` ableiten.
|
||||
@@ -172,8 +177,10 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
|
||||
ohne Antworten keinen Sinn ergeben; offen/geschlossen anderer Folien, aktuelle Folie/Pause, Einstellungen bleiben.
|
||||
Idempotent, in einer Transaktion. Tests: `PollResetTest.php`.
|
||||
- **Pause:** `current_slide_id = null` + `paused_slide_id` = Pause (Teilnehmende sehen „Kurze Pause“), ohne
|
||||
`paused_slide_id` = noch nicht gestartet. Immer über `Poll::showSlide()` / `showEmbeddedSlide()` / `pause()` setzen,
|
||||
nie `current_slide_id` direkt. Presenter: P pausiert, ←/→ setzt bei der pausierten Folie fort.
|
||||
`paused_slide_id` = noch nicht gestartet. Immer über `Poll::showSlide()` / `showEmbeddedSlide()` / `pause()` /
|
||||
`forgetSlide()` setzen, nie `current_slide_id` direkt. Presenter: P pausiert, ←/→ setzt bei der pausierten Folie fort.
|
||||
Wird die Live- oder pausierte Folie gelöscht, pausiert die Umfrage und setzt mit der nachrückenden Folie fort
|
||||
(`forgetSlide()`, keine FKs auf `current_slide_id`/`paused_slide_id`, sie dürfen nie auf gelöschte Folien zeigen).
|
||||
- **Einbettung** (`/e/{key}/{id}`, `EmbedController`): eigener `embed_key` statt Admin-Token (darf nur diese Folie zeigen,
|
||||
live schalten, pausieren und `SlideControlService`-Aktionen), wird beim ersten Dashboard-Aufruf erzeugt
|
||||
(`ensureEmbedKey`, idempotent) und lässt sich neu erzeugen. Die Seite schaltet sich live, solange sie sichtbar ist
|
||||
@@ -192,7 +199,7 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
|
||||
`ResultsService::withoutContents()`. Volle Ansicht in der Verwaltung (`slides:answers` → „Auswertung“).
|
||||
- **Skala-Kommentare** (Setting `comments`, `Slide::hasComments()`): optionales Feld `comment`, gespeichert als `text_value`
|
||||
in derselben Zeile wie `numeric_value` (ohne Setting wird es ignoriert). Öffentliche Skalen liefern im Presenter-/Embed-State
|
||||
`results.comments` (Teilnehmende bekommen immer `[]`, `PollStateService::participantResults()`)
|
||||
`results.comments` (Teilnehmende bekommen sie nie: Skalen liefern ihnen grundsätzlich keine `results`, siehe `PollStateService::forParticipant()`)
|
||||
(älteste zuerst, je `id`, `text`, `value` – `value` nur mit Setting `comment_ratings`, sonst `null`); `Comments` in `plenario.js` blättert sie automatisch durch (Sekunden pro Kommentar = Setting `comment_interval`, Auswahl
|
||||
`Slide::COMMENT_INTERVALS`, Standard 8, im State als `results.commentInterval`; „Kommentar X von N“,
|
||||
vor/zurück/Pause, Zustand übersteht das Neu-Rendern beim Polling). Bei internem Feedback erscheinen sie erst,
|
||||
@@ -242,6 +249,9 @@ Kein WebSocket: Presenter (`/admin/{token}/state`) und Teilnehmende (`/p/{code}/
|
||||
- Einrückung 4 Spaces, LF (siehe `.editorconfig`).
|
||||
- Keine neuen Frontend-Abhängigkeiten / kein Build-Schritt ohne Rücksprache.
|
||||
- Schemaänderungen nur per neuer Migration, nie bestehende Migration ändern (sobald deployed).
|
||||
- Beim Löschen nie auf `ON DELETE CASCADE` verlassen: SQLite setzt Fremdschlüssel ohne `PRAGMA foreign_keys = ON`
|
||||
nicht durch (die Test-Suite schaltet sie aber ein, Fehler fallen dort also nicht auf). Abhängige Daten über
|
||||
`dependent` + `cascadeCallbacks` im ORM löschen (z. B. Polls → Slides → SlideOptions/Responses).
|
||||
- Commits klein und thematisch; Commit-Messages auf Englisch im Imperativ.
|
||||
- **`main` ist geschützt:** nie direkt auf `main` committen oder pushen. Jede Änderung auf einem
|
||||
eigenen Branch (z. B. `feature/…`, `fix/…`, `docs/…`), pushen und per Pull Request in Gitea mergen.
|
||||
|
||||
@@ -3,20 +3,34 @@
|
||||
Live-Umfragen für Vorträge, Workshops und Meetings – ähnlich wie Mentimeter oder Claper,
|
||||
aber **ohne Login**: Wer eine Umfrage anlegt, bekommt einen geheimen Admin-Link per E-Mail.
|
||||
|
||||
Basiert auf **CakePHP 5.4** (PHP ≥ 8.2), läuft lokal mit **SQLite**, ohne Build-Schritt fürs Frontend.
|
||||
Basiert auf **CakePHP 5.4** (PHP 8.3 oder neuer, das automatische Deployment verlangt 8.4),
|
||||
läuft lokal mit **SQLite**, ohne Build-Schritt fürs Frontend.
|
||||
|
||||
## Funktionen
|
||||
|
||||
- Umfrage anlegen mit Titel + E-Mail-Adresse, Admin-Link kommt per Mail
|
||||
- Umfrage anlegen mit Titel + E-Mail-Adresse, der Admin-Link kommt per Mail
|
||||
- Optionales Captcha: keins, einfache Rechenaufgabe oder Google reCAPTCHA v2
|
||||
- Folientypen: **Multiple Choice** (Einfach-/Mehrfachauswahl), **Wortwolke**, **Offene Frage**, **Skala**, **Inhaltsfolie**
|
||||
- Präsentationsmodus (Vollbild, Tastatursteuerung, QR-Code, Live-Ergebnisse)
|
||||
- Teilnahme über 6-stelligen Code oder QR-Code, anonym (Cookie), eine Antwort pro Person und Folie
|
||||
- Ergebnisse optional auch für Teilnehmende sichtbar
|
||||
- PDF-Export der Ergebnisse (wahlweise ohne oder mit internem/anonymem Feedback), Antworten zurücksetzen, Folien sortieren
|
||||
- Folientypen:
|
||||
- **Multiple Choice** (Einfach- oder Mehrfachauswahl)
|
||||
- **Wortwolke** – Begriffe einzeln eingeben, vorhandene per Klick unterstützen (optional mit Downvotes)
|
||||
- **Offene Frage** – optional als anonymes Feedback, das nur in der Verwaltung sichtbar ist
|
||||
- **Skala** – optional mit Kommentaren, die in der Präsentation durchlaufen, oder als internes Feedback
|
||||
- **Quiz** – richtige Antwort(en) und Zeitlimit, aufgelöst wird erst am Ende
|
||||
- **Reihenfolge** – Einträge sortieren, aufgelöst wird beim Schließen der Abstimmung
|
||||
- **Fragen & Antworten** – Fragen sammeln, per Upvote priorisieren, nacheinander besprechen
|
||||
- **Inhaltsfolie** und **YouTube-Video** (ohne Abstimmung)
|
||||
- Präsentationsmodus: Vollbild, Tastatursteuerung, QR-Code, Pause, Tag-/Nachtmodus, Live-Ergebnisse
|
||||
- Ergebnisse erscheinen auf der Bühne, nicht auf den Geräten der Teilnehmenden – dort nur, wo sie damit
|
||||
arbeiten (Wortwolke) oder ihre eigene Antwort aufgelöst wird (Quiz, Reihenfolge)
|
||||
- Teilnahme über 6-stelligen Code oder QR-Code, anonym (Cookie); eine Antwort pro Person und Folie
|
||||
(Wortwolke und Fragen & Antworten: mehrere Beiträge pro Person)
|
||||
- **Einbetten** einzelner Folien in andere Präsentationssoftware (z. B. Canva): Die Folie schaltet sich live,
|
||||
sobald sie in der Präsentation sichtbar ist, und pausiert die Umfrage, wenn weitergeblättert wird
|
||||
- PDF-Export der Ergebnisse (wahlweise ohne oder mit internem/anonymem Feedback)
|
||||
- Antworten einer Folie oder der ganzen Umfrage zurücksetzen, Folien per Drag & Drop sortieren
|
||||
- „Admin-Link verloren?“ – schickt alle Links zu einer Adresse erneut
|
||||
- Admin-Link neu erzeugen (alter Link wird ungültig), Umfrage löschen
|
||||
- Rate-Limit für Anlegen und Wiederherstellen pro IP
|
||||
- Admin-Link bzw. Einbett-Links neu erzeugen (alte werden ungültig), Umfrage löschen
|
||||
- Rate-Limits pro IP für Anlegen, Wiederherstellen und Abstimmen
|
||||
|
||||
## Lokal starten
|
||||
|
||||
@@ -31,6 +45,8 @@ Unter Windows ggf. `php bin/cake.php …` statt `bin/cake …`.
|
||||
Lokal werden keine Mails verschickt: Sie landen als `.eml` in `tmp/mails/`. Zusätzlich wird der
|
||||
Admin-Link im Debug-Modus direkt nach dem Anlegen angezeigt.
|
||||
|
||||
Nach neuen Migrationen `bin/cake cache clear_all` ausführen, sonst nutzt das ORM das alte Schema aus dem Cache.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
@@ -41,7 +57,7 @@ vendor/bin/phpcs # CakePHP Coding Standard
|
||||
## Konfiguration
|
||||
|
||||
Alle Einstellungen gehen über Umgebungsvariablen oder `config/.env`
|
||||
(Vorlage: [config/.env.example](config/.env.example)). Wichtig für den Betrieb:
|
||||
(Vorlage mit allen Variablen: [config/.env.example](config/.env.example)). Wichtig für den Betrieb:
|
||||
|
||||
| Variable | Bedeutung |
|
||||
|---|---|
|
||||
@@ -54,16 +70,29 @@ Alle Einstellungen gehen über Umgebungsvariablen oder `config/.env`
|
||||
| `CAPTCHA_TYPE` | `none`, `math` (Standard) oder `recaptcha` |
|
||||
| `RECAPTCHA_SITE_KEY`, `RECAPTCHA_SECRET_KEY` | Für reCAPTCHA v2 („Ich bin kein Roboter“) |
|
||||
| `SHOW_ADMIN_LINK_AFTER_CREATE` | Nur für Entwicklung |
|
||||
| `THROTTLE_CREATE_PER_HOUR`, `THROTTLE_RECOVER_PER_HOUR` | Rate-Limits pro IP (0 = aus) |
|
||||
| `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_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 |
|
||||
|
||||
## Deployment
|
||||
|
||||
**Automatisch (Gitea Actions):** [.gitea/workflows/ci.yml](.gitea/workflows/ci.yml) testet jeden Push.
|
||||
`main` ist geschützt, gemergt wird nur per Pull Request mit grünem Test. Nach dem Merge deployt der Job
|
||||
`deploy` per SSH – aber nur, wenn die Repo-Variable `DEPLOY_ENABLED=true` gesetzt ist. Er holt den Code,
|
||||
führt `composer install --no-dev`, die Migrationen und `cache clear_all` aus. Benötigte Variablen und Secrets
|
||||
stehen im Kopf der Workflow-Datei. Einmalig auf dem Server: `config/.env` anlegen, ohne sie bricht der Deploy ab.
|
||||
|
||||
**Manuell:**
|
||||
|
||||
1. Code auschecken, `composer install --no-dev --optimize-autoloader`
|
||||
2. `config/.env` (oder echte Umgebungsvariablen) setzen, mindestens `DEBUG=false`,
|
||||
`APP_FULL_BASE_URL`, `SECURITY_SALT`, Mail-Transport
|
||||
3. `bin/cake migrations migrate`
|
||||
4. Webserver-Document-Root auf `webroot/` zeigen lassen; `tmp/`, `logs/` und `data/` beschreibbar machen
|
||||
3. `bin/cake migrations migrate` und `bin/cake cache clear_all`
|
||||
4. Document-Root auf `webroot/` zeigen lassen; `tmp/`, `logs/` und `data/` beschreibbar machen.
|
||||
Liegt die App direkt im Document-Root (z. B. `public_html`), leiten `.htaccess` und `index.php`
|
||||
im Projektroot alles nach `webroot/` weiter.
|
||||
|
||||
Live-Updates laufen über kurzes Polling (Standard alle 2 s) – kein WebSocket-Server nötig.
|
||||
Für sehr große Runden (mehrere hundert Teilnehmende) `POLL_INTERVAL_MS` erhöhen und MySQL/PostgreSQL statt SQLite verwenden.
|
||||
@@ -72,7 +101,13 @@ Für sehr große Runden (mehrere hundert Teilnehmende) `POLL_INTERVAL_MS` erhöh
|
||||
|
||||
- Teilnehmende sind anonym. Gespeichert wird nur ein HMAC der Cookie-ID, pro Umfrage unterschiedlich.
|
||||
- Die E-Mail-Adresse dient nur dem Versand der Admin-Links.
|
||||
- In der Datenbank liegt nur der SHA-256-Hash des Admin-Tokens (plus eine mit `SECURITY_SALT` verschlüsselte Kopie für die Wiederherstellungs-Mail).
|
||||
- In der Datenbank liegt nur der SHA-256-Hash des Admin-Tokens (plus eine mit `SECURITY_SALT` verschlüsselte
|
||||
Kopie für die Wiederherstellungs-Mail). In Fehler-Logs werden Admin-Tokens und Einbett-Schlüssel maskiert.
|
||||
- Für die Rate-Limits wird ein Hash der IP-Adresse höchstens eine Stunde im Cache gehalten.
|
||||
- Löschen einer Umfrage entfernt Folien, Optionen und alle Antworten.
|
||||
- Drittanbieter: Mit `CAPTCHA_TYPE=recaptcha` lädt das Formular Google reCAPTCHA (Google erhält u. a. die
|
||||
IP-Adresse). YouTube-Folien werden im Präsentationsmodus über `youtube-nocookie.com` eingebettet;
|
||||
Teilnehmende bekommen nur einen Link. Beides gehört in die Datenschutzerklärung des Betreibers.
|
||||
|
||||
## Für KI-Agents
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Migrations\BaseMigration;
|
||||
|
||||
/**
|
||||
* Removes answer options and responses whose slide no longer exists.
|
||||
*
|
||||
* Deleting a poll used to rely on ON DELETE CASCADE, which SQLite does not enforce
|
||||
* by default, so options and responses of deleted polls could stay behind.
|
||||
* PollsTable now deletes them via the ORM; this cleans up what was left before.
|
||||
* Safe to run repeatedly, a no-op on databases that enforce foreign keys.
|
||||
*/
|
||||
class RemoveOrphanedRows extends BaseMigration
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$this->execute('DELETE FROM responses WHERE slide_id NOT IN (SELECT id FROM slides)');
|
||||
$this->execute('DELETE FROM slide_options WHERE slide_id NOT IN (SELECT id FROM slides)');
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleted rows cannot be restored.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Migrations\BaseMigration;
|
||||
|
||||
/**
|
||||
* polls.show_results_to_participants is unused: results belong on the stage, participants
|
||||
* only get them where they interact with them (see PollStateService). There is no switch per poll.
|
||||
*/
|
||||
class DropShowResultsToParticipants extends BaseMigration
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$table = $this->table('polls');
|
||||
if ($table->hasColumn('show_results_to_participants')) {
|
||||
$table->removeColumn('show_results_to_participants')->update();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
$table = $this->table('polls');
|
||||
if (!$table->hasColumn('show_results_to_participants')) {
|
||||
$table->addColumn('show_results_to_participants', 'boolean', [
|
||||
'null' => false,
|
||||
'default' => true,
|
||||
'after' => 'is_active',
|
||||
])->update();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Error\RedactingErrorLogger;
|
||||
use Cake\Cache\Engine\FileEngine;
|
||||
use Cake\Database\Connection;
|
||||
use Cake\Database\Driver\Sqlite;
|
||||
@@ -236,6 +237,8 @@ return [
|
||||
'trace' => true,
|
||||
'ignoredDeprecationPaths' => [],
|
||||
'traceFormat' => null,
|
||||
// Masks admin tokens and embed keys in logged URLs and messages.
|
||||
'logger' => RedactingErrorLogger::class,
|
||||
],
|
||||
|
||||
/*
|
||||
|
||||
@@ -13,11 +13,6 @@ use Cake\Http\ServerRequest;
|
||||
*/
|
||||
interface CaptchaInterface
|
||||
{
|
||||
/**
|
||||
* @return string 'none' | 'math' | 'recaptcha'
|
||||
*/
|
||||
public function getType(): string;
|
||||
|
||||
/**
|
||||
* Prepares a challenge and returns the data the view element needs.
|
||||
*
|
||||
|
||||
@@ -22,14 +22,6 @@ class MathCaptcha implements CaptchaInterface
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return 'math';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
|
||||
@@ -10,14 +10,6 @@ use Cake\Http\ServerRequest;
|
||||
*/
|
||||
class NoCaptcha implements CaptchaInterface
|
||||
{
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
|
||||
@@ -34,14 +34,6 @@ class RecaptchaCaptcha implements CaptchaInterface
|
||||
$this->client = $client ?? new Client(['timeout' => 5]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return 'recaptcha';
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
|
||||
@@ -71,8 +71,7 @@ class HomeController extends AppController
|
||||
$this->request->allowMethod(['post']);
|
||||
$captcha = CaptchaFactory::create('create');
|
||||
|
||||
$poll = $this->Polls->newEmptyEntity();
|
||||
$poll = $this->Polls->patchEntity($poll, (array)$this->request->getData(), ['fields' => ['title', 'email']]);
|
||||
$poll = $this->Polls->newPoll((array)$this->request->getData());
|
||||
|
||||
if ($this->isHoneypotFilled()) {
|
||||
$this->Flash->error(__('Die Umfrage konnte nicht angelegt werden.'));
|
||||
@@ -81,7 +80,7 @@ class HomeController extends AppController
|
||||
} elseif (!$poll->hasErrors() && !$this->throttle('create', 'Plenario.throttle.createPerHour')) {
|
||||
$this->Flash->error(__('Zu viele Umfragen in kurzer Zeit. Bitte versuche es später noch einmal.'));
|
||||
} elseif (!$poll->hasErrors()) {
|
||||
[$poll, $token] = $this->Polls->createPoll((array)$this->request->getData());
|
||||
[$poll, $token] = $this->Polls->insertPoll($poll);
|
||||
if ($token !== null) {
|
||||
$adminUrl = Router::url(['_name' => 'admin', 'token' => $token], true);
|
||||
$joinUrl = Router::url(['_name' => 'participate', 'code' => $poll->join_code], true);
|
||||
|
||||
@@ -41,7 +41,6 @@ class SlidesController extends AdminAppController
|
||||
$slide = $this->Slides->newEntity(['type' => $type, 'settings' => Slide::DEFAULT_SETTINGS[$type]], [
|
||||
'validate' => false,
|
||||
]);
|
||||
$slide->setNew(true);
|
||||
$slide->poll_id = $this->poll->id;
|
||||
// A quiz is started by the presenter (that also starts its timer).
|
||||
$slide->is_voting_open = $type !== Slide::TYPE_QUIZ;
|
||||
@@ -105,12 +104,22 @@ class SlidesController extends AdminAppController
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$slide = $this->loadSlide($id);
|
||||
if ($this->poll->current_slide_id === $slide->id) {
|
||||
$this->poll->current_slide_id = null;
|
||||
// Deleting the live (or paused) slide pauses the poll; → resumes with the slide taking its place.
|
||||
$ids = $this->Slides->find()
|
||||
->select(['id'])
|
||||
->where(['poll_id' => $this->poll->id])
|
||||
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
|
||||
->all()
|
||||
->extract('id')
|
||||
->toList();
|
||||
$index = (int)array_search($slide->id, $ids, true);
|
||||
$this->poll->forgetSlide($slide->id, $ids[$index + 1] ?? $ids[$index - 1] ?? null);
|
||||
|
||||
$this->Slides->getConnection()->transactional(function () use ($slide): void {
|
||||
$this->Polls->saveOrFail($this->poll);
|
||||
}
|
||||
$this->Slides->deleteOrFail($slide);
|
||||
$this->Slides->normalizePositions($this->poll->id);
|
||||
});
|
||||
$this->Flash->success(__('Folie gelöscht.'));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Error;
|
||||
|
||||
use Cake\Error\ErrorLogger;
|
||||
use Stringable;
|
||||
|
||||
/**
|
||||
* Error logger that never writes secrets from URLs to the log.
|
||||
*
|
||||
* The admin token (/admin/{token}) and the embed key (/e/{key}) are the only
|
||||
* authorisation of PlenarIO. CakePHP logs the request URL, the referer and
|
||||
* exception messages (e.g. "A route matching /admin/… could not be found"),
|
||||
* so every message is redacted before it is written.
|
||||
* Configured via `Error.logger` in config/app.php.
|
||||
*/
|
||||
class RedactingErrorLogger extends ErrorLogger
|
||||
{
|
||||
/**
|
||||
* Same character set and length as the token/key route patterns in config/routes.php.
|
||||
*/
|
||||
protected const PATTERN = '#/(admin|e)/[A-Za-z0-9_-]{20,64}(?=[/?\#"\'\s]|$)#m';
|
||||
|
||||
public const PLACEHOLDER = '[redacted]';
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function log($level, Stringable|string $message, array $context = []): void
|
||||
{
|
||||
parent::log($level, static::redact((string)$message), $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces admin tokens and embed keys in URLs with a placeholder.
|
||||
*
|
||||
* @param string $message Log message
|
||||
* @return string
|
||||
*/
|
||||
public static function redact(string $message): string
|
||||
{
|
||||
return (string)preg_replace(self::PATTERN, '/$1/' . self::PLACEHOLDER, $message);
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,24 @@ class Poll extends Entity
|
||||
$this->embed_seen_at = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A slide is being deleted. If it was live or is the one a pause resumes, the poll pauses
|
||||
* and resumes with $resumeSlideId instead (null: no slides left = not started). Idempotent.
|
||||
*
|
||||
* @param int $slideId Deleted slide
|
||||
* @param int|null $resumeSlideId Slide that takes its place (must belong to this poll)
|
||||
* @return void
|
||||
*/
|
||||
public function forgetSlide(int $slideId, ?int $resumeSlideId): void
|
||||
{
|
||||
if ($this->current_slide_id !== $slideId && $this->paused_slide_id !== $slideId) {
|
||||
return;
|
||||
}
|
||||
$this->current_slide_id = null;
|
||||
$this->paused_slide_id = $resumeSlideId;
|
||||
$this->embed_seen_at = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool Paused after a slide had been live (not: not started yet)
|
||||
*/
|
||||
|
||||
@@ -48,7 +48,9 @@ class PollsTable extends Table
|
||||
'foreignKey' => 'poll_id',
|
||||
'sort' => ['Slides.position' => 'ASC', 'Slides.id' => 'ASC'],
|
||||
'dependent' => true,
|
||||
'cascadeCallbacks' => false,
|
||||
// Delete slide by slide so their options and responses go too. Do not rely on
|
||||
// ON DELETE CASCADE: SQLite does not enforce foreign keys by default.
|
||||
'cascadeCallbacks' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -182,6 +184,22 @@ class PollsTable extends Table
|
||||
return (string)preg_replace('/[^A-Z0-9]/', '', strtoupper($code));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds and validates a new, not yet saved poll from form input (title + email, normalised).
|
||||
*
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @return \App\Model\Entity\Poll Check getErrors()
|
||||
*/
|
||||
public function newPoll(array $data): Poll
|
||||
{
|
||||
$field = fn(string $key): string => is_scalar($data[$key] ?? null) ? trim((string)$data[$key]) : '';
|
||||
|
||||
return $this->newEntity([
|
||||
'title' => $field('title'),
|
||||
'email' => strtolower($field('email')),
|
||||
], ['fields' => ['title', 'email']]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and persists a new poll.
|
||||
*
|
||||
@@ -190,11 +208,17 @@ class PollsTable extends Table
|
||||
*/
|
||||
public function createPoll(array $data): array
|
||||
{
|
||||
$poll = $this->newEntity([
|
||||
'title' => trim((string)($data['title'] ?? '')),
|
||||
'email' => strtolower(trim((string)($data['email'] ?? ''))),
|
||||
], ['fields' => ['title', 'email']]);
|
||||
return $this->insertPoll($this->newPoll($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns token and join code and saves a poll built by newPoll().
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll New poll
|
||||
* @return array{0: \App\Model\Entity\Poll, 1: string|null} The entity (check getErrors()) and the plain token on success
|
||||
*/
|
||||
public function insertPoll(Poll $poll): array
|
||||
{
|
||||
if ($poll->hasErrors()) {
|
||||
return [$poll, null];
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
* 'min', 'max', 'minLabel', 'maxLabel', 'private' (bool);
|
||||
* 'comments' => [['id', 'text', 'value' (int|null)]] oldest first (only with the comment field, else [];
|
||||
* 'value' is null unless the setting comment_ratings is on;
|
||||
* presentation only, emptied for participants in PollStateService);
|
||||
* presentation only: participants never get results of scale slides, see PollStateService);
|
||||
* 'commentInterval' => int seconds per comment while they rotate;
|
||||
* open/scale with 'private' (anonymous/internal feedback): contents are included for the
|
||||
* presenter/embed, which start with the results hidden and may show them on demand;
|
||||
@@ -332,7 +332,7 @@ class ResultsService
|
||||
|
||||
/**
|
||||
* Results of a private slide without its contents: only type, participants and the scale range.
|
||||
* Used where internal feedback must not appear (participants, public PDF export).
|
||||
* Used where internal feedback must not appear (public PDF export, see ReportService).
|
||||
*
|
||||
* @param array<string, mixed> $results Result of forSlide()
|
||||
* @return array<string, mixed>
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.4
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\View;
|
||||
|
||||
/**
|
||||
* A view class that is used for AJAX responses.
|
||||
* Currently only switches the default layout and sets the response type -
|
||||
* which just maps to text/html by default.
|
||||
*/
|
||||
class AjaxView extends AppView
|
||||
{
|
||||
/**
|
||||
* The name of the layout file to render the view inside of. The name
|
||||
* specified is the filename of the layout in /templates/Layout without
|
||||
* the .php extension.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $layout = 'ajax';
|
||||
|
||||
/**
|
||||
* Initialization hook method.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
|
||||
$this->response = $this->response->withType('ajax');
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
|
||||
echo $this->fetch('content');
|
||||
@@ -5,7 +5,9 @@ namespace App\Test\TestCase\Controller;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\PollsTable;
|
||||
use App\Service\VoteService;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\Database\Driver\Sqlite;
|
||||
use Cake\TestSuite\EmailTrait;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
@@ -180,6 +182,44 @@ class AdminControllerTest extends TestCase
|
||||
$this->assertSame(2, $this->slidesTable()->get($third->id)->position);
|
||||
}
|
||||
|
||||
public function testDeletingTheLiveSlidePausesAndResumesWithTheNextOne(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$first = $this->createSlide($poll, Slide::TYPE_OPEN);
|
||||
$second = $this->createSlide($poll, Slide::TYPE_SCALE);
|
||||
$third = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$poll = $this->goLive($poll, $second);
|
||||
|
||||
$this->post("/admin/$token/slides/{$second->id}/delete");
|
||||
$poll = $this->pollsTable()->get($poll->id);
|
||||
$this->assertTrue($poll->isPaused(), 'Participants see the pause page.');
|
||||
$this->assertSame($third->id, $poll->paused_slide_id);
|
||||
|
||||
// The paused slide is deleted as well: resume with the previous one (last slide).
|
||||
$this->post("/admin/$token/slides/{$third->id}/delete");
|
||||
$poll = $this->pollsTable()->get($poll->id);
|
||||
$this->assertTrue($poll->isPaused());
|
||||
$this->assertSame($first->id, $poll->paused_slide_id);
|
||||
|
||||
// No slides left: back to "not started".
|
||||
$this->post("/admin/$token/slides/{$first->id}/delete");
|
||||
$poll = $this->pollsTable()->get($poll->id);
|
||||
$this->assertNull($poll->current_slide_id);
|
||||
$this->assertNull($poll->paused_slide_id);
|
||||
$this->assertFalse($poll->isPaused());
|
||||
}
|
||||
|
||||
public function testDeletingAnotherSlideKeepsTheLiveOne(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$live = $this->createSlide($poll, Slide::TYPE_OPEN);
|
||||
$other = $this->createSlide($poll, Slide::TYPE_SCALE);
|
||||
$poll = $this->goLive($poll, $live);
|
||||
|
||||
$this->post("/admin/$token/slides/{$other->id}/delete");
|
||||
$this->assertSame($live->id, $this->pollsTable()->get($poll->id)->current_slide_id);
|
||||
}
|
||||
|
||||
public function testReorderSlidesByDragAndDrop(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
@@ -284,6 +324,36 @@ class AdminControllerTest extends TestCase
|
||||
$this->assertFalse($this->pollsTable()->exists(['id' => $poll->id]));
|
||||
}
|
||||
|
||||
public function testDeletePollRemovesOptionsAndResponses(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$poll = $this->goLive($poll, $slide);
|
||||
(new VoteService())->submit($poll, $slide, 'participant', ['option_id' => $slide->slide_options[0]->id]);
|
||||
$options = $this->fetchTable('SlideOptions');
|
||||
$responses = $this->fetchTable('Responses');
|
||||
$this->assertTrue($responses->exists(['slide_id' => $slide->id]));
|
||||
|
||||
// A normal SQLite connection does not enforce foreign keys (the test suite turns them on),
|
||||
// so deleting must not rely on ON DELETE CASCADE.
|
||||
$connection = $responses->getConnection();
|
||||
$sqlite = $connection->getDriver() instanceof Sqlite;
|
||||
if ($sqlite) {
|
||||
$connection->execute('PRAGMA foreign_keys = OFF');
|
||||
}
|
||||
try {
|
||||
$this->post("/admin/$token/delete", ['confirm_code' => $poll->join_code]);
|
||||
} finally {
|
||||
if ($sqlite) {
|
||||
$connection->execute('PRAGMA foreign_keys = ON');
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertFalse($this->slidesTable()->exists(['id' => $slide->id]));
|
||||
$this->assertFalse($options->exists(['slide_id' => $slide->id]), 'Options must not outlive their poll.');
|
||||
$this->assertFalse($responses->exists(['slide_id' => $slide->id]), 'Responses must not outlive their poll.');
|
||||
}
|
||||
|
||||
public function testQrAndExport(): void
|
||||
{
|
||||
[, $token] = $this->createPoll();
|
||||
|
||||
@@ -70,6 +70,17 @@ class HomeControllerTest extends TestCase
|
||||
$this->assertResponseNotContains('/admin/', 'Admin link must not be shown when disabled');
|
||||
}
|
||||
|
||||
public function testCreateAcceptsEmailWithSurroundingSpaces(): void
|
||||
{
|
||||
$this->session(['Captcha.math.create' => 7]);
|
||||
$this->post('/create', ['title' => ' Retro ', 'email' => ' Owner@Example.org ', 'captcha_answer' => '7']);
|
||||
|
||||
$this->assertRedirect(['_name' => 'created']);
|
||||
$poll = $this->pollsTable()->find()->firstOrFail();
|
||||
$this->assertSame('Retro', $poll->title);
|
||||
$this->assertSame('owner@example.org', $poll->email);
|
||||
}
|
||||
|
||||
public function testIndexRendersHiddenHoneypot(): void
|
||||
{
|
||||
$this->get('/');
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Error;
|
||||
|
||||
use App\Error\RedactingErrorLogger;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\Log\Engine\ArrayLog;
|
||||
use Cake\Log\Log;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* Admin tokens and embed keys must never end up in the error log.
|
||||
*/
|
||||
class RedactingErrorLoggerTest extends TestCase
|
||||
{
|
||||
use IntegrationTestTrait;
|
||||
use PlenarioTestTrait;
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Log::drop('error');
|
||||
Log::setConfig('error', ['className' => ArrayLog::class, 'levels' => ['warning', 'error', 'critical', 'alert', 'emergency']]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Log::drop('error');
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testRedactsTokensAndKeys(): void
|
||||
{
|
||||
$token = str_repeat('a', 20) . '-_B9';
|
||||
$message = "Request URL: /admin/$token/slides/5/edit\n"
|
||||
. "Referer URL: https://example.org/e/$token/12\n"
|
||||
. "A route matching \"/admin/$token?x=1\" could not be found.\n"
|
||||
. "Request URL: /admin/$token";
|
||||
|
||||
$redacted = RedactingErrorLogger::redact($message);
|
||||
|
||||
$this->assertStringNotContainsString($token, $redacted);
|
||||
$this->assertStringContainsString('/admin/[redacted]/slides/5/edit', $redacted);
|
||||
$this->assertStringContainsString('/e/[redacted]/12', $redacted);
|
||||
$this->assertStringContainsString('"/admin/[redacted]?x=1"', $redacted);
|
||||
}
|
||||
|
||||
public function testLeavesOtherUrlsAlone(): void
|
||||
{
|
||||
$message = 'Request URL: /p/K7P2QX/state and /admin/short';
|
||||
|
||||
$this->assertSame($message, RedactingErrorLogger::redact($message));
|
||||
}
|
||||
|
||||
public function testErrorLogNeverContainsTheAdminToken(): void
|
||||
{
|
||||
[, $token] = $this->createPoll();
|
||||
|
||||
$this->get("/admin/$token/slides/999999/edit");
|
||||
$this->assertResponseCode(404);
|
||||
|
||||
$logs = implode("\n", Log::engine('error')->read());
|
||||
$this->assertStringContainsString('/admin/[redacted]/slides/999999/edit', $logs);
|
||||
$this->assertStringNotContainsString($token, $logs);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user