Add initial Plenario live polling app
CakePHP 5.4 app for live polls: create via email without login, manage via secret admin link, join via code. Includes slide types (choice, wordcloud, open, scale, content), presenter mode, CSV export, captcha, throttling, tests and Gitea CI/deploy workflow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
eb319f8c1e
120 files changed
+15572
No files matched your search
@@ -0,0 +1,26 @@
|
||||
; This file is for unifying the coding style for different editors and IDEs.
|
||||
; More information at https://editorconfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.bat]
|
||||
end_of_line = crlf
|
||||
|
||||
[*.yml]
|
||||
indent_size = 2
|
||||
|
||||
[*.twig]
|
||||
insert_final_newline = false
|
||||
|
||||
[*.neon]
|
||||
indent_style = tab
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
@@ -0,0 +1,36 @@
|
||||
# Define the line ending behavior of the different file extensions
|
||||
# Set default behavior, in case users don't have core.autocrlf set.
|
||||
* text text=auto eol=lf
|
||||
|
||||
# Declare files that will always have CRLF line endings on checkout.
|
||||
*.bat eol=crlf
|
||||
|
||||
# Declare files that will always have LF line endings on checkout.
|
||||
*.pem eol=lf
|
||||
|
||||
# Denote all files that are truly binary and should not be modified.
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.webp binary
|
||||
*.avif binary
|
||||
*.ico binary
|
||||
*.mo binary
|
||||
*.pdf binary
|
||||
*.xls binary
|
||||
*.xlsx binary
|
||||
*.phar binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.ttc binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.eot binary
|
||||
*.gz binary
|
||||
*.bz2 binary
|
||||
*.7z binary
|
||||
*.zip binary
|
||||
*.webm binary
|
||||
*.mp4 binary
|
||||
*.ogv binary
|
||||
@@ -0,0 +1,146 @@
|
||||
# CI + Deployment (Gitea Actions, GitHub Actions compatible).
|
||||
#
|
||||
# - test: runs on every push to any branch. Its commit status is what the branch
|
||||
# protection of main requires, so a PR can only be merged once the tests are green.
|
||||
# - deploy: runs only on push to main (i.e. after a merge), only if the tests are green and
|
||||
# ONLY if the repository variable DEPLOY_ENABLED is "true" (deactivated by default).
|
||||
#
|
||||
# Target: DirectAdmin hosting, app checked out directly into the domain's public_html
|
||||
# (the root .htaccess/index.php forward every request to webroot/).
|
||||
# The server pulls the code itself over HTTPS with the job's short-lived token, so no
|
||||
# deploy key and no stored credentials are needed on the server.
|
||||
#
|
||||
# Repository variables (Settings → Actions → Variables):
|
||||
# DEPLOY_ENABLED "true" to enable deployment (anything else = disabled)
|
||||
# SSH_HOST e.g. plenario.gnilebein.de
|
||||
# SSH_PORT optional, default 22
|
||||
# SSH_USER e.g. gnilebein.de
|
||||
# SSH_FINGERPRINT optional but recommended: SHA256 host key fingerprint (ssh-keygen -lf)
|
||||
# DEPLOY_PATH e.g. /home/gnilebein.de/domains/plenario.gnilebein.de/public_html
|
||||
# PHP_BIN optional, PHP CLI binary (default: auto-detect, must be >= 8.4)
|
||||
# COMPOSER_BIN optional, composer command (default: auto-detect, else composer.phar
|
||||
# is installed once to ~/.local/bin)
|
||||
# Repository secrets:
|
||||
# SSH_KEY private deploy key (preferred), or
|
||||
# SSH_PASSWORD password (fallback)
|
||||
#
|
||||
# One-time setup on the server: create config/.env (DEBUG=false, APP_FULL_BASE_URL,
|
||||
# SECURITY_SALT, mail settings – see config/.env.example). The deploy aborts without it.
|
||||
name: CI / Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.5'
|
||||
extensions: mbstring, intl, pdo_sqlite, sqlite3
|
||||
coverage: none
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --no-interaction --prefer-dist --no-progress
|
||||
|
||||
- name: Run tests
|
||||
run: vendor/bin/phpunit
|
||||
|
||||
- name: Coding standard
|
||||
run: vendor/bin/phpcs --warning-severity=0
|
||||
|
||||
deploy:
|
||||
needs: test
|
||||
# Deactivated until the repository variable DEPLOY_ENABLED is "true".
|
||||
if: vars.DEPLOY_ENABLED == 'true' && github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
concurrency:
|
||||
group: deploy-production
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- name: Deploy via SSH
|
||||
uses: appleboy/ssh-action@v1.0.3
|
||||
with:
|
||||
host: ${{ vars.SSH_HOST }}
|
||||
port: ${{ vars.SSH_PORT || 22 }}
|
||||
username: ${{ vars.SSH_USER }}
|
||||
key: ${{ secrets.SSH_KEY }}
|
||||
password: ${{ secrets.SSH_PASSWORD }}
|
||||
fingerprint: ${{ vars.SSH_FINGERPRINT }}
|
||||
script_stop: true
|
||||
script: |
|
||||
set -eu
|
||||
DEPLOY_PATH="${{ vars.DEPLOY_PATH }}"
|
||||
PHP="${{ vars.PHP_BIN }}"
|
||||
COMPOSER="${{ vars.COMPOSER_BIN }}"
|
||||
REPO_URL="${{ github.server_url }}/${{ github.repository }}.git"
|
||||
GIT_AUTH="Authorization: Basic $(printf 'oauth2:%s' '${{ github.token }}' | base64 | tr -d '\n')"
|
||||
|
||||
if [ -z "$DEPLOY_PATH" ] || [ ! -d "$DEPLOY_PATH" ]; then
|
||||
echo "DEPLOY_PATH is not set or does not exist: '$DEPLOY_PATH'" >&2
|
||||
exit 1
|
||||
fi
|
||||
cd "$DEPLOY_PATH"
|
||||
|
||||
# --- PHP ---------------------------------------------------------------
|
||||
if [ -z "$PHP" ]; then
|
||||
for candidate in /usr/local/php85/bin/php /usr/local/php84/bin/php /usr/local/bin/php php; do
|
||||
if command -v "$candidate" >/dev/null 2>&1 \
|
||||
&& "$candidate" -r 'exit(PHP_VERSION_ID >= 80400 ? 0 : 1);'; then
|
||||
PHP="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if [ -z "$PHP" ]; then
|
||||
echo "No PHP >= 8.4 found – set the repository variable PHP_BIN." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Using PHP: $PHP ($("$PHP" -r 'echo PHP_VERSION;'))"
|
||||
|
||||
# --- Composer (installed once, verified against the official checksum) --
|
||||
if [ -z "$COMPOSER" ]; then
|
||||
if command -v composer >/dev/null 2>&1; then
|
||||
COMPOSER="$PHP $(command -v composer)"
|
||||
else
|
||||
PHAR="$HOME/.local/bin/composer.phar"
|
||||
if [ ! -f "$PHAR" ]; then
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
EXPECTED="$(curl -fsSL https://composer.github.io/installer.sig)"
|
||||
curl -fsSL https://getcomposer.org/installer -o /tmp/composer-setup.php
|
||||
ACTUAL="$("$PHP" -r "echo hash_file('sha384', '/tmp/composer-setup.php');")"
|
||||
if [ "$EXPECTED" != "$ACTUAL" ]; then
|
||||
rm -f /tmp/composer-setup.php
|
||||
echo "Composer installer checksum mismatch" >&2
|
||||
exit 1
|
||||
fi
|
||||
"$PHP" /tmp/composer-setup.php --quiet --install-dir="$HOME/.local/bin" --filename=composer.phar
|
||||
rm -f /tmp/composer-setup.php
|
||||
fi
|
||||
COMPOSER="$PHP $PHAR"
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- Code: first run initialises the checkout, later runs update it -----
|
||||
if [ ! -d .git ]; then
|
||||
git init -q
|
||||
git remote add origin "$REPO_URL"
|
||||
fi
|
||||
git remote set-url origin "$REPO_URL"
|
||||
git -c "http.extraHeader=$GIT_AUTH" fetch --quiet origin '+refs/heads/main:refs/remotes/origin/main'
|
||||
git reset --hard origin/main
|
||||
echo "Deployed commit: $(git rev-parse --short HEAD)"
|
||||
|
||||
if [ ! -f config/.env ]; then
|
||||
echo "config/.env is missing – create it once on the server (see config/.env.example)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
$COMPOSER install --no-dev --optimize-autoloader --no-interaction --no-progress
|
||||
"$PHP" bin/cake.php migrations migrate
|
||||
"$PHP" bin/cake.php cache clear_all
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
# CakePHP specific files #
|
||||
##########################
|
||||
/config/app_local.php
|
||||
/config/.env
|
||||
/.env
|
||||
/logs/*
|
||||
/tmp/*
|
||||
/vendor/*
|
||||
/plugins/*/vendor/
|
||||
# Plugin-Assets, die per `bin/cake plugin assets symlink|copy` entstehen
|
||||
/webroot/debug_kit
|
||||
/webroot/bake
|
||||
# SQLite-Backups aus der Deploy-Pipeline
|
||||
/data/backups/
|
||||
# Composer
|
||||
/composer.phar
|
||||
# Test-/Analyse-Artefakte
|
||||
/coverage/
|
||||
/build/
|
||||
/.phpstan/
|
||||
/.psalm/
|
||||
|
||||
# Migrations Lock-Datei (wird zur Laufzeit generiert)
|
||||
/config/Migrations/schema-dump-default.lock
|
||||
|
||||
# Gecachte Assets (werden on-the-fly generiert)
|
||||
/webroot/cache_css/*
|
||||
/webroot/cache_js/*
|
||||
|
||||
# Uploads / User-Dateien (falls genutzt)
|
||||
/webroot/files/*
|
||||
/files/*
|
||||
|
||||
# Claude AI
|
||||
.claude/
|
||||
CLAUDE.local.md
|
||||
|
||||
# OS generated files #
|
||||
######################
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
Icon
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
.directory
|
||||
|
||||
# Tool specific files #
|
||||
#######################
|
||||
# PHPUnit
|
||||
.phpunit.cache
|
||||
.phpunit.result.cache
|
||||
tests.sqlite
|
||||
# vim
|
||||
*~
|
||||
*.swp
|
||||
*.swo
|
||||
# sublime text & textmate
|
||||
*.sublime-*
|
||||
*.stTheme.cache
|
||||
*.tmlanguage.cache
|
||||
*.tmPreferences.cache
|
||||
# Eclipse
|
||||
.settings/*
|
||||
# JetBrains
|
||||
.idea/*
|
||||
# NetBeans
|
||||
nbproject/*
|
||||
# Visual Studio Code
|
||||
.vscode
|
||||
# nova
|
||||
.nova
|
||||
# Sass preprocessor
|
||||
.sass-cache/
|
||||
# node
|
||||
/node_modules/*
|
||||
# yarn
|
||||
yarn-debug.log
|
||||
yarn-error.log
|
||||
|
||||
# PHP CS Fixer
|
||||
.php_cs.cache
|
||||
.php-cs-fixer.cache
|
||||
# Plenario: lokale SQLite-Datenbank und Mail-Dumps
|
||||
/data/*.sqlite
|
||||
/data/*.sqlite-journal
|
||||
/data/*.sqlite-wal
|
||||
/data/*.sqlite-shm
|
||||
@@ -0,0 +1,12 @@
|
||||
# Uncomment the following to prevent the httpoxy vulnerability
|
||||
# See: https://httpoxy.org/
|
||||
#<IfModule mod_headers.c>
|
||||
# RequestHeader unset Proxy
|
||||
#</IfModule>
|
||||
|
||||
<IfModule mod_rewrite.c>
|
||||
RewriteEngine on
|
||||
RewriteRule ^(\.well-known/.*)$ $1 [L]
|
||||
RewriteRule ^$ webroot/ [L]
|
||||
RewriteRule (.*) webroot/$1 [L]
|
||||
</IfModule>
|
||||
@@ -0,0 +1,159 @@
|
||||
# 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.
|
||||
Lokale, maschinenspezifische Infos gehören in `CLAUDE.local.md` (nicht versioniert).
|
||||
|
||||
## Rolle & Arbeitsweise
|
||||
|
||||
Du arbeitest in diesem Projekt als **Senior PHP-Entwickler** (CakePHP, modernes PHP 8) und
|
||||
**UI/UX-Experte** (zugängliche, klare, mobile-taugliche Oberflächen).
|
||||
|
||||
- **Idiomatisch:** Nutze die Mittel von CakePHP und PHP so, wie sie gedacht sind (ORM, Finder,
|
||||
Validatoren, Middleware, Helper, benannte Routen, Konventionen statt Eigenbau). Kein Workaround,
|
||||
wo das Framework eine Lösung bietet. Im Frontend: semantisches HTML, Vanilla JS, schlankes CSS.
|
||||
- **Idempotent:** Änderungen, Befehle, Migrationen, Seeds und Deploy-Schritte müssen sich gefahrlos
|
||||
mehrfach ausführen lassen und dabei dasselbe Ergebnis liefern (z. B. vorher prüfen statt blind
|
||||
anlegen, keine doppelten Einträge, wiederholte POSTs ohne Nebenwirkungen abfangen).
|
||||
- **UX zuerst mitdenken:** verständliche deutsche Texte, sinnvolle Fehlermeldungen, Tastatur- und
|
||||
Screenreader-Bedienbarkeit, ausreichende Kontraste, gute Darstellung auf Smartphone und Beamer.
|
||||
|
||||
## Projekt in einem Satz
|
||||
|
||||
Plenario ist ein Mentimeter-/Claper-ähnliches Live-Umfragetool auf **CakePHP 5.4**: Umfrage per
|
||||
E-Mail anlegen, kein Login, Verwaltung über einen geheimen Admin-Link, Teilnahme per Code.
|
||||
|
||||
## Befehle
|
||||
|
||||
| Zweck | Befehl |
|
||||
|---|---|
|
||||
| Abhängigkeiten | `composer install` |
|
||||
| Migrationen | `bin/cake migrations migrate` (Windows: `php bin/cake.php migrations migrate`) |
|
||||
| Dev-Server | `bin/cake server -p 8765` → http://localhost:8765 |
|
||||
| Tests | `vendor/bin/phpunit` |
|
||||
| Coding Standard | `vendor/bin/phpcs` / Autofix `vendor/bin/phpcbf` |
|
||||
| Neue Migration | `bin/cake bake migration NameDerMigration` |
|
||||
|
||||
**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).
|
||||
|
||||
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
|
||||
|
||||
```
|
||||
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)
|
||||
src/
|
||||
Captcha/ CaptchaInterface + NoCaptcha / MathCaptcha / RecaptchaCaptcha, CaptchaFactory
|
||||
Controller/
|
||||
HomeController Startseite, Anlegen (/create), Bestätigung, Join, Recover
|
||||
AdminAppController Basis für /admin/{token}: löst Poll über Token-Hash auf (404 sonst), setzt Privacy-Header
|
||||
AdminController Dashboard, Settings, Present, State-JSON, Control, QR, CSV-Export, Token rotieren, Löschen
|
||||
SlidesController Folien-CRUD, Sortieren, Antworten zurücksetzen
|
||||
ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid
|
||||
Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal)
|
||||
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')
|
||||
templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email
|
||||
webroot/css/plenario.css Eigenes CSS, kein Framework
|
||||
webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung
|
||||
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`, `show_results_to_participants`
|
||||
- `slides`: `type` (`choice|wordcloud|open|scale|content`), `question`, `description`, `position`,
|
||||
`settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open`
|
||||
- `slide_options`: Antwortoptionen für `choice`
|
||||
- `responses`: `participant_hash`, `slide_option_id` | `text_value` | `numeric_value`.
|
||||
Mehrfachauswahl/mehrere Wörter = mehrere Zeilen mit gleichem `participant_hash`.
|
||||
|
||||
### Zentrale Regeln (nicht versehentlich brechen)
|
||||
|
||||
- **Kein Login.** Zugriff auf die Verwaltung = Besitz des Tokens in der URL `/admin/{token}`.
|
||||
Token nie loggen, nie in JSON ausgeben, nie als Referrer leaken (`Referrer-Policy: no-referrer`).
|
||||
Lookup immer über `PollsTable::hashToken()` / Finder `byAdminToken`.
|
||||
- Admin-Aktionen müssen **immer** auf `$this->poll` eingeschränkt sein (z. B. `SlidesController::loadSlide()`
|
||||
prüft `poll_id`). Neue Admin-Controller von `AdminAppController` ableiten.
|
||||
- `SECURITY_SALT` verschlüsselt Admin-Tokens und hasht Teilnehmer-IDs → darf in Produktion nicht geändert werden.
|
||||
- Teilnehmende sind anonym: nur `VoteService::participantHash()` (HMAC, pro Poll) speichern.
|
||||
- Abgestimmt werden darf nur auf der **aktuellen** Folie (`polls.current_slide_id`), bei offener Abstimmung,
|
||||
aktivem Poll und einmal pro Teilnehmer. Diese Logik gehört in `VoteService`, nicht in Controller.
|
||||
- Ausnahme Wortwolke: Begriffe werden einzeln abgegeben (AJAX, `vote` liefert dann JSON `{ok, message, state}`),
|
||||
jeder Begriff einmal pro Person, max. `max_words` (0 = unbegrenzt). Einen vorhandenen Begriff erneut nennen
|
||||
bzw. in der Wolke anklicken = Upvote (gleiche Zeile in `responses`). Mit `allow_upvotes` sehen Teilnehmende
|
||||
die Wolke live (auch ohne `show_results_to_participants`); 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, zählen nicht zu `max_words`.
|
||||
Wortgröße richtet sich nur nach den Upvotes (`count`), Downvotes stehen separat in `down`.
|
||||
- `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">`.
|
||||
- Ausgaben in Templates immer mit `h()` escapen. JS baut DOM mit `textContent`, nie `innerHTML` mit Nutzerdaten.
|
||||
- Routen nur benannt verwenden (`['_name' => 'admin', 'token' => $adminToken]`), keine Fallbacks einführen.
|
||||
|
||||
### 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
|
||||
7. Tests in `tests/TestCase/Service/VoteServiceTest.php`
|
||||
|
||||
### 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.
|
||||
|
||||
## Konventionen
|
||||
|
||||
- Sprache der UI: **Deutsch**, Texte über `__()`. Code, Kommentare, Bezeichner: Englisch.
|
||||
- PHP: `declare(strict_types=1);`, CakePHP Coding Standard (`phpcs.xml`), typisierte Properties statt dynamischer.
|
||||
- Tables über `fetchTable()` holen und in typisierte Properties legen.
|
||||
- Einrückung 4 Spaces, LF (siehe `.editorconfig`).
|
||||
- Keine neuen Frontend-Abhängigkeiten / kein Build-Schritt ohne Rücksprache.
|
||||
- Schemaänderungen nur per neuer Migration, nie bestehende Migration ändern (sobald deployed).
|
||||
- Commits klein und thematisch; Commit-Messages auf Englisch im Imperativ.
|
||||
- **`main` ist geschützt:** nie direkt auf `main` committen oder pushen. Jede Änderung auf einem
|
||||
eigenen Branch (z. B. `feature/…`, `fix/…`, `docs/…`), pushen und per Pull Request in Gitea mergen.
|
||||
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`:
|
||||
|
||||
- Job `test` (PHPUnit + phpcs) läuft bei jedem Push auf jeden Branch. `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.
|
||||
|
||||
Produktiv auf dem Server in `config/.env`: `DEBUG=false`, `APP_FULL_BASE_URL`, `SECURITY_SALT`, SMTP.
|
||||
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.
|
||||
|
||||
## Bekannte Grenzen / Ideen
|
||||
|
||||
- Doppelte Stimmen sind möglich, wenn Teilnehmende Cookies löschen (bewusst: keine Accounts, kein IP-Tracking).
|
||||
- Polling skaliert für typische Meetings; für sehr große Events wären Server-Sent Events/WebSockets sinnvoll.
|
||||
- Mögliche Erweiterungen: Q&A mit Upvotes, Quiz mit richtigen Antworten/Punkten, Bilder auf Folien,
|
||||
Umfrage duplizieren, mehrsprachige UI (Übersetzungen unter `resources/locales`).
|
||||
@@ -0,0 +1,8 @@
|
||||
# CLAUDE.md
|
||||
|
||||
Alle Projektinfos für Agents stehen in **AGENTS.md** – bitte dort lesen und dort pflegen:
|
||||
|
||||
@AGENTS.md
|
||||
|
||||
Maschinenspezifische Hinweise (lokale PHP-Version, Pfade, Shell) stehen in `CLAUDE.local.md`
|
||||
(gitignored). Wenn du lokal etwas Neues über die Umgebung lernst, ergänze es dort.
|
||||
@@ -0,0 +1,79 @@
|
||||
# Plenario
|
||||
|
||||
Live-Umfragen für Vorträge, Workshops und Meetings – ähnlich wie Mentimeter oder Claper,
|
||||
aber **ohne Login**: Wer eine Umfrage anlegt, bekommt einen geheimen Admin-Link per E-Mail.
|
||||
|
||||
Basiert auf **CakePHP 5.4** (PHP ≥ 8.2), läuft lokal mit **SQLite**, ohne Build-Schritt fürs Frontend.
|
||||
|
||||
## Funktionen
|
||||
|
||||
- Umfrage anlegen mit Titel + E-Mail-Adresse, Admin-Link kommt per Mail
|
||||
- Optionales Captcha: keins, einfache Rechenaufgabe oder Google reCAPTCHA v2
|
||||
- Folientypen: **Multiple Choice** (Einfach-/Mehrfachauswahl), **Wortwolke**, **Offene Frage**, **Skala**, **Inhaltsfolie**
|
||||
- Präsentationsmodus (Vollbild, Tastatursteuerung, QR-Code, Live-Ergebnisse)
|
||||
- Teilnahme über 6-stelligen Code oder QR-Code, anonym (Cookie), eine Antwort pro Person und Folie
|
||||
- Ergebnisse optional auch für Teilnehmende sichtbar
|
||||
- CSV-Export, Antworten zurücksetzen, Folien sortieren
|
||||
- „Admin-Link verloren?“ – schickt alle Links zu einer Adresse erneut
|
||||
- Admin-Link neu erzeugen (alter Link wird ungültig), Umfrage löschen
|
||||
- Rate-Limit für Anlegen und Wiederherstellen pro IP
|
||||
|
||||
## Lokal starten
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
## Tests
|
||||
|
||||
```bash
|
||||
vendor/bin/phpunit # nutzt tmp/tests.sqlite, Schema kommt aus den Migrationen
|
||||
vendor/bin/phpcs # CakePHP Coding Standard
|
||||
```
|
||||
|
||||
## Konfiguration
|
||||
|
||||
Alle Einstellungen gehen über Umgebungsvariablen oder `config/.env`
|
||||
(Vorlage: [config/.env.example](config/.env.example)). Wichtig für den Betrieb:
|
||||
|
||||
| Variable | Bedeutung |
|
||||
|---|---|
|
||||
| `DEBUG` | `false` in Produktion |
|
||||
| `APP_FULL_BASE_URL` | Absolute URL, wird für Links in E-Mails gebraucht (Pflicht in Produktion) |
|
||||
| `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` |
|
||||
| `EMAIL_TRANSPORT_DEFAULT_URL` | z. B. `smtp://user:pw@mail.example.org:587?tls=true` |
|
||||
| `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` | Rate-Limits pro IP (0 = aus) |
|
||||
| `POLL_INTERVAL_MS` | Aktualisierungsintervall der Live-Ansichten |
|
||||
|
||||
## Deployment
|
||||
|
||||
1. Code auschecken, `composer install --no-dev --optimize-autoloader`
|
||||
2. `config/.env` (oder echte Umgebungsvariablen) setzen, mindestens `DEBUG=false`,
|
||||
`APP_FULL_BASE_URL`, `SECURITY_SALT`, Mail-Transport
|
||||
3. `bin/cake migrations migrate`
|
||||
4. Webserver-Document-Root auf `webroot/` zeigen lassen; `tmp/`, `logs/` und `data/` beschreibbar machen
|
||||
|
||||
Live-Updates laufen über kurzes Polling (Standard alle 2 s) – kein WebSocket-Server nötig.
|
||||
Für sehr große Runden (mehrere hundert Teilnehmende) `POLL_INTERVAL_MS` erhöhen und MySQL/PostgreSQL statt SQLite verwenden.
|
||||
|
||||
## Datenschutz
|
||||
|
||||
- Teilnehmende sind anonym. Gespeichert wird nur ein HMAC der Cookie-ID, pro Umfrage unterschiedlich.
|
||||
- Die E-Mail-Adresse dient nur dem Versand der Admin-Links.
|
||||
- In der Datenbank liegt nur der SHA-256-Hash des Admin-Tokens (plus eine mit `SECURITY_SALT` verschlüsselte Kopie für die Wiederherstellungs-Mail).
|
||||
|
||||
## Für KI-Agents
|
||||
|
||||
Siehe [AGENTS.md](AGENTS.md).
|
||||
@@ -0,0 +1,47 @@
|
||||
#
|
||||
# Bash completion file for CakePHP console.
|
||||
# Copy this file to a file named `cake` under `/etc/bash_completion.d/`.
|
||||
# For more info check https://book.cakephp.org/5/en/console-commands/completion.html#how-to-enable-bash-autocompletion-for-the-cakephp-console
|
||||
#
|
||||
|
||||
_cake()
|
||||
{
|
||||
local cur prev opts cake
|
||||
COMPREPLY=()
|
||||
cake="${COMP_WORDS[0]}"
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
|
||||
if [[ "$cur" == -* ]] ; then
|
||||
if [[ ${COMP_CWORD} = 1 ]] ; then
|
||||
opts=$(${cake} completion options)
|
||||
elif [[ ${COMP_CWORD} = 2 ]] ; then
|
||||
opts=$(${cake} completion options "${COMP_WORDS[1]}")
|
||||
else
|
||||
opts=$(${cake} completion options "${COMP_WORDS[1]}" "${COMP_WORDS[2]}")
|
||||
fi
|
||||
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ ${COMP_CWORD} = 1 ]] ; then
|
||||
opts=$(${cake} completion commands)
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ ${COMP_CWORD} = 2 ]] ; then
|
||||
opts=$(${cake} completion subcommands $prev)
|
||||
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
|
||||
if [[ $COMPREPLY = "" ]] ; then
|
||||
_filedir
|
||||
return 0
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
complete -F _cake cake bin/cake
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env sh
|
||||
################################################################################
|
||||
#
|
||||
# Cake is a shell script for invoking CakePHP shell commands
|
||||
#
|
||||
# CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
#
|
||||
# Licensed under The MIT License
|
||||
# For full copyright and license information, please see the LICENSE.txt
|
||||
# Redistributions of files must retain the above copyright notice.
|
||||
#
|
||||
# @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
# @link https://cakephp.org CakePHP(tm) Project
|
||||
# @since 1.2.0
|
||||
# @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
#
|
||||
################################################################################
|
||||
|
||||
# Canonicalize by following every symlink of the given name recursively
|
||||
canonicalize() {
|
||||
NAME="$1"
|
||||
if [ -f "$NAME" ]
|
||||
then
|
||||
DIR=$(dirname -- "$NAME")
|
||||
NAME=$(cd -P "$DIR" > /dev/null && pwd -P)/$(basename -- "$NAME")
|
||||
fi
|
||||
while [ -h "$NAME" ]; do
|
||||
DIR=$(dirname -- "$NAME")
|
||||
SYM=$(readlink "$NAME")
|
||||
NAME=$(cd "$DIR" > /dev/null && cd "$(dirname -- "$SYM")" > /dev/null && pwd)/$(basename -- "$SYM")
|
||||
done
|
||||
echo "$NAME"
|
||||
}
|
||||
|
||||
# Find a CLI version of PHP
|
||||
findCliPhp() {
|
||||
for TESTEXEC in php php-cli /usr/local/bin/php
|
||||
do
|
||||
SAPI=$(echo "<?= PHP_SAPI ?>" | $TESTEXEC 2>/dev/null)
|
||||
if [ "$SAPI" = "cli" ]
|
||||
then
|
||||
echo $TESTEXEC
|
||||
return
|
||||
fi
|
||||
done
|
||||
echo "Failed to find a CLI version of PHP; falling back to system standard php executable" >&2
|
||||
echo "php";
|
||||
}
|
||||
|
||||
# If current path is a symlink, resolve to real path
|
||||
realname="$0"
|
||||
if [ -L "$realname" ]
|
||||
then
|
||||
realname=$(readlink -f "$0")
|
||||
fi
|
||||
|
||||
CONSOLE=$(dirname -- "$(canonicalize "$realname")")
|
||||
APP=$(dirname "$CONSOLE")
|
||||
|
||||
# If your CLI PHP is somewhere that this doesn't find, you can define a PHP environment
|
||||
# variable with the correct path in it.
|
||||
if [ -z "$PHP" ]
|
||||
then
|
||||
PHP=$(findCliPhp)
|
||||
fi
|
||||
|
||||
if [ "$(basename "$realname")" != 'cake' ]
|
||||
then
|
||||
exec "$PHP" "$CONSOLE"/cake.php "$(basename "$realname")" "$@"
|
||||
else
|
||||
exec "$PHP" "$CONSOLE"/cake.php "$@"
|
||||
fi
|
||||
|
||||
exit
|
||||
@@ -0,0 +1,27 @@
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::
|
||||
:: Cake is a Windows batch script for invoking CakePHP shell commands
|
||||
::
|
||||
:: CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
:: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
::
|
||||
:: Licensed under The MIT License
|
||||
:: Redistributions of files must retain the above copyright notice.
|
||||
::
|
||||
:: @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
:: @link https://cakephp.org CakePHP(tm) Project
|
||||
:: @since 2.0.0
|
||||
:: @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
|
||||
@echo off
|
||||
|
||||
SET app=%0
|
||||
SET lib=%~dp0
|
||||
|
||||
php "%lib%cake.php" %*
|
||||
|
||||
echo.
|
||||
|
||||
exit /B %ERRORLEVEL%
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/php -q
|
||||
<?php
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Application;
|
||||
use Cake\Console\CommandRunner;
|
||||
|
||||
// Build the runner with an application and root executable name.
|
||||
$runner = new CommandRunner(new Application(dirname(__DIR__) . '/config'), 'cake');
|
||||
exit($runner->run($argv));
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "cakephp/app",
|
||||
"description": "CakePHP skeleton app",
|
||||
"license": "MIT",
|
||||
"type": "project",
|
||||
"homepage": "https://cakephp.org",
|
||||
"require": {
|
||||
"php": ">=8.2",
|
||||
"cakephp/cakephp": "5.4.*",
|
||||
"cakephp/migrations": "^5.0",
|
||||
"cakephp/plugin-installer": "^2.0",
|
||||
"chillerlan/php-qrcode": "^6.0",
|
||||
"josegonzalez/dotenv": "^4.0",
|
||||
"mobiledetect/mobiledetectlib": "^4.8.03"
|
||||
},
|
||||
"require-dev": {
|
||||
"cakephp/bake": "^3.6",
|
||||
"cakephp/cakephp-codesniffer": "^5.3",
|
||||
"cakephp/debug_kit": "^5.2",
|
||||
"phpunit/phpunit": "^11.5.3 || ^12.1.3 || ^13.0"
|
||||
},
|
||||
"suggest": {
|
||||
"cakephp/repl": "Console tools for a REPL interface for CakePHP applications.",
|
||||
"dereuromark/cakephp-ide-helper": "After baking your code, this keeps your annotations in sync with the code evolving from there on for maximum IDE and PHPStan/Psalm compatibility.",
|
||||
"markstory/asset_compress": "An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.",
|
||||
"phpstan/phpstan": "PHPStan focuses on finding errors in your code without actually running it. It catches whole classes of bugs even before you write tests for the code."
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"App\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"App\\Test\\": "tests/",
|
||||
"Cake\\Test\\": "vendor/cakephp/cakephp/tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"cakephp/plugin-installer": true,
|
||||
"dealerdirect/phpcodesniffer-composer-installer": true
|
||||
},
|
||||
"platform-check": true,
|
||||
"sort-packages": true
|
||||
},
|
||||
"scripts": {
|
||||
"post-install-cmd": "App\\Console\\Installer::postInstall",
|
||||
"post-create-project-cmd": "App\\Console\\Installer::postInstall",
|
||||
"check": [
|
||||
"@test",
|
||||
"@cs-check"
|
||||
],
|
||||
"cs-check": "phpcs --colors -p",
|
||||
"cs-fix": "phpcbf --colors -p",
|
||||
"test": "phpunit --colors=always"
|
||||
}
|
||||
}
|
||||
Generated
+6594
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,38 @@
|
||||
# Plenario environment configuration
|
||||
# Copy to config/.env (not committed) or set these as real environment variables.
|
||||
# Real environment variables take precedence over this file.
|
||||
|
||||
# --- Core -------------------------------------------------------------------
|
||||
DEBUG=false
|
||||
# Absolute URL used in e-mails, MUST be set in production
|
||||
APP_FULL_BASE_URL=https://plenario.example.org
|
||||
# Generate with: php -r "echo bin2hex(random_bytes(32));"
|
||||
SECURITY_SALT=change-me-to-a-long-random-string
|
||||
APP_DEFAULT_LOCALE=de_DE
|
||||
|
||||
# --- Database ---------------------------------------------------------------
|
||||
# Empty = SQLite file data/plenario.sqlite
|
||||
# DATABASE_URL=mysql://user:password@localhost/plenario?encoding=utf8mb4
|
||||
# DATABASE_URL=postgres://user:password@localhost/plenario
|
||||
|
||||
# --- Mail -------------------------------------------------------------------
|
||||
# Empty = .eml files in tmp/mails/ (development only!)
|
||||
# EMAIL_TRANSPORT_DEFAULT_URL=smtp://user:password@mail.example.org:587?tls=true
|
||||
MAIL_FROM=noreply@plenario.example.org
|
||||
MAIL_FROM_NAME=Plenario
|
||||
|
||||
# --- Captcha ----------------------------------------------------------------
|
||||
# none | math | recaptcha
|
||||
CAPTCHA_TYPE=math
|
||||
# Only for CAPTCHA_TYPE=recaptcha (reCAPTCHA v2 checkbox, https://www.google.com/recaptcha/admin)
|
||||
RECAPTCHA_SITE_KEY=
|
||||
RECAPTCHA_SECRET_KEY=
|
||||
|
||||
# --- Behaviour --------------------------------------------------------------
|
||||
# Show the admin link right after creation (development only, never in production)
|
||||
SHOW_ADMIN_LINK_AFTER_CREATE=false
|
||||
# Max. polls / recovery mails per IP and hour (0 = unlimited)
|
||||
THROTTLE_CREATE_PER_HOUR=10
|
||||
THROTTLE_RECOVER_PER_HOUR=5
|
||||
# How often presenter and participant pages poll for updates (ms)
|
||||
POLL_INTERVAL_MS=2000
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Migrations\BaseMigration;
|
||||
|
||||
/**
|
||||
* Initial Plenario schema.
|
||||
*
|
||||
* polls - one "presentation" created via e-mail, managed through a secret admin link
|
||||
* slides - questions / content slides of a poll, ordered by `position`
|
||||
* slide_options - answer options for choice slides
|
||||
* responses - participant answers (one row per selected option / entered text / value)
|
||||
*/
|
||||
class CreateInitialSchema extends BaseMigration
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function change(): void
|
||||
{
|
||||
$this->table('polls')
|
||||
->addColumn('title', 'string', ['limit' => 200, 'null' => false])
|
||||
->addColumn('email', 'string', ['limit' => 255, 'null' => false])
|
||||
// sha256 of the secret admin token; the token itself is only sent by mail
|
||||
->addColumn('admin_token_hash', 'string', ['limit' => 64, 'null' => false])
|
||||
// token encrypted with Security.salt so the recovery mail can resend the same link
|
||||
->addColumn('admin_token_encrypted', 'text', ['null' => false])
|
||||
// short public code participants use to join, e.g. "K7P2QX"
|
||||
->addColumn('join_code', 'string', ['limit' => 12, 'null' => false])
|
||||
->addColumn('current_slide_id', 'integer', ['null' => true, 'default' => null])
|
||||
->addColumn('is_active', 'boolean', ['null' => false, 'default' => true])
|
||||
->addColumn('show_results_to_participants', 'boolean', ['null' => false, 'default' => true])
|
||||
->addColumn('last_admin_access', 'datetime', ['null' => true, 'default' => null])
|
||||
->addColumn('created', 'datetime', ['null' => false])
|
||||
->addColumn('modified', 'datetime', ['null' => false])
|
||||
->addIndex(['admin_token_hash'], ['unique' => true])
|
||||
->addIndex(['join_code'], ['unique' => true])
|
||||
->addIndex(['email'])
|
||||
->create();
|
||||
|
||||
$this->table('slides')
|
||||
->addColumn('poll_id', 'integer', ['null' => false])
|
||||
// choice | wordcloud | open | scale | content
|
||||
->addColumn('type', 'string', ['limit' => 20, 'null' => false])
|
||||
->addColumn('question', 'string', ['limit' => 500, 'null' => false])
|
||||
->addColumn('description', 'text', ['null' => true, 'default' => null])
|
||||
->addColumn('position', 'integer', ['null' => false, 'default' => 0])
|
||||
// JSON encoded type specific settings (multiple, scale_min, scale_max, ...)
|
||||
->addColumn('settings', 'text', ['null' => true, 'default' => null])
|
||||
->addColumn('is_voting_open', 'boolean', ['null' => false, 'default' => true])
|
||||
->addColumn('created', 'datetime', ['null' => false])
|
||||
->addColumn('modified', 'datetime', ['null' => false])
|
||||
->addIndex(['poll_id', 'position'])
|
||||
->addForeignKey('poll_id', 'polls', 'id', ['delete' => 'CASCADE', 'update' => 'NO_ACTION'])
|
||||
->create();
|
||||
|
||||
$this->table('slide_options')
|
||||
->addColumn('slide_id', 'integer', ['null' => false])
|
||||
->addColumn('label', 'string', ['limit' => 255, 'null' => false])
|
||||
->addColumn('position', 'integer', ['null' => false, 'default' => 0])
|
||||
->addIndex(['slide_id', 'position'])
|
||||
->addForeignKey('slide_id', 'slides', 'id', ['delete' => 'CASCADE', 'update' => 'NO_ACTION'])
|
||||
->create();
|
||||
|
||||
$this->table('responses')
|
||||
->addColumn('slide_id', 'integer', ['null' => false])
|
||||
// sha256 of the participant cookie id - anonymous, only used to prevent double voting
|
||||
->addColumn('participant_hash', 'string', ['limit' => 64, 'null' => false])
|
||||
->addColumn('slide_option_id', 'integer', ['null' => true, 'default' => null])
|
||||
->addColumn('text_value', 'string', ['limit' => 500, 'null' => true, 'default' => null])
|
||||
->addColumn('numeric_value', 'integer', ['null' => true, 'default' => null])
|
||||
->addColumn('created', 'datetime', ['null' => false])
|
||||
->addIndex(['slide_id', 'participant_hash'])
|
||||
->addIndex(['slide_option_id'])
|
||||
->addForeignKey('slide_id', 'slides', 'id', ['delete' => 'CASCADE', 'update' => 'NO_ACTION'])
|
||||
->addForeignKey('slide_option_id', 'slide_options', 'id', ['delete' => 'CASCADE', 'update' => 'NO_ACTION'])
|
||||
->create();
|
||||
}
|
||||
}
|
||||
+509
@@ -0,0 +1,509 @@
|
||||
<?php
|
||||
|
||||
use Cake\Cache\Engine\FileEngine;
|
||||
use Cake\Database\Connection;
|
||||
use Cake\Database\Driver\Sqlite;
|
||||
use Cake\Log\Engine\FileLog;
|
||||
use Cake\Mailer\Transport\MailTransport;
|
||||
use function Cake\Core\env;
|
||||
|
||||
return [
|
||||
/*
|
||||
* Plenario application settings.
|
||||
*
|
||||
* Every value can be overridden in config/app_local.php or via environment
|
||||
* variables (see config/.env.example).
|
||||
*
|
||||
* - captcha.type: 'none' | 'math' | 'recaptcha'
|
||||
* - captcha.recaptcha: Google reCAPTCHA v2 ("I'm not a robot") keys.
|
||||
* - showAdminLinkAfterCreate: show the admin link directly on the
|
||||
* confirmation page (useful for local development without mail server).
|
||||
* Defaults to the debug flag. NEVER enable this in production, otherwise
|
||||
* the e-mail confirmation is pointless.
|
||||
* - throttle: max. number of polls / recovery mails per IP and hour.
|
||||
* - pollIntervalMs: how often presenter / participant pages poll for state.
|
||||
*/
|
||||
'Plenario' => [
|
||||
'captcha' => [
|
||||
'type' => env('CAPTCHA_TYPE', 'math'),
|
||||
'recaptcha' => [
|
||||
'siteKey' => env('RECAPTCHA_SITE_KEY', ''),
|
||||
'secretKey' => env('RECAPTCHA_SECRET_KEY', ''),
|
||||
],
|
||||
],
|
||||
'showAdminLinkAfterCreate' => filter_var(
|
||||
env('SHOW_ADMIN_LINK_AFTER_CREATE', env('DEBUG', false)),
|
||||
FILTER_VALIDATE_BOOLEAN,
|
||||
),
|
||||
'throttle' => [
|
||||
'createPerHour' => (int)env('THROTTLE_CREATE_PER_HOUR', 10),
|
||||
'recoverPerHour' => (int)env('THROTTLE_RECOVER_PER_HOUR', 5),
|
||||
],
|
||||
'pollIntervalMs' => (int)env('POLL_INTERVAL_MS', 2000),
|
||||
],
|
||||
|
||||
/*
|
||||
* Debug Level:
|
||||
*
|
||||
* Production Mode:
|
||||
* false: No error messages, errors, or warnings shown.
|
||||
*
|
||||
* Development Mode:
|
||||
* true: Errors and warnings shown.
|
||||
*/
|
||||
'debug' => filter_var(env('DEBUG', false), FILTER_VALIDATE_BOOLEAN),
|
||||
|
||||
/*
|
||||
* Configure basic information about the application.
|
||||
*
|
||||
* - namespace - The namespace to find app classes under.
|
||||
* - defaultLocale - The default locale for translation, formatting currencies and numbers, date and time.
|
||||
* - encoding - The encoding used for HTML + database connections.
|
||||
* - base - The base directory the app resides in. If false this
|
||||
* will be auto-detected.
|
||||
* - dir - Name of app directory.
|
||||
* - webroot - The webroot directory.
|
||||
* - wwwRoot - The file path to webroot.
|
||||
* - baseUrl - To configure CakePHP to *not* use mod_rewrite and to
|
||||
* use CakePHP pretty URLs, remove these .htaccess
|
||||
* files:
|
||||
* /.htaccess
|
||||
* /webroot/.htaccess
|
||||
* And uncomment the baseUrl key below.
|
||||
* - fullBaseUrl - SECURITY: A base URL to use for absolute links.
|
||||
* IMPORTANT: This MUST be set in production to prevent Host Header Injection attacks
|
||||
* that can compromise password reset and other security-critical features.
|
||||
* Set this via APP_FULL_BASE_URL environment variable or directly in config.
|
||||
* Example: 'https://example.com'
|
||||
* When not set, the application will throw an exception in production mode.
|
||||
* - imageBaseUrl - Web path to the public images/ directory under webroot.
|
||||
* - cssBaseUrl - Web path to the public css/ directory under webroot.
|
||||
* - jsBaseUrl - Web path to the public js/ directory under webroot.
|
||||
* - paths - Configure paths for non class-based resources. Supports the
|
||||
* `plugins`, `templates`, `locales` subkeys, which allow the definition of
|
||||
* paths for plugins, view templates and locale files respectively.
|
||||
*/
|
||||
'App' => [
|
||||
'namespace' => 'App',
|
||||
'encoding' => env('APP_ENCODING', 'UTF-8'),
|
||||
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'de_DE'),
|
||||
'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'UTC'),
|
||||
'base' => false,
|
||||
'dir' => 'src',
|
||||
'webroot' => 'webroot',
|
||||
'wwwRoot' => WWW_ROOT,
|
||||
//'baseUrl' => env('SCRIPT_NAME'),
|
||||
'fullBaseUrl' => env('APP_FULL_BASE_URL', false),
|
||||
'imageBaseUrl' => 'img/',
|
||||
'cssBaseUrl' => 'css/',
|
||||
'jsBaseUrl' => 'js/',
|
||||
'paths' => [
|
||||
'plugins' => [ROOT . DS . 'plugins' . DS],
|
||||
'templates' => [ROOT . DS . 'templates' . DS],
|
||||
'locales' => [RESOURCES . 'locales' . DS],
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
* Security and encryption configuration
|
||||
*
|
||||
* - salt - A random string used in security hashing methods.
|
||||
* The salt value is also used as the encryption key.
|
||||
* You should treat it as extremely sensitive data.
|
||||
*/
|
||||
'Security' => [
|
||||
'salt' => env('SECURITY_SALT'),
|
||||
],
|
||||
|
||||
/*
|
||||
* Apply timestamps with the last modified time to static assets (js, css, images).
|
||||
* Will append a querystring parameter containing the time the file was modified.
|
||||
* This is useful for busting browser caches.
|
||||
*
|
||||
* Set to true to apply timestamps when debug is true. Set to 'force' to always
|
||||
* enable timestamping regardless of debug value.
|
||||
*/
|
||||
'Asset' => [
|
||||
//'timestamp' => true,
|
||||
// 'cacheTime' => '+1 year'
|
||||
],
|
||||
|
||||
/*
|
||||
* Configure the cache adapters.
|
||||
*/
|
||||
'Cache' => [
|
||||
'default' => [
|
||||
'className' => FileEngine::class,
|
||||
'path' => CACHE,
|
||||
'url' => env('CACHE_DEFAULT_URL', null),
|
||||
],
|
||||
|
||||
/*
|
||||
* Rate limiting of poll creation / recovery mails (App\Service\ThrottleService).
|
||||
*/
|
||||
'throttle' => [
|
||||
'className' => FileEngine::class,
|
||||
'prefix' => 'plenario_',
|
||||
'path' => CACHE . 'throttle' . DS,
|
||||
'duration' => '+1 hour',
|
||||
'url' => env('CACHE_THROTTLE_URL', null),
|
||||
],
|
||||
|
||||
/*
|
||||
* Configure the cache used for general framework caching.
|
||||
* Translation cache files are stored with this configuration.
|
||||
* Duration will be set to '+2 minutes' in bootstrap.php when debug = true
|
||||
* If you set 'className' => 'Null' core cache will be disabled.
|
||||
*/
|
||||
'_cake_translations_' => [
|
||||
'className' => FileEngine::class,
|
||||
'prefix' => 'myapp_cake_translations_',
|
||||
'path' => CACHE . 'persistent' . DS,
|
||||
'serialize' => true,
|
||||
'duration' => '+1 years',
|
||||
'url' => env('CACHE_CAKECORE_URL', null),
|
||||
],
|
||||
|
||||
/*
|
||||
* Configure the cache for model and datasource caches. This cache
|
||||
* configuration is used to store schema descriptions, and table listings
|
||||
* in connections.
|
||||
* Duration will be set to '+2 minutes' in bootstrap.php when debug = true
|
||||
*/
|
||||
'_cake_model_' => [
|
||||
'className' => FileEngine::class,
|
||||
'prefix' => 'myapp_cake_model_',
|
||||
'path' => CACHE . 'models' . DS,
|
||||
'serialize' => true,
|
||||
'duration' => '+1 years',
|
||||
'url' => env('CACHE_CAKEMODEL_URL', null),
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
* Configure the Error and Exception handlers used by your application.
|
||||
*
|
||||
* By default errors are displayed using Debugger, when debug is true and logged
|
||||
* by Cake\Log\Log when debug is false.
|
||||
*
|
||||
* In CLI environments exceptions will be printed to stderr with a backtrace.
|
||||
* In web environments an HTML page will be displayed for the exception.
|
||||
* With debug true, framework errors like Missing Controller will be displayed.
|
||||
* When debug is false, framework errors will be coerced into generic HTTP errors.
|
||||
*
|
||||
* Options:
|
||||
*
|
||||
* - `errorLevel` - int - The level of errors you are interested in capturing.
|
||||
* - `trace` - boolean - Whether backtraces should be included in
|
||||
* logged errors/exceptions.
|
||||
* - `log` - boolean - Whether you want exceptions logged.
|
||||
* - `exceptionRenderer` - string - The class responsible for rendering uncaught exceptions.
|
||||
* The chosen class will be used for both CLI and web environments. If you want different
|
||||
* classes used in CLI and web environments you'll need to write that conditional logic as well.
|
||||
* The conventional location for custom renderers is in `src/Error`. Your exception renderer needs to
|
||||
* implement the `render()` method and return either a string or Http\Response.
|
||||
* `errorRenderer` - string - The class responsible for rendering PHP errors. The selected
|
||||
* class will be used for both web and CLI contexts. If you want different classes for each environment
|
||||
* you'll need to write that conditional logic as well. Error renderers need to
|
||||
* to implement the `Cake\Error\ErrorRendererInterface`.
|
||||
* - `skipLog` - array - List of exceptions to skip for logging. Exceptions that
|
||||
* extend one of the listed exceptions will also be skipped for logging.
|
||||
* E.g.:
|
||||
* `'skipLog' => ['Cake\Http\Exception\NotFoundException', 'Cake\Http\Exception\UnauthorizedException']`
|
||||
* - `extraFatalErrorMemory` - int - The number of megabytes to increase the memory limit by
|
||||
* when a fatal error is encountered. This allows
|
||||
* breathing room to complete logging or error handling.
|
||||
* - `ignoredDeprecationPaths` - array - A list of glob-compatible file paths that deprecations
|
||||
* should be ignored in. Use this to ignore deprecations for plugins or parts of
|
||||
* your application that still emits deprecations.
|
||||
* - `traceFormat` - when logging errors, List of `'array'`, `'points'`, `'shortPoints'`, defaults to `shortPoints`.
|
||||
*/
|
||||
'Error' => [
|
||||
'errorLevel' => E_ALL,
|
||||
'skipLog' => [],
|
||||
'log' => true,
|
||||
'trace' => true,
|
||||
'ignoredDeprecationPaths' => [],
|
||||
'traceFormat' => null,
|
||||
],
|
||||
|
||||
/*
|
||||
* Debugger configuration
|
||||
*
|
||||
* Define development error values for Cake\Error\Debugger
|
||||
*
|
||||
* - `editor` Set the editor URL format you want to use.
|
||||
* By default atom, emacs, macvim, phpstorm, sublime, textmate, and vscode are
|
||||
* available. You can add additional editor link formats using
|
||||
* `Debugger::addEditor()` during your application bootstrap.
|
||||
* - `editorBasePath` - The base path to your project for editor integration.
|
||||
* Used to generate file links in stack traces.
|
||||
* - `outputMask` A mapping of `key` to `replacement` values that
|
||||
* `Debugger` should replace in dumped data and logs generated by `Debugger`.
|
||||
*/
|
||||
'Debugger' => [
|
||||
'editor' => 'phpstorm',
|
||||
],
|
||||
|
||||
/*
|
||||
* Email configuration.
|
||||
*
|
||||
* By defining transports separately from delivery profiles you can easily
|
||||
* re-use transport configuration across multiple profiles.
|
||||
*
|
||||
* You can specify multiple configurations for production, development and
|
||||
* testing.
|
||||
*
|
||||
* Each transport needs a `className`. Valid options are as follows:
|
||||
*
|
||||
* Mail - Send using PHP mail function
|
||||
* Smtp - Send using SMTP
|
||||
* Debug - Do not send the email, just return the result
|
||||
*
|
||||
* You can add custom transports (or override existing transports) by adding the
|
||||
* appropriate file to src/Mailer/Transport. Transports should be named
|
||||
* 'YourTransport.php', where 'Your' is the name of the transport.
|
||||
*/
|
||||
'EmailTransport' => [
|
||||
'default' => [
|
||||
'className' => MailTransport::class,
|
||||
/*
|
||||
* The keys host, port, timeout, username, password, client and tls
|
||||
* are used in SMTP transports
|
||||
*/
|
||||
'host' => 'localhost',
|
||||
'port' => 25,
|
||||
'timeout' => 30,
|
||||
/*
|
||||
* It is recommended to set these options through your environment or app_local.php
|
||||
*/
|
||||
//'username' => null,
|
||||
//'password' => null,
|
||||
'client' => null,
|
||||
'tls' => false,
|
||||
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
* Email delivery profiles
|
||||
*
|
||||
* Delivery profiles allow you to predefine various properties about email
|
||||
* messages from your application and give the settings a name. This saves
|
||||
* duplication across your application and makes maintenance and development
|
||||
* easier. Each profile accepts a number of keys. See `Cake\Mailer\Mailer`
|
||||
* for more information.
|
||||
*/
|
||||
'Email' => [
|
||||
'default' => [
|
||||
'transport' => 'default',
|
||||
'from' => [env('MAIL_FROM', 'noreply@localhost') => env('MAIL_FROM_NAME', 'Plenario')],
|
||||
/*
|
||||
* Will by default be set to config value of App.encoding, if that exists otherwise to UTF-8.
|
||||
*/
|
||||
//'charset' => 'utf-8',
|
||||
//'headerCharset' => 'utf-8',
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
* Connection information used by the ORM to connect
|
||||
* to your application's datastores.
|
||||
*
|
||||
* ### Notes
|
||||
* - Drivers include Mysql Postgres Sqlite Sqlserver
|
||||
* See vendor\cakephp\cakephp\src\Database\Driver for the complete list
|
||||
* - Do not use periods in database name - it may lead to errors.
|
||||
* See https://github.com/cakephp/cakephp/issues/6471 for details.
|
||||
* - 'encoding' is recommended to be set to full UTF-8 4-Byte support.
|
||||
* E.g set it to 'utf8mb4' in MariaDB and MySQL and 'utf8' for any
|
||||
* other RDBMS.
|
||||
*/
|
||||
'Datasources' => [
|
||||
/*
|
||||
* These configurations should contain permanent settings used
|
||||
* by all environments.
|
||||
*
|
||||
* The values in app_local.php will override any values set here
|
||||
* and should be used for local and per-environment configurations.
|
||||
*
|
||||
* Environment variable-based configurations can be loaded here or
|
||||
* in app_local.php depending on the application's needs.
|
||||
*/
|
||||
'default' => [
|
||||
'className' => Connection::class,
|
||||
'driver' => Sqlite::class,
|
||||
'persistent' => false,
|
||||
'timezone' => 'UTC',
|
||||
|
||||
/*
|
||||
* For MariaDB/MySQL the internal default changed from utf8 to utf8mb4, aka full utf-8 support
|
||||
*/
|
||||
'encoding' => 'utf8',
|
||||
|
||||
/*
|
||||
* If your MySQL server is configured with `skip-character-set-client-handshake`
|
||||
* then you MUST use the `flags` config to set your charset encoding.
|
||||
* For e.g. `'flags' => [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4']`
|
||||
*/
|
||||
'flags' => [],
|
||||
'cacheMetadata' => true,
|
||||
'log' => false,
|
||||
|
||||
/*
|
||||
* Set identifier quoting to true if you are using reserved words or
|
||||
* special characters in your table or column names. Enabling this
|
||||
* setting will result in queries built using the Query Builder having
|
||||
* identifiers quoted when creating SQL. It should be noted that this
|
||||
* decreases performance because each query needs to be traversed and
|
||||
* manipulated before being executed.
|
||||
*/
|
||||
'quoteIdentifiers' => false,
|
||||
|
||||
/*
|
||||
* During development, if using MySQL < 5.6, uncommenting the
|
||||
* following line could boost the speed at which schema metadata is
|
||||
* fetched from the database. It can also be set directly with the
|
||||
* mysql configuration directive 'innodb_stats_on_metadata = 0'
|
||||
* which is the recommended value in production environments
|
||||
*/
|
||||
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
|
||||
],
|
||||
|
||||
/*
|
||||
* The test connection is used during the test suite.
|
||||
*/
|
||||
'test' => [
|
||||
'className' => Connection::class,
|
||||
'driver' => Sqlite::class,
|
||||
'persistent' => false,
|
||||
'timezone' => 'UTC',
|
||||
'encoding' => 'utf8',
|
||||
'flags' => [],
|
||||
'cacheMetadata' => true,
|
||||
'quoteIdentifiers' => false,
|
||||
'log' => false,
|
||||
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
* Configures logging options
|
||||
*/
|
||||
'Log' => [
|
||||
'debug' => [
|
||||
'className' => FileLog::class,
|
||||
'path' => LOGS,
|
||||
'file' => 'debug',
|
||||
'url' => env('LOG_DEBUG_URL', null),
|
||||
'scopes' => null,
|
||||
'levels' => ['notice', 'info', 'debug'],
|
||||
],
|
||||
'error' => [
|
||||
'className' => FileLog::class,
|
||||
'path' => LOGS,
|
||||
'file' => 'error',
|
||||
'url' => env('LOG_ERROR_URL', null),
|
||||
'scopes' => null,
|
||||
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
|
||||
],
|
||||
// To enable this dedicated query log, you need to set your datasource's log flag to true
|
||||
'queries' => [
|
||||
'className' => FileLog::class,
|
||||
'path' => LOGS,
|
||||
'file' => 'queries',
|
||||
'url' => env('LOG_QUERIES_URL', null),
|
||||
'scopes' => ['cake.database.queries'],
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
* Session configuration.
|
||||
*
|
||||
* Contains an array of settings to use for session configuration. The
|
||||
* `defaults` key is used to define a default preset to use for sessions, any
|
||||
* settings declared here will override the settings of the default config.
|
||||
*
|
||||
* ## Options
|
||||
*
|
||||
* - `cookie` - The name of the cookie to use. Defaults to value set for `session.name` php.ini config.
|
||||
* Avoid using `.` in cookie names, as PHP will drop sessions from cookies with `.` in the name.
|
||||
* - `cookiePath` - The url path for which session cookie is set. Maps to the
|
||||
* `session.cookie_path` php.ini config. Defaults to base path of app.
|
||||
* - `timeout` - The time in minutes a session can be 'idle'. If no request is received in
|
||||
* this duration, the session will be expired and rotated. Pass 0 to disable idle timeout checks.
|
||||
* - `defaults` - The default configuration set to use as a basis for your session.
|
||||
* There are four built-in options: php, cake, cache, database.
|
||||
* - `handler` - Can be used to enable a custom session handler. Expects an
|
||||
* array with at least the `engine` key, being the name of the Session engine
|
||||
* class to use for managing the session. CakePHP bundles the `CacheSession`
|
||||
* and `DatabaseSession` engines.
|
||||
* - `ini` - An associative array of additional 'session.*` ini values to set.
|
||||
*
|
||||
* Within the `ini` key, you will likely want to define:
|
||||
*
|
||||
* - `session.cookie_lifetime` - The number of seconds that cookies are valid for. This
|
||||
* should be longer than `Session.timeout`.
|
||||
* - `session.gc_maxlifetime` - The number of seconds after which a session is considered 'garbage'
|
||||
* that can be deleted by PHP's session cleanup behavior. This value should be greater than both
|
||||
* `Sesssion.timeout` and `session.cookie_lifetime`.
|
||||
*
|
||||
* The built-in `defaults` options are:
|
||||
*
|
||||
* - 'php' - Uses settings defined in your php.ini.
|
||||
* - 'cake' - Saves session files in CakePHP's /tmp directory.
|
||||
* - 'database' - Uses CakePHP's database sessions.
|
||||
* - 'cache' - Use the Cache class to save sessions.
|
||||
*
|
||||
* To define a custom session handler, save it at src/Http/Session/<name>.php.
|
||||
* Make sure the class implements PHP's `SessionHandlerInterface` and set
|
||||
* Session.handler to <name>
|
||||
*
|
||||
* To use database sessions, load the SQL file located at config/schema/sessions.sql
|
||||
*/
|
||||
'Session' => [
|
||||
'defaults' => 'php',
|
||||
],
|
||||
|
||||
/**
|
||||
* DebugKit configuration.
|
||||
*
|
||||
* Contains an array of configurations to apply to the DebugKit plugin, if loaded.
|
||||
* Documentation: https://book.cakephp.org/debugkit/5/en/index.html#configuration
|
||||
*
|
||||
* ## Options
|
||||
*
|
||||
* - `panels` - Enable or disable panels. The key is the panel name, and the value is true to enable,
|
||||
* or false to disable.
|
||||
* - `includeSchemaReflection` - Set to true to enable logging of schema reflection queries. Disabled by default.
|
||||
* - `safeTld` - Set an array of whitelisted TLDs for local development.
|
||||
* - `forceEnable` - Force DebugKit to display. Careful with this, it is usually safer to simply whitelist
|
||||
* your local TLDs.
|
||||
* - `ignorePathsPattern` - Regex pattern (including delimiter) to ignore paths.
|
||||
* DebugKit won’t save data for request URLs that match this regex.
|
||||
* - `ignoreAuthorization` - Set to true to ignore Cake Authorization plugin for DebugKit requests.
|
||||
* Disabled by default.
|
||||
* - `maxDepth` - Defines how many levels of nested data should be shown in general for debug output.
|
||||
* Default is 5. WARNING: Increasing the max depth level can lead to an out of memory error.
|
||||
* - `variablesPanelMaxDepth` - Defines how many levels of nested data should be shown in the variables tab.
|
||||
* Default is 5. WARNING: Increasing the max depth level can lead to an out of memory error.
|
||||
*/
|
||||
'DebugKit' => [
|
||||
'forceEnable' => filter_var(env('DEBUG_KIT_FORCE_ENABLE', false), FILTER_VALIDATE_BOOLEAN),
|
||||
'safeTld' => env('DEBUG_KIT_SAFE_TLD', null),
|
||||
'ignoreAuthorization' => env('DEBUG_KIT_IGNORE_AUTHORIZATION', false),
|
||||
],
|
||||
|
||||
/**
|
||||
* TestSuite configuration.
|
||||
*
|
||||
* ## Options
|
||||
*
|
||||
* - `errorLevel` - Defaults to `E_ALL`. Can be set to `false` to disable overwrite error level.
|
||||
* - `fixtureStrategy` - Defaults to TruncateStrategy. Can be set to any class implementing FixtureStrategyInterface.
|
||||
*/
|
||||
'TestSuite' => [
|
||||
'errorLevel' => null,
|
||||
'fixtureStrategy' => null,
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
/*
|
||||
* Local configuration overrides for Plenario.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
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' => [
|
||||
'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 production use SMTP, e.g.
|
||||
* EMAIL_TRANSPORT_DEFAULT_URL=smtp://user:pass@mail.example.org:587?tls=true
|
||||
*/
|
||||
'default' => [
|
||||
'className' => \App\Mailer\Transport\FileTransport::class,
|
||||
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
|
||||
],
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,239 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.8
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/*
|
||||
* This file is loaded by your src/Application.php bootstrap method.
|
||||
* Feel free to extend/extract parts of the bootstrap process into your own files
|
||||
* to suit your needs/preferences.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Configure paths required to find CakePHP + general filepath constants
|
||||
*/
|
||||
require __DIR__ . DIRECTORY_SEPARATOR . 'paths.php';
|
||||
|
||||
/*
|
||||
* Bootstrap CakePHP
|
||||
* Currently all this does is initialize the router (without loading your routes)
|
||||
*/
|
||||
require CORE_PATH . 'config' . DS . 'bootstrap.php';
|
||||
|
||||
use Cake\Cache\Cache;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\Configure\Engine\PhpConfig;
|
||||
use Cake\Datasource\ConnectionManager;
|
||||
use Cake\Error\ErrorTrap;
|
||||
use Cake\Error\ExceptionTrap;
|
||||
use Cake\Http\ServerRequest;
|
||||
use Cake\Log\Log;
|
||||
use Cake\Mailer\Mailer;
|
||||
use Cake\Mailer\TransportFactory;
|
||||
use Cake\Routing\Router;
|
||||
use Cake\Utility\Security;
|
||||
use Detection\MobileDetect;
|
||||
use function Cake\Core\env;
|
||||
|
||||
/*
|
||||
* Load global functions for collections, translations, debugging etc.
|
||||
*/
|
||||
require CAKE . 'functions.php';
|
||||
|
||||
/*
|
||||
* See https://github.com/josegonzalez/php-dotenv for API details.
|
||||
*
|
||||
* Uncomment block of code below if you want to use `.env` file during development.
|
||||
* You should copy `config/.env.example` to `config/.env` and set/modify the
|
||||
* variables as required.
|
||||
*
|
||||
* The purpose of the .env file is to emulate the presence of the environment
|
||||
* variables like they would be present in production.
|
||||
*
|
||||
* If you use .env files, be careful to not commit them to source control to avoid
|
||||
* security risks. See https://github.com/josegonzalez/php-dotenv#general-security-information
|
||||
* for more information for recommended practices.
|
||||
*/
|
||||
// Plenario: config/.env is optional. Real environment variables always win.
|
||||
if (file_exists(CONFIG . '.env')) {
|
||||
$dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
|
||||
$dotenv->parse()
|
||||
->skipExisting()
|
||||
->putenv()
|
||||
->toEnv()
|
||||
->toServer();
|
||||
}
|
||||
|
||||
/*
|
||||
* Initializes default Config store and loads the main configuration file (app.php)
|
||||
*
|
||||
* CakePHP contains 2 configuration files after project creation:
|
||||
* - `config/app.php` for the default application configuration.
|
||||
* - `config/app_local.php` for environment specific configuration.
|
||||
*/
|
||||
try {
|
||||
Configure::config('default', new PhpConfig());
|
||||
Configure::load('app', 'default', false);
|
||||
} catch (Exception $e) {
|
||||
exit($e->getMessage() . "\n");
|
||||
}
|
||||
|
||||
/*
|
||||
* Load an environment local configuration file to provide overrides to your configuration.
|
||||
* Notice: For security reasons app_local.php **should not** be included in your git repo.
|
||||
*/
|
||||
if (file_exists(CONFIG . 'app_local.php')) {
|
||||
Configure::load('app_local', 'default');
|
||||
}
|
||||
|
||||
/*
|
||||
* When debug = true the metadata cache should only last for a short time.
|
||||
*/
|
||||
if (Configure::read('debug')) {
|
||||
Configure::write('Cache._cake_model_.duration', '+1 minute');
|
||||
Configure::write('Cache._cake_translations_.duration', '+1 minute');
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the default server timezone. Using UTC makes time calculations / conversions easier.
|
||||
* Check https://php.net/manual/en/timezones.php for list of valid timezone strings.
|
||||
*/
|
||||
date_default_timezone_set(Configure::read('App.defaultTimezone'));
|
||||
|
||||
/*
|
||||
* Configure the mbstring extension to use the correct encoding.
|
||||
*/
|
||||
mb_internal_encoding(Configure::read('App.encoding'));
|
||||
|
||||
/*
|
||||
* Set the default locale. This controls how dates, number and currency is
|
||||
* formatted and sets the default language to use for translations.
|
||||
*/
|
||||
ini_set('intl.default_locale', Configure::read('App.defaultLocale'));
|
||||
|
||||
/*
|
||||
* Register application error and exception handlers.
|
||||
*/
|
||||
(new ErrorTrap(Configure::read('Error')))->register();
|
||||
(new ExceptionTrap(Configure::read('Error')))->register();
|
||||
|
||||
/*
|
||||
* CLI/Command specific configuration.
|
||||
*/
|
||||
if (PHP_SAPI === 'cli') {
|
||||
// Set the fullBaseUrl to allow URLs to be generated in commands.
|
||||
// This is useful when sending email from commands.
|
||||
// Configure::write('App.fullBaseUrl', php_uname('n'));
|
||||
|
||||
// Set logs to different files so they don't have permission conflicts.
|
||||
if (Configure::check('Log.debug')) {
|
||||
Configure::write('Log.debug.file', 'cli-debug');
|
||||
}
|
||||
if (Configure::check('Log.error')) {
|
||||
Configure::write('Log.error.file', 'cli-error');
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Set the full base URL for the application.
|
||||
*
|
||||
* SECURITY: In production, App.fullBaseUrl MUST be explicitly configured to prevent
|
||||
* Host Header Injection attacks. The HostHeaderMiddleware enforces this requirement
|
||||
* and validates incoming Host headers against the configured value.
|
||||
*
|
||||
* Set APP_FULL_BASE_URL in your environment variables or configure App.fullBaseUrl
|
||||
* in config/app.php or config/app_local.php
|
||||
*
|
||||
* Example: APP_FULL_BASE_URL=https://example.com
|
||||
*/
|
||||
$fullBaseUrl = Configure::read('App.fullBaseUrl');
|
||||
if (!$fullBaseUrl) {
|
||||
$httpHost = env('HTTP_HOST');
|
||||
|
||||
/*
|
||||
* Development mode fallback: Use HTTP_HOST for convenience.
|
||||
* WARNING: This is ONLY safe in development. In production, the
|
||||
* HostHeaderMiddleware will reject requests when fullBaseUrl is not configured.
|
||||
*/
|
||||
if ($httpHost) {
|
||||
$s = null;
|
||||
if (env('HTTPS') || env('HTTP_X_FORWARDED_PROTO') === 'https') {
|
||||
$s = 's';
|
||||
}
|
||||
$fullBaseUrl = 'http' . $s . '://' . $httpHost;
|
||||
}
|
||||
unset($httpHost, $s);
|
||||
}
|
||||
if ($fullBaseUrl) {
|
||||
Router::fullBaseUrl($fullBaseUrl);
|
||||
}
|
||||
unset($fullBaseUrl);
|
||||
|
||||
/*
|
||||
* Apply the loaded configuration settings to their respective systems.
|
||||
* This will also remove the loaded config data from memory.
|
||||
*/
|
||||
Cache::setConfig(Configure::consume('Cache'));
|
||||
ConnectionManager::setConfig(Configure::consume('Datasources'));
|
||||
TransportFactory::setConfig(Configure::consume('EmailTransport'));
|
||||
Mailer::setConfig(Configure::consume('Email'));
|
||||
Log::setConfig(Configure::consume('Log'));
|
||||
Security::setSalt(Configure::consume('Security.salt'));
|
||||
|
||||
/*
|
||||
* Setup detectors for mobile and tablet.
|
||||
* If you don't use these checks you can safely remove this code
|
||||
* and the mobiledetect package from composer.json.
|
||||
*/
|
||||
ServerRequest::addDetector('mobile', function ($request) {
|
||||
$detector = new MobileDetect();
|
||||
|
||||
return $detector->isMobile();
|
||||
});
|
||||
ServerRequest::addDetector('tablet', function ($request) {
|
||||
$detector = new MobileDetect();
|
||||
|
||||
return $detector->isTablet();
|
||||
});
|
||||
|
||||
/*
|
||||
* You can enable default locale format parsing by adding calls
|
||||
* to `useLocaleParser()`. This enables the automatic conversion of
|
||||
* locale specific date formats when processing request data. For details see
|
||||
* @link https://book.cakephp.org/5/en/core-libraries/internationalization-and-localization.html#parsing-localized-datetime-data
|
||||
*/
|
||||
// \Cake\Database\TypeFactory::build('time')->useLocaleParser();
|
||||
// \Cake\Database\TypeFactory::build('date')->useLocaleParser();
|
||||
// \Cake\Database\TypeFactory::build('datetime')->useLocaleParser();
|
||||
// \Cake\Database\TypeFactory::build('timestamp')->useLocaleParser();
|
||||
// \Cake\Database\TypeFactory::build('datetimefractional')->useLocaleParser();
|
||||
// \Cake\Database\TypeFactory::build('timestampfractional')->useLocaleParser();
|
||||
// \Cake\Database\TypeFactory::build('datetimetimezone')->useLocaleParser();
|
||||
// \Cake\Database\TypeFactory::build('timestamptimezone')->useLocaleParser();
|
||||
|
||||
/*
|
||||
* Custom Inflector rules, can be set to correctly pluralize or singularize
|
||||
* table, model, controller names or whatever other string is passed to the
|
||||
* inflection functions.
|
||||
*/
|
||||
// \Cake\Utility\Inflector::rules('plural', ['/^(inflect)or$/i' => '\1ables']);
|
||||
// \Cake\Utility\Inflector::rules('irregular', ['red' => 'redlings']);
|
||||
// \Cake\Utility\Inflector::rules('uninflected', ['dontinflectme']);
|
||||
|
||||
// set a custom date and time format
|
||||
// see https://book.cakephp.org/5/en/core-libraries/time.html#setting-the-default-locale-and-format-string
|
||||
// and https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax
|
||||
// \Cake\I18n\Date::setToStringFormat('dd.MM.yyyy');
|
||||
// \Cake\I18n\Time::setToStringFormat('dd.MM.yyyy HH:mm');
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license MIT License (https://opensource.org/licenses/mit-license.php)
|
||||
*/
|
||||
|
||||
/*
|
||||
* Use the DS to separate the directories in other defines
|
||||
*/
|
||||
if (!defined('DS')) {
|
||||
define('DS', DIRECTORY_SEPARATOR);
|
||||
}
|
||||
|
||||
/*
|
||||
* These definitions should only be edited if you have cake installed in
|
||||
* a directory layout other than the way it is distributed.
|
||||
* When using custom settings be sure to use the DS and do not add a trailing DS.
|
||||
*/
|
||||
|
||||
/*
|
||||
* The full path to the directory which holds "src", WITHOUT a trailing DS.
|
||||
*/
|
||||
define('ROOT', dirname(__DIR__));
|
||||
|
||||
/*
|
||||
* The actual directory name for the application directory. Normally
|
||||
* named 'src'.
|
||||
*/
|
||||
define('APP_DIR', 'src');
|
||||
|
||||
/*
|
||||
* Path to the application's directory.
|
||||
*/
|
||||
define('APP', ROOT . DS . APP_DIR . DS);
|
||||
|
||||
/*
|
||||
* Path to the config directory.
|
||||
*/
|
||||
define('CONFIG', ROOT . DS . 'config' . DS);
|
||||
|
||||
/*
|
||||
* File path to the webroot directory.
|
||||
*
|
||||
* To derive your webroot from your webserver change this to:
|
||||
*
|
||||
* `define('WWW_ROOT', rtrim($_SERVER['DOCUMENT_ROOT'], DS) . DS);`
|
||||
*/
|
||||
define('WWW_ROOT', ROOT . DS . 'webroot' . DS);
|
||||
|
||||
/*
|
||||
* Path to the tests directory.
|
||||
*/
|
||||
define('TESTS', ROOT . DS . 'tests' . DS);
|
||||
|
||||
/*
|
||||
* Path to the temporary files directory.
|
||||
*/
|
||||
define('TMP', ROOT . DS . 'tmp' . DS);
|
||||
|
||||
/*
|
||||
* Path to the logs directory.
|
||||
*/
|
||||
define('LOGS', ROOT . DS . 'logs' . DS);
|
||||
|
||||
/*
|
||||
* Path to the cache files directory. It can be shared between hosts in a multi-server setup.
|
||||
*/
|
||||
define('CACHE', TMP . 'cache' . DS);
|
||||
|
||||
/*
|
||||
* Path to the resources directory.
|
||||
*/
|
||||
define('RESOURCES', ROOT . DS . 'resources' . DS);
|
||||
|
||||
/*
|
||||
* The absolute path to the "cake" directory, WITHOUT a trailing DS.
|
||||
*
|
||||
* CakePHP should always be installed with composer, so look there.
|
||||
*/
|
||||
define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp');
|
||||
|
||||
/*
|
||||
* Path to the cake directory.
|
||||
*/
|
||||
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
|
||||
define('CAKE', CORE_PATH . 'src' . DS);
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
/**
|
||||
* Plugin configuration.
|
||||
*
|
||||
* In this file, you configure which plugins are loaded in the different states your app can be.
|
||||
* It's loaded via the `parent::bootstrap();` call inside your `Application::bootstrap()` method.
|
||||
* For more information see https://book.cakephp.org/5/en/plugins.html#loading-plugins-via-configuration-array
|
||||
*
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 5.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
/*
|
||||
* List of plugins to load in the form `PluginName` => `[configuration options]`.
|
||||
*
|
||||
* Available options:
|
||||
* - onlyDebug: Load the plugin only in debug mode. Default false.
|
||||
* - onlyCli: Load the plugin only in CLI mode. Default false.
|
||||
* - optional: Do not throw an exception if the plugin is not found. Default false.
|
||||
*/
|
||||
return [
|
||||
'DebugKit' => ['onlyDebug' => true],
|
||||
'Bake' => ['onlyCli' => true, 'optional' => true],
|
||||
'Migrations' => ['onlyCli' => true],
|
||||
|
||||
// Additional plugins here
|
||||
];
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
/**
|
||||
* Plenario routes.
|
||||
*
|
||||
* Public: / start page (create poll, join by code)
|
||||
* /recover re-send admin links by e-mail
|
||||
* /p/{code} participant view
|
||||
* Admin: /admin/{token}/... everything behind the secret admin token
|
||||
*
|
||||
* All routes are named so templates build URLs via ['_name' => ...].
|
||||
* There are intentionally NO fallback routes.
|
||||
*/
|
||||
|
||||
use Cake\Routing\Route\DashedRoute;
|
||||
use Cake\Routing\RouteBuilder;
|
||||
|
||||
return function (RouteBuilder $routes): void {
|
||||
$routes->setRouteClass(DashedRoute::class);
|
||||
|
||||
$routes->scope('/', function (RouteBuilder $builder): void {
|
||||
// --- public -------------------------------------------------------
|
||||
$builder->connect('/', 'Home::index', ['_name' => 'home']);
|
||||
$builder->connect('/create', 'Home::create', ['_name' => 'create'])->setMethods(['POST']);
|
||||
$builder->connect('/created', 'Home::created', ['_name' => 'created']);
|
||||
$builder->connect('/join', 'Home::join', ['_name' => 'join']);
|
||||
$builder->connect('/recover', 'Home::recover', ['_name' => 'recover']);
|
||||
|
||||
// --- participants -------------------------------------------------
|
||||
$builder->connect('/p', 'Home::join', ['_name' => 'join:short']);
|
||||
$builder->connect('/p/{code}', 'Participate::view', ['_name' => 'participate'])
|
||||
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
|
||||
->setPass(['code']);
|
||||
$builder->connect('/p/{code}/state', 'Participate::state', ['_name' => 'participate:state'])
|
||||
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
|
||||
->setPass(['code']);
|
||||
$builder->connect('/p/{code}/vote', 'Participate::vote', ['_name' => 'participate:vote'])
|
||||
->setPatterns(['code' => '[A-Za-z0-9-]{4,16}'])
|
||||
->setPass(['code'])
|
||||
->setMethods(['POST']);
|
||||
|
||||
// --- admin (secret token) -----------------------------------------
|
||||
$builder->scope('/admin/{token}', function (RouteBuilder $admin): void {
|
||||
$token = ['token' => '[A-Za-z0-9_-]{20,64}', 'id' => '\d+'];
|
||||
|
||||
$admin->connect('/', 'Admin::index', ['_name' => 'admin'])->setPatterns($token);
|
||||
$admin->connect('/settings', 'Admin::settings', ['_name' => 'admin:settings'])
|
||||
->setPatterns($token)->setMethods(['POST']);
|
||||
$admin->connect('/rotate-token', 'Admin::rotateToken', ['_name' => 'admin:rotate'])
|
||||
->setPatterns($token)->setMethods(['POST']);
|
||||
$admin->connect('/delete', 'Admin::delete', ['_name' => 'admin:delete'])
|
||||
->setPatterns($token)->setMethods(['POST']);
|
||||
$admin->connect('/present', 'Admin::present', ['_name' => 'admin:present'])->setPatterns($token);
|
||||
$admin->connect('/state', 'Admin::state', ['_name' => 'admin:state'])->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);
|
||||
$admin->connect('/export.csv', 'Admin::export', ['_name' => 'admin:export'])->setPatterns($token);
|
||||
|
||||
$admin->connect('/slides/add', 'Slides::add', ['_name' => 'slides:add'])->setPatterns($token);
|
||||
$admin->connect('/slides/{id}/edit', 'Slides::edit', ['_name' => 'slides:edit'])
|
||||
->setPatterns($token)->setPass(['id']);
|
||||
$admin->connect('/slides/{id}/delete', 'Slides::delete', ['_name' => 'slides:delete'])
|
||||
->setPatterns($token)->setPass(['id'])->setMethods(['POST']);
|
||||
$admin->connect('/slides/{id}/move/{direction}', 'Slides::move', ['_name' => 'slides:move'])
|
||||
->setPatterns($token + ['direction' => 'up|down'])->setPass(['id', 'direction'])->setMethods(['POST']);
|
||||
$admin->connect('/slides/{id}/reset', 'Slides::reset', ['_name' => 'slides:reset'])
|
||||
->setPatterns($token)->setPass(['id'])->setMethods(['POST']);
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
#
|
||||
# Licensed under The MIT License
|
||||
# For full copyright and license information, please see the LICENSE.txt
|
||||
# Redistributions of files must retain the above copyright notice.
|
||||
# MIT License (https://opensource.org/licenses/mit-license.php)
|
||||
|
||||
CREATE TABLE i18n (
|
||||
id int NOT NULL auto_increment,
|
||||
locale varchar(6) NOT NULL,
|
||||
model varchar(255) NOT NULL,
|
||||
foreign_key int(10) NOT NULL,
|
||||
field varchar(255) NOT NULL,
|
||||
content text,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE INDEX I18N_LOCALE_FIELD(locale, model, foreign_key, field),
|
||||
INDEX I18N_FIELD(model, foreign_key, field)
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
#
|
||||
# Licensed under The MIT License
|
||||
# For full copyright and license information, please see the LICENSE.txt
|
||||
# Redistributions of files must retain the above copyright notice.
|
||||
# MIT License (https://opensource.org/licenses/mit-license.php)
|
||||
|
||||
CREATE TABLE `sessions` (
|
||||
`id` char(40) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
|
||||
`created` datetime DEFAULT CURRENT_TIMESTAMP, -- optional, requires MySQL 5.6.5+
|
||||
`modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- optional, requires MySQL 5.6.5+
|
||||
`data` blob DEFAULT NULL, -- for PostgreSQL use bytea instead of blob
|
||||
`expires` int(10) unsigned DEFAULT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
Whitespace-only changes.
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
|
||||
require 'webroot' . DIRECTORY_SEPARATOR . 'index.php';
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0"?>
|
||||
<ruleset name="App">
|
||||
<rule ref="CakePHP"/>
|
||||
<rule ref="SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingNativeTypeHint">
|
||||
<exclude-pattern>*/src/Controller/*</exclude-pattern>
|
||||
</rule>
|
||||
|
||||
<file>src/</file>
|
||||
<file>tests/</file>
|
||||
</ruleset>
|
||||
@@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
colors="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
bootstrap="tests/bootstrap.php"
|
||||
cacheDirectory=".phpunit.cache"
|
||||
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.1/phpunit.xsd">
|
||||
<php>
|
||||
<ini name="memory_limit" value="-1"/>
|
||||
</php>
|
||||
|
||||
<!-- Add any additional test suites you want to run here -->
|
||||
<testsuites>
|
||||
<testsuite name="app">
|
||||
<directory>tests/TestCase/</directory>
|
||||
</testsuite>
|
||||
<!-- Add plugin test suites here. -->
|
||||
</testsuites>
|
||||
|
||||
<!-- Load extension for fixtures -->
|
||||
<extensions>
|
||||
<bootstrap class="Cake\TestSuite\Fixture\Extension\PHPUnitExtension"/>
|
||||
</extensions>
|
||||
|
||||
<!-- Ignore vendor tests in code coverage reports -->
|
||||
<source>
|
||||
<include>
|
||||
<directory suffix=".php">src/</directory>
|
||||
<directory suffix=".php">plugins/*/src/</directory>
|
||||
</include>
|
||||
<exclude>
|
||||
<file>src/Console/Installer.php</file>
|
||||
</exclude>
|
||||
</source>
|
||||
</phpunit>
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.3.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App;
|
||||
|
||||
use App\Middleware\HostHeaderMiddleware;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Core\ContainerInterface;
|
||||
use Cake\Datasource\FactoryLocator;
|
||||
use Cake\Error\Middleware\ErrorHandlerMiddleware;
|
||||
use Cake\Event\EventManagerInterface;
|
||||
use Cake\Http\BaseApplication;
|
||||
use Cake\Http\Middleware\BodyParserMiddleware;
|
||||
use Cake\Http\Middleware\CsrfProtectionMiddleware;
|
||||
use Cake\Http\MiddlewareQueue;
|
||||
use Cake\ORM\Locator\TableLocator;
|
||||
use Cake\Routing\Middleware\AssetMiddleware;
|
||||
use Cake\Routing\Middleware\RoutingMiddleware;
|
||||
|
||||
/**
|
||||
* Application setup class.
|
||||
*
|
||||
* This defines the bootstrapping logic and middleware layers you
|
||||
* want to use in your application.
|
||||
*
|
||||
* @extends \Cake\Http\BaseApplication<\App\Application>
|
||||
*/
|
||||
class Application extends BaseApplication
|
||||
{
|
||||
/**
|
||||
* Load all the application configuration and bootstrap logic.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function bootstrap(): void
|
||||
{
|
||||
// Call parent to load bootstrap from files.
|
||||
parent::bootstrap();
|
||||
|
||||
// By default, does not allow fallback classes.
|
||||
FactoryLocator::add(
|
||||
'Table',
|
||||
(new TableLocator())->allowFallbackClass(false),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the middleware queue your application will use.
|
||||
*
|
||||
* @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
|
||||
* @return \Cake\Http\MiddlewareQueue The updated middleware queue.
|
||||
*/
|
||||
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
|
||||
{
|
||||
$middlewareQueue
|
||||
// Catch any exceptions in the lower layers,
|
||||
// and make an error page/response
|
||||
->add(new ErrorHandlerMiddleware(Configure::read('Error'), $this))
|
||||
|
||||
// Validate Host header to prevent Host Header Injection attacks.
|
||||
// In production, ensures App.fullBaseUrl is configured and validates
|
||||
// the incoming Host header against it.
|
||||
->add(new HostHeaderMiddleware())
|
||||
|
||||
// Handle plugin/theme assets like CakePHP normally does.
|
||||
->add(new AssetMiddleware([
|
||||
'cacheTime' => Configure::read('Asset.cacheTime'),
|
||||
]))
|
||||
|
||||
// Add routing middleware.
|
||||
// If you have a large number of routes connected, turning on routes
|
||||
// caching in production could improve performance.
|
||||
// See https://github.com/CakeDC/cakephp-cached-routing
|
||||
->add(new RoutingMiddleware($this))
|
||||
|
||||
// Parse various types of encoded request bodies so that they are
|
||||
// available as array through $request->getData()
|
||||
// https://book.cakephp.org/5/en/controllers/middleware.html#body-parser-middleware
|
||||
->add(new BodyParserMiddleware())
|
||||
|
||||
// Cross Site Request Forgery (CSRF) Protection Middleware
|
||||
// https://book.cakephp.org/5/en/security/csrf.html#cross-site-request-forgery-csrf-middleware
|
||||
->add(new CsrfProtectionMiddleware([
|
||||
'httponly' => true,
|
||||
]));
|
||||
|
||||
return $middlewareQueue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register application container services.
|
||||
*
|
||||
* @param \Cake\Core\ContainerInterface $container The Container to update.
|
||||
* @return void
|
||||
* @link https://book.cakephp.org/5/en/development/dependency-injection.html#dependency-injection
|
||||
*/
|
||||
public function services(ContainerInterface $container): void
|
||||
{
|
||||
// Allow your Tables to be dependency injected
|
||||
//$container->delegate(new \Cake\ORM\Locator\TableContainer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Register custom event listeners here
|
||||
*
|
||||
* @param \Cake\Event\EventManagerInterface $eventManager
|
||||
* @return \Cake\Event\EventManagerInterface
|
||||
* @link https://book.cakephp.org/5/en/core-libraries/events.html#registering-listeners
|
||||
*/
|
||||
public function events(EventManagerInterface $eventManager): EventManagerInterface
|
||||
{
|
||||
// $eventManager->on(new SomeCustomListenerClass());
|
||||
|
||||
return $eventManager;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Captcha;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Builds the captcha configured in `Plenario.captcha.type`.
|
||||
*/
|
||||
class CaptchaFactory
|
||||
{
|
||||
/**
|
||||
* @param string $scope Form scope ("create", "recover", ...)
|
||||
* @param string|null $type Override the configured type
|
||||
* @return \App\Captcha\CaptchaInterface
|
||||
*/
|
||||
public static function create(string $scope, ?string $type = null): CaptchaInterface
|
||||
{
|
||||
$type ??= (string)Configure::read('Plenario.captcha.type', 'math');
|
||||
|
||||
return match (strtolower($type)) {
|
||||
'none', '', 'off', 'false' => new NoCaptcha(),
|
||||
'math' => new MathCaptcha($scope),
|
||||
'recaptcha' => new RecaptchaCaptcha(
|
||||
(string)Configure::read('Plenario.captcha.recaptcha.siteKey', ''),
|
||||
(string)Configure::read('Plenario.captcha.recaptcha.secretKey', ''),
|
||||
),
|
||||
default => throw new InvalidArgumentException(sprintf(
|
||||
'Unknown captcha type "%s". Use none, math or recaptcha.',
|
||||
$type,
|
||||
)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Captcha;
|
||||
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* A captcha protects the public forms (create poll, recover links).
|
||||
*
|
||||
* Lifecycle: the controller calls challenge() when rendering the form and passes
|
||||
* the returned array to the `captcha` element; on submit it calls verify().
|
||||
*/
|
||||
interface CaptchaInterface
|
||||
{
|
||||
/**
|
||||
* @return string 'none' | 'math' | 'recaptcha'
|
||||
*/
|
||||
public function getType(): string;
|
||||
|
||||
/**
|
||||
* Prepares a challenge and returns the data the view element needs.
|
||||
*
|
||||
* @param \Cake\Http\ServerRequest $request Current request (session access)
|
||||
* @return array<string, mixed> Always contains 'type'
|
||||
*/
|
||||
public function challenge(ServerRequest $request): array;
|
||||
|
||||
/**
|
||||
* @param \Cake\Http\ServerRequest $request Submitted request
|
||||
* @return bool
|
||||
*/
|
||||
public function verify(ServerRequest $request): bool;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Captcha;
|
||||
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* Simple arithmetic captcha ("Was ist 4 + 7?"). The expected answer is kept in
|
||||
* the session per form scope and is valid for a single verification only.
|
||||
*
|
||||
* Request field: `captcha_answer`.
|
||||
*/
|
||||
class MathCaptcha implements CaptchaInterface
|
||||
{
|
||||
public const FIELD = 'captcha_answer';
|
||||
|
||||
/**
|
||||
* @param string $scope Form scope, e.g. "create" or "recover"
|
||||
*/
|
||||
public function __construct(protected string $scope)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return 'math';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
protected function sessionKey(): string
|
||||
{
|
||||
return 'Captcha.math.' . $this->scope;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function challenge(ServerRequest $request): array
|
||||
{
|
||||
$a = random_int(1, 12);
|
||||
$b = random_int(1, 9);
|
||||
if (random_int(0, 1) === 1 && $a > $b) {
|
||||
$question = sprintf('%d − %d', $a, $b);
|
||||
$answer = $a - $b;
|
||||
} else {
|
||||
$question = sprintf('%d + %d', $a, $b);
|
||||
$answer = $a + $b;
|
||||
}
|
||||
$request->getSession()->write($this->sessionKey(), $answer);
|
||||
|
||||
return ['type' => 'math', 'question' => $question, 'field' => self::FIELD];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function verify(ServerRequest $request): bool
|
||||
{
|
||||
$session = $request->getSession();
|
||||
$expected = $session->read($this->sessionKey());
|
||||
$session->delete($this->sessionKey());
|
||||
|
||||
$given = trim((string)$request->getData(self::FIELD, ''));
|
||||
if ($expected === null || $given === '' || !preg_match('/^-?\d+$/', $given)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int)$given === (int)$expected;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Captcha;
|
||||
|
||||
use Cake\Http\ServerRequest;
|
||||
|
||||
/**
|
||||
* Captcha disabled (CAPTCHA_TYPE=none).
|
||||
*/
|
||||
class NoCaptcha implements CaptchaInterface
|
||||
{
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return 'none';
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function challenge(ServerRequest $request): array
|
||||
{
|
||||
return ['type' => 'none'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function verify(ServerRequest $request): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Captcha;
|
||||
|
||||
use Cake\Http\Client;
|
||||
use Cake\Http\ServerRequest;
|
||||
use Cake\Log\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Google reCAPTCHA v2 checkbox. Requires RECAPTCHA_SITE_KEY and RECAPTCHA_SECRET_KEY.
|
||||
* Fails closed: missing keys or network errors reject the submission.
|
||||
*
|
||||
* Request field: `g-recaptcha-response` (set by Google's widget).
|
||||
*/
|
||||
class RecaptchaCaptcha implements CaptchaInterface
|
||||
{
|
||||
public const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
|
||||
public const FIELD = 'g-recaptcha-response';
|
||||
|
||||
protected Client $client;
|
||||
|
||||
/**
|
||||
* @param string $siteKey Public site key
|
||||
* @param string $secretKey Secret key
|
||||
* @param \Cake\Http\Client|null $client HTTP client (injectable for tests)
|
||||
*/
|
||||
public function __construct(
|
||||
protected string $siteKey,
|
||||
protected string $secretKey,
|
||||
?Client $client = null,
|
||||
) {
|
||||
$this->client = $client ?? new Client(['timeout' => 5]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return 'recaptcha';
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function challenge(ServerRequest $request): array
|
||||
{
|
||||
return ['type' => 'recaptcha', 'siteKey' => $this->siteKey];
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function verify(ServerRequest $request): bool
|
||||
{
|
||||
$token = (string)$request->getData(self::FIELD, '');
|
||||
if ($token === '') {
|
||||
return false;
|
||||
}
|
||||
if ($this->siteKey === '' || $this->secretKey === '') {
|
||||
Log::error('reCAPTCHA is enabled but RECAPTCHA_SITE_KEY / RECAPTCHA_SECRET_KEY are not configured.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->client->post(self::VERIFY_URL, [
|
||||
'secret' => $this->secretKey,
|
||||
'response' => $token,
|
||||
'remoteip' => $request->clientIp(),
|
||||
]);
|
||||
$json = $response->getJson();
|
||||
} catch (Throwable $e) {
|
||||
Log::error('reCAPTCHA verification failed: ' . $e->getMessage());
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return is_array($json) && ($json['success'] ?? false) === true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\Console;
|
||||
|
||||
if (!defined('STDIN')) {
|
||||
define('STDIN', fopen('php://stdin', 'r'));
|
||||
}
|
||||
|
||||
use Cake\Codeception\Console\Installer as CodeceptionInstaller;
|
||||
use Cake\Utility\Security;
|
||||
use Composer\IO\IOInterface;
|
||||
use Composer\Script\Event;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Provides installation hooks for when this application is installed through
|
||||
* composer. Customize this class to suit your needs.
|
||||
*/
|
||||
class Installer
|
||||
{
|
||||
/**
|
||||
* An array of directories to be made writable
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
public const WRITABLE_DIRS = [
|
||||
'logs',
|
||||
'tmp',
|
||||
'tmp/cache',
|
||||
'tmp/cache/models',
|
||||
'tmp/cache/persistent',
|
||||
'tmp/cache/views',
|
||||
'tmp/sessions',
|
||||
'tmp/tests',
|
||||
];
|
||||
|
||||
/**
|
||||
* Does some routine installation tasks so people don't have to.
|
||||
*
|
||||
* @param \Composer\Script\Event $event The composer event object.
|
||||
* @throws \Exception Exception raised by validator.
|
||||
* @return void
|
||||
*/
|
||||
public static function postInstall(Event $event): void
|
||||
{
|
||||
$io = $event->getIO();
|
||||
|
||||
$rootDir = dirname(__DIR__, 2);
|
||||
|
||||
static::createAppLocalConfig($rootDir, $io);
|
||||
static::createWritableDirectories($rootDir, $io);
|
||||
|
||||
static::setFolderPermissions($rootDir, $io);
|
||||
static::setSecuritySalt($rootDir, $io);
|
||||
|
||||
if (class_exists(CodeceptionInstaller::class)) {
|
||||
CodeceptionInstaller::customizeCodeceptionBinary($event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create config/app_local.php file if it does not exist.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function createAppLocalConfig(string $dir, IOInterface $io): void
|
||||
{
|
||||
$appLocalConfig = $dir . '/config/app_local.php';
|
||||
$appLocalConfigTemplate = $dir . '/config/app_local.example.php';
|
||||
if (!file_exists($appLocalConfig)) {
|
||||
copy($appLocalConfigTemplate, $appLocalConfig);
|
||||
$io->write('Created `config/app_local.php` file');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the `logs` and `tmp` directories.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function createWritableDirectories(string $dir, IOInterface $io): void
|
||||
{
|
||||
foreach (static::WRITABLE_DIRS as $path) {
|
||||
$path = $dir . '/' . $path;
|
||||
if (!file_exists($path)) {
|
||||
mkdir($path);
|
||||
$io->write('Created `' . $path . '` directory');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set globally writable permissions on the "tmp" and "logs" directory.
|
||||
*
|
||||
* This is not the most secure default, but it gets people up and running quickly.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function setFolderPermissions(string $dir, IOInterface $io): void
|
||||
{
|
||||
// ask if the permissions should be changed
|
||||
if ($io->isInteractive()) {
|
||||
$validator = function (string $arg): string {
|
||||
if (in_array($arg, ['Y', 'y', 'N', 'n'])) {
|
||||
return $arg;
|
||||
}
|
||||
throw new Exception('This is not a valid answer. Please choose Y or n.');
|
||||
};
|
||||
$setFolderPermissions = $io->askAndValidate(
|
||||
'<info>Set Folder Permissions ? (Default to Y)</info> [<comment>Y,n</comment>]? ',
|
||||
$validator,
|
||||
10,
|
||||
'Y',
|
||||
);
|
||||
|
||||
if (in_array($setFolderPermissions, ['n', 'N'])) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Change the permissions on a path and output the results.
|
||||
$changePerms = function (string $path) use ($io): void {
|
||||
$currentPerms = fileperms($path) & 0777;
|
||||
$worldWritable = $currentPerms | 0007;
|
||||
if ($worldWritable == $currentPerms) {
|
||||
return;
|
||||
}
|
||||
|
||||
$res = chmod($path, $worldWritable);
|
||||
if ($res) {
|
||||
$io->write('Permissions set on ' . $path);
|
||||
} else {
|
||||
$io->write('Failed to set permissions on ' . $path);
|
||||
}
|
||||
};
|
||||
|
||||
$walker = function (string $dir) use (&$walker, $changePerms): void {
|
||||
$files = array_diff(scandir($dir) ?: [], ['.', '..']);
|
||||
foreach ($files as $file) {
|
||||
$path = $dir . '/' . $file;
|
||||
|
||||
if (!is_dir($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$changePerms($path);
|
||||
$walker($path);
|
||||
}
|
||||
};
|
||||
|
||||
$walker($dir . '/tmp');
|
||||
$changePerms($dir . '/tmp');
|
||||
$changePerms($dir . '/logs');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the security.salt value in the application's config file.
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @return void
|
||||
*/
|
||||
public static function setSecuritySalt(string $dir, IOInterface $io): void
|
||||
{
|
||||
$newKey = hash('sha256', Security::randomBytes(64));
|
||||
static::setSecuritySaltInFile($dir, $io, $newKey, 'app_local.php');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the security.salt value in a given file
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @param string $newKey key to set in the file
|
||||
* @param string $file A path to a file relative to the application's root
|
||||
* @return void
|
||||
*/
|
||||
public static function setSecuritySaltInFile(string $dir, IOInterface $io, string $newKey, string $file): void
|
||||
{
|
||||
$config = $dir . '/config/' . $file;
|
||||
$content = file_get_contents($config);
|
||||
if ($content === false) {
|
||||
$io->write('Config file not readable or not found: config/' . $file);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$content = str_replace('__SALT__', $newKey, $content, $count);
|
||||
|
||||
if ($count == 0) {
|
||||
$io->write('No Security.salt placeholder to replace.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = file_put_contents($config, $content);
|
||||
if ($result) {
|
||||
$io->write('Updated Security.salt value in config/' . $file);
|
||||
|
||||
return;
|
||||
}
|
||||
$io->write('Unable to update Security.salt value.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the APP_NAME value in a given file
|
||||
*
|
||||
* @param string $dir The application's root directory.
|
||||
* @param \Composer\IO\IOInterface $io IO interface to write to console.
|
||||
* @param string $appName app name to set in the file
|
||||
* @param string $file A path to a file relative to the application's root
|
||||
* @return void
|
||||
*/
|
||||
public static function setAppNameInFile(string $dir, IOInterface $io, string $appName, string $file): void
|
||||
{
|
||||
$config = $dir . '/config/' . $file;
|
||||
$content = file_get_contents($config);
|
||||
if ($content === false) {
|
||||
$io->write('Config file not readable or not found: config/' . $file);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$content = str_replace('__APP_NAME__', $appName, $content, $count);
|
||||
|
||||
if ($count == 0) {
|
||||
$io->write('No __APP_NAME__ placeholder to replace.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = file_put_contents($config, $content);
|
||||
if ($result) {
|
||||
$io->write('Updated __APP_NAME__ value in config/' . $file);
|
||||
|
||||
return;
|
||||
}
|
||||
$io->write('Unable to update __APP_NAME__ value.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Table\PollsTable;
|
||||
use Cake\Event\EventInterface;
|
||||
use Cake\Http\Exception\NotFoundException;
|
||||
use Cake\Http\Response;
|
||||
use Cake\I18n\DateTime;
|
||||
|
||||
/**
|
||||
* Base class for everything under /admin/{token}.
|
||||
*
|
||||
* "Authentication" = possession of the secret token. The poll is resolved via
|
||||
* the sha256 hash of the token in beforeFilter(); unknown tokens yield a 404.
|
||||
* Subclasses use $this->poll and $this->token.
|
||||
*/
|
||||
abstract class AdminAppController extends AppController
|
||||
{
|
||||
protected PollsTable $Polls;
|
||||
|
||||
protected Poll $poll;
|
||||
|
||||
protected string $token;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
/** @var \App\Model\Table\PollsTable $polls */
|
||||
$polls = $this->fetchTable('Polls');
|
||||
$this->Polls = $polls;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
|
||||
* @return void
|
||||
*/
|
||||
public function beforeFilter(EventInterface $event): void
|
||||
{
|
||||
parent::beforeFilter($event);
|
||||
|
||||
$this->token = (string)$this->request->getParam('token');
|
||||
/** @var \App\Model\Entity\Poll|null $poll */
|
||||
$poll = $this->Polls->find('byAdminToken', token: $this->token)->first();
|
||||
if ($poll === null) {
|
||||
throw new NotFoundException(__('Diese Admin-URL ist ungültig.'));
|
||||
}
|
||||
$this->poll = $poll;
|
||||
|
||||
// Track usage at most every 10 minutes to avoid a write per request.
|
||||
if ($poll->last_admin_access === null || $poll->last_admin_access->wasWithinLast('10 minutes') === false) {
|
||||
$this->Polls->updateAll(['last_admin_access' => DateTime::now()], ['id' => $poll->id]);
|
||||
}
|
||||
|
||||
$this->set('poll', $poll);
|
||||
$this->set('adminToken', $this->token);
|
||||
}
|
||||
|
||||
/**
|
||||
* The token is part of the URL: never send it as referrer, never index it, never cache it.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
|
||||
* @return void
|
||||
*/
|
||||
public function beforeRender(EventInterface $event): void
|
||||
{
|
||||
parent::beforeRender($event);
|
||||
$this->response = $this->protect($this->response);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Http\Response $response Response
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
protected function protect(Response $response): Response
|
||||
{
|
||||
return $response
|
||||
->withHeader('Referrer-Policy', 'no-referrer')
|
||||
->withHeader('X-Robots-Tag', 'noindex, nofollow')
|
||||
->withHeader('Cache-Control', 'no-store, private');
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
protected function json(array $data, int $status = 200): Response
|
||||
{
|
||||
return $this->protect(parent::json($data, $status));
|
||||
}
|
||||
|
||||
/**
|
||||
* URL array for a named admin route of the current poll.
|
||||
*
|
||||
* @param string $name Route name
|
||||
* @param array<string, mixed> $params Extra params
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function adminUrl(string $name = 'admin', array $params = []): array
|
||||
{
|
||||
return ['_name' => $name, 'token' => $this->token] + $params;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Mailer\PollMailer;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\ResponsesTable;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use App\Service\PollStateService;
|
||||
use App\Service\VoteService;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Http\Exception\BadRequestException;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Log\Log;
|
||||
use Cake\Routing\Router;
|
||||
use chillerlan\QRCode\Output\QRMarkupSVG;
|
||||
use chillerlan\QRCode\QRCode;
|
||||
use chillerlan\QRCode\QROptions;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Poll level admin actions: dashboard, settings, presenter mode, export.
|
||||
*/
|
||||
class AdminController extends AdminAppController
|
||||
{
|
||||
protected SlidesTable $Slides;
|
||||
|
||||
protected ResponsesTable $Responses;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
/** @var \App\Model\Table\SlidesTable $slides */
|
||||
$slides = $this->fetchTable('Slides');
|
||||
$this->Slides = $slides;
|
||||
/** @var \App\Model\Table\ResponsesTable $responses */
|
||||
$responses = $this->fetchTable('Responses');
|
||||
$this->Responses = $responses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard: settings + slide list.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function index(): void
|
||||
{
|
||||
$slides = $this->Slides->listForPoll($this->poll->id);
|
||||
$responseCounts = $this->Responses->countParticipantsPerSlide($this->poll->id);
|
||||
$typeLabels = Slide::typeLabels();
|
||||
$typeDescriptions = Slide::typeDescriptions();
|
||||
$joinUrl = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true);
|
||||
|
||||
$this->set(compact('slides', 'responseCounts', 'typeLabels', 'typeDescriptions', 'joinUrl'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function settings(): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$this->Polls->patchEntity($this->poll, (array)$this->request->getData(), [
|
||||
'fields' => ['title', 'is_active', 'show_results_to_participants'],
|
||||
]);
|
||||
if ($this->Polls->save($this->poll)) {
|
||||
$this->Flash->success(__('Einstellungen gespeichert.'));
|
||||
} else {
|
||||
$this->Flash->error(__('Die Einstellungen konnten nicht gespeichert werden.'));
|
||||
}
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidates the current admin link and mails a new one.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function rotateToken(): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$token = $this->Polls->assignNewToken($this->poll);
|
||||
$this->Polls->saveOrFail($this->poll);
|
||||
$this->token = $token;
|
||||
|
||||
$adminUrl = Router::url($this->adminUrl(), true);
|
||||
$joinUrl = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true);
|
||||
try {
|
||||
(new PollMailer())->send('adminLink', [$this->poll, $adminUrl, $joinUrl]);
|
||||
$this->Flash->success(__('Neuer Admin-Link erstellt und per E-Mail verschickt. Der alte Link ist ab sofort ungültig – speichere dir diese Seite als Lesezeichen.'));
|
||||
} catch (Throwable $e) {
|
||||
Log::error('Mail delivery failed: ' . $e->getMessage());
|
||||
$this->Flash->warning(__('Neuer Admin-Link erstellt, die E-Mail konnte aber nicht verschickt werden. Speichere dir diese Seite unbedingt als Lesezeichen!'));
|
||||
}
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the whole poll incl. slides and responses.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function delete(): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$confirm = strtoupper(trim((string)$this->request->getData('confirm_code')));
|
||||
if ($confirm !== $this->poll->join_code) {
|
||||
$this->Flash->error(__('Zum Löschen bitte den Teilnahme-Code {0} eingeben.', $this->poll->join_code));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
|
||||
$this->Polls->deleteOrFail($this->poll);
|
||||
$this->Flash->success(__('Die Umfrage „{0}“ wurde gelöscht.', $this->poll->title));
|
||||
|
||||
return $this->redirect(['_name' => 'home']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Full screen presenter mode.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function present(): void
|
||||
{
|
||||
if ($this->poll->current_slide_id === null) {
|
||||
$first = $this->Slides->find()
|
||||
->where(['poll_id' => $this->poll->id])
|
||||
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
|
||||
->first();
|
||||
if ($first !== null) {
|
||||
$this->poll->current_slide_id = $first->id;
|
||||
$this->Polls->saveOrFail($this->poll);
|
||||
}
|
||||
}
|
||||
|
||||
$this->viewBuilder()->setLayout('present');
|
||||
$this->set('joinUrl', Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true));
|
||||
$this->set('joinBaseUrl', Router::url(['_name' => 'join:short'], true));
|
||||
$this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000));
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON state for the presenter screen.
|
||||
*
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function state(): Response
|
||||
{
|
||||
return $this->json((new PollStateService())->forPresenter($this->poll));
|
||||
}
|
||||
|
||||
/**
|
||||
* Presenter controls. Field `action`:
|
||||
* goto (+ slide_id), next, prev, open, close, toggle, stop
|
||||
*
|
||||
* Answers with the new state as JSON for XHR requests, otherwise redirects back.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function control(): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$action = (string)$this->request->getData('action');
|
||||
$slides = $this->Slides->listForPoll($this->poll->id);
|
||||
$ids = array_map(fn(Slide $s) => $s->id, $slides);
|
||||
$index = array_search($this->poll->current_slide_id, $ids, true);
|
||||
|
||||
switch ($action) {
|
||||
case 'goto':
|
||||
$target = (int)$this->request->getData('slide_id');
|
||||
if (!in_array($target, $ids, true)) {
|
||||
throw new BadRequestException('Unknown slide');
|
||||
}
|
||||
$this->poll->current_slide_id = $target;
|
||||
break;
|
||||
case 'next':
|
||||
case 'prev':
|
||||
if ($ids !== []) {
|
||||
$index = $index === false ? 0 : $index + ($action === 'next' ? 1 : -1);
|
||||
$this->poll->current_slide_id = $ids[max(0, min(count($ids) - 1, $index))];
|
||||
}
|
||||
break;
|
||||
case 'stop':
|
||||
$this->poll->current_slide_id = null;
|
||||
break;
|
||||
case 'open':
|
||||
case 'close':
|
||||
case 'toggle':
|
||||
if ($index !== false) {
|
||||
$slide = $slides[$index];
|
||||
$slide->is_voting_open = match ($action) {
|
||||
'open' => true,
|
||||
'close' => false,
|
||||
default => !$slide->is_voting_open,
|
||||
};
|
||||
$this->Slides->saveOrFail($slide);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw new BadRequestException('Unknown action');
|
||||
}
|
||||
$this->Polls->saveOrFail($this->poll);
|
||||
|
||||
if ($this->request->is('json') || $this->request->is('ajax')) {
|
||||
return $this->json((new PollStateService())->forPresenter($this->poll));
|
||||
}
|
||||
|
||||
return $this->redirect($this->referer($this->adminUrl(), true));
|
||||
}
|
||||
|
||||
/**
|
||||
* QR code (SVG) with the participant URL.
|
||||
*
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function qr(): Response
|
||||
{
|
||||
$url = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true);
|
||||
$options = new QROptions([
|
||||
'outputInterface' => QRMarkupSVG::class,
|
||||
'outputBase64' => false,
|
||||
'svgAddXmlHeader' => true,
|
||||
'addQuietzone' => true,
|
||||
'quietzoneSize' => 2,
|
||||
'drawLightModules' => false,
|
||||
]);
|
||||
$svg = (new QRCode($options))->render($url);
|
||||
|
||||
return $this->protect($this->response)
|
||||
->withType('image/svg+xml')
|
||||
->withHeader('Cache-Control', 'private, max-age=3600')
|
||||
->withStringBody((string)$svg);
|
||||
}
|
||||
|
||||
/**
|
||||
* CSV export of all responses (semicolon separated, UTF-8 with BOM for Excel).
|
||||
*
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function export(): Response
|
||||
{
|
||||
$slides = $this->Slides->listForPoll($this->poll->id);
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
assert($handle !== false);
|
||||
fwrite($handle, "\xEF\xBB\xBF");
|
||||
fputcsv($handle, ['Folie', 'Typ', 'Frage', 'Teilnehmer (anonym)', 'Antwort', 'Zeitpunkt'], ';', '"', '');
|
||||
|
||||
foreach ($slides as $position => $slide) {
|
||||
if (!$slide->isInteractive()) {
|
||||
continue;
|
||||
}
|
||||
$labels = [];
|
||||
foreach ($slide->slide_options ?? [] as $option) {
|
||||
$labels[$option->id] = $option->label;
|
||||
}
|
||||
$responses = $this->Responses->find()
|
||||
->where(['slide_id' => $slide->id])
|
||||
->orderBy(['id' => 'ASC'])
|
||||
->all();
|
||||
foreach ($responses as $response) {
|
||||
$answer = match (true) {
|
||||
$response->slide_option_id !== null => $labels[$response->slide_option_id] ?? '',
|
||||
$response->text_value !== null && $response->numeric_value === VoteService::DOWNVOTE
|
||||
=> __('Downvote: {0}', $response->text_value),
|
||||
$response->numeric_value !== null => (string)$response->numeric_value,
|
||||
default => (string)$response->text_value,
|
||||
};
|
||||
fputcsv($handle, [
|
||||
$position + 1,
|
||||
$slide->typeLabel(),
|
||||
$slide->question,
|
||||
substr($response->participant_hash, 0, 8),
|
||||
$this->csvSafe($answer),
|
||||
$response->created->i18nFormat('yyyy-MM-dd HH:mm:ss'),
|
||||
], ';', '"', '');
|
||||
}
|
||||
}
|
||||
rewind($handle);
|
||||
$csv = (string)stream_get_contents($handle);
|
||||
fclose($handle);
|
||||
|
||||
$filename = 'plenario-' . $this->poll->join_code . '-' . date('Ymd') . '.csv';
|
||||
|
||||
return $this->protect($this->response)
|
||||
->withType('csv')
|
||||
->withCharset('UTF-8')
|
||||
->withDownload($filename)
|
||||
->withStringBody($csv);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevents CSV/formula injection in spreadsheet programs.
|
||||
*
|
||||
* @param string $value Cell value
|
||||
* @return string
|
||||
*/
|
||||
protected function csvSafe(string $value): string
|
||||
{
|
||||
return preg_match('/^[=+\-@\t\r]/', $value) ? "'" . $value : $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use Cake\Controller\Controller;
|
||||
use Cake\Event\EventInterface;
|
||||
use Cake\Http\Response;
|
||||
|
||||
/**
|
||||
* Base controller of Plenario.
|
||||
*/
|
||||
class AppController extends Controller
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
|
||||
$this->loadComponent('Flash');
|
||||
}
|
||||
|
||||
/**
|
||||
* Security headers for every HTML response.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
|
||||
* @return void
|
||||
*/
|
||||
public function beforeRender(EventInterface $event): void
|
||||
{
|
||||
parent::beforeRender($event);
|
||||
|
||||
$this->response = $this->response
|
||||
->withHeader('X-Content-Type-Options', 'nosniff')
|
||||
->withHeader('X-Frame-Options', 'SAMEORIGIN')
|
||||
->withHeader('Referrer-Policy', 'same-origin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a JSON response without going through the view layer.
|
||||
*
|
||||
* @param array<string, mixed> $data Payload
|
||||
* @param int $status HTTP status
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
protected function json(array $data, int $status = 200): Response
|
||||
{
|
||||
return $this->response
|
||||
->withStatus($status)
|
||||
->withType('application/json')
|
||||
->withHeader('Cache-Control', 'no-store')
|
||||
->withStringBody((string)json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.3.4
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\Controller;
|
||||
|
||||
use Cake\Event\EventInterface;
|
||||
|
||||
/**
|
||||
* Error Handling Controller
|
||||
*
|
||||
* Controller used by ExceptionRenderer to render error responses.
|
||||
*/
|
||||
class ErrorController extends AppController
|
||||
{
|
||||
/**
|
||||
* Initialization hook method.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
// Only add parent::initialize() if you are confident your `AppController` is safe.
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeFilter callback.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event.
|
||||
* @return void
|
||||
*/
|
||||
public function beforeFilter(EventInterface $event): void
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* beforeRender callback.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event.
|
||||
* @return void
|
||||
*/
|
||||
public function beforeRender(EventInterface $event): void
|
||||
{
|
||||
parent::beforeRender($event);
|
||||
|
||||
$this->viewBuilder()->setTemplatePath('Error');
|
||||
}
|
||||
|
||||
/**
|
||||
* afterFilter callback.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event.
|
||||
* @return void
|
||||
*/
|
||||
public function afterFilter(EventInterface $event): void
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Captcha\CaptchaFactory;
|
||||
use App\Mailer\PollMailer;
|
||||
use App\Model\Table\PollsTable;
|
||||
use App\Service\ThrottleService;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Http\Response;
|
||||
use Cake\Log\Log;
|
||||
use Cake\Routing\Router;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Public pages: start page, poll creation, joining by code, link recovery.
|
||||
*/
|
||||
class HomeController extends AppController
|
||||
{
|
||||
protected PollsTable $Polls;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
/** @var \App\Model\Table\PollsTable $polls */
|
||||
$polls = $this->fetchTable('Polls');
|
||||
$this->Polls = $polls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start page with "create poll" and "join" forms.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function index(): void
|
||||
{
|
||||
$poll = $this->Polls->newEmptyEntity();
|
||||
$captcha = CaptchaFactory::create('create')->challenge($this->request);
|
||||
$this->set(compact('poll', 'captcha'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a poll and mails the admin link.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function create(): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$captcha = CaptchaFactory::create('create');
|
||||
|
||||
$poll = $this->Polls->newEmptyEntity();
|
||||
$poll = $this->Polls->patchEntity($poll, (array)$this->request->getData(), ['fields' => ['title', 'email']]);
|
||||
|
||||
if (!$captcha->verify($this->request)) {
|
||||
$this->Flash->error(__('Die Sicherheitsabfrage war nicht korrekt. Bitte versuche es erneut.'));
|
||||
} elseif (!$poll->hasErrors() && !$this->throttle('create', 'Plenario.throttle.createPerHour')) {
|
||||
$this->Flash->error(__('Zu viele Umfragen in kurzer Zeit. Bitte versuche es später noch einmal.'));
|
||||
} elseif (!$poll->hasErrors()) {
|
||||
[$poll, $token] = $this->Polls->createPoll((array)$this->request->getData());
|
||||
if ($token !== null) {
|
||||
$adminUrl = Router::url(['_name' => 'admin', 'token' => $token], true);
|
||||
$joinUrl = Router::url(['_name' => 'participate', 'code' => $poll->join_code], true);
|
||||
$sent = $this->sendMail(fn(PollMailer $mailer) => $mailer->send('adminLink', [$poll, $adminUrl, $joinUrl]));
|
||||
|
||||
$session = $this->request->getSession();
|
||||
$session->write('Plenario.created', [
|
||||
'email' => $poll->email,
|
||||
'title' => $poll->title,
|
||||
'mailSent' => $sent,
|
||||
'adminUrl' => Configure::read('Plenario.showAdminLinkAfterCreate') ? $adminUrl : null,
|
||||
]);
|
||||
|
||||
return $this->redirect(['_name' => 'created']);
|
||||
}
|
||||
$this->Flash->error(__('Die Umfrage konnte nicht angelegt werden.'));
|
||||
}
|
||||
|
||||
// Re-render the start page with errors.
|
||||
$this->set('poll', $poll);
|
||||
$this->set('captcha', $captcha->challenge($this->request));
|
||||
$this->render('index');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirmation page after creating a poll.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function created(): ?Response
|
||||
{
|
||||
$created = $this->request->getSession()->consume('Plenario.created');
|
||||
if (!is_array($created)) {
|
||||
return $this->redirect(['_name' => 'home']);
|
||||
}
|
||||
$this->set('created', $created);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join by code: GET /join?code=XYZ or POST from the start page form.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function join(): ?Response
|
||||
{
|
||||
$code = (string)($this->request->getData('code') ?? $this->request->getQuery('code') ?? '');
|
||||
if ($code === '') {
|
||||
$this->set('code', '');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$poll = $this->Polls->find('byJoinCode', code: $code)->first();
|
||||
if ($poll === null) {
|
||||
$this->Flash->error(__('Zu diesem Code wurde keine Umfrage gefunden.'));
|
||||
$this->set('code', $code);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends all admin links of an e-mail address. Always answers with the same
|
||||
* message to avoid leaking which addresses exist.
|
||||
*
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function recover(): ?Response
|
||||
{
|
||||
$captcha = CaptchaFactory::create('recover');
|
||||
|
||||
if ($this->request->is('post')) {
|
||||
$email = strtolower(trim((string)$this->request->getData('email')));
|
||||
if (!$captcha->verify($this->request)) {
|
||||
$this->Flash->error(__('Die Sicherheitsabfrage war nicht korrekt. Bitte versuche es erneut.'));
|
||||
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
$this->Flash->error(__('Bitte gib eine gültige E-Mail-Adresse ein.'));
|
||||
} elseif (!$this->throttle('recover', 'Plenario.throttle.recoverPerHour')) {
|
||||
$this->Flash->error(__('Zu viele Anfragen. Bitte versuche es später noch einmal.'));
|
||||
} else {
|
||||
$this->sendRecoveryMail($email);
|
||||
$this->Flash->success(__(
|
||||
'Falls zu {0} Umfragen existieren, haben wir dir die Admin-Links per E-Mail geschickt.',
|
||||
$email,
|
||||
));
|
||||
|
||||
return $this->redirect(['_name' => 'recover']);
|
||||
}
|
||||
}
|
||||
|
||||
$this->set('captcha', $captcha->challenge($this->request));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $email Normalised e-mail
|
||||
* @return void
|
||||
*/
|
||||
protected function sendRecoveryMail(string $email): void
|
||||
{
|
||||
/** @var list<\App\Model\Entity\Poll> $polls */
|
||||
$polls = $this->Polls->find()
|
||||
->where(['email' => $email])
|
||||
->orderBy(['created' => 'DESC'])
|
||||
->limit(50)
|
||||
->all()
|
||||
->toList();
|
||||
|
||||
$links = [];
|
||||
foreach ($polls as $poll) {
|
||||
$token = $this->Polls->decryptToken($poll);
|
||||
if ($token === null) {
|
||||
continue;
|
||||
}
|
||||
$links[] = [
|
||||
'title' => $poll->title,
|
||||
'url' => Router::url(['_name' => 'admin', 'token' => $token], true),
|
||||
'created' => $poll->created->i18nFormat('dd.MM.yyyy HH:mm'),
|
||||
];
|
||||
}
|
||||
if ($links !== []) {
|
||||
$this->sendMail(fn(PollMailer $mailer) => $mailer->send('recovery', [$email, $links]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $bucket Throttle bucket
|
||||
* @param string $configKey Configure key holding the hourly limit
|
||||
* @return bool
|
||||
*/
|
||||
protected function throttle(string $bucket, string $configKey): bool
|
||||
{
|
||||
return (new ThrottleService())->attempt(
|
||||
$bucket,
|
||||
(string)$this->request->clientIp(),
|
||||
(int)Configure::read($configKey, 0),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a mail and logs (instead of throwing) transport errors.
|
||||
*
|
||||
* @param callable(\App\Mailer\PollMailer): mixed $send Callback
|
||||
* @return bool
|
||||
*/
|
||||
protected function sendMail(callable $send): bool
|
||||
{
|
||||
try {
|
||||
$send(new PollMailer());
|
||||
|
||||
return true;
|
||||
} catch (Throwable $e) {
|
||||
Log::error('Mail delivery failed: ' . $e->getMessage());
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Table\PollsTable;
|
||||
use App\Service\PollStateService;
|
||||
use App\Service\VoteException;
|
||||
use App\Service\VoteService;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Event\EventInterface;
|
||||
use Cake\Http\Cookie\Cookie;
|
||||
use Cake\Http\Exception\NotFoundException;
|
||||
use Cake\Http\Response;
|
||||
use Cake\I18n\DateTime;
|
||||
|
||||
/**
|
||||
* Participant pages under /p/{code}.
|
||||
*
|
||||
* Participants are anonymous. A random id is stored in the cookie
|
||||
* `plenario_pid`; only an HMAC of it (scoped per poll) ends up in the database.
|
||||
*/
|
||||
class ParticipateController extends AppController
|
||||
{
|
||||
public const COOKIE = 'plenario_pid';
|
||||
|
||||
protected PollsTable $Polls;
|
||||
|
||||
protected string $participantId;
|
||||
|
||||
protected bool $newParticipant = false;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
/** @var \App\Model\Table\PollsTable $polls */
|
||||
$polls = $this->fetchTable('Polls');
|
||||
$this->Polls = $polls;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
|
||||
* @return void
|
||||
*/
|
||||
public function beforeFilter(EventInterface $event): void
|
||||
{
|
||||
parent::beforeFilter($event);
|
||||
|
||||
$pid = (string)$this->request->getCookie(self::COOKIE, '');
|
||||
if (!preg_match('/^[a-f0-9]{32}$/', $pid)) {
|
||||
$pid = bin2hex(random_bytes(16));
|
||||
$this->newParticipant = true;
|
||||
}
|
||||
$this->participantId = $pid;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
|
||||
* @return void
|
||||
*/
|
||||
public function afterFilter(EventInterface $event): void
|
||||
{
|
||||
parent::afterFilter($event);
|
||||
if ($this->newParticipant) {
|
||||
$this->response = $this->response->withCookie(Cookie::create(self::COOKIE, $this->participantId, [
|
||||
'expires' => new DateTime('+1 year'),
|
||||
'path' => '/',
|
||||
'httponly' => true,
|
||||
'secure' => $this->request->is('https'),
|
||||
'samesite' => 'Lax',
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $code Join code
|
||||
* @return void
|
||||
*/
|
||||
public function view(string $code): void
|
||||
{
|
||||
$poll = $this->loadPoll($code);
|
||||
$stateService = new PollStateService();
|
||||
$slide = $poll->is_active ? $stateService->currentSlide($poll) : null;
|
||||
$state = $stateService->forParticipant($poll, $this->participantHash($poll));
|
||||
|
||||
$this->set(compact('poll', 'slide', 'state'));
|
||||
$this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $code Join code
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function state(string $code): Response
|
||||
{
|
||||
$poll = $this->loadPoll($code);
|
||||
|
||||
return $this->json((new PollStateService())->forParticipant($poll, $this->participantHash($poll)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores an answer. AJAX requests (word cloud entries and upvotes) get JSON
|
||||
* `{ok, message, state}` instead of a redirect with flash message.
|
||||
*
|
||||
* @param string $code Join code
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function vote(string $code): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$poll = $this->loadPoll($code);
|
||||
$stateService = new PollStateService();
|
||||
$slide = $stateService->currentSlide($poll);
|
||||
$submittedSlideId = (int)$this->request->getData('slide_id');
|
||||
$ajax = $this->request->is('ajax');
|
||||
|
||||
try {
|
||||
if ($slide === null || $slide->id !== $submittedSlideId) {
|
||||
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
|
||||
}
|
||||
(new VoteService())->submit($poll, $slide, $this->participantHash($poll), (array)$this->request->getData());
|
||||
$ok = true;
|
||||
$message = __('Danke für deine Antwort!');
|
||||
} catch (VoteException $e) {
|
||||
$ok = false;
|
||||
$message = $e->getMessage();
|
||||
}
|
||||
|
||||
if ($ajax) {
|
||||
return $this->json([
|
||||
'ok' => $ok,
|
||||
'message' => $message,
|
||||
'state' => $stateService->forParticipant($poll, $this->participantHash($poll)),
|
||||
]);
|
||||
}
|
||||
$ok ? $this->Flash->success($message) : $this->Flash->error($message);
|
||||
|
||||
return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $code Join code
|
||||
* @return \App\Model\Entity\Poll
|
||||
*/
|
||||
protected function loadPoll(string $code): Poll
|
||||
{
|
||||
/** @var \App\Model\Entity\Poll|null $poll */
|
||||
$poll = $this->Polls->find('byJoinCode', code: $code)->first();
|
||||
if ($poll === null) {
|
||||
throw new NotFoundException(__('Zu diesem Code wurde keine Umfrage gefunden.'));
|
||||
}
|
||||
|
||||
return $poll;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @return string
|
||||
*/
|
||||
protected function participantHash(Poll $poll): string
|
||||
{
|
||||
return VoteService::participantHash($this->participantId, $poll->id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use Cake\Http\Exception\NotFoundException;
|
||||
use Cake\Http\Response;
|
||||
|
||||
/**
|
||||
* Slide CRUD below /admin/{token}/slides.
|
||||
*/
|
||||
class SlidesController extends AdminAppController
|
||||
{
|
||||
protected SlidesTable $Slides;
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
/** @var \App\Model\Table\SlidesTable $slides */
|
||||
$slides = $this->fetchTable('Slides');
|
||||
$this->Slides = $slides;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function add(): ?Response
|
||||
{
|
||||
$type = (string)($this->request->getData('type') ?? $this->request->getQuery('type', Slide::TYPE_CHOICE));
|
||||
if (!array_key_exists($type, Slide::typeLabels())) {
|
||||
$type = Slide::TYPE_CHOICE;
|
||||
}
|
||||
$slide = $this->Slides->newEntity(['type' => $type, 'settings' => Slide::DEFAULT_SETTINGS[$type]], [
|
||||
'validate' => false,
|
||||
]);
|
||||
$slide->setNew(true);
|
||||
$slide->poll_id = $this->poll->id;
|
||||
$optionsText = $type === Slide::TYPE_CHOICE ? "\n" : '';
|
||||
|
||||
if ($this->request->is('post')) {
|
||||
$optionsText = (string)$this->request->getData('options_text', '');
|
||||
if ($this->saveSlide($slide, $optionsText)) {
|
||||
$this->Flash->success(__('Folie angelegt.'));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
}
|
||||
|
||||
$this->set(compact('slide', 'optionsText'));
|
||||
$this->render('form');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $id Slide id
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function edit(string $id): ?Response
|
||||
{
|
||||
$slide = $this->loadSlide($id);
|
||||
$optionsText = implode("\n", array_map(fn($o) => $o->label, $slide->slide_options ?? []));
|
||||
|
||||
if ($this->request->is(['post', 'put', 'patch'])) {
|
||||
$optionsText = (string)$this->request->getData('options_text', '');
|
||||
if ($this->saveSlide($slide, $optionsText)) {
|
||||
$this->Flash->success(__('Folie gespeichert.'));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
}
|
||||
|
||||
$hasResponses = $this->Slides->Responses->exists(['slide_id' => $slide->id]);
|
||||
$this->set(compact('slide', 'optionsText', 'hasResponses'));
|
||||
$this->render('form');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $id Slide id
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function delete(string $id): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$slide = $this->loadSlide($id);
|
||||
if ($this->poll->current_slide_id === $slide->id) {
|
||||
$this->poll->current_slide_id = null;
|
||||
$this->Polls->saveOrFail($this->poll);
|
||||
}
|
||||
$this->Slides->deleteOrFail($slide);
|
||||
$this->Slides->normalizePositions($this->poll->id);
|
||||
$this->Flash->success(__('Folie gelöscht.'));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $id Slide id
|
||||
* @param string $direction up|down
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function move(string $id, string $direction): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$this->Slides->move($this->loadSlide($id), $direction);
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all responses of a slide.
|
||||
*
|
||||
* @param string $id Slide id
|
||||
* @return \Cake\Http\Response|null
|
||||
*/
|
||||
public function reset(string $id): ?Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$slide = $this->loadSlide($id);
|
||||
$this->Slides->Responses->deleteAll(['slide_id' => $slide->id]);
|
||||
$this->Flash->success(__('Antworten der Folie „{0}“ wurden gelöscht.', $slide->question));
|
||||
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a slide that belongs to the current poll (404 otherwise).
|
||||
*
|
||||
* @param string $id Slide id
|
||||
* @return \App\Model\Entity\Slide
|
||||
*/
|
||||
protected function loadSlide(string $id): Slide
|
||||
{
|
||||
/** @var \App\Model\Entity\Slide|null $slide */
|
||||
$slide = $this->Slides->find()
|
||||
->where(['Slides.id' => (int)$id, 'Slides.poll_id' => $this->poll->id])
|
||||
->contain(['SlideOptions'])
|
||||
->first();
|
||||
if ($slide === null) {
|
||||
throw new NotFoundException(__('Folie nicht gefunden.'));
|
||||
}
|
||||
|
||||
return $slide;
|
||||
}
|
||||
|
||||
/**
|
||||
* Patches and saves a slide incl. its options.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide (new or existing)
|
||||
* @param string $optionsText Options textarea (choice slides)
|
||||
* @return bool
|
||||
*/
|
||||
protected function saveSlide(Slide $slide, string $optionsText): bool
|
||||
{
|
||||
$data = (array)$this->request->getData();
|
||||
// The type of an existing slide cannot change (would invalidate responses).
|
||||
$data['type'] = $slide->type;
|
||||
$this->Slides->patchEntity($slide, $data, [
|
||||
'fields' => ['type', 'question', 'description', 'settings', 'is_voting_open'],
|
||||
'associated' => [],
|
||||
]);
|
||||
|
||||
$labels = SlidesTable::parseOptionLines($optionsText);
|
||||
if ($slide->type === Slide::TYPE_CHOICE && count($labels) < 2) {
|
||||
$slide->setError('options_text', __('Bitte gib mindestens zwei Antwortoptionen an (eine pro Zeile).'));
|
||||
}
|
||||
if ($slide->hasErrors()) {
|
||||
$this->Flash->error(__('Bitte prüfe deine Eingaben.'));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels): bool {
|
||||
if (!$this->Slides->save($slide)) {
|
||||
return false;
|
||||
}
|
||||
if ($slide->type === Slide::TYPE_CHOICE) {
|
||||
$this->Slides->syncOptions($slide, $labels);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mailer;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use Cake\Mailer\Mailer;
|
||||
|
||||
/**
|
||||
* Mails sent by Plenario. Templates: templates/email/{html,text}/.
|
||||
*/
|
||||
class PollMailer extends Mailer
|
||||
{
|
||||
/**
|
||||
* Mail with the secret admin link after a poll was created.
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @param string $adminUrl Absolute admin URL (contains the token)
|
||||
* @param string $joinUrl Absolute participant URL
|
||||
* @return void
|
||||
*/
|
||||
public function adminLink(Poll $poll, string $adminUrl, string $joinUrl): void
|
||||
{
|
||||
$this
|
||||
->setTo($poll->email)
|
||||
->setSubject(__('Deine Umfrage „{0}“ – Admin-Link', $poll->title))
|
||||
->setEmailFormat('both')
|
||||
->setViewVars(compact('poll', 'adminUrl', 'joinUrl'))
|
||||
->viewBuilder()
|
||||
->setTemplate('admin_link');
|
||||
}
|
||||
|
||||
/**
|
||||
* Recovery mail listing all admin links of an e-mail address.
|
||||
*
|
||||
* @param string $email Recipient
|
||||
* @param list<array{title: string, url: string, created: string}> $links Admin links
|
||||
* @return void
|
||||
*/
|
||||
public function recovery(string $email, array $links): void
|
||||
{
|
||||
$this
|
||||
->setTo($email)
|
||||
->setSubject(__('Deine Admin-Links bei Plenario'))
|
||||
->setEmailFormat('both')
|
||||
->setViewVars(compact('links'))
|
||||
->viewBuilder()
|
||||
->setTemplate('recovery');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mailer\Transport;
|
||||
|
||||
use Cake\Mailer\AbstractTransport;
|
||||
use Cake\Mailer\Message;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Development transport: writes every mail as .eml file to tmp/mails/
|
||||
* instead of sending it. Configure via EmailTransport.default.className.
|
||||
*
|
||||
* Options: `path` (default TMP/mails/).
|
||||
*/
|
||||
class FileTransport extends AbstractTransport
|
||||
{
|
||||
/**
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected array $_defaultConfig = [
|
||||
'path' => TMP . 'mails' . DS,
|
||||
];
|
||||
|
||||
/**
|
||||
* @param \Cake\Mailer\Message $message Message
|
||||
* @return array{headers: string, message: string}
|
||||
*/
|
||||
public function send(Message $message): array
|
||||
{
|
||||
$this->checkRecipient($message);
|
||||
|
||||
$path = rtrim((string)$this->getConfig('path'), '/\\') . DS;
|
||||
if (!is_dir($path) && !mkdir($path, 0775, true) && !is_dir($path)) {
|
||||
throw new RuntimeException(sprintf('Could not create mail directory "%s".', $path));
|
||||
}
|
||||
|
||||
$headers = $message->getHeadersString(
|
||||
['from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'subject'],
|
||||
);
|
||||
$body = $message->getBodyString();
|
||||
|
||||
$file = $path . date('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.eml';
|
||||
file_put_contents($file, $headers . "\r\n\r\n" . $body);
|
||||
|
||||
return ['headers' => $headers, 'message' => $body];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Middleware;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Http\Exception\BadRequestException;
|
||||
use Cake\Http\Exception\InternalErrorException;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\MiddlewareInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
/**
|
||||
* Middleware to validate Host header and prevent Host Header Injection attacks.
|
||||
*
|
||||
* In production, this middleware ensures that App.fullBaseUrl is configured
|
||||
* and validates incoming Host headers against it. This prevents attackers
|
||||
* from manipulating password reset links and other security-critical URLs.
|
||||
*
|
||||
* @see https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/17-Testing_for_Host_Header_Injection
|
||||
*/
|
||||
class HostHeaderMiddleware implements MiddlewareInterface
|
||||
{
|
||||
/**
|
||||
* Process the request and validate the Host header.
|
||||
*
|
||||
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
|
||||
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
|
||||
* @return \Psr\Http\Message\ResponseInterface A response.
|
||||
*/
|
||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
if (Configure::read('debug')) {
|
||||
return $handler->handle($request);
|
||||
}
|
||||
|
||||
$fullBaseUrl = Configure::read('App.fullBaseUrl');
|
||||
if (!$fullBaseUrl) {
|
||||
throw new InternalErrorException(
|
||||
'SECURITY: App.fullBaseUrl is not configured. ' .
|
||||
'This is required in production to prevent Host Header Injection attacks. ' .
|
||||
'Set APP_FULL_BASE_URL environment variable or configure App.fullBaseUrl in config/app.php',
|
||||
);
|
||||
}
|
||||
|
||||
$configuredHost = parse_url($fullBaseUrl, PHP_URL_HOST);
|
||||
$requestHost = $request->getUri()->getHost();
|
||||
|
||||
if ($configuredHost && $requestHost && strtolower($configuredHost) !== strtolower($requestHost)) {
|
||||
throw new BadRequestException(
|
||||
'Invalid Host header. Request host does not match configured application host.',
|
||||
);
|
||||
}
|
||||
|
||||
return $handler->handle($request);
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Entity;
|
||||
|
||||
use Cake\ORM\Entity;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property string $title
|
||||
* @property string $email
|
||||
* @property string $admin_token_hash
|
||||
* @property string $admin_token_encrypted
|
||||
* @property string $join_code
|
||||
* @property int|null $current_slide_id
|
||||
* @property bool $is_active
|
||||
* @property bool $show_results_to_participants
|
||||
* @property \Cake\I18n\DateTime|null $last_admin_access
|
||||
* @property \Cake\I18n\DateTime $created
|
||||
* @property \Cake\I18n\DateTime $modified
|
||||
* @property array<\App\Model\Entity\Slide> $slides
|
||||
*/
|
||||
class Poll extends Entity
|
||||
{
|
||||
/**
|
||||
* Only harmless fields are mass assignable. Tokens, join code and the
|
||||
* current slide are always set explicitly in code.
|
||||
*
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
protected array $_accessible = [
|
||||
'title' => true,
|
||||
'email' => true,
|
||||
'is_active' => true,
|
||||
'show_results_to_participants' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* Never leak secrets when an entity is serialised (JSON, debug output).
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
protected array $_hidden = [
|
||||
'admin_token_hash',
|
||||
'admin_token_encrypted',
|
||||
'email',
|
||||
];
|
||||
|
||||
/**
|
||||
* "K7P2QX" -> "K7P 2QX" for nicer display.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function formattedJoinCode(): string
|
||||
{
|
||||
return trim(chunk_split($this->join_code, 3, ' '));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Entity;
|
||||
|
||||
use Cake\ORM\Entity;
|
||||
|
||||
/**
|
||||
* One answer row of a participant. A multi-select vote or a word cloud entry
|
||||
* with several words results in several rows with the same participant_hash.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $slide_id
|
||||
* @property string $participant_hash
|
||||
* @property int|null $slide_option_id
|
||||
* @property string|null $text_value
|
||||
* @property int|null $numeric_value
|
||||
* @property \Cake\I18n\DateTime $created
|
||||
*/
|
||||
class Response extends Entity
|
||||
{
|
||||
/**
|
||||
* Responses are only created by VoteService, never mass assigned from requests.
|
||||
*
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
protected array $_accessible = [
|
||||
'slide_id' => true,
|
||||
'participant_hash' => true,
|
||||
'slide_option_id' => true,
|
||||
'text_value' => true,
|
||||
'numeric_value' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
protected array $_hidden = ['participant_hash'];
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Entity;
|
||||
|
||||
use Cake\ORM\Entity;
|
||||
|
||||
/**
|
||||
* A slide of a poll. `type` decides how participants answer and how results
|
||||
* are aggregated (see \App\Service\ResultsService and \App\Service\VoteService).
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $poll_id
|
||||
* @property string $type
|
||||
* @property string $question
|
||||
* @property string|null $description
|
||||
* @property int $position
|
||||
* @property array<string, mixed>|null $settings
|
||||
* @property bool $is_voting_open
|
||||
* @property \Cake\I18n\DateTime $created
|
||||
* @property \Cake\I18n\DateTime $modified
|
||||
* @property \App\Model\Entity\Poll $poll
|
||||
* @property array<\App\Model\Entity\SlideOption> $slide_options
|
||||
* @property array<\App\Model\Entity\Response> $responses
|
||||
*/
|
||||
class Slide extends Entity
|
||||
{
|
||||
public const TYPE_CHOICE = 'choice';
|
||||
public const TYPE_WORDCLOUD = 'wordcloud';
|
||||
public const TYPE_OPEN = 'open';
|
||||
public const TYPE_SCALE = 'scale';
|
||||
public const TYPE_CONTENT = 'content';
|
||||
|
||||
/**
|
||||
* Default settings per type. Unknown keys are dropped on save.
|
||||
*
|
||||
* @var array<string, array<string, mixed>>
|
||||
*/
|
||||
public const DEFAULT_SETTINGS = [
|
||||
self::TYPE_CHOICE => ['multiple' => false],
|
||||
// max_words: words per participant incl. upvotes (not downvotes), 0 = unlimited;
|
||||
// allow_downvotes only takes effect together with allow_upvotes
|
||||
self::TYPE_WORDCLOUD => ['max_words' => 0, 'allow_upvotes' => true, 'allow_downvotes' => true],
|
||||
self::TYPE_OPEN => [],
|
||||
self::TYPE_SCALE => ['scale_min' => 1, 'scale_max' => 5, 'min_label' => '', 'max_label' => ''],
|
||||
self::TYPE_CONTENT => [],
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
protected array $_accessible = [
|
||||
'type' => true,
|
||||
'question' => true,
|
||||
'description' => true,
|
||||
'settings' => true,
|
||||
'is_voting_open' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array<string, string> type => human readable label
|
||||
*/
|
||||
public static function typeLabels(): array
|
||||
{
|
||||
return [
|
||||
self::TYPE_CHOICE => __('Multiple Choice'),
|
||||
self::TYPE_WORDCLOUD => __('Wortwolke'),
|
||||
self::TYPE_OPEN => __('Offene Frage'),
|
||||
self::TYPE_SCALE => __('Skala'),
|
||||
self::TYPE_CONTENT => __('Inhaltsfolie'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> type => short description
|
||||
*/
|
||||
public static function typeDescriptions(): array
|
||||
{
|
||||
return [
|
||||
self::TYPE_CHOICE => __('Antwortoptionen vorgeben, Ergebnis als Balkendiagramm.'),
|
||||
self::TYPE_WORDCLOUD => __('Teilnehmende geben Begriffe ein oder unterstützen vorhandene, häufige werden größer.'),
|
||||
self::TYPE_OPEN => __('Freitext-Antworten, live als Liste.'),
|
||||
self::TYPE_SCALE => __('Bewertung auf einer Skala, z. B. 1 bis 5.'),
|
||||
self::TYPE_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function typeLabel(): string
|
||||
{
|
||||
return static::typeLabels()[$this->type] ?? $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether participants can answer this slide at all.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isInteractive(): bool
|
||||
{
|
||||
return $this->type !== self::TYPE_CONTENT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings merged with the type defaults.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getSettings(): array
|
||||
{
|
||||
$defaults = self::DEFAULT_SETTINGS[$this->type] ?? [];
|
||||
|
||||
return array_intersect_key(array_merge($defaults, (array)($this->settings ?? [])), $defaults);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key Setting name
|
||||
* @return mixed
|
||||
*/
|
||||
public function setting(string $key): mixed
|
||||
{
|
||||
return $this->getSettings()[$key] ?? null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Entity;
|
||||
|
||||
use Cake\ORM\Entity;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property int $slide_id
|
||||
* @property string $label
|
||||
* @property int $position
|
||||
*/
|
||||
class SlideOption extends Entity
|
||||
{
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
protected array $_accessible = [
|
||||
'label' => true,
|
||||
'position' => true,
|
||||
];
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use Cake\ORM\Query\SelectQuery;
|
||||
use Cake\ORM\RulesChecker;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\Utility\Security;
|
||||
use Cake\Validation\Validator;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Polls ("presentations"). Access control works exclusively via the secret
|
||||
* admin token - there are no user accounts.
|
||||
*
|
||||
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\HasMany $Slides
|
||||
* @method \App\Model\Entity\Poll newEmptyEntity()
|
||||
* @method \App\Model\Entity\Poll get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
|
||||
* @method \App\Model\Entity\Poll saveOrFail(\Cake\Datasource\EntityInterface $entity, array $options = [])
|
||||
*/
|
||||
class PollsTable extends Table
|
||||
{
|
||||
/**
|
||||
* Characters used for join codes (no 0/O, 1/I/L to avoid confusion).
|
||||
*/
|
||||
public const JOIN_CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
|
||||
|
||||
public const JOIN_CODE_LENGTH = 6;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $config The configuration for the Table.
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(array $config): void
|
||||
{
|
||||
parent::initialize($config);
|
||||
|
||||
$this->setTable('polls');
|
||||
$this->setDisplayField('title');
|
||||
$this->setPrimaryKey('id');
|
||||
|
||||
$this->addBehavior('Timestamp');
|
||||
|
||||
$this->hasMany('Slides', [
|
||||
'foreignKey' => 'poll_id',
|
||||
'sort' => ['Slides.position' => 'ASC', 'Slides.id' => 'ASC'],
|
||||
'dependent' => true,
|
||||
'cascadeCallbacks' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Validation\Validator $validator Validator instance.
|
||||
* @return \Cake\Validation\Validator
|
||||
*/
|
||||
public function validationDefault(Validator $validator): Validator
|
||||
{
|
||||
$validator
|
||||
->scalar('title')
|
||||
->maxLength('title', 200, __('Der Titel darf maximal 200 Zeichen lang sein.'))
|
||||
->requirePresence('title', 'create')
|
||||
->notEmptyString('title', __('Bitte gib einen Titel ein.'));
|
||||
|
||||
$validator
|
||||
->email('email', false, __('Bitte gib eine gültige E-Mail-Adresse ein.'))
|
||||
->maxLength('email', 255)
|
||||
->requirePresence('email', 'create')
|
||||
->notEmptyString('email', __('Bitte gib deine E-Mail-Adresse ein.'));
|
||||
|
||||
$validator->boolean('is_active');
|
||||
$validator->boolean('show_results_to_participants');
|
||||
|
||||
return $validator;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
|
||||
* @return \Cake\ORM\RulesChecker
|
||||
*/
|
||||
public function buildRules(RulesChecker $rules): RulesChecker
|
||||
{
|
||||
$rules->add($rules->isUnique(['join_code']), ['errorField' => 'join_code']);
|
||||
$rules->add($rules->isUnique(['admin_token_hash']), ['errorField' => 'admin_token_hash']);
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new admin token: URL safe, 256 bit entropy.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function generateToken(): string
|
||||
{
|
||||
return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $token Plain admin token
|
||||
* @return string sha256 hex digest
|
||||
*/
|
||||
public static function hashToken(string $token): string
|
||||
{
|
||||
return hash('sha256', $token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns a fresh admin token to the poll (hash + encrypted copy).
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll entity
|
||||
* @return string The plain token (only ever shown in the admin URL / mail)
|
||||
*/
|
||||
public function assignNewToken(Poll $poll): string
|
||||
{
|
||||
$token = static::generateToken();
|
||||
$poll->admin_token_hash = static::hashToken($token);
|
||||
$poll->admin_token_encrypted = base64_encode(Security::encrypt($token, static::encryptionKey()));
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypts the stored admin token (used by the recovery mail).
|
||||
*
|
||||
* @param \App\Model\Entity\Poll $poll Poll entity
|
||||
* @return string|null
|
||||
*/
|
||||
public function decryptToken(Poll $poll): ?string
|
||||
{
|
||||
$raw = base64_decode((string)$poll->admin_token_encrypted, true);
|
||||
if ($raw === false) {
|
||||
return null;
|
||||
}
|
||||
$token = Security::decrypt($raw, static::encryptionKey());
|
||||
if ($token === null || static::hashToken($token) !== $poll->admin_token_hash) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string 32 byte key derived from Security.salt
|
||||
*/
|
||||
protected static function encryptionKey(): string
|
||||
{
|
||||
return hash('sha256', 'plenario-admin-token|' . Security::getSalt());
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a join code that is not yet in use.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function generateJoinCode(): string
|
||||
{
|
||||
$alphabet = self::JOIN_CODE_ALPHABET;
|
||||
$max = strlen($alphabet) - 1;
|
||||
for ($attempt = 0; $attempt < 50; $attempt++) {
|
||||
$code = '';
|
||||
for ($i = 0; $i < self::JOIN_CODE_LENGTH; $i++) {
|
||||
$code .= $alphabet[random_int(0, $max)];
|
||||
}
|
||||
if (!$this->exists(['join_code' => $code])) {
|
||||
return $code;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException('Could not generate a unique join code.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalises user input like " k7p-2qx " to "K7P2QX".
|
||||
*
|
||||
* @param string $code Raw user input
|
||||
* @return string
|
||||
*/
|
||||
public static function normalizeJoinCode(string $code): string
|
||||
{
|
||||
return (string)preg_replace('/[^A-Z0-9]/', '', strtoupper($code));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and persists a new poll.
|
||||
*
|
||||
* @param array<string, mixed> $data title + email
|
||||
* @return array{0: \App\Model\Entity\Poll, 1: string|null} The entity (check getErrors()) and the plain token on success
|
||||
*/
|
||||
public function createPoll(array $data): array
|
||||
{
|
||||
$poll = $this->newEntity([
|
||||
'title' => trim((string)($data['title'] ?? '')),
|
||||
'email' => strtolower(trim((string)($data['email'] ?? ''))),
|
||||
], ['fields' => ['title', 'email']]);
|
||||
|
||||
if ($poll->hasErrors()) {
|
||||
return [$poll, null];
|
||||
}
|
||||
|
||||
$token = $this->assignNewToken($poll);
|
||||
$poll->join_code = $this->generateJoinCode();
|
||||
$poll->is_active = true;
|
||||
$poll->show_results_to_participants = true;
|
||||
|
||||
if (!$this->save($poll)) {
|
||||
return [$poll, null];
|
||||
}
|
||||
|
||||
return [$poll, $token];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\ORM\Query\SelectQuery $query Query
|
||||
* @param string $token Plain admin token
|
||||
* @return \Cake\ORM\Query\SelectQuery
|
||||
*/
|
||||
public function findByAdminToken(SelectQuery $query, string $token): SelectQuery
|
||||
{
|
||||
return $query->where(['Polls.admin_token_hash' => static::hashToken($token)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\ORM\Query\SelectQuery $query Query
|
||||
* @param string $code Join code (will be normalised)
|
||||
* @return \Cake\ORM\Query\SelectQuery
|
||||
*/
|
||||
public function findByJoinCode(SelectQuery $query, string $code): SelectQuery
|
||||
{
|
||||
return $query->where(['Polls.join_code' => static::normalizeJoinCode($code)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use App\Service\VoteService;
|
||||
use Cake\ORM\Table;
|
||||
|
||||
/**
|
||||
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\BelongsTo $Slides
|
||||
* @property \App\Model\Table\SlideOptionsTable&\Cake\ORM\Association\BelongsTo $SlideOptions
|
||||
* @method \App\Model\Entity\Response newEntity(array $data, array $options = [])
|
||||
*/
|
||||
class ResponsesTable extends Table
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $config The configuration for the Table.
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(array $config): void
|
||||
{
|
||||
parent::initialize($config);
|
||||
|
||||
$this->setTable('responses');
|
||||
$this->setPrimaryKey('id');
|
||||
|
||||
$this->addBehavior('Timestamp', [
|
||||
'events' => ['Model.beforeSave' => ['created' => 'new']],
|
||||
]);
|
||||
|
||||
$this->belongsTo('Slides', ['foreignKey' => 'slide_id', 'joinType' => 'INNER']);
|
||||
$this->belongsTo('SlideOptions', ['foreignKey' => 'slide_option_id']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $slideId Slide id
|
||||
* @param string $participantHash Participant hash
|
||||
* @return bool
|
||||
*/
|
||||
public function hasResponded(int $slideId, string $participantHash): bool
|
||||
{
|
||||
return $this->exists(['slide_id' => $slideId, 'participant_hash' => $participantHash]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Word cloud terms a participant named/upvoted and downvoted on a slide.
|
||||
*
|
||||
* @param int $slideId Slide id
|
||||
* @param string $participantHash Participant hash
|
||||
* @return array{up: list<string>, down: list<string>} raw text values
|
||||
*/
|
||||
public function wordVotesOf(int $slideId, string $participantHash): array
|
||||
{
|
||||
$rows = $this->find()
|
||||
->select(['text_value', 'numeric_value'])
|
||||
->where(['slide_id' => $slideId, 'participant_hash' => $participantHash, 'text_value IS NOT' => null])
|
||||
->orderBy(['id' => 'ASC'])
|
||||
->disableHydration()
|
||||
->all();
|
||||
|
||||
$votes = ['up' => [], 'down' => []];
|
||||
foreach ($rows as $row) {
|
||||
$votes[(int)$row['numeric_value'] === VoteService::DOWNVOTE ? 'down' : 'up'][] = (string)$row['text_value'];
|
||||
}
|
||||
|
||||
return $votes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether anybody named (or upvoted) a word cloud term on a slide.
|
||||
*
|
||||
* @param int $slideId Slide id
|
||||
* @param string $key Word key, see VoteService::wordKey()
|
||||
* @return bool
|
||||
*/
|
||||
public function wordExists(int $slideId, string $key): bool
|
||||
{
|
||||
$rows = $this->find()
|
||||
->select(['text_value'])
|
||||
->where([
|
||||
'slide_id' => $slideId,
|
||||
'text_value IS NOT' => null,
|
||||
'numeric_value IS' => null,
|
||||
])
|
||||
->disableHydration()
|
||||
->all();
|
||||
foreach ($rows as $row) {
|
||||
if (VoteService::wordKey((string)$row['text_value']) === $key) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of distinct participants that answered a slide.
|
||||
*
|
||||
* @param int $slideId Slide id
|
||||
* @return int
|
||||
*/
|
||||
public function countParticipants(int $slideId): int
|
||||
{
|
||||
$row = $this->find()
|
||||
->select(['n' => $this->find()->func()->count('DISTINCT participant_hash')])
|
||||
->where(['slide_id' => $slideId])
|
||||
->disableHydration()
|
||||
->first();
|
||||
|
||||
return (int)($row['n'] ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of responding participants per slide of a poll.
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @return array<int, int> slide_id => participant count
|
||||
*/
|
||||
public function countParticipantsPerSlide(int $pollId): array
|
||||
{
|
||||
$rows = $this->find()
|
||||
->select([
|
||||
'slide_id' => 'Responses.slide_id',
|
||||
'n' => $this->find()->func()->count('DISTINCT Responses.participant_hash'),
|
||||
])
|
||||
->innerJoinWith('Slides')
|
||||
->where(['Slides.poll_id' => $pollId])
|
||||
->groupBy(['Responses.slide_id'])
|
||||
->disableHydration()
|
||||
->all();
|
||||
|
||||
$counts = [];
|
||||
foreach ($rows as $row) {
|
||||
$counts[(int)$row['slide_id']] = (int)$row['n'];
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use Cake\ORM\Table;
|
||||
use Cake\Validation\Validator;
|
||||
|
||||
/**
|
||||
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\BelongsTo $Slides
|
||||
* @property \App\Model\Table\ResponsesTable&\Cake\ORM\Association\HasMany $Responses
|
||||
* @method \App\Model\Entity\SlideOption newEntity(array $data, array $options = [])
|
||||
*/
|
||||
class SlideOptionsTable extends Table
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $config The configuration for the Table.
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(array $config): void
|
||||
{
|
||||
parent::initialize($config);
|
||||
|
||||
$this->setTable('slide_options');
|
||||
$this->setDisplayField('label');
|
||||
$this->setPrimaryKey('id');
|
||||
|
||||
$this->belongsTo('Slides', ['foreignKey' => 'slide_id', 'joinType' => 'INNER']);
|
||||
$this->hasMany('Responses', ['foreignKey' => 'slide_option_id', 'dependent' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Validation\Validator $validator Validator instance.
|
||||
* @return \Cake\Validation\Validator
|
||||
*/
|
||||
public function validationDefault(Validator $validator): Validator
|
||||
{
|
||||
$validator
|
||||
->scalar('label')
|
||||
->maxLength('label', 255)
|
||||
->notEmptyString('label');
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Model\Table;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use ArrayObject;
|
||||
use Cake\Datasource\EntityInterface;
|
||||
use Cake\Event\EventInterface;
|
||||
use Cake\ORM\RulesChecker;
|
||||
use Cake\ORM\Table;
|
||||
use Cake\Validation\Validator;
|
||||
|
||||
/**
|
||||
* @property \App\Model\Table\PollsTable&\Cake\ORM\Association\BelongsTo $Polls
|
||||
* @property \App\Model\Table\SlideOptionsTable&\Cake\ORM\Association\HasMany $SlideOptions
|
||||
* @property \App\Model\Table\ResponsesTable&\Cake\ORM\Association\HasMany $Responses
|
||||
* @method \App\Model\Entity\Slide newEmptyEntity()
|
||||
* @method \App\Model\Entity\Slide get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
|
||||
*/
|
||||
class SlidesTable extends Table
|
||||
{
|
||||
public const MAX_OPTIONS = 20;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $config The configuration for the Table.
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(array $config): void
|
||||
{
|
||||
parent::initialize($config);
|
||||
|
||||
$this->setTable('slides');
|
||||
$this->setDisplayField('question');
|
||||
$this->setPrimaryKey('id');
|
||||
|
||||
$this->addBehavior('Timestamp');
|
||||
$this->getSchema()->setColumnType('settings', 'json');
|
||||
|
||||
$this->belongsTo('Polls', ['foreignKey' => 'poll_id', 'joinType' => 'INNER']);
|
||||
$this->hasMany('SlideOptions', [
|
||||
'foreignKey' => 'slide_id',
|
||||
'sort' => ['SlideOptions.position' => 'ASC', 'SlideOptions.id' => 'ASC'],
|
||||
'dependent' => true,
|
||||
]);
|
||||
$this->hasMany('Responses', [
|
||||
'foreignKey' => 'slide_id',
|
||||
'dependent' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Validation\Validator $validator Validator instance.
|
||||
* @return \Cake\Validation\Validator
|
||||
*/
|
||||
public function validationDefault(Validator $validator): Validator
|
||||
{
|
||||
$validator
|
||||
->inList('type', array_keys(Slide::typeLabels()))
|
||||
->requirePresence('type', 'create')
|
||||
->notEmptyString('type');
|
||||
|
||||
$validator
|
||||
->scalar('question')
|
||||
->maxLength('question', 500, __('Die Frage darf maximal 500 Zeichen lang sein.'))
|
||||
->requirePresence('question', 'create')
|
||||
->notEmptyString('question', __('Bitte gib eine Frage bzw. Überschrift ein.'));
|
||||
|
||||
$validator
|
||||
->scalar('description')
|
||||
->maxLength('description', 5000)
|
||||
->allowEmptyString('description');
|
||||
|
||||
$validator->boolean('is_voting_open');
|
||||
|
||||
return $validator;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
|
||||
* @return \Cake\ORM\RulesChecker
|
||||
*/
|
||||
public function buildRules(RulesChecker $rules): RulesChecker
|
||||
{
|
||||
$rules->add($rules->existsIn(['poll_id'], 'Polls'), ['errorField' => 'poll_id']);
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise settings before they are marshalled into the entity.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event
|
||||
* @param \ArrayObject<string, mixed> $data Request data
|
||||
* @param \ArrayObject<string, mixed> $options Options
|
||||
* @return void
|
||||
*/
|
||||
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options): void
|
||||
{
|
||||
if (isset($data['question']) && is_string($data['question'])) {
|
||||
$data['question'] = trim($data['question']);
|
||||
}
|
||||
if (isset($data['settings']) && is_array($data['settings']) && isset($data['type'])) {
|
||||
$data['settings'] = static::sanitizeSettings((string)$data['type'], $data['settings']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign the next free position for new slides.
|
||||
*
|
||||
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event
|
||||
* @param \Cake\Datasource\EntityInterface $entity Slide
|
||||
* @param \ArrayObject<string, mixed> $options Options
|
||||
* @return void
|
||||
*/
|
||||
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
|
||||
{
|
||||
if ($entity->isNew() && !$entity->has('position')) {
|
||||
$max = $this->find()
|
||||
->where(['poll_id' => $entity->get('poll_id')])
|
||||
->select(['max' => $this->find()->func()->max('position')])
|
||||
->disableHydration()
|
||||
->first();
|
||||
$entity->set('position', (int)($max['max'] ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces raw settings input to the known keys of the type, with proper types.
|
||||
*
|
||||
* @param string $type Slide type
|
||||
* @param array<string, mixed> $input Raw settings
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function sanitizeSettings(string $type, array $input): array
|
||||
{
|
||||
$settings = Slide::DEFAULT_SETTINGS[$type] ?? [];
|
||||
switch ($type) {
|
||||
case Slide::TYPE_CHOICE:
|
||||
$settings['multiple'] = filter_var($input['multiple'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
break;
|
||||
case Slide::TYPE_WORDCLOUD:
|
||||
$settings['max_words'] = max(0, min(50, (int)($input['max_words'] ?? 0)));
|
||||
$settings['allow_upvotes'] = filter_var($input['allow_upvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
|
||||
$settings['allow_downvotes'] = filter_var($input['allow_downvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
|
||||
break;
|
||||
case Slide::TYPE_SCALE:
|
||||
$min = max(0, min(1, (int)($input['scale_min'] ?? 1)));
|
||||
$max = max(2, min(10, (int)($input['scale_max'] ?? 5)));
|
||||
$settings['scale_min'] = $min;
|
||||
$settings['scale_max'] = $max;
|
||||
$settings['min_label'] = mb_substr(trim((string)($input['min_label'] ?? '')), 0, 60);
|
||||
$settings['max_label'] = mb_substr(trim((string)($input['max_label'] ?? '')), 0, 60);
|
||||
break;
|
||||
}
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a textarea (one option per line) into a clean list of labels.
|
||||
*
|
||||
* @param string $raw Textarea content
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function parseOptionLines(string $raw): array
|
||||
{
|
||||
$labels = [];
|
||||
foreach (preg_split('/\R/', $raw) ?: [] as $line) {
|
||||
$line = mb_substr(trim($line), 0, 255);
|
||||
if ($line !== '' && !in_array($line, $labels, true)) {
|
||||
$labels[] = $line;
|
||||
}
|
||||
}
|
||||
|
||||
return array_slice($labels, 0, self::MAX_OPTIONS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronises the answer options of a slide with the given labels.
|
||||
* Options whose label is unchanged keep their id (and therefore their votes);
|
||||
* removed options are deleted together with their votes.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Saved slide
|
||||
* @param list<string> $labels New labels in display order
|
||||
* @return void
|
||||
*/
|
||||
public function syncOptions(Slide $slide, array $labels): void
|
||||
{
|
||||
$existing = $this->SlideOptions->find()
|
||||
->where(['slide_id' => $slide->id])
|
||||
->all()
|
||||
->indexBy('label')
|
||||
->toArray();
|
||||
|
||||
$this->getConnection()->transactional(function () use ($slide, $labels, $existing): void {
|
||||
foreach ($labels as $index => $label) {
|
||||
$option = $existing[$label] ?? $this->SlideOptions->newEntity(['label' => $label]);
|
||||
$option->set('slide_id', $slide->id);
|
||||
$option->set('position', $index + 1);
|
||||
$this->SlideOptions->saveOrFail($option);
|
||||
unset($existing[$label]);
|
||||
}
|
||||
foreach ($existing as $obsolete) {
|
||||
$this->SlideOptions->deleteOrFail($obsolete);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps the slide with its neighbour.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide to move
|
||||
* @param string $direction 'up' or 'down'
|
||||
* @return bool Whether something changed
|
||||
*/
|
||||
public function move(Slide $slide, string $direction): bool
|
||||
{
|
||||
$this->normalizePositions($slide->poll_id);
|
||||
$slide = $this->get($slide->id);
|
||||
|
||||
$neighbour = $this->find()
|
||||
->where([
|
||||
'poll_id' => $slide->poll_id,
|
||||
'position' . ($direction === 'up' ? ' <' : ' >') => $slide->position,
|
||||
])
|
||||
->orderBy(['position' => $direction === 'up' ? 'DESC' : 'ASC'])
|
||||
->first();
|
||||
if ($neighbour === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool)$this->getConnection()->transactional(function () use ($slide, $neighbour): bool {
|
||||
$position = $slide->position;
|
||||
$slide->position = $neighbour->position;
|
||||
$neighbour->position = $position;
|
||||
|
||||
return $this->save($slide) && $this->save($neighbour);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renumbers positions 1..n (closes gaps after deletions).
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @return void
|
||||
*/
|
||||
public function normalizePositions(int $pollId): void
|
||||
{
|
||||
$slides = $this->find()
|
||||
->where(['poll_id' => $pollId])
|
||||
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
|
||||
->all();
|
||||
$position = 1;
|
||||
foreach ($slides as $slide) {
|
||||
if ($slide->position !== $position) {
|
||||
$this->updateAll(['position' => $position], ['id' => $slide->id]);
|
||||
}
|
||||
$position++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordered slides of a poll including options.
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @return list<\App\Model\Entity\Slide>
|
||||
*/
|
||||
public function listForPoll(int $pollId): array
|
||||
{
|
||||
/** @var list<\App\Model\Entity\Slide> $slides */
|
||||
$slides = $this->find()
|
||||
->where(['Slides.poll_id' => $pollId])
|
||||
->contain(['SlideOptions'])
|
||||
->orderBy(['Slides.position' => 'ASC', 'Slides.id' => 'ASC'])
|
||||
->all()
|
||||
->toList();
|
||||
|
||||
return $slides;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\ResponsesTable;
|
||||
use App\Model\Table\SlidesTable;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
|
||||
/**
|
||||
* Builds the JSON state polled by the presenter screen (/admin/{token}/state)
|
||||
* and the participant page (/p/{code}/state).
|
||||
*
|
||||
* The participant state never contains results unless the poll allows it and
|
||||
* the participant has answered (or voting is closed). Exception: word clouds
|
||||
* with upvotes enabled show the live cloud while voting is open, because
|
||||
* participants upvote by clicking words in it.
|
||||
*/
|
||||
class PollStateService
|
||||
{
|
||||
use LocatorAwareTrait;
|
||||
|
||||
protected SlidesTable $Slides;
|
||||
|
||||
protected ResponsesTable $Responses;
|
||||
|
||||
protected ResultsService $results;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
/** @var \App\Model\Table\SlidesTable $slides */
|
||||
$slides = $this->fetchTable('Slides');
|
||||
$this->Slides = $slides;
|
||||
/** @var \App\Model\Table\ResponsesTable $responses */
|
||||
$responses = $this->fetchTable('Responses');
|
||||
$this->Responses = $responses;
|
||||
$this->results = new ResultsService();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @return \App\Model\Entity\Slide|null
|
||||
*/
|
||||
public function currentSlide(Poll $poll): ?Slide
|
||||
{
|
||||
if ($poll->current_slide_id === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var \App\Model\Entity\Slide|null $slide */
|
||||
$slide = $this->Slides->find()
|
||||
->where(['Slides.id' => $poll->current_slide_id, 'Slides.poll_id' => $poll->id])
|
||||
->contain(['SlideOptions'])
|
||||
->first();
|
||||
|
||||
return $slide;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function forPresenter(Poll $poll): array
|
||||
{
|
||||
$slides = $this->Slides->listForPoll($poll->id);
|
||||
$current = null;
|
||||
$index = null;
|
||||
foreach ($slides as $i => $slide) {
|
||||
if ($slide->id === $poll->current_slide_id) {
|
||||
$current = $slide;
|
||||
$index = $i;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'poll' => [
|
||||
'title' => $poll->title,
|
||||
'joinCode' => $poll->join_code,
|
||||
'joinCodeFormatted' => $poll->formattedJoinCode(),
|
||||
'isActive' => $poll->is_active,
|
||||
],
|
||||
'slides' => array_map(fn(Slide $s) => [
|
||||
'id' => $s->id,
|
||||
'type' => $s->type,
|
||||
'question' => $s->question,
|
||||
], $slides),
|
||||
'index' => $index,
|
||||
'count' => count($slides),
|
||||
'slide' => $current ? $this->slidePayload($current) : null,
|
||||
'results' => $current ? $this->results->forSlide($current) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @param string $participantHash Participant hash
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function forParticipant(Poll $poll, string $participantHash): array
|
||||
{
|
||||
$slide = $poll->is_active ? $this->currentSlide($poll) : null;
|
||||
$words = $slide?->type === Slide::TYPE_WORDCLOUD ? $this->wordState($slide, $participantHash) : null;
|
||||
$hasResponded = $words !== null
|
||||
? $words['mine'] !== [] || $words['down'] !== []
|
||||
: $slide && $slide->isInteractive() && $this->Responses->hasResponded($slide->id, $participantHash);
|
||||
|
||||
$showResults = $slide !== null
|
||||
&& $slide->isInteractive()
|
||||
&& (
|
||||
($poll->show_results_to_participants && ($hasResponded || !$slide->is_voting_open))
|
||||
|| ($words !== null && $words['allowUpvotes'] && $slide->is_voting_open)
|
||||
);
|
||||
|
||||
return [
|
||||
'isActive' => $poll->is_active,
|
||||
'slideId' => $slide?->id,
|
||||
'isVotingOpen' => $slide?->is_voting_open ?? false,
|
||||
'hasResponded' => $hasResponded,
|
||||
// Changes whenever the participant page must re-render.
|
||||
'version' => implode(':', [
|
||||
(int)$poll->is_active,
|
||||
$slide?->id ?? 0,
|
||||
(int)($slide?->is_voting_open ?? 0),
|
||||
// Word clouds are answered word by word without reload.
|
||||
$words !== null ? (int)$words['limitReached'] : (int)$hasResponded,
|
||||
$slide?->modified?->toUnixString() ?? 0,
|
||||
]),
|
||||
'slide' => $showResults ? $this->slidePayload($slide) : null,
|
||||
'results' => $showResults ? $this->results->forSlide($slide) : null,
|
||||
'words' => $words,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Word cloud progress of one participant.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Word cloud slide
|
||||
* @param string $participantHash Participant hash
|
||||
* @return array{mine: list<string>, down: list<string>, max: int, remaining: int|null,
|
||||
* limitReached: bool, allowUpvotes: bool, allowDownvotes: bool}
|
||||
* `mine` (named/upvoted) and `down` are lower case word keys, `remaining` is null when unlimited
|
||||
*/
|
||||
public function wordState(Slide $slide, string $participantHash): array
|
||||
{
|
||||
$votes = $this->Responses->wordVotesOf($slide->id, $participantHash);
|
||||
$mine = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['up'])));
|
||||
$down = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['down'])));
|
||||
$max = (int)$slide->setting('max_words');
|
||||
$remaining = $max > 0 ? max(0, $max - count($mine)) : null;
|
||||
$allowUpvotes = (bool)$slide->setting('allow_upvotes');
|
||||
|
||||
return [
|
||||
'mine' => $mine,
|
||||
'down' => $down,
|
||||
'max' => $max,
|
||||
'remaining' => $remaining,
|
||||
'limitReached' => $remaining === 0,
|
||||
'allowUpvotes' => $allowUpvotes,
|
||||
'allowDownvotes' => $allowUpvotes && (bool)$slide->setting('allow_downvotes'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function slidePayload(Slide $slide): array
|
||||
{
|
||||
return [
|
||||
'id' => $slide->id,
|
||||
'type' => $slide->type,
|
||||
'typeLabel' => $slide->typeLabel(),
|
||||
'question' => $slide->question,
|
||||
'description' => (string)$slide->description,
|
||||
'isVotingOpen' => $slide->is_voting_open,
|
||||
'isInteractive' => $slide->isInteractive(),
|
||||
'settings' => $slide->getSettings(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\ResponsesTable;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
|
||||
/**
|
||||
* Aggregates responses of a slide into a JSON friendly structure that is
|
||||
* rendered by webroot/js/plenario.js (presenter + participant views).
|
||||
*
|
||||
* Shape (always present): ['type' => string, 'participants' => int, ...]
|
||||
* - choice: 'options' => [['id', 'label', 'count', 'percent']]
|
||||
* - wordcloud: 'words' => [['key' (lower case), 'text', 'count', 'down', 'weight' (0..1)]]
|
||||
* (count = participants who named or upvoted the word, down = downvotes,
|
||||
* weight follows count)
|
||||
* - open: 'answers' => [['text', 'created']] newest first
|
||||
* - scale: 'buckets' => [['value', 'count', 'percent']], 'average' => float|null,
|
||||
* 'min', 'max', 'minLabel', 'maxLabel'
|
||||
*/
|
||||
class ResultsService
|
||||
{
|
||||
use LocatorAwareTrait;
|
||||
|
||||
public const MAX_ANSWERS = 200;
|
||||
|
||||
protected ResponsesTable $Responses;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
/** @var \App\Model\Table\ResponsesTable $responses */
|
||||
$responses = $this->fetchTable('Responses');
|
||||
$this->Responses = $responses;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide incl. slide_options
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function forSlide(Slide $slide): array
|
||||
{
|
||||
$result = [
|
||||
'type' => $slide->type,
|
||||
'participants' => $slide->isInteractive() ? $this->Responses->countParticipants($slide->id) : 0,
|
||||
];
|
||||
|
||||
return $result + match ($slide->type) {
|
||||
Slide::TYPE_CHOICE => $this->choice($slide),
|
||||
Slide::TYPE_WORDCLOUD => $this->wordcloud($slide),
|
||||
Slide::TYPE_OPEN => $this->open($slide),
|
||||
Slide::TYPE_SCALE => $this->scale($slide),
|
||||
default => [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function choice(Slide $slide): array
|
||||
{
|
||||
$counts = $this->Responses->find()
|
||||
->select(['slide_option_id', 'n' => $this->Responses->find()->func()->count('*')])
|
||||
->where(['slide_id' => $slide->id, 'slide_option_id IS NOT' => null])
|
||||
->groupBy(['slide_option_id'])
|
||||
->disableHydration()
|
||||
->all()
|
||||
->combine('slide_option_id', 'n')
|
||||
->toArray();
|
||||
|
||||
$total = array_sum(array_map('intval', $counts));
|
||||
$options = [];
|
||||
foreach ($slide->slide_options ?? [] as $option) {
|
||||
$count = (int)($counts[$option->id] ?? 0);
|
||||
$options[] = [
|
||||
'id' => $option->id,
|
||||
'label' => $option->label,
|
||||
'count' => $count,
|
||||
'percent' => $total > 0 ? round($count / $total * 100, 1) : 0,
|
||||
];
|
||||
}
|
||||
|
||||
return ['options' => $options, 'votes' => $total];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function wordcloud(Slide $slide): array
|
||||
{
|
||||
$rows = $this->Responses->find()
|
||||
->select(['text_value', 'numeric_value'])
|
||||
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null])
|
||||
->disableHydration()
|
||||
->all();
|
||||
|
||||
// Group case-insensitively, display the most frequent spelling.
|
||||
$groups = [];
|
||||
$downvotes = [];
|
||||
foreach ($rows as $row) {
|
||||
$text = (string)$row['text_value'];
|
||||
$key = VoteService::wordKey($text);
|
||||
if ((int)$row['numeric_value'] === VoteService::DOWNVOTE) {
|
||||
$downvotes[$key] = ($downvotes[$key] ?? 0) + 1;
|
||||
continue;
|
||||
}
|
||||
$groups[$key]['count'] = ($groups[$key]['count'] ?? 0) + 1;
|
||||
$groups[$key]['spellings'][$text] = ($groups[$key]['spellings'][$text] ?? 0) + 1;
|
||||
}
|
||||
// Size follows the upvotes (count); downvotes are shown separately.
|
||||
uasort($groups, fn($a, $b) => $b['count'] <=> $a['count']);
|
||||
|
||||
$maxCount = $groups === [] ? 1 : max(array_column($groups, 'count'));
|
||||
$words = [];
|
||||
foreach ($groups as $key => $group) {
|
||||
arsort($group['spellings']);
|
||||
$words[] = [
|
||||
'key' => (string)$key,
|
||||
'text' => (string)array_key_first($group['spellings']),
|
||||
'count' => $group['count'],
|
||||
'down' => $downvotes[$key] ?? 0,
|
||||
'weight' => round($group['count'] / $maxCount, 3),
|
||||
];
|
||||
}
|
||||
|
||||
return ['words' => $words];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function open(Slide $slide): array
|
||||
{
|
||||
$rows = $this->Responses->find()
|
||||
->select(['text_value', 'created'])
|
||||
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null])
|
||||
->orderBy(['id' => 'DESC'])
|
||||
->limit(self::MAX_ANSWERS)
|
||||
->all();
|
||||
|
||||
$answers = [];
|
||||
foreach ($rows as $row) {
|
||||
$answers[] = ['text' => $row->text_value, 'created' => $row->created->toIso8601String()];
|
||||
}
|
||||
|
||||
return ['answers' => $answers];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function scale(Slide $slide): array
|
||||
{
|
||||
$min = (int)$slide->setting('scale_min');
|
||||
$max = (int)$slide->setting('scale_max');
|
||||
$counts = $this->Responses->find()
|
||||
->select(['numeric_value', 'n' => $this->Responses->find()->func()->count('*')])
|
||||
->where(['slide_id' => $slide->id, 'numeric_value IS NOT' => null])
|
||||
->groupBy(['numeric_value'])
|
||||
->disableHydration()
|
||||
->all()
|
||||
->combine('numeric_value', 'n')
|
||||
->toArray();
|
||||
|
||||
$total = 0;
|
||||
$sum = 0;
|
||||
foreach ($counts as $value => $count) {
|
||||
$total += (int)$count;
|
||||
$sum += (int)$value * (int)$count;
|
||||
}
|
||||
$buckets = [];
|
||||
for ($value = $min; $value <= $max; $value++) {
|
||||
$count = (int)($counts[$value] ?? 0);
|
||||
$buckets[] = [
|
||||
'value' => $value,
|
||||
'count' => $count,
|
||||
'percent' => $total > 0 ? round($count / $total * 100, 1) : 0,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'buckets' => $buckets,
|
||||
'average' => $total > 0 ? round($sum / $total, 2) : null,
|
||||
'min' => $min,
|
||||
'max' => $max,
|
||||
'minLabel' => (string)$slide->setting('min_label'),
|
||||
'maxLabel' => (string)$slide->setting('max_label'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Cake\Cache\Cache;
|
||||
|
||||
/**
|
||||
* Very small fixed-window rate limiter backed by the "throttle" cache config.
|
||||
* Used to limit poll creation and recovery mails per client IP.
|
||||
*/
|
||||
class ThrottleService
|
||||
{
|
||||
public const WINDOW_SECONDS = 3600;
|
||||
|
||||
/**
|
||||
* Registers a hit and returns whether the action is still allowed.
|
||||
*
|
||||
* @param string $bucket Logical action, e.g. "create"
|
||||
* @param string $identifier Client identifier, e.g. IP address
|
||||
* @param int $limit Allowed hits per window; <= 0 disables throttling
|
||||
* @return bool
|
||||
*/
|
||||
public function attempt(string $bucket, string $identifier, int $limit): bool
|
||||
{
|
||||
if ($limit <= 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$key = 'throttle_' . $bucket . '_' . hash('sha256', $identifier);
|
||||
$now = time();
|
||||
/** @var array{start: int, hits: int}|null $state */
|
||||
$state = Cache::read($key, 'throttle');
|
||||
if (!is_array($state) || $state['start'] + self::WINDOW_SECONDS <= $now) {
|
||||
$state = ['start' => $now, 'hits' => 0];
|
||||
}
|
||||
if ($state['hits'] >= $limit) {
|
||||
return false;
|
||||
}
|
||||
$state['hits']++;
|
||||
Cache::write($key, $state, 'throttle');
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Thrown when a vote is rejected. The message is safe to show to participants.
|
||||
*/
|
||||
class VoteException extends RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Model\Entity\Poll;
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Model\Table\ResponsesTable;
|
||||
use Cake\ORM\Locator\LocatorAwareTrait;
|
||||
use Cake\Utility\Security;
|
||||
|
||||
/**
|
||||
* Validates and stores participant answers.
|
||||
*
|
||||
* Rules:
|
||||
* - the poll must be active and the slide must be the poll's current slide
|
||||
* - voting on the slide must be open
|
||||
* - every participant can answer a slide exactly once, except word clouds:
|
||||
* there words are submitted one by one (each word once per participant,
|
||||
* at most `max_words` words, 0 = unlimited). Submitting a word that already
|
||||
* exists in the cloud is an upvote – both are stored as the same row.
|
||||
* `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing
|
||||
* word of someone else. Each participant rates a word only once (up or down);
|
||||
* downvotes do not count towards `max_words`.
|
||||
*/
|
||||
class VoteService
|
||||
{
|
||||
use LocatorAwareTrait;
|
||||
|
||||
public const MAX_WORD_LENGTH = 40;
|
||||
public const MAX_TEXT_LENGTH = 500;
|
||||
|
||||
/**
|
||||
* `responses.numeric_value` of a word cloud downvote (upvotes/words: null).
|
||||
*/
|
||||
public const DOWNVOTE = -1;
|
||||
|
||||
protected ResponsesTable $Responses;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
/** @var \App\Model\Table\ResponsesTable $responses */
|
||||
$responses = $this->fetchTable('Responses');
|
||||
$this->Responses = $responses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives the anonymous participant hash from the cookie id. The poll id is
|
||||
* part of the HMAC key so participants cannot be correlated across polls.
|
||||
*
|
||||
* @param string $participantId Random id from the participant cookie
|
||||
* @param int $pollId Poll id
|
||||
* @return string
|
||||
*/
|
||||
public static function participantHash(string $participantId, int $pollId): string
|
||||
{
|
||||
return hash_hmac('sha256', $participantId, Security::getSalt() . '|poll|' . $pollId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Poll $poll Poll
|
||||
* @param \App\Model\Entity\Slide $slide Slide (with slide_options for choice slides)
|
||||
* @param string $participantHash Participant hash
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @return void
|
||||
* @throws \App\Service\VoteException
|
||||
*/
|
||||
public function submit(Poll $poll, Slide $slide, string $participantHash, array $data): void
|
||||
{
|
||||
if (!$poll->is_active) {
|
||||
throw new VoteException(__('Diese Umfrage ist derzeit geschlossen.'));
|
||||
}
|
||||
if ($slide->poll_id !== $poll->id || $poll->current_slide_id !== $slide->id) {
|
||||
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
|
||||
}
|
||||
if (!$slide->isInteractive()) {
|
||||
throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.'));
|
||||
}
|
||||
if (!$slide->is_voting_open) {
|
||||
throw new VoteException(__('Die Abstimmung zu dieser Frage ist geschlossen.'));
|
||||
}
|
||||
if ($slide->type !== Slide::TYPE_WORDCLOUD && $this->Responses->hasResponded($slide->id, $participantHash)) {
|
||||
throw new VoteException(__('Du hast bereits abgestimmt.'));
|
||||
}
|
||||
|
||||
$rows = match ($slide->type) {
|
||||
Slide::TYPE_CHOICE => $this->choiceRows($slide, $data),
|
||||
Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data),
|
||||
Slide::TYPE_OPEN => $this->openRows($data),
|
||||
Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
|
||||
default => throw new VoteException(__('Unbekannter Folientyp.')),
|
||||
};
|
||||
|
||||
$entities = [];
|
||||
foreach ($rows as $row) {
|
||||
$entities[] = $this->Responses->newEntity($row + [
|
||||
'slide_id' => $slide->id,
|
||||
'participant_hash' => $participantHash,
|
||||
]);
|
||||
}
|
||||
$this->Responses->saveManyOrFail($entities);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
protected function choiceRows(Slide $slide, array $data): array
|
||||
{
|
||||
$selected = $data['option_ids'] ?? $data['option_id'] ?? [];
|
||||
$selected = array_values(array_unique(array_map('intval', (array)$selected)));
|
||||
$validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []);
|
||||
$selected = array_values(array_intersect($selected, $validIds));
|
||||
|
||||
if ($selected === []) {
|
||||
throw new VoteException(__('Bitte wähle eine Antwort aus.'));
|
||||
}
|
||||
if (!$slide->setting('multiple') && count($selected) > 1) {
|
||||
throw new VoteException(__('Bitte wähle nur eine Antwort aus.'));
|
||||
}
|
||||
|
||||
return array_map(fn(int $id) => ['slide_option_id' => $id], $selected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized key of a word cloud term: whitespace collapsed, trimmed, cut to
|
||||
* MAX_WORD_LENGTH. Use wordKey() for case-insensitive comparison.
|
||||
*
|
||||
* @param string $word Raw input
|
||||
* @return string
|
||||
*/
|
||||
public static function cleanWord(string $word): string
|
||||
{
|
||||
$word = trim((string)preg_replace('/\s+/u', ' ', $word));
|
||||
|
||||
return mb_substr($word, 0, self::MAX_WORD_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Case-insensitive grouping key of a word cloud term.
|
||||
*
|
||||
* @param string $word Word
|
||||
* @return string
|
||||
*/
|
||||
public static function wordKey(string $word): string
|
||||
{
|
||||
return mb_strtolower(self::cleanWord($word));
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts `word` (string) or `words` (list). Words the participant already
|
||||
* submitted are skipped, the rest is cut to the remaining limit.
|
||||
*
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param string $participantHash Participant hash
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
protected function wordRows(Slide $slide, string $participantHash, array $data): array
|
||||
{
|
||||
$votes = $this->Responses->wordVotesOf($slide->id, $participantHash);
|
||||
$existing = array_values(array_unique(array_map(self::wordKey(...), $votes['up'])));
|
||||
$downvoted = array_fill_keys(array_map(self::wordKey(...), $votes['down']), true);
|
||||
if (($data['vote'] ?? null) === 'down') {
|
||||
return $this->downvoteRows($slide, (string)($data['word'] ?? ''), $existing, $downvoted);
|
||||
}
|
||||
|
||||
$input = array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? []));
|
||||
$seen = array_fill_keys($existing, true);
|
||||
|
||||
$words = [];
|
||||
$duplicate = false;
|
||||
$rejected = false;
|
||||
foreach ($input as $word) {
|
||||
$word = self::cleanWord((string)$word);
|
||||
$key = mb_strtolower($word);
|
||||
if ($word === '') {
|
||||
continue;
|
||||
}
|
||||
if (isset($downvoted[$key])) {
|
||||
$rejected = true;
|
||||
continue;
|
||||
}
|
||||
if (isset($seen[$key])) {
|
||||
$duplicate = true;
|
||||
continue;
|
||||
}
|
||||
$seen[$key] = true;
|
||||
$words[] = $word;
|
||||
}
|
||||
|
||||
$max = (int)$slide->setting('max_words');
|
||||
if ($max > 0) {
|
||||
$remaining = max(0, $max - count($existing));
|
||||
if ($remaining === 0) {
|
||||
throw new VoteException(__n(
|
||||
'Du hast deinen Begriff bereits abgegeben.',
|
||||
'Du hast bereits alle {0} Begriffe abgegeben.',
|
||||
$max,
|
||||
$max,
|
||||
));
|
||||
}
|
||||
$words = array_slice($words, 0, $remaining);
|
||||
}
|
||||
if ($words === []) {
|
||||
throw new VoteException(match (true) {
|
||||
$duplicate => __('Diesen Begriff hast du schon genannt.'),
|
||||
$rejected => __('Diesen Begriff hast du bereits abgelehnt.'),
|
||||
default => __('Bitte gib einen Begriff ein.'),
|
||||
});
|
||||
}
|
||||
|
||||
return array_map(fn(string $word) => ['text_value' => $word], $words);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param string $word Word to downvote
|
||||
* @param list<string> $own Keys the participant named/upvoted
|
||||
* @param array<string, true> $downvoted Keys the participant downvoted
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
protected function downvoteRows(Slide $slide, string $word, array $own, array $downvoted): array
|
||||
{
|
||||
if (!$slide->setting('allow_upvotes') || !$slide->setting('allow_downvotes')) {
|
||||
throw new VoteException(__('Downvotes sind bei dieser Frage nicht möglich.'));
|
||||
}
|
||||
$word = self::cleanWord($word);
|
||||
$key = mb_strtolower($word);
|
||||
if ($word === '' || !$this->Responses->wordExists($slide->id, $key)) {
|
||||
throw new VoteException(__('Diesen Begriff gibt es nicht in der Wortwolke.'));
|
||||
}
|
||||
if (in_array($key, $own, true)) {
|
||||
throw new VoteException(__('Du hast diesen Begriff selbst genannt.'));
|
||||
}
|
||||
if (isset($downvoted[$key])) {
|
||||
throw new VoteException(__('Diesen Begriff hast du bereits abgelehnt.'));
|
||||
}
|
||||
|
||||
return [['text_value' => $word, 'numeric_value' => self::DOWNVOTE]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
protected function openRows(array $data): array
|
||||
{
|
||||
$text = trim((string)($data['text'] ?? ''));
|
||||
if ($text === '') {
|
||||
throw new VoteException(__('Bitte gib eine Antwort ein.'));
|
||||
}
|
||||
if (mb_strlen($text) > self::MAX_TEXT_LENGTH) {
|
||||
throw new VoteException(__('Die Antwort darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
|
||||
}
|
||||
|
||||
return [['text_value' => $text]];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Model\Entity\Slide $slide Slide
|
||||
* @param array<string, mixed> $data Request data
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
protected function scaleRows(Slide $slide, array $data): array
|
||||
{
|
||||
$value = filter_var($data['value'] ?? null, FILTER_VALIDATE_INT);
|
||||
$min = (int)$slide->setting('scale_min');
|
||||
$max = (int)$slide->setting('scale_max');
|
||||
if ($value === false || $value < $min || $value > $max) {
|
||||
throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max));
|
||||
}
|
||||
|
||||
return [['numeric_value' => $value]];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.4
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\View;
|
||||
|
||||
/**
|
||||
* A view class that is used for AJAX responses.
|
||||
* Currently only switches the default layout and sets the response type -
|
||||
* which just maps to text/html by default.
|
||||
*/
|
||||
class AjaxView extends AppView
|
||||
{
|
||||
/**
|
||||
* The name of the layout file to render the view inside of. The name
|
||||
* specified is the filename of the layout in /templates/Layout without
|
||||
* the .php extension.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $layout = 'ajax';
|
||||
|
||||
/**
|
||||
* Initialization hook method.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
parent::initialize();
|
||||
|
||||
$this->response = $this->response->withType('ajax');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 3.0.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
*/
|
||||
namespace App\View;
|
||||
|
||||
use Cake\View\View;
|
||||
|
||||
/**
|
||||
* Application View
|
||||
*
|
||||
* Your application's default view class
|
||||
*
|
||||
* @link https://book.cakephp.org/5/en/views.html#the-app-view
|
||||
*/
|
||||
class AppView extends View
|
||||
{
|
||||
/**
|
||||
* Initialization hook method.
|
||||
*
|
||||
* Use this method to add common initialization code like adding helpers.
|
||||
*
|
||||
* e.g. `$this->addHelper('Html');`
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initialize(): void
|
||||
{
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
/**
|
||||
* Admin dashboard of a poll.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var string $adminToken
|
||||
* @var list<\App\Model\Entity\Slide> $slides
|
||||
* @var array<int, int> $responseCounts
|
||||
* @var array<string, string> $typeLabels
|
||||
* @var array<string, string> $typeDescriptions
|
||||
* @var string $joinUrl
|
||||
*/
|
||||
$this->assign('title', $poll->title);
|
||||
$this->assign('noindex', '1');
|
||||
$url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $adminToken] + $params;
|
||||
?>
|
||||
<div class="admin-head">
|
||||
<div>
|
||||
<p class="eyebrow"><?= __('Verwaltung') ?></p>
|
||||
<h1><?= h($poll->title) ?></h1>
|
||||
<p class="muted">
|
||||
<?php if ($poll->is_active) : ?>
|
||||
<span class="badge badge--ok"><?= __('aktiv') ?></span>
|
||||
<?php else : ?>
|
||||
<span class="badge badge--off"><?= __('geschlossen') ?></span>
|
||||
<?php endif; ?>
|
||||
<?= __('{0} Folien', count($slides)) ?>
|
||||
</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>
|
||||
<a class="button" href="<?= $this->Url->build($url('admin:export')) ?>"><?= __('CSV-Export') ?></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="notice">
|
||||
<strong><?= __('Bookmark diese Seite!') ?></strong>
|
||||
<?= __('Diese URL ist dein Zugang zur Umfrage. Wer sie kennt, kann alles bearbeiten.') ?>
|
||||
</div>
|
||||
|
||||
<div class="grid grid--sidebar">
|
||||
<section>
|
||||
<div class="section-head">
|
||||
<h2><?= __('Folien') ?></h2>
|
||||
</div>
|
||||
|
||||
<?php if ($slides === []) : ?>
|
||||
<div class="empty">
|
||||
<p><?= __('Noch keine Folien. Wähle unten einen Typ, um die erste Frage anzulegen.') ?></p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<ol class="slide-list">
|
||||
<?php foreach ($slides as $i => $slide) :
|
||||
$isCurrent = $poll->current_slide_id === $slide->id;
|
||||
$count = $responseCounts[$slide->id] ?? 0;
|
||||
?>
|
||||
<li class="slide-item<?= $isCurrent ? ' slide-item--current' : '' ?>">
|
||||
<div class="slide-item__pos"><?= $i + 1 ?></div>
|
||||
<div class="slide-item__body">
|
||||
<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->isInteractive()) : ?>
|
||||
<span class="muted"><?= __n('{0} Antwort', '{0} Antworten', $count, $count) ?></span>
|
||||
<?php if (!$slide->is_voting_open) : ?><span class="muted">· <?= __('Abstimmung geschlossen') ?></span><?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<a class="slide-item__title" href="<?= $this->Url->build($url('slides:edit', ['id' => $slide->id])) ?>"><?= h($slide->question) ?></a>
|
||||
<?php if ($slide->type === 'choice' && $slide->slide_options) : ?>
|
||||
<p class="slide-item__options muted"><?= h(implode(' · ', array_map(fn($o) => $o->label, $slide->slide_options))) ?></p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="slide-item__actions">
|
||||
<?php if (!$isCurrent) : ?>
|
||||
<?= $this->Form->postLink(__('Live'), $url('admin:control'), [
|
||||
'data' => ['action' => 'goto', 'slide_id' => $slide->id],
|
||||
'class' => 'button button--small',
|
||||
'title' => __('Diese Folie jetzt den Teilnehmenden zeigen'),
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
<a class="button button--small" href="<?= $this->Url->build($url('slides:edit', ['id' => $slide->id])) ?>"><?= __('Bearbeiten') ?></a>
|
||||
<?= $this->Form->postLink('↑', $url('slides:move', ['id' => $slide->id, 'direction' => 'up']), [
|
||||
'class' => 'button button--small button--icon', 'title' => __('Nach oben'),
|
||||
]) ?>
|
||||
<?= $this->Form->postLink('↓', $url('slides:move', ['id' => $slide->id, 'direction' => 'down']), [
|
||||
'class' => 'button button--small button--icon', 'title' => __('Nach unten'),
|
||||
]) ?>
|
||||
<?php if ($count > 0) : ?>
|
||||
<?= $this->Form->postLink(__('Zurücksetzen'), $url('slides:reset', ['id' => $slide->id]), [
|
||||
'class' => 'button button--small',
|
||||
'confirm' => __('Alle {0} Antworten dieser Folie löschen?', $count),
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
<?= $this->Form->postLink(__('Löschen'), $url('slides:delete', ['id' => $slide->id]), [
|
||||
'class' => 'button button--small button--danger',
|
||||
'confirm' => __('Folie „{0}“ inkl. aller Antworten löschen?', $slide->question),
|
||||
]) ?>
|
||||
</div>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ol>
|
||||
|
||||
<h3><?= __('Neue Folie') ?></h3>
|
||||
<div class="type-picker">
|
||||
<?php foreach ($typeLabels as $type => $label) : ?>
|
||||
<a class="type-card type-card--<?= h($type) ?>" href="<?= $this->Url->build($url('slides:add', ['?' => ['type' => $type]])) ?>">
|
||||
<strong><?= h($label) ?></strong>
|
||||
<span><?= h($typeDescriptions[$type]) ?></span>
|
||||
</a>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside class="sidebar">
|
||||
<section class="card">
|
||||
<h2><?= __('Teilnahme') ?></h2>
|
||||
<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>
|
||||
|
||||
<section class="card">
|
||||
<h2><?= __('Einstellungen') ?></h2>
|
||||
<?= $this->Form->create($poll, ['url' => $url('admin:settings')]) ?>
|
||||
<?= $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('show_results_to_participants', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Teilnehmende sehen Ergebnisse nach ihrer Antwort'),
|
||||
]) ?>
|
||||
<?= $this->Form->button(__('Speichern'), ['class' => 'button']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
|
||||
<section class="card card--danger">
|
||||
<h2><?= __('Sicherheit') ?></h2>
|
||||
<p class="hint"><?= __('Link versehentlich geteilt? Erzeuge einen neuen – der alte wird sofort ungültig.') ?></p>
|
||||
<?= $this->Form->postLink(__('Neuen Admin-Link erzeugen'), $url('admin:rotate'), [
|
||||
'class' => 'button button--small',
|
||||
'confirm' => __('Neuen Admin-Link erzeugen? Der aktuelle Link funktioniert danach nicht mehr.'),
|
||||
]) ?>
|
||||
|
||||
<h3><?= __('Umfrage löschen') ?></h3>
|
||||
<?= $this->Form->create(null, ['url' => $url('admin:delete')]) ?>
|
||||
<?= $this->Form->control('confirm_code', [
|
||||
'label' => __('Zum Bestätigen Code {0} eingeben', $poll->join_code),
|
||||
'autocomplete' => 'off',
|
||||
'required' => true,
|
||||
]) ?>
|
||||
<?= $this->Form->button(__('Endgültig löschen'), ['class' => 'button button--danger']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
/**
|
||||
* Presenter screen. Rendered empty and filled by webroot/js/plenario.js
|
||||
* (Plenario.presenter) from /admin/{token}/state.
|
||||
*
|
||||
* Keyboard: ←/→ slides, V voting on/off, H hide results, F fullscreen, Q QR code.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var string $adminToken
|
||||
* @var string $joinUrl
|
||||
* @var string $joinBaseUrl
|
||||
* @var int $pollIntervalMs
|
||||
*/
|
||||
$this->assign('title', $poll->title);
|
||||
$host = preg_replace('#^https?://#', '', $joinBaseUrl);
|
||||
?>
|
||||
<div class="stage"
|
||||
data-presenter
|
||||
data-state-url="<?= $this->Url->build(['_name' => 'admin:state', 'token' => $adminToken]) ?>"
|
||||
data-control-url="<?= $this->Url->build(['_name' => 'admin:control', 'token' => $adminToken]) ?>"
|
||||
data-interval="<?= (int)$pollIntervalMs ?>">
|
||||
|
||||
<header class="stage__top">
|
||||
<div class="stage__join">
|
||||
<?= __('Mitmachen auf') ?> <strong><?= h($host) ?></strong>
|
||||
<?= __('mit Code') ?> <strong class="stage__code"><?= h($poll->formattedJoinCode()) ?></strong>
|
||||
</div>
|
||||
<button type="button" class="stage__qr" data-qr-toggle title="<?= __('QR-Code vergrößern (Q)') ?>">
|
||||
<img src="<?= $this->Url->build(['_name' => 'admin:qr', 'token' => $adminToken]) ?>" alt="<?= __('QR-Code') ?>">
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<main class="stage__main">
|
||||
<p class="stage__type" data-type></p>
|
||||
<h1 class="stage__question" data-question><?= __('Lade …') ?></h1>
|
||||
<p class="stage__description" data-description></p>
|
||||
<div class="stage__results" data-results></div>
|
||||
</main>
|
||||
|
||||
<footer class="stage__controls">
|
||||
<a class="ctrl" href="<?= $this->Url->build(['_name' => 'admin', 'token' => $adminToken]) ?>" title="<?= __('Zur Verwaltung') ?>">✎</a>
|
||||
<button type="button" class="ctrl" data-action="prev" title="<?= __('Vorherige Folie (←)') ?>">←</button>
|
||||
<span class="ctrl-counter" data-counter>–</span>
|
||||
<button type="button" class="ctrl" data-action="next" title="<?= __('Nächste Folie (→)') ?>">→</button>
|
||||
<button type="button" class="ctrl ctrl--wide" data-action="toggle" data-voting title="<?= __('Abstimmung öffnen/schließen (V)') ?>"></button>
|
||||
<button type="button" class="ctrl ctrl--wide" data-hide-results title="<?= __('Ergebnisse ein-/ausblenden (H)') ?>"><?= __('Ergebnisse verbergen') ?></button>
|
||||
<span class="ctrl-counter" data-participants></span>
|
||||
<button type="button" class="ctrl" data-fullscreen title="<?= __('Vollbild (F)') ?>">⛶</button>
|
||||
</footer>
|
||||
|
||||
<div class="qr-overlay" data-qr-overlay hidden>
|
||||
<img src="<?= $this->Url->build(['_name' => 'admin:qr', 'token' => $adminToken]) ?>" alt="<?= __('QR-Code') ?>">
|
||||
<p><?= h($joinUrl) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var string $message
|
||||
* @var string $url
|
||||
*/
|
||||
use Cake\Core\Configure;
|
||||
|
||||
$this->setLayout('error');
|
||||
|
||||
if (Configure::read('debug')) :
|
||||
$this->setLayout('dev_error');
|
||||
|
||||
$this->assign('title', $message);
|
||||
$this->assign('templateName', 'error400.php');
|
||||
|
||||
$this->start('file');
|
||||
echo $this->element('auto_table_warning');
|
||||
$this->end();
|
||||
endif;
|
||||
$this->assign('title', __('Nicht gefunden'));
|
||||
?>
|
||||
<h1><?= __('Nicht gefunden') ?></h1>
|
||||
<p class="lead"><?= h($message) ?></p>
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var \Cake\Database\StatementInterface $error
|
||||
* @var string $message
|
||||
* @var string $url
|
||||
*/
|
||||
use Cake\Core\Configure;
|
||||
use Cake\Error\Debugger;
|
||||
|
||||
$this->setLayout('error');
|
||||
|
||||
if (Configure::read('debug')) :
|
||||
$this->setLayout('dev_error');
|
||||
|
||||
$this->assign('title', $message);
|
||||
$this->assign('templateName', 'error500.php');
|
||||
|
||||
$this->start('file');
|
||||
if (!empty($error->queryString)) : ?>
|
||||
<p class="notice"><strong>SQL Query: </strong><?= h($error->queryString) ?></p>
|
||||
<?php endif;
|
||||
if (!empty($error->params)) : ?>
|
||||
<strong>SQL Query Params: </strong>
|
||||
<?php Debugger::dump($error->params) ?>
|
||||
<?php endif;
|
||||
if ($error instanceof Error) :
|
||||
$file = $error->getFile();
|
||||
$line = $error->getLine(); ?>
|
||||
<strong>Error in: </strong>
|
||||
<?= $this->Html->link(sprintf('%s, line %s', Debugger::trimPath($file), $line), Debugger::editorUrl($file, $line)); ?>
|
||||
<?php endif;
|
||||
echo $this->element('auto_table_warning');
|
||||
$this->end();
|
||||
endif;
|
||||
$this->assign('title', __('Fehler'));
|
||||
?>
|
||||
<h1><?= __('Da ist etwas schiefgelaufen') ?></h1>
|
||||
<p class="lead"><?= __('Bitte versuche es in einem Moment noch einmal.') ?></p>
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
/**
|
||||
* Confirmation after creating a poll.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var array{email: string, title: string, mailSent: bool, adminUrl: string|null} $created
|
||||
*/
|
||||
$this->assign('title', __('Umfrage erstellt'));
|
||||
$this->assign('noindex', '1');
|
||||
?>
|
||||
<section class="card card--narrow center">
|
||||
<div class="icon-circle" aria-hidden="true">✉</div>
|
||||
<h1><?= __('Fast geschafft!') ?></h1>
|
||||
<?php if ($created['mailSent']) : ?>
|
||||
<p class="lead"><?= __('Wir haben den Admin-Link für „{0}“ an <strong>{1}</strong> geschickt.', h($created['title']), h($created['email'])) ?></p>
|
||||
<p><?= __('Öffne die E-Mail und klicke auf den Link, um Fragen anzulegen. Schau ggf. auch im Spam-Ordner nach.') ?></p>
|
||||
<?php else : ?>
|
||||
<p class="lead"><?= __('Die Umfrage wurde angelegt, aber die E-Mail an {0} konnte nicht verschickt werden.', h($created['email'])) ?></p>
|
||||
<p><?= __('Versuche es später über „Admin-Link verloren?“ erneut.') ?></p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!empty($created['adminUrl'])) : ?>
|
||||
<div class="devnote">
|
||||
<strong><?= __('Entwicklungsmodus') ?></strong>
|
||||
<p><?= __('Admin-Link direkt (nur sichtbar, weil showAdminLinkAfterCreate aktiv ist):') ?></p>
|
||||
<a class="button button--primary" href="<?= h($created['adminUrl']) ?>"><?= __('Zur Verwaltung') ?></a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
/**
|
||||
* Start page: create a poll (e-mail, no login) or join one by code.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var array<string, mixed> $captcha
|
||||
*/
|
||||
$this->assign('title', __('Live-Umfragen ohne Login'));
|
||||
?>
|
||||
<section class="hero">
|
||||
<h1><?= __('Live-Umfragen für Vorträge, Workshops und Meetings') ?></h1>
|
||||
<p class="lead"><?= __('Fragen anlegen, Code zeigen, Ergebnisse live sehen. Ohne Konto – der Verwaltungslink kommt per E-Mail.') ?></p>
|
||||
</section>
|
||||
|
||||
<div class="grid grid--2">
|
||||
<section class="card">
|
||||
<h2><?= __('Neue Umfrage erstellen') ?></h2>
|
||||
<?= $this->Form->create($poll, ['url' => ['_name' => 'create'], 'novalidate' => false]) ?>
|
||||
<?= $this->Form->control('title', [
|
||||
'label' => __('Titel'),
|
||||
'placeholder' => __('z. B. Team-Retro Oktober'),
|
||||
'maxlength' => 200,
|
||||
'required' => true,
|
||||
]) ?>
|
||||
<?= $this->Form->control('email', [
|
||||
'label' => __('Deine E-Mail-Adresse'),
|
||||
'type' => 'email',
|
||||
'placeholder' => 'name@example.org',
|
||||
'required' => true,
|
||||
'autocomplete' => 'email',
|
||||
]) ?>
|
||||
<?= $this->element('captcha', ['captcha' => $captcha]) ?>
|
||||
<p class="hint"><?= __('Wir schicken dir einen geheimen Admin-Link. Die Adresse wird nur dafür verwendet.') ?></p>
|
||||
<?= $this->Form->button(__('Umfrage erstellen'), ['class' => 'button button--primary']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
|
||||
<section class="card card--accent">
|
||||
<h2><?= __('An einer Umfrage teilnehmen') ?></h2>
|
||||
<?= $this->Form->create(null, ['url' => ['_name' => 'join'], 'type' => 'get']) ?>
|
||||
<?= $this->Form->control('code', [
|
||||
'label' => __('Teilnahme-Code'),
|
||||
'placeholder' => 'K7P 2QX',
|
||||
'class' => 'input-code',
|
||||
'autocomplete' => 'off',
|
||||
'autocapitalize' => 'characters',
|
||||
'required' => true,
|
||||
]) ?>
|
||||
<?= $this->Form->button(__('Teilnehmen'), ['class' => 'button']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="features">
|
||||
<div><strong><?= __('Multiple Choice') ?></strong><span><?= __('Balkendiagramm in Echtzeit') ?></span></div>
|
||||
<div><strong><?= __('Wortwolke') ?></strong><span><?= __('Begriffe sammeln und gewichten') ?></span></div>
|
||||
<div><strong><?= __('Offene Fragen') ?></strong><span><?= __('Freitext-Antworten live') ?></span></div>
|
||||
<div><strong><?= __('Skala') ?></strong><span><?= __('Bewertungen mit Durchschnitt') ?></span></div>
|
||||
</section>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
/**
|
||||
* Join form (/join, /p).
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var string $code
|
||||
*/
|
||||
$this->assign('title', __('Teilnehmen'));
|
||||
?>
|
||||
<section class="card card--narrow center">
|
||||
<h1><?= __('Teilnehmen') ?></h1>
|
||||
<p class="lead"><?= __('Gib den Code ein, der in der Präsentation angezeigt wird.') ?></p>
|
||||
<?= $this->Form->create(null, ['url' => ['_name' => 'join'], 'type' => 'get']) ?>
|
||||
<?= $this->Form->control('code', [
|
||||
'label' => ['text' => __('Teilnahme-Code'), 'class' => 'sr-only'],
|
||||
'value' => $code,
|
||||
'placeholder' => 'K7P 2QX',
|
||||
'class' => 'input-code input-code--big',
|
||||
'autocomplete' => 'off',
|
||||
'autocapitalize' => 'characters',
|
||||
'autofocus' => true,
|
||||
'required' => true,
|
||||
]) ?>
|
||||
<?= $this->Form->button(__('Los geht’s'), ['class' => 'button button--primary button--block']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
/**
|
||||
* Re-send admin links.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var array<string, mixed> $captcha
|
||||
*/
|
||||
$this->assign('title', __('Admin-Link verloren?'));
|
||||
?>
|
||||
<section class="card card--narrow">
|
||||
<h1><?= __('Admin-Link verloren?') ?></h1>
|
||||
<p><?= __('Gib die E-Mail-Adresse ein, mit der du deine Umfragen erstellt hast. Wir schicken dir alle zugehörigen Admin-Links erneut zu.') ?></p>
|
||||
<?= $this->Form->create(null, ['url' => ['_name' => 'recover']]) ?>
|
||||
<?= $this->Form->control('email', [
|
||||
'label' => __('E-Mail-Adresse'),
|
||||
'type' => 'email',
|
||||
'required' => true,
|
||||
'autocomplete' => 'email',
|
||||
]) ?>
|
||||
<?= $this->element('captcha', ['captcha' => $captcha]) ?>
|
||||
<?= $this->Form->button(__('Links zuschicken'), ['class' => 'button button--primary']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
/**
|
||||
* Participant page. Server rendered; webroot/js/plenario.js (Plenario.participant)
|
||||
* polls /p/{code}/state, reloads when the slide changes and updates results live.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var \App\Model\Entity\Slide|null $slide
|
||||
* @var array<string, mixed> $state
|
||||
* @var int $pollIntervalMs
|
||||
*/
|
||||
$this->assign('title', $poll->title);
|
||||
$this->assign('bodyClass', 'participant');
|
||||
$voteUrl = ['_name' => 'participate:vote', 'code' => $poll->join_code];
|
||||
$words = $state['words'] ?? null;
|
||||
?>
|
||||
<div class="participant-view"
|
||||
data-participant
|
||||
data-state-url="<?= $this->Url->build(['_name' => 'participate:state', 'code' => $poll->join_code]) ?>"
|
||||
data-version="<?= h($state['version']) ?>"
|
||||
data-vote-url="<?= $this->Url->build($voteUrl) ?>"
|
||||
data-interval="<?= (int)$pollIntervalMs ?>">
|
||||
|
||||
<p class="eyebrow center"><?= h($poll->title) ?></p>
|
||||
|
||||
<?php if (!$poll->is_active) : ?>
|
||||
<section class="card center">
|
||||
<h1><?= __('Diese Umfrage ist geschlossen.') ?></h1>
|
||||
<p class="muted"><?= __('Danke fürs Vorbeischauen!') ?></p>
|
||||
</section>
|
||||
|
||||
<?php elseif ($slide === null) : ?>
|
||||
<section class="card center waiting">
|
||||
<div class="pulse" aria-hidden="true"></div>
|
||||
<h1><?= __('Gleich geht’s los …') ?></h1>
|
||||
<p class="muted"><?= __('Warte, bis die erste Frage gestartet wird. Die Seite aktualisiert sich automatisch.') ?></p>
|
||||
</section>
|
||||
|
||||
<?php elseif (!$slide->isInteractive()) : ?>
|
||||
<section class="card">
|
||||
<h1><?= h($slide->question) ?></h1>
|
||||
<?php if ($slide->description) : ?>
|
||||
<div class="prose"><?= nl2br(h($slide->description)) ?></div>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
|
||||
<?php else : ?>
|
||||
<section class="card">
|
||||
<h1 class="question"><?= h($slide->question) ?></h1>
|
||||
<?php if ($slide->description) : ?>
|
||||
<p class="muted"><?= nl2br(h($slide->description)) ?></p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($words !== null && $slide->is_voting_open && !$words['limitReached']) : ?>
|
||||
<?= $this->Form->create(null, ['url' => $voteUrl, 'class' => 'vote-form word-form', 'data-word-form' => true]) ?>
|
||||
<?= $this->Form->hidden('slide_id', ['value' => $slide->id]) ?>
|
||||
<p class="hint" data-words-remaining>
|
||||
<?= $words['remaining'] === null
|
||||
? __('Du kannst beliebig viele Begriffe abgeben.')
|
||||
: __n('Du kannst noch einen Begriff abgeben.', 'Du kannst noch {0} Begriffe abgeben.', $words['remaining'], $words['remaining']) ?>
|
||||
</p>
|
||||
<div class="word-entry">
|
||||
<input type="text" name="word" maxlength="40" class="word-input" required autofocus
|
||||
autocomplete="off" autocapitalize="off" spellcheck="false"
|
||||
placeholder="<?= __('Begriff eingeben …') ?>"
|
||||
role="combobox" aria-autocomplete="list" aria-expanded="false"
|
||||
aria-controls="word-suggestions" data-word-input>
|
||||
<ul class="suggestions" id="word-suggestions" role="listbox" hidden data-suggestions></ul>
|
||||
</div>
|
||||
<p class="word-message" data-word-message aria-live="polite"></p>
|
||||
<?= $this->Form->button(__('Begriff senden'), ['class' => 'button button--primary button--block']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
<?php elseif ($state['hasResponded']) : ?>
|
||||
<p class="done">✓ <?= __('Deine Antwort ist angekommen.') ?></p>
|
||||
<?php elseif (!$slide->is_voting_open) : ?>
|
||||
<p class="muted"><?= __('Die Abstimmung zu dieser Frage ist geschlossen.') ?></p>
|
||||
<?php else : ?>
|
||||
<?= $this->Form->create(null, ['url' => $voteUrl, 'class' => 'vote-form']) ?>
|
||||
<?= $this->Form->hidden('slide_id', ['value' => $slide->id]) ?>
|
||||
|
||||
<?php if ($slide->type === 'choice') :
|
||||
$multiple = (bool)$slide->setting('multiple'); ?>
|
||||
<?php if ($multiple) : ?><p class="hint"><?= __('Mehrfachauswahl möglich') ?></p><?php endif; ?>
|
||||
<div class="choices">
|
||||
<?php foreach ($slide->slide_options as $option) : ?>
|
||||
<label class="choice">
|
||||
<input type="<?= $multiple ? 'checkbox' : 'radio' ?>"
|
||||
name="<?= $multiple ? 'option_ids[]' : 'option_id' ?>"
|
||||
value="<?= (int)$option->id ?>" <?= $multiple ? '' : 'required' ?>>
|
||||
<span><?= h($option->label) ?></span>
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
|
||||
<?php elseif ($slide->type === 'open') : ?>
|
||||
<textarea name="text" rows="4" maxlength="500" required
|
||||
placeholder="<?= __('Deine Antwort …') ?>"></textarea>
|
||||
|
||||
<?php elseif ($slide->type === 'scale') : ?>
|
||||
<div class="scale">
|
||||
<?php for ($v = (int)$slide->setting('scale_min'); $v <= (int)$slide->setting('scale_max'); $v++) : ?>
|
||||
<label class="scale__step">
|
||||
<input type="radio" name="value" value="<?= $v ?>" required>
|
||||
<span><?= $v ?></span>
|
||||
</label>
|
||||
<?php endfor; ?>
|
||||
</div>
|
||||
<div class="scale__labels">
|
||||
<span><?= h((string)$slide->setting('min_label')) ?></span>
|
||||
<span><?= h((string)$slide->setting('max_label')) ?></span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?= $this->Form->button(__('Absenden'), ['class' => 'button button--primary button--block']) ?>
|
||||
<?= $this->Form->end() ?>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
|
||||
<section class="card results-card" data-results-card <?= $state['results'] ? '' : 'hidden' ?>>
|
||||
<h2><?= $words !== null ? __('Wortwolke') : __('Ergebnisse') ?></h2>
|
||||
<?php if ($words !== null && $words['allowUpvotes'] && $slide->is_voting_open && !$words['limitReached']) : ?>
|
||||
<p class="hint" data-upvote-hint><?= $words['allowDownvotes']
|
||||
? __('Tippe auf einen Begriff, um ihn zu unterstützen, oder auf „−“, um ihn abzulehnen.')
|
||||
: __('Tippe auf einen Begriff, um ihn zu unterstützen.') ?></p>
|
||||
<?php endif; ?>
|
||||
<div data-results></div>
|
||||
</section>
|
||||
<script type="application/json" data-initial-state><?= json_encode($state, JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?></script>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
/**
|
||||
* Add / edit form for slides. Type specific fields are rendered per type;
|
||||
* the type itself cannot be changed after creation.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var string $adminToken
|
||||
* @var \App\Model\Entity\Slide $slide
|
||||
* @var string $optionsText
|
||||
* @var bool|null $hasResponses
|
||||
*/
|
||||
$isNew = $slide->isNew();
|
||||
$settings = $slide->getSettings();
|
||||
$this->assign('title', $isNew ? __('Neue Folie') : __('Folie bearbeiten'));
|
||||
$this->assign('noindex', '1');
|
||||
$formUrl = $isNew
|
||||
? ['_name' => 'slides:add', 'token' => $adminToken, '?' => ['type' => $slide->type]]
|
||||
: ['_name' => 'slides:edit', 'token' => $adminToken, 'id' => $slide->id];
|
||||
$optionsError = $slide->getError('options_text');
|
||||
?>
|
||||
<p><a href="<?= $this->Url->build(['_name' => 'admin', 'token' => $adminToken]) ?>">← <?= __('Zurück zu „{0}“', h($poll->title)) ?></a></p>
|
||||
|
||||
<section class="card card--form">
|
||||
<p class="eyebrow"><?= h($slide->typeLabel()) ?></p>
|
||||
<h1><?= $isNew ? __('Neue Folie') : __('Folie bearbeiten') ?></h1>
|
||||
|
||||
<?= $this->Form->create($slide, ['url' => $formUrl]) ?>
|
||||
<?= $this->Form->hidden('type') ?>
|
||||
<?= $this->Form->control('question', [
|
||||
'label' => $slide->type === 'content' ? __('Überschrift') : __('Frage'),
|
||||
'maxlength' => 500,
|
||||
'required' => true,
|
||||
'autofocus' => $isNew,
|
||||
]) ?>
|
||||
<?= $this->Form->control('description', [
|
||||
'type' => 'textarea',
|
||||
'rows' => $slide->type === 'content' ? 6 : 2,
|
||||
'label' => $slide->type === 'content' ? __('Text') : __('Beschreibung (optional)'),
|
||||
]) ?>
|
||||
|
||||
<?php if ($slide->type === 'choice') : ?>
|
||||
<div class="input textarea<?= $optionsError ? ' error' : '' ?>">
|
||||
<label for="options-text"><?= __('Antwortoptionen (eine pro Zeile, max. 20)') ?></label>
|
||||
<textarea id="options-text" name="options_text" rows="6" required><?= h($optionsText) ?></textarea>
|
||||
<?php if ($optionsError) : ?>
|
||||
<div class="error-message"><?= h(implode(' ', (array)$optionsError)) ?></div>
|
||||
<?php endif; ?>
|
||||
<?php if (!empty($hasResponses)) : ?>
|
||||
<p class="hint"><?= __('Achtung: Entfernte oder umbenannte Optionen verlieren ihre bisherigen Stimmen.') ?></p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?= $this->Form->control('settings.multiple', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Mehrfachauswahl erlauben'),
|
||||
'checked' => (bool)$settings['multiple'],
|
||||
]) ?>
|
||||
<?php elseif ($slide->type === 'wordcloud') : ?>
|
||||
<?= $this->Form->control('settings.max_words', [
|
||||
'type' => 'number', 'min' => 0, 'max' => 50,
|
||||
'label' => __('Begriffe pro Person (0 = unbegrenzt)'),
|
||||
'value' => $settings['max_words'],
|
||||
]) ?>
|
||||
<p class="hint"><?= __('Upvotes zählen mit: Wer einen vorhandenen Begriff unterstützt oder erneut eingibt, verbraucht einen Begriff.') ?></p>
|
||||
<?= $this->Form->control('settings.allow_upvotes', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Upvotes erlauben (Teilnehmende sehen die Wortwolke live und können Begriffe per Klick unterstützen)'),
|
||||
'checked' => (bool)$settings['allow_upvotes'],
|
||||
]) ?>
|
||||
<?= $this->Form->control('settings.allow_downvotes', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Downvotes erlauben (nur zusammen mit Upvotes: Teilnehmende können Begriffe anderer ablehnen)'),
|
||||
'checked' => (bool)$settings['allow_downvotes'],
|
||||
]) ?>
|
||||
<?php elseif ($slide->type === 'scale') : ?>
|
||||
<div class="grid grid--2 grid--tight">
|
||||
<?= $this->Form->control('settings.scale_min', [
|
||||
'type' => 'select', 'options' => [0 => '0', 1 => '1'],
|
||||
'label' => __('Von'), 'value' => $settings['scale_min'],
|
||||
]) ?>
|
||||
<?= $this->Form->control('settings.scale_max', [
|
||||
'type' => 'select', 'options' => array_combine(range(2, 10), range(2, 10)),
|
||||
'label' => __('Bis'), 'value' => $settings['scale_max'],
|
||||
]) ?>
|
||||
<?= $this->Form->control('settings.min_label', [
|
||||
'label' => __('Beschriftung links (optional)'), 'maxlength' => 60,
|
||||
'placeholder' => __('z. B. gar nicht'), 'value' => $settings['min_label'],
|
||||
]) ?>
|
||||
<?= $this->Form->control('settings.max_label', [
|
||||
'label' => __('Beschriftung rechts (optional)'), 'maxlength' => 60,
|
||||
'placeholder' => __('z. B. sehr'), 'value' => $settings['max_label'],
|
||||
]) ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($slide->isInteractive()) : ?>
|
||||
<?= $this->Form->control('is_voting_open', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Abstimmung geöffnet'),
|
||||
'checked' => $isNew ? true : $slide->is_voting_open,
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="form-actions">
|
||||
<?= $this->Form->button($isNew ? __('Folie anlegen') : __('Speichern'), ['class' => 'button button--primary']) ?>
|
||||
<a class="button button--ghost" href="<?= $this->Url->build(['_name' => 'admin', 'token' => $adminToken]) ?>"><?= __('Abbrechen') ?></a>
|
||||
</div>
|
||||
<?= $this->Form->end() ?>
|
||||
</section>
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
/**
|
||||
* Renders the configured captcha inside a form.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var array<string, mixed> $captcha Result of CaptchaInterface::challenge()
|
||||
*/
|
||||
$type = $captcha['type'] ?? 'none';
|
||||
?>
|
||||
<?php if ($type === 'math') : ?>
|
||||
<div class="input text">
|
||||
<label for="captcha-answer"><?= __('Sicherheitsfrage: Was ist {0}?', h($captcha['question'])) ?></label>
|
||||
<input type="text" inputmode="numeric" pattern="-?[0-9]*" autocomplete="off" required
|
||||
id="captcha-answer" name="<?= h($captcha['field']) ?>" class="input-short">
|
||||
</div>
|
||||
<?php elseif ($type === 'recaptcha') : ?>
|
||||
<div class="input text">
|
||||
<?php if (empty($captcha['siteKey'])) : ?>
|
||||
<p class="hint hint--error"><?= __('reCAPTCHA ist aktiviert, aber nicht konfiguriert (RECAPTCHA_SITE_KEY fehlt).') ?></p>
|
||||
<?php else : ?>
|
||||
<div class="g-recaptcha" data-sitekey="<?= h($captcha['siteKey']) ?>"></div>
|
||||
<?php $this->Html->script('https://www.google.com/recaptcha/api.js', ['block' => 'script', 'async' => true, 'defer' => true, 'once' => true]) ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var array $params
|
||||
* @var string $message
|
||||
*/
|
||||
$class = 'message';
|
||||
if (!empty($params['class'])) {
|
||||
$class .= ' ' . $params['class'];
|
||||
}
|
||||
if (!isset($params['escape']) || $params['escape'] !== false) {
|
||||
$message = h($message);
|
||||
}
|
||||
?>
|
||||
<div class="<?= h($class) ?>" onclick="this.classList.add('hidden');"><?= $message ?></div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var array $params
|
||||
* @var string $message
|
||||
*/
|
||||
if (!isset($params['escape']) || $params['escape'] !== false) {
|
||||
$message = h($message);
|
||||
}
|
||||
?>
|
||||
<div class="message error" onclick="this.classList.add('hidden');"><?= $message ?></div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var array $params
|
||||
* @var string $message
|
||||
*/
|
||||
if (!isset($params['escape']) || $params['escape'] !== false) {
|
||||
$message = h($message);
|
||||
}
|
||||
?>
|
||||
<div class="message" onclick="this.classList.add('hidden');"><?= $message ?></div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var array $params
|
||||
* @var string $message
|
||||
*/
|
||||
if (!isset($params['escape']) || $params['escape'] !== false) {
|
||||
$message = h($message);
|
||||
}
|
||||
?>
|
||||
<div class="message success" onclick="this.classList.add('hidden')"><?= $message ?></div>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var array $params
|
||||
* @var string $message
|
||||
*/
|
||||
if (!isset($params['escape']) || $params['escape'] !== false) {
|
||||
$message = h($message);
|
||||
}
|
||||
?>
|
||||
<div class="message warning" onclick="this.classList.add('hidden');"><?= $message ?></div>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var string $adminUrl
|
||||
* @var string $joinUrl
|
||||
*/
|
||||
?>
|
||||
<p><?= __('Hallo,') ?></p>
|
||||
<p><?= __('deine Umfrage <strong>{0}</strong> wurde angelegt. Über den folgenden Link kannst du Fragen anlegen, die Präsentation starten und Ergebnisse ansehen:', h($poll->title)) ?></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 verwalten') ?></a>
|
||||
</p>
|
||||
<p style="font-size:13px;color:#5b5f7a;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>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
* @var \Cake\View\View $this
|
||||
* @var string $content
|
||||
*/
|
||||
|
||||
$lines = explode("\n", $content);
|
||||
|
||||
foreach ($lines as $line) :
|
||||
echo '<p> ' . $line . "</p>\n";
|
||||
endforeach;
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var list<array{title: string, url: string, created: string}> $links
|
||||
*/
|
||||
?>
|
||||
<p><?= __('Hallo,') ?></p>
|
||||
<p><?= __('du hast deine Admin-Links angefordert. Zu dieser E-Mail-Adresse gehören folgende Umfragen:') ?></p>
|
||||
<ul style="padding-left:18px;">
|
||||
<?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>
|
||||
</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>
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
* @var string $adminUrl
|
||||
* @var string $joinUrl
|
||||
*/
|
||||
?>
|
||||
<?= __('Hallo,') ?>
|
||||
|
||||
|
||||
<?= __('deine Umfrage "{0}" wurde angelegt. Über den folgenden Link kannst du Fragen anlegen, die Präsentation starten und Ergebnisse ansehen:', $poll->title) ?>
|
||||
|
||||
|
||||
<?= $adminUrl ?>
|
||||
|
||||
|
||||
<?= __('Wichtig: Wer diesen Link kennt, kann die Umfrage bearbeiten. Gib ihn nicht weiter.') ?>
|
||||
|
||||
|
||||
<?= __('Teilnehmende erreichen die Umfrage unter {0} mit dem Code {1}.', $joinUrl, $poll->formattedJoinCode()) ?>
|
||||
|
||||
|
||||
<?= __('Du hast diese Umfrage nicht angelegt? Dann kannst du diese E-Mail ignorieren.') ?>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
* @var \Cake\View\View $this
|
||||
* @var string $content
|
||||
*/
|
||||
|
||||
echo $content;
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
* @var list<array{title: string, url: string, created: string}> $links
|
||||
*/
|
||||
?>
|
||||
<?= __('Hallo,') ?>
|
||||
|
||||
|
||||
<?= __('du hast deine Admin-Links angefordert. Zu dieser E-Mail-Adresse gehören folgende Umfragen:') ?>
|
||||
|
||||
|
||||
<?php foreach ($links as $link) : ?>
|
||||
- <?= $link['title'] ?> (<?= __('angelegt am {0}', $link['created']) ?>)
|
||||
<?= $link['url'] ?>
|
||||
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?= __('Du hast diese E-Mail nicht angefordert? Dann kannst du sie ignorieren – deine Links bleiben unverändert gültig.') ?>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
|
||||
echo $this->fetch('content');
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
/**
|
||||
* Default layout for public, participant and admin pages.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
$title = $this->fetch('title');
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<?= $this->Html->charset() ?>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="csrf-token" content="<?= h((string)$this->request->getAttribute('csrfToken')) ?>">
|
||||
<?php if ($this->fetch('noindex')) : ?>
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<?php endif; ?>
|
||||
<title><?= $title ? h($title) . ' · ' : '' ?>Plenario</title>
|
||||
<?= $this->Html->meta('icon') ?>
|
||||
<?= $this->Html->css(['normalize.min', 'plenario']) ?>
|
||||
<?= $this->fetch('meta') ?>
|
||||
<?= $this->fetch('css') ?>
|
||||
</head>
|
||||
<body class="<?= h($this->fetch('bodyClass')) ?>">
|
||||
<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="brand" href="<?= $this->Url->build(['_name' => 'home']) ?>">
|
||||
<span class="brand__mark" aria-hidden="true"></span>Plenario
|
||||
</a>
|
||||
<nav class="site-nav">
|
||||
<a href="<?= $this->Url->build(['_name' => 'join']) ?>"><?= __('Teilnehmen') ?></a>
|
||||
<a href="<?= $this->Url->build(['_name' => 'recover']) ?>"><?= __('Admin-Link verloren?') ?></a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
<main class="container main">
|
||||
<?= $this->Flash->render() ?>
|
||||
<?= $this->fetch('content') ?>
|
||||
</main>
|
||||
<footer class="site-footer container">
|
||||
<span>Plenario – <?= __('Live-Umfragen ohne Login') ?></span>
|
||||
</footer>
|
||||
<?= $this->Html->script('plenario') ?>
|
||||
<?= $this->fetch('script') ?>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
/**
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<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>
|
||||
<?= $this->fetch('content') ?>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
|
||||
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* For full copyright and license information, please see the LICENSE.txt
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
|
||||
* @link https://cakephp.org CakePHP(tm) Project
|
||||
* @since 0.10.0
|
||||
* @license https://opensource.org/licenses/mit-license.php MIT License
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
|
||||
echo $this->fetch('content');
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
/**
|
||||
* Layout for production error pages (debug = false).
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<?= $this->Html->charset() ?>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title><?= h($this->fetch('title')) ?> · Plenario</title>
|
||||
<?= $this->Html->meta('icon') ?>
|
||||
<?= $this->Html->css(['normalize.min', 'plenario']) ?>
|
||||
</head>
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container site-header__inner">
|
||||
<a class="brand" href="<?= $this->Url->build('/') ?>"><span class="brand__mark" aria-hidden="true"></span>Plenario</a>
|
||||
</div>
|
||||
</header>
|
||||
<main class="container main">
|
||||
<section class="card card--narrow center">
|
||||
<?= $this->fetch('content') ?>
|
||||
<p><a class="button" href="<?= $this->Url->build('/') ?>"><?= __('Zur Startseite') ?></a></p>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
/**
|
||||
* Full screen presenter layout (dark, no navigation).
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
*/
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<?= $this->Html->charset() ?>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<meta name="csrf-token" content="<?= h((string)$this->request->getAttribute('csrfToken')) ?>">
|
||||
<title><?= h($this->fetch('title')) ?> · Plenario</title>
|
||||
<?= $this->Html->meta('icon') ?>
|
||||
<?= $this->Html->css(['normalize.min', 'plenario']) ?>
|
||||
</head>
|
||||
<body class="present">
|
||||
<?= $this->fetch('content') ?>
|
||||
<?= $this->Html->script('plenario') ?>
|
||||
<?= $this->fetch('script') ?>
|
||||
</body>
|
||||
</html>
|
||||
Whitespace-only changes.
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\Fixture;
|
||||
|
||||
use Cake\TestSuite\Fixture\TestFixture;
|
||||
|
||||
/**
|
||||
* Empty fixture - schema comes from migrations, test data is created in the tests
|
||||
* (see App\Test\TestCase\PlenarioTestTrait).
|
||||
*/
|
||||
class PollsFixture extends TestFixture
|
||||
{
|
||||
/**
|
||||
* @var array<array<string, mixed>>
|
||||
*/
|
||||
public array $records = [];
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\Fixture;
|
||||
|
||||
use Cake\TestSuite\Fixture\TestFixture;
|
||||
|
||||
/**
|
||||
* Empty fixture - schema comes from migrations, test data is created in the tests
|
||||
* (see App\Test\TestCase\PlenarioTestTrait).
|
||||
*/
|
||||
class ResponsesFixture extends TestFixture
|
||||
{
|
||||
/**
|
||||
* @var array<array<string, mixed>>
|
||||
*/
|
||||
public array $records = [];
|
||||
}
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user