Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
85627b364d | ||
|
|
2c0b8d2216
|
||
|
|
59ce3e3e10 | ||
|
|
74b69f3c9a
|
||
|
|
99fcfec165
|
||
|
|
446617de6f
|
||
|
|
fc28d158cb
|
||
|
|
9d682fa0a3
|
||
|
|
b61bf34a1b
|
||
|
|
0c97f61763 | ||
|
|
66ed198f87
|
||
|
|
a07a9a1a34 | ||
|
|
72b688186f
|
||
|
|
8262411225 | ||
|
|
7fa33bbbdd
|
||
|
|
6f20ddf5f7 | ||
|
|
f21aead039
|
||
|
|
4f03414d7a | ||
|
|
872a211afa | ||
|
|
1ceac5ee68
|
||
|
|
82b352c053
|
||
|
|
514ab050a7 | ||
|
|
3d6ade668f
|
||
|
|
349359dad3
|
||
|
|
664088e139 | ||
|
|
e3f74e375f
|
||
|
|
bd401ed94a | ||
|
|
7b83cf2f2c
|
||
|
|
6e8fef022b
|
||
|
|
f0b5f7b2bb | ||
|
|
af15cee1a2 | ||
|
|
87ecdff54e
|
||
|
|
cbb24111ff
|
||
|
|
37f02fa1dc
|
||
|
|
f7fe4a47aa
|
||
|
|
ae57bf1352
|
||
|
|
d690f16673
|
||
|
|
b811294065
|
||
|
|
a19cd8339e
|
||
|
|
3c07eba7db | ||
|
|
4caff47a09
|
||
|
|
33c75e504f
|
||
|
|
8522918c75
|
||
|
|
492872750c | ||
|
|
a395b50894
|
||
|
|
f887b99a1e | ||
|
|
8c7818ee40
|
||
|
|
a633ac6f23 | ||
|
|
06a1171bf5 | ||
|
|
3ba6e3e7ad
|
||
|
|
9c6a19f0de
|
||
|
|
355a22384b | ||
|
|
0eb054ed29
|
||
|
|
e4622b439e
|
||
|
|
3c66597696 | ||
|
|
97a60290b4
|
||
|
|
7be66fa5e4 | ||
|
|
61718ed7c6
|
||
|
|
303431c02b | ||
|
|
28bfd535f4
|
No files matched your search
@@ -85,9 +85,9 @@ jobs:
|
||||
index.php .htaccess composer.json composer.lock | tar -x -C build
|
||||
cd "build/$NAME"
|
||||
rm -f bin/cake.bat bin/bash_completion.sh
|
||||
# --no-scripts: the installer must not bake a random salt into app_local.php (SECURITY_SALT comes from config/.env)
|
||||
# --no-scripts: no app_local.php in the package; everything comes from config/.env (see app_local.example.php)
|
||||
composer install --no-dev --no-scripts --no-interaction --no-progress --prefer-dist --optimize-autoloader
|
||||
cp config/app_local.example.php config/app_local.php
|
||||
rm -f config/app_local.example.php
|
||||
mkdir -p tmp/cache/models tmp/cache/persistent tmp/cache/views tmp/sessions logs data
|
||||
printf '%s\n' "$VERSION" > VERSION
|
||||
cd ../..
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
/webroot/bake
|
||||
# SQLite-Backups aus der Deploy-Pipeline
|
||||
/data/backups/
|
||||
# Folienbilder (UPLOADS_PATH)
|
||||
/data/uploads/
|
||||
# Composer
|
||||
/composer.phar
|
||||
# Test-/Analyse-Artefakte
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# AGENTS.md – Infos für KI-Agents
|
||||
|
||||
Diese Datei ist die zentrale Arbeitsgrundlage für KI-Agents (Claude Code, Codex, Cursor, …).
|
||||
**Halte sie aktuell**, wenn du Architektur, Konventionen, Routen, Konfiguration oder Befehle änderst.
|
||||
**Halte sie und `docs/` aktuell**, wenn du Architektur, Konventionen, Routen, Konfiguration oder Befehle änderst.
|
||||
Lokale, maschinenspezifische Infos gehören in `CLAUDE.local.md` (nicht versioniert).
|
||||
|
||||
## Rolle & Arbeitsweise
|
||||
@@ -33,6 +33,8 @@ E-Mail anlegen, kein Login, Verwaltung über einen geheimen Admin-Link, Teilnahm
|
||||
| Tests | `vendor/bin/phpunit` |
|
||||
| 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 [docs/operations.md](docs/operations.md)) |
|
||||
|
||||
**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).
|
||||
@@ -40,74 +42,46 @@ E-Mail anlegen, kein Login, Verwaltung über einen geheimen Admin-Link, Teilnahm
|
||||
Zum manuellen Testen im Browser bzw. per HTTP den Cake-Dev-Server nutzen (`bin/cake server`).
|
||||
Mails landen lokal als `.eml` in `tmp/mails/`; im Debug-Modus zeigt `/created` den Admin-Link direkt an.
|
||||
|
||||
## Architektur
|
||||
## Weitere Dokumentation (`docs/`)
|
||||
|
||||
Hier stehen nur Überblick und Regeln, die nie gebrochen werden dürfen. **Wer einen Bereich ändert, liest vorher das
|
||||
passende Dokument und pflegt es danach** (Details zu Verhalten, Settings, Tests und Fallstricken):
|
||||
|
||||
| Bereich | Dokument |
|
||||
|---|---|
|
||||
| Lokal starten, Tests, Mitarbeit | [docs/development.md](docs/development.md) |
|
||||
| Verzeichnisstruktur, Klassen, Tabellen | [docs/architecture.md](docs/architecture.md) |
|
||||
| Folientypen (Wortwolke, Quiz, Q&A, Reihenfolge, YouTube, Skala/Sterne, Kommentare), Checkliste „Neuen Folientyp hinzufügen“ | [docs/slide-types.md](docs/slide-types.md) |
|
||||
| Folienbilder (Upload, Ablage, Löschen) | [docs/images.md](docs/images.md) |
|
||||
| Live-Schaltung, Referentenansicht, Pause, Ausblenden, Zurücksetzen, Duplizieren, Einbettung, internes Feedback | [docs/presenter.md](docs/presenter.md) |
|
||||
| Dashboard-Fragmente, Farbschema, Textformatierung, Vollbild | [docs/frontend.md](docs/frontend.md) |
|
||||
| PDF-Export | [docs/pdf-export.md](docs/pdf-export.md) |
|
||||
| Ablauf/Cleanup von Umfragen, CI/Deploy, Releases, Docker | [docs/operations.md](docs/operations.md) |
|
||||
| Betreiber-Anleitung (Docker, Cronjob, Releases) und Umgebungsvariablen | [docs/deployment.md](docs/deployment.md), [docs/configuration.md](docs/configuration.md) |
|
||||
|
||||
## Architektur in Kürze
|
||||
|
||||
```
|
||||
config/
|
||||
app.php Defaults inkl. Block 'Plenario' (Captcha, Throttle, Polling) und Cache 'throttle'
|
||||
app_local.example.php Vorlage für app_local.php (SQLite, FileTransport) – app_local.php ist gitignored
|
||||
.env.example Alle Umgebungsvariablen (config/.env wird optional geladen)
|
||||
routes.php Alle Routen benannt, KEINE Fallback-Routen
|
||||
Migrations/ Schema (einzige Quelle der Wahrheit, auch für Tests)
|
||||
config/ app.php (Block 'Plenario'), app_local.php (nur lokal, gitignored; Produktion nur .env), .env.example,
|
||||
routes.php (alle Routen benannt, KEINE Fallbacks), Migrations/ (Schema = einzige Quelle der Wahrheit)
|
||||
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/
|
||||
AppController Basis aller Controller: `joinUrl()`, `adminUrlFor()`, `setPollInterval()`, `throttle()`, `json()`,
|
||||
`protect()` (no-referrer/noindex/no-store für Seiten mit Geheimnis in der URL: Admin, Embed)
|
||||
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 (no-referrer, no-store)
|
||||
AdminController Dashboard, Settings, Present, State-JSON, Control, QR, PDF-Export, Token rotieren, Zurücksetzen, Löschen
|
||||
SlidesController Folien-CRUD, Ein-/Ausblenden (`visibility`), Duplizieren (`duplicate` → `SlidesTable::duplicate()`, Kopie direkt dahinter, öffnet das Formular der Kopie), Antworten offener Fragen bzw. Skala-Auswertung (`answers`), Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen,
|
||||
YouTube-Link prüfen (`youtubeCheck`, JSON)
|
||||
ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen, eigene Antwort/Kommentar bearbeiten; 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; `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
|
||||
für alle Antworten inkl. JSON und Fehlerseiten; vom Controller gesetzte Header gewinnen
|
||||
Model/ Polls → Slides → SlideOptions, Slides → Responses
|
||||
Service/
|
||||
VoteService Validiert + speichert Antworten (alle Abstimmungsregeln hier)
|
||||
ResultsService Aggregiert Ergebnisse je Folientyp (JSON-Struktur im Docblock)
|
||||
PollStateService State-JSON für Presenter und Teilnehmende
|
||||
ThrottleService Rate-Limit pro IP (Cache 'throttle'), in Controllern über `AppController::throttle()`:
|
||||
Anlegen/Recover pro Stunde, Antworten (`vote`) pro Minute (`THROTTLE_VOTES_PER_MINUTE`, 429)
|
||||
YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client)
|
||||
QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen
|
||||
SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam)
|
||||
ResetService Antworten löschen: einzelne Folie (`slide`) bzw. alle Folien der Umfrage (`poll`)
|
||||
ReportService Daten für den PDF-Export: Ergebnisse aller interaktiven Folien, mit/ohne interne Inhalte
|
||||
View/PdfView.php Rendert Template als HTML (Layout `pdf`) und wandelt es mit Dompdf in ein PDF
|
||||
templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email
|
||||
webroot/css/plenario.css Eigenes CSS, kein Framework; Farben nur als Tokens (Hell/Dunkel, siehe Theme unten)
|
||||
webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Sortieren (`makeSortable`: Pointer Events + Pfeiltasten,
|
||||
genutzt für Folienliste, Reihenfolge-Editor und Teilnehmer-Antwort)
|
||||
tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures sind leer
|
||||
Controller/ AppController (Basis), Home, Admin (+ AdminAppController), Slides, Participate, Embed, Error
|
||||
Service/ VoteService, ResultsService, PollStateService, ThrottleService, ImageService, YouTubeService,
|
||||
QaService, SlideControlService, ResetService, ReportService
|
||||
Model/ Polls → Slides → SlideOptions, Slides → Responses
|
||||
Middleware/ HostHeader, SecurityHeaders (CSP mit Nonce, Framing, Referrer-Policy)
|
||||
Command/ images_cleanup, polls list|show|delete|remind|cleanup
|
||||
Mailer/ PollMailer
|
||||
templates/ Deutsche UI; Layouts: default, present, error, email, fragment, pdf
|
||||
webroot/ css/plenario.css (eigenes CSS, Tokens), js/plenario.js (Vanilla JS)
|
||||
tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures sind leer
|
||||
```
|
||||
|
||||
### Datenmodell
|
||||
Folientypen: `choice|wordcloud|open|scale|content|quiz|youtube|qa|order`. Live-Updates: kein WebSocket, Presenter und
|
||||
Teilnehmende pollen per `fetch` (`Plenario.pollIntervalMs`), die Teilnehmerseite lädt bei geänderter `version` neu.
|
||||
Vollständige Struktur und Datenmodell: [docs/architecture.md](docs/architecture.md).
|
||||
|
||||
- `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),
|
||||
`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`,
|
||||
`is_hidden` (ausgeblendet: vorbereitet, aber nicht Teil der Präsentation),
|
||||
`settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open`,
|
||||
`voting_started_at` / `voting_ends_at` (nur Quiz: Start und Deadline, `null` = manuell beenden),
|
||||
`stage` / `focus_response_id` (nur Q&A: Phase und gerade besprochene Frage)
|
||||
- `slide_options`: Antwortoptionen für `choice`, `quiz` und `order`; `is_correct` markiert richtige Quiz-Antworten,
|
||||
bei `order` ist `position` die richtige Reihenfolge
|
||||
- `responses`: `participant_hash`, `slide_option_id` | `text_value` | `numeric_value` | `parent_id`.
|
||||
Mehrfachauswahl/mehrere Wörter = mehrere Zeilen mit gleichem `participant_hash`.
|
||||
Q&A: Frage = Zeile mit `text_value`, Upvote = Zeile mit `parent_id` (= id der Frage, FK mit CASCADE).
|
||||
Reihenfolge: eine Zeile pro Person, `text_value` = Options-ids kommagetrennt (`VoteService::parseOrder()`).
|
||||
Skala: `numeric_value`, optional Kommentar in `text_value`.
|
||||
|
||||
### Zentrale Regeln (nicht versehentlich brechen)
|
||||
## Zentrale Regeln (nicht versehentlich brechen)
|
||||
|
||||
- **Kein Login.** Zugriff auf die Verwaltung = Besitz des Tokens in der URL `/admin/{token}`.
|
||||
Token nie loggen (Fehler-Logs maskiert `RedactingErrorLogger` automatisch; eigene `Log::…`-Aufrufe nie mit URL/Token),
|
||||
@@ -128,193 +102,23 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures
|
||||
Reihenfolge nach dem Schließen) – dann nur die Lösung **ohne** Zählungen/Verteilung (`PollStateService::participantResults()`
|
||||
entfernt `count`, `percent`, `placed`, `correctCount`; die JS-Renderer erkennen daran die Teilnehmeransicht).
|
||||
Q&A nutzt eigenes `qa`. Es gibt keinen Schalter dafür pro Umfrage.
|
||||
- Ausnahme Wortwolke: Begriffe werden einzeln abgegeben (AJAX, `vote` liefert dann JSON `{ok, message, state}`),
|
||||
jeder Begriff einmal pro Person, beliebig viele Begriffe. Einen vorhandenen Begriff erneut nennen
|
||||
bzw. in der Wolke anklicken = Upvote (gleiche Zeile in `responses`). Mit `allow_upvotes` sehen Teilnehmende
|
||||
die Wolke live; Vorschläge inkl. Kölner Phonetik in `plenario.js` (`Words`).
|
||||
Downvotes (`vote=down`, Setting `allow_downvotes`, nur zusammen mit Upvotes): Zeile mit `numeric_value = VoteService::DOWNVOTE` (-1),
|
||||
nur auf fremde, vorhandene Begriffe, ein Rating pro Begriff und Person.
|
||||
Wortgröße richtet sich nur nach den Upvotes (`count`), Downvotes stehen separat in `down`.
|
||||
`vote=remove` nimmt den eigenen Eintrag zu einem Begriff zurück (genannt/Upvote oder Downvote, `VoteService::removeWord()`,
|
||||
löscht nur Zeilen mit dem eigenen `participant_hash`); Tippfehler = entfernen und neu eingeben, kein Bearbeiten (die Zeile
|
||||
ist zugleich die Stimme). Teilnehmende bekommen dafür `words.own` (eigene Begriffe wie eingegeben) und sehen sie als Chips mit „ד.
|
||||
- Quiz: Phasen `ready` → `running` → `finished` (`Slide::quizPhase()`). Neue Quiz-Folien starten geschlossen;
|
||||
erst der Presenter startet (`control` open/toggle → `Slide::setVotingOpen()` setzt Start + Deadline aus
|
||||
`time_limit`, erneutes Öffnen eines laufenden Quiz startet den Timer nicht neu). „Offen“ heißt immer
|
||||
`Slide::isVotingOpen()` (inkl. Deadline), nicht nur `is_voting_open`. Abgelaufene Quizze schließt
|
||||
`SlidesTable::closeIfExpired()` beim State-Abruf. **Zählungen und `is_correct` dürfen vor `finished` nie im
|
||||
JSON/HTML landen** (weder Presenter noch Teilnehmende); danach sehen Teilnehmende die Lösung und ob sie
|
||||
richtig lagen (ohne Verteilung). Zurücksetzen setzt das Quiz wieder auf `ready`.
|
||||
- **Quiz:** Zählungen und `is_correct` dürfen vor `finished` nie im JSON/HTML landen (weder Presenter noch Teilnehmende);
|
||||
„offen“ heißt immer `Slide::isVotingOpen()`, nicht nur `is_voting_open`. Details: [docs/slide-types.md](docs/slide-types.md).
|
||||
- **Reihenfolge:** richtige Reihenfolge und Zählungen erst nach dem Schließen der Abstimmung im JSON.
|
||||
- **Pause/Live-Folie:** `current_slide_id`/`paused_slide_id` nur über `Poll::showSlide()` / `showEmbeddedSlide()` / `pause()` /
|
||||
`forgetSlide()` setzen, nie direkt. Details: [docs/presenter.md](docs/presenter.md).
|
||||
- `Poll`/`Response` haben `_hidden` für sensible Felder; mass assignment über `_accessible` restriktiv halten.
|
||||
- Alle POST-Formulare laufen über CSRF (`CsrfProtectionMiddleware`). JS sendet `X-CSRF-Token` aus `<meta name="csrf-token">`.
|
||||
Ausnahme: Embed-Routen (siehe [docs/presenter.md](docs/presenter.md)).
|
||||
- Ausgaben in Templates immer mit `h()` escapen. JS baut DOM mit `textContent`, nie `innerHTML` mit Nutzerdaten.
|
||||
- **CSP:** keine Inline-Event-Handler (`onclick=` …) und kein `eval`; Verhalten per `data-*`-Attribut in `plenario.js`.
|
||||
Skripte über `$this->Html->script()` (bekommt die Nonce automatisch); ein unvermeidbares Inline-`<script>` braucht
|
||||
`nonce` aus dem Request-Attribut `cspScriptNonce` (Beispiel: `element/theme_init`). Neue externe Quellen (Skripte,
|
||||
Iframes) in `SecurityHeadersMiddleware::policy()` freigeben. Inline-`style`-Attribute sind erlaubt.
|
||||
Bestätigungs-Buttons: `Form->postButton()` + `data-confirm`, nie `postLink` mit `confirm`.
|
||||
- Routen nur benannt verwenden (`['_name' => 'admin', 'token' => $adminToken]`), keine Fallbacks einführen.
|
||||
|
||||
- Q&A-Folie (`qa`, „Fragen & Antworten“): Phasen `collect` → `vote` → `discuss` (`Slide::qaStage()`, `QaService`),
|
||||
der Presenter schaltet manuell weiter (V bzw. Stepper, auch zurück). `collect`: Fragen einreichen (max.
|
||||
`VoteService::MAX_QA_QUESTIONS` pro Person, gleiche Frage nur einmal pro Folie), Teilnehmende sehen alle bisherigen Fragen
|
||||
(gegen Dubletten, eigene markiert), aber noch keine Upvotes.
|
||||
`vote`: Upvotes auf fremde Fragen, Budget pro Person = Anteil der Fragen (Setting `upvote_share` in Prozent, `Slide::QA_UPVOTE_SHARES`, aufgerundet, mindestens 1:
|
||||
`Slide::qaBudget(Anzahl Fragen)`; im State/JSON `maxUpvotes`), wächst also mit der Fragenzahl, frei verteilbar (auch mehrere auf eine Frage,
|
||||
je Upvote eine Zeile), `vote=remove` nimmt eine Stimme der Frage zurück; im State `qa.upvoted` = {Frage-id: eigene Stimmen}.
|
||||
Setting `max_upvotes_per_question` begrenzt die eigenen Stimmen je Frage (0 = nur durch das Budget begrenzt,
|
||||
effektiv `Slide::qaUpvotesPerQuestion($budget)`, State `maxPerQuestion`). `upvote_share = 0` = ohne Upvotes: es gibt keine Phase `vote`
|
||||
(`Slide::qaStages()` = collect → discuss, im Presenter-JSON `results.stages`), besprochen wird in Eingangsreihenfolge;
|
||||
wird es während `vote` auf 0 gesetzt, springt `SlidesController::saveSlide()` nach `discuss`.
|
||||
Setting `allow_self_upvote` (Standard aus, für Themen-Priorisierung) erlaubt Stimmen auf eigene Fragen aus demselben Budget
|
||||
(State `qa.allowSelfUpvote`); bewusst aus, weil anonym sonst Selbstvermarktung die Rangfolge bestimmt;
|
||||
Teilnehmende sehen alle Fragen in Eingangsreihenfolge **ohne** Zählung; die Bühne (Presenter/Embed) zeigt in `vote` keine Fragen,
|
||||
sondern nur den Hinweis „Schau auf dein Gerät und stimme ab“ mit Fragenzahl, Budget und vergebener Gesamtsumme (`Results.qa`); auch sonst gibt es dort
|
||||
keine Zählungen je Frage und keine Rangfolge (`ResultsService::qa()`, nur die Summe `upvotes`), damit niemand beeinflusst wird. `discuss`: Abstimmung zu, Fragen nach Upvotes
|
||||
sortiert (Gleichstand: älteste zuerst), `focus_response_id` = aktuelle Frage. In `discuss` blättern next/prev
|
||||
(→/←, Klicker) zuerst durch die Fragen, erst danach durch die Folien. Fokuswechsel per `updateAll` ohne `modified`,
|
||||
damit Teilnehmerseiten nicht neu laden. Teilnehmende bekommen nie `results`, sondern `qa` aus `PollStateService::qaState()`.
|
||||
Zurücksetzen startet wieder bei `collect`.
|
||||
**Vorab eingereichte Fragen** (z. B. per Mail): Textarea `prepared_text` im Folienformular (eine Frage pro Zeile, höchstens
|
||||
`QaService::MAX_PREPARED`), nur in `collect` sichtbar/änderbar. `QaService::syncPrepared()` gleicht sie idempotent ab (gleiche Texte
|
||||
behalten ihre id, entfernte verschwinden samt Upvotes, von Teilnehmenden schon gestellte werden nicht doppelt angelegt). Gespeichert
|
||||
als normale Fragen mit `participant_hash = VoteService::PREPARED_HASH` (kein gültiger HMAC → niemand kann sie bearbeiten/löschen,
|
||||
jeder darf sie unterstützen); sie zählen nicht als Teilnehmende. Zurücksetzen löscht sie wie alle Antworten, Duplizieren kopiert sie nicht.
|
||||
Tests: `QaPreparedTest.php`.
|
||||
Eigene Fragen bearbeiten/löschen (`vote=edit|delete` + `question_id`, `VoteService::editQuestion()`) nur in `collect`:
|
||||
danach könnten Upvotes bzw. die Besprechung an einem anderen Text hängen. Bearbeiten prüft Dubletten ohne die eigene Frage,
|
||||
Löschen entfernt auch übrig gebliebene Upvotes (Presenter von `vote` zurück nach `collect`). Im JS hält `qaEditing` das
|
||||
Neu-Rendern beim Polling an, solange eine Frage bearbeitet wird.
|
||||
|
||||
- YouTube-Folie (`youtube`): nicht interaktiv (wie `content`). Settings `url` (wie eingegeben), `video_id`, `start` (Sekunden),
|
||||
`autoplay`. Startzeit-Feld leer = Timecode aus dem Link (`t`/`start`), sonst gewinnt das Feld (`1:30`, `2` = Minuten).
|
||||
Beim Speichern prüft `SlidesController::prepareYouTube()` per oEmbed: nicht gefunden/nicht einbettbar = Fehler,
|
||||
YouTube nicht erreichbar = speichern mit Warnung; leerer Titel wird mit dem Videotitel gefüllt. Eingebettet wird nur
|
||||
im Presenter (`youtube-nocookie.com`), Teilnehmende sehen Link + Teilen-Button (Web Share API, sonst Kopieren).
|
||||
Iframes brauchen `referrerpolicy="strict-origin"`, weil Admin-Seiten `no-referrer` senden und YouTube ohne Referrer
|
||||
nicht abspielt (nur Origin, nie der Pfad mit Token). Tests mocken YouTube über `HttpClientTrait` (`mockClientGet`).
|
||||
|
||||
- Reihenfolge-Folie (`order`): Admin legt die Einträge in der richtigen Reihenfolge an (Formular `order_options[]`, Zeilen
|
||||
per Drag & Drop/Pfeiltasten sortierbar, ids bleiben beim Umsortieren erhalten). Teilnehmende bekommen sie per
|
||||
`Slide::shuffledOptions(participantHash)` gemischt (stabil, nie schon richtig), sortieren und senden `order[]` (alle ids genau einmal),
|
||||
einmal pro Person. Startet offen wie normale Folien; **aufgelöst wird beim Schließen der Abstimmung** (`Slide::isOrderRevealed()`).
|
||||
Vorher landen weder richtige Reihenfolge noch Zählungen im JSON (Presenter sieht die Einträge gemischt mit Seed `slide:{id}`);
|
||||
danach sieht der Presenter die Lösung inkl. „X von N komplett richtig“ und je Eintrag, wie oft er an der richtigen Stelle lag;
|
||||
Teilnehmende nur die Lösung mit eigenen Platzierungen und `order.isCorrect`. Tests: `OrderTest.php`, `OrderSlideTest.php`.
|
||||
|
||||
- **Zurücksetzen** (`ResetService`) löscht **nur Antworten**: Folie (`slides:reset`) bzw. alle Folien der Umfrage
|
||||
(`admin:reset`, Dashboard → „Sicherheit“). Nur Quiz (`ready`) und Q&A (`collect`) springen zurück, weil ihre Phasen
|
||||
ohne Antworten keinen Sinn ergeben; offen/geschlossen anderer Folien, aktuelle Folie/Pause, Einstellungen bleiben.
|
||||
Idempotent, in einer Transaktion. Tests: `PollResetTest.php`.
|
||||
- **Duplizieren** (`slides:duplicate`, POST): kopiert Fragetext (+ „(Kopie)“), Beschreibung, Einstellungen und Optionen
|
||||
inkl. `is_correct`, **nie Antworten**. Die Kopie landet direkt hinter dem Original und startet wie eine neue Folie
|
||||
(`Slide::startFresh()`: Quiz `ready`, Q&A `collect`, sonst offen) – auch `add()` nutzt `startFresh()`.
|
||||
Tests: `DuplicateSlideTest.php`.
|
||||
- **Ausgeblendete Folien** (`is_hidden`, `slides:visibility` mit `hidden=1|0`, explizit statt Toggle → idempotent):
|
||||
bleiben in der Verwaltung (gestrichelt, Badge „ausgeblendet“), gehören aber nicht zur Präsentation. Präsentation =
|
||||
`SlidesTable::listForPoll($pollId, true)`: Start, →/←, `goto` (400 für ausgeblendete), Zähler im Presenter-State
|
||||
(`count` ohne, `hiddenCount` = ausgeblendete), PDF-Export (Nummerierung wie in der Präsentation). Einbettung einer
|
||||
ausgeblendeten Folie geht nicht live (`isHidden` im Embed-State). Eine ausgeblendete Folie darf nie live/pausiert sein:
|
||||
Ausblenden der Live- oder pausierten Folie pausiert wie Löschen (`forgetSlide()` + `SlidesTable::replacementFor()` =
|
||||
nächste sichtbare Folie, sonst die vorige). `is_hidden` ist nicht mass-assignable. Tests: `HiddenSlideTest.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()` /
|
||||
`forgetSlide()` setzen, nie `current_slide_id` direkt. Presenter: P bzw. der Pause-Button schaltet um (Aktionen `stop`/`resume`, beide idempotent, kein Server-Toggle),
|
||||
←/→ setzt ebenfalls 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
|
||||
(IntersectionObserver + `visibilitychange`), sendet Heartbeats und beim Verschwinden `pause` (sendBeacon).
|
||||
`pause` wirkt nur, wenn die eigene Folie noch live ist; `heartbeat` holt keine Folie zurück, die im Presenter
|
||||
gewechselt wurde. Bleiben Heartbeats aus (`Plenario.embed.timeoutSeconds`), pausiert `PollsTable::pauseIfEmbedStale()`
|
||||
beim nächsten State-Abruf. Embed-Routen haben **keinen CSRF-Check** (Third-Party-Iframe ohne Cookies, der Schlüssel
|
||||
ist die Berechtigung, siehe `Application::middleware()`) und erlauben Framing per CSP `frame-ancestors`
|
||||
(`EMBED_FRAME_ANCESTORS`); alle anderen Seiten bleiben `X-Frame-Options: SAMEORIGIN`. Beides entscheidet
|
||||
`SecurityHeadersMiddleware::isEmbed()` anhand des Pfads (auch für Fehlerseiten).
|
||||
|
||||
- **Anonymes / internes Feedback** (offene Frage bzw. Skala mit Setting `private`, `Slide::isPrivate()`): steuert den
|
||||
Schalter „Ergebnisse verbergen“ (H) im Presenter/Embed. Das JSON enthält die vollständigen Ergebnisse plus
|
||||
`results.private = true`; `initPresenter` verbirgt sie beim Wechsel auf eine solche Folie und zeigt stattdessen nur die
|
||||
Anzahl (`Results.privateSummary`). Einblenden gilt nur für diese Folie, die globale Wahl für normale Folien (`hideAll`)
|
||||
bleibt unberührt. Teilnehmende bekommen (wie bei allen Abstimmungsfolien) keine `results`. Die Fassung des PDF-Exports ohne interne Inhalte entfernt sie per
|
||||
`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 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 (Anzeigedauer nach Textlänge, kein Setting pro Folie:
|
||||
`Comments.delay()` = 2,5 s + 15 Zeichen/s, 5–30 s, geteilt durch das Tempo der Umfrage `polls.comment_speed` (Prozent aus
|
||||
`Poll::COMMENT_SPEEDS`, im State `poll.commentSpeed` als Faktor, Dashboard → „Einstellungen“); Vor/Zurück/Fortsetzen geben dem Kommentar wieder die volle Zeit; „Kommentar X von N“,
|
||||
vor/zurück/Pause, Laufbalken bis zum Wechsel (`Comments.progress()`, setzt nach dem Neu-Rendern per negativem
|
||||
`animation-delay` fort, bei Pause unsichtbar), Zustand übersteht das Neu-Rendern beim Polling; die Box ist so hoch wie der längste Kommentar – alle liegen unsichtbar in derselben Grid-Zelle –, damit die zentrierte Bühne beim Wechsel nicht springt; höchstens `--comment-max` ≈ 5 Zeilen, längere Kommentare setzt `Comments.fit()` kleiner statt sie abzuschneiden; die Bewertung steht über dem Text, damit sie an fester Stelle bleibt; der Fortschritt läuft als Rahmen der Box: `Comments.progressBorder()`, SVG-Rechteck mit `pathLength` 100, zwei Linien ab gegenüberliegenden Ecken). Bei internem Feedback erscheinen sie erst,
|
||||
wenn der Presenter die Ergebnisse einblendet.
|
||||
- **Sterne-Bewertung** (Skala mit Setting `style = stars`, `Slide::isStarRating()`, Standard `numbers`): immer 1 bis `scale_max`
|
||||
Sterne (`SlidesTable::sanitizeSettings()` erzwingt `scale_min = 1`), gespeichert wie jede Skala als `numeric_value`.
|
||||
Teilnehmende wählen Sterne (Radios in DOM-Reihenfolge 1..n, Füllung per CSS `:has()`), der State enthält `results.stars`;
|
||||
`Results.stars` in `plenario.js` zeigt den Durchschnitt als teilweise gefüllte Sterne und die Verteilung als Donut 5 → 1.
|
||||
Text-Ausgabe (Auswertung, PDF) über `Slide::ratingText()` (`★★★★☆`), barrierearm über `element/rating`.
|
||||
- **Skala-Darstellung auf der Bühne:** Durchschnitt (große Zahl + Skala bzw. Sterne) und Verteilung (Donut per CSS
|
||||
`conic-gradient`, je Wert eine eigene Farbe aus `--c0…--c5` in fester Reihenfolge, bei mehr Werten gemischt; Legende mit „% (Anzahl)“ und den Beschriftungen der Enden) nebeneinander
|
||||
(`Results.scaleLayout()` / `Results.donut()`). Setting `scale_view` (`Slide::SCALE_VIEWS`: `both` | `average` | `chart`,
|
||||
Dropdown im Formular) zeigt nur einen Teil, dann zentriert; im JSON `results.view`, die Daten bleiben vollständig.
|
||||
Gilt nur für Presenter/Embed, Auswertung und PDF zeigen immer beides.
|
||||
- **Antwort nachträglich bearbeiten** (gegen Tippfehler, `VoteService::hasEditableText()`): Antwort einer offenen Frage
|
||||
(darf nicht leer werden) bzw. Kommentar einer Skala (ändern, ergänzen, leeren; die Bewertung bleibt unveränderlich),
|
||||
nur solange die Abstimmung offen ist. `participate:edit` → `VoteService::editText()`, gleiche Vorbedingungen wie
|
||||
`submit()`, in der Folien-Sperre, legt nie eine neue Antwort an.
|
||||
|
||||
- **Formatierung von Folientexten** (nur `description`, nie Eingaben von Teilnehmenden) im WhatsApp-Stil: `*fett*`,
|
||||
`_kursiv_`, `~durchgestrichen~`, Aufzählung mit `- `/`* ` am Zeilenanfang, Zeilenumbrüche. Zwei gleiche Implementierungen:
|
||||
`FormatHelper::text()` (PHP: Teilnehmerseite, PDF; escapt alles und erzeugt nur diese Tags) und `Format` in `plenario.js`
|
||||
(Presenter/Embed; baut DOM-Knoten, kein `innerHTML`). Regeln in beiden gleich halten (Regex `INLINE`/`LIST_ITEM`),
|
||||
Tests: `FormatHelperTest.php`.
|
||||
- **PDF-Export** (`/admin/{token}/export.pdf`, `admin:export`, `ReportService` + `PdfView`, Dompdf): Ergebnisse aller
|
||||
interaktiven Folien (Inhaltsfolien/YouTube fehlen). Standard ist die Fassung **ohne interne Inhalte**: private Folien
|
||||
(`Slide::isPrivate()`) erscheinen nur mit Teilnehmerzahl. `?internal=1` = vollständige Fassung inkl.
|
||||
anonymer Antworten, interner Skalen und Kommentar-Bewertungen (Dateiname `…-intern.pdf`, Hinweis „Vertraulich“ auf jeder
|
||||
Seite); ohne private Folien wird der Parameter ignoriert. Quiz/Reihenfolge folgen auch hier den Auflöse-Regeln
|
||||
(vor `finished` bzw. Schließen keine Zählungen/Lösung). Layout `templates/layout/pdf.php` ist eigenständig: keine
|
||||
externen Ressourcen, keine CSS-Variablen, Schrift DejaVu Sans; Seitenzahlen setzt `PdfView::addPageNumbers()`.
|
||||
Tests prüfen das HTML über `PlenarioTestTrait::exportHtml()` (das PDF selbst ist nicht durchsuchbar).
|
||||
|
||||
- **Vollbild & Display anlassen** (Teilnehmeransicht, `initScreenTools` in `plenario.js`): zwei optionale Icon-Buttons im Header neben dem Farbschema-Schalter (Layout-Block `headerTools`)
|
||||
(`data-fullscreen-toggle`, `data-wakelock-toggle`), bleiben ohne Browser-Unterstützung versteckt (iPhone-Safari kennt kein Vollbild).
|
||||
Der Wake Lock ist standardmäßig an (braucht keine Nutzergeste); nur ein bewusstes Ausschalten wird gemerkt.
|
||||
Die Seite lädt bei Folienwechsel neu: der Wake Lock wird per `sessionStorage` (`plenario-wakelock`) wieder angefordert,
|
||||
Vollbild braucht eine Nutzergeste und muss nach dem Wechsel ggf. neu gewählt werden.
|
||||
|
||||
- **Dashboard ohne Neuladen** (`initAdminDashboard()`, `Fragments` in `plenario.js`): Formulare in `[data-live]` (Folienliste, Kopf)
|
||||
und das Folienformular im `<dialog>` laufen per `fetch` mit Header `X-Fragment`; `AdminAppController::beforeRender()` nimmt dann
|
||||
das Layout `fragment` (nur Inhalt + Flash). Die Server-Aktionen bleiben normale POST + Redirect, das JS tauscht die Bereiche
|
||||
`[data-refresh="head|slides|flash"]` (als DOM-Knoten, nie `innerHTML`) und stellt den Fokus wieder her. Bearbeiten/Anlegen:
|
||||
Links mit `data-modal` laden das Formular (`[data-modal-content]`) in den Dialog; Validierungsfehler kommen als Formular
|
||||
zurück (Dialog bleibt offen), Erfolg als Dashboard-Fragment (Dialog schließt). Ohne JS funktioniert alles als normale Seite.
|
||||
**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`.
|
||||
|
||||
### Neuen Folientyp hinzufügen (Checkliste)
|
||||
|
||||
1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php`
|
||||
2. Settings-Sanitizing in `SlidesTable::sanitizeSettings()`
|
||||
3. Validierung/Speicherung in `VoteService::submit()` (eigene `…Rows()`-Methode)
|
||||
4. Aggregation in `ResultsService::forSlide()` + Docblock der JSON-Struktur
|
||||
5. Formularfelder in `templates/Slides/form.php`, Eingabe in `templates/Participate/view.php`
|
||||
6. Renderer in `webroot/js/plenario.js` (`Results.<type>`), Styles in `plenario.css`, Badge-Farbe;
|
||||
Ausgabe im PDF-Export (`templates/Admin/export.php`)
|
||||
7. Tests in `tests/TestCase/Service/VoteServiceTest.php` (Quiz: `QuizTest.php`, Q&A: `QaTest.php`)
|
||||
8. Nach neuen Spalten lokal `bin/cake cache clear_all`, sonst nutzt das ORM das alte Schema aus dem Cache
|
||||
|
||||
### Farbschema (Tag/Nacht)
|
||||
|
||||
`data-theme="light|dark"` auf `<html>`, ohne Attribut gilt die Systemeinstellung. `element/theme_init` setzt die
|
||||
Wahl aus `localStorage` vor dem ersten Rendern (Inline-Skript im `<head>`), `element/theme_switch` ist der Schalter
|
||||
(`Theme` in `plenario.js`). Presenter: eigener Schlüssel `plenario-theme-present`, Standard dunkel, Taste T.
|
||||
Neue Farben als Token in beiden Dark-Blöcken von `plenario.css` pflegen; auf der Bühne Overlays mit `rgba(var(--tint), …)`.
|
||||
|
||||
### Live-Updates
|
||||
|
||||
Kein WebSocket: Presenter (`/admin/{token}/state`) und Teilnehmende (`/p/{code}/state`) pollen per `fetch`
|
||||
(`Plenario.pollIntervalMs`). Die Teilnehmerseite lädt neu, wenn sich `version` im State ändert.
|
||||
- Bilder: Datei erst nach dem Commit löschen, nie davor; keine Pflichtfelder zum Bild. Details: [docs/images.md](docs/images.md).
|
||||
- Neuer Folientyp: Checkliste in [docs/slide-types.md](docs/slide-types.md).
|
||||
|
||||
## Konventionen
|
||||
|
||||
@@ -335,46 +139,14 @@ Kein WebSocket: Presenter (`/admin/{token}/state`) und Teilnehmende (`/p/{code}/
|
||||
eigenen Branch (z. B. `feature/…`, `fix/…`, `docs/…`), pushen und per Pull Request in Gitea mergen.
|
||||
Merge erst, wenn der Status-Check `test` grün ist. Kein Force-Push auf `main`.
|
||||
|
||||
## Deployment
|
||||
|
||||
Deploy erfolgt über Git (Remote: Gitea) mit `.gitea/workflows/ci.yml`:
|
||||
## Deployment in Kürze
|
||||
|
||||
- Job `phpunit` (PHPUnit + phpcs) läuft bei jedem Push auf jeden Branch, als Matrix gegen PHP 8.4 und 8.5.
|
||||
Der Sammel-Job `test` ist nur grün, wenn alle Matrix-Läufe grün sind, und bleibt der Check, den der Branch-Schutz
|
||||
verlangt (so muss dort bei neuen PHP-Versionen nichts angepasst werden). `main` ist per Branch-Schutz
|
||||
in Gitea gesperrt: kein direkter Push, Merge nur per PR und nur mit grünem Status-Check des Jobs `test`.
|
||||
- Job `deploy` läuft nur bei Push auf `main`, nur bei grünen Tests und **nur wenn die Repo-Variable
|
||||
`DEPLOY_ENABLED=true` gesetzt ist** (standardmäßig deaktiviert). Er verbindet sich per SSH
|
||||
(DirectAdmin, `plenario.gnilebein.de`, Checkout direkt in `public_html`), holt den Code per HTTPS mit
|
||||
dem kurzlebigen Job-Token (kein Deploy-Key auf dem Server), macht `git reset --hard origin/main`,
|
||||
bricht ab, wenn `config/.env` fehlt, dann `composer install --no-dev`, `migrations migrate`, `cache clear_all`. PHP und Composer werden
|
||||
automatisch erkannt (überschreibbar über `PHP_BIN`/`COMPOSER_BIN`).
|
||||
- Benötigte Variablen/Secrets sind im Kopf der Workflow-Datei dokumentiert. Zugangsdaten nur als
|
||||
Gitea-Secret, nie ins Repo.
|
||||
|
||||
**Container (Docker) – nur für Testzwecke, nicht für den Produktivbetrieb geeignet** (eingebauter PHP-Server, SQLite; das steht
|
||||
auch in der README und darf dort nicht als „empfohlen“ oder produktionstauglich erscheinen): `Dockerfile` (`php:8.5-cli-alpine`, Multi-Stage mit Composer) startet über
|
||||
`docker/entrypoint.sh` den eingebauten Server (`bin/cake server -H 0.0.0.0 -p 8765`, `PHP_CLI_SERVER_WORKERS=8`,
|
||||
sonst bedient er nur einen Request gleichzeitig). Code in `/app`, SQLite in Volume `/data`
|
||||
(`DATABASE_URL=sqlite:////data/plenario.sqlite`), Konfiguration nur per Umgebungsvariablen (`config/.env.example`).
|
||||
`SECURITY_SALT` ist Pflicht (Entrypoint bricht sonst ab; `composer install --no-scripts`, damit kein Salt eingebrannt wird).
|
||||
Der Start ist idempotent (Migrationen + `cache clear_all`). Der Healthcheck prüft eine statische Datei, weil die Host-Prüfung
|
||||
(`APP_FULL_BASE_URL`) `127.0.0.1` auf echten Seiten mit 400 ablehnt. Betrieb hinter einem TLS-Proxy mit `X-Forwarded-Proto`.
|
||||
Beispiel: `docker-compose.yml`. Image und App-Paket entstehen nur bei Releases (siehe nächster Absatz).
|
||||
|
||||
**Releases (SemVer):** `.gitea/workflows/release.yml` läuft nur bei Tags `vMAJOR.MINOR.PATCH[-suffix]` (kein Build bei normalen
|
||||
Pushes). Job `test` (PHPUnit + phpcs) gatet `package` und `image`. `package` baut `plenario-<version>.tar.gz` (git archive des Tags,
|
||||
`composer install --no-dev --no-scripts`, `app_local.php` aus dem Example, leere `tmp/`/`logs/`/`data/`, Datei `VERSION`; nur per Whitelist: bin, config, plugins, resources, src, templates, webroot, index.php, .htaccess, composer-Dateien;
|
||||
kein tests/CI/Docker/README) + `SHA256SUMS` und hängt sie an das Gitea-Release (wird angelegt bzw. aktualisiert, Changelog = Commit-Betreffs
|
||||
seit dem letzten Tag, Suffix = Pre-Release). `image` pusht `:<version>`, `:<major>.<minor>`, `:<major>` und `:latest` (die
|
||||
beiden letzten nicht bei Pre-Releases bzw. `v0.`) in die Gitea-Registry (Variablen `DOCKER_REPO`, `IMAGE_NAME`, Secret `PAT`).
|
||||
Wer das Paket ändert (z. B. weitere Dateien ausschließen), pflegt den Schritt „Build package“ in dieser Datei.
|
||||
|
||||
Produktiv auf dem Server in `config/.env`: `DEBUG=false`, `APP_FULL_BASE_URL`, `SECURITY_SALT`, SMTP
|
||||
(`SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_TLS` – einzelne Variablen statt URL; `EMAIL_TRANSPORT_DEFAULT_URL` geht weiter als Altlast).
|
||||
Ohne `DEBUG=false` steht die per Composer erzeugte `app_local.php` auf debug=true und zeigt Admin-Links direkt an.
|
||||
Document-Root zeigt idealerweise auf `webroot/`; liegt die App direkt im Document-Root (z. B. `public_html`),
|
||||
leiten `.htaccess` + `index.php` im Projektroot alles nach `webroot/` weiter.
|
||||
CI (`.gitea/workflows/ci.yml`): Job `phpunit` (PHPUnit + phpcs, PHP 8.4/8.5) auf jedem Push, der Sammel-Job `test` ist der
|
||||
Check des Branch-Schutzes. Job `deploy` läuft nur bei Push auf `main`, grünen Tests und `DEPLOY_ENABLED=true`. Releases
|
||||
entstehen nur bei Tags `vMAJOR.MINOR.PATCH` (`release.yml`). Docker ist nur für Tests gedacht, nie als
|
||||
produktionstauglich darstellen. Alles Weitere (Server-Konfiguration, Paket, Container, Ablauf/Cron von Umfragen):
|
||||
[docs/operations.md](docs/operations.md).
|
||||
|
||||
## Bekannte Grenzen / Ideen
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Alle Projektinfos für Agents stehen in **AGENTS.md** – bitte dort lesen und dort pflegen:
|
||||
Alle Projektinfos für Agents stehen in **AGENTS.md** (Details je Bereich unter **docs/**) – bitte dort lesen und dort pflegen:
|
||||
|
||||
@AGENTS.md
|
||||
|
||||
|
||||
+10
-6
@@ -2,20 +2,23 @@
|
||||
# Configuration only through environment variables (see config/.env.example).
|
||||
|
||||
FROM php:8.5-cli-alpine AS base
|
||||
RUN apk add --no-cache icu-libs \
|
||||
&& apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev \
|
||||
&& docker-php-ext-install -j"$(nproc)" intl \
|
||||
# gd with JPEG/WebP: slide images are scaled and stored as WebP
|
||||
RUN apk add --no-cache icu-libs libjpeg-turbo libpng libwebp \
|
||||
&& apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev libjpeg-turbo-dev libpng-dev libwebp-dev \
|
||||
&& docker-php-ext-configure gd --with-jpeg --with-webp \
|
||||
&& docker-php-ext-install -j"$(nproc)" intl gd \
|
||||
&& apk del .build-deps
|
||||
# Image uploads of up to 10 MB (IMAGE_MAX_UPLOAD_MB) must pass PHP's limits
|
||||
RUN printf 'upload_max_filesize=10M\npost_max_size=12M\n' > /usr/local/etc/php/conf.d/plenario-uploads.ini
|
||||
|
||||
FROM base AS build
|
||||
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
|
||||
WORKDIR /app
|
||||
COPY composer.json composer.lock ./
|
||||
# --no-scripts: the installer must not bake a random salt into app_local.php (SECURITY_SALT comes at runtime)
|
||||
# --no-scripts: no app_local.php in the image; everything comes from the environment at runtime
|
||||
RUN composer install --no-dev --no-scripts --no-progress --prefer-dist --optimize-autoloader
|
||||
COPY . .
|
||||
RUN composer dump-autoload --no-dev --optimize \
|
||||
&& cp config/app_local.example.php config/app_local.php
|
||||
RUN composer dump-autoload --no-dev --optimize
|
||||
|
||||
FROM base
|
||||
WORKDIR /app
|
||||
@@ -25,6 +28,7 @@ COPY docker/entrypoint.sh /usr/local/bin/plenario-entrypoint
|
||||
ENV DEBUG=false \
|
||||
SHOW_ADMIN_LINK_AFTER_CREATE=false \
|
||||
DATABASE_URL=sqlite:////data/plenario.sqlite \
|
||||
UPLOADS_PATH=/data/uploads \
|
||||
PHP_CLI_SERVER_WORKERS=8
|
||||
|
||||
RUN chmod +x /usr/local/bin/plenario-entrypoint \
|
||||
|
||||
@@ -22,16 +22,10 @@ läuft lokal mit **SQLite**, ohne Build-Schritt fürs Frontend.
|
||||
|
||||
- [So funktioniert es](#so-funktioniert-es)
|
||||
- [Funktionen](#funktionen)
|
||||
- [Lokal starten (Entwicklung)](#lokal-starten-entwicklung)
|
||||
- [Tests](#tests)
|
||||
- [Konfiguration](#konfiguration)
|
||||
- [Deployment mit Docker](#deployment-mit-docker)
|
||||
- [Deployment ohne Docker](#deployment-ohne-docker)
|
||||
- [Releases und Versionierung](#releases-und-versionierung)
|
||||
- [Automatisches Deployment (Gitea Actions)](#automatisches-deployment-gitea-actions)
|
||||
- [Konfiguration und Deployment](#konfiguration-und-deployment)
|
||||
- [Betrieb & Skalierung](#betrieb--skalierung)
|
||||
- [Datenschutz](#datenschutz)
|
||||
- [Mitentwickeln](#mitentwickeln)
|
||||
- [Entwicklung und Mitarbeit](#entwicklung-und-mitarbeit)
|
||||
|
||||
## So funktioniert es
|
||||
|
||||
@@ -61,6 +55,9 @@ Wichtige Tasten im Präsentationsmodus: `←` / `→` Folie wechseln, `P` Pause,
|
||||
- **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)
|
||||
- **Bilder** auf Folien (außer YouTube): werden beim Hochladen auf höchstens 1600 Pixel verkleinert und als WebP
|
||||
gespeichert (Kameradaten wie der Aufnahmeort fallen dabei weg), mit Bildbeschreibung und Platzierung oben, daneben
|
||||
oder bildschirmfüllend
|
||||
- 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)
|
||||
@@ -74,205 +71,15 @@ Wichtige Tasten im Präsentationsmodus: `←` / `→` Folie wechseln, `P` Pause,
|
||||
- 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 (Entwicklung)
|
||||
## Konfiguration und Deployment
|
||||
|
||||
Voraussetzungen: PHP 8.4+ mit den Erweiterungen `intl`, `mbstring`, `openssl`, `pdo_sqlite`, `curl`
|
||||
sowie [Composer](https://getcomposer.org/).
|
||||
Alle Einstellungen gehen über Umgebungsvariablen oder `config/.env` (Vorlage: [config/.env.example](config/.env.example)).
|
||||
Für die Produktion zählen mindestens `DEBUG=false`, `APP_FULL_BASE_URL`, `SECURITY_SALT` (nach dem ersten Einsatz
|
||||
**nie mehr ändern**) und ein Mail-Transport (`SMTP_*`).
|
||||
|
||||
```bash
|
||||
git clone https://gitea.gnilebein.de/gnilebein/Plenario.git
|
||||
cd Plenario
|
||||
composer install # legt config/app_local.php an (SQLite, Mails als Datei)
|
||||
bin/cake migrations migrate # erstellt data/plenario.sqlite
|
||||
bin/cake server -p 8765 # http://localhost:8765
|
||||
```
|
||||
|
||||
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.
|
||||
Zurücksetzen der lokalen Daten: `data/plenario.sqlite` löschen und die Migrationen erneut laufen lassen.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
vendor/bin/phpunit # nutzt tmp/tests.sqlite, Schema kommt aus den Migrationen
|
||||
vendor/bin/phpcs # CakePHP Coding Standard (Autofix: vendor/bin/phpcbf)
|
||||
```
|
||||
|
||||
## Konfiguration
|
||||
|
||||
Alle Einstellungen gehen über Umgebungsvariablen oder `config/.env`
|
||||
(Vorlage mit allen Variablen: [config/.env.example](config/.env.example)). Echte Umgebungsvariablen
|
||||
haben Vorrang vor der Datei.
|
||||
|
||||
| Variable | Bedeutung |
|
||||
|---|---|
|
||||
| `DEBUG` | `false` in Produktion |
|
||||
| `APP_FULL_BASE_URL` | Absolute URL, wird für Links in E-Mails gebraucht (Pflicht in Produktion). In Produktion wird außerdem der Host-Header dagegen geprüft |
|
||||
| `SECURITY_SALT` | Langer Zufallswert. **Nicht nachträglich ändern** – damit werden Admin-Tokens verschlüsselt und Teilnehmer-IDs gehasht |
|
||||
| `DATABASE_URL` | Leer = SQLite in `data/`. Sonst z. B. `mysql://user:pw@host/plenario?encoding=utf8mb4` oder `postgres://user:pw@host/plenario` |
|
||||
| `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD` | Mailserver (Port Standard 587). Ohne `SMTP_HOST` werden Mails nur als Datei abgelegt |
|
||||
| `SMTP_TLS` | `true` (Standard) = STARTTLS; Port 465 nutzt automatisch SSL; `false` = unverschlüsselt |
|
||||
| `MAIL_FROM`, `MAIL_FROM_NAME` | Absender |
|
||||
| `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` | 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 |
|
||||
|
||||
Einen `SECURITY_SALT` erzeugen:
|
||||
|
||||
```bash
|
||||
php -r "echo bin2hex(random_bytes(32));"
|
||||
# oder ohne PHP:
|
||||
openssl rand -hex 32
|
||||
```
|
||||
|
||||
## Deployment mit Docker
|
||||
|
||||
> **Nur für Testzwecke.** Das Docker-Image ist zum Ausprobieren und für Tests gedacht und **nicht für den
|
||||
> Produktionsbetrieb geeignet**: Es nutzt den eingebauten PHP-Server (kein Webserver wie Apache oder nginx mit PHP-FPM)
|
||||
> und SQLite in einem Volume. Für den echten Betrieb siehe [Deployment ohne Docker](#deployment-ohne-docker).
|
||||
|
||||
Das [Dockerfile](Dockerfile) baut ein schlankes Image (`php:8.5-cli-alpine`, Multi-Stage mit Composer).
|
||||
Der eingebaute PHP-Server läuft mit 8 Workern auf Port **8765**, die SQLite-Datenbank liegt im Volume `/data`.
|
||||
Beim Start laufen die Migrationen automatisch (idempotent, mehrfaches Starten ist unproblematisch).
|
||||
|
||||
Das fertige Image liegt in der Gitea-Registry:
|
||||
`gitea.gnilebein.de/gnilebein/plenario:latest` (letzter stabiler Release). Für feste Versionen gibt es die
|
||||
SemVer-Tags `:1.4.0`, `:1.4` und `:1` (Pre-Releases wie `v1.5.0-rc.1` nur als `:1.5.0-rc.1`).
|
||||
Gebaut wird das Image nur bei einem neuen Release-Tag, siehe [Releases](#releases-und-versionierung).
|
||||
|
||||
### Schnellstart mit `docker run`
|
||||
|
||||
```bash
|
||||
docker run -d --name plenario -p 8765:8765 -v plenario-data:/data \
|
||||
-e SECURITY_SALT="$(openssl rand -hex 32)" \
|
||||
-e APP_FULL_BASE_URL=https://plenario.example.org \
|
||||
-e MAIL_FROM=noreply@example.org \
|
||||
-e SMTP_HOST=mail.example.org -e SMTP_PORT=587 \
|
||||
-e SMTP_USER=noreply@example.org -e SMTP_PASSWORD='geheim' \
|
||||
--restart unless-stopped \
|
||||
gitea.gnilebein.de/gnilebein/plenario:latest
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
1. Eine `.env` neben der [docker-compose.yml](docker-compose.yml) anlegen (Vorlage: [config/.env.example](config/.env.example)):
|
||||
|
||||
```dotenv
|
||||
SECURITY_SALT=<64 Zeichen Zufall, siehe oben>
|
||||
APP_FULL_BASE_URL=https://plenario.example.org
|
||||
MAIL_FROM=noreply@example.org
|
||||
MAIL_FROM_NAME=PlenarIO
|
||||
SMTP_HOST=mail.example.org
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=noreply@example.org
|
||||
SMTP_PASSWORD=geheim
|
||||
SMTP_TLS=true
|
||||
CAPTCHA_TYPE=math
|
||||
```
|
||||
|
||||
2. Starten:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose logs -f plenario # Start und Migrationen beobachten
|
||||
```
|
||||
|
||||
3. Aktualisieren auf die neueste Version:
|
||||
|
||||
```bash
|
||||
docker compose pull && docker compose up -d
|
||||
```
|
||||
|
||||
Die Datenbank bleibt im Volume `plenario-data` erhalten; neue Migrationen laufen beim Start automatisch.
|
||||
|
||||
Statt das Image zu ziehen, lässt sich auch lokal bauen: in der `docker-compose.yml` die Zeile `# build: .`
|
||||
aktivieren oder `docker build -t plenario .` ausführen.
|
||||
|
||||
### Wichtig im Container
|
||||
|
||||
- **`SECURITY_SALT` ist Pflicht.** Fehlt er, bricht der Start mit einer Fehlermeldung ab. Er wird nicht ins Image
|
||||
eingebrannt, sondern zur Laufzeit gesetzt. Nach dem ersten Einsatz **nie mehr ändern** (sonst werden
|
||||
Admin-Tokens unlesbar und Teilnehmer-IDs ungültig).
|
||||
- **`APP_FULL_BASE_URL` muss die öffentliche URL sein**, inklusive `https://`. Sie wird für die Links in
|
||||
E-Mails verwendet, und in Produktion wird der Host-Header dagegen geprüft.
|
||||
- **Mail-Versand einrichten.** Ohne `SMTP_HOST` schreibt PlenarIO Mails nur als Datei ins
|
||||
Container-Dateisystem – der Admin-Link kommt dann **nie** bei den Nutzenden an.
|
||||
- **TLS-Proxy davorschalten** (Caddy, nginx, Traefik, …), der `X-Forwarded-Proto` setzt. Der eingebaute
|
||||
PHP-Server spricht nur HTTP. Beispiel für Caddy:
|
||||
|
||||
```
|
||||
plenario.example.org {
|
||||
reverse_proxy localhost:8765
|
||||
}
|
||||
```
|
||||
|
||||
- **Daten sichern:** Alles Wichtige liegt in `/data` (SQLite-Datei `plenario.sqlite`). Backup z. B. mit
|
||||
`docker run --rm -v plenario-data:/data -v "$PWD":/backup alpine tar czf /backup/plenario-data.tgz -C /data .`
|
||||
- **Bind-Mount statt Volume:** Der Container läuft als Benutzer `www-data` (UID 82). Das Host-Verzeichnis
|
||||
muss für ihn beschreibbar sein (`chown 82:82 ./data`).
|
||||
- **Andere Datenbank:** Für viele gleichzeitige Teilnehmende `DATABASE_URL` auf MySQL/PostgreSQL setzen
|
||||
(siehe [Betrieb & Skalierung](#betrieb--skalierung)).
|
||||
- **Healthcheck:** Das Image prüft eine statische Datei (`/css/plenario.css`), weil die Host-Prüfung echte Seiten
|
||||
bei Aufrufen über `127.0.0.1` ablehnen würde.
|
||||
- **Weitere Einstellungen** (Captcha, Rate-Limits, Polling, Einbettung) gehen ebenfalls per Umgebungsvariable,
|
||||
siehe [Konfiguration](#konfiguration).
|
||||
|
||||
## Deployment ohne Docker
|
||||
|
||||
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` 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.
|
||||
|
||||
Bei Updates: Code aktualisieren, `composer install --no-dev`, Migrationen und `cache clear_all` wiederholen.
|
||||
|
||||
## Automatisches Deployment (Gitea Actions)
|
||||
|
||||
[.gitea/workflows/ci.yml](.gitea/workflows/ci.yml) testet jeden Push (PHPUnit + phpcs).
|
||||
`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.
|
||||
|
||||
Der Workflow bedient vor allem die Instanz unter <https://plenario.gnilebein.de/>, ist aber nicht fest darauf
|
||||
verdrahtet: Ziel und Werkzeuge kommen ausschließlich aus Repository-Variablen (`SSH_HOST`, `SSH_PORT`, `SSH_USER`,
|
||||
`DEPLOY_PATH`, optional `PHP_BIN`/`COMPOSER_BIN`) und Secrets (`SSH_KEY` oder `SSH_PASSWORD`). Wer PlenarIO auf einem
|
||||
eigenen Server betreibt, setzt dort seine Werte und `DEPLOY_ENABLED=true` – die Workflow-Datei bleibt unverändert.
|
||||
Voraussetzungen: SSH-Zugang mit Shell, `git` und PHP ≥ 8.4 auf dem Server, der Server erreicht die Gitea-Instanz per
|
||||
HTTPS. Ohne `DEPLOY_ENABLED` passiert nichts (Standard).
|
||||
|
||||
## Releases und Versionierung
|
||||
|
||||
PlenarIO nutzt [Semantic Versioning](https://semver.org/lang/de/) (`MAJOR.MINOR.PATCH`): Major bei inkompatiblen
|
||||
Änderungen (z. B. Schema-/Konfigurationsumbrüche), Minor für neue Funktionen, Patch für Fehlerbehebungen.
|
||||
Eine Version entsteht durch einen Tag auf `main`:
|
||||
|
||||
```bash
|
||||
git tag v1.4.0 && git push origin v1.4.0 # Pre-Release: v1.5.0-rc.1
|
||||
```
|
||||
|
||||
Der Workflow [.gitea/workflows/release.yml](.gitea/workflows/release.yml) läuft nur bei solchen Tags (`vX.Y.Z[-suffix]`),
|
||||
führt zuerst die Tests aus und erzeugt dann
|
||||
|
||||
- ein **App-Paket** `plenario-<version>.tar.gz` samt `SHA256SUMS` als Anhang des Gitea-Releases (fertig mit
|
||||
Produktions-`vendor/`, nur die Anwendung (Whitelist), ohne Tests, CI, Docker und Entwicklerdateien, `VERSION`-Datei enthalten; Einrichtung wie unter
|
||||
[Deployment ohne Docker](#deployment-ohne-docker), nur ohne Composer-Schritt) und
|
||||
- das **Docker-Image** mit den Tags `:<version>`, `:<major>.<minor>`, `:<major>` und `:latest`.
|
||||
|
||||
Tags mit Suffix (`-rc.1`, `-beta.2`) werden als Pre-Release markiert und bekommen weder `:latest` noch `:<major>`.
|
||||
Der Workflow ist wiederholbar: ein erneuter Lauf aktualisiert das vorhandene Release.
|
||||
- [Konfiguration](docs/configuration.md): alle Umgebungsvariablen, `SECURITY_SALT` erzeugen
|
||||
- [Deployment](docs/deployment.md): ohne Docker (Produktivbetrieb), Docker (nur Testbetrieb), Cronjob und Admin-CLI
|
||||
für Ablauf und Aufräumen von Umfragen, automatisches Deployment per Gitea Actions, Releases und Versionierung
|
||||
|
||||
## Betrieb & Skalierung
|
||||
|
||||
@@ -292,10 +99,9 @@ Für Einzelveranstaltungen und typische Meetings reicht SQLite problemlos.
|
||||
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.
|
||||
|
||||
## Mitentwickeln
|
||||
## Entwicklung und Mitarbeit
|
||||
|
||||
- Quellcode, Issues und Pull Requests: <https://gitea.gnilebein.de/gnilebein/Plenario>
|
||||
- `main` ist geschützt: Änderungen auf einem eigenen Branch pushen und per Pull Request mergen.
|
||||
Vor jedem Commit müssen `vendor/bin/phpunit` und `vendor/bin/phpcs` grün sein.
|
||||
- Architektur, Konventionen und Regeln, die man nicht versehentlich brechen darf, stehen in
|
||||
[AGENTS.md](AGENTS.md) (zentrale Arbeitsgrundlage, auch für KI-Agents).
|
||||
- Lokales Setup, Tests und Ablauf: [docs/development.md](docs/development.md)
|
||||
- Architektur, Konventionen und Regeln, die man nicht versehentlich brechen darf: [AGENTS.md](AGENTS.md)
|
||||
(zentrale Arbeitsgrundlage, auch für KI-Agents), Details in [docs/](docs/README.md)
|
||||
@@ -41,8 +41,17 @@ 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
|
||||
# (PHP's upload_max_filesize and post_max_size must allow it) and slides with an image per poll
|
||||
# UPLOADS_PATH=/var/www/plenario-uploads
|
||||
IMAGE_MAX_UPLOAD_MB=10
|
||||
IMAGE_MAX_PER_POLL=20
|
||||
# Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s)
|
||||
EMBED_HEARTBEAT_SECONDS=5
|
||||
EMBED_TIMEOUT_SECONDS=20
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Migrations\BaseMigration;
|
||||
|
||||
/**
|
||||
* One optional image per slide. The (scaled) file lives in the upload directory, see
|
||||
* \App\Service\ImageService; the table only holds its random file name and how to show it.
|
||||
*/
|
||||
class AddImageToSlides extends BaseMigration
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$table = $this->table('slides');
|
||||
$columns = [
|
||||
// file name inside the poll's upload directory (null = no image)
|
||||
'image' => ['string', ['null' => true, 'default' => null, 'limit' => 40]],
|
||||
// alternative text, '' = purely decorative image
|
||||
'image_alt' => ['string', ['null' => true, 'default' => null, 'limit' => 255]],
|
||||
// top | side | full (null = default of the slide type)
|
||||
'image_layout' => ['string', ['null' => true, 'default' => null, 'limit' => 8]],
|
||||
'image_width' => ['integer', ['null' => true, 'default' => null]],
|
||||
'image_height' => ['integer', ['null' => true, 'default' => null]],
|
||||
];
|
||||
$changed = false;
|
||||
foreach ($columns as $name => [$type, $options]) {
|
||||
if (!$table->hasColumn($name)) {
|
||||
$table->addColumn($name, $type, $options);
|
||||
$changed = true;
|
||||
}
|
||||
}
|
||||
if ($changed) {
|
||||
$table->update();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
$table = $this->table('slides');
|
||||
foreach (['image', 'image_alt', 'image_layout', 'image_width', 'image_height'] as $name) {
|
||||
if ($table->hasColumn($name)) {
|
||||
$table->removeColumn($name);
|
||||
}
|
||||
}
|
||||
$table->update();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Migrations\BaseMigration;
|
||||
|
||||
/**
|
||||
* When the reminder mail before a poll expires was sent (null = not yet), so it goes out only once.
|
||||
*/
|
||||
class AddExpiryRemindedAtToPolls extends BaseMigration
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$table = $this->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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,7 +49,26 @@ 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' => [
|
||||
// One sub directory per poll. In containers keep it on the volume, e.g. /data/uploads.
|
||||
'path' => (string)env('UPLOADS_PATH', ROOT . DS . 'data' . DS . 'uploads'),
|
||||
// Largest accepted upload (the original, before scaling). PHP's upload_max_filesize/post_max_size must allow it.
|
||||
'maxUploadBytes' => (int)env('IMAGE_MAX_UPLOAD_MB', 10) * 1024 * 1024,
|
||||
// Longest edge after scaling, in pixels.
|
||||
'maxEdge' => 1600,
|
||||
'quality' => 82,
|
||||
// Slides with an image per poll.
|
||||
'maxPerPoll' => (int)env('IMAGE_MAX_PER_POLL', 20),
|
||||
],
|
||||
// Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva).
|
||||
'embed' => [
|
||||
// A visible embedded slide reports every N seconds that it is still on screen ...
|
||||
@@ -353,6 +372,10 @@ return [
|
||||
'default' => [
|
||||
'className' => Connection::class,
|
||||
'driver' => Sqlite::class,
|
||||
// Default: SQLite file in data/. For MySQL/MariaDB/PostgreSQL set DATABASE_URL, e.g.
|
||||
// mysql://user:pass@localhost/plenario?encoding=utf8mb4
|
||||
'database' => ROOT . DS . 'data' . DS . 'plenario.sqlite',
|
||||
'url' => env('DATABASE_URL', null),
|
||||
'persistent' => false,
|
||||
'timezone' => 'UTC',
|
||||
|
||||
@@ -396,6 +419,8 @@ return [
|
||||
'test' => [
|
||||
'className' => Connection::class,
|
||||
'driver' => Sqlite::class,
|
||||
'database' => ROOT . DS . 'tmp' . DS . 'tests.sqlite',
|
||||
'url' => env('DATABASE_TEST_URL', null),
|
||||
'persistent' => false,
|
||||
'timezone' => 'UTC',
|
||||
'encoding' => 'utf8',
|
||||
|
||||
@@ -1,65 +1,35 @@
|
||||
<?php
|
||||
/*
|
||||
* Local configuration overrides for Plenario.
|
||||
* Development defaults for PlenarIO. Only for local work: `composer install` copies this file to
|
||||
* config/app_local.php (gitignored, never overwritten afterwards).
|
||||
*
|
||||
* Copy this file to config/app_local.php (done automatically by
|
||||
* `composer install`) and adjust it. app_local.php is NOT committed.
|
||||
*
|
||||
* Every value can alternatively be provided via environment variables.
|
||||
* Production does NOT use app_local.php. Everything is configured in config/.env or real environment
|
||||
* variables (see config/.env.example); config/app.php reads them. The release package and the Docker image
|
||||
* ship without app_local.php on purpose: it takes precedence over the environment, so a stale copy would
|
||||
* silently override settings (e.g. force the file mail transport).
|
||||
*/
|
||||
|
||||
use Cake\Database\Driver\Sqlite;
|
||||
use function Cake\Core\env;
|
||||
|
||||
return [
|
||||
'debug' => filter_var(env('DEBUG', true), FILTER_VALIDATE_BOOLEAN),
|
||||
|
||||
'App' => [
|
||||
// Absolute base URL used for links in e-mails, e.g. https://plenario.example.org
|
||||
'fullBaseUrl' => env('APP_FULL_BASE_URL', 'http://localhost:8765'),
|
||||
],
|
||||
|
||||
'Security' => [
|
||||
// Replaced by a random value during `composer install`
|
||||
'salt' => env('SECURITY_SALT', '__SALT__'),
|
||||
],
|
||||
|
||||
'Plenario' => [
|
||||
'captcha' => [
|
||||
// 'none' | 'math' | 'recaptcha'
|
||||
'type' => env('CAPTCHA_TYPE', 'math'),
|
||||
'recaptcha' => [
|
||||
'siteKey' => env('RECAPTCHA_SITE_KEY', ''),
|
||||
'secretKey' => env('RECAPTCHA_SECRET_KEY', ''),
|
||||
],
|
||||
],
|
||||
// Shows the admin link on the confirmation page. Development only!
|
||||
'showAdminLinkAfterCreate' => filter_var(env('SHOW_ADMIN_LINK_AFTER_CREATE', env('DEBUG', true)), FILTER_VALIDATE_BOOLEAN),
|
||||
],
|
||||
|
||||
'Datasources' => [
|
||||
/*
|
||||
* Default: SQLite file in data/. For MySQL/MariaDB/PostgreSQL set
|
||||
* DATABASE_URL, e.g.
|
||||
* mysql://user:pass@localhost/plenario?encoding=utf8mb4
|
||||
*/
|
||||
'default' => [
|
||||
'driver' => Sqlite::class,
|
||||
'database' => ROOT . DS . 'data' . DS . 'plenario.sqlite',
|
||||
'url' => env('DATABASE_URL', null),
|
||||
],
|
||||
'test' => [
|
||||
'driver' => Sqlite::class,
|
||||
'database' => ROOT . DS . 'tmp' . DS . 'tests.sqlite',
|
||||
'url' => env('DATABASE_TEST_URL', null),
|
||||
],
|
||||
],
|
||||
|
||||
'EmailTransport' => [
|
||||
/*
|
||||
* Local default: mails are written as .eml files to tmp/mails/.
|
||||
* For real delivery set SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD and SMTP_TLS
|
||||
* (see config/.env.example); then this override is skipped.
|
||||
*/
|
||||
// Mails are written as .eml files to tmp/mails/ unless an SMTP server is configured
|
||||
'default' => env('SMTP_HOST') || env('EMAIL_TRANSPORT_DEFAULT_URL') ? [] : [
|
||||
'className' => \App\Mailer\Transport\FileTransport::class,
|
||||
],
|
||||
|
||||
@@ -33,6 +33,10 @@ return function (RouteBuilder $routes): void {
|
||||
$builder->connect('/p/{code}/state', 'Participate::state', ['_name' => 'participate:state'])
|
||||
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
|
||||
->setPass(['code']);
|
||||
// Slide images (also used by presenter and embed): random file name, only images of this poll.
|
||||
$builder->connect('/p/{code}/img/{file}', 'Participate::image', ['_name' => 'participate:image'])
|
||||
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}', 'file' => '[a-f0-9]{24}\.webp'])
|
||||
->setPass(['code', 'file']);
|
||||
$builder->connect('/p/{code}/vote', 'Participate::vote', ['_name' => 'participate:vote'])
|
||||
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
|
||||
->setPass(['code'])
|
||||
@@ -72,7 +76,9 @@ return function (RouteBuilder $routes): void {
|
||||
$admin->connect('/delete', 'Admin::delete', ['_name' => 'admin:delete'])
|
||||
->setPatterns($token)->setMethods(['POST']);
|
||||
$admin->connect('/present', 'Admin::present', ['_name' => 'admin:present'])->setPatterns($token);
|
||||
$admin->connect('/speaker', 'Admin::speaker', ['_name' => 'admin:speaker'])->setPatterns($token);
|
||||
$admin->connect('/state', 'Admin::state', ['_name' => 'admin:state'])->setPatterns($token);
|
||||
$admin->connect('/live', 'Admin::live', ['_name' => 'admin:live'])->setPatterns($token);
|
||||
$admin->connect('/control', 'Admin::control', ['_name' => 'admin:control'])
|
||||
->setPatterns($token)->setMethods(['POST']);
|
||||
$admin->connect('/qr.svg', 'Admin::qr', ['_name' => 'admin:qr'])->setPatterns($token);
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Entwicklerdokumentation
|
||||
|
||||
Details zu PlenarIO. Die zentrale Einstiegsdatei mit Rolle, Befehlen, Konventionen und den Regeln, die nie gebrochen
|
||||
werden dürfen, ist [AGENTS.md](../AGENTS.md). Die [README](../README.md) gibt den Überblick für Anwender.
|
||||
|
||||
| Dokument | Inhalt |
|
||||
|---|---|
|
||||
| [development.md](development.md) | Lokal starten, Tests, Mitarbeit |
|
||||
| [architecture.md](architecture.md) | Verzeichnisstruktur, Klassen, Datenmodell |
|
||||
| [slide-types.md](slide-types.md) | Folientypen im Detail, Checkliste für neue Typen |
|
||||
| [images.md](images.md) | Folienbilder |
|
||||
| [presenter.md](presenter.md) | Live-Schaltung, Pause, Ausblenden, Zurücksetzen, Duplizieren, Einbettung, internes Feedback |
|
||||
| [frontend.md](frontend.md) | Dashboard-Fragmente, Farbschema, Textformatierung, Vollbild |
|
||||
| [pdf-export.md](pdf-export.md) | PDF-Export |
|
||||
| [operations.md](operations.md) | Ablauf von Umfragen, Deployment, Releases, Docker |
|
||||
| [deployment.md](deployment.md) | Anleitung für Betreiber: Docker, ohne Docker, Cronjob, Admin-CLI, Gitea Actions, Releases |
|
||||
| [configuration.md](configuration.md) | Alle Umgebungsvariablen |
|
||||
|
||||
Wer Verhalten ändert, pflegt das passende Dokument mit (und AGENTS.md nur, wenn sich eine zentrale Regel ändert).
|
||||
@@ -0,0 +1,73 @@
|
||||
# Architektur und Datenmodell
|
||||
|
||||
Verzeichnisstruktur, Klassen und Tabellen im Detail.
|
||||
|
||||
```
|
||||
config/
|
||||
app.php Defaults inkl. Block 'Plenario' (Captcha, Throttle, Polling) und Cache 'throttle'
|
||||
app_local.example.php Dev-Defaults (debug, FileTransport), von `composer install` nach app_local.php kopiert (gitignored, nur lokal, nie in Produktion)
|
||||
.env.example Alle Umgebungsvariablen (config/.env wird optional geladen)
|
||||
routes.php Alle Routen benannt, KEINE Fallback-Routen
|
||||
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/
|
||||
AppController Basis aller Controller: `joinUrl()`, `adminUrlFor()`, `setPollInterval()`, `throttle()`, `json()`,
|
||||
`protect()` (no-referrer/noindex/no-store für Seiten mit Geheimnis in der URL: Admin, Embed)
|
||||
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 (no-referrer, no-store)
|
||||
AdminController Dashboard, Settings, Present, State-JSON, Control, QR, PDF-Export, Token rotieren, Zurücksetzen, Löschen
|
||||
SlidesController Folien-CRUD, Ein-/Ausblenden (`visibility`), Duplizieren (`duplicate` → `SlidesTable::duplicate()`, Kopie direkt dahinter, öffnet das Formular der Kopie), Antworten offener Fragen bzw. Skala-Auswertung (`answers`), Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen,
|
||||
YouTube-Link prüfen (`youtubeCheck`, JSON)
|
||||
ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen, eigene Antwort/Kommentar bearbeiten; 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`)
|
||||
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
|
||||
für alle Antworten inkl. JSON und Fehlerseiten; vom Controller gesetzte Header gewinnen
|
||||
Model/ Polls → Slides → SlideOptions, Slides → Responses
|
||||
Service/
|
||||
VoteService Validiert + speichert Antworten (alle Abstimmungsregeln hier)
|
||||
ResultsService Aggregiert Ergebnisse je Folientyp (JSON-Struktur im Docblock)
|
||||
PollStateService State-JSON für Presenter und Teilnehmende
|
||||
ThrottleService Rate-Limit pro IP (Cache 'throttle'), in Controllern über `AppController::throttle()`:
|
||||
Anlegen/Recover pro Stunde, Antworten (`vote`) pro Minute (`THROTTLE_VOTES_PER_MINUTE`, 429)
|
||||
ImageService Folienbilder: prüfen, drehen (EXIF), auf `maxEdge` verkleinern, als WebP speichern, löschen, aufräumen
|
||||
YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client)
|
||||
QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen
|
||||
SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam)
|
||||
ResetService Antworten löschen: einzelne Folie (`slide`) bzw. alle Folien der Umfrage (`poll`)
|
||||
ReportService Daten für den PDF-Export: Ergebnisse aller interaktiven Folien, mit/ohne interne Inhalte
|
||||
View/PdfView.php Rendert Template als HTML (Layout `pdf`) und wandelt es mit Dompdf in ein PDF
|
||||
templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email
|
||||
webroot/css/plenario.css Eigenes CSS, kein Framework; Farben nur als Tokens (Hell/Dunkel, siehe Theme unten)
|
||||
webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Sortieren (`makeSortable`: Pointer Events + Pfeiltasten,
|
||||
genutzt für Folienliste, Reihenfolge-Editor und Teilnehmer-Antwort)
|
||||
tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures sind leer
|
||||
```
|
||||
|
||||
## 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`,
|
||||
`last_admin_access` (höchstens alle 10 min aktualisiert, nur Anzeige in `polls list|show`),
|
||||
`expiry_reminded_at` (Erinnerungsmail vor dem Ablauf verschickt, siehe [operations.md](operations.md)),
|
||||
`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`,
|
||||
`is_hidden` (ausgeblendet: vorbereitet, aber nicht Teil der Präsentation),
|
||||
`settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open`,
|
||||
`voting_started_at` / `voting_ends_at` (nur Quiz: Start und Deadline, `null` = manuell beenden),
|
||||
`stage` / `focus_response_id` (nur Q&A: Phase und gerade besprochene Frage)
|
||||
- `slides.image` / `image_alt` / `image_layout` / `image_width` / `image_height`: optionales Bild (siehe [images.md](images.md))
|
||||
- `slide_options`: Antwortoptionen für `choice`, `quiz` und `order`; `is_correct` markiert richtige Quiz-Antworten,
|
||||
bei `order` ist `position` die richtige Reihenfolge
|
||||
- `responses`: `participant_hash`, `slide_option_id` | `text_value` | `numeric_value` | `parent_id`.
|
||||
Mehrfachauswahl/mehrere Wörter = mehrere Zeilen mit gleichem `participant_hash`.
|
||||
Q&A: Frage = Zeile mit `text_value`, Upvote = Zeile mit `parent_id` (= id der Frage, FK mit CASCADE).
|
||||
Reihenfolge: eine Zeile pro Person, `text_value` = Options-ids kommagetrennt (`VoteService::parseOrder()`).
|
||||
Skala: `numeric_value`, optional Kommentar in `text_value`.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Konfiguration
|
||||
|
||||
Alle Einstellungen über Umgebungsvariablen oder `config/.env`. Anleitung zum Betrieb: [deployment.md](deployment.md).
|
||||
|
||||
Alle Einstellungen gehen über Umgebungsvariablen oder `config/.env`
|
||||
(Vorlage mit allen Variablen: [config/.env.example](../config/.env.example)). Echte Umgebungsvariablen
|
||||
haben Vorrang vor der Datei.
|
||||
|
||||
**Pflicht in Produktion:** `DEBUG=false`, `APP_FULL_BASE_URL`, `SECURITY_SALT` und ein Mail-Transport (`SMTP_HOST`).
|
||||
Alles andere ist optional und hat einen Standardwert. In der Spalte „Standard“ bedeutet „–“: kein Standard, der Wert muss gesetzt werden.
|
||||
|
||||
| Variable | Pflicht? | Standard | Bedeutung |
|
||||
|---|---|---|---|
|
||||
| `DEBUG` | Produktion: ja | `false` (lokal: die von Composer erzeugte `app_local.php` setzt `true`) | In Produktion `false` lassen, sonst werden Admin-Links direkt angezeigt |
|
||||
| `APP_FULL_BASE_URL` | Produktion: ja | – (lokal `http://localhost:8765`) | Öffentliche URL inkl. `https://`, wird für Links in E-Mails gebraucht. In Produktion wird außerdem der Host-Header dagegen geprüft |
|
||||
| `SECURITY_SALT` | ja | – (lokal wird er von Composer erzeugt) | Langer Zufallswert. **Nicht nachträglich ändern** – damit werden Admin-Tokens verschlüsselt und Teilnehmer-IDs gehasht |
|
||||
| `DATABASE_URL` | optional | leer = SQLite in `data/` | Sonst z. B. `mysql://user:pw@host/plenario?encoding=utf8mb4` oder `postgres://user:pw@host/plenario` |
|
||||
| `SMTP_HOST` | Produktion: ja | leer = Mails nur als Datei in `tmp/mails/` (per `app_local.php`), sonst PHP `mail()` | Mailserver. Ohne ihn kommt der Admin-Link nie bei den Nutzenden an. **Achtung:** Eine `config/app_local.php` hat Vorrang vor `.env`; ein `FileTransport` darin (ältere Vorlage) überschreibt SMTP, die Mails landen dann nur in `tmp/mails/`. Auf Servern gehört keine `app_local.php` hin, sie ist nur für die lokale Entwicklung. `bin/cake polls remind` zeigt den verwendeten Transport an und warnt davor |
|
||||
| `SMTP_PORT` | optional | `587` | Port 465 nutzt automatisch SSL |
|
||||
| `SMTP_USER`, `SMTP_PASSWORD` | optional | leer | Zugangsdaten, falls der Mailserver sie verlangt |
|
||||
| `SMTP_TLS` | optional | `true` | `true` = STARTTLS, `false` = unverschlüsselt |
|
||||
| `MAIL_FROM` | empfohlen | `noreply@localhost` | Absenderadresse, sollte zum Mailserver passen |
|
||||
| `MAIL_FROM_NAME` | optional | `PlenarIO` | Absendername |
|
||||
| `CAPTCHA_TYPE` | optional | `math` | `none`, `math` (Rechenaufgabe) oder `recaptcha` |
|
||||
| `RECAPTCHA_SITE_KEY`, `RECAPTCHA_SECRET_KEY` | nur bei `recaptcha` | leer | Für reCAPTCHA v2 („Ich bin kein Roboter“) |
|
||||
| `SHOW_ADMIN_LINK_AFTER_CREATE` | optional | Wert von `DEBUG` | Nur für Entwicklung, in Produktion nie aktivieren |
|
||||
| `THROTTLE_CREATE_PER_HOUR` | optional | `10` | Umfragen pro IP und Stunde (0 = aus) |
|
||||
| `THROTTLE_RECOVER_PER_HOUR` | optional | `5` | Wiederherstellungs-Mails pro IP und Stunde (0 = aus) |
|
||||
| `THROTTLE_VOTES_PER_MINUTE` | optional | `600` | Antworten pro IP und Minute (0 = aus). Hoch lassen: Oft teilt sich ein ganzer Saal eine IP |
|
||||
| `POLL_RETENTION_DAYS` | optional | `90` | Umfragen werden so viele Tage nach dem Anlegen vom Cronjob gelöscht (0 = nie) |
|
||||
| `POLL_REMINDER_DAYS` | optional | `14` | So viele Tage vorher bekommt der Besitzer eine Erinnerungsmail (0 = keine, muss kleiner als die Laufzeit sein) |
|
||||
| `POLL_INTERVAL_MS` | optional | `2000` | Aktualisierungsintervall der Live-Ansichten in Millisekunden |
|
||||
| `EMBED_HEARTBEAT_SECONDS` | optional | `5` | Eingebettete Folien: Intervall des Lebenszeichens |
|
||||
| `EMBED_TIMEOUT_SECONDS` | optional | `20` | Eingebettete Folien: Zeit ohne Lebenszeichen bis zur automatischen Pause |
|
||||
| `EMBED_FRAME_ANCESTORS` | optional | `*` (alle) | Welche Seiten Folien einbetten dürfen (CSP `frame-ancestors`), z. B. `https://*.canva.com` |
|
||||
|
||||
Einen `SECURITY_SALT` erzeugen:
|
||||
|
||||
```bash
|
||||
php -r "echo bin2hex(random_bytes(32));"
|
||||
# oder ohne PHP:
|
||||
openssl rand -hex 32
|
||||
```
|
||||
@@ -0,0 +1,211 @@
|
||||
# Deployment
|
||||
|
||||
Betrieb von PlenarIO: Docker (nur Testbetrieb), Installation ohne Docker, Cronjob, Admin-CLI, Gitea Actions und Releases.
|
||||
Alle Variablen: [configuration.md](configuration.md).
|
||||
|
||||
## Deployment mit Docker
|
||||
|
||||
> **Nur für Testzwecke.** Das Docker-Image ist zum Ausprobieren und für Tests gedacht und **nicht für den
|
||||
> Produktionsbetrieb geeignet**: Es nutzt den eingebauten PHP-Server (kein Webserver wie Apache oder nginx mit PHP-FPM)
|
||||
> und SQLite in einem Volume. Für den echten Betrieb siehe [Deployment ohne Docker](#deployment-ohne-docker).
|
||||
|
||||
Das [Dockerfile](../Dockerfile) baut ein schlankes Image (`php:8.5-cli-alpine`, Multi-Stage mit Composer).
|
||||
Der eingebaute PHP-Server läuft mit 8 Workern auf Port **8765**, die SQLite-Datenbank und die Folienbilder (`/data/uploads`)
|
||||
liegen im Volume `/data`.
|
||||
Beim Start laufen die Migrationen automatisch (idempotent, mehrfaches Starten ist unproblematisch).
|
||||
|
||||
Das fertige Image liegt in der Gitea-Registry:
|
||||
`gitea.gnilebein.de/gnilebein/plenario:latest` (letzter stabiler Release). Für feste Versionen gibt es die
|
||||
SemVer-Tags `:1.4.0`, `:1.4` und `:1` (Pre-Releases wie `v1.5.0-rc.1` nur als `:1.5.0-rc.1`).
|
||||
Gebaut wird das Image nur bei einem neuen Release-Tag, siehe [Releases](#releases-und-versionierung).
|
||||
|
||||
### Schnellstart mit `docker run`
|
||||
|
||||
```bash
|
||||
docker run -d --name plenario -p 8765:8765 -v plenario-data:/data \
|
||||
-e SECURITY_SALT="$(openssl rand -hex 32)" \
|
||||
-e APP_FULL_BASE_URL=https://plenario.example.org \
|
||||
-e MAIL_FROM=noreply@example.org \
|
||||
-e SMTP_HOST=mail.example.org -e SMTP_PORT=587 \
|
||||
-e SMTP_USER=noreply@example.org -e SMTP_PASSWORD='geheim' \
|
||||
--restart unless-stopped \
|
||||
gitea.gnilebein.de/gnilebein/plenario:latest
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
1. Eine `.env` neben der [docker-compose.yml](../docker-compose.yml) anlegen (Vorlage: [config/.env.example](../config/.env.example)):
|
||||
|
||||
```dotenv
|
||||
SECURITY_SALT=<64 Zeichen Zufall, siehe oben>
|
||||
APP_FULL_BASE_URL=https://plenario.example.org
|
||||
MAIL_FROM=noreply@example.org
|
||||
MAIL_FROM_NAME=PlenarIO
|
||||
SMTP_HOST=mail.example.org
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=noreply@example.org
|
||||
SMTP_PASSWORD=geheim
|
||||
SMTP_TLS=true
|
||||
CAPTCHA_TYPE=math
|
||||
```
|
||||
|
||||
2. Starten:
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
docker compose logs -f plenario # Start und Migrationen beobachten
|
||||
```
|
||||
|
||||
3. Aktualisieren auf die neueste Version:
|
||||
|
||||
```bash
|
||||
docker compose pull && docker compose up -d
|
||||
```
|
||||
|
||||
Die Datenbank bleibt im Volume `plenario-data` erhalten; neue Migrationen laufen beim Start automatisch.
|
||||
|
||||
Statt das Image zu ziehen, lässt sich auch lokal bauen: in der `docker-compose.yml` die Zeile `# build: .`
|
||||
aktivieren oder `docker build -t plenario .` ausführen.
|
||||
|
||||
### Wichtig im Container
|
||||
|
||||
- **Cronjob:** Der Container führt kein cron aus. Das Ablaufen und Erinnern von Umfragen braucht einen Aufruf vom Host,
|
||||
siehe [Cronjob einrichten](#cronjob-einrichten).
|
||||
|
||||
- **`SECURITY_SALT` ist Pflicht.** Fehlt er, bricht der Start mit einer Fehlermeldung ab. Er wird nicht ins Image
|
||||
eingebrannt, sondern zur Laufzeit gesetzt. Nach dem ersten Einsatz **nie mehr ändern** (sonst werden
|
||||
Admin-Tokens unlesbar und Teilnehmer-IDs ungültig).
|
||||
- **`APP_FULL_BASE_URL` muss die öffentliche URL sein**, inklusive `https://`. Sie wird für die Links in
|
||||
E-Mails verwendet, und in Produktion wird der Host-Header dagegen geprüft.
|
||||
- **Mail-Versand einrichten.** Ohne `SMTP_HOST` schreibt PlenarIO Mails nur als Datei ins
|
||||
Container-Dateisystem – der Admin-Link kommt dann **nie** bei den Nutzenden an.
|
||||
- **TLS-Proxy davorschalten** (Caddy, nginx, Traefik, …), der `X-Forwarded-Proto` setzt. Der eingebaute
|
||||
PHP-Server spricht nur HTTP. Beispiel für Caddy:
|
||||
|
||||
```
|
||||
plenario.example.org {
|
||||
reverse_proxy localhost:8765
|
||||
}
|
||||
```
|
||||
|
||||
- **Daten sichern:** Alles Wichtige liegt in `/data` (SQLite-Datei `plenario.sqlite`). Backup z. B. mit
|
||||
`docker run --rm -v plenario-data:/data -v "$PWD":/backup alpine tar czf /backup/plenario-data.tgz -C /data .`
|
||||
- **Bind-Mount statt Volume:** Der Container läuft als Benutzer `www-data` (UID 82). Das Host-Verzeichnis
|
||||
muss für ihn beschreibbar sein (`chown 82:82 ./data`).
|
||||
- **Andere Datenbank:** Für viele gleichzeitige Teilnehmende `DATABASE_URL` auf MySQL/PostgreSQL setzen
|
||||
(siehe [Betrieb & Skalierung](../README.md#betrieb--skalierung)).
|
||||
- **Healthcheck:** Das Image prüft eine statische Datei (`/css/plenario.css`), weil die Host-Prüfung echte Seiten
|
||||
bei Aufrufen über `127.0.0.1` ablehnen würde.
|
||||
- **Weitere Einstellungen** (Captcha, Rate-Limits, Polling, Einbettung) gehen ebenfalls per Umgebungsvariable,
|
||||
siehe [Konfiguration](configuration.md).
|
||||
|
||||
## Deployment ohne Docker
|
||||
|
||||
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` 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.
|
||||
|
||||
Folienbilder landen in `data/uploads` (anderer Ort: `UPLOADS_PATH`), nie unter `webroot/`; das Verzeichnis gehört in die
|
||||
Datensicherung. Voraussetzungen: PHP-Erweiterung `gd` mit WebP sowie `upload_max_filesize` und `post_max_size` passend zu
|
||||
`IMAGE_MAX_UPLOAD_MB` (Standard 10 MB, PHP-Standard sind nur 2 MB bzw. 8 MB). Dateien ohne Folie (z. B. nach einem Absturz)
|
||||
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)
|
||||
|
||||
Zum Verwalten per Hand und für Skripte/Cron:
|
||||
|
||||
| Befehl | Zweck |
|
||||
|---|---|
|
||||
| `bin/cake polls list [--expired] [--email=text] [--sort=created\|activity\|title] [--json]` | Umfragen mit E-Mail, Ablaufdatum und Erinnerung |
|
||||
| `bin/cake polls show <id\|code> [--link] [--json]` | Details; mit `--link` auch der geheime Admin-Link (nur auf Wunsch) |
|
||||
| `bin/cake polls delete <id\|code> [--yes]` | Eine Umfrage samt Folien, Antworten und Bildern löschen (fragt nach) |
|
||||
| `bin/cake polls remind [<id\|code>] [--dry-run]` | Erinnerungsmails für bald ablaufende Umfragen (je Umfrage einmal). Mit ID oder Code geht die Mail sofort und erzwungen nur an diese Umfrage, zum Testen: unabhängig vom Erinnerungsfenster und von `POLL_REMINDER_DAYS`, beliebig oft, ohne die Umfrage als erinnert zu markieren (die reguläre Erinnerung kommt trotzdem noch) |
|
||||
| `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.
|
||||
|
||||
Mit `--json` geben `polls list` und `polls show` statt der Tabelle bzw. des Texts reines JSON aus (Datumswerte als
|
||||
ISO 8601, ohne weitere Ausgabe), z. B. für `jq`: `bin/cake polls list --json --expired | jq '.[].email'`. Der Admin-Link
|
||||
steht auch dort nur mit `--link` (`adminUrl`, sonst `null`).
|
||||
|
||||
### Cronjob einrichten
|
||||
|
||||
Ein einziger täglicher Cronjob erledigt Erinnern, Löschen und Bild-Aufräumen (`polls cleanup`). Ohne ihn läuft keine
|
||||
Umfrage ab und niemand wird erinnert.
|
||||
|
||||
**Server mit Shell/DirectAdmin** (Menü „Cronjobs“ bzw. `crontab -e`), täglich um 3:17 Uhr:
|
||||
|
||||
```
|
||||
17 3 * * * cd /pfad/zu/plenario && /pfad/zu/php bin/cake.php polls cleanup --quiet
|
||||
```
|
||||
|
||||
- Das Verzeichnis muss das Projektstammverzeichnis sein (dort liegt `config/.env`, sie wird automatisch gelesen).
|
||||
Den PHP-Pfad zeigt `which php` bzw. in DirectAdmin die PHP-Auswahl, z. B. `/usr/local/php84/bin/php`; es muss PHP ≥ 8.4 sein.
|
||||
- `--quiet` unterdrückt die Ausgabe bei Erfolg. Fehler (z. B. ein fehlgeschlagener Mailversand) erscheinen trotzdem,
|
||||
Exit-Code 1; mit gesetzter `MAILTO` schickt cron sie per Mail. Ein Protokoll geht mit `>> logs/cleanup.log 2>&1`.
|
||||
- Der Benutzer des Cronjobs braucht Schreibrechte auf `tmp/`, `logs/`, `data/` (Datenbank, Bilder), derselbe Benutzer wie der Webserver.
|
||||
- Die Erinnerungsmails brauchen den produktiven Mail-Transport (`SMTP_*`) und `APP_FULL_BASE_URL` in der `config/.env`,
|
||||
sonst stimmen die Links nicht.
|
||||
|
||||
**Docker** (nur Testbetrieb): Im Container läuft kein cron, der Aufruf kommt vom Host:
|
||||
|
||||
```
|
||||
17 3 * * * cd /pfad/zu/compose && docker compose exec -T plenario bin/cake polls cleanup --quiet
|
||||
```
|
||||
|
||||
**Erster Einsatz:** Umfragen, die zu dem Zeitpunkt schon älter als `POLL_RETENTION_DAYS` sind, werden ohne Erinnerung
|
||||
gelöscht (die Mail geht nur im Fenster vor dem Ablauf raus). Deshalb erst prüfen und dann den Cronjob anlegen:
|
||||
|
||||
```
|
||||
bin/cake polls list --expired # was wäre sofort weg?
|
||||
bin/cake polls cleanup --dry-run # Erinnerungen und Löschungen nur anzeigen
|
||||
```
|
||||
|
||||
Der Befehl ist idempotent: mehrfaches Ausführen (auch zweimal am Tag) verschickt keine Erinnerung doppelt und
|
||||
löscht nichts Zusätzliches.
|
||||
|
||||
## Automatisches Deployment (Gitea Actions)
|
||||
|
||||
[.gitea/workflows/ci.yml](../.gitea/workflows/ci.yml) testet jeden Push (PHPUnit + phpcs).
|
||||
`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.
|
||||
|
||||
Der Workflow bedient vor allem die Instanz unter <https://plenario.gnilebein.de/>, ist aber nicht fest darauf
|
||||
verdrahtet: Ziel und Werkzeuge kommen ausschließlich aus Repository-Variablen (`SSH_HOST`, `SSH_PORT`, `SSH_USER`,
|
||||
`DEPLOY_PATH`, optional `PHP_BIN`/`COMPOSER_BIN`) und Secrets (`SSH_KEY` oder `SSH_PASSWORD`). Wer PlenarIO auf einem
|
||||
eigenen Server betreibt, setzt dort seine Werte und `DEPLOY_ENABLED=true` – die Workflow-Datei bleibt unverändert.
|
||||
Voraussetzungen: SSH-Zugang mit Shell, `git` und PHP ≥ 8.4 auf dem Server, der Server erreicht die Gitea-Instanz per
|
||||
HTTPS. Ohne `DEPLOY_ENABLED` passiert nichts (Standard).
|
||||
|
||||
## Releases und Versionierung
|
||||
|
||||
PlenarIO nutzt [Semantic Versioning](https://semver.org/lang/de/) (`MAJOR.MINOR.PATCH`): Major bei inkompatiblen
|
||||
Änderungen (z. B. Schema-/Konfigurationsumbrüche), Minor für neue Funktionen, Patch für Fehlerbehebungen.
|
||||
Eine Version entsteht durch einen Tag auf `main`:
|
||||
|
||||
```bash
|
||||
git tag v1.4.0 && git push origin v1.4.0 # Pre-Release: v1.5.0-rc.1
|
||||
```
|
||||
|
||||
Der Workflow [.gitea/workflows/release.yml](../.gitea/workflows/release.yml) läuft nur bei solchen Tags (`vX.Y.Z[-suffix]`),
|
||||
führt zuerst die Tests aus und erzeugt dann
|
||||
|
||||
- ein **App-Paket** `plenario-<version>.tar.gz` samt `SHA256SUMS` als Anhang des Gitea-Releases (fertig mit
|
||||
Produktions-`vendor/`, nur die Anwendung (Whitelist), ohne Tests, CI, Docker und Entwicklerdateien, `VERSION`-Datei enthalten; Einrichtung wie unter
|
||||
[Deployment ohne Docker](#deployment-ohne-docker), nur ohne Composer-Schritt) und
|
||||
- das **Docker-Image** mit den Tags `:<version>`, `:<major>.<minor>`, `:<major>` und `:latest`.
|
||||
|
||||
Tags mit Suffix (`-rc.1`, `-beta.2`) werden als Pre-Release markiert und bekommen weder `:latest` noch `:<major>`.
|
||||
Der Workflow ist wiederholbar: ein erneuter Lauf aktualisiert das vorhandene Release.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Entwicklung
|
||||
|
||||
Lokales Setup, Tests und Mitarbeit. Regeln und Konventionen: [AGENTS.md](../AGENTS.md).
|
||||
|
||||
## Lokal starten
|
||||
|
||||
Voraussetzungen: PHP 8.4+ mit den Erweiterungen `intl`, `mbstring`, `openssl`, `pdo_sqlite`, `curl`, `gd` (mit WebP)
|
||||
sowie [Composer](https://getcomposer.org/).
|
||||
|
||||
```bash
|
||||
git clone https://gitea.gnilebein.de/gnilebein/Plenario.git
|
||||
cd Plenario
|
||||
composer install # legt config/app_local.php an (nur Dev-Defaults: debug, Mails als Datei)
|
||||
bin/cake migrations migrate # erstellt data/plenario.sqlite
|
||||
bin/cake server -p 8765 # http://localhost:8765
|
||||
```
|
||||
|
||||
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.
|
||||
Zurücksetzen der lokalen Daten: `data/plenario.sqlite` löschen und die Migrationen erneut laufen lassen.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
vendor/bin/phpunit # nutzt tmp/tests.sqlite, Schema kommt aus den Migrationen
|
||||
vendor/bin/phpcs # CakePHP Coding Standard (Autofix: vendor/bin/phpcbf)
|
||||
```
|
||||
|
||||
Vor jedem Commit müssen beide grün sein. `main` ist geschützt: Änderungen auf einem eigenen Branch pushen und per Pull Request mergen.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Frontend und Oberfläche
|
||||
|
||||
Dashboard-Fragmente, Farbschema, Textformatierung, Vollbild. CSP-Regeln stehen in [AGENTS.md](../AGENTS.md).
|
||||
|
||||
## Dashboard ohne Neuladen
|
||||
|
||||
- **Einklappbare Seitenleiste** der Verwaltung: `<details class="card collapsible">` mit `<summary><h2>`. Standard: Teilnahme,
|
||||
Einstellungen (direkt unter dem QR-Code) offen; „Ergebnisse als PDF“, „In Präsentation einbetten“ und „Sicherheit“ zu.
|
||||
Offene Karten trennt eine Linie zwischen Überschrift und Inhalt.
|
||||
Anker-Links wie `#export` öffnen ihre Karte (`openCollapsible()` in `plenario.js`).
|
||||
|
||||
- **Dashboard ohne Neuladen** (`initAdminDashboard()`, `Fragments` in `plenario.js`): Formulare in `[data-live]` (Folienliste, Kopf)
|
||||
und das Folienformular im `<dialog>` laufen per `fetch` mit Header `X-Fragment`; `AdminAppController::beforeRender()` nimmt dann
|
||||
das Layout `fragment` (nur Inhalt + Flash). Die Server-Aktionen bleiben normale POST + Redirect, das JS tauscht die Bereiche
|
||||
`[data-refresh="head|slides|flash"]` (als DOM-Knoten, nie `innerHTML`) und stellt den Fokus wieder her. Bearbeiten/Anlegen:
|
||||
Links mit `data-modal` laden das Formular (`[data-modal-content]`) in den Dialog; Validierungsfehler kommen als Formular
|
||||
zurück (Dialog bleibt offen), Erfolg als Dashboard-Fragment (Dialog schließt). Ohne JS funktioniert alles als normale Seite.
|
||||
Die Liste folgt auch dem Presenter (Live-Markierung, Status): `initAdminDashboard()` pollt `admin:live` (`AdminController::live()`,
|
||||
nur `{version}` aus `PollStateService::dashboardVersion()`, billiger als der Presenter-State) und lädt `head`/`slides` nur bei geänderter Version
|
||||
neu – nie bei offenem Dialog, laufender Anfrage oder Drag & Drop; der Fokus wird wiederhergestellt. Wechselt dabei die Live-Folie, scrollt `revealCurrent()` sie per `scrollIntoView({block: 'nearest'})` in den
|
||||
sichtbaren Bereich (bei langen Listen; bewegt nichts, wenn sie schon sichtbar ist; ohne Animation bei `prefers-reduced-motion`). Test: `PollResetTest::testDashboardLiveVersionFollowsThePresenter`.
|
||||
**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`.
|
||||
|
||||
## Farbschema (Tag/Nacht)
|
||||
|
||||
`data-theme="light|dark"` auf `<html>`, ohne Attribut gilt die Systemeinstellung. `element/theme_init` setzt die
|
||||
Wahl aus `localStorage` vor dem ersten Rendern (Inline-Skript im `<head>`), `element/theme_switch` ist der Schalter
|
||||
(`Theme` in `plenario.js`). Presenter: eigener Schlüssel `plenario-theme-present`, Standard dunkel, Taste T.
|
||||
Neue Farben als Token in beiden Dark-Blöcken von `plenario.css` pflegen; auf der Bühne Overlays mit `rgba(var(--tint), …)`.
|
||||
|
||||
## Formatierung von Folientexten
|
||||
|
||||
- **Formatierung von Folientexten** (nur `description`, nie Eingaben von Teilnehmenden) im WhatsApp-Stil: `*fett*`,
|
||||
`_kursiv_`, `~durchgestrichen~`, Aufzählung mit `- `/`* ` am Zeilenanfang, Zeilenumbrüche. Zwei gleiche Implementierungen:
|
||||
`FormatHelper::text()` (PHP: Teilnehmerseite, PDF; escapt alles und erzeugt nur diese Tags) und `Format` in `plenario.js`
|
||||
(Presenter/Embed; baut DOM-Knoten, kein `innerHTML`). Regeln in beiden gleich halten (Regex `INLINE`/`LIST_ITEM`),
|
||||
Tests: `FormatHelperTest.php`.
|
||||
|
||||
## Vollbild & Display anlassen
|
||||
|
||||
- **Vollbild & Display anlassen** (Teilnehmeransicht, `initScreenTools` in `plenario.js`): zwei optionale Icon-Buttons im Header neben dem Farbschema-Schalter (Layout-Block `headerTools`)
|
||||
(`data-fullscreen-toggle`, `data-wakelock-toggle`), bleiben ohne Browser-Unterstützung versteckt (iPhone-Safari kennt kein Vollbild).
|
||||
Der Wake Lock ist standardmäßig an (braucht keine Nutzergeste); nur ein bewusstes Ausschalten wird gemerkt.
|
||||
Die Seite lädt bei Folienwechsel neu: der Wake Lock wird per `sessionStorage` (`plenario-wakelock`) wieder angefordert,
|
||||
Vollbild braucht eine Nutzergeste und muss nach dem Wechsel ggf. neu gewählt werden.
|
||||
|
||||
## Favicon
|
||||
|
||||
Das Logo (`.brand__mark` in `plenario.css`) ist auch das Favicon: `webroot/favicon.svg` (moderne Browser), `favicon.ico`
|
||||
(16/32/48 px, Fallback) und `apple-touch-icon.png` (180 px, iOS, deckend ohne Rundung, die macht iOS selbst). Eingebunden über
|
||||
`templates/element/favicon.php` in allen drei Layouts (default, present, error). Die Dateien sind statisch und werden aus
|
||||
einer Geometrie erzeugt (auch das Mail-Logo, siehe unten): Ändert sich das Logo, `php resources/favicon/generate.php webroot` ausführen (braucht `ext-gd`)
|
||||
und Farben/Anteile im Skript an `.brand__mark` angleichen. Test: `FaviconTest.php`.
|
||||
|
||||
## E-Mail-Layout
|
||||
|
||||
`templates/layout/email/html/default.php` übernimmt Logo und Farben der Webseite (Light-Theme): Hintergrund `--bg`, Text `--text`,
|
||||
Grau `--muted`, Buttons/Links und „IO“ in `--primary`. Mails kennen weder Stylesheets noch SVG, deshalb stehen die Werte als
|
||||
Inline-Styles (Tabelle für die Markenzeile) im Layout und in den Mail-Templates. **Ändert sich ein Token in `plenario.css`,
|
||||
die Hex-Werte in `templates/layout/email/` und `templates/email/html/` nachziehen.** Das Logo ist `resources/mail/logo.png`
|
||||
(wird vom Favicon-Generator mit erzeugt) und hängt als Inline-Anhang (`cid:`) an jeder Mail: `PollMailer` fügt es im Konstruktor
|
||||
hinzu, so erscheint es auch ohne „Bilder laden“ und ohne öffentliche Basis-URL. Test: `PollMailerTest.php`.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Folienbilder
|
||||
|
||||
Ein Bild pro Folie: Upload, Verarbeitung, Auslieferung und Löschregeln.
|
||||
|
||||
- **Folienbilder** (ein Bild pro Folie, alle Typen außer `youtube`, `Slide::supportsImage()`): Upload im Folienformular (multipart,
|
||||
`SlidesController::prepareImage()`), verarbeitet von `ImageService::store()`: Format per `getimagesizefromstring` (JPEG/PNG/GIF/WebP,
|
||||
**kein SVG, keine animierten GIFs**), EXIF-Drehung (eigener Parser, die `exif`-Erweiterung fehlt oft), längste Kante höchstens
|
||||
`Plenario.images.maxEdge` (1600), Ausgabe immer WebP (entfernt alle Metadaten inkl. GPS). Das Original wird nie gespeichert.
|
||||
Ablage `{Plenario.images.path}/{poll_id}/{24 Hex}.webp` (Standard `data/uploads`, Docker `/data/uploads`) **außerhalb von `webroot/`**,
|
||||
ausgeliefert über `participate:image` (`/p/{code}/img/{file}`, auch für Presenter und Einbettung; nur Dateien dieser Umfrage, `immutable`
|
||||
gecacht, kein Cookie). Jedes neue Bild bekommt einen neuen Namen → neue URL, ersetzte Bilder sind sofort 404.
|
||||
Eine Bildbeschreibung wird bewusst nicht abgefragt (`image_alt` bleibt `""`, die Spalte ist ungenutzt): Bilder sind Beamer-Dekoration. Nie Pflichtfelder zum Bild einführen, die den Upload verwerfen: das Dateifeld lässt sich nach einem Fehler nicht neu füllen. Layout `image_layout` (`top`|`side`|`full`, `full` nur
|
||||
Inhaltsfolien, `null` = Standard je Typ: Inhaltsfolie `side`, sonst `top`; `Slide::imageLayout()`); `side` gilt nur für die Bühne
|
||||
(CSS `stage--img-*`), Teilnehmende sehen das Bild immer oben (`element/slide_image`). Kontingent `Plenario.images.maxPerPoll` Folien mit Bild.
|
||||
Im State steht `slide.image` = `{url, alt, layout, width, height}` (`PollStateService::slidePayload()`).
|
||||
**Löschen:** die Datei geht nach dem Commit weg, nie davor. Bild ersetzen/entfernen: alte Datei nach erfolgreichem Speichern; Fehler beim
|
||||
Speichern: die neue Datei wird verworfen (`discardImage()`). Folie löschen: explizit im Controller nach der Transaktion
|
||||
(`Model.afterDeleteCommit` feuert **nicht** innerhalb einer äußeren Transaktion). Umfrage löschen: `PollsTable::afterDeleteCommit` räumt das
|
||||
Verzeichnis. Duplizieren kopiert die Datei (kein geteiltes Bild, keine Referenzzählung). Zurücksetzen lässt Bilder unberührt.
|
||||
Reste (Absturz) entfernt `bin/cake images_cleanup`. Beim Patchen von Entity-Feldern ist `patch([...], ['guard' => false])` nötig, und
|
||||
`patch()` setzt Fehler des Feldes zurück: Fehlermeldungen erst danach setzen. Das Upload-Objekt gehört nicht in `patchEntity()` (Marshaller
|
||||
scheitert an `UploadedFile`). Tests: `SlideImageTest.php`, `ImageServiceTest.php` (`ImageTestTrait`).
|
||||
@@ -0,0 +1,68 @@
|
||||
# Betrieb: Ablauf, Deployment, Releases, Docker
|
||||
|
||||
Aufräumen und Erinnerungen, CI/CD, Release-Pakete, Container.
|
||||
|
||||
## Ablauf von Umfragen
|
||||
|
||||
- **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`; Cron-Einrichtung für Server und Docker steht in [deployment.md](deployment.md) unter
|
||||
„Cronjob einrichten“, im Container läuft kein cron). `last_admin_access` fließt nicht mehr ein. `polls show --link`
|
||||
ist die einzige Stelle, die den Admin-Link ausgibt (nie in `list`).
|
||||
`polls list|show --json` gibt nur JSON aus (`PollsCommand::pollData()`/`printJson()`, Ausgabemodus RAW, sonst würden `<…>` in Titeln als
|
||||
Markup verschluckt; nie das Token, `adminUrl` nur mit `--link`).
|
||||
`polls remind <id|code>` erzwingt die Erinnerung für genau eine Umfrage (Testzweck): ignoriert Fenster, Marker und `POLL_REMINDER_DAYS`,
|
||||
setzt `expiry_reminded_at` nicht, braucht aber ein Ablaufdatum (`POLL_RETENTION_DAYS` > 0).
|
||||
Tests: `PollsCommandsTest.php` (leert vorher alle Umfragen).
|
||||
|
||||
## Deployment
|
||||
|
||||
Deploy erfolgt über Git (Remote: Gitea) mit `.gitea/workflows/ci.yml`:
|
||||
|
||||
- Job `phpunit` (PHPUnit + phpcs) läuft bei jedem Push auf jeden Branch, als Matrix gegen PHP 8.4 und 8.5.
|
||||
Der Sammel-Job `test` ist nur grün, wenn alle Matrix-Läufe grün sind, und bleibt der Check, den der Branch-Schutz
|
||||
verlangt (so muss dort bei neuen PHP-Versionen nichts angepasst werden). `main` ist per Branch-Schutz
|
||||
in Gitea gesperrt: kein direkter Push, Merge nur per PR und nur mit grünem Status-Check des Jobs `test`.
|
||||
- Job `deploy` läuft nur bei Push auf `main`, nur bei grünen Tests und **nur wenn die Repo-Variable
|
||||
`DEPLOY_ENABLED=true` gesetzt ist** (standardmäßig deaktiviert). Er verbindet sich per SSH
|
||||
(DirectAdmin, `plenario.gnilebein.de`, Checkout direkt in `public_html`), holt den Code per HTTPS mit
|
||||
dem kurzlebigen Job-Token (kein Deploy-Key auf dem Server), macht `git reset --hard origin/main`,
|
||||
bricht ab, wenn `config/.env` fehlt, dann `composer install --no-dev`, `migrations migrate`, `cache clear_all`. PHP und Composer werden
|
||||
automatisch erkannt (überschreibbar über `PHP_BIN`/`COMPOSER_BIN`).
|
||||
- Benötigte Variablen/Secrets sind im Kopf der Workflow-Datei dokumentiert. Zugangsdaten nur als
|
||||
Gitea-Secret, nie ins Repo.
|
||||
|
||||
## Container (Docker)
|
||||
|
||||
**Container (Docker) – nur für Testzwecke, nicht für den Produktivbetrieb geeignet** (eingebauter PHP-Server, SQLite; das steht
|
||||
auch in der README und in [deployment.md](deployment.md) und darf dort nicht als „empfohlen“ oder produktionstauglich erscheinen): `Dockerfile` (`php:8.5-cli-alpine`, Multi-Stage mit Composer) startet über
|
||||
`docker/entrypoint.sh` den eingebauten Server (`bin/cake server -H 0.0.0.0 -p 8765`, `PHP_CLI_SERVER_WORKERS=8`,
|
||||
sonst bedient er nur einen Request gleichzeitig). Code in `/app`, SQLite in Volume `/data`
|
||||
(`DATABASE_URL=sqlite:////data/plenario.sqlite`), Konfiguration nur per Umgebungsvariablen (`config/.env.example`).
|
||||
`SECURITY_SALT` ist Pflicht (Entrypoint bricht sonst ab; `composer install --no-scripts`, damit kein Salt eingebrannt wird).
|
||||
Der Start ist idempotent (Migrationen + `cache clear_all`). Der Healthcheck prüft eine statische Datei, weil die Host-Prüfung
|
||||
(`APP_FULL_BASE_URL`) `127.0.0.1` auf echten Seiten mit 400 ablehnt. Betrieb hinter einem TLS-Proxy mit `X-Forwarded-Proto`.
|
||||
Beispiel: `docker-compose.yml`. Image und App-Paket entstehen nur bei Releases (siehe „Releases“).
|
||||
|
||||
## Releases (SemVer)
|
||||
|
||||
**Releases (SemVer):** `.gitea/workflows/release.yml` läuft nur bei Tags `vMAJOR.MINOR.PATCH[-suffix]` (kein Build bei normalen
|
||||
Pushes). Job `test` (PHPUnit + phpcs) gatet `package` und `image`. `package` baut `plenario-<version>.tar.gz` (git archive des Tags,
|
||||
`composer install --no-dev --no-scripts`, **ohne** `app_local.php` (nur `.env`), leere `tmp/`/`logs/`/`data/`, Datei `VERSION`; nur per Whitelist: bin, config, plugins, resources, src, templates, webroot, index.php, .htaccess, composer-Dateien;
|
||||
kein tests/CI/Docker/README) + `SHA256SUMS` und hängt sie an das Gitea-Release (wird angelegt bzw. aktualisiert, Changelog = Commit-Betreffs
|
||||
seit dem letzten Tag, Suffix = Pre-Release). `image` pusht `:<version>`, `:<major>.<minor>`, `:<major>` und `:latest` (die
|
||||
beiden letzten nicht bei Pre-Releases bzw. `v0.`) in die Gitea-Registry (Variablen `DOCKER_REPO`, `IMAGE_NAME`, Secret `PAT`).
|
||||
Wer das Paket ändert (z. B. weitere Dateien ausschließen), pflegt den Schritt „Build package“ in `release.yml`.
|
||||
|
||||
## Produktiv-Konfiguration
|
||||
|
||||
Produktiv auf dem Server in `config/.env`: `DEBUG=false`, `APP_FULL_BASE_URL`, `SECURITY_SALT`, SMTP
|
||||
(`SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_TLS` – einzelne Variablen statt URL; `EMAIL_TRANSPORT_DEFAULT_URL` geht weiter als Altlast).
|
||||
Produktion kennt keine `app_local.php`: Paket und Docker-Image liefern sie nicht mit, `app.php` liest alles aus der Umgebung (Standard `DEBUG=false`). Eine `app_local.php` hätte Vorrang vor `.env` und überschreibt still einzelne Werte (z. B. den Mail-Transport); auf bestehenden Servern aus der Zeit vor diesem Stand löschen.
|
||||
Document-Root zeigt idealerweise auf `webroot/`; liegt die App direkt im Document-Root (z. B. `public_html`),
|
||||
leiten `.htaccess` + `index.php` im Projektroot alles nach `webroot/` weiter.
|
||||
@@ -0,0 +1,12 @@
|
||||
# PDF-Export
|
||||
|
||||
Ergebnisbericht der Umfrage als PDF.
|
||||
|
||||
- **PDF-Export** (`/admin/{token}/export.pdf`, `admin:export`, `ReportService` + `PdfView`, Dompdf): Ergebnisse aller
|
||||
interaktiven Folien (Inhaltsfolien/YouTube fehlen). Standard ist die Fassung **ohne interne Inhalte**: private Folien
|
||||
(`Slide::isPrivate()`) erscheinen nur mit Teilnehmerzahl. `?internal=1` = vollständige Fassung inkl.
|
||||
anonymer Antworten, interner Skalen und Kommentar-Bewertungen (Dateiname `…-intern.pdf`, Hinweis „Vertraulich“ auf jeder
|
||||
Seite); ohne private Folien wird der Parameter ignoriert. Quiz/Reihenfolge folgen auch hier den Auflöse-Regeln
|
||||
(vor `finished` bzw. Schließen keine Zählungen/Lösung). Layout `templates/layout/pdf.php` ist eigenständig: keine
|
||||
externen Ressourcen, keine CSS-Variablen, Schrift DejaVu Sans; Seitenzahlen setzt `PdfView::addPageNumbers()`.
|
||||
Tests prüfen das HTML über `PlenarioTestTrait::exportHtml()` (das PDF selbst ist nicht durchsuchbar).
|
||||
@@ -0,0 +1,79 @@
|
||||
# Präsentation, Steuerung und Einbettung
|
||||
|
||||
Live-Schaltung, Pause, Ausblenden, Zurücksetzen, Duplizieren, Einbettung und anonymes Feedback.
|
||||
|
||||
## Live-Updates
|
||||
|
||||
Kein WebSocket: Presenter (`/admin/{token}/state`) und Teilnehmende (`/p/{code}/state`) pollen per `fetch`
|
||||
(`Plenario.pollIntervalMs`). Die Teilnehmerseite lädt neu, wenn sich `version` im State ändert.
|
||||
|
||||
## Referentenansicht
|
||||
|
||||
- Die Referentenansicht lädt **nie** den YouTube-Player (`renderMedia()` in `plenario.js` zeigt dort nur einen Hinweis),
|
||||
damit das Video nicht doppelt zu hören ist.
|
||||
|
||||
- `/admin/{token}/speaker` (`admin:speaker`, Button ⧉ im Präsentationsmodus und Eintrag „Referentenansicht“ im Aufklappmenü (▾) von „Präsentieren“ in der Verwaltung, jeweils neues Fenster) ist für den eigenen Bildschirm des
|
||||
Präsentierenden: gleiche Seite und gleiches JS wie `present` (`initPresenter`, Steuerung per Tasten/Buttons), plus
|
||||
`data-next`-Kasten „Als Nächstes“ links neben der aktuellen Folie (`stage--speaker`). Anders als `present` startet sie die Präsentation nicht.
|
||||
- Datenquelle ist `next` im Presenter-State (`PollStateService::nextPreview()`): Folie hinter der Live-Folie (ausgeblendete werden übersprungen),
|
||||
bei Pause die pausierte, vor dem Start die erste, `null` nach der letzten. Nur Beschriftungen – nie `is_correct`, bei Reihenfolge keine Optionen
|
||||
(die gespeicherte Reihenfolge ist die Lösung). Tests: `SpeakerViewTest.php`.
|
||||
|
||||
## Pause
|
||||
|
||||
- **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()` /
|
||||
`forgetSlide()` setzen, nie `current_slide_id` direkt. Presenter: P bzw. der Pause-Button schaltet um (Aktionen `stop`/`resume`, beide idempotent, kein Server-Toggle),
|
||||
←/→ setzt ebenfalls 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).
|
||||
|
||||
## Ausgeblendete Folien
|
||||
|
||||
- **Ausgeblendete Folien** (`is_hidden`, `slides:visibility` mit `hidden=1|0`, explizit statt Toggle → idempotent):
|
||||
bleiben in der Verwaltung (gestrichelt, Badge „ausgeblendet“), gehören aber nicht zur Präsentation. Präsentation =
|
||||
`SlidesTable::listForPoll($pollId, true)`: Start, →/←, `goto` (400 für ausgeblendete), Zähler im Presenter-State
|
||||
(`count` ohne, `hiddenCount` = ausgeblendete), PDF-Export (Nummerierung wie in der Präsentation). Einbettung einer
|
||||
ausgeblendeten Folie geht nicht live (`isHidden` im Embed-State). Eine ausgeblendete Folie darf nie live/pausiert sein:
|
||||
Ausblenden der Live- oder pausierten Folie pausiert wie Löschen (`forgetSlide()` + `SlidesTable::replacementFor()` =
|
||||
nächste sichtbare Folie, sonst die vorige). `is_hidden` ist nicht mass-assignable. Tests: `HiddenSlideTest.php`.
|
||||
|
||||
## Zurücksetzen
|
||||
|
||||
- **Zurücksetzen** (`ResetService`) löscht **nur Antworten**: Folie (`slides:reset`) bzw. alle Folien der Umfrage
|
||||
(`admin:reset`, Dashboard → „Sicherheit“). Jede Folie geht danach in den Zustand einer neuen Folie (`Slide::startFresh()`:
|
||||
Quiz `ready`, Q&A `collect`, alle anderen offen – bei Reihenfolge bleibt die Lösung so verdeckt); Einstellungen bleiben. Das Zurücksetzen der
|
||||
Umfrage setzt außerdem die Präsentation auf „nicht gestartet“ (`Poll::notStarted()`: weder live noch pausiert). Vorab eingetragene Q&A-Fragen bleiben standardmäßig erhalten (nur ihre Upvotes gehen weg):
|
||||
Folien-Reset behält sie immer, der Umfrage-Reset hat die Checkbox `keep_prepared` (nur sichtbar, wenn es welche gibt).
|
||||
Die Reset-Buttons (Dashboard, ↺ je Folie) erscheinen nicht nur bei Antworten, sondern auch, wenn eine Folie vom Ausgangszustand abweicht
|
||||
(`Slide::isFresh()`: Quiz gestartet, Folie geschlossen, Q&A-Phase) oder die Präsentation läuft/pausiert (`Poll::isStarted()`).
|
||||
Idempotent, in einer Transaktion. Tests: `PollResetTest.php`.
|
||||
|
||||
## Duplizieren
|
||||
|
||||
- **Duplizieren** (`slides:duplicate`, POST): kopiert Fragetext (+ „(Kopie)“), Beschreibung, Einstellungen und Optionen
|
||||
inkl. `is_correct`, **nie Antworten**. Die Kopie landet direkt hinter dem Original und startet wie eine neue Folie
|
||||
(`Slide::startFresh()`: Quiz `ready`, Q&A `collect`, sonst offen) – auch `add()` nutzt `startFresh()`.
|
||||
Tests: `DuplicateSlideTest.php`.
|
||||
|
||||
## Einbettung
|
||||
|
||||
- **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
|
||||
(IntersectionObserver + `visibilitychange`), sendet Heartbeats und beim Verschwinden `pause` (sendBeacon).
|
||||
`pause` wirkt nur, wenn die eigene Folie noch live ist; `heartbeat` holt keine Folie zurück, die im Presenter
|
||||
gewechselt wurde. Bleiben Heartbeats aus (`Plenario.embed.timeoutSeconds`), pausiert `PollsTable::pauseIfEmbedStale()`
|
||||
beim nächsten State-Abruf. Embed-Routen haben **keinen CSRF-Check** (Third-Party-Iframe ohne Cookies, der Schlüssel
|
||||
ist die Berechtigung, siehe `Application::middleware()`) und erlauben Framing per CSP `frame-ancestors`
|
||||
(`EMBED_FRAME_ANCESTORS`); alle anderen Seiten bleiben `X-Frame-Options: SAMEORIGIN`. Beides entscheidet
|
||||
`SecurityHeadersMiddleware::isEmbed()` anhand des Pfads (auch für Fehlerseiten).
|
||||
|
||||
## Anonymes / internes Feedback
|
||||
|
||||
- **Anonymes / internes Feedback** (offene Frage bzw. Skala mit Setting `private`, `Slide::isPrivate()`): steuert den
|
||||
Schalter „Ergebnisse verbergen“ (H) im Presenter/Embed. Das JSON enthält die vollständigen Ergebnisse plus
|
||||
`results.private = true`; `initPresenter` verbirgt sie beim Wechsel auf eine solche Folie und zeigt stattdessen nur die
|
||||
Anzahl (`Results.privateSummary`). Einblenden gilt nur für diese Folie, die globale Wahl für normale Folien (`hideAll`)
|
||||
bleibt unberührt. Teilnehmende bekommen (wie bei allen Abstimmungsfolien) keine `results`. Die Fassung des PDF-Exports ohne interne Inhalte entfernt sie per
|
||||
`ResultsService::withoutContents()`. Volle Ansicht in der Verwaltung (`slides:answers` → „Auswertung“).
|
||||
@@ -0,0 +1,128 @@
|
||||
# Folientypen
|
||||
|
||||
Details zu den einzelnen Folientypen. Übersicht und zentrale Regeln stehen in [AGENTS.md](../AGENTS.md).
|
||||
|
||||
## Wortwolke
|
||||
|
||||
- Ausnahme Wortwolke: Begriffe werden einzeln abgegeben (AJAX, `vote` liefert dann JSON `{ok, message, state}`),
|
||||
jeder Begriff einmal pro Person, beliebig viele Begriffe. Einen vorhandenen Begriff erneut nennen
|
||||
bzw. in der Wolke anklicken = Upvote (gleiche Zeile in `responses`). Mit `allow_upvotes` sehen Teilnehmende
|
||||
die Wolke live; Vorschläge inkl. Kölner Phonetik in `plenario.js` (`Words`).
|
||||
Downvotes (`vote=down`, Setting `allow_downvotes`, nur zusammen mit Upvotes): Zeile mit `numeric_value = VoteService::DOWNVOTE` (-1),
|
||||
nur auf fremde, vorhandene Begriffe, ein Rating pro Begriff und Person.
|
||||
Wortgröße richtet sich nur nach den Upvotes (`count`), Downvotes stehen separat in `down`.
|
||||
`vote=remove` nimmt den eigenen Eintrag zu einem Begriff zurück (genannt/Upvote oder Downvote, `VoteService::removeWord()`,
|
||||
löscht nur Zeilen mit dem eigenen `participant_hash`); Tippfehler = entfernen und neu eingeben, kein Bearbeiten (die Zeile
|
||||
ist zugleich die Stimme). Teilnehmende bekommen dafür `words.own` (eigene Begriffe wie eingegeben) und sehen sie als Chips mit „ד.
|
||||
|
||||
## Quiz
|
||||
|
||||
- Quiz: Phasen `ready` → `running` → `finished` (`Slide::quizPhase()`). Neue Quiz-Folien starten geschlossen;
|
||||
erst der Presenter startet (`control` open/toggle → `Slide::setVotingOpen()` setzt Start + Deadline aus
|
||||
`time_limit`, erneutes Öffnen eines laufenden Quiz startet den Timer nicht neu). „Offen“ heißt immer
|
||||
`Slide::isVotingOpen()` (inkl. Deadline), nicht nur `is_voting_open`. Abgelaufene Quizze schließt
|
||||
`SlidesTable::closeIfExpired()` beim State-Abruf. **Zählungen und `is_correct` dürfen vor `finished` nie im
|
||||
JSON/HTML landen** (weder Presenter noch Teilnehmende); danach sehen Teilnehmende die Lösung und ob sie
|
||||
richtig lagen (ohne Verteilung). Zurücksetzen setzt das Quiz wieder auf `ready`.
|
||||
**Klicker/Presenter-Stick** (sendet nur →/← bzw. Bild↑/↓): `AdminController::control` behandelt `next` auf einem Quiz als
|
||||
Schritt – `ready` → starten, `running` → beenden (Lösung), erst `finished` → nächste Folie. `prev` geht immer zur vorigen Folie
|
||||
und startet nie ein Quiz. Tests: `QuizClickerTest.php`.
|
||||
|
||||
## Fragen & Antworten (Q&A)
|
||||
|
||||
- Q&A-Folie (`qa`, „Fragen & Antworten“): Phasen `collect` → `vote` → `discuss` (`Slide::qaStage()`, `QaService`),
|
||||
der Presenter schaltet manuell weiter (V bzw. Stepper, auch zurück). `collect`: Fragen einreichen (max.
|
||||
`VoteService::MAX_QA_QUESTIONS` pro Person, gleiche Frage nur einmal pro Folie), Teilnehmende sehen alle bisherigen Fragen
|
||||
(gegen Dubletten, eigene markiert), aber noch keine Upvotes.
|
||||
`vote`: Upvotes auf fremde Fragen, Budget pro Person = Anteil der Fragen (Setting `upvote_share` in Prozent, `Slide::QA_UPVOTE_SHARES`, aufgerundet, mindestens 1:
|
||||
`Slide::qaBudget(Anzahl Fragen)`; im State/JSON `maxUpvotes`), wächst also mit der Fragenzahl, frei verteilbar (auch mehrere auf eine Frage,
|
||||
je Upvote eine Zeile), `vote=remove` nimmt eine Stimme der Frage zurück; im State `qa.upvoted` = {Frage-id: eigene Stimmen}.
|
||||
Setting `max_upvotes_per_question` begrenzt die eigenen Stimmen je Frage (0 = nur durch das Budget begrenzt,
|
||||
effektiv `Slide::qaUpvotesPerQuestion($budget)`, State `maxPerQuestion`). `upvote_share = 0` = ohne Upvotes: es gibt keine Phase `vote`
|
||||
(`Slide::qaStages()` = collect → discuss, im Presenter-JSON `results.stages`), besprochen wird in Eingangsreihenfolge;
|
||||
wird es während `vote` auf 0 gesetzt, springt `SlidesController::saveSlide()` nach `discuss`.
|
||||
Setting `allow_self_upvote` (Standard aus, für Themen-Priorisierung) erlaubt Stimmen auf eigene Fragen aus demselben Budget
|
||||
(State `qa.allowSelfUpvote`); bewusst aus, weil anonym sonst Selbstvermarktung die Rangfolge bestimmt;
|
||||
Teilnehmende sehen alle Fragen in Eingangsreihenfolge **ohne** Zählung; die Bühne (Presenter/Embed) zeigt in `vote` keine Fragen,
|
||||
sondern nur den Hinweis „Schau auf dein Gerät und stimme ab“ mit Fragenzahl, Budget und vergebener Gesamtsumme (`Results.qa`); auch sonst gibt es dort
|
||||
keine Zählungen je Frage und keine Rangfolge (`ResultsService::qa()`, nur die Summe `upvotes`), damit niemand beeinflusst wird. `discuss`: Abstimmung zu, Fragen nach Upvotes
|
||||
sortiert (Gleichstand: älteste zuerst), `focus_response_id` = aktuelle Frage. In `discuss` blättern next/prev
|
||||
(→/←, Klicker) zuerst durch die Fragen, erst danach durch die Folien. Fokuswechsel per `updateAll` ohne `modified`,
|
||||
damit Teilnehmerseiten nicht neu laden. Teilnehmende bekommen nie `results`, sondern `qa` aus `PollStateService::qaState()`.
|
||||
Zurücksetzen startet wieder bei `collect`.
|
||||
**Vorab eingereichte Fragen** (z. B. per Mail): Textarea `prepared_text` im Folienformular (eine Frage pro Zeile, höchstens
|
||||
`QaService::MAX_PREPARED`), nur in `collect` sichtbar/änderbar. `QaService::syncPrepared()` gleicht sie idempotent ab (gleiche Texte
|
||||
behalten ihre id, entfernte verschwinden samt Upvotes, von Teilnehmenden schon gestellte werden nicht doppelt angelegt). Gespeichert
|
||||
als normale Fragen mit `participant_hash = VoteService::PREPARED_HASH` (kein gültiger HMAC → niemand kann sie bearbeiten/löschen,
|
||||
jeder darf sie unterstützen); sie zählen nicht als Teilnehmende. Zurücksetzen behält sie (außer die Checkbox beim Umfrage-Reset ist abgewählt), Duplizieren kopiert sie nicht.
|
||||
Tests: `QaPreparedTest.php`.
|
||||
Eigene Fragen bearbeiten/löschen (`vote=edit|delete` + `question_id`, `VoteService::editQuestion()`) nur in `collect`:
|
||||
danach könnten Upvotes bzw. die Besprechung an einem anderen Text hängen. Bearbeiten prüft Dubletten ohne die eigene Frage,
|
||||
Löschen entfernt auch übrig gebliebene Upvotes (Presenter von `vote` zurück nach `collect`). Im JS hält `qaEditing` das
|
||||
Neu-Rendern beim Polling an, solange eine Frage bearbeitet wird.
|
||||
|
||||
## YouTube
|
||||
|
||||
- YouTube-Folie (`youtube`): nicht interaktiv (wie `content`). Settings `url` (wie eingegeben), `video_id`, `start` (Sekunden),
|
||||
`autoplay`. Startzeit-Feld leer = Timecode aus dem Link (`t`/`start`), sonst gewinnt das Feld (`1:30`, `2` = Minuten).
|
||||
Beim Speichern prüft `SlidesController::prepareYouTube()` per oEmbed: nicht gefunden/nicht einbettbar = Fehler,
|
||||
YouTube nicht erreichbar = speichern mit Warnung; leerer Titel wird mit dem Videotitel gefüllt. Eingebettet wird nur
|
||||
im Presenter (`youtube-nocookie.com`), Teilnehmende sehen Link + Teilen-Button (Web Share API, sonst Kopieren).
|
||||
Iframes brauchen `referrerpolicy="strict-origin"`, weil Admin-Seiten `no-referrer` senden und YouTube ohne Referrer
|
||||
nicht abspielt (nur Origin, nie der Pfad mit Token). Tests mocken YouTube über `HttpClientTrait` (`mockClientGet`).
|
||||
|
||||
## Reihenfolge
|
||||
|
||||
- Reihenfolge-Folie (`order`): Admin legt die Einträge in der richtigen Reihenfolge an (Formular `order_options[]`, Zeilen
|
||||
per Drag & Drop/Pfeiltasten sortierbar, ids bleiben beim Umsortieren erhalten). Teilnehmende bekommen sie per
|
||||
`Slide::shuffledOptions(participantHash)` gemischt (stabil, nie schon richtig), sortieren und senden `order[]` (alle ids genau einmal),
|
||||
einmal pro Person. Startet offen wie normale Folien; **aufgelöst wird beim Schließen der Abstimmung** (`Slide::isOrderRevealed()`).
|
||||
Vorher landen weder richtige Reihenfolge noch Zählungen im JSON (Presenter sieht die Einträge gemischt mit Seed `slide:{id}`);
|
||||
danach sieht der Presenter die Lösung inkl. „X von N komplett richtig“ und je Eintrag, wie oft er an der richtigen Stelle lag;
|
||||
Teilnehmende nur die Lösung mit eigenen Platzierungen und `order.isCorrect`. Tests: `OrderTest.php`, `OrderSlideTest.php`.
|
||||
|
||||
## Skala, Sterne und Kommentare
|
||||
|
||||
- **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 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 (Anzeigedauer nach Textlänge, kein Setting pro Folie:
|
||||
`Comments.delay()` = 2,5 s + 15 Zeichen/s, 5–30 s, geteilt durch das Tempo der Umfrage `polls.comment_speed` (Prozent aus
|
||||
`Poll::COMMENT_SPEEDS`, im State `poll.commentSpeed` als Faktor, Dashboard → „Einstellungen“); Vor/Zurück/Fortsetzen geben dem Kommentar wieder die volle Zeit; „Kommentar X von N“,
|
||||
vor/zurück/Pause, Laufbalken bis zum Wechsel (`Comments.progress()`, setzt nach dem Neu-Rendern per negativem
|
||||
`animation-delay` fort, bei Pause unsichtbar), Zustand übersteht das Neu-Rendern beim Polling; die Box ist so hoch wie der längste Kommentar – alle liegen unsichtbar in derselben Grid-Zelle –, damit die zentrierte Bühne beim Wechsel nicht springt; höchstens `--comment-max` ≈ 5 Zeilen, längere Kommentare setzt `Comments.fit()` kleiner statt sie abzuschneiden; die Bewertung steht über dem Text, damit sie an fester Stelle bleibt; der Fortschritt läuft als Rahmen der Box: `Comments.progressBorder()`, SVG-Rechteck mit `pathLength` 100, zwei Linien ab gegenüberliegenden Ecken). Bei internem Feedback erscheinen sie erst,
|
||||
wenn der Presenter die Ergebnisse einblendet.
|
||||
- **Kommentare bei Multiple Choice** (Setting `comments`, gleiches `Slide::hasComments()` wie bei Skalen): optionales Feld `comment`,
|
||||
gespeichert als `text_value` **nur in der ersten Zeile** der Person (bei Mehrfachauswahl gibt es mehrere Zeilen; Zählungen
|
||||
gruppieren nach `slide_option_id` und ignorieren `text_value`). Bearbeiten/Anlegen/Leeren wie bei Skalen über `participate:edit`
|
||||
(`editText()` und `ownText()` lesen die Zeile mit der kleinsten id). Presenter/Embed bekommen `results.comments` (`value` immer
|
||||
`null`, keine Zuordnung zur Option), `Results.choice` zeigt sie mit `Comments` unter den Balken; Teilnehmende nie.
|
||||
Volle Liste: `slides:answers` („Kommentare“), PDF-Export unter der Tabelle. Tests: `ChoiceCommentsTest.php`.
|
||||
- **Sterne-Bewertung** (Skala mit Setting `style = stars`, `Slide::isStarRating()`, Standard `numbers`): immer 1 bis `scale_max`
|
||||
Sterne (`SlidesTable::sanitizeSettings()` erzwingt `scale_min = 1`), gespeichert wie jede Skala als `numeric_value`.
|
||||
Teilnehmende wählen Sterne (Radios in DOM-Reihenfolge 1..n, Füllung per CSS `:has()`), der State enthält `results.stars`;
|
||||
`Results.stars` in `plenario.js` zeigt den Durchschnitt als teilweise gefüllte Sterne und die Verteilung als Donut 5 → 1.
|
||||
Text-Ausgabe (Auswertung, PDF) über `Slide::ratingText()` (`★★★★☆`), barrierearm über `element/rating`.
|
||||
- **Skala-Darstellung auf der Bühne:** Durchschnitt (große Zahl + Skala bzw. Sterne) und Verteilung (Donut per CSS
|
||||
`conic-gradient`, je Wert eine eigene Farbe aus `--c0…--c5` in fester Reihenfolge, bei mehr Werten gemischt; Legende mit „% (Anzahl)“ und den Beschriftungen der Enden) nebeneinander
|
||||
(`Results.scaleLayout()` / `Results.donut()`). Setting `scale_view` (`Slide::SCALE_VIEWS`: `both` | `average` | `chart`,
|
||||
Dropdown im Formular) zeigt nur einen Teil, dann zentriert; im JSON `results.view`, die Daten bleiben vollständig.
|
||||
Gilt nur für Presenter/Embed, Auswertung und PDF zeigen immer beides.
|
||||
- **Antwort nachträglich bearbeiten** (gegen Tippfehler, `VoteService::hasEditableText()`): Antwort einer offenen Frage
|
||||
(darf nicht leer werden) bzw. Kommentar einer Skala (ändern, ergänzen, leeren; die Bewertung bleibt unveränderlich),
|
||||
nur solange die Abstimmung offen ist. `participate:edit` → `VoteService::editText()`, gleiche Vorbedingungen wie
|
||||
`submit()`, in der Folien-Sperre, legt nie eine neue Antwort an.
|
||||
|
||||
## Neuen Folientyp hinzufügen (Checkliste)
|
||||
|
||||
0. Bilder: `Slide::supportsImage()` entscheidet, ob der Typ ein Bild tragen kann (Standard ja).
|
||||
|
||||
1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php`
|
||||
2. Settings-Sanitizing in `SlidesTable::sanitizeSettings()`
|
||||
3. Validierung/Speicherung in `VoteService::submit()` (eigene `…Rows()`-Methode)
|
||||
4. Aggregation in `ResultsService::forSlide()` + Docblock der JSON-Struktur
|
||||
5. Formularfelder in `templates/Slides/form.php`, Eingabe in `templates/Participate/view.php`
|
||||
6. Renderer in `webroot/js/plenario.js` (`Results.<type>`), Styles in `plenario.css`, Badge-Farbe;
|
||||
Ausgabe im PDF-Export (`templates/Admin/export.php`)
|
||||
7. Tests in `tests/TestCase/Service/VoteServiceTest.php` (Quiz: `QuizTest.php`, Q&A: `QaTest.php`)
|
||||
8. Nach neuen Spalten lokal `bin/cake cache clear_all`, sonst nutzt das ORM das alte Schema aus dem Cache
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
// Generates webroot/favicon.svg, favicon.ico, apple-touch-icon.png and resources/mail/logo.png (needs ext-gd). Run after a logo change:
|
||||
// php resources/favicon/generate.php webroot
|
||||
// Mirrors .brand__mark in webroot/css/plenario.css:
|
||||
// rounded square (radius 6/22), conic gradient 40/25/20/15 % from 12 o'clock, clockwise.
|
||||
declare(strict_types=1);
|
||||
|
||||
$out = rtrim($argv[1] ?? 'webroot', '/\\');
|
||||
$colors = ['#4b3fe0', '#e0457b', '#12a08a', '#f29a1f'];
|
||||
$stops = [0.40, 0.65, 0.85, 1.00];
|
||||
$radiusRatio = 6 / 22;
|
||||
|
||||
// ---- SVG ---------------------------------------------------------------------------------
|
||||
$size = 32;
|
||||
$c = $size / 2;
|
||||
$R = 24; // larger than the corner distance, the clip path trims it
|
||||
$point = function (float $fraction) use ($c, $R): array {
|
||||
$a = deg2rad($fraction * 360);
|
||||
|
||||
return [round($c + $R * sin($a), 3), round($c - $R * cos($a), 3)];
|
||||
};
|
||||
$paths = '';
|
||||
$prev = 0.0;
|
||||
foreach ($stops as $i => $stop) {
|
||||
[$x1, $y1] = $point($prev);
|
||||
[$x2, $y2] = $point($stop);
|
||||
$large = ($stop - $prev) > 0.5 ? 1 : 0;
|
||||
$paths .= sprintf(
|
||||
" <path fill=\"%s\" d=\"M%d %d L%s %s A%d %d 0 %d 1 %s %s Z\"/>\n",
|
||||
$colors[$i],
|
||||
$c,
|
||||
$c,
|
||||
$x1,
|
||||
$y1,
|
||||
$R,
|
||||
$R,
|
||||
$large,
|
||||
$x2,
|
||||
$y2,
|
||||
);
|
||||
$prev = $stop;
|
||||
}
|
||||
$rx = round($size * $radiusRatio, 2);
|
||||
$svg = <<<SVG
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {$size} {$size}" width="{$size}" height="{$size}">
|
||||
<title>PlenarIO</title>
|
||||
<clipPath id="r"><rect width="{$size}" height="{$size}" rx="{$rx}"/></clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
{$paths} </g>
|
||||
</svg>
|
||||
|
||||
SVG;
|
||||
file_put_contents($out . '/favicon.svg', $svg);
|
||||
|
||||
// ---- PNG / ICO (GD, 4x4 supersampling) ---------------------------------------------------
|
||||
$rgb = fn(string $hex): array => [hexdec(substr($hex, 1, 2)), hexdec(substr($hex, 3, 2)), hexdec(substr($hex, 5, 2))];
|
||||
$palette = array_map($rgb, $colors);
|
||||
|
||||
$render = function (int $n, float $padding = 0.0) use ($stops, $palette, $radiusRatio): string {
|
||||
$img = imagecreatetruecolor($n, $n);
|
||||
imagealphablending($img, false);
|
||||
imagesavealpha($img, true);
|
||||
$ss = 4;
|
||||
$inner = $n * (1 - 2 * $padding);
|
||||
$r = $inner * $radiusRatio;
|
||||
$offset = $n * $padding;
|
||||
for ($y = 0; $y < $n; $y++) {
|
||||
for ($x = 0; $x < $n; $x++) {
|
||||
$sum = [0.0, 0.0, 0.0];
|
||||
$cover = 0;
|
||||
for ($sy = 0; $sy < $ss; $sy++) {
|
||||
for ($sx = 0; $sx < $ss; $sx++) {
|
||||
$px = $x + ($sx + 0.5) / $ss - $offset;
|
||||
$py = $y + ($sy + 0.5) / $ss - $offset;
|
||||
if ($px < 0 || $py < 0 || $px > $inner || $py > $inner) {
|
||||
continue;
|
||||
}
|
||||
// rounded corners
|
||||
$cx = min(max($px, $r), $inner - $r);
|
||||
$cy = min(max($py, $r), $inner - $r);
|
||||
if (($px - $cx) ** 2 + ($py - $cy) ** 2 > $r ** 2) {
|
||||
continue;
|
||||
}
|
||||
$angle = atan2($px - $inner / 2, -($py - $inner / 2)); // 0 = top, clockwise
|
||||
$f = fmod($angle / (2 * M_PI) + 1, 1);
|
||||
$k = 0;
|
||||
while ($k < 3 && $f >= $stops[$k]) {
|
||||
$k++;
|
||||
}
|
||||
foreach ($palette[$k] as $j => $v) {
|
||||
$sum[$j] += $v;
|
||||
}
|
||||
$cover++;
|
||||
}
|
||||
}
|
||||
$total = $ss * $ss;
|
||||
if ($cover === 0) {
|
||||
$col = imagecolorallocatealpha($img, 0, 0, 0, 127);
|
||||
} else {
|
||||
$col = imagecolorallocatealpha(
|
||||
$img,
|
||||
(int)round($sum[0] / $cover),
|
||||
(int)round($sum[1] / $cover),
|
||||
(int)round($sum[2] / $cover),
|
||||
(int)round(127 * (1 - $cover / $total)),
|
||||
);
|
||||
}
|
||||
imagesetpixel($img, $x, $y, $col);
|
||||
}
|
||||
}
|
||||
ob_start();
|
||||
imagepng($img, null, 9);
|
||||
$png = (string)ob_get_clean();
|
||||
|
||||
return $png;
|
||||
};
|
||||
|
||||
// favicon.ico with 16, 32 and 48 px (PNG compressed entries)
|
||||
$sizes = [16, 32, 48];
|
||||
$images = array_map(fn(int $n): string => $render($n), $sizes);
|
||||
$ico = pack('vvv', 0, 1, count($sizes));
|
||||
$offset = 6 + 16 * count($sizes);
|
||||
foreach ($sizes as $i => $n) {
|
||||
$ico .= pack('CCCCvvVV', $n, $n, 0, 0, 1, 32, strlen($images[$i]), $offset);
|
||||
$offset += strlen($images[$i]);
|
||||
}
|
||||
file_put_contents($out . '/favicon.ico', $ico . implode('', $images));
|
||||
|
||||
// Logo for e-mails (resources/mail/logo.png, attached inline by PollMailer): mail clients show no SVG.
|
||||
// 96 px, displayed at 32 px for sharp edges on high-DPI screens.
|
||||
$mailDir = dirname(__DIR__) . '/mail';
|
||||
if (!is_dir($mailDir)) {
|
||||
mkdir($mailDir, 0775, true);
|
||||
}
|
||||
file_put_contents($mailDir . '/logo.png', $render(96));
|
||||
|
||||
// iOS ignores transparency (fills black) and rounds the corners itself: opaque full-bleed square.
|
||||
$apple = imagecreatetruecolor(180, 180);
|
||||
$stopsPx = $stops;
|
||||
for ($y = 0; $y < 180; $y++) {
|
||||
for ($x = 0; $x < 180; $x++) {
|
||||
$angle = atan2($x + 0.5 - 90, -($y + 0.5 - 90));
|
||||
$f = fmod($angle / (2 * M_PI) + 1, 1);
|
||||
$k = 0;
|
||||
while ($k < 3 && $f >= $stopsPx[$k]) {
|
||||
$k++;
|
||||
}
|
||||
imagesetpixel($apple, $x, $y, imagecolorallocate($apple, ...$palette[$k]));
|
||||
}
|
||||
}
|
||||
imagepng($apple, $out . '/apple-touch-icon.png', 9);
|
||||
echo "ok\n";
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.6 KiB |
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Service\ImageService;
|
||||
use Cake\Command\Command;
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
|
||||
/**
|
||||
* Removes image files that no slide refers to any more (aborted uploads, crashes while deleting).
|
||||
* Idempotent, safe to run at any time, e.g. from cron.
|
||||
*
|
||||
* Usage: bin/cake images_cleanup [--dry-run]
|
||||
*/
|
||||
class ImagesCleanupCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public static function defaultName(): string
|
||||
{
|
||||
return 'images_cleanup';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Console\ConsoleOptionParser $parser Parser
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
|
||||
{
|
||||
return $parser
|
||||
->setDescription(__('Löscht Bilddateien, die zu keiner Folie mehr gehören.'))
|
||||
->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
|
||||
{
|
||||
/** @var \App\Model\Table\SlidesTable $slides */
|
||||
$slides = $this->fetchTable('Slides');
|
||||
$referenced = [];
|
||||
$rows = $slides->find()
|
||||
->select(['poll_id', 'image'])
|
||||
->where(['image IS NOT' => null])
|
||||
->disableHydration()
|
||||
->all();
|
||||
foreach ($rows as $row) {
|
||||
$referenced[(int)$row['poll_id']][] = (string)$row['image'];
|
||||
}
|
||||
|
||||
$dryRun = (bool)$args->getOption('dry-run');
|
||||
$removed = (new ImageService())->cleanup($referenced, $dryRun);
|
||||
foreach ($removed as $path) {
|
||||
$io->out(($dryRun ? __('Verwaist: {0}', $path) : __('Gelöscht: {0}', $path)));
|
||||
}
|
||||
$io->success($dryRun
|
||||
? __('{0} verwaiste Datei(en) gefunden (nichts gelöscht).', count($removed))
|
||||
: __('{0} verwaiste Datei(en) entfernt.', count($removed)));
|
||||
|
||||
return static::CODE_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
use Cake\Core\Configure;
|
||||
|
||||
/**
|
||||
* Sends the reminders (`polls remind`), then deletes expired polls (POLL_RETENTION_DAYS after creation,
|
||||
* see Poll::expiresAt()). Idempotent, made for cron:
|
||||
*
|
||||
* 17 3 * * * cd /path/to/plenario && php bin/cake.php polls cleanup --quiet
|
||||
*
|
||||
* Usage: bin/cake polls cleanup [--dry-run]
|
||||
*/
|
||||
class PollsCleanupCommand extends PollsCommand
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public static function defaultName(): string
|
||||
{
|
||||
return 'polls cleanup';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Console\ConsoleOptionParser $parser Parser
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
|
||||
{
|
||||
return $parser
|
||||
->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Table\PollsTable;
|
||||
use Cake\Command\Command;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOutput;
|
||||
use Cake\I18n\DateTime;
|
||||
use Cake\Routing\Router;
|
||||
|
||||
/**
|
||||
* Shared helpers of the `polls …` admin commands (list, show, delete, cleanup).
|
||||
*/
|
||||
abstract class PollsCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @return \App\Model\Table\PollsTable
|
||||
*/
|
||||
protected function polls(): PollsTable
|
||||
{
|
||||
/** @var \App\Model\Table\PollsTable $polls */
|
||||
$polls = $this->fetchTable('Polls');
|
||||
|
||||
return $polls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Machine-readable form of a poll (for `--json`). Never contains the admin token.
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @return array<string, mixed> Dates as ISO 8601 (server time zone), null where empty
|
||||
*/
|
||||
protected function pollData(Poll $poll): array
|
||||
{
|
||||
$date = fn(?DateTime $d): ?string => $d?->format(DATE_ATOM);
|
||||
|
||||
return [
|
||||
'id' => $poll->id,
|
||||
'title' => $poll->title,
|
||||
'email' => $poll->email,
|
||||
'joinCode' => $poll->join_code,
|
||||
'joinUrl' => $this->joinLink($poll),
|
||||
'created' => $date($poll->created),
|
||||
'lastAdminAccess' => $date($poll->last_admin_access),
|
||||
'expiresAt' => $date($poll->expiresAt()),
|
||||
'expired' => $poll->isExpired(),
|
||||
'reminderSentAt' => $date($poll->expiry_reminded_at),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints data as JSON only: nothing else on stdout, no markup interpretation (titles may contain "<").
|
||||
*
|
||||
* @param \Cake\Console\ConsoleIo $io Console
|
||||
* @param mixed $data JSON serialisable data
|
||||
* @return void
|
||||
*/
|
||||
protected function printJson(ConsoleIo $io, mixed $data): void
|
||||
{
|
||||
$io->setOutputAs(ConsoleOutput::RAW);
|
||||
$io->out((string)json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
|
||||
/**
|
||||
* Deletes polls for good (slides, answers and images included). Unknown polls are an error (exit code 1).
|
||||
*
|
||||
* Usage: bin/cake polls delete <id|code> [--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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
|
||||
/**
|
||||
* Lists polls with owner, activity and expiry date. Never prints admin links.
|
||||
*
|
||||
* Usage: bin/cake polls list [--expired] [--email=<part>] [--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('json', [
|
||||
'help' => __('Ausgabe als JSON statt als Tabelle (für Skripte).'),
|
||||
'boolean' => true,
|
||||
])
|
||||
->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 ($args->getOption('json')) {
|
||||
$this->printJson($io, array_map($this->pollData(...), $polls));
|
||||
|
||||
return static::CODE_SUCCESS;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Mailer\PollMailer;
|
||||
use App\Model\Entity\Poll;
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
use Cake\I18n\DateTime;
|
||||
use Cake\Mailer\Transport\SmtpTransport;
|
||||
use Cake\Mailer\TransportFactory;
|
||||
use ReflectionClass;
|
||||
use function Cake\Core\env;
|
||||
|
||||
/**
|
||||
* Mails the owners of polls that expire soon (POLL_REMINDER_DAYS before the end), once per poll.
|
||||
* Idempotent: a poll is marked after a successful send; a failed send is retried at the next run.
|
||||
* `polls cleanup` runs this first, a separate cron entry is not needed.
|
||||
*
|
||||
* With an id or code the reminder goes to that one poll right now (for testing the mail): regardless of the
|
||||
* reminder window, of an earlier reminder and of POLL_REMINDER_DAYS. A forced reminder does not set the
|
||||
* "reminded" marker, so the regular reminder still goes out when it is due.
|
||||
*
|
||||
* Usage: bin/cake polls remind [<id|code>] [--dry-run]
|
||||
*/
|
||||
class PollsRemindCommand extends PollsCommand
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public static function defaultName(): string
|
||||
{
|
||||
return 'polls remind';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Console\ConsoleOptionParser $parser Parser
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
|
||||
{
|
||||
return $parser
|
||||
->setDescription(__('Erinnert Besitzer per E-Mail, bevor ihre Umfrage automatisch gelöscht wird.'))
|
||||
->addArgument('poll', [
|
||||
'help' => __('Optional: ID oder Beitrittscode. Verschickt die Erinnerung sofort und erzwungen an diese Umfrage (zum Testen), ohne sie als erinnert zu markieren.'),
|
||||
'required' => false,
|
||||
])
|
||||
->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
|
||||
{
|
||||
$dryRun = (bool)$args->getOption('dry-run');
|
||||
$reference = $args->getArgument('poll');
|
||||
$forced = $reference !== null;
|
||||
|
||||
if ($forced) {
|
||||
$poll = $this->findPoll((string)$reference);
|
||||
if ($poll === null) {
|
||||
$io->err(__('Umfrage „{0}“ nicht gefunden.', $reference));
|
||||
|
||||
return static::CODE_ERROR;
|
||||
}
|
||||
if ($poll->expiresAt() === null) {
|
||||
$io->err(__('Umfragen laufen nie ab (POLL_RETENTION_DAYS=0), die Mail braucht ein Ablaufdatum.'));
|
||||
|
||||
return static::CODE_ERROR;
|
||||
}
|
||||
$due = [$poll];
|
||||
} elseif (Poll::reminderLeadDays() === 0) {
|
||||
$io->out(__('Erinnerungen sind aus (POLL_REMINDER_DAYS=0 oder Umfragen laufen nie ab).'));
|
||||
|
||||
return static::CODE_SUCCESS;
|
||||
} else {
|
||||
/** @var list<\App\Model\Entity\Poll> $due */
|
||||
$due = $this->polls()->find('reminderDue')->orderBy(['Polls.id' => 'ASC'])->all()->toList();
|
||||
}
|
||||
|
||||
if (!$dryRun && $due !== []) {
|
||||
$io->out($this->describeTransport());
|
||||
}
|
||||
|
||||
$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;
|
||||
}
|
||||
if (!$forced) {
|
||||
// Only the marker column; the poll may have been changed meanwhile.
|
||||
$this->polls()->updateAll(['expiry_reminded_at' => DateTime::now()], ['id' => $poll->id]);
|
||||
}
|
||||
$io->out(($forced ? __('Erinnert (erzwungen, nicht markiert): {0}', $label) : __('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;
|
||||
}
|
||||
|
||||
/**
|
||||
* One line about the mail transport in use (never the password), so a misconfiguration is visible at once.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function describeTransport(): string
|
||||
{
|
||||
$transport = TransportFactory::get('default');
|
||||
$config = $transport->getConfig();
|
||||
$class = (new ReflectionClass($transport))->getShortName();
|
||||
if ($transport instanceof SmtpTransport) {
|
||||
return __(
|
||||
'Mail-Transport: {0} {1}:{2}, Benutzer {3}, TLS {4}',
|
||||
$class,
|
||||
$config['host'],
|
||||
$config['port'],
|
||||
$config['username'] ?? __('(keiner)'),
|
||||
$config['tls'] ? __('ja') : __('nein'),
|
||||
);
|
||||
}
|
||||
|
||||
if (trim((string)env('SMTP_HOST', '')) !== '') {
|
||||
return __(
|
||||
'WARNUNG: SMTP_HOST ist gesetzt, aber der Transport ist {0}. Vermutlich überschreibt config/app_local.php ' .
|
||||
'den Transport (auf Servern config/app_local.php löschen, Konfiguration nur über .env). Es wird nichts verschickt.',
|
||||
$class,
|
||||
);
|
||||
}
|
||||
|
||||
return __('Mail-Transport: {0} (kein SMTP, SMTP_HOST nicht gesetzt)', $class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
|
||||
/**
|
||||
* Details of one poll. The secret admin link is only printed with --link.
|
||||
*
|
||||
* Usage: bin/cake polls show <id|code> [--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('json', [
|
||||
'help' => __('Ausgabe als JSON statt als Text (für Skripte).'),
|
||||
'boolean' => 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();
|
||||
if ($args->getOption('json')) {
|
||||
$data = $this->pollData($poll) + ['slides' => $slides, 'adminUrl' => null];
|
||||
if ($args->getOption('link')) {
|
||||
$data['adminUrl'] = $this->adminLink($poll);
|
||||
if ($data['adminUrl'] === null) {
|
||||
$io->err(__('Der Admin-Link lässt sich nicht entschlüsseln (SECURITY_SALT geändert?).'));
|
||||
|
||||
return static::CODE_ERROR;
|
||||
}
|
||||
}
|
||||
$this->printJson($io, $data);
|
||||
|
||||
return static::CODE_SUCCESS;
|
||||
}
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,15 @@ class AdminController extends AdminAppController
|
||||
// Created on first visit, so every slide has its embed URL ready to copy.
|
||||
$embedKey = $this->Polls->ensureEmbedKey($this->poll);
|
||||
|
||||
$this->set(compact('slides', 'responseCounts', 'typeLabels', 'typeDescriptions', 'joinUrl', 'embedKey'));
|
||||
$hasPrepared = $this->Responses->hasPrepared($this->poll->id);
|
||||
$this->setPollInterval();
|
||||
|
||||
// Answers are not the only thing a reset undoes: a started quiz, closed slides or a running presentation too.
|
||||
$canReset = $responseCounts !== []
|
||||
|| $this->poll->isStarted()
|
||||
|| array_filter($slides, fn(Slide $slide) => !$slide->isFresh()) !== [];
|
||||
|
||||
$this->set(compact('slides', 'responseCounts', 'canReset', 'hasPrepared', 'typeLabels', 'typeDescriptions', 'joinUrl', 'embedKey'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,15 +125,17 @@ class AdminController extends AdminAppController
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all responses of all slides; slides, settings and the presentation are kept
|
||||
* (e.g. to run the poll with another group).
|
||||
* Deletes all responses of all slides and puts the presentation back to "not started"; slides and settings
|
||||
* are kept (e.g. to run the poll with another group). Prepared Q&A questions stay unless
|
||||
* `keep_prepared` is sent as 0.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function reset(): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
(new ResetService())->poll($this->poll);
|
||||
$keepPrepared = $this->request->getData('keep_prepared', '1') !== '0';
|
||||
(new ResetService())->poll($this->poll, $keepPrepared);
|
||||
$this->Flash->success(__('Alle Antworten wurden gelöscht.'));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
@@ -159,7 +169,16 @@ class AdminController extends AdminAppController
|
||||
*/
|
||||
public function present(): void
|
||||
{
|
||||
if ($this->poll->current_slide_id === null && !$this->poll->isPaused()) {
|
||||
$this->prepareStage(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $start Show the first slide if the presentation has not been started yet
|
||||
* @return void
|
||||
*/
|
||||
private function prepareStage(bool $start): void
|
||||
{
|
||||
if ($start && $this->poll->current_slide_id === null && !$this->poll->isPaused()) {
|
||||
$first = $this->Slides->find()
|
||||
->where(['poll_id' => $this->poll->id, 'is_hidden' => false])
|
||||
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
|
||||
@@ -176,6 +195,19 @@ class AdminController extends AdminAppController
|
||||
$this->setPollInterval();
|
||||
}
|
||||
|
||||
/**
|
||||
* Speaker view for a second window or screen: current slide, preview of the next one and the
|
||||
* same controls as the presenter screen. Unlike present() it never starts the presentation.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function speaker(): void
|
||||
{
|
||||
$this->prepareStage(false);
|
||||
$this->set('speaker', true);
|
||||
$this->viewBuilder()->setTemplate('present');
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON state for the presenter screen.
|
||||
*
|
||||
@@ -186,13 +218,25 @@ class AdminController extends AdminAppController
|
||||
return $this->json((new PollStateService())->forPresenter($this->poll));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fingerprint of the dashboard content (JSON `{version}`), polled by the dashboard so the
|
||||
* live marker follows the presenter. See PollStateService::dashboardVersion().
|
||||
*
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function live(): Response
|
||||
{
|
||||
return $this->json(['version' => (new PollStateService())->dashboardVersion($this->poll)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Presenter controls. Field `action`:
|
||||
* goto (+ slide_id), next, prev, stop (pause), resume (continue after a pause), and the slide actions of
|
||||
* SlideControlService (open, close, toggle, stage, question).
|
||||
*
|
||||
* On a Q&A slide that is being discussed, next/prev step through the questions
|
||||
* first (like builds in presentation software). While paused, next/prev resume
|
||||
* first (like builds in presentation software); on a quiz, next starts it and then ends it
|
||||
* before moving on, prev always goes to the previous slide. While paused, next/prev resume
|
||||
* the slide that was live before.
|
||||
*
|
||||
* Answers with the new state as JSON for XHR requests, otherwise redirects back.
|
||||
@@ -216,6 +260,15 @@ class AdminController extends AdminAppController
|
||||
) {
|
||||
$action = 'none';
|
||||
}
|
||||
// Forward on a quiz is a build step too: start it, then end it, only then the next slide.
|
||||
// Back never touches the quiz, so a clicker can page through the slides afterwards.
|
||||
if ($current !== null && $current->isQuiz() && $action === 'next') {
|
||||
$phase = $current->quizPhase();
|
||||
if ($phase !== Slide::QUIZ_FINISHED) {
|
||||
(new SlideControlService())->apply($current, $phase === Slide::QUIZ_READY ? 'open' : 'close');
|
||||
$action = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
switch ($action) {
|
||||
case 'none':
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Controller;
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\PollsTable;
|
||||
use App\Service\ImageService;
|
||||
use App\Service\PollStateService;
|
||||
use App\Service\VoteException;
|
||||
use App\Service\VoteService;
|
||||
@@ -49,6 +50,10 @@ class ParticipateController extends AppController
|
||||
public function beforeFilter(EventInterface $event): void
|
||||
{
|
||||
parent::beforeFilter($event);
|
||||
if ($this->request->getParam('action') === 'image') {
|
||||
// Cacheable static content: no participant id, no cookie.
|
||||
return;
|
||||
}
|
||||
|
||||
$pid = (string)$this->request->getCookie(self::COOKIE, '');
|
||||
if (!preg_match('/^[a-f0-9]{32}$/', $pid)) {
|
||||
@@ -95,6 +100,30 @@ class ParticipateController extends AppController
|
||||
$this->setPollInterval();
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves the image of a slide of this poll. The file name is random and changes with every new
|
||||
* image, so the answer can be cached for good; unknown or replaced images are 404.
|
||||
*
|
||||
* @param string $code Join code
|
||||
* @param string $file Stored file name
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function image(string $code, string $file): Response
|
||||
{
|
||||
$poll = $this->loadPoll($code);
|
||||
$path = $this->fetchTable('Slides')->exists(['poll_id' => $poll->id, 'image' => $file])
|
||||
? (new ImageService())->path($poll->id, $file)
|
||||
: null;
|
||||
if ($path === null) {
|
||||
throw new NotFoundException(__('Bild nicht gefunden.'));
|
||||
}
|
||||
|
||||
return $this->response
|
||||
->withFile($path)
|
||||
->withHeader('Content-Type', 'image/webp')
|
||||
->withHeader('Cache-Control', 'private, max-age=31536000, immutable');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $code Join code
|
||||
* @return \Cake\Http\Response
|
||||
|
||||
@@ -5,12 +5,17 @@ namespace App\Controller;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use App\Service\ImageException;
|
||||
use App\Service\ImageService;
|
||||
use App\Service\QaService;
|
||||
use App\Service\ResetService;
|
||||
use App\Service\ResultsService;
|
||||
use App\Service\YouTubeService;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Http\Exception\NotFoundException;
|
||||
use Cake\Http\Response;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Slide CRUD below /admin/{token}/slides.
|
||||
@@ -115,6 +120,9 @@ class SlidesController extends AdminAppController
|
||||
$this->Slides->deleteOrFail($slide);
|
||||
$this->Slides->normalizePositions($this->poll->id);
|
||||
});
|
||||
// After the commit (a rolled back deletion keeps its image). Model.afterDeleteCommit does not fire
|
||||
// inside this transaction, so the file is removed here.
|
||||
(new ImageService())->delete($this->poll->id, $slide->image);
|
||||
$this->Flash->success(__('Folie gelöscht.'));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
@@ -201,7 +209,7 @@ class SlidesController extends AdminAppController
|
||||
}
|
||||
|
||||
/**
|
||||
* All answers of an open question or the ratings of a scale
|
||||
* All answers of an open question, the ratings of a scale or the comments of a choice slide
|
||||
* (also anonymous/internal feedback, which is never shown on the stage).
|
||||
*
|
||||
* @param string $id Slide id
|
||||
@@ -210,7 +218,7 @@ class SlidesController extends AdminAppController
|
||||
public function answers(string $id): void
|
||||
{
|
||||
$slide = $this->loadSlide($id);
|
||||
if (!in_array($slide->type, [Slide::TYPE_OPEN, Slide::TYPE_SCALE], true)) {
|
||||
if (!in_array($slide->type, [Slide::TYPE_OPEN, Slide::TYPE_SCALE], true) && !$slide->hasComments()) {
|
||||
throw new NotFoundException(__('Folie nicht gefunden.'));
|
||||
}
|
||||
$results = new ResultsService();
|
||||
@@ -289,6 +297,8 @@ class SlidesController extends AdminAppController
|
||||
$data = (array)$this->request->getData();
|
||||
// The type of an existing slide cannot change (would invalidate responses).
|
||||
$data['type'] = $slide->type;
|
||||
// The upload is handled by prepareImage(); the marshaller must not see the file object.
|
||||
unset($data['image']);
|
||||
$fields = ['type', 'question', 'description', 'settings', 'is_voting_open'];
|
||||
if ($slide->isQuiz() || $slide->isQa()) {
|
||||
// Quiz and Q&A voting is controlled by the presenter only.
|
||||
@@ -299,6 +309,7 @@ class SlidesController extends AdminAppController
|
||||
foreach ($youtube['errors'] as $field => $message) {
|
||||
$slide->setError($field, $message);
|
||||
}
|
||||
$image = $this->prepareImage($slide, $data);
|
||||
|
||||
$labels = SlidesTable::parseOptionLines($optionsText);
|
||||
$correct = [];
|
||||
@@ -326,11 +337,136 @@ class SlidesController extends AdminAppController
|
||||
}
|
||||
}
|
||||
if ($slide->hasErrors()) {
|
||||
$this->Flash->error(__('Bitte prüfe deine Eingaben.'));
|
||||
$this->discardImage($slide, $image);
|
||||
$this->Flash->error(__('Bitte prüfe deine Eingaben.') . ($image['new'] !== null ? ' ' . __('Das Bild musst du danach erneut auswählen.') : ''));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$saved = $this->persistSlide($slide, $labels, $correct, $youtube);
|
||||
} catch (Throwable $e) {
|
||||
$this->discardImage($slide, $image);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
if (!$saved) {
|
||||
$this->discardImage($slide, $image);
|
||||
|
||||
return false;
|
||||
}
|
||||
// Committed: the replaced (or removed) image is no longer referenced.
|
||||
if ($image['old'] !== null && $image['old'] !== $slide->image) {
|
||||
(new ImageService())->delete($this->poll->id, $image['old']);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the image of a posted slide: stores a new upload (scaled to WebP), takes over alternative
|
||||
* text and layout, or removes the image (`remove_image`). The values are set on the entity;
|
||||
* use discardImage() if the slide is not saved after all.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide with the posted data patched
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @return array{new: string|null, old: string|null, original: array<string, mixed>}
|
||||
* `new` = file stored for this request, `old` = file the slide had before
|
||||
*/
|
||||
protected function prepareImage(Slide $slide, array $data): array
|
||||
{
|
||||
$fields = ['image', 'image_alt', 'image_layout', 'image_width', 'image_height'];
|
||||
$original = [];
|
||||
foreach ($fields as $field) {
|
||||
$original[$field] = $slide->get($field);
|
||||
}
|
||||
$state = ['new' => null, 'old' => $slide->image, 'original' => $original];
|
||||
if (!Slide::supportsImage($slide->type)) {
|
||||
return $state;
|
||||
}
|
||||
|
||||
// Collected and set at the end: patching a field resets its errors.
|
||||
$errors = [];
|
||||
$upload = $this->request->getUploadedFile('image');
|
||||
$hasUpload = $upload instanceof UploadedFileInterface && $upload->getError() !== UPLOAD_ERR_NO_FILE;
|
||||
$remove = !$hasUpload && filter_var($data['remove_image'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
|
||||
if ($hasUpload) {
|
||||
if (!$slide->hasImage() && $this->Slides->countImages($this->poll->id) >= (int)Configure::read('Plenario.images.maxPerPoll', 20)) {
|
||||
$errors['image'] = __(
|
||||
'Pro Umfrage sind höchstens {0} Folien mit Bild möglich. Entferne bei einer anderen Folie das Bild.',
|
||||
(int)Configure::read('Plenario.images.maxPerPoll', 20),
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
$stored = (new ImageService())->store($upload, $this->poll->id);
|
||||
$state['new'] = $stored['name'];
|
||||
$slide->patch(['image' => $stored['name'], 'image_width' => $stored['width'], 'image_height' => $stored['height']], ['guard' => false]);
|
||||
} catch (ImageException $e) {
|
||||
$errors['image'] = $e->getMessage();
|
||||
}
|
||||
}
|
||||
} elseif ($remove) {
|
||||
$slide->patch(['image' => null, 'image_alt' => null, 'image_layout' => null, 'image_width' => null, 'image_height' => null], ['guard' => false]);
|
||||
}
|
||||
|
||||
if (!$slide->hasImage()) {
|
||||
$this->setErrors($slide, $errors);
|
||||
|
||||
return $state;
|
||||
}
|
||||
$layout = $data['image_layout'] ?? null;
|
||||
$slide->patch([
|
||||
// Presentation images are decoration: no description is asked for (alt="").
|
||||
'image_alt' => '',
|
||||
'image_layout' => in_array($layout, Slide::IMAGE_LAYOUTS, true) ? $layout : null,
|
||||
], ['guard' => false]);
|
||||
$this->setErrors($slide, $errors);
|
||||
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param array<string, string> $errors Field => message
|
||||
* @return void
|
||||
*/
|
||||
protected function setErrors(Slide $slide, array $errors): void
|
||||
{
|
||||
foreach ($errors as $field => $message) {
|
||||
$slide->setError($field, $message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws away the image stored for this request and restores the previous image values
|
||||
* of the entity (the slide was not saved, the form is shown again).
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param array{new: string|null, old: string|null, original: array<string, mixed>} $image State of prepareImage()
|
||||
* @return void
|
||||
*/
|
||||
protected function discardImage(Slide $slide, array $image): void
|
||||
{
|
||||
if ($image['new'] !== null) {
|
||||
(new ImageService())->delete($this->poll->id, $image['new']);
|
||||
}
|
||||
$errors = $slide->getErrors();
|
||||
$slide->patch($image['original'], ['guard' => false]);
|
||||
$slide->setErrors($errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the slide and its options in one transaction.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param list<string> $labels Option labels
|
||||
* @param list<string> $correct Labels of the correct options
|
||||
* @param array{errors: array<string, string>, warning: string|null} $youtube Result of prepareYouTube()
|
||||
* @return bool
|
||||
*/
|
||||
protected function persistSlide(Slide $slide, array $labels, array $correct, array $youtube): bool
|
||||
{
|
||||
return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels, $correct, $youtube): bool {
|
||||
if (!$this->Slides->save($slide)) {
|
||||
return false;
|
||||
|
||||
@@ -13,6 +13,28 @@ use Throwable;
|
||||
*/
|
||||
class PollMailer extends Mailer
|
||||
{
|
||||
/**
|
||||
* Content-ID of the logo that layout/email/html/default.php references as `cid:plenario-logo`.
|
||||
*/
|
||||
public const LOGO_CID = 'plenario-logo';
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|string|null $profile Mailer profile, see parent
|
||||
*/
|
||||
public function __construct(array|string|null $profile = null)
|
||||
{
|
||||
parent::__construct($profile);
|
||||
// Inline attachment: shown without "load images" prompts and independent of a public base URL.
|
||||
$this->addAttachments([
|
||||
'logo.png' => [
|
||||
'file' => RESOURCES . 'mail' . DS . 'logo.png',
|
||||
'mimetype' => 'image/png',
|
||||
'contentId' => static::LOGO_CID,
|
||||
'contentDisposition' => false,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a mail like send(), but logs transport errors instead of throwing them,
|
||||
* so the user gets a friendly hint and the action itself still succeeds.
|
||||
@@ -53,6 +75,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.
|
||||
*
|
||||
|
||||
@@ -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).
|
||||
*
|
||||
@@ -109,6 +158,18 @@ class Poll extends Entity
|
||||
$this->embed_seen_at = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Back to "not started": neither live nor paused. Idempotent.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function notStarted(): void
|
||||
{
|
||||
$this->current_slide_id = null;
|
||||
$this->paused_slide_id = null;
|
||||
$this->embed_seen_at = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A slide leaves the presentation (deleted or hidden). If it was live or is the one a pause
|
||||
* resumes, the poll pauses and resumes with $resumeSlideId instead (null: no slides left =
|
||||
@@ -128,6 +189,14 @@ class Poll extends Entity
|
||||
$this->embed_seen_at = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool Live or paused, i.e. not in the state notStarted() sets
|
||||
*/
|
||||
public function isStarted(): bool
|
||||
{
|
||||
return $this->current_slide_id !== null || $this->paused_slide_id !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool Paused after a slide had been live (not: not started yet)
|
||||
*/
|
||||
|
||||
@@ -19,6 +19,11 @@ use Cake\ORM\Entity;
|
||||
* @property int $position
|
||||
* @property bool $is_hidden Prepared, but skipped in the presentation (never live)
|
||||
* @property array<string, mixed>|null $settings
|
||||
* @property string|null $image File name of the slide image in the poll's upload directory (see ImageService)
|
||||
* @property string|null $image_alt Always '' (decorative): images are shown on the stage, no description is asked for
|
||||
* @property string|null $image_layout top|side|full, null = default of the type (see imageLayout())
|
||||
* @property int|null $image_width Pixels of the stored (scaled) image
|
||||
* @property int|null $image_height
|
||||
* @property bool $is_voting_open
|
||||
* @property \Cake\I18n\DateTime|null $voting_started_at Quiz: start of the voting window
|
||||
* @property \Cake\I18n\DateTime|null $voting_ends_at Quiz: deadline (null = closed manually)
|
||||
@@ -101,7 +106,9 @@ class Slide extends Entity
|
||||
* @var array<string, array<string, mixed>>
|
||||
*/
|
||||
public const DEFAULT_SETTINGS = [
|
||||
self::TYPE_CHOICE => ['multiple' => false],
|
||||
// comments: optional comment field (stored in text_value of the participant's first row),
|
||||
// comments rotate in the presentation like those of a scale
|
||||
self::TYPE_CHOICE => ['multiple' => false, 'comments' => false],
|
||||
// allow_downvotes only takes effect together with allow_upvotes
|
||||
self::TYPE_WORDCLOUD => ['allow_upvotes' => true, 'allow_downvotes' => true],
|
||||
// private: anonymous feedback, answers only visible in the admin area (never on the stage)
|
||||
@@ -133,6 +140,15 @@ class Slide extends Entity
|
||||
self::TYPE_ORDER => [],
|
||||
];
|
||||
|
||||
/**
|
||||
* Where the image of a slide goes: above the results, next to the text (presenter only,
|
||||
* participants' phones always show it on top) or - content slides - as large as possible.
|
||||
*/
|
||||
public const IMAGE_TOP = 'top';
|
||||
public const IMAGE_SIDE = 'side';
|
||||
public const IMAGE_FULL = 'full';
|
||||
public const IMAGE_LAYOUTS = [self::IMAGE_TOP, self::IMAGE_SIDE, self::IMAGE_FULL];
|
||||
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
@@ -144,6 +160,41 @@ class Slide extends Entity
|
||||
'is_voting_open' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether slides of this type can carry an image (everything but YouTube, which has its own media).
|
||||
*
|
||||
* @param string $type Slide type
|
||||
* @return bool
|
||||
*/
|
||||
public static function supportsImage(string $type): bool
|
||||
{
|
||||
return $type !== self::TYPE_YOUTUBE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function hasImage(): bool
|
||||
{
|
||||
return $this->image !== null && $this->image !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Layout of the image: the chosen one, otherwise by type - next to the text on content slides,
|
||||
* above the question's answers elsewhere. "full" only exists for content slides.
|
||||
*
|
||||
* @return string One of IMAGE_LAYOUTS
|
||||
*/
|
||||
public function imageLayout(): string
|
||||
{
|
||||
$layout = $this->image_layout;
|
||||
if (!in_array($layout, self::IMAGE_LAYOUTS, true) || ($layout === self::IMAGE_FULL && $this->type !== self::TYPE_CONTENT)) {
|
||||
return $this->type === self::TYPE_CONTENT ? self::IMAGE_SIDE : self::IMAGE_TOP;
|
||||
}
|
||||
|
||||
return $layout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> type => human readable label
|
||||
*/
|
||||
@@ -448,6 +499,21 @@ class Slide extends Entity
|
||||
$this->focus_response_id = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the slide is in the state startFresh() sets (nothing started, closed or discussed yet).
|
||||
* A reset has nothing to do for such a slide unless it has answers.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isFresh(): bool
|
||||
{
|
||||
return $this->is_voting_open === !$this->isQuiz()
|
||||
&& $this->voting_started_at === null
|
||||
&& $this->voting_ends_at === null
|
||||
&& $this->stage === ($this->isQa() ? self::QA_COLLECT : null)
|
||||
&& $this->focus_response_id === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens or closes voting. Opening a quiz that is not running (re)starts its
|
||||
* voting window and timer; opening a running quiz changes nothing.
|
||||
@@ -500,13 +566,13 @@ class Slide extends Entity
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale with an optional comment field for participants.
|
||||
* Multiple choice or scale with an optional comment field for participants.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasComments(): bool
|
||||
{
|
||||
return $this->type === self::TYPE_SCALE && (bool)$this->setting('comments');
|
||||
return in_array($this->type, [self::TYPE_CHOICE, self::TYPE_SCALE], true) && (bool)$this->setting('comments');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,12 @@ declare(strict_types=1);
|
||||
namespace App\Model\Table;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Service\ImageService;
|
||||
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;
|
||||
@@ -54,6 +59,20 @@ class PollsTable extends Table
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* After the poll is gone for good, so are the image files of its slides (the slides remove
|
||||
* their own; this also sweeps what a crash left behind).
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event
|
||||
* @param \Cake\Datasource\EntityInterface $entity Deleted poll
|
||||
* @param \ArrayObject<string, mixed> $options Options
|
||||
* @return void
|
||||
*/
|
||||
public function afterDeleteCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
|
||||
{
|
||||
(new ImageService())->deletePoll((int)$entity->get('id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Validation\Validator $validator Validator instance.
|
||||
* @return \Cake\Validation\Validator
|
||||
@@ -258,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
|
||||
|
||||
@@ -172,6 +172,18 @@ class ResponsesTable extends Table
|
||||
return (int)($row['n'] ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $pollId Poll id
|
||||
* @return bool Whether the poll has Q&A questions entered beforehand
|
||||
*/
|
||||
public function hasPrepared(int $pollId): bool
|
||||
{
|
||||
return $this->find()
|
||||
->innerJoinWith('Slides')
|
||||
->where(['Slides.poll_id' => $pollId, 'Responses.participant_hash' => VoteService::PREPARED_HASH])
|
||||
->count() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of responding participants per slide of a poll.
|
||||
*
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
namespace App\Model\Table;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Service\ImageService;
|
||||
use App\Service\YouTubeService;
|
||||
use ArrayObject;
|
||||
use Cake\Database\Expression\QueryExpression;
|
||||
@@ -12,6 +13,7 @@ use Cake\Event\EventInterface;
|
||||
use Cake\ORM\RulesChecker;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\Validation\Validator;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property \App\Model\Table\PollsTable&\Cake\ORM\Association\BelongsTo $Polls
|
||||
@@ -109,6 +111,17 @@ class SlidesTable extends Table
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of slides of a poll that carry an image (they count against `Plenario.images.maxPerPoll`).
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @return int
|
||||
*/
|
||||
public function countImages(int $pollId): int
|
||||
{
|
||||
return $this->find()->where(['poll_id' => $pollId, 'image IS NOT' => null])->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign the next free position for new slides.
|
||||
*
|
||||
@@ -142,6 +155,7 @@ class SlidesTable extends Table
|
||||
switch ($type) {
|
||||
case Slide::TYPE_CHOICE:
|
||||
$settings['multiple'] = filter_var($input['multiple'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
$settings['comments'] = filter_var($input['comments'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
break;
|
||||
case Slide::TYPE_WORDCLOUD:
|
||||
$settings['allow_upvotes'] = filter_var($input['allow_upvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
|
||||
@@ -345,6 +359,36 @@ class SlidesTable extends Table
|
||||
$copy->position = $slide->position + 1;
|
||||
$copy->startFresh();
|
||||
|
||||
// The copy gets its own file, so deleting one slide never takes the image of the other.
|
||||
$images = new ImageService();
|
||||
$imageCopy = $slide->hasImage() ? $images->copy($slide->poll_id, (string)$slide->image) : null;
|
||||
if ($imageCopy !== null) {
|
||||
$copy->image = $imageCopy;
|
||||
$copy->image_alt = $slide->image_alt;
|
||||
$copy->image_layout = $slide->image_layout;
|
||||
$copy->image_width = $slide->image_width;
|
||||
$copy->image_height = $slide->image_height;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->persistCopy($slide, $copy);
|
||||
} catch (Throwable $e) {
|
||||
// Rolled back: the copied file belongs to no slide.
|
||||
$images->delete($slide->poll_id, $imageCopy);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a duplicated slide behind its original, together with the copies of the options.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Original incl. slide_options
|
||||
* @param \App\Model\Entity\Slide $copy Prepared copy
|
||||
* @return \App\Model\Entity\Slide
|
||||
*/
|
||||
protected function persistCopy(Slide $slide, Slide $copy): Slide
|
||||
{
|
||||
return $this->getConnection()->transactional(function () use ($slide, $copy): Slide {
|
||||
$this->updateAll(
|
||||
['position' => new QueryExpression('position + 1')],
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Thrown when an uploaded image is rejected. The message is safe to show to the admin.
|
||||
*/
|
||||
class ImageException extends RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use GdImage;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
|
||||
/**
|
||||
* Stores the images of slides.
|
||||
*
|
||||
* Uploads are decoded, rotated upright (EXIF orientation), scaled down to `Plenario.images.maxEdge`
|
||||
* and written as WebP. Re-encoding drops all metadata (GPS position of phone photos!) and defuses
|
||||
* files that are valid in two formats. Only the result is kept, never the original.
|
||||
*
|
||||
* Files live outside webroot in `{Plenario.images.path}/{poll id}/{random name}.webp` and are served
|
||||
* by ParticipateController::image(). Replacing an image creates a new random name, so the URL changes
|
||||
* and browsers can cache images forever.
|
||||
*
|
||||
* Deleting is idempotent: a missing file is fine. The database is the source of truth; files left
|
||||
* behind by a crash are removed by `bin/cake images_cleanup`.
|
||||
*/
|
||||
class ImageService
|
||||
{
|
||||
/**
|
||||
* Source formats that are accepted (animated GIFs are not, see assertNotAnimated()).
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected const TYPES = [
|
||||
IMAGETYPE_JPEG => 'jpeg',
|
||||
IMAGETYPE_PNG => 'png',
|
||||
IMAGETYPE_GIF => 'gif',
|
||||
IMAGETYPE_WEBP => 'webp',
|
||||
];
|
||||
|
||||
/**
|
||||
* Decoded pixels, to keep the memory use of the decoder in check (a bitmap needs 4 bytes per pixel).
|
||||
*/
|
||||
protected const MAX_PIXELS = 40_000_000;
|
||||
|
||||
/**
|
||||
* Whether the PHP installation can process images (GD with WebP).
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function isAvailable(): bool
|
||||
{
|
||||
return extension_loaded('gd') && function_exists('imagewebp') && function_exists('imagecreatefromstring');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a stored name has the shape generated by store() (guards file system access).
|
||||
*
|
||||
* @param string $name File name
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValidName(string $name): bool
|
||||
{
|
||||
return (bool)preg_match('/^[a-f0-9]{24}\.webp$/', $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates, scales and stores an upload.
|
||||
*
|
||||
* @param \Psr\Http\Message\UploadedFileInterface $file Uploaded file
|
||||
* @param int $pollId Poll the image belongs to
|
||||
* @return array{name: string, width: int, height: int}
|
||||
* @throws \App\Service\ImageException If the file cannot be used
|
||||
*/
|
||||
public function store(UploadedFileInterface $file, int $pollId): array
|
||||
{
|
||||
if (!self::isAvailable()) {
|
||||
throw new ImageException(__('Auf diesem Server können keine Bilder verarbeitet werden (PHP-Erweiterung GD mit WebP fehlt).'));
|
||||
}
|
||||
$this->assertUploaded($file);
|
||||
|
||||
$bytes = (string)$file->getStream();
|
||||
$info = @getimagesizefromstring($bytes);
|
||||
$type = $info === false ? null : (self::TYPES[$info[2]] ?? null);
|
||||
if ($info === false || $type === null) {
|
||||
throw new ImageException(__('Bitte wähle ein Bild im Format JPEG, PNG, WebP oder GIF aus.'));
|
||||
}
|
||||
if ($info[0] < 1 || $info[1] < 1 || $info[0] * $info[1] > self::MAX_PIXELS) {
|
||||
throw new ImageException(__('Das Bild hat zu viele Pixel. Bitte wähle ein kleineres Bild (höchstens 40 Megapixel).'));
|
||||
}
|
||||
if ($type === 'gif') {
|
||||
$this->assertNotAnimated($bytes);
|
||||
}
|
||||
|
||||
$image = @imagecreatefromstring($bytes);
|
||||
if (!$image instanceof GdImage) {
|
||||
throw new ImageException(__('Das Bild konnte nicht gelesen werden. Ist die Datei beschädigt?'));
|
||||
}
|
||||
if ($type === 'jpeg') {
|
||||
$image = $this->orient($image, self::jpegOrientation($bytes));
|
||||
}
|
||||
$image = $this->scale($image, (int)Configure::read('Plenario.images.maxEdge', 1600));
|
||||
|
||||
$name = bin2hex(random_bytes(12)) . '.webp';
|
||||
$directory = $this->directory($pollId);
|
||||
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) {
|
||||
throw new ImageException(__('Das Bild konnte nicht gespeichert werden (Upload-Verzeichnis nicht beschreibbar).'));
|
||||
}
|
||||
// Write under a temporary name first: a half written file must never be served.
|
||||
$temporary = $directory . DS . $name . '.tmp';
|
||||
$written = @imagewebp($image, $temporary, (int)Configure::read('Plenario.images.quality', 82));
|
||||
$width = imagesx($image);
|
||||
$height = imagesy($image);
|
||||
if (!$written || !@rename($temporary, $directory . DS . $name)) {
|
||||
@unlink($temporary);
|
||||
throw new ImageException(__('Das Bild konnte nicht gespeichert werden.'));
|
||||
}
|
||||
|
||||
return ['name' => $name, 'width' => $width, 'height' => $height];
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a stored image (duplicated slides get their own file, so deleting one never affects the other).
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @param string $name Source file name
|
||||
* @return string|null Name of the copy, null if the source file is gone
|
||||
*/
|
||||
public function copy(int $pollId, string $name): ?string
|
||||
{
|
||||
$source = $this->path($pollId, $name);
|
||||
if ($source === null) {
|
||||
return null;
|
||||
}
|
||||
$copy = bin2hex(random_bytes(12)) . '.webp';
|
||||
|
||||
return @copy($source, $this->directory($pollId) . DS . $copy) ? $copy : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Absolute path of a stored image, null if the name is invalid or the file does not exist.
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @param string $name File name
|
||||
* @return string|null
|
||||
*/
|
||||
public function path(int $pollId, string $name): ?string
|
||||
{
|
||||
if (!self::isValidName($name)) {
|
||||
return null;
|
||||
}
|
||||
$path = $this->directory($pollId) . DS . $name;
|
||||
|
||||
return is_file($path) ? $path : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes one image file. Idempotent, ignores unknown names and missing files.
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @param string|null $name File name
|
||||
* @return void
|
||||
*/
|
||||
public function delete(int $pollId, ?string $name): void
|
||||
{
|
||||
if ($name === null || !self::isValidName($name)) {
|
||||
return;
|
||||
}
|
||||
@unlink($this->directory($pollId) . DS . $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all images of a poll (and its directory).
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @return void
|
||||
*/
|
||||
public function deletePoll(int $pollId): void
|
||||
{
|
||||
$directory = $this->directory($pollId);
|
||||
foreach (glob($directory . DS . '*') ?: [] as $file) {
|
||||
if (is_file($file)) {
|
||||
@unlink($file);
|
||||
}
|
||||
}
|
||||
@rmdir($directory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes files that no slide refers to (left behind by aborted uploads, crashes or deleted polls).
|
||||
*
|
||||
* @param array<int, list<string>> $referenced Used file names per poll id
|
||||
* @param bool $dryRun Only report, delete nothing
|
||||
* @return list<string> Removed paths relative to the upload directory
|
||||
*/
|
||||
public function cleanup(array $referenced, bool $dryRun = false): array
|
||||
{
|
||||
$removed = [];
|
||||
$root = $this->root();
|
||||
foreach (glob($root . DS . '*', GLOB_ONLYDIR) ?: [] as $directory) {
|
||||
$pollId = basename($directory);
|
||||
if (!ctype_digit($pollId)) {
|
||||
continue;
|
||||
}
|
||||
$used = $referenced[(int)$pollId] ?? [];
|
||||
foreach (glob($directory . DS . '*') ?: [] as $file) {
|
||||
if (is_file($file) && !in_array(basename($file), $used, true)) {
|
||||
if (!$dryRun) {
|
||||
@unlink($file);
|
||||
}
|
||||
$removed[] = $pollId . '/' . basename($file);
|
||||
}
|
||||
}
|
||||
if (!$dryRun) {
|
||||
// Only succeeds for an empty directory.
|
||||
@rmdir($directory);
|
||||
}
|
||||
}
|
||||
|
||||
return $removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Upload root directory
|
||||
*/
|
||||
protected function root(): string
|
||||
{
|
||||
return rtrim((string)Configure::read('Plenario.images.path'), '/\\');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $pollId Poll id
|
||||
* @return string
|
||||
*/
|
||||
protected function directory(int $pollId): string
|
||||
{
|
||||
return $this->root() . DS . $pollId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Psr\Http\Message\UploadedFileInterface $file Uploaded file
|
||||
* @return void
|
||||
*/
|
||||
protected function assertUploaded(UploadedFileInterface $file): void
|
||||
{
|
||||
switch ($file->getError()) {
|
||||
case UPLOAD_ERR_OK:
|
||||
break;
|
||||
case UPLOAD_ERR_INI_SIZE:
|
||||
case UPLOAD_ERR_FORM_SIZE:
|
||||
throw new ImageException(__(
|
||||
'Die Datei ist größer, als der Server erlaubt ({0}). Bitte wähle ein kleineres Bild.',
|
||||
(string)ini_get('upload_max_filesize'),
|
||||
));
|
||||
default:
|
||||
throw new ImageException(__('Das Bild konnte nicht hochgeladen werden. Bitte versuche es noch einmal.'));
|
||||
}
|
||||
$max = (int)Configure::read('Plenario.images.maxUploadBytes', 10 * 1024 * 1024);
|
||||
if (($file->getSize() ?? 0) > $max) {
|
||||
throw new ImageException(__('Das Bild ist zu groß (höchstens {0} MB).', (int)round($max / 1024 / 1024)));
|
||||
}
|
||||
if (($file->getSize() ?? 0) === 0) {
|
||||
throw new ImageException(__('Die Datei ist leer.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GD cannot keep animations, so an animated GIF would silently become a still image.
|
||||
*
|
||||
* @param string $bytes GIF file
|
||||
* @return void
|
||||
*/
|
||||
protected function assertNotAnimated(string $bytes): void
|
||||
{
|
||||
// Every frame starts with a graphic control extension followed by an image descriptor.
|
||||
if (preg_match_all('/\x21\xF9\x04.{4}\x00[\x2C\x21]/s', $bytes) > 1) {
|
||||
throw new ImageException(__('Animierte GIFs werden nicht unterstützt. Bitte wähle ein Standbild (JPEG, PNG oder WebP).'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotates/flips a decoded image according to the EXIF orientation (1-8).
|
||||
*
|
||||
* @param \GdImage $image Image
|
||||
* @param int $orientation EXIF orientation
|
||||
* @return \GdImage
|
||||
*/
|
||||
protected function orient(GdImage $image, int $orientation): GdImage
|
||||
{
|
||||
// GD rotates counter-clockwise, EXIF names the rotation that is needed to display it upright.
|
||||
// 5 and 7 are mirrored first (flip, then rotate), 2 and 4 are plain mirrors.
|
||||
$angle = [3 => 180, 4 => 180, 5 => 90, 6 => 270, 7 => 270, 8 => 90][$orientation] ?? 0;
|
||||
$mirror = in_array($orientation, [2, 4, 5, 7], true);
|
||||
if ($mirror) {
|
||||
imageflip($image, IMG_FLIP_HORIZONTAL);
|
||||
}
|
||||
if ($angle !== 0) {
|
||||
$rotated = imagerotate($image, $angle, 0);
|
||||
if ($rotated instanceof GdImage) {
|
||||
return $rotated;
|
||||
}
|
||||
}
|
||||
|
||||
return $image;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scales an image down so that its longer edge is at most `$maxEdge` pixels (never up).
|
||||
* The result is a true color image with alpha channel, ready for WebP.
|
||||
*
|
||||
* @param \GdImage $image Image
|
||||
* @param int $maxEdge Longest edge in pixels
|
||||
* @return \GdImage
|
||||
*/
|
||||
protected function scale(GdImage $image, int $maxEdge): GdImage
|
||||
{
|
||||
imagepalettetotruecolor($image);
|
||||
imagealphablending($image, false);
|
||||
imagesavealpha($image, true);
|
||||
|
||||
$width = imagesx($image);
|
||||
$height = imagesy($image);
|
||||
$longest = max($width, $height);
|
||||
if ($longest <= $maxEdge) {
|
||||
return $image;
|
||||
}
|
||||
$factor = $maxEdge / $longest;
|
||||
$scaled = imagescale($image, max(1, (int)round($width * $factor)), max(1, (int)round($height * $factor)), IMG_BICUBIC);
|
||||
|
||||
if (!$scaled instanceof GdImage) {
|
||||
return $image;
|
||||
}
|
||||
imagealphablending($scaled, false);
|
||||
imagesavealpha($scaled, true);
|
||||
|
||||
return $scaled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the EXIF orientation of a JPEG without the exif extension (it is not always installed).
|
||||
*
|
||||
* @param string $bytes JPEG file
|
||||
* @return int Orientation 1-8, 1 = upright/unknown
|
||||
*/
|
||||
public static function jpegOrientation(string $bytes): int
|
||||
{
|
||||
$length = strlen($bytes);
|
||||
$offset = 2;
|
||||
// Walk the marker segments until the one holding the Exif data (APP1).
|
||||
while ($offset + 4 <= $length && $bytes[$offset] === "\xFF") {
|
||||
$marker = ord($bytes[$offset + 1]);
|
||||
if ($marker === 0xDA || $marker === 0xD9) {
|
||||
break;
|
||||
}
|
||||
$size = unpack('n', substr($bytes, $offset + 2, 2))[1] ?? 0;
|
||||
if ($marker === 0xE1 && substr($bytes, $offset + 4, 6) === "Exif\0\0") {
|
||||
return self::tiffOrientation(substr($bytes, $offset + 10, max(0, $size - 8)));
|
||||
}
|
||||
$offset += 2 + $size;
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $tiff TIFF structure of the Exif segment
|
||||
* @return int Orientation 1-8
|
||||
*/
|
||||
protected static function tiffOrientation(string $tiff): int
|
||||
{
|
||||
if (strlen($tiff) < 14) {
|
||||
return 1;
|
||||
}
|
||||
$little = substr($tiff, 0, 2) === 'II';
|
||||
$short = $little ? 'v' : 'n';
|
||||
$long = $little ? 'V' : 'N';
|
||||
$first = unpack($long, substr($tiff, 4, 4))[1] ?? 0;
|
||||
if ($first < 8 || $first + 2 > strlen($tiff)) {
|
||||
return 1;
|
||||
}
|
||||
$entries = unpack($short, substr($tiff, $first, 2))[1] ?? 0;
|
||||
for ($i = 0; $i < $entries; $i++) {
|
||||
$entry = $first + 2 + $i * 12;
|
||||
if ($entry + 12 > strlen($tiff)) {
|
||||
break;
|
||||
}
|
||||
if ((unpack($short, substr($tiff, $entry, 2))[1] ?? 0) === 0x0112) {
|
||||
$value = unpack($short, substr($tiff, $entry + 8, 2))[1] ?? 1;
|
||||
|
||||
return $value >= 1 && $value <= 8 ? $value : 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use App\Model\Table\PollsTable;
|
||||
use App\Model\Table\ResponsesTable;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
use Cake\Routing\Router;
|
||||
|
||||
/**
|
||||
* Builds the JSON state polled by the presenter screen (/admin/{token}/state)
|
||||
@@ -56,6 +57,33 @@ class PollStateService
|
||||
$this->results = new ResultsService();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cheap fingerprint of everything the admin dashboard shows (live/paused slide, slide settings
|
||||
* and status, answer counts). The dashboard polls it and reloads its lists when it changes.
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @return string
|
||||
*/
|
||||
public function dashboardVersion(Poll $poll): string
|
||||
{
|
||||
$slides = $this->Slides->find()
|
||||
->select([
|
||||
'n' => $this->Slides->find()->func()->count('*'),
|
||||
'latest' => $this->Slides->find()->func()->max('modified'),
|
||||
])
|
||||
->where(['poll_id' => $poll->id])
|
||||
->disableHydration()
|
||||
->first();
|
||||
|
||||
return md5(json_encode([
|
||||
(int)$poll->is_active,
|
||||
$poll->current_slide_id,
|
||||
$poll->paused_slide_id,
|
||||
$slides,
|
||||
$this->Responses->countParticipantsPerSlide($poll->id),
|
||||
], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @return \App\Model\Entity\Slide|null
|
||||
@@ -103,12 +131,51 @@ class PollStateService
|
||||
], $slides),
|
||||
'index' => $index,
|
||||
'count' => count($slides),
|
||||
'next' => $this->nextPreview($poll, $slides, $index),
|
||||
'hiddenCount' => $this->Slides->find()->where(['poll_id' => $poll->id, 'is_hidden' => true])->count(),
|
||||
'slide' => $current ? $this->slidePayload($current) : null,
|
||||
'slide' => $current ? $this->slidePayload($current, $poll) : null,
|
||||
'results' => $current ? $this->results->forSlide($current) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview of the slide that comes next for the speaker view: the one behind the live slide, the
|
||||
* paused one while paused (that is where "continue" goes), the first one before the start.
|
||||
* Labels only: never `is_correct` and never the options of an order slide (they are stored in the
|
||||
* correct order), so nothing leaks that is not allowed in the JSON before the slide is resolved.
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @param list<\App\Model\Entity\Slide> $slides Visible slides in presentation order
|
||||
* @param int|null $index Index of the live slide in `$slides`
|
||||
* @return array<string, mixed>|null Null after the last slide
|
||||
*/
|
||||
private function nextPreview(Poll $poll, array $slides, ?int $index): ?array
|
||||
{
|
||||
if ($index !== null) {
|
||||
$next = $slides[$index + 1] ?? null;
|
||||
} else {
|
||||
$next = $slides[0] ?? null;
|
||||
foreach ($slides as $slide) {
|
||||
if ($poll->paused_slide_id !== null && $slide->id === $poll->paused_slide_id) {
|
||||
$next = $slide;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($next === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $next->id,
|
||||
'type' => $next->type,
|
||||
'typeLabel' => $next->typeLabel(),
|
||||
'question' => $next->question,
|
||||
'description' => (string)$next->description,
|
||||
'options' => $next->isOrder() ? [] : array_map(fn($o) => $o->label, $next->slide_options ?? []),
|
||||
'hasImage' => $next->hasImage(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* State of one embedded slide (/e/{key}/{slide}/state). Same shape as forPresenter(),
|
||||
* but always for this slide, live or not, plus `isLive`. Never contains the slide list.
|
||||
@@ -128,7 +195,7 @@ class PollStateService
|
||||
'isHidden' => $slide->is_hidden,
|
||||
'index' => null,
|
||||
'count' => null,
|
||||
'slide' => $this->slidePayload($slide),
|
||||
'slide' => $this->slidePayload($slide, $poll),
|
||||
'results' => $this->results->forSlide($slide),
|
||||
];
|
||||
}
|
||||
@@ -181,7 +248,7 @@ class PollStateService
|
||||
$words !== null || $qa !== null ? 0 : (int)$hasResponded,
|
||||
$slide?->modified?->toUnixString() ?? 0,
|
||||
]),
|
||||
'slide' => $showResults ? $this->slidePayload($slide) : null,
|
||||
'slide' => $showResults ? $this->slidePayload($slide, $poll) : null,
|
||||
'results' => $showResults ? $this->participantResults($slide) : null,
|
||||
'words' => $words,
|
||||
'quiz' => $quiz,
|
||||
@@ -371,9 +438,10 @@ class PollStateService
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param \App\Model\Entity\Poll $poll Poll of the slide (the image URL contains its join code)
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function slidePayload(Slide $slide): array
|
||||
public function slidePayload(Slide $slide, Poll $poll): array
|
||||
{
|
||||
return [
|
||||
'id' => $slide->id,
|
||||
@@ -388,6 +456,14 @@ class PollStateService
|
||||
'embedUrl' => $slide->youtubeEmbedUrl(),
|
||||
'watchUrl' => $slide->youtubeWatchUrl(),
|
||||
] : null,
|
||||
// Image of the slide: URL (random file name), alternative text ('' = decorative), layout (top|side|full)
|
||||
'image' => $slide->hasImage() ? [
|
||||
'url' => Router::url(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image]),
|
||||
'alt' => (string)$slide->image_alt,
|
||||
'layout' => $slide->imageLayout(),
|
||||
'width' => $slide->image_width,
|
||||
'height' => $slide->image_height,
|
||||
] : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,9 @@ use App\Model\Table\SlidesTable;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
|
||||
/**
|
||||
* Deletes responses of a slide or of the whole poll. Everything else (slides, settings,
|
||||
* the presentation's current slide) stays; only quiz and Q&A slides go back to their
|
||||
* start, since their phases make no sense without answers.
|
||||
* Deletes responses of a slide or of the whole poll. Everything else (slides, settings) stays;
|
||||
* every slide goes back to the state of a new one (Slide::startFresh()),
|
||||
* and resetting the poll puts the presentation back to "not started".
|
||||
* Idempotent: resetting twice gives the same result.
|
||||
*/
|
||||
class ResetService
|
||||
@@ -37,44 +37,53 @@ class ResetService
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all responses of a slide. A quiz goes back to "not started"
|
||||
* (so it can be played again), a Q&A slide back to collecting questions.
|
||||
* Deletes all responses of a slide and puts it back to the state of a new slide: a quiz is
|
||||
* "not started" (so it can be played again), a Q&A slide collects questions, all others are open.
|
||||
*
|
||||
* Questions the admin entered beforehand (Q&A) are kept unless $keepPrepared is false;
|
||||
* only the upvotes on them are removed.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param bool $keepPrepared Keep prepared Q&A questions
|
||||
* @return void
|
||||
*/
|
||||
public function slide(Slide $slide): void
|
||||
public function slide(Slide $slide, bool $keepPrepared = true): void
|
||||
{
|
||||
$this->Slides->getConnection()->transactional(function () use ($slide): void {
|
||||
$this->Responses->deleteAll(['slide_id' => $slide->id]);
|
||||
if ($slide->isQa()) {
|
||||
(new QaService())->reset($slide);
|
||||
|
||||
return;
|
||||
}
|
||||
if ($slide->isQuiz()) {
|
||||
$slide->is_voting_open = false;
|
||||
$slide->voting_started_at = null;
|
||||
$slide->voting_ends_at = null;
|
||||
$this->Slides->saveOrFail($slide);
|
||||
$this->Slides->getConnection()->transactional(function () use ($slide, $keepPrepared): void {
|
||||
$conditions = ['slide_id' => $slide->id];
|
||||
if ($keepPrepared) {
|
||||
$conditions['participant_hash !='] = VoteService::PREPARED_HASH;
|
||||
}
|
||||
$this->Responses->deleteAll($conditions);
|
||||
// Back to the state of a new slide: quiz ready, Q&A collecting, everything else open.
|
||||
$slide->startFresh();
|
||||
$this->Slides->saveOrFail($slide);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the responses of all slides of the poll (see slide()).
|
||||
* The presentation stays where it is.
|
||||
* Deletes the responses of all slides of the poll (see slide()) and puts the
|
||||
* presentation back to "not started" (no live and no paused slide). Idempotent.
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @param bool $keepPrepared Keep prepared Q&A questions
|
||||
* @return void
|
||||
*/
|
||||
public function poll(Poll $poll): void
|
||||
public function poll(Poll $poll, bool $keepPrepared = true): void
|
||||
{
|
||||
$this->Slides->getConnection()->transactional(function () use ($poll): void {
|
||||
$this->Slides->getConnection()->transactional(function () use ($poll, $keepPrepared): void {
|
||||
foreach ($this->Slides->find()->where(['poll_id' => $poll->id])->all() as $slide) {
|
||||
/** @var \App\Model\Entity\Slide $slide */
|
||||
$this->slide($slide);
|
||||
$this->slide($slide, $keepPrepared);
|
||||
}
|
||||
|
||||
if ($poll->current_slide_id === null && $poll->paused_slide_id === null) {
|
||||
return;
|
||||
}
|
||||
$poll->notStarted();
|
||||
/** @var \App\Model\Table\PollsTable $polls */
|
||||
$polls = $this->fetchTable('Polls');
|
||||
$polls->saveOrFail($poll);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,9 @@ use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
* rendered by webroot/js/plenario.js (presenter + participant views).
|
||||
*
|
||||
* Shape (always present): ['type' => string, 'participants' => int, ...]
|
||||
* - choice: 'options' => [['id', 'label', 'count', 'percent']]
|
||||
* - choice: 'options' => [['id', 'label', 'count', 'percent']], 'votes' (int),
|
||||
* 'comments' => [['id', 'text', 'value' (always null)]] oldest first (only with the comment
|
||||
* field, else []; presentation only, participants never get results of choice slides)
|
||||
* - wordcloud: 'words' => [['key' (lower case), 'text', 'count', 'down', 'weight' (0..1)]]
|
||||
* (count = participants who named or upvoted the word, down = downvotes,
|
||||
* weight follows count)
|
||||
@@ -78,7 +80,7 @@ class ResultsService
|
||||
];
|
||||
|
||||
return $result + match ($slide->type) {
|
||||
Slide::TYPE_CHOICE => $this->choice($slide),
|
||||
Slide::TYPE_CHOICE => $this->choice($slide, $limit),
|
||||
Slide::TYPE_WORDCLOUD => $this->wordcloud($slide),
|
||||
Slide::TYPE_OPEN => $this->open($slide, $limit),
|
||||
Slide::TYPE_SCALE => $this->scale($slide, $limit, $withRatings),
|
||||
@@ -141,9 +143,10 @@ class ResultsService
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param int|null $limit Max. comments (newest), null = all
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function choice(Slide $slide): array
|
||||
protected function choice(Slide $slide, ?int $limit = null): array
|
||||
{
|
||||
$counts = $this->Responses->find()
|
||||
->select(['slide_option_id', 'n' => $this->Responses->find()->func()->count('*')])
|
||||
@@ -166,7 +169,13 @@ class ResultsService
|
||||
];
|
||||
}
|
||||
|
||||
return ['options' => $options, 'votes' => $total];
|
||||
$comments = [];
|
||||
foreach ($slide->hasComments() ? $this->comments($slide, $limit) : [] as $comment) {
|
||||
// No option next to the comment: with several choices it would only be a guess anyway.
|
||||
$comments[] = ['id' => $comment['id'], 'text' => $comment['text'], 'value' => null];
|
||||
}
|
||||
|
||||
return ['options' => $options, 'votes' => $total, 'comments' => $comments];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -182,6 +191,12 @@ class ResultsService
|
||||
'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null,
|
||||
'revealed' => $phase === Slide::QUIZ_FINISHED,
|
||||
];
|
||||
if ($phase === Slide::QUIZ_READY) {
|
||||
// Answers are only shown once the quiz has been started.
|
||||
$result['options'] = [];
|
||||
|
||||
return $result;
|
||||
}
|
||||
if ($phase !== Slide::QUIZ_FINISHED) {
|
||||
$result['options'] = array_map(fn($option) => [
|
||||
'id' => $option->id,
|
||||
@@ -371,18 +386,21 @@ class ResultsService
|
||||
}
|
||||
|
||||
/**
|
||||
* Comments of a scale with their rating, oldest first; the unfiltered call
|
||||
* Comments of a scale with their rating (choice: without value), oldest first; the unfiltered call
|
||||
* (ratings regardless of comment_ratings) is only for the admin area.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Scale slide
|
||||
* @param \App\Model\Entity\Slide $slide Scale or choice slide
|
||||
* @param int|null $limit Max. comments (the newest ones), null = all
|
||||
* @return list<array{id: int, text: string, value: int, created: string}>
|
||||
* @return list<array{id: int, text: string, value: int|null, created: string}>
|
||||
*/
|
||||
public function comments(Slide $slide, ?int $limit = null): array
|
||||
{
|
||||
// Scale: the rating row carries the comment. Choice: the comment sits in the first of the
|
||||
// participant's rows, which always has an option.
|
||||
$answered = $slide->type === Slide::TYPE_CHOICE ? 'slide_option_id IS NOT' : 'numeric_value IS NOT';
|
||||
$query = $this->Responses->find()
|
||||
->select(['id', 'text_value', 'numeric_value', 'created'])
|
||||
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null, 'numeric_value IS NOT' => null])
|
||||
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null, $answered => null])
|
||||
->orderBy(['id' => 'DESC']);
|
||||
if ($limit !== null) {
|
||||
$query->limit($limit);
|
||||
@@ -393,7 +411,7 @@ class ResultsService
|
||||
$comments[] = [
|
||||
'id' => (int)$row->id,
|
||||
'text' => (string)$row->text_value,
|
||||
'value' => (int)$row->numeric_value,
|
||||
'value' => $row->numeric_value === null ? null : (int)$row->numeric_value,
|
||||
'created' => $row->created->toIso8601String(),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -136,20 +136,20 @@ class VoteService
|
||||
|
||||
/**
|
||||
* Whether the participant may change the text of their answer afterwards (e.g. to fix a typo):
|
||||
* the answer of an open question and the comment of a scale with comment field.
|
||||
* the answer of an open question and the comment of a choice or scale slide with comment field.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @return bool
|
||||
*/
|
||||
public static function hasEditableText(Slide $slide): bool
|
||||
{
|
||||
return $slide->type === Slide::TYPE_OPEN || ($slide->type === Slide::TYPE_SCALE && $slide->hasComments());
|
||||
return $slide->type === Slide::TYPE_OPEN || $slide->hasComments();
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the text of the participant's own answer as long as voting on the slide is open
|
||||
* (see hasEditableText()). Open question: `text`, must not be empty. Scale: `comment`, the
|
||||
* rating itself stays unchanged and an empty comment removes it. Same preconditions as submit().
|
||||
* (see hasEditableText()). Open question: `text`, must not be empty. Choice/scale: `comment`, the
|
||||
* selection or rating itself stays unchanged and an empty comment removes it. Same preconditions as submit().
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
@@ -167,13 +167,17 @@ class VoteService
|
||||
$text = $slide->type === Slide::TYPE_OPEN ? $this->openRows($data)[0]['text_value'] : self::comment($data);
|
||||
$this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $text): void {
|
||||
$this->lockSlide($slide);
|
||||
// A multiple choice answer has several rows; the comment always lives in the first one.
|
||||
$row = $this->Responses->find()
|
||||
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
|
||||
->orderBy(['id' => 'ASC'])
|
||||
->first();
|
||||
if ($row === null) {
|
||||
throw new VoteException($slide->type === Slide::TYPE_OPEN
|
||||
? __('Du hast hier noch nicht geantwortet.')
|
||||
: __('Bitte gib zuerst deine Bewertung ab.'));
|
||||
throw new VoteException(match ($slide->type) {
|
||||
Slide::TYPE_OPEN => __('Du hast hier noch nicht geantwortet.'),
|
||||
Slide::TYPE_CHOICE => __('Bitte gib zuerst deine Auswahl ab.'),
|
||||
default => __('Bitte gib zuerst deine Bewertung ab.'),
|
||||
});
|
||||
}
|
||||
$row->text_value = $text;
|
||||
$this->Responses->saveOrFail($row);
|
||||
@@ -181,7 +185,7 @@ class VoteService
|
||||
}
|
||||
|
||||
/**
|
||||
* Text of the participant's own answer: open answer or scale comment (null: none or not answered yet).
|
||||
* Text of the participant's own answer: open answer or choice/scale comment (null: none or not answered yet).
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param string $participantHash Participant hash
|
||||
@@ -192,6 +196,7 @@ class VoteService
|
||||
$row = $this->Responses->find()
|
||||
->select(['text_value'])
|
||||
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash])
|
||||
->orderBy(['id' => 'ASC'])
|
||||
->disableHydration()
|
||||
->first();
|
||||
|
||||
@@ -281,7 +286,15 @@ class VoteService
|
||||
throw new VoteException(__('Bitte wähle nur eine Antwort aus.'));
|
||||
}
|
||||
|
||||
return array_map(fn(int $id) => ['slide_option_id' => $id], $selected);
|
||||
// The optional comment goes into the first row only, so it is stored once per participant;
|
||||
// counts group by option and ignore text_value.
|
||||
$comment = $slide->hasComments() ? self::comment($data) : null;
|
||||
|
||||
return array_map(
|
||||
fn(int $id, int $index) => ['slide_option_id' => $id, 'text_value' => $index === 0 ? $comment : null],
|
||||
$selected,
|
||||
array_keys($selected),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -103,6 +103,18 @@ $bar = function (float $percent, bool $ok = false): string {
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php if ($slide->hasComments()) : ?>
|
||||
<h3><?= __n('{0} Kommentar', '{0} Kommentare', count($r['comments']), count($r['comments'])) ?></h3>
|
||||
<?php if ($r['comments'] === []) : ?>
|
||||
<p class="empty"><?= __('Keine Kommentare.') ?></p>
|
||||
<?php else : ?>
|
||||
<ol class="list">
|
||||
<?php foreach ($r['comments'] as $comment) : ?>
|
||||
<li><?= nl2br(h($comment['text'])) ?></li>
|
||||
<?php endforeach; ?>
|
||||
</ol>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php elseif ($slide->type === 'quiz') : ?>
|
||||
<?php if (!$r['revealed']) : ?>
|
||||
|
||||
+90
-52
@@ -11,6 +11,7 @@
|
||||
* @var array<string, string> $typeDescriptions
|
||||
* @var string $joinUrl
|
||||
* @var string $embedKey
|
||||
* @var int $pollIntervalMs
|
||||
*/
|
||||
$this->assign('title', $poll->title);
|
||||
$this->assign('noindex', '1');
|
||||
@@ -34,8 +35,20 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
</p>
|
||||
</div>
|
||||
<div class="admin-head__actions">
|
||||
<a class="button button--primary" target="_blank" rel="noopener"
|
||||
href="<?= $this->Url->build($url('admin:present')) ?>">▶ <?= __('Präsentieren') ?></a>
|
||||
<div class="split">
|
||||
<a class="button button--primary split__main" target="_blank" rel="noopener"
|
||||
href="<?= $this->Url->build($url('admin:present')) ?>">▶ <?= __('Präsentieren') ?></a>
|
||||
<button type="button" class="button button--primary split__toggle" data-menu-toggle aria-haspopup="true" aria-expanded="false"
|
||||
aria-controls="present-menu" title="<?= h(__('Weitere Ansichten')) ?>">
|
||||
<span aria-hidden="true">▾</span><span class="sr-only"><?= __('Weitere Ansichten') ?></span>
|
||||
</button>
|
||||
<div class="split__menu" id="present-menu" data-menu hidden>
|
||||
<a class="split__item" target="_blank" rel="noopener" href="<?= $this->Url->build($url('admin:speaker')) ?>">
|
||||
⧉ <?= __('Referentenansicht') ?>
|
||||
<small><?= __('Aktuelle und nächste Folie im eigenen Fenster, startet die Präsentation nicht') ?></small>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<?php if ($poll->current_slide_id !== null) : ?>
|
||||
<?= $this->Form->postButton('⏸ ' . __('Pause'), $url('admin:control'), [
|
||||
'data' => ['action' => 'stop'],
|
||||
@@ -52,7 +65,9 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
<?= __('Diese URL ist dein Zugang zur Umfrage. Wer sie kennt, kann alles bearbeiten.') ?>
|
||||
</div>
|
||||
|
||||
<div class="grid grid--sidebar">
|
||||
<div class="grid grid--sidebar"
|
||||
data-dashboard-live="<?= $this->Url->build($url('admin:live')) ?>"
|
||||
data-interval="<?= (int)$pollIntervalMs ?>">
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<h2><?= __('Folien') ?></h2>
|
||||
@@ -84,6 +99,7 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
<div class="slide-item__meta">
|
||||
<span class="badge badge--type-<?= h($slide->type) ?>"><?= h($slide->typeLabel()) ?></span>
|
||||
<?php if ($isCurrent) : ?><span class="badge badge--live"><?= __('live') ?></span><?php endif; ?>
|
||||
<?php if ($slide->hasImage()) : ?><span class="badge" title="<?= h(__('Die Folie hat ein Bild')) ?>">🖼 <?= __('Bild') ?></span><?php endif; ?>
|
||||
<?php if ($slide->is_hidden) : ?><span class="badge badge--off" title="<?= __('Wird beim Präsentieren übersprungen und fehlt im PDF-Export') ?>"><?= __('ausgeblendet') ?></span><?php endif; ?>
|
||||
<?php if ($slide->isInteractive()) : ?>
|
||||
<span class="muted"><?= __n('{0} Antwort', '{0} Antworten', $count, $count) ?></span>
|
||||
@@ -143,7 +159,11 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
<?php if (($slide->type === 'open' || $slide->isPrivate() || $slide->hasComments()) && $count > 0) :
|
||||
$answersLabel = $slide->type === 'scale' ? __('Auswertung') : __('Antworten'); ?>
|
||||
$answersLabel = match ($slide->type) {
|
||||
'scale' => __('Auswertung'),
|
||||
'choice' => __('Kommentare'),
|
||||
default => __('Antworten'),
|
||||
}; ?>
|
||||
<a class="button button--small button--icon" href="<?= $this->Url->build($url('slides:answers', ['id' => $slide->id])) ?>"
|
||||
title="<?= h($answersLabel) ?>" aria-label="<?= h(__('{0} der Folie „{1}“ ansehen', $answersLabel, $slide->question)) ?>">📊</a>
|
||||
<?php endif; ?>
|
||||
@@ -170,12 +190,14 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
'data-confirm' => $isCurrent ? __('Diese Folie ist gerade live. Ausblenden und die Umfrage pausieren?') : null,
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
<?php if ($count > 0) : ?>
|
||||
<?php if ($count > 0 || !$slide->isFresh()) : ?>
|
||||
<?= $this->Form->postButton('↺', $url('slides:reset', ['id' => $slide->id]), [
|
||||
'class' => 'button button--small button--icon',
|
||||
'title' => __('Zurücksetzen: alle Antworten dieser Folie löschen'),
|
||||
'aria-label' => __('Antworten der Folie „{0}“ zurücksetzen', $slide->question),
|
||||
'data-confirm' => __('Alle {0} Antworten dieser Folie löschen?', $count),
|
||||
'title' => __('Zurücksetzen: Antworten löschen und Folie wie neu starten'),
|
||||
'aria-label' => __('Folie „{0}“ zurücksetzen', $slide->question),
|
||||
'data-confirm' => $count > 0
|
||||
? __('Alle {0} Antworten dieser Folie löschen und die Folie zurücksetzen?', $count)
|
||||
: __('Folie zurücksetzen?'),
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
<?= $this->Form->postButton('🗑', $url('slides:delete', ['id' => $slide->id]), [
|
||||
@@ -203,18 +225,44 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
</section>
|
||||
|
||||
<aside class="sidebar">
|
||||
<section class="card">
|
||||
<h2><?= __('Teilnahme') ?></h2>
|
||||
<details class="card collapsible" open>
|
||||
<summary><h2><?= __('Teilnahme') ?></h2></summary>
|
||||
<p class="join-code"><?= h($poll->formattedJoinCode()) ?></p>
|
||||
<img class="qr" src="<?= $this->Url->build($url('admin:qr')) ?>" alt="<?= __('QR-Code zur Teilnahme') ?>" width="160" height="160">
|
||||
<div class="copy-field">
|
||||
<input type="text" readonly value="<?= h($joinUrl) ?>" aria-label="<?= __('Teilnahme-Link') ?>" data-copy-source>
|
||||
<button type="button" class="button button--small" data-copy><?= __('Kopieren') ?></button>
|
||||
</div>
|
||||
</section>
|
||||
</details>
|
||||
|
||||
<section class="card" id="export">
|
||||
<h2><?= __('Ergebnisse als PDF') ?></h2>
|
||||
<details class="card collapsible" open>
|
||||
<summary><h2><?= __('Einstellungen') ?></h2></summary>
|
||||
<?= $this->Form->create($poll, ['url' => $url('admin:settings'), 'type' => 'post']) ?>
|
||||
<?= $this->Form->control('title', ['label' => __('Titel'), 'maxlength' => 200]) ?>
|
||||
<?= $this->Form->control('is_active', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Umfrage ist aktiv (Teilnehmende können abstimmen)'),
|
||||
]) ?>
|
||||
<?= $this->Form->control('comment_speed', [
|
||||
'type' => 'select',
|
||||
'label' => __('Tempo der Kommentare in der Präsentation'),
|
||||
'options' => [
|
||||
50 => __('Viel langsamer (doppelt so lange)'),
|
||||
75 => __('Langsamer'),
|
||||
100 => __('Normal'),
|
||||
125 => __('Schneller'),
|
||||
150 => __('Deutlich schneller'),
|
||||
200 => __('Sehr schnell (halb so lange)'),
|
||||
],
|
||||
'aria-describedby' => 'comment-speed-hint',
|
||||
]) ?>
|
||||
<p class="hint" id="comment-speed-hint"><?= __('Gilt für die Kommentare von Skala-Folien, die nacheinander durchlaufen. Die Anzeigedauer richtet sich weiter nach der Textlänge und wird mit diesem Faktor verkürzt oder verlängert.') ?></p>
|
||||
<?= $this->Form->button(__('Speichern'), ['class' => 'button']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</details>
|
||||
|
||||
<details class="card collapsible" id="export">
|
||||
<summary><h2><?= __('Ergebnisse als PDF') ?></h2></summary>
|
||||
<p class="hint"><?= __('Alle Folien mit Abstimmung und ihre Ergebnisse in einem Dokument, z. B. fürs Protokoll.') ?></p>
|
||||
<?= $this->Form->create(null, ['url' => $url('admin:export'), 'type' => 'get']) ?>
|
||||
<?php if ($hasInternal) : ?>
|
||||
@@ -238,10 +286,10 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
<?php endif; ?>
|
||||
<?= $this->Form->button(__('PDF herunterladen'), ['class' => 'button']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
</details>
|
||||
|
||||
<section class="card" id="embed">
|
||||
<h2><?= __('In Präsentation einbetten') ?></h2>
|
||||
<details class="card collapsible" id="embed">
|
||||
<summary><h2><?= __('In Präsentation einbetten') ?></h2></summary>
|
||||
<p class="hint"><?= __('Jede Folie hat einen eigenen Einbett-Link (unter „Einbett-Link“ in der Folienliste). Füge ihn z. B. in Canva als Einbettung auf einer Folie ein.') ?></p>
|
||||
<p class="hint"><?= __('Sobald die eingebettete Folie im Vortrag zu sehen ist, wird sie live geschaltet. Bei allen anderen Folien sehen Teilnehmende eine Pause-Seite.') ?></p>
|
||||
<p class="hint"><?= __('Der Link zeigt nur diese Folie und kann sie live schalten – die Umfrage bearbeiten kann damit niemand.') ?></p>
|
||||
@@ -249,36 +297,13 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
'class' => 'button button--small',
|
||||
'data-confirm' => __('Neue Einbett-Links erzeugen? Alle bisher eingebetteten Folien funktionieren danach nicht mehr.'),
|
||||
]) ?>
|
||||
</section>
|
||||
</details>
|
||||
|
||||
<section class="card">
|
||||
<h2><?= __('Einstellungen') ?></h2>
|
||||
<?= $this->Form->create($poll, ['url' => $url('admin:settings'), 'type' => 'post']) ?>
|
||||
<?= $this->Form->control('title', ['label' => __('Titel'), 'maxlength' => 200]) ?>
|
||||
<?= $this->Form->control('is_active', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Umfrage ist aktiv (Teilnehmende können abstimmen)'),
|
||||
]) ?>
|
||||
<?= $this->Form->control('comment_speed', [
|
||||
'type' => 'select',
|
||||
'label' => __('Tempo der Kommentare in der Präsentation'),
|
||||
'options' => [
|
||||
50 => __('Viel langsamer (doppelt so lange)'),
|
||||
75 => __('Langsamer'),
|
||||
100 => __('Normal'),
|
||||
125 => __('Schneller'),
|
||||
150 => __('Deutlich schneller'),
|
||||
200 => __('Sehr schnell (halb so lange)'),
|
||||
],
|
||||
'aria-describedby' => 'comment-speed-hint',
|
||||
]) ?>
|
||||
<p class="hint" id="comment-speed-hint"><?= __('Gilt für die Kommentare von Skala-Folien, die nacheinander durchlaufen. Die Anzeigedauer richtet sich weiter nach der Textlänge und wird mit diesem Faktor verkürzt oder verlängert.') ?></p>
|
||||
<?= $this->Form->button(__('Speichern'), ['class' => 'button']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
|
||||
<section class="card card--danger">
|
||||
<h2><?= __('Sicherheit') ?></h2>
|
||||
<details class="card card--danger collapsible">
|
||||
<summary><h2><?= __('Sicherheit') ?></h2></summary>
|
||||
<?php if ($poll->expiresAt() !== null) : ?>
|
||||
<p class="hint"><?= __('Diese Umfrage wird am {0} automatisch gelöscht. Sichere die Ergebnisse vorher als PDF.', h($poll->expiresAt()->i18nFormat('dd.MM.yyyy'))) ?></p>
|
||||
<?php endif; ?>
|
||||
<p class="hint"><?= __('Link versehentlich geteilt? Erzeuge einen neuen – der alte wird sofort ungültig.') ?></p>
|
||||
<?= $this->Form->postButton(__('Neuen Admin-Link erzeugen'), $url('admin:rotate'), [
|
||||
'class' => 'button button--small',
|
||||
@@ -286,15 +311,28 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
]) ?>
|
||||
|
||||
<h3><?= __('Umfrage zurücksetzen') ?></h3>
|
||||
<p class="hint"><?= __('Löscht alle Antworten aller Folien, z. B. für eine neue Gruppe. Folien und Einstellungen bleiben erhalten.') ?></p>
|
||||
<?php if ($responseCounts !== []) : ?>
|
||||
<p class="hint"><?= $this->Html->link(__('Ergebnisse vorher als PDF sichern'), '#export') ?></p>
|
||||
<?= $this->Form->postButton(__('Alle Antworten löschen'), $url('admin:reset'), [
|
||||
<p class="hint"><?= __('Löscht alle Antworten aller Folien und setzt die Präsentation auf „nicht gestartet“ zurück, z. B. für eine neue Gruppe. Folien und Einstellungen bleiben erhalten.') ?></p>
|
||||
<?php if ($canReset) : ?>
|
||||
<?php if ($responseCounts !== []) : ?>
|
||||
<p class="hint"><?= $this->Html->link(__('Ergebnisse vorher als PDF sichern'), '#export') ?></p>
|
||||
<?php endif; ?>
|
||||
<?= $this->Form->create(null, ['url' => $url('admin:reset')]) ?>
|
||||
<?php if ($hasPrepared) : ?>
|
||||
<?= $this->Form->control('keep_prepared', [
|
||||
'type' => 'checkbox',
|
||||
'checked' => true,
|
||||
'label' => __('Vorab eingetragene Fragen (Fragen & Antworten) behalten'),
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
<?= $this->Form->button(__('Umfrage zurücksetzen'), [
|
||||
'class' => 'button button--small button--danger',
|
||||
'data-confirm' => __('Alle Antworten aller Folien unwiderruflich löschen?'),
|
||||
'data-confirm' => $responseCounts !== []
|
||||
? __('Umfrage zurücksetzen? Alle Antworten aller Folien werden unwiderruflich gelöscht und die Präsentation wird auf „nicht gestartet“ gestellt.')
|
||||
: __('Alle Folien zurücksetzen und die Präsentation auf „nicht gestartet“ stellen?'),
|
||||
]) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
<?php else : ?>
|
||||
<p class="hint"><em><?= __('Noch nichts zurückzusetzen: Es gibt keine Antworten.') ?></em></p>
|
||||
<p class="hint"><em><?= __('Noch nichts zurückzusetzen: keine Antworten, alle Folien im Ausgangszustand, Präsentation nicht gestartet.') ?></em></p>
|
||||
<?php endif; ?>
|
||||
|
||||
<h3><?= __('Umfrage löschen') ?></h3>
|
||||
@@ -306,7 +344,7 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
]) ?>
|
||||
<?= $this->Form->button(__('Endgültig löschen'), ['class' => 'button button--danger']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
</details>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* (Plenario.presenter) from /admin/{token}/state.
|
||||
*
|
||||
* Keyboard: ←/→ slides, P pause/resume (→ resumes too), V voting on/off, H hide results, F fullscreen, Q QR code, T light/dark.
|
||||
* The speaker view (admin:speaker) is this page plus a preview of the next slide, meant for the presenter's own screen.
|
||||
* Q&A slides: V switches to the next stage; while discussing ←/→ step through the questions first.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
@@ -12,11 +13,13 @@
|
||||
* @var string $joinUrl
|
||||
* @var string $joinBaseUrl
|
||||
* @var int $pollIntervalMs
|
||||
* @var bool|null $speaker Speaker view (second window): adds the preview of the next slide
|
||||
*/
|
||||
$speaker = $speaker ?? false;
|
||||
$this->assign('title', $poll->title);
|
||||
$host = preg_replace('#^https?://#', '', $joinBaseUrl);
|
||||
?>
|
||||
<div class="stage"
|
||||
<div class="stage<?= $speaker ? ' stage--speaker' : '' ?>"
|
||||
data-presenter
|
||||
data-state-url="<?= $this->Url->build(['_name' => 'admin:state', 'token' => $adminToken]) ?>"
|
||||
data-control-url="<?= $this->Url->build(['_name' => 'admin:control', 'token' => $adminToken]) ?>"
|
||||
@@ -34,15 +37,35 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);
|
||||
</header>
|
||||
|
||||
<main class="stage__main">
|
||||
<?php if ($speaker) : ?>
|
||||
<p class="stage__label"><?= __('Aktuelle Folie') ?></p>
|
||||
<?php endif; ?>
|
||||
<p class="stage__status" data-status></p>
|
||||
<h1 class="stage__question" data-question><?= __('Lade …') ?></h1>
|
||||
<div class="stage__description formatted" data-description></div>
|
||||
<div class="stage__media" data-media hidden></div>
|
||||
<figure class="stage__image" data-image hidden></figure>
|
||||
<div class="stage__results" data-results></div>
|
||||
</main>
|
||||
|
||||
<?php if ($speaker) : ?>
|
||||
<aside class="stage__next" data-next aria-label="<?= h(__('Nächste Folie')) ?>">
|
||||
<p class="stage__label stage__next-label"><?= __('Als Nächstes') ?> <span data-next-meta></span></p>
|
||||
<h2 class="stage__next-question" data-next-question></h2>
|
||||
<div class="stage__next-description formatted" data-next-description></div>
|
||||
<ul class="stage__next-options" data-next-options></ul>
|
||||
<p class="stage__next-note muted" data-next-note></p>
|
||||
</aside>
|
||||
<?php endif; ?>
|
||||
|
||||
<footer class="stage__controls">
|
||||
<a class="ctrl" href="<?= $this->Url->build(['_name' => 'admin', 'token' => $adminToken]) ?>" title="<?= __('Zur Verwaltung') ?>">✎</a>
|
||||
<?php if (!$speaker) : ?>
|
||||
<a class="ctrl" href="<?= $this->Url->build(['_name' => 'admin:speaker', 'token' => $adminToken]) ?>" target="_blank" rel="noopener"
|
||||
title="<?= __('Referentenansicht in neuem Fenster öffnen (mit Vorschau der nächsten Folie)') ?>">
|
||||
<span aria-hidden="true">⧉</span><span class="sr-only"><?= __('Referentenansicht öffnen') ?></span>
|
||||
</a>
|
||||
<?php endif; ?>
|
||||
<button type="button" class="ctrl" data-action="prev" aria-keyshortcuts="ArrowLeft PageUp" title="<?= __('Vorherige Folie (←)') ?>">
|
||||
<span aria-hidden="true">←</span><span class="sr-only"><?= __('Vorherige Folie') ?></span>
|
||||
</button>
|
||||
|
||||
@@ -42,6 +42,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);
|
||||
<h1 class="stage__question" data-question><?= h($slide->question) ?></h1>
|
||||
<div class="stage__description formatted" data-description></div>
|
||||
<div class="stage__media" data-media hidden></div>
|
||||
<figure class="stage__image" data-image hidden></figure>
|
||||
<div class="stage__results" data-results></div>
|
||||
</main>
|
||||
|
||||
|
||||
@@ -110,6 +110,7 @@ $countdown = function (?int $remaining): string {
|
||||
<?php if ($slide->description) : ?>
|
||||
<div class="prose formatted"><?= $this->Format->text($slide->description) ?></div>
|
||||
<?php endif; ?>
|
||||
<?= $this->element('slide_image', compact('slide', 'poll')) ?>
|
||||
</section>
|
||||
|
||||
<?php else : ?>
|
||||
@@ -118,6 +119,7 @@ $countdown = function (?int $remaining): string {
|
||||
<?php if ($slide->description) : ?>
|
||||
<div class="muted formatted"><?= $this->Format->text($slide->description) ?></div>
|
||||
<?php endif; ?>
|
||||
<?= $this->element('slide_image', compact('slide', 'poll')) ?>
|
||||
|
||||
<?php if ($quiz !== null) : ?>
|
||||
<?php if ($quiz['phase'] === 'ready') : ?>
|
||||
@@ -266,7 +268,9 @@ $countdown = function (?int $remaining): string {
|
||||
aria-describedby="edit-text-hint"><?= h((string)$ownText) ?></textarea>
|
||||
<p class="hint" id="edit-text-hint"><?= $isOpen
|
||||
? __('Möglich, solange die Abstimmung läuft.')
|
||||
: __('Möglich, solange die Abstimmung läuft. Ein leeres Feld entfernt deinen Kommentar, deine Bewertung bleibt.') ?></p>
|
||||
: ($slide->type === 'choice'
|
||||
? __('Möglich, solange die Abstimmung läuft. Ein leeres Feld entfernt deinen Kommentar, deine Auswahl bleibt.')
|
||||
: __('Möglich, solange die Abstimmung läuft. Ein leeres Feld entfernt deinen Kommentar, deine Bewertung bleibt.')) ?></p>
|
||||
<?= $this->Form->button($isOpen ? __('Antwort speichern') : __('Kommentar speichern'), ['class' => 'button button--primary button--block']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</details>
|
||||
@@ -290,6 +294,11 @@ $countdown = function (?int $remaining): string {
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php if ($slide->hasComments()) : ?>
|
||||
<label class="scale-comment" for="choice-comment"><?= __('Kommentar (optional)') ?></label>
|
||||
<textarea id="choice-comment" name="comment" rows="3" maxlength="500"
|
||||
placeholder="<?= __('Möchtest du deine Auswahl begründen?') ?>"></textarea>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php elseif ($slide->type === 'open') : ?>
|
||||
<textarea name="text" rows="4" maxlength="500" required
|
||||
|
||||
@@ -9,13 +9,18 @@
|
||||
* @var \App\Model\Entity\Slide $slide
|
||||
* @var list<array{text: string, created: string}> $answers
|
||||
* @var array<string, mixed>|null $scale Distribution of a scale slide, null for open questions
|
||||
* @var list<array{id: int, text: string, value: int, created: string}> $comments Comments of a scale, oldest first
|
||||
* @var list<array{id: int, text: string, value: int|null, created: string}> $comments Comments of a scale or choice slide, oldest first
|
||||
*/
|
||||
use Cake\I18n\DateTime;
|
||||
|
||||
$this->assign('title', $slide->question);
|
||||
$this->assign('noindex', '1');
|
||||
$count = $scale !== null ? array_sum(array_column($scale['buckets'], 'count')) : count($answers);
|
||||
$isChoice = $slide->type === 'choice';
|
||||
$count = match (true) {
|
||||
$scale !== null => array_sum(array_column($scale['buckets'], 'count')),
|
||||
$isChoice => count($comments),
|
||||
default => count($answers),
|
||||
};
|
||||
?>
|
||||
<p><a href="<?= $this->Url->build(['_name' => 'admin', 'token' => $adminToken]) ?>">← <?= __('Zurück zur Verwaltung') ?></a></p>
|
||||
|
||||
@@ -27,6 +32,8 @@ $count = $scale !== null ? array_sum(array_column($scale['buckets'], 'count')) :
|
||||
<h1><?= h($slide->question) ?></h1>
|
||||
<?php if ($scale !== null) : ?>
|
||||
<p class="muted"><?= __n('{0} Bewertung', '{0} Bewertungen', $count, $count) ?></p>
|
||||
<?php elseif ($isChoice) : ?>
|
||||
<p class="muted"><?= __n('{0} Kommentar, neueste zuerst', '{0} Kommentare, neueste zuerst', $count, $count) ?></p>
|
||||
<?php else : ?>
|
||||
<p class="muted"><?= __n('{0} Antwort, neueste zuerst', '{0} Antworten, neueste zuerst', $count, $count) ?></p>
|
||||
<?php endif; ?>
|
||||
@@ -85,6 +92,20 @@ $count = $scale !== null ? array_sum(array_column($scale['buckets'], 'count')) :
|
||||
</ol>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
<?php elseif ($isChoice) : ?>
|
||||
<?php if ($comments === []) : ?>
|
||||
<p class="empty"><?= __('Noch keine Kommentare.') ?></p>
|
||||
<?php else : ?>
|
||||
<ol class="answers-page" reversed>
|
||||
<?php foreach (array_reverse($comments) as $comment) :
|
||||
$created = new DateTime($comment['created']); ?>
|
||||
<li>
|
||||
<?= h($comment['text']) ?>
|
||||
<time datetime="<?= h($comment['created']) ?>"><?= h($created->i18nFormat('dd.MM.yyyy, HH:mm')) ?></time>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ol>
|
||||
<?php endif; ?>
|
||||
<?php elseif ($answers === []) : ?>
|
||||
<p class="empty"><?= __('Noch keine Antworten.') ?></p>
|
||||
<?php else : ?>
|
||||
|
||||
@@ -31,7 +31,7 @@ $optionsError = $slide->getError('options_text');
|
||||
<p class="eyebrow"><?= h($slide->typeLabel()) ?></p>
|
||||
<h1 id="modal-title"><?= $isNew ? __('Neue Folie') : __('Folie bearbeiten') ?></h1>
|
||||
|
||||
<?= $this->Form->create($slide, ['url' => $formUrl]) ?>
|
||||
<?= $this->Form->create($slide, ['url' => $formUrl, 'type' => 'file']) ?>
|
||||
<?= $this->Form->hidden('type') ?>
|
||||
<?php if ($slide->isYouTube()) :
|
||||
$urlError = $slide->getError('youtube_url');
|
||||
@@ -116,6 +116,8 @@ $optionsError = $slide->getError('options_text');
|
||||
]) ?>
|
||||
<p class="hint" id="description-format"><?= __('Formatierung wie bei WhatsApp: *fett*, _kursiv_, ~durchgestrichen~, Aufzählung mit „- “ am Zeilenanfang.') ?></p>
|
||||
|
||||
<?= $this->element('slide_image_fields', compact('slide', 'poll')) ?>
|
||||
|
||||
<?php if ($slide->type === 'choice') : ?>
|
||||
<div class="input textarea<?= $optionsError ? ' error' : '' ?>">
|
||||
<label for="options-text"><?= __('Antwortoptionen (eine pro Zeile, max. 20)') ?></label>
|
||||
@@ -132,6 +134,12 @@ $optionsError = $slide->getError('options_text');
|
||||
'label' => __('Mehrfachauswahl erlauben'),
|
||||
'checked' => (bool)$settings['multiple'],
|
||||
]) ?>
|
||||
<?= $this->Form->control('settings.comments', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Kommentarfeld anzeigen (Teilnehmende können ihre Auswahl optional begründen)'),
|
||||
'checked' => (bool)$settings['comments'],
|
||||
]) ?>
|
||||
<p class="hint"><?= __('Die Kommentare laufen in der Präsentation nacheinander unter dem Ergebnis durch (nicht bei den Teilnehmenden). Das Tempo stellst du für die ganze Umfrage in den Einstellungen im Dashboard ein.') ?></p>
|
||||
<?php elseif ($slide->type === 'open') : ?>
|
||||
<?= $this->Form->control('settings.private', [
|
||||
'type' => 'checkbox',
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
/**
|
||||
* Favicon links shared by all layouts. The SVG is the logo (same shape as .brand__mark in plenario.css) and wins
|
||||
* wherever it is supported; favicon.ico is the fallback, apple-touch-icon.png is the iOS home screen icon.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
$asset = fn(string $file): string => $this->Url->assetUrl($file, ['pathPrefix' => '']);
|
||||
?>
|
||||
<link rel="icon" href="<?= h($asset('favicon.ico')) ?>" sizes="32x32">
|
||||
<link rel="icon" href="<?= h($asset('favicon.svg')) ?>" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="<?= h($asset('apple-touch-icon.png')) ?>">
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/**
|
||||
* The image of a slide on the participant's page (always above the content, whatever the stage layout).
|
||||
* Width and height reserve the space, so the page does not jump while the image loads.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Slide $slide
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
*/
|
||||
if (!$slide->hasImage()) {
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<figure class="slide-image">
|
||||
<img src="<?= h($this->Url->build(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image])) ?>"
|
||||
alt="<?= h((string)$slide->image_alt) ?>"
|
||||
<?= $slide->image_width && $slide->image_height ? 'width="' . (int)$slide->image_width . '" height="' . (int)$slide->image_height . '"' : '' ?>
|
||||
decoding="async">
|
||||
</figure>
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
/**
|
||||
* Image fields of the slide form: upload, alternative text, layout, remove.
|
||||
* Not for slide types without image support (YouTube).
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Slide $slide
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
*/
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Service\ImageService;
|
||||
use Cake\Core\Configure;
|
||||
|
||||
if (!Slide::supportsImage($slide->type)) {
|
||||
return;
|
||||
}
|
||||
$request = $this->getRequest();
|
||||
$posted = $request->is(['post', 'put', 'patch']);
|
||||
$hasImage = $slide->hasImage();
|
||||
// After a failed save the posted values are shown again.
|
||||
$layout = $posted && in_array($request->getData('image_layout'), Slide::IMAGE_LAYOUTS, true)
|
||||
? (string)$request->getData('image_layout')
|
||||
: $slide->imageLayout();
|
||||
$layouts = [
|
||||
Slide::IMAGE_TOP => __('Oben (über den Antworten bzw. Ergebnissen)'),
|
||||
Slide::IMAGE_SIDE => __('Daneben (Bild links, Text und Ergebnis rechts)'),
|
||||
];
|
||||
if ($slide->type === Slide::TYPE_CONTENT) {
|
||||
$layouts[Slide::IMAGE_FULL] = __('Bildschirm füllen (Bild so groß wie möglich)');
|
||||
}
|
||||
$imageError = $slide->getError('image');
|
||||
$maxMb = (int)round((int)Configure::read('Plenario.images.maxUploadBytes', 10 * 1024 * 1024) / 1024 / 1024);
|
||||
?>
|
||||
<fieldset class="image-fields" data-image-fields>
|
||||
<legend><?= __('Bild (optional)') ?></legend>
|
||||
<?php if (!ImageService::isAvailable()) : ?>
|
||||
<p class="hint"><?= __('Bilder sind auf diesem Server nicht verfügbar (PHP-Erweiterung GD mit WebP fehlt).') ?></p>
|
||||
<?php else : ?>
|
||||
<?php if ($hasImage) : ?>
|
||||
<figure class="image-fields__current">
|
||||
<img src="<?= h($this->Url->build(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image])) ?>"
|
||||
alt="<?= h((string)$slide->image_alt) ?>" width="<?= (int)$slide->image_width ?>" height="<?= (int)$slide->image_height ?>">
|
||||
</figure>
|
||||
<?php // Without JavaScript the checkbox does the job; with it, the button toggles the same checkbox. ?>
|
||||
<div class="image-fields__remove" data-image-remove>
|
||||
<?= $this->Form->control('remove_image', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Bild entfernen'),
|
||||
'value' => '1',
|
||||
'hiddenField' => false,
|
||||
'checked' => false,
|
||||
]) ?>
|
||||
<button type="button" class="button button--danger button--small" hidden aria-pressed="false" data-image-remove-button
|
||||
data-label-remove="<?= h(__('Bild entfernen')) ?>" data-label-undo="<?= h(__('Entfernen rückgängig machen')) ?>">
|
||||
<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14M10 11v5M14 11v5"/>
|
||||
</svg>
|
||||
<span data-label><?= __('Bild entfernen') ?></span>
|
||||
</button>
|
||||
<span class="hint" role="status" aria-live="polite" data-image-remove-status></span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div class="input file<?= $imageError ? ' error' : '' ?>">
|
||||
<label for="image-file"><?= $hasImage ? __('Anderes Bild hochladen') : __('Bild hochladen') ?></label>
|
||||
<input type="file" id="image-file" name="image" accept="image/jpeg,image/png,image/webp,image/gif"
|
||||
aria-describedby="image-hint<?= $imageError ? ' image-error' : '' ?>" <?= $imageError ? 'aria-invalid="true"' : '' ?>>
|
||||
<p class="hint" id="image-hint"><?= __('JPEG, PNG, WebP oder GIF (nicht animiert), bis {0} MB. Das Bild wird automatisch auf höchstens 1600 Pixel verkleinert und als WebP gespeichert, Kameradaten wie der Aufnahmeort werden dabei entfernt.', $maxMb) ?></p>
|
||||
<?php if ($imageError) : ?>
|
||||
<div class="error-message" id="image-error"><?= h(implode(' ', (array)$imageError)) ?></div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<fieldset class="scale-style image-fields__layout">
|
||||
<legend><?= __('Platzierung in der Präsentation') ?></legend>
|
||||
<?= $this->Form->radio('image_layout', array_map(
|
||||
fn($value, $text) => ['value' => $value, 'text' => $text],
|
||||
array_keys($layouts),
|
||||
$layouts,
|
||||
), ['value' => $layout]) ?>
|
||||
<p class="hint"><?= __('Auf dem Smartphone der Teilnehmenden steht das Bild immer oben.') ?></p>
|
||||
</fieldset>
|
||||
<?php endif; ?>
|
||||
</fieldset>
|
||||
@@ -11,7 +11,10 @@
|
||||
<p style="margin:24px 0;">
|
||||
<a href="<?= h($adminUrl) ?>" style="display:inline-block;background:#4b3fe0;color:#ffffff;text-decoration:none;padding:12px 20px;border-radius:8px;font-weight:600;"><?= __('Umfrage verwalten') ?></a>
|
||||
</p>
|
||||
<p style="font-size:13px;color:#5b5f7a;word-break:break-all;"><?= h($adminUrl) ?></p>
|
||||
<p style="font-size:13px;color:#5d6280;word-break:break-all;"><?= h($adminUrl) ?></p>
|
||||
<p><strong><?= __('Wichtig:') ?></strong> <?= __('Wer diesen Link kennt, kann die Umfrage bearbeiten. Gib ihn nicht weiter.') ?></p>
|
||||
<p><?= __('Teilnehmende erreichen die Umfrage unter {0} mit dem Code <strong>{1}</strong>.', '<a href="' . h($joinUrl) . '">' . h($joinUrl) . '</a>', h($poll->formattedJoinCode())) ?></p>
|
||||
<p style="font-size:13px;color:#5b5f7a;"><?= __('Du hast diese Umfrage nicht angelegt? Dann kannst du diese E-Mail ignorieren.') ?></p>
|
||||
<?php if ($poll->expiresAt() !== null) : ?>
|
||||
<p><?= __('Hinweis: Die Umfrage wird am {0} automatisch gelöscht. Vorher erinnern wir dich per E-Mail.', h($poll->expiresAt()->format('d.m.Y'))) ?></p>
|
||||
<?php endif; ?>
|
||||
<p style="font-size:13px;color:#5d6280;"><?= __('Du hast diese Umfrage nicht angelegt? Dann kannst du diese E-Mail ignorieren.') ?></p>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var string $adminUrl
|
||||
* @var \Cake\I18n\DateTime $expires
|
||||
*/
|
||||
?>
|
||||
<p><?= __('Hallo,') ?></p>
|
||||
<p><?= __('deine Umfrage <strong>{0}</strong> wird am <strong>{1}</strong> automatisch gelöscht, einschließlich aller Folien, Antworten und Bilder.', h($poll->title), h($expires->format('d.m.Y'))) ?></p>
|
||||
<p><?= __('Möchtest du die Ergebnisse behalten, sichere sie vorher in der Verwaltung als PDF:') ?></p>
|
||||
<p style="margin:24px 0;">
|
||||
<a href="<?= h($adminUrl) ?>" style="display:inline-block;background:#4b3fe0;color:#ffffff;text-decoration:none;padding:12px 20px;border-radius:8px;font-weight:600;"><?= __('Umfrage öffnen') ?></a>
|
||||
</p>
|
||||
<p style="font-size:13px;color:#5d6280;word-break:break-all;"><?= h($adminUrl) ?></p>
|
||||
<p><strong><?= __('Wichtig:') ?></strong> <?= __('Wer diesen Link kennt, kann die Umfrage bearbeiten. Gib ihn nicht weiter.') ?></p>
|
||||
<p style="font-size:13px;color:#5d6280;"><?= __('Du brauchst die Umfrage nicht mehr? Dann musst du nichts tun.') ?></p>
|
||||
@@ -10,8 +10,8 @@
|
||||
<?php foreach ($links as $link) : ?>
|
||||
<li style="margin-bottom:12px;">
|
||||
<a href="<?= h($link['url']) ?>" style="color:#4b3fe0;font-weight:600;"><?= h($link['title']) ?></a><br>
|
||||
<span style="font-size:13px;color:#5b5f7a;"><?= __('angelegt am {0}', h($link['created'])) ?></span>
|
||||
<span style="font-size:13px;color:#5d6280;"><?= __('angelegt am {0}', h($link['created'])) ?></span>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<p style="font-size:13px;color:#5b5f7a;"><?= __('Du hast diese E-Mail nicht angefordert? Dann kannst du sie ignorieren – deine Links bleiben unverändert gültig.') ?></p>
|
||||
<p style="font-size:13px;color:#5d6280;"><?= __('Du hast diese E-Mail nicht angefordert? Dann kannst du sie ignorieren – deine Links bleiben unverändert gültig.') ?></p>
|
||||
@@ -21,4 +21,9 @@
|
||||
<?= __('Teilnehmende erreichen die Umfrage unter {0} mit dem Code {1}.', $joinUrl, $poll->formattedJoinCode()) ?>
|
||||
|
||||
|
||||
<?php if ($poll->expiresAt() !== null) : ?>
|
||||
<?= __('Hinweis: Die Umfrage wird am {0} automatisch gelöscht. Vorher erinnern wir dich per E-Mail.', $poll->expiresAt()->format('d.m.Y')) ?>
|
||||
|
||||
|
||||
<?php endif; ?>
|
||||
<?= __('Du hast diese Umfrage nicht angelegt? Dann kannst du diese E-Mail ignorieren.') ?>
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var string $adminUrl
|
||||
* @var \Cake\I18n\DateTime $expires
|
||||
*/
|
||||
?>
|
||||
<?= __('Hallo,') ?>
|
||||
|
||||
|
||||
<?= __('deine Umfrage "{0}" wird am {1} automatisch gelöscht, einschließlich aller Folien, Antworten und Bilder.', $poll->title, $expires->format('d.m.Y')) ?>
|
||||
|
||||
|
||||
<?= __('Möchtest du die Ergebnisse behalten, sichere sie vorher in der Verwaltung als PDF:') ?>
|
||||
|
||||
|
||||
<?= $adminUrl ?>
|
||||
|
||||
|
||||
<?= __('Wichtig: Wer diesen Link kennt, kann die Umfrage bearbeiten. Gib ihn nicht weiter.') ?>
|
||||
|
||||
|
||||
<?= __('Du brauchst die Umfrage nicht mehr? Dann musst du nichts tun.') ?>
|
||||
@@ -17,7 +17,7 @@ $title = $this->fetch('title');
|
||||
<?php endif; ?>
|
||||
<title><?= $title ? h($title) . ' · ' : '' ?>PlenarIO</title>
|
||||
<?= $this->element('theme_init') ?>
|
||||
<?= $this->Html->meta('icon') ?>
|
||||
<?= $this->element('favicon') ?>
|
||||
<?= $this->Html->css(['normalize.min', 'plenario']) ?>
|
||||
<?= $this->fetch('meta') ?>
|
||||
<?= $this->fetch('css') ?>
|
||||
|
||||
@@ -1,17 +1,32 @@
|
||||
<?php
|
||||
/**
|
||||
* HTML mail layout. Colors mirror the web tokens in webroot/css/plenario.css (light theme):
|
||||
* --bg #f5f6fb, --surface #fff, --text #1d1f33, --muted #5d6280, --primary #4b3fe0.
|
||||
* Inline styles and a table for the brand row: mail clients ignore stylesheets and flexbox.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
|
||||
use App\Mailer\PollMailer;
|
||||
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title><?= $this->fetch('title') ?></title>
|
||||
</head>
|
||||
<body style="margin:0;padding:24px;background:#f4f5fb;font-family:Segoe UI,Helvetica,Arial,sans-serif;color:#1d1f33;">
|
||||
<div style="max-width:560px;margin:0 auto;background:#ffffff;border-radius:12px;padding:32px;">
|
||||
<p style="margin:0 0 24px;font-size:20px;font-weight:700;color:#4b3fe0;">PlenarIO</p>
|
||||
<body style="margin:0;padding:24px;background:#f5f6fb;font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;color:#1d1f33;">
|
||||
<div style="max-width:560px;margin:0 auto;background:#ffffff;border-radius:12px;padding:32px;color:#1d1f33;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 24px;">
|
||||
<tr>
|
||||
<td style="padding:0 10px 0 0;vertical-align:middle;">
|
||||
<img src="cid:<?= PollMailer::LOGO_CID ?>" width="32" height="32" alt="" style="display:block;border:0;border-radius:8px;">
|
||||
</td>
|
||||
<td style="vertical-align:middle;font-size:20px;font-weight:800;line-height:1;color:#1d1f33;">Plenar<span style="color:#4b3fe0;">IO</span></td>
|
||||
</tr>
|
||||
</table>
|
||||
<?= $this->fetch('content') ?>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<meta name="robots" content="noindex">
|
||||
<title><?= h($this->fetch('title')) ?> · PlenarIO</title>
|
||||
<?= $this->element('theme_init') ?>
|
||||
<?= $this->Html->meta('icon') ?>
|
||||
<?= $this->element('favicon') ?>
|
||||
<?= $this->Html->css(['normalize.min', 'plenario']) ?>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<meta name="csrf-token" content="<?= h((string)$this->request->getAttribute('csrfToken')) ?>">
|
||||
<title><?= h($this->fetch('title')) ?> · PlenarIO</title>
|
||||
<?= $this->element('theme_init', ['key' => 'plenario-theme-present', 'fallback' => 'dark']) ?>
|
||||
<?= $this->Html->meta('icon') ?>
|
||||
<?= $this->element('favicon') ?>
|
||||
<?= $this->Html->css(['normalize.min', 'plenario']) ?>
|
||||
</head>
|
||||
<body class="present">
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Command;
|
||||
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\Console\TestSuite\ConsoleIntegrationTestTrait;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\I18n\DateTime;
|
||||
use Cake\TestSuite\EmailTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* `bin/cake polls list|show|delete|remind|cleanup` and the poll expiry (counted from creation).
|
||||
*/
|
||||
class PollsCommandsTest extends TestCase
|
||||
{
|
||||
use ConsoleIntegrationTestTrait;
|
||||
use EmailTrait;
|
||||
use PlenarioTestTrait;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Configure::write('Plenario.retention.days', 90);
|
||||
Configure::write('Plenario.retention.reminderDays', 14);
|
||||
Configure::write('App.fullBaseUrl', 'https://plenario.test');
|
||||
// The commands act on all polls: start without leftovers of other tests (fixtures are empty).
|
||||
$this->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 testListAndShowAsJson(): void
|
||||
{
|
||||
[$old, $token] = $this->createPoll('Alt <b>&</b>', 'alt@example.org');
|
||||
$this->createPoll('Neu', 'neu@example.org');
|
||||
$this->age($old->id, 120);
|
||||
|
||||
$this->exec('polls list --json');
|
||||
$this->assertExitSuccess();
|
||||
$rows = json_decode(implode("
|
||||
", $this->_out->messages()), true, flags: JSON_THROW_ON_ERROR);
|
||||
$this->assertCount(2, $rows);
|
||||
$this->assertSame('Alt <b>&</b>', $rows[0]['title']);
|
||||
$this->assertSame('alt@example.org', $rows[0]['email']);
|
||||
$this->assertTrue($rows[0]['expired']);
|
||||
$this->assertFalse($rows[1]['expired']);
|
||||
$this->assertNull($rows[1]['reminderSentAt']);
|
||||
$this->assertArrayNotHasKey('adminUrl', $rows[0]);
|
||||
$this->assertStringNotContainsString($token, implode('', $this->_out->messages()));
|
||||
|
||||
$this->exec('polls list --json --expired');
|
||||
$this->assertCount(1, json_decode(implode("
|
||||
", $this->_out->messages()), true));
|
||||
|
||||
$this->exec('polls list --json --email=gibtsnicht');
|
||||
$this->assertSame([], json_decode(implode("
|
||||
", $this->_out->messages()), true));
|
||||
|
||||
$this->exec('polls show ' . $old->id . ' --json');
|
||||
$data = json_decode(implode("
|
||||
", $this->_out->messages()), true, flags: JSON_THROW_ON_ERROR);
|
||||
$this->assertSame($old->id, $data['id']);
|
||||
$this->assertNull($data['adminUrl']);
|
||||
$this->assertStringNotContainsString($token, implode('', $this->_out->messages()));
|
||||
|
||||
$this->exec('polls show ' . $old->id . ' --json --link');
|
||||
$data = json_decode(implode("
|
||||
", $this->_out->messages()), true, flags: JSON_THROW_ON_ERROR);
|
||||
$this->assertSame('https://plenario.test/admin/' . $token, $data['adminUrl']);
|
||||
}
|
||||
|
||||
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 testRemindCanBeForcedForOnePoll(): void
|
||||
{
|
||||
[$young] = $this->createPoll('Frisch', 'frisch@example.org');
|
||||
[$other] = $this->createPoll('Anderer', 'anderer@example.org');
|
||||
|
||||
// Not in the reminder window at all, yet it is sent on request, to this poll only.
|
||||
$this->exec('polls remind ' . $young->join_code);
|
||||
$this->assertExitSuccess();
|
||||
$this->assertOutputContains('erzwungen');
|
||||
$this->assertMailCount(1);
|
||||
$this->assertMailSentTo('frisch@example.org');
|
||||
$this->assertNull($this->pollsTable()->get($young->id)->expiry_reminded_at, 'a forced reminder does not mark the poll');
|
||||
|
||||
// Sendable again (also after a regular reminder), still not marked.
|
||||
$this->pollsTable()->updateAll(['expiry_reminded_at' => DateTime::now()], ['id' => $young->id]);
|
||||
$this->exec('polls remind ' . $young->id);
|
||||
$this->assertExitSuccess();
|
||||
$this->assertMailCount(2);
|
||||
|
||||
// Dry run sends nothing.
|
||||
$this->exec('polls remind ' . $other->id . ' --dry-run');
|
||||
$this->assertOutputContains('Würde erinnern');
|
||||
$this->assertMailCount(2);
|
||||
|
||||
// Works with reminders switched off, fails without an expiry date and for unknown polls.
|
||||
Configure::write('Plenario.retention.reminderDays', 0);
|
||||
$this->exec('polls remind ' . $other->id);
|
||||
$this->assertExitSuccess();
|
||||
$this->assertMailCount(3);
|
||||
|
||||
$this->exec('polls remind 99999');
|
||||
$this->assertExitError();
|
||||
$this->assertErrorContains('nicht gefunden');
|
||||
|
||||
Configure::write('Plenario.retention.days', 0);
|
||||
$this->exec('polls remind ' . $other->id);
|
||||
$this->assertExitError();
|
||||
$this->assertMailCount(3);
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -107,7 +107,7 @@ class AdminControllerTest extends TestCase
|
||||
$slide = $this->slidesTable()->find()->contain(['SlideOptions'])->firstOrFail();
|
||||
$this->assertSame($poll->id, $slide->poll_id);
|
||||
$this->assertSame(['Pizza', 'Pasta'], array_map(fn($o) => $o->label, $slide->slide_options));
|
||||
$this->assertSame(['multiple' => true], $slide->settings);
|
||||
$this->assertSame(['multiple' => true, 'comments' => false], $slide->settings);
|
||||
$this->assertSame(1, $slide->position);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Controller;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use App\Service\ResultsService;
|
||||
use App\Service\VoteException;
|
||||
use App\Service\VoteService;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* Multiple choice slides with an optional comment field (stored once per participant in the first row).
|
||||
*/
|
||||
class ChoiceCommentsTest 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();
|
||||
$this->enableCsrfToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings Extra settings
|
||||
* @return array{0: \App\Model\Entity\Poll, 1: string, 2: \App\Model\Entity\Slide}
|
||||
*/
|
||||
protected function choiceWithComments(array $settings = ['comments' => true, 'multiple' => true]): array
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$slide = $this->createSlide($poll, Slide::TYPE_CHOICE, ['settings' => $settings], ['Ja', 'Nein', 'Vielleicht']);
|
||||
$poll = $this->goLive($poll, $slide);
|
||||
|
||||
return [$poll, $token, $slide];
|
||||
}
|
||||
|
||||
protected function hash(string $char, Poll $poll): string
|
||||
{
|
||||
return VoteService::participantHash(str_repeat($char, 32), $poll->id);
|
||||
}
|
||||
|
||||
public function testSettingIsSanitized(): void
|
||||
{
|
||||
$this->assertTrue(SlidesTable::sanitizeSettings(Slide::TYPE_CHOICE, ['comments' => '1'])['comments']);
|
||||
$this->assertFalse(SlidesTable::sanitizeSettings(Slide::TYPE_CHOICE, [])['comments']);
|
||||
}
|
||||
|
||||
public function testFormShowsAndSavesCommentSetting(): void
|
||||
{
|
||||
[, $token] = $this->createPoll();
|
||||
$this->get("/admin/$token/slides/add?type=choice");
|
||||
$this->assertResponseContains('name="settings[comments]"');
|
||||
|
||||
$this->post("/admin/$token/slides/add?type=choice", [
|
||||
'type' => 'choice',
|
||||
'question' => 'Was nehmen wir?',
|
||||
'options_text' => "Ja\nNein",
|
||||
'settings' => ['comments' => '1'],
|
||||
]);
|
||||
$slide = $this->slidesTable()->find()->firstOrFail();
|
||||
$this->assertTrue($slide->hasComments());
|
||||
}
|
||||
|
||||
public function testParticipantPageShowsCommentFieldOnlyWhenEnabled(): void
|
||||
{
|
||||
[$poll] = $this->choiceWithComments();
|
||||
$this->get('/p/' . $poll->join_code);
|
||||
$this->assertResponseContains('name="comment"');
|
||||
|
||||
[$other] = $this->choiceWithComments(['multiple' => true]);
|
||||
$this->get('/p/' . $other->join_code);
|
||||
$this->assertResponseNotContains('name="comment"');
|
||||
}
|
||||
|
||||
public function testCommentIsStoredOnceInFirstRowAndCountsStayCorrect(): void
|
||||
{
|
||||
[$poll, , $slide] = $this->choiceWithComments();
|
||||
$options = array_map(fn($o) => $o->id, $slide->slide_options);
|
||||
|
||||
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
|
||||
'option_ids' => [$options[0], $options[2]],
|
||||
'comment' => ' Weil <deshalb> ',
|
||||
]);
|
||||
|
||||
$rows = $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->orderBy(['id' => 'ASC'])->all()->toList();
|
||||
$this->assertCount(2, $rows);
|
||||
$this->assertSame('Weil <deshalb>', $rows[0]->text_value);
|
||||
$this->assertNull($rows[1]->text_value);
|
||||
|
||||
$results = (new ResultsService())->forSlide($slide);
|
||||
$this->assertSame([1, 0, 1], array_column($results['options'], 'count'));
|
||||
$this->assertSame(2, $results['votes']);
|
||||
$this->assertSame(1, $results['participants']);
|
||||
$this->assertSame(['Weil <deshalb>'], array_column($results['comments'], 'text'));
|
||||
$this->assertSame([null], array_column($results['comments'], 'value'));
|
||||
}
|
||||
|
||||
public function testCommentIsIgnoredWithoutCommentField(): void
|
||||
{
|
||||
[$poll, , $slide] = $this->choiceWithComments(['multiple' => false]);
|
||||
|
||||
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
|
||||
'option_id' => $slide->slide_options[0]->id,
|
||||
'comment' => 'Eingeschmuggelt',
|
||||
]);
|
||||
|
||||
$row = $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->firstOrFail();
|
||||
$this->assertNull($row->text_value);
|
||||
$this->assertSame([], (new ResultsService())->forSlide($slide)['comments']);
|
||||
}
|
||||
|
||||
public function testTooLongCommentIsRejected(): void
|
||||
{
|
||||
[$poll, , $slide] = $this->choiceWithComments();
|
||||
|
||||
$this->expectException(VoteException::class);
|
||||
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
|
||||
'option_ids' => [$slide->slide_options[0]->id],
|
||||
'comment' => str_repeat('x', VoteService::MAX_TEXT_LENGTH + 1),
|
||||
]);
|
||||
}
|
||||
|
||||
public function testCommentCanBeEditedAddedAndRemoved(): void
|
||||
{
|
||||
[$poll, , $slide] = $this->choiceWithComments();
|
||||
$hash = $this->hash('a', $poll);
|
||||
$votes = new VoteService();
|
||||
$votes->submit($poll, $slide, $hash, [
|
||||
'option_ids' => [$slide->slide_options[0]->id, $slide->slide_options[1]->id],
|
||||
]);
|
||||
$this->assertNull($votes->ownText($slide, $hash));
|
||||
|
||||
$votes->editText($poll, $slide, $hash, ['comment' => 'Nachgereicht']);
|
||||
$this->assertSame('Nachgereicht', $votes->ownText($slide, $hash));
|
||||
|
||||
$votes->editText($poll, $slide, $hash, ['comment' => 'Korrigiert']);
|
||||
$this->assertSame(['Korrigiert'], array_column((new ResultsService())->comments($slide), 'text'));
|
||||
$this->assertSame(2, $this->slidesTable()->Responses->find()->where(['slide_id' => $slide->id])->count());
|
||||
|
||||
$votes->editText($poll, $slide, $hash, ['comment' => '']);
|
||||
$this->assertNull($votes->ownText($slide, $hash));
|
||||
$this->assertSame([], (new ResultsService())->comments($slide));
|
||||
}
|
||||
|
||||
public function testEditRequiresAnAnswer(): void
|
||||
{
|
||||
[$poll, , $slide] = $this->choiceWithComments();
|
||||
|
||||
$this->expectException(VoteException::class);
|
||||
(new VoteService())->editText($poll, $slide, $this->hash('z', $poll), ['comment' => 'Ohne Auswahl']);
|
||||
}
|
||||
|
||||
public function testPresenterGetsCommentsButParticipantsNever(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->choiceWithComments();
|
||||
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
|
||||
'option_ids' => [$slide->slide_options[0]->id],
|
||||
'comment' => 'Sichtbar auf der Bühne',
|
||||
]);
|
||||
|
||||
$this->get("/admin/$token/state");
|
||||
$results = json_decode((string)$this->_response->getBody(), true)['results'];
|
||||
$this->assertSame(['Sichtbar auf der Bühne'], array_column($results['comments'], 'text'));
|
||||
|
||||
$this->get('/p/' . $poll->join_code . '/state');
|
||||
$state = json_decode((string)$this->_response->getBody(), true);
|
||||
$this->assertNull($state['results']);
|
||||
$this->assertStringNotContainsString('Sichtbar auf der Bühne', (string)$this->_response->getBody());
|
||||
}
|
||||
|
||||
public function testAnswersPageListsCommentsOfChoiceSlides(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->choiceWithComments();
|
||||
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
|
||||
'option_ids' => [$slide->slide_options[0]->id],
|
||||
'comment' => 'Erster <Kommentar>',
|
||||
]);
|
||||
|
||||
$this->get("/admin/$token/slides/{$slide->id}/answers");
|
||||
$this->assertResponseOk();
|
||||
$this->assertResponseContains('Erster <Kommentar>');
|
||||
}
|
||||
|
||||
public function testAnswersPageIsNotFoundForChoiceWithoutComments(): void
|
||||
{
|
||||
[, $token, $slide] = $this->choiceWithComments(['multiple' => false]);
|
||||
|
||||
$this->get("/admin/$token/slides/{$slide->id}/answers");
|
||||
$this->assertResponseCode(404);
|
||||
}
|
||||
|
||||
public function testExportContainsComments(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->choiceWithComments();
|
||||
(new VoteService())->submit($poll, $slide, $this->hash('a', $poll), [
|
||||
'option_ids' => [$slide->slide_options[0]->id],
|
||||
'comment' => 'Im PDF enthalten',
|
||||
]);
|
||||
|
||||
$this->assertStringContainsString('Im PDF enthalten', $this->exportHtml($token));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Controller;
|
||||
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* The logo as favicon: links in every layout and the files behind them.
|
||||
*/
|
||||
class FaviconTest extends TestCase
|
||||
{
|
||||
use IntegrationTestTrait;
|
||||
use PlenarioTestTrait;
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
|
||||
|
||||
public function testAllLayoutsLinkTheIcons(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$this->createSlide($poll);
|
||||
|
||||
// default, present and error layout
|
||||
foreach (['/', '/admin/' . $token . '/present', '/does-not-exist'] as $url) {
|
||||
$this->get($url);
|
||||
// Root-relative, no "img/" prefix (static files live directly in webroot/).
|
||||
$this->assertResponseRegExp('#<link rel="icon" href="/favicon\.svg(\?[^"]*)?" type="image/svg\+xml">#', $url);
|
||||
$this->assertResponseRegExp('#<link rel="icon" href="/favicon\.ico(\?[^"]*)?" sizes="32x32">#', $url);
|
||||
$this->assertResponseRegExp('#<link rel="apple-touch-icon" href="/apple-touch-icon\.png(\?[^"]*)?">#', $url);
|
||||
}
|
||||
}
|
||||
|
||||
public function testIconFilesAreValid(): void
|
||||
{
|
||||
$svg = (string)file_get_contents(WWW_ROOT . 'favicon.svg');
|
||||
$this->assertStringContainsString('<svg', $svg);
|
||||
$this->assertNotFalse(simplexml_load_string($svg), 'favicon.svg is not well-formed XML');
|
||||
|
||||
// ICO: reserved 0, type 1, three images; each entry's data starts with the PNG signature.
|
||||
$ico = (string)file_get_contents(WWW_ROOT . 'favicon.ico');
|
||||
$header = unpack('vreserved/vtype/vcount', $ico);
|
||||
$this->assertSame([0, 1, 3], [$header['reserved'], $header['type'], $header['count']]);
|
||||
for ($i = 0; $i < $header['count']; $i++) {
|
||||
$entry = unpack('Voffset', $ico, 6 + 16 * $i + 12);
|
||||
$this->assertSame("\x89PNG", substr($ico, $entry['offset'], 4));
|
||||
}
|
||||
|
||||
$this->assertSame([180, 180], array_slice(getimagesize(WWW_ROOT . 'apple-touch-icon.png'), 0, 2));
|
||||
}
|
||||
}
|
||||
@@ -52,9 +52,11 @@ class PollResetTest extends TestCase
|
||||
$quiz->setVotingOpen(true);
|
||||
$quiz->is_voting_open = false;
|
||||
$order->is_voting_open = false;
|
||||
$choice->is_voting_open = false;
|
||||
$qa->stage = Slide::QA_DISCUSS;
|
||||
$qa->is_voting_open = false;
|
||||
$this->slidesTable()->saveManyOrFail([$quiz, $order, $qa]);
|
||||
$this->slidesTable()->saveManyOrFail([$quiz, $order, $qa, $choice]);
|
||||
$poll->showSlide($qa->id);
|
||||
$poll->pause();
|
||||
$this->pollsTable()->saveOrFail($poll);
|
||||
|
||||
@@ -66,23 +68,63 @@ class PollResetTest extends TestCase
|
||||
$this->assertSame(0, $responses->find()->where(['slide_id IN' => [$choice->id, $quiz->id, $order->id, $qa->id]])->count());
|
||||
$this->assertSame(1, $responses->find()->where(['slide_id' => $foreign->id])->count(), 'other polls stay untouched');
|
||||
|
||||
// The presentation stays where it is (paused on the choice slide).
|
||||
// The presentation is back to "not started".
|
||||
$poll = $this->pollsTable()->get($poll->id);
|
||||
$this->assertNull($poll->current_slide_id);
|
||||
$this->assertSame($choice->id, $poll->paused_slide_id);
|
||||
$this->assertNull($poll->paused_slide_id);
|
||||
|
||||
$slides = $this->slidesTable();
|
||||
$this->assertSame(Slide::QUIZ_READY, $slides->get($quiz->id)->quizPhase());
|
||||
$this->assertNull($slides->get($quiz->id)->voting_started_at);
|
||||
$this->assertFalse($slides->get($order->id)->is_voting_open, 'open/closed is kept');
|
||||
$this->assertTrue($slides->get($order->id)->is_voting_open, 'ordering is open again, solution hidden');
|
||||
$this->assertSame(Slide::QA_COLLECT, $slides->get($qa->id)->qaStage());
|
||||
$this->assertTrue($slides->get($qa->id)->is_voting_open);
|
||||
$this->assertTrue($slides->get($choice->id)->is_voting_open);
|
||||
$this->assertTrue($slides->get($choice->id)->is_voting_open, 'closed slides are open again');
|
||||
|
||||
// Idempotent: a second reset changes nothing and does not fail.
|
||||
$this->post("/admin/$token/reset");
|
||||
$this->assertRedirect(['_name' => 'admin', 'token' => $token]);
|
||||
$this->assertSame($choice->id, $this->pollsTable()->get($poll->id)->paused_slide_id);
|
||||
$this->assertNull($this->pollsTable()->get($poll->id)->paused_slide_id);
|
||||
}
|
||||
|
||||
public function testResetStopsLivePresentation(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$second = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$poll = $this->goLive($poll, $second);
|
||||
(new VoteService())->submit($poll, $second, VoteService::participantHash(str_repeat('a', 32), $poll->id), [
|
||||
'option_id' => $second->slide_options[0]->id,
|
||||
]);
|
||||
|
||||
$this->post("/admin/$token/reset");
|
||||
$reloaded = $this->pollsTable()->get($poll->id);
|
||||
$this->assertNull($reloaded->current_slide_id);
|
||||
$this->assertNull($reloaded->paused_slide_id);
|
||||
}
|
||||
|
||||
public function testResetKeepsPreparedQuestionsUnlessAsked(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$qa = $this->createSlide($poll, Slide::TYPE_QA);
|
||||
$responses = TableRegistry::getTableLocator()->get('Responses');
|
||||
$question = $responses->saveOrFail($responses->newEntity([
|
||||
'slide_id' => $qa->id,
|
||||
'participant_hash' => VoteService::PREPARED_HASH,
|
||||
'text_value' => 'Vorbereitet?',
|
||||
], ['accessibleFields' => ['*' => true]]));
|
||||
$responses->saveOrFail($responses->newEntity([
|
||||
'slide_id' => $qa->id,
|
||||
'participant_hash' => VoteService::participantHash(str_repeat('a', 32), $poll->id),
|
||||
'parent_id' => $question->id,
|
||||
], ['accessibleFields' => ['*' => true]]));
|
||||
|
||||
$this->post("/admin/$token/reset");
|
||||
$this->assertSame(1, $responses->find()->where(['slide_id' => $qa->id])->count());
|
||||
$this->assertSame(1, $responses->find()->where(['id' => $question->id])->count());
|
||||
|
||||
$this->post("/admin/$token/reset", ['keep_prepared' => '0']);
|
||||
$this->assertSame(0, $responses->find()->where(['slide_id' => $qa->id])->count());
|
||||
}
|
||||
|
||||
public function testResetRequiresPost(): void
|
||||
@@ -107,4 +149,65 @@ class PollResetTest extends TestCase
|
||||
$this->get("/admin/$token");
|
||||
$this->assertResponseContains("/admin/$token/reset\"");
|
||||
}
|
||||
|
||||
public function testDashboardOffersResetWithoutAnswersWhenSlidesWereTouched(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$quiz = $this->createSlide($poll, Slide::TYPE_QUIZ);
|
||||
$quiz->startFresh();
|
||||
$this->slidesTable()->saveOrFail($quiz);
|
||||
$choice = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$this->get("/admin/$token");
|
||||
$this->assertResponseContains('Noch nichts zurückzusetzen');
|
||||
|
||||
// Quiz started, nobody answered yet.
|
||||
$quiz->setVotingOpen(true);
|
||||
$this->slidesTable()->saveOrFail($quiz);
|
||||
$this->get("/admin/$token");
|
||||
$this->assertResponseContains("/admin/$token/reset\"");
|
||||
$this->assertResponseContains("/admin/$token/slides/{$quiz->id}/reset");
|
||||
$this->assertResponseNotContains("/admin/$token/slides/{$choice->id}/reset");
|
||||
|
||||
// Closed slide.
|
||||
$quiz->startFresh();
|
||||
$this->slidesTable()->saveOrFail($quiz);
|
||||
$choice->is_voting_open = false;
|
||||
$this->slidesTable()->saveOrFail($choice);
|
||||
$this->get("/admin/$token");
|
||||
$this->assertResponseContains("/admin/$token/reset\"");
|
||||
$this->assertResponseContains("/admin/$token/slides/{$choice->id}/reset");
|
||||
|
||||
// Presentation running.
|
||||
$choice->startFresh();
|
||||
$this->slidesTable()->saveOrFail($choice);
|
||||
$this->goLive($poll, $choice);
|
||||
$this->get("/admin/$token");
|
||||
$this->assertResponseContains("/admin/$token/reset\"");
|
||||
}
|
||||
|
||||
public function testDashboardLiveVersionFollowsThePresenter(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$first = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$second = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$version = function () use ($token): string {
|
||||
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
|
||||
$this->get("/admin/$token/live");
|
||||
$this->assertResponseOk();
|
||||
|
||||
return json_decode((string)$this->_response->getBody(), true)['version'];
|
||||
};
|
||||
|
||||
$start = $version();
|
||||
$this->assertSame($start, $version(), 'stable while nothing happens');
|
||||
|
||||
$poll = $this->goLive($poll, $first);
|
||||
$live = $version();
|
||||
$this->assertNotSame($start, $live, 'live slide changed');
|
||||
|
||||
$this->goLive($poll, $second);
|
||||
$this->assertNotSame($live, $version(), 'live marker moved');
|
||||
|
||||
$this->assertStringNotContainsString($token, (string)$this->_response->getBody());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Controller;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* Stepping through a presentation with a clicker (only next/prev): a quiz is started and ended before moving on.
|
||||
*/
|
||||
class QuizClickerTest 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();
|
||||
$this->enableCsrfToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function control(string $token, string $action): array
|
||||
{
|
||||
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
|
||||
$this->post("/admin/$token/control", ['action' => $action]);
|
||||
$this->assertResponseOk();
|
||||
|
||||
return json_decode((string)$this->_response->getBody(), true);
|
||||
}
|
||||
|
||||
protected function createQuiz(Poll $poll, array $data = []): Slide
|
||||
{
|
||||
$quiz = $this->createSlide($poll, Slide::TYPE_QUIZ, $data);
|
||||
$quiz->startFresh();
|
||||
|
||||
return $this->slidesTable()->saveOrFail($quiz);
|
||||
}
|
||||
|
||||
public function testNextStartsAndEndsQuizBeforeMovingOn(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$intro = $this->createSlide($poll, Slide::TYPE_CONTENT);
|
||||
$quiz = $this->createQuiz($poll, ['settings' => ['time_limit' => 0] + Slide::DEFAULT_SETTINGS[Slide::TYPE_QUIZ]]);
|
||||
$outro = $this->createSlide($poll, Slide::TYPE_CONTENT);
|
||||
$this->goLive($poll, $intro);
|
||||
|
||||
// Arriving at the quiz does not start it.
|
||||
$state = $this->control($token, 'next');
|
||||
$this->assertSame($quiz->id, $state['slide']['id']);
|
||||
$this->assertSame(Slide::QUIZ_READY, $this->slidesTable()->get($quiz->id)->quizPhase());
|
||||
|
||||
// Next: start. Next: end. Next: next slide.
|
||||
$state = $this->control($token, 'next');
|
||||
$this->assertSame($quiz->id, $state['slide']['id']);
|
||||
$this->assertSame(Slide::QUIZ_RUNNING, $this->slidesTable()->get($quiz->id)->quizPhase());
|
||||
|
||||
$state = $this->control($token, 'next');
|
||||
$this->assertSame($quiz->id, $state['slide']['id']);
|
||||
$this->assertSame(Slide::QUIZ_FINISHED, $this->slidesTable()->get($quiz->id)->quizPhase());
|
||||
|
||||
$state = $this->control($token, 'next');
|
||||
$this->assertSame($outro->id, $state['slide']['id']);
|
||||
|
||||
// Back never restarts the quiz: it is passed through and stays finished.
|
||||
$state = $this->control($token, 'prev');
|
||||
$this->assertSame($quiz->id, $state['slide']['id']);
|
||||
$this->assertSame(Slide::QUIZ_FINISHED, $this->slidesTable()->get($quiz->id)->quizPhase());
|
||||
$state = $this->control($token, 'prev');
|
||||
$this->assertSame($intro->id, $state['slide']['id']);
|
||||
}
|
||||
|
||||
public function testPrevOnUnstartedQuizJustGoesBack(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$intro = $this->createSlide($poll, Slide::TYPE_CONTENT);
|
||||
$quiz = $this->createQuiz($poll);
|
||||
$this->goLive($poll, $quiz);
|
||||
|
||||
$state = $this->control($token, 'prev');
|
||||
$this->assertSame($intro->id, $state['slide']['id']);
|
||||
$this->assertSame(Slide::QUIZ_READY, $this->slidesTable()->get($quiz->id)->quizPhase());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Controller;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Test\TestCase\ImageTestTrait;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* Images on slides: upload and scaling, alternative text, quota, serving, and what happens to the
|
||||
* file when the image is replaced, removed or the slide (or poll) is deleted or duplicated.
|
||||
*/
|
||||
class SlideImageTest extends TestCase
|
||||
{
|
||||
use ImageTestTrait;
|
||||
use IntegrationTestTrait;
|
||||
use PlenarioTestTrait;
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses'];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->enableCsrfToken();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->clearImages();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a content slide with an uploaded image through the form.
|
||||
*
|
||||
* @return array{0: \App\Model\Entity\Poll, 1: string, 2: \App\Model\Entity\Slide}
|
||||
*/
|
||||
protected function slideWithImage(array $data = []): array
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$this->postWithImage("/admin/$token/slides/add?type=content", $data + [
|
||||
'type' => 'content',
|
||||
'question' => 'Mit Bild',
|
||||
], $this->makeImage(3000, 2000));
|
||||
$slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->first();
|
||||
|
||||
return [$poll, $token, $slide];
|
||||
}
|
||||
|
||||
public function testUploadStoresScaledImageWithAltAndLayout(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage(['image_layout' => 'full']);
|
||||
|
||||
$this->assertRedirect(['_name' => 'admin', 'token' => $token]);
|
||||
$this->assertNotNull($slide);
|
||||
$this->assertTrue($slide->hasImage());
|
||||
$this->assertSame([1600, 1067], [$slide->image_width, $slide->image_height]);
|
||||
$this->assertSame(Slide::IMAGE_FULL, $slide->imageLayout());
|
||||
$this->assertSame([$slide->image], $this->storedImages($poll->id));
|
||||
}
|
||||
|
||||
public function testLayoutDefaultsByType(): void
|
||||
{
|
||||
[$poll, , $content] = $this->slideWithImage();
|
||||
$this->assertSame(Slide::IMAGE_SIDE, $content->imageLayout());
|
||||
|
||||
$choice = $this->createSlide($poll, Slide::TYPE_CHOICE, ['image' => 'a', 'image_layout' => 'full']);
|
||||
$this->assertSame(Slide::IMAGE_TOP, $choice->imageLayout(), 'full exists for content slides only');
|
||||
}
|
||||
|
||||
public function testNoDescriptionIsNeeded(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$this->postWithImage("/admin/$token/slides/add?type=content", [
|
||||
'type' => 'content',
|
||||
'question' => 'Ohne Beschreibung',
|
||||
], $this->makeImage());
|
||||
|
||||
$this->assertRedirect(['_name' => 'admin', 'token' => $token]);
|
||||
$slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail();
|
||||
$this->assertTrue($slide->hasImage());
|
||||
$this->assertSame('', $slide->image_alt);
|
||||
$this->assertSame([$slide->image], $this->storedImages($poll->id));
|
||||
}
|
||||
|
||||
public function testRejectsFilesThatAreNoImages(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$path = tempnam(sys_get_temp_dir(), 'plen');
|
||||
$this->imageFiles[] = $path;
|
||||
file_put_contents($path, 'just text');
|
||||
|
||||
$this->postWithImage("/admin/$token/slides/add?type=content", [
|
||||
'type' => 'content',
|
||||
'question' => 'Kein Bild',
|
||||
], $path, UPLOAD_ERR_OK, 'text.jpg');
|
||||
|
||||
$this->assertResponseContains('JPEG, PNG, WebP oder GIF');
|
||||
$this->assertSame(0, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count());
|
||||
}
|
||||
|
||||
public function testFailedSaveKeepsTheOldImage(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
$old = $slide->image;
|
||||
|
||||
$this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [
|
||||
'question' => '',
|
||||
], $this->makeImage(100, 100));
|
||||
|
||||
$this->assertResponseContains('Bitte prüfe deine Eingaben');
|
||||
$this->assertSame([$old], $this->storedImages($poll->id));
|
||||
$this->assertSame($old, $this->slidesTable()->get($slide->id)->image);
|
||||
}
|
||||
|
||||
public function testQuotaPerPoll(): void
|
||||
{
|
||||
Configure::write('Plenario.images.maxPerPoll', 1);
|
||||
[$poll, $token] = $this->slideWithImage();
|
||||
|
||||
$this->postWithImage("/admin/$token/slides/add?type=content", [
|
||||
'type' => 'content',
|
||||
'question' => 'Zweites Bild',
|
||||
], $this->makeImage());
|
||||
|
||||
$this->assertResponseContains('höchstens 1 Folien mit Bild');
|
||||
$this->assertCount(1, $this->storedImages($poll->id));
|
||||
$this->assertSame(1, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count());
|
||||
}
|
||||
|
||||
public function testReplacingAnImageDeletesTheOldFile(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
$old = $slide->image;
|
||||
|
||||
$this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [
|
||||
'question' => 'Mit Bild',
|
||||
], $this->makeImage(300, 200));
|
||||
|
||||
$slide = $this->slidesTable()->get($slide->id);
|
||||
$this->assertNotSame($old, $slide->image);
|
||||
$this->assertSame([$slide->image], $this->storedImages($poll->id));
|
||||
$this->assertSame([300, 200], [$slide->image_width, $slide->image_height]);
|
||||
}
|
||||
|
||||
public function testEditingWithoutUploadKeepsImageAndAllowsAltChange(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
|
||||
$this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [
|
||||
'question' => 'Mit Bild',
|
||||
'image_layout' => 'top',
|
||||
], $this->makeImage(), UPLOAD_ERR_NO_FILE);
|
||||
|
||||
$after = $this->slidesTable()->get($slide->id);
|
||||
$this->assertSame($slide->image, $after->image);
|
||||
$this->assertSame(Slide::IMAGE_TOP, $after->imageLayout());
|
||||
$this->assertSame([$slide->image], $this->storedImages($poll->id));
|
||||
}
|
||||
|
||||
public function testRemoveImage(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
|
||||
$this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Mit Bild', 'remove_image' => '1']);
|
||||
$this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Mit Bild', 'remove_image' => '1']);
|
||||
|
||||
$after = $this->slidesTable()->get($slide->id);
|
||||
$this->assertFalse($after->hasImage());
|
||||
$this->assertSame([], $this->storedImages($poll->id));
|
||||
}
|
||||
|
||||
public function testDeletingTheSlideDeletesTheFile(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
$other = $this->createSlide($poll, Slide::TYPE_OPEN);
|
||||
|
||||
$this->post("/admin/$token/slides/{$other->id}/delete");
|
||||
$this->assertCount(1, $this->storedImages($poll->id), 'another slide does not touch the image');
|
||||
|
||||
$this->post("/admin/$token/slides/{$slide->id}/delete");
|
||||
|
||||
$this->assertSame([], $this->storedImages($poll->id));
|
||||
}
|
||||
|
||||
public function testDeletingThePollDeletesAllImages(): void
|
||||
{
|
||||
[$poll, $token] = $this->slideWithImage();
|
||||
$this->postWithImage("/admin/$token/slides/add?type=content", [
|
||||
'type' => 'content',
|
||||
'question' => 'Zweites',
|
||||
], $this->makeImage());
|
||||
$this->assertCount(2, $this->storedImages($poll->id));
|
||||
|
||||
$this->post("/admin/$token/delete", ['confirm_code' => $poll->join_code]);
|
||||
|
||||
$this->assertSame([], $this->storedImages($poll->id));
|
||||
$this->assertDirectoryDoesNotExist($this->uploadRoot() . DS . $poll->id);
|
||||
}
|
||||
|
||||
public function testDuplicateGetsItsOwnFile(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage(['image_layout' => 'top']);
|
||||
|
||||
$this->post("/admin/$token/slides/{$slide->id}/duplicate");
|
||||
|
||||
$slides = $this->slidesTable()->listForPoll($poll->id);
|
||||
$copy = $slides[1];
|
||||
$this->assertTrue($copy->hasImage());
|
||||
$this->assertNotSame($slide->image, $copy->image);
|
||||
$this->assertSame(Slide::IMAGE_TOP, $copy->imageLayout());
|
||||
$this->assertCount(2, $this->storedImages($poll->id));
|
||||
|
||||
$this->post("/admin/$token/slides/{$copy->id}/delete");
|
||||
|
||||
$this->assertSame([$slide->image], $this->storedImages($poll->id), 'the original keeps its image');
|
||||
}
|
||||
|
||||
public function testResetKeepsImages(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
|
||||
$this->post("/admin/$token/reset");
|
||||
|
||||
$this->assertTrue($this->slidesTable()->get($slide->id)->hasImage());
|
||||
$this->assertCount(1, $this->storedImages($poll->id));
|
||||
}
|
||||
|
||||
public function testYouTubeSlidesIgnoreImages(): void
|
||||
{
|
||||
$this->assertFalse(Slide::supportsImage(Slide::TYPE_YOUTUBE));
|
||||
$this->assertTrue(Slide::supportsImage(Slide::TYPE_QUIZ));
|
||||
}
|
||||
|
||||
public function testImageIsServedForTheOwnPollOnly(): void
|
||||
{
|
||||
[$poll, , $slide] = $this->slideWithImage();
|
||||
[$otherPoll] = $this->createPoll('Andere');
|
||||
|
||||
$this->get(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image]);
|
||||
|
||||
$this->assertResponseOk();
|
||||
$this->assertContentType('image/webp');
|
||||
$this->assertHeaderContains('Cache-Control', 'immutable');
|
||||
$this->assertHeaderContains('Cache-Control', 'private');
|
||||
$this->assertSame(IMAGETYPE_WEBP, getimagesizefromstring((string)$this->_response->getBody())[2]);
|
||||
$this->assertCookieNotSet('plenario_pid');
|
||||
|
||||
$this->get(['_name' => 'participate:image', 'code' => $otherPoll->join_code, 'file' => $slide->image]);
|
||||
$this->assertResponseCode(404);
|
||||
|
||||
$this->get('/p/' . $poll->join_code . '/img/' . str_repeat('a', 24) . '.webp');
|
||||
$this->assertResponseCode(404);
|
||||
$this->get('/p/' . $poll->join_code . '/img/..%2F..%2Fapp.php');
|
||||
$this->assertResponseCode(404);
|
||||
}
|
||||
|
||||
public function testImageIsGoneWhenReplaced(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
$old = $slide->image;
|
||||
$this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [
|
||||
'question' => 'Mit Bild',
|
||||
], $this->makeImage(300, 200));
|
||||
|
||||
$this->get(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $old]);
|
||||
|
||||
$this->assertResponseCode(404);
|
||||
}
|
||||
|
||||
public function testPresenterStateAndParticipantPageShowTheImage(): void
|
||||
{
|
||||
[$poll, $token, $slide] = $this->slideWithImage();
|
||||
$poll = $this->goLive($poll, $slide);
|
||||
|
||||
$this->get("/admin/$token/state");
|
||||
$payload = json_decode((string)$this->_response->getBody(), true)['slide'];
|
||||
$this->assertSame('', $payload['image']['alt']);
|
||||
$this->assertSame('side', $payload['image']['layout']);
|
||||
$this->assertSame("/p/{$poll->join_code}/img/{$slide->image}", $payload['image']['url']);
|
||||
|
||||
$this->get('/p/' . $poll->join_code);
|
||||
$this->assertResponseOk();
|
||||
$this->assertResponseContains('/p/' . $poll->join_code . '/img/' . $slide->image);
|
||||
$this->assertResponseContains('alt=""');
|
||||
$this->assertResponseContains('width="1600" height="1067"');
|
||||
}
|
||||
|
||||
public function testSlideWithoutImageHasNoImagePayload(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$slide = $this->createSlide($poll, Slide::TYPE_OPEN);
|
||||
$this->goLive($poll, $slide);
|
||||
|
||||
$this->get("/admin/$token/state");
|
||||
|
||||
$this->assertNull(json_decode((string)$this->_response->getBody(), true)['slide']['image']);
|
||||
}
|
||||
|
||||
public function testEditFormShowsImageFields(): void
|
||||
{
|
||||
[, $token, $slide] = $this->slideWithImage();
|
||||
|
||||
$this->get("/admin/$token/slides/{$slide->id}/edit");
|
||||
|
||||
$this->assertResponseOk();
|
||||
$this->assertResponseContains('enctype="multipart/form-data"');
|
||||
$this->assertResponseContains('name="remove_image"');
|
||||
$this->assertResponseContains('Bildschirm füllen');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Controller;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* Speaker view (second window): preview of the next slide, no side effects, no solutions in the JSON.
|
||||
*/
|
||||
class SpeakerViewTest 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();
|
||||
$this->enableCsrfToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function state(string $token): array
|
||||
{
|
||||
$this->get("/admin/$token/state");
|
||||
$this->assertResponseOk();
|
||||
|
||||
return json_decode((string)$this->_response->getBody(), true);
|
||||
}
|
||||
|
||||
public function testSpeakerPageDoesNotStartThePresentation(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
$this->get("/admin/$token/speaker");
|
||||
$this->assertResponseOk();
|
||||
$this->assertResponseContains('data-next');
|
||||
$this->assertNull($this->pollsTable()->get($poll->id)->current_slide_id);
|
||||
}
|
||||
|
||||
$this->get("/admin/$token/present");
|
||||
$this->assertResponseNotContains('data-next-question');
|
||||
}
|
||||
|
||||
public function testSpeakerPageNeedsTheToken(): void
|
||||
{
|
||||
$this->get('/admin/' . str_repeat('x', 30) . '/speaker');
|
||||
$this->assertResponseCode(404);
|
||||
}
|
||||
|
||||
public function testNextIsTheSlideBehindTheLiveOne(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$first = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$second = $this->createSlide($poll, Slide::TYPE_CHOICE, ['question' => 'Zweite?']);
|
||||
$hidden = $this->createSlide($poll, Slide::TYPE_CONTENT);
|
||||
$hidden->is_hidden = true;
|
||||
$this->slidesTable()->saveOrFail($hidden);
|
||||
$this->createSlide($poll, Slide::TYPE_WORDCLOUD, ['question' => 'Letzte?']);
|
||||
|
||||
$this->assertSame($first->id, $this->state($token)['next']['id'], 'before the start: the first slide');
|
||||
|
||||
$this->goLive($poll, $first);
|
||||
$next = $this->state($token)['next'];
|
||||
$this->assertSame($second->id, $next['id']);
|
||||
$this->assertSame('Zweite?', $next['question']);
|
||||
$this->assertSame(['Ja', 'Nein'], $next['options']);
|
||||
|
||||
$this->goLive($poll, $second);
|
||||
$this->assertSame('Letzte?', $this->state($token)['next']['question'], 'hidden slides are skipped');
|
||||
|
||||
$last = $this->slidesTable()->find()->where(['poll_id' => $poll->id, 'type' => Slide::TYPE_WORDCLOUD])->firstOrFail();
|
||||
$this->goLive($poll, $last);
|
||||
$this->assertNull($this->state($token)['next'], 'nothing after the last slide');
|
||||
}
|
||||
|
||||
public function testPreviewRevealsNoSolution(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$first = $this->createSlide($poll, Slide::TYPE_CONTENT);
|
||||
$this->createSlide($poll, Slide::TYPE_QUIZ, [], ['Richtig', 'Falsch']);
|
||||
$this->createSlide($poll, Slide::TYPE_ORDER, [], ['Eins', 'Zwei', 'Drei']);
|
||||
$this->goLive($poll, $first);
|
||||
|
||||
$quiz = $this->state($token)['next'];
|
||||
$this->assertSame(['Richtig', 'Falsch'], $quiz['options']);
|
||||
$this->assertStringNotContainsString('is_correct', json_encode($quiz));
|
||||
|
||||
$order = $this->slidesTable()->find()->where(['poll_id' => $poll->id, 'type' => Slide::TYPE_ORDER])->firstOrFail();
|
||||
$quizSlide = $this->slidesTable()->find()->where(['poll_id' => $poll->id, 'type' => Slide::TYPE_QUIZ])->firstOrFail();
|
||||
$this->goLive($poll, $quizSlide);
|
||||
$this->assertSame([], $this->state($token)['next']['options'], 'the stored order is the solution');
|
||||
$this->assertSame($order->id, $this->state($token)['next']['id']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Laminas\Diactoros\UploadedFile;
|
||||
|
||||
/**
|
||||
* Helpers for tests with slide images: generated pictures and a throw-away upload directory.
|
||||
* Call clearImages() from tearDown().
|
||||
*/
|
||||
trait ImageTestTrait
|
||||
{
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
protected array $imageFiles = [];
|
||||
|
||||
/**
|
||||
* Writes a picture to a temporary file.
|
||||
*
|
||||
* @param int $width Width in pixels
|
||||
* @param int $height Height in pixels
|
||||
* @param string $format jpeg|png|gif|webp
|
||||
* @return string Path
|
||||
*/
|
||||
protected function makeImage(int $width = 400, int $height = 300, string $format = 'jpeg'): string
|
||||
{
|
||||
$image = imagecreatetruecolor($width, $height);
|
||||
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, (int)imagecolorallocate($image, 200, 40, 40));
|
||||
imagefilledellipse($image, intdiv($width, 2), intdiv($height, 2), intdiv($width, 2), intdiv($height, 2), (int)imagecolorallocate($image, 250, 250, 250));
|
||||
$path = tempnam(sys_get_temp_dir(), 'plen');
|
||||
match ($format) {
|
||||
'png' => imagepng($image, $path),
|
||||
'gif' => imagegif($image, $path),
|
||||
'webp' => imagewebp($image, $path),
|
||||
default => imagejpeg($image, $path),
|
||||
};
|
||||
$this->imageFiles[] = $path;
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Posts a form with an uploaded file in the field `image` (the test request carries files
|
||||
* separately from the form data).
|
||||
*
|
||||
* @param string $url URL
|
||||
* @param array<string, mixed> $data Form data
|
||||
* @param string|null $path File to upload, null = no upload field at all
|
||||
* @param int $error Upload error code (UPLOAD_ERR_NO_FILE = field left empty)
|
||||
* @param string $name Client file name
|
||||
* @return void
|
||||
*/
|
||||
protected function postWithImage(string $url, array $data, ?string $path, int $error = UPLOAD_ERR_OK, string $name = 'bild.jpg'): void
|
||||
{
|
||||
$this->_request['files'] = $path === null ? [] : [
|
||||
'image' => new UploadedFile($path, (int)filesize($path), $error, $name, 'image/jpeg'),
|
||||
];
|
||||
try {
|
||||
$this->post($url, $data);
|
||||
} finally {
|
||||
$this->_request['files'] = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string The upload directory of the tests
|
||||
*/
|
||||
protected function uploadRoot(): string
|
||||
{
|
||||
return (string)Configure::read('Plenario.images.path');
|
||||
}
|
||||
|
||||
/**
|
||||
* Files stored for a poll.
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @return list<string> File names
|
||||
*/
|
||||
protected function storedImages(int $pollId): array
|
||||
{
|
||||
$files = array_map('basename', glob($this->uploadRoot() . DS . $pollId . DS . '*') ?: []);
|
||||
sort($files);
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes temporary pictures and the upload directory of the tests.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function clearImages(): void
|
||||
{
|
||||
foreach ($this->imageFiles as $file) {
|
||||
@unlink($file);
|
||||
}
|
||||
$this->imageFiles = [];
|
||||
foreach (glob($this->uploadRoot() . DS . '*', GLOB_ONLYDIR) ?: [] as $directory) {
|
||||
array_map('unlink', glob($directory . DS . '*') ?: []);
|
||||
@rmdir($directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Mailer;
|
||||
|
||||
use App\Mailer\PollMailer;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\TestSuite\EmailTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
class PollMailerTest extends TestCase
|
||||
{
|
||||
use EmailTrait;
|
||||
use PlenarioTestTrait;
|
||||
|
||||
public function testHtmlMailShowsLogoAndWebColors(): void
|
||||
{
|
||||
[$poll] = $this->createPoll('Retro', 'owner@example.org');
|
||||
|
||||
$this->assertTrue((new PollMailer())->sendSafely('expiryReminder', [$poll, 'https://example.org/admin/x']));
|
||||
|
||||
$this->assertMailCount(1);
|
||||
$this->assertMailContainsAttachment('logo.png');
|
||||
// The logo is referenced by Content-ID, not by a URL that images-off clients would block.
|
||||
$this->assertMailContainsHtml('src="cid:' . PollMailer::LOGO_CID . '"');
|
||||
// Brand and text colors as on the web (--text, --primary, --muted), not the old off-by-a-bit values.
|
||||
$this->assertMailContainsHtml('Plenar<span style="color:#4b3fe0;">IO</span>');
|
||||
$this->assertMailContainsHtml('color:#5d6280');
|
||||
$this->assertMailContainsHtml('background:#f5f6fb');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Service;
|
||||
|
||||
use App\Service\ImageException;
|
||||
use App\Service\ImageService;
|
||||
use App\Test\TestCase\ImageTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
use Laminas\Diactoros\UploadedFile;
|
||||
|
||||
/**
|
||||
* Scaling, validation and file handling of slide images.
|
||||
*/
|
||||
class ImageServiceTest extends TestCase
|
||||
{
|
||||
use ImageTestTrait;
|
||||
|
||||
protected ImageService $images;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->images = new ImageService();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->clearImages();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
protected function file(string $path, int $error = UPLOAD_ERR_OK): UploadedFile
|
||||
{
|
||||
return new UploadedFile($path, (int)filesize($path), $error, 'bild.jpg', 'image/jpeg');
|
||||
}
|
||||
|
||||
public function testLargeImageIsScaledDownAndStoredAsWebp(): void
|
||||
{
|
||||
$stored = $this->images->store($this->file($this->makeImage(3200, 2000)), 7);
|
||||
|
||||
$this->assertSame(1600, $stored['width']);
|
||||
$this->assertSame(1000, $stored['height']);
|
||||
$this->assertTrue(ImageService::isValidName($stored['name']));
|
||||
$path = $this->images->path(7, $stored['name']);
|
||||
$this->assertNotNull($path);
|
||||
$info = getimagesize($path);
|
||||
$this->assertSame(IMAGETYPE_WEBP, $info[2]);
|
||||
$this->assertSame([1600, 1000], [$info[0], $info[1]]);
|
||||
}
|
||||
|
||||
public function testSmallImageIsNotEnlarged(): void
|
||||
{
|
||||
$stored = $this->images->store($this->file($this->makeImage(300, 200, 'png')), 7);
|
||||
|
||||
$this->assertSame([300, 200], [$stored['width'], $stored['height']]);
|
||||
}
|
||||
|
||||
public function testAcceptsGifAndWebp(): void
|
||||
{
|
||||
foreach (['gif', 'webp'] as $format) {
|
||||
$stored = $this->images->store($this->file($this->makeImage(40, 30, $format)), 7);
|
||||
$this->assertSame([40, 30], [$stored['width'], $stored['height']], $format);
|
||||
}
|
||||
}
|
||||
|
||||
public function testExifOrientationIsApplied(): void
|
||||
{
|
||||
// A landscape JPEG that says "rotate by 90°" ends up as a portrait picture.
|
||||
$jpeg = (string)file_get_contents($this->makeImage(200, 100));
|
||||
$path = $this->makeImage(1, 1);
|
||||
file_put_contents($path, substr($jpeg, 0, 2) . $this->exifOrientation(6) . substr($jpeg, 2));
|
||||
|
||||
$this->assertSame(6, ImageService::jpegOrientation((string)file_get_contents($path)));
|
||||
$stored = $this->images->store($this->file($path), 7);
|
||||
|
||||
$this->assertSame([100, 200], [$stored['width'], $stored['height']]);
|
||||
}
|
||||
|
||||
public function testJpegWithoutExifIsUpright(): void
|
||||
{
|
||||
$this->assertSame(1, ImageService::jpegOrientation((string)file_get_contents($this->makeImage(20, 10))));
|
||||
$this->assertSame(1, ImageService::jpegOrientation('not a jpeg'));
|
||||
}
|
||||
|
||||
public function testRejectsNonImages(): void
|
||||
{
|
||||
$path = tempnam(sys_get_temp_dir(), 'plen');
|
||||
$this->imageFiles[] = $path;
|
||||
file_put_contents($path, '<?php echo 1;');
|
||||
|
||||
$this->expectException(ImageException::class);
|
||||
$this->images->store($this->file($path), 7);
|
||||
}
|
||||
|
||||
public function testRejectsSvg(): void
|
||||
{
|
||||
$path = tempnam(sys_get_temp_dir(), 'plen');
|
||||
$this->imageFiles[] = $path;
|
||||
file_put_contents($path, '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><script>alert(1)</script></svg>');
|
||||
|
||||
$this->expectException(ImageException::class);
|
||||
$this->images->store($this->file($path), 7);
|
||||
}
|
||||
|
||||
public function testRejectsAnimatedGif(): void
|
||||
{
|
||||
$header = 'GIF89a' . "\x01\x00\x01\x00" . "\x80\x00\x00" . "\x00\x00\x00\xFF\xFF\xFF";
|
||||
$frame = "\x21\xF9\x04\x00\x0A\x00\x00\x00" . "\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00" . "\x02\x02\x44\x01\x00";
|
||||
$path = tempnam(sys_get_temp_dir(), 'plen');
|
||||
$this->imageFiles[] = $path;
|
||||
file_put_contents($path, $header . $frame . $frame . "\x3B");
|
||||
|
||||
$this->expectException(ImageException::class);
|
||||
$this->expectExceptionMessage('Animierte GIFs');
|
||||
$this->images->store($this->file($path), 7);
|
||||
}
|
||||
|
||||
public function testRejectsUploadErrors(): void
|
||||
{
|
||||
$path = $this->makeImage();
|
||||
|
||||
$this->expectException(ImageException::class);
|
||||
$this->images->store($this->file($path, UPLOAD_ERR_PARTIAL), 7);
|
||||
}
|
||||
|
||||
public function testDeleteCopyAndPollCleanup(): void
|
||||
{
|
||||
$first = $this->images->store($this->file($this->makeImage()), 7)['name'];
|
||||
$copy = $this->images->copy(7, $first);
|
||||
|
||||
$this->assertNotNull($copy);
|
||||
$this->assertNotSame($first, $copy);
|
||||
$this->assertCount(2, $this->storedImages(7));
|
||||
|
||||
$this->images->delete(7, $first);
|
||||
$this->images->delete(7, $first);
|
||||
$this->images->delete(7, null);
|
||||
$this->images->delete(7, '../../evil.php');
|
||||
$this->assertSame([$copy], $this->storedImages(7));
|
||||
$this->assertNull($this->images->copy(7, $first), 'copy of a missing file');
|
||||
|
||||
$this->images->deletePoll(7);
|
||||
$this->images->deletePoll(7);
|
||||
$this->assertSame([], $this->storedImages(7));
|
||||
$this->assertDirectoryDoesNotExist($this->uploadRoot() . DS . '7');
|
||||
}
|
||||
|
||||
public function testPathRejectsForeignNames(): void
|
||||
{
|
||||
$name = $this->images->store($this->file($this->makeImage()), 7)['name'];
|
||||
|
||||
$this->assertNotNull($this->images->path(7, $name));
|
||||
$this->assertNull($this->images->path(8, $name), 'other poll');
|
||||
$this->assertNull($this->images->path(7, '../7/' . $name));
|
||||
$this->assertNull($this->images->path(7, 'image.php'));
|
||||
}
|
||||
|
||||
public function testCleanupRemovesOrphansOnly(): void
|
||||
{
|
||||
$kept = $this->images->store($this->file($this->makeImage()), 7)['name'];
|
||||
$orphan = $this->images->store($this->file($this->makeImage()), 7)['name'];
|
||||
$gone = $this->images->store($this->file($this->makeImage()), 8)['name'];
|
||||
|
||||
$this->assertEqualsCanonicalizing(['7/' . $orphan, '8/' . $gone], $this->images->cleanup([7 => [$kept]], true));
|
||||
$this->assertCount(2, $this->storedImages(7), 'dry run deletes nothing');
|
||||
|
||||
$removed = $this->images->cleanup([7 => [$kept]]);
|
||||
|
||||
$this->assertEqualsCanonicalizing(['7/' . $orphan, '8/' . $gone], $removed);
|
||||
$this->assertSame([$kept], $this->storedImages(7));
|
||||
$this->assertSame([], $this->storedImages(8));
|
||||
$this->assertSame([], $this->images->cleanup([7 => [$kept]]), 'second run changes nothing');
|
||||
}
|
||||
|
||||
/**
|
||||
* An Exif segment (big endian) that only contains the orientation.
|
||||
*
|
||||
* @param int $orientation 1-8
|
||||
* @return string
|
||||
*/
|
||||
protected function exifOrientation(int $orientation): string
|
||||
{
|
||||
$tiff = "MM\x00\x2A\x00\x00\x00\x08" . "\x00\x01" . "\x01\x12\x00\x03\x00\x00\x00\x01" . pack('n', $orientation) . "\x00\x00" . "\x00\x00\x00\x00";
|
||||
|
||||
return "\xFF\xE1" . pack('n', 2 + 6 + strlen($tiff)) . "Exif\x00\x00" . $tiff;
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,22 @@ class QuizTest extends TestCase
|
||||
$this->assertSame(Slide::QUIZ_FINISHED, $slide->quizPhase());
|
||||
}
|
||||
|
||||
public function testReadyQuizHidesAnswerOptions(): void
|
||||
{
|
||||
[$poll, $slide] = $this->createQuiz();
|
||||
|
||||
$results = (new ResultsService())->forSlide($slide);
|
||||
$this->assertSame('ready', $results['phase']);
|
||||
$this->assertSame([], $results['options']);
|
||||
|
||||
$state = $this->participantState($poll, 'p1');
|
||||
$this->assertStringNotContainsString('Berlin', (string)json_encode($state));
|
||||
|
||||
$slide = $this->setOpen($slide, true);
|
||||
$results = (new ResultsService())->forSlide($slide);
|
||||
$this->assertSame(['Berlin', 'Hamburg', 'München'], array_column($results['options'], 'label'));
|
||||
}
|
||||
|
||||
public function testRunningQuizHidesCountsAndCorrectAnswers(): void
|
||||
{
|
||||
[$poll, $slide] = $this->createQuiz();
|
||||
|
||||
@@ -34,6 +34,9 @@ if (empty($_SERVER['HTTP_HOST']) && !Configure::read('App.fullBaseUrl')) {
|
||||
Configure::write('App.fullBaseUrl', 'http://localhost');
|
||||
}
|
||||
|
||||
// Slide images of the tests never touch the real upload directory.
|
||||
Configure::write('Plenario.images.path', TMP . 'tests-images');
|
||||
|
||||
// Fixate now to avoid one-second-leap-issues
|
||||
Chronos::setTestNow(Chronos::now());
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 876 B |
@@ -154,6 +154,15 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; }
|
||||
.card--accent { background: var(--primary-soft); border-color: transparent; }
|
||||
.card--danger h2 { color: var(--danger); }
|
||||
|
||||
/* Collapsible card: <details class="card collapsible"><summary><h2>…</h2></summary>…</details> */
|
||||
.collapsible > summary { display: flex; align-items: center; justify-content: space-between; gap: 12px; cursor: pointer; list-style: none; }
|
||||
.collapsible > summary::-webkit-details-marker { display: none; }
|
||||
.collapsible > summary::after { content: "▾"; color: var(--muted); font-size: 1.5em; line-height: 0; transition: transform .15s; }
|
||||
.collapsible:not([open]) > summary::after { transform: rotate(-90deg); }
|
||||
.collapsible > summary h2 { margin: 0; }
|
||||
.collapsible[open] > summary { margin: 0 -24px 16px; padding: 0 24px 12px; border-bottom: 1px solid var(--border); }
|
||||
.collapsible > summary:focus-visible { outline: 2px solid var(--primary); outline-offset: 4px; border-radius: 6px; }
|
||||
|
||||
.hero { text-align: center; max-width: 760px; margin: 16px auto 40px; }
|
||||
.hero h1 { font-size: clamp(1.9rem, 4.5vw, 3rem); }
|
||||
|
||||
@@ -177,6 +186,16 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; }
|
||||
.button:disabled { opacity: .6; cursor: wait; }
|
||||
.button--primary { background: var(--primary); border-color: var(--primary); color: var(--primary-ink); }
|
||||
.button--primary:hover { filter: brightness(1.08); }
|
||||
/* Split button: main action plus a menu with further views (Präsentieren ▾ → Referentenansicht). */
|
||||
.split { position: relative; display: inline-flex; }
|
||||
.split__main { border-top-right-radius: 0; border-bottom-right-radius: 0; }
|
||||
.split__toggle { border-top-left-radius: 0; border-bottom-left-radius: 0; border-left-color: rgba(255, 255, 255, .35); padding-inline: 8px; }
|
||||
.split__toggle > span[aria-hidden] { font-size: 1.5em; line-height: 0; }
|
||||
.split__menu { position: absolute; top: calc(100% + 4px); left: 0; z-index: 20; min-width: 260px; max-width: min(340px, 90vw); padding: 4px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); }
|
||||
.split__menu[hidden] { display: none; }
|
||||
.split__item { display: block; padding: 10px 12px; border-radius: 8px; color: var(--text); text-decoration: none; }
|
||||
.split__item:hover, .split__item:focus-visible { background: var(--primary-soft); }
|
||||
.split__item small { display: block; margin-top: 2px; color: var(--muted); font-size: .8rem; }
|
||||
.button--danger { color: var(--danger); }
|
||||
.button--danger:hover { border-color: var(--danger); }
|
||||
.button--ghost { border-color: transparent; background: transparent; }
|
||||
@@ -678,6 +697,27 @@ body.present {
|
||||
--star: #d48500;
|
||||
--star-empty: #c3c8da;
|
||||
}
|
||||
/* Speaker view (second window): current slide left, preview of the next one right. */
|
||||
.stage--speaker { grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); grid-template-rows: auto 1fr auto; column-gap: 3vw; }
|
||||
.stage--speaker > .stage__top, .stage--speaker > .stage__controls { grid-column: 1 / -1; }
|
||||
.stage--speaker .stage__question { font-size: clamp(1.5rem, 3vw, 2.6rem); }
|
||||
.stage--speaker .stage__description { font-size: clamp(1rem, 1.5vw, 1.3rem); }
|
||||
.stage--speaker .stage__results { font-size: clamp(.9rem, 1.3vw, 1.2rem); }
|
||||
.stage--speaker > .stage__main { align-self: stretch; padding: 2vh 2vw; border: 2px solid var(--c1); border-radius: 12px; }
|
||||
.stage--speaker > .stage__main > .stage__label { color: var(--c1); }
|
||||
.stage__next { align-self: stretch; max-height: 100%; overflow: auto; padding: 2vh 2vw; border: 2px dashed rgba(var(--tint), .3); border-radius: 12px; background: rgba(var(--tint), .05); }
|
||||
.stage__label { text-transform: uppercase; letter-spacing: .12em; color: var(--muted); font-weight: 700; font-size: .85rem; margin: 0 0 .6em; }
|
||||
.stage__next-question { font-size: clamp(1.2rem, 2.2vw, 2rem); margin: 0 0 .4em; }
|
||||
.stage__next-description { color: var(--muted); font-size: clamp(.95rem, 1.3vw, 1.15rem); margin: 0 0 .8em; }
|
||||
.stage__next-description:empty, .stage__next-options:empty, .stage__next-note:empty { display: none; }
|
||||
.stage__next-options { margin: 0 0 .8em; padding-left: 1.2em; font-size: clamp(.95rem, 1.3vw, 1.15rem); }
|
||||
.stage__next-note { margin: 0; font-size: .9rem; }
|
||||
.stage__next--end .stage__next-question { color: var(--muted); font-weight: 400; }
|
||||
@media (max-width: 800px) {
|
||||
body.present:has(.stage--speaker) { overflow: auto; }
|
||||
.stage--speaker { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto auto auto auto; height: auto; min-height: 100vh; }
|
||||
.stage__next { align-self: stretch; margin-bottom: 2vh; }
|
||||
}
|
||||
.stage__top { display: flex; justify-content: space-between; align-items: center; gap: 16px; font-size: clamp(1rem, 1.6vw, 1.4rem); color: var(--muted); }
|
||||
.stage__top strong { color: var(--text); }
|
||||
.stage__code { letter-spacing: .12em; background: rgba(var(--tint), .1); padding: 2px 10px; border-radius: 8px; }
|
||||
@@ -694,6 +734,19 @@ body.present {
|
||||
.stage--video .stage__description { font-size: clamp(1rem, 1.6vw, 1.3rem); }
|
||||
.stage--content .stage__description { color: var(--text); font-size: clamp(1.3rem, 2.6vw, 2.2rem); }
|
||||
.stage__results { font-size: clamp(1rem, 1.8vw, 1.5rem); margin-top: 2vh; }
|
||||
/* slide images: above the results (default), next to the text (side) or as large as possible (full) */
|
||||
.stage__image { margin: 1vh auto 0; }
|
||||
.stage__image img { display: block; max-width: 100%; max-height: 38vh; width: auto; height: auto; margin: 0 auto; object-fit: contain; border-radius: 8px; }
|
||||
.stage--img-side .stage__main { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); grid-auto-rows: min-content; align-content: center; column-gap: 4vw; }
|
||||
.stage--img-side .stage__main > * { grid-column: 2; }
|
||||
.stage--img-side .stage__main > .stage__image { grid-column: 1; grid-row: 1 / span 5; align-self: center; margin: 0; }
|
||||
.stage--img-side .stage__image img { max-height: 68vh; }
|
||||
.stage--img-full .stage__image img { max-height: 66vh; }
|
||||
.stage--img-full .stage__question { font-size: clamp(1.5rem, 3vw, 2.6rem); }
|
||||
@media (max-width: 800px) {
|
||||
.stage--img-side .stage__main { display: flex; }
|
||||
.stage--img-side .stage__image img { max-height: 38vh; }
|
||||
}
|
||||
.stage .bar__track { height: 1.1em; }
|
||||
/* scale on stage: big average next to a compact donut */
|
||||
.stage .scale-results__row { gap: 2vw; }
|
||||
@@ -779,3 +832,16 @@ body.present {
|
||||
body:has(dialog[open]) { overflow: hidden; }
|
||||
.slide-item__actions form { display: contents; }
|
||||
.slide-item__actions button:disabled, .admin-head__actions button:disabled { opacity: .6; cursor: progress; }
|
||||
|
||||
/* slide images: participant page and slide form */
|
||||
.slide-image { margin: 1em 0; }
|
||||
.slide-image img { display: block; max-width: 100%; height: auto; margin: 0 auto; border-radius: 8px; }
|
||||
.image-fields, .image-fields__layout { border: 0; padding: 0; margin: 0 0 16px; min-width: 0; }
|
||||
.image-fields > legend { font-weight: 600; padding: 0; margin-bottom: .5em; }
|
||||
.image-fields__layout > legend { padding: 0; margin-bottom: .25em; }
|
||||
.image-fields__current { margin: 0 0 .75em; }
|
||||
.image-fields__current.is-removed img { opacity: .3; filter: grayscale(1); }
|
||||
.image-fields__remove { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; margin: 0 0 1em; }
|
||||
.image-fields__remove .button { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.image-fields__remove .hint { margin: 0; }
|
||||
.image-fields__current img { display: block; max-width: 100%; max-height: 180px; width: auto; height: auto; border-radius: 6px; }
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 2.1 KiB |
@@ -0,0 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
|
||||
<title>PlenarIO</title>
|
||||
<clipPath id="r"><rect width="32" height="32" rx="8.73"/></clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<path fill="#4b3fe0" d="M16 16 L16 -8 A24 24 0 0 1 30.107 35.416 Z"/>
|
||||
<path fill="#e0457b" d="M16 16 L30.107 35.416 A24 24 0 0 1 -3.416 30.107 Z"/>
|
||||
<path fill="#12a08a" d="M16 16 L-3.416 30.107 A24 24 0 0 1 -3.416 1.893 Z"/>
|
||||
<path fill="#f29a1f" d="M16 16 L-3.416 1.893 A24 24 0 0 1 16 -8 Z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 531 B |
+194
-3
@@ -610,7 +610,7 @@
|
||||
|
||||
choice: function (results) {
|
||||
var max = Math.max.apply(null, results.options.map(function (o) { return o.count; }).concat([1]));
|
||||
return el('div', { class: 'bars' }, results.options.map(function (option, index) {
|
||||
var bars = el('div', { class: 'bars' }, results.options.map(function (option, index) {
|
||||
return el('div', { class: 'bar bar--c' + (index % 6) }, [
|
||||
el('div', { class: 'bar__label', text: option.label }),
|
||||
el('div', { class: 'bar__track' }, [
|
||||
@@ -619,6 +619,10 @@
|
||||
el('div', { class: 'bar__value', text: formatNumber(option.percent) + ' % (' + option.count + ')' })
|
||||
]);
|
||||
}));
|
||||
if (!results.comments || !results.comments.length) {
|
||||
return bars;
|
||||
}
|
||||
return el('div', { class: 'choice-results' }, [bars, Comments.render(results.comments, String)]);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -892,7 +896,8 @@
|
||||
} else if (results.phase === 'running') {
|
||||
children.push(el('p', { class: 'quiz-status', text: 'Quiz läuft – ohne Zeitlimit' }));
|
||||
} else {
|
||||
children.push(el('p', { class: 'quiz-status', text: 'Bereit – starte das Quiz, um die Antworten freizugeben' }));
|
||||
children.push(el('p', { class: 'quiz-status', text: 'Bereit – die Antworten erscheinen, sobald das Quiz gestartet wird' }));
|
||||
return el('div', { class: 'quiz-results quiz-results--' + results.phase }, children);
|
||||
}
|
||||
children.push(el('ol', { class: 'quiz-grid' }, results.options.map(function (option, index) {
|
||||
return el('li', { class: 'quiz-tile quiz-tile--c' + (index % 6), text: option.label });
|
||||
@@ -1283,11 +1288,59 @@
|
||||
mediaKey = key;
|
||||
media.textContent = '';
|
||||
media.hidden = !video;
|
||||
if (video) {
|
||||
if (video && root.classList.contains('stage--speaker')) {
|
||||
// Speaker view never loads the player: the video plays in the presentation window only (no double audio).
|
||||
media.appendChild(el('p', {class: 'stage__media-note muted', text: 'Das Video wird nur im Präsentationsfenster abgespielt.'}));
|
||||
} else if (video) {
|
||||
media.appendChild(youtubeFrame(video.embedUrl, slide.question));
|
||||
}
|
||||
}
|
||||
|
||||
/** Shows the image of the slide (layout: top | side | full via stage--img-* classes); the <img> stays while the file stays. */
|
||||
function renderImage(slide) {
|
||||
var figure = q('[data-image]');
|
||||
var image = slide && slide.image ? slide.image : null;
|
||||
['top', 'side', 'full'].forEach(function (layout) {
|
||||
root.classList.toggle('stage--img-' + layout, !!image && image.layout === layout);
|
||||
});
|
||||
figure.hidden = !image;
|
||||
if (!image) {
|
||||
figure.textContent = '';
|
||||
return;
|
||||
}
|
||||
var img = figure.querySelector('img');
|
||||
if (!img) {
|
||||
img = document.createElement('img');
|
||||
figure.appendChild(img);
|
||||
}
|
||||
if (img.getAttribute('src') !== image.url) {
|
||||
img.setAttribute('src', image.url);
|
||||
}
|
||||
img.setAttribute('alt', image.alt || '');
|
||||
if (image.width && image.height) {
|
||||
img.setAttribute('width', image.width);
|
||||
img.setAttribute('height', image.height);
|
||||
}
|
||||
}
|
||||
|
||||
/** Speaker view: preview of the slide that "next" will show (labels only, the server sends no solutions). */
|
||||
function renderNext(next) {
|
||||
var box = q('[data-next]');
|
||||
if (!box) {
|
||||
return;
|
||||
}
|
||||
var options = q('[data-next-options]');
|
||||
options.textContent = '';
|
||||
setText('[data-next-meta]', next ? '· ' + next.typeLabel : '');
|
||||
setText('[data-next-question]', next ? next.question : 'Das war die letzte Folie');
|
||||
Format.render(q('[data-next-description]'), next ? next.description : '');
|
||||
(next ? next.options : []).forEach(function (label) {
|
||||
options.appendChild(el('li', { text: label }));
|
||||
});
|
||||
setText('[data-next-note]', next && next.hasImage ? 'Die Folie enthält ein Bild.' : '');
|
||||
box.classList.toggle('stage__next--end', !next);
|
||||
}
|
||||
|
||||
function render(newState) {
|
||||
var serialized = JSON.stringify(newState);
|
||||
if (serialized === last) {
|
||||
@@ -1296,6 +1349,7 @@
|
||||
last = serialized;
|
||||
state = newState;
|
||||
var slide = state.slide;
|
||||
renderNext(state.next);
|
||||
|
||||
setText('[data-counter]', state.count === 0
|
||||
? '0 / 0'
|
||||
@@ -1327,6 +1381,7 @@
|
||||
: 'Drücke → um zu starten.');
|
||||
q('[data-results]').innerHTML = '';
|
||||
renderMedia(null);
|
||||
renderImage(null);
|
||||
root.classList.remove('stage--video');
|
||||
q('[data-voting]').hidden = true;
|
||||
setText('[data-participants]', '');
|
||||
@@ -1347,6 +1402,7 @@
|
||||
root.classList.toggle('stage--content', !slide.isInteractive);
|
||||
root.classList.toggle('stage--video', slide.type === 'youtube');
|
||||
renderMedia(slide);
|
||||
renderImage(slide);
|
||||
root.classList.toggle('stage--closed', closed);
|
||||
root.classList.toggle('stage--qa', !!qaStage);
|
||||
|
||||
@@ -2198,6 +2254,33 @@
|
||||
|
||||
// ------------------------------------------------------------------ slide form
|
||||
|
||||
/** Slide image: a trash button toggles the "remove image" checkbox (the checkbox stays for use without JavaScript). */
|
||||
function initImageRemove(box) {
|
||||
var checkbox = box.querySelector('input[type="checkbox"]');
|
||||
var button = box.querySelector('[data-image-remove-button]');
|
||||
var status = box.querySelector('[data-image-remove-status]');
|
||||
var figure = box.parentNode.querySelector('.image-fields__current');
|
||||
if (!checkbox || !button) {
|
||||
return;
|
||||
}
|
||||
var field = checkbox.closest('.input');
|
||||
if (field) {
|
||||
field.hidden = true;
|
||||
}
|
||||
button.hidden = false;
|
||||
button.addEventListener('click', function () {
|
||||
checkbox.checked = !checkbox.checked;
|
||||
button.setAttribute('aria-pressed', checkbox.checked ? 'true' : 'false');
|
||||
button.querySelector('[data-label]').textContent = button.getAttribute(checkbox.checked ? 'data-label-undo' : 'data-label-remove');
|
||||
if (figure) {
|
||||
figure.classList.toggle('is-removed', checkbox.checked);
|
||||
}
|
||||
if (status) {
|
||||
status.textContent = checkbox.checked ? 'Das Bild wird beim Speichern entfernt.' : '';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Quiz slide form: add further answer rows (the server renders a few already). */
|
||||
function initQuizOptions(fieldset) {
|
||||
var list = fieldset.querySelector('[data-quiz-list]');
|
||||
@@ -2643,12 +2726,63 @@
|
||||
}
|
||||
}
|
||||
|
||||
function currentSlideId() {
|
||||
var current = document.querySelector('.slide-item--current');
|
||||
return current ? current.getAttribute('data-slide-id') : null;
|
||||
}
|
||||
|
||||
/** Scrolls the live slide into view if it is outside (no movement if it is already visible). */
|
||||
function revealCurrent() {
|
||||
var current = document.querySelector('.slide-item--current');
|
||||
if (current) {
|
||||
var calm = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
current.scrollIntoView({ block: 'nearest', behavior: calm ? 'auto' : 'smooth' });
|
||||
}
|
||||
}
|
||||
|
||||
function refreshList() {
|
||||
return Fragments.request(window.location.href).then(function (doc) {
|
||||
Fragments.apply(doc, ['head', 'slides']);
|
||||
});
|
||||
}
|
||||
|
||||
// The presenter (other window, clicker) moves the live marker: poll a cheap fingerprint
|
||||
// and reload the lists when it changes. Own actions already refresh, so they skip one round.
|
||||
var liveRoot = document.querySelector('[data-dashboard-live]');
|
||||
var liveVersion = null;
|
||||
if (liveRoot) {
|
||||
poll(function () {
|
||||
if ((dialog && dialog.open) || document.querySelector('[data-live] [aria-busy], .slide-item--dragging')) {
|
||||
return null; // never replace the DOM under a dialog, a pending request or a drag
|
||||
}
|
||||
return getJson(liveRoot.getAttribute('data-dashboard-live')).then(function (state) {
|
||||
var previous = liveVersion;
|
||||
liveVersion = state.version;
|
||||
if (previous === null || previous === state.version) {
|
||||
return null;
|
||||
}
|
||||
var active = document.activeElement;
|
||||
var item = active && active.closest ? active.closest('[data-slide-id]') : null;
|
||||
var form = active && active.closest ? active.closest('form') : null;
|
||||
var next = item ? item.nextElementSibling : null;
|
||||
var target = item ? {
|
||||
id: item.getAttribute('data-slide-id'),
|
||||
action: form ? form.getAttribute('action') : null,
|
||||
nextId: next ? next.getAttribute('data-slide-id') : null
|
||||
} : null;
|
||||
|
||||
var liveBefore = currentSlideId();
|
||||
return refreshList().then(function () {
|
||||
restoreFocus(target);
|
||||
// The presenter moved on: keep the live slide in view on long lists.
|
||||
if (currentSlideId() !== liveBefore) {
|
||||
revealCurrent();
|
||||
}
|
||||
});
|
||||
});
|
||||
}, Math.max(4000, parseInt(liveRoot.getAttribute('data-interval'), 10) * 2 || 4000));
|
||||
}
|
||||
|
||||
function openModal(doc) {
|
||||
var content = doc.querySelector('[data-modal-content]');
|
||||
var flash = doc.querySelector('[data-refresh="flash"]');
|
||||
@@ -2685,6 +2819,7 @@
|
||||
return wasOpen ? null : refreshList();
|
||||
}
|
||||
Fragments.apply(doc);
|
||||
liveVersion = null; // the next poll only takes the new fingerprint
|
||||
if (dialog && dialog.open) {
|
||||
dirty = false;
|
||||
dialog.close();
|
||||
@@ -2786,6 +2921,7 @@
|
||||
initCopy(root);
|
||||
root.querySelectorAll('[data-youtube-form]').forEach(initYouTubeForm);
|
||||
root.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions);
|
||||
root.querySelectorAll('[data-image-remove]').forEach(initImageRemove);
|
||||
root.querySelectorAll('[data-sortable]').forEach(initSortable);
|
||||
root.querySelectorAll('[data-order-options]').forEach(initOrderOptions);
|
||||
root.querySelectorAll('[data-scale-style]').forEach(initScaleStyle);
|
||||
@@ -2799,6 +2935,61 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Collapsible dashboard cards (<details class="collapsible">): in-page links like #export open their closed card.
|
||||
function openCollapsible(hash) {
|
||||
var target = hash && hash.length > 1 ? document.getElementById(decodeURIComponent(hash.slice(1))) : null;
|
||||
var card = target && target.closest ? target.closest('details.collapsible') : null;
|
||||
if (card && !card.open) {
|
||||
card.open = true;
|
||||
}
|
||||
}
|
||||
document.addEventListener('click', function (event) {
|
||||
var link = event.target.closest ? event.target.closest('a[href^="#"]') : null;
|
||||
if (link) {
|
||||
openCollapsible(link.getAttribute('href'));
|
||||
}
|
||||
});
|
||||
window.addEventListener('hashchange', function () { openCollapsible(window.location.hash); });
|
||||
openCollapsible(window.location.hash);
|
||||
|
||||
// Split button menus ([data-menu-toggle] + [data-menu]). Delegated: the dashboard head is replaced on live refresh.
|
||||
function closeMenus(except) {
|
||||
document.querySelectorAll('[data-menu]').forEach(function (menu) {
|
||||
var toggle = menu.parentNode.querySelector('[data-menu-toggle]');
|
||||
if (!menu.hidden && menu !== except) {
|
||||
menu.hidden = true;
|
||||
toggle.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
});
|
||||
}
|
||||
document.addEventListener('click', function (event) {
|
||||
var toggle = event.target.closest ? event.target.closest('[data-menu-toggle]') : null;
|
||||
if (!toggle) {
|
||||
closeMenus(null); // outside click or a click on a menu item
|
||||
return;
|
||||
}
|
||||
var menu = toggle.parentNode.querySelector('[data-menu]');
|
||||
closeMenus(menu);
|
||||
menu.hidden = !menu.hidden;
|
||||
toggle.setAttribute('aria-expanded', menu.hidden ? 'false' : 'true');
|
||||
if (!menu.hidden) {
|
||||
var first = menu.querySelector('a, button');
|
||||
if (first) {
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', function (event) {
|
||||
if (event.key !== 'Escape') {
|
||||
return;
|
||||
}
|
||||
var open = document.querySelector('[data-menu]:not([hidden])');
|
||||
if (open) {
|
||||
closeMenus(null);
|
||||
open.parentNode.querySelector('[data-menu-toggle]').focus();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
document.querySelectorAll('[data-theme-switch]').forEach(initThemeSwitch);
|
||||
initWidgets(document);
|
||||
|
||||
Reference in new issue
Block a user