From d1facd32a6f2bfae671a7e722a3aabb888a12472 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sun, 8 Nov 2026 19:21:10 +0100 Subject: [PATCH] Replace CSV export with PDF export The results export is now a PDF (Dompdf) with all interactive slides. By default private slides (anonymous/internal feedback) only show their number of participants; ?internal=1 creates the complete version incl. their answers, marked as confidential on every page. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 22 +- README.md | 2 +- composer.json | 1 + composer.lock | 308 +++++++++++++++++- config/routes.php | 2 +- src/Controller/AdminController.php | 104 +----- src/Model/Entity/Slide.php | 2 +- src/Service/ReportService.php | 116 +++++++ src/View/PdfView.php | 113 +++++++ templates/Admin/export.php | 229 +++++++++++++ templates/Admin/index.php | 30 +- templates/Slides/answers.php | 2 +- templates/Slides/form.php | 4 +- templates/layout/pdf.php | 55 ++++ .../Controller/AdminControllerTest.php | 3 +- tests/TestCase/Controller/OrderSlideTest.php | 6 +- tests/TestCase/Controller/PdfExportTest.php | 169 ++++++++++ tests/TestCase/Controller/QaSlideTest.php | 6 +- .../TestCase/Controller/ScaleCommentsTest.php | 6 +- tests/TestCase/PlenarioTestTrait.php | 23 ++ webroot/css/plenario.css | 9 + 21 files changed, 1102 insertions(+), 110 deletions(-) create mode 100644 src/Service/ReportService.php create mode 100644 src/View/PdfView.php create mode 100644 templates/Admin/export.php create mode 100644 templates/layout/pdf.php create mode 100644 tests/TestCase/Controller/PdfExportTest.php diff --git a/AGENTS.md b/AGENTS.md index 8fbaa4a..79e37be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,7 @@ src/ 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 + AdminController Dashboard, Settings, Present, State-JSON, Control, QR, PDF-Export, Token rotieren, Löschen SlidesController Folien-CRUD, Antworten offener Fragen bzw. Skala-Auswertung (`answers`), Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen, YouTube-Link prüfen (`youtubeCheck`, JSON) ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid @@ -69,6 +69,8 @@ src/ YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam) + ReportService Daten für den PDF-Export: Ergebnisse aller interaktiven Folien, mit/ohne interne Inhalte + View/PdfView.php Rendert Template als HTML (Layout `pdf`) und wandelt es mit Dompdf in ein PDF templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email webroot/css/plenario.css Eigenes CSS, kein Framework; Farben nur als Tokens (Hell/Dunkel, siehe Theme unten) webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Sortieren (`makeSortable`: Pointer Events + Pfeiltasten, @@ -168,16 +170,25 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures - **Anonymes Feedback** (offene Frage mit Setting `private`, `Slide::isPrivate()`): Antworttexte erscheinen **nie** im Presenter-/Embed-JSON (`results.answers` leer, nur `participants`) und nie bei Teilnehmenden (keine `results`, unabhängig von `show_results_to_participants`). Lesen nur in der Verwaltung (`slides:answers`, - `ResultsService::answers()`) und im CSV-Export. + `ResultsService::answers()`) und in der vollständigen Fassung des PDF-Exports. - **Internes Feedback** (Skala mit Setting `private`, ebenfalls `Slide::isPrivate()`): Presenter-/Embed-JSON enthält `buckets: []` und `average: null` (nur `participants`), Teilnehmende bekommen keine `results`. Verteilung und - Durchschnitt nur in der Verwaltung (`slides:answers` → „Auswertung“, `ResultsService::scaleResults()`) und im CSV-Export. + Durchschnitt nur in der Verwaltung (`slides:answers` → „Auswertung“, `ResultsService::scaleResults()`) und in der vollständigen Fassung des PDF-Exports. - **Skala-Kommentare** (Setting `comments`, `Slide::hasComments()`): optionales Feld `comment`, gespeichert als `text_value` in derselben Zeile wie `numeric_value` (ohne Setting wird es ignoriert). Öffentliche Skalen liefern im Presenter-/Embed-State `results.comments` (Teilnehmende bekommen immer `[]`, `PollStateService::participantResults()`) (älteste zuerst, je `id`, `text`, `value` – `value` nur mit Setting `comment_ratings`, sonst `null`); `Comments` in `plenario.js` blättert sie automatisch durch („Kommentar X von N“, vor/zurück/Pause, Zustand übersteht das Neu-Rendern beim Polling). Bei internem Feedback bleibt `comments` leer, - lesbar nur in der Auswertung (`ResultsService::comments()`) und im CSV-Export. + lesbar nur in der Auswertung (`ResultsService::comments()`) und in der vollständigen Fassung des PDF-Exports. + +- **PDF-Export** (`/admin/{token}/export.pdf`, `admin:export`, `ReportService` + `PdfView`, Dompdf): Ergebnisse aller + interaktiven Folien (Inhaltsfolien/YouTube fehlen). Standard ist die Fassung **ohne interne Inhalte**: private Folien + (`Slide::isPrivate()`) erscheinen nur mit Teilnehmerzahl, wie im Presenter. `?internal=1` = vollständige Fassung inkl. + anonymer Antworten, interner Skalen und Kommentar-Bewertungen (Dateiname `…-intern.pdf`, Hinweis „Vertraulich“ auf jeder + Seite); ohne private Folien wird der Parameter ignoriert. Quiz/Reihenfolge folgen auch hier den Auflöse-Regeln + (vor `finished` bzw. Schließen keine Zählungen/Lösung). Layout `templates/layout/pdf.php` ist eigenständig: keine + externen Ressourcen, keine CSS-Variablen, Schrift DejaVu Sans; Seitenzahlen setzt `PdfView::addPageNumbers()`. + Tests prüfen das HTML über `PlenarioTestTrait::exportHtml()` (das PDF selbst ist nicht durchsuchbar). ### Neuen Folientyp hinzufügen (Checkliste) @@ -186,7 +197,8 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures 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.`), Styles in `plenario.css`, Badge-Farbe +6. Renderer in `webroot/js/plenario.js` (`Results.`), Styles in `plenario.css`, Badge-Farbe; + Ausgabe im PDF-Export (`templates/Admin/export.php`) 7. Tests in `tests/TestCase/Service/VoteServiceTest.php` (Quiz: `QuizTest.php`, Q&A: `QaTest.php`) 8. Nach neuen Spalten lokal `bin/cake cache clear_all`, sonst nutzt das ORM das alte Schema aus dem Cache diff --git a/README.md b/README.md index d2f2318..f0cb0c9 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Basiert auf **CakePHP 5.4** (PHP ≥ 8.2), läuft lokal mit **SQLite**, ohne Bui - 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 +- PDF-Export der Ergebnisse (wahlweise ohne oder mit internem/anonymem Feedback), 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 diff --git a/composer.json b/composer.json index 1e06fb4..9018403 100644 --- a/composer.json +++ b/composer.json @@ -10,6 +10,7 @@ "cakephp/migrations": "^5.0", "cakephp/plugin-installer": "^2.0", "chillerlan/php-qrcode": "^6.0", + "dompdf/dompdf": "^3.1", "josegonzalez/dotenv": "^4.0", "mobiledetect/mobiledetectlib": "^4.8.03" }, diff --git a/composer.lock b/composer.lock index 0c89f90..b984e32 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "88c13c87305bce8edbbea435904da107", + "content-hash": "ddccb2d95917b222589d74cc89a09235", "packages": [ { "name": "cakephp/cakephp", @@ -550,6 +550,164 @@ "time": "2026-10-29T14:10:42+00:00", "published-time": "2026-10-29T14:45:12+00:00" }, + { + "name": "dompdf/dompdf", + "version": "v3.1.6", + "source": { + "type": "git", + "url": "https://github.com/dompdf/dompdf.git", + "reference": "6d4b4eb8500f7a786da8868ba463a71b725a4005" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/dompdf/zipball/6d4b4eb8500f7a786da8868ba463a71b725a4005", + "reference": "6d4b4eb8500f7a786da8868ba463a71b725a4005", + "shasum": "" + }, + "require": { + "dompdf/php-font-lib": "^1.0.0", + "dompdf/php-svg-lib": "^1.0.0", + "ext-dom": "*", + "ext-mbstring": "*", + "masterminds/html5": "^2.0", + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "ext-gd": "*", + "ext-json": "*", + "ext-zip": "*", + "mockery/mockery": "^1.3", + "phpunit/phpunit": "^7.5 || ^8 || ^9 || ^10 || ^11", + "squizlabs/php_codesniffer": "^3.5", + "symfony/process": "^4.4 || ^5.4 || ^6.2 || ^7.0" + }, + "suggest": { + "ext-gd": "Needed to process images", + "ext-gmagick": "Improves image processing performance", + "ext-imagick": "Improves image processing performance", + "ext-zlib": "Needed for pdf stream compression" + }, + "type": "library", + "autoload": { + "psr-4": { + "Dompdf\\": "src/" + }, + "classmap": [ + "lib/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1" + ], + "authors": [ + { + "name": "The Dompdf Community", + "homepage": "https://github.com/dompdf/dompdf/blob/master/AUTHORS.md" + } + ], + "description": "DOMPDF is a CSS 2.1 compliant HTML to PDF converter", + "homepage": "https://github.com/dompdf/dompdf", + "support": { + "issues": "https://github.com/dompdf/dompdf/issues", + "source": "https://github.com/dompdf/dompdf/tree/v3.1.6" + }, + "time": "2026-07-20T12:29:38+00:00", + "published-time": "2026-07-20T12:35:08+00:00" + }, + { + "name": "dompdf/php-font-lib", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/dompdf/php-font-lib.git", + "reference": "a6e9a688a2a80016ac080b97be73d3e10c444c9a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/php-font-lib/zipball/a6e9a688a2a80016ac080b97be73d3e10c444c9a", + "reference": "a6e9a688a2a80016ac080b97be73d3e10c444c9a", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": "^7.1 || ^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.5 || ^8 || ^9 || ^10 || ^11 || ^12" + }, + "type": "library", + "autoload": { + "psr-4": { + "FontLib\\": "src/FontLib" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-2.1-or-later" + ], + "authors": [ + { + "name": "The FontLib Community", + "homepage": "https://github.com/dompdf/php-font-lib/blob/master/AUTHORS.md" + } + ], + "description": "A library to read, parse, export and make subsets of different types of font files.", + "homepage": "https://github.com/dompdf/php-font-lib", + "support": { + "issues": "https://github.com/dompdf/php-font-lib/issues", + "source": "https://github.com/dompdf/php-font-lib/tree/1.0.2" + }, + "time": "2026-01-20T14:10:26+00:00", + "published-time": "2026-01-20T14:14:50+00:00" + }, + { + "name": "dompdf/php-svg-lib", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/dompdf/php-svg-lib.git", + "reference": "8259ffb930817e72b1ff1caef5d226501f3dfeb1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/php-svg-lib/zipball/8259ffb930817e72b1ff1caef5d226501f3dfeb1", + "reference": "8259ffb930817e72b1ff1caef5d226501f3dfeb1", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": "^7.1 || ^8.0", + "sabberworm/php-css-parser": "^8.4 || ^9.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.5 || ^8 || ^9 || ^10 || ^11" + }, + "type": "library", + "autoload": { + "psr-4": { + "Svg\\": "src/Svg" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-or-later" + ], + "authors": [ + { + "name": "The SvgLib Community", + "homepage": "https://github.com/dompdf/php-svg-lib/blob/master/AUTHORS.md" + } + ], + "description": "A library to read, parse and export to PDF SVG files.", + "homepage": "https://github.com/dompdf/php-svg-lib", + "support": { + "issues": "https://github.com/dompdf/php-svg-lib/issues", + "source": "https://github.com/dompdf/php-svg-lib/tree/1.0.2" + }, + "time": "2026-01-02T16:01:13+00:00", + "published-time": "2026-01-02T16:02:22+00:00" + }, { "name": "josegonzalez/dotenv", "version": "4.0.0", @@ -914,6 +1072,75 @@ "time": "2020-02-19T09:02:13+00:00", "published-time": "2020-02-20T19:46:58+00:00" }, + { + "name": "masterminds/html5", + "version": "2.12.0", + "source": { + "type": "git", + "url": "https://github.com/Masterminds/html5-php.git", + "reference": "15e16663bd6f512352209d0e3a789c0a691c0d9b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Masterminds/html5-php/zipball/15e16663bd6f512352209d0e3a789c0a691c0d9b", + "reference": "15e16663bd6f512352209d0e3a789c0a691c0d9b", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=7.4" + }, + "require-dev": { + "phpunit/phpunit": "^6 || ^7 || ^8 || ^9 || ^10" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.7-dev" + } + }, + "autoload": { + "psr-4": { + "Masterminds\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Matt Butcher", + "email": "technosophos@gmail.com" + }, + { + "name": "Matt Farina", + "email": "matt@mattfarina.com" + }, + { + "name": "Asmir Mustafic", + "email": "goetas@gmail.com" + } + ], + "description": "An HTML5 parser and serializer.", + "homepage": "http://masterminds.github.io/html5-php", + "keywords": [ + "HTML5", + "dom", + "html", + "parser", + "querypath", + "serializer", + "xml" + ], + "support": { + "issues": "https://github.com/Masterminds/html5-php/issues", + "source": "https://github.com/Masterminds/html5-php/tree/2.12.0" + }, + "time": "2026-10-25T08:57:58+00:00", + "published-time": "2026-10-25T08:58:48+00:00" + }, { "name": "mobiledetect/mobiledetectlib", "version": "4.11.0", @@ -1570,6 +1797,85 @@ }, "time": "2021-10-29T13:26:27+00:00", "published-time": "2021-10-29T13:27:19+00:00" + }, + { + "name": "sabberworm/php-css-parser", + "version": "v9.5.0", + "source": { + "type": "git", + "url": "https://github.com/MyIntervals/PHP-CSS-Parser.git", + "reference": "f284e63b6e891e0c28631e54ba06c3ed102a9ef3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/MyIntervals/PHP-CSS-Parser/zipball/f284e63b6e891e0c28631e54ba06c3ed102a9ef3", + "reference": "f284e63b6e891e0c28631e54ba06c3ed102a9ef3", + "shasum": "" + }, + "require": { + "ext-iconv": "*", + "php": "^7.2.0 || ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0" + }, + "require-dev": { + "php-parallel-lint/php-parallel-lint": "1.4.0", + "phpstan/extension-installer": "1.4.3", + "phpstan/phpstan": "1.12.33 || 2.2.9", + "phpstan/phpstan-phpunit": "1.4.2 || 2.0.18", + "phpstan/phpstan-strict-rules": "1.6.2 || 2.0.12", + "phpunit/phpunit": "8.5.54", + "rawr/phpunit-data-provider": "3.3.1", + "rector/rector": "1.2.10 || 2.6.2", + "rector/type-perfect": "1.0.0 || 2.1.4", + "squizlabs/php_codesniffer": "4.0.4" + }, + "suggest": { + "ext-mbstring": "for parsing UTF-8 CSS" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "9.6.x-dev" + } + }, + "autoload": { + "files": [ + "src/Rule/Rule.php", + "src/RuleSet/RuleContainer.php" + ], + "psr-4": { + "Sabberworm\\CSS\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Raphael Schweikert" + }, + { + "name": "Oliver Klee", + "email": "github@oliverklee.de" + }, + { + "name": "Jake Hotson", + "email": "jake.github@qzdesign.co.uk" + } + ], + "description": "Parser for CSS Files written in PHP", + "homepage": "https://www.sabberworm.com/blog/2010/6/10/php-css-parser", + "keywords": [ + "css", + "parser", + "stylesheet" + ], + "support": { + "issues": "https://github.com/MyIntervals/PHP-CSS-Parser/issues", + "source": "https://github.com/MyIntervals/PHP-CSS-Parser/tree/v9.5.0" + }, + "time": "2026-09-20T15:02:00+00:00", + "published-time": "2026-09-20T15:20:25+00:00" } ], "packages-dev": [ diff --git a/config/routes.php b/config/routes.php index 93f74c6..a28f2fe 100644 --- a/config/routes.php +++ b/config/routes.php @@ -70,7 +70,7 @@ return function (RouteBuilder $routes): void { $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('/export.pdf', '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']) diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index f943153..a478c92 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -9,11 +9,13 @@ use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; use App\Service\PollStateService; use App\Service\QaService; +use App\Service\ReportService; use App\Service\SlideControlService; -use App\Service\VoteService; +use App\View\PdfView; use Cake\Core\Configure; use Cake\Http\Exception\BadRequestException; use Cake\Http\Response; +use Cake\I18n\DateTime; use Cake\Log\Log; use Cake\Routing\Router; use chillerlan\QRCode\Output\QRMarkupSVG; @@ -275,97 +277,27 @@ class AdminController extends AdminAppController } /** - * CSV export of all responses (semicolon separated, UTF-8 with BOM for Excel). + * PDF report with the results of all interactive slides. + * Query `internal=1` includes anonymous/internal feedback (complete version for the owner), + * otherwise private slides only show their number of participants. * * @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'], ';', '"', ''); + $report = new ReportService(); + $hasInternal = $report->hasInternalContent($this->poll); + $includeInternal = $hasInternal && $this->request->getQuery('internal') === '1'; - foreach ($slides as $position => $slide) { - if (!$slide->isInteractive()) { - continue; - } - $labels = []; - foreach ($slide->slide_options ?? [] as $option) { - $labels[$option->id] = $slide->isQuiz() - ? __('{0} ({1})', $option->label, $option->is_correct ? __('richtig') : __('falsch')) - : $option->label; - } - $responses = $this->Responses->find() - ->where(['slide_id' => $slide->id]) - ->orderBy(['id' => 'ASC']) - ->all(); - $texts = []; - foreach ($responses as $response) { - $texts[$response->id] = (string)$response->text_value; - $answer = match (true) { - $slide->isOrder() => $this->orderAnswer($slide, $labels, (string)$response->text_value), - $response->parent_id !== null => __('Upvote: {0}', $texts[$response->parent_id] ?? ''), - $response->slide_option_id !== null => $labels[$response->slide_option_id] ?? '', - $response->text_value !== null && $response->numeric_value === VoteService::DOWNVOTE - => __('Downvote: {0}', $response->text_value), - $slide->type === Slide::TYPE_SCALE && $response->text_value !== null - => __('{0} (Kommentar: {1})', $response->numeric_value, $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); + $this->viewBuilder()->setClassName(PdfView::class); + $this->set([ + 'sections' => $report->build($this->poll, $includeInternal), + 'includeInternal' => $includeInternal, + 'hasInternal' => $hasInternal, + 'exportedAt' => DateTime::now(), + ]); + $filename = 'plenario-' . $this->poll->join_code . '-' . date('Ymd') . ($includeInternal ? '-intern' : '') . '.pdf'; - $filename = 'plenario-' . $this->poll->join_code . '-' . date('Ymd') . '.csv'; - - return $this->protect($this->response) - ->withType('csv') - ->withCharset('UTF-8') - ->withDownload($filename) - ->withStringBody($csv); - } - - /** - * Ordering answer for the CSV export, e.g. "A → C → B (falsch)". - * - * @param \App\Model\Entity\Slide $slide Ordering slide incl. slide_options - * @param array $labels Option labels by id - * @param string $text Stored answer (option ids) - * @return string - */ - protected function orderAnswer(Slide $slide, array $labels, string $text): string - { - $given = VoteService::parseOrder($text); - $correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? [])); - - return __( - '{0} ({1})', - implode(' → ', array_map(fn(int $id) => $labels[$id] ?? '?', $given)), - $given === $correct ? __('richtig') : __('falsch'), - ); - } - - /** - * 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; + return $this->render()->withDownload($filename); } } diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index af61d4a..29a3db8 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -384,7 +384,7 @@ class Slide extends Entity /** * Open question or scale collecting anonymous/internal feedback: answers and ratings are - * never shown on the presenter screen or to participants, only in the admin area and the CSV export. + * never shown on the presenter screen or to participants, only in the admin area and the complete version of the PDF export. * * @return bool */ diff --git a/src/Service/ReportService.php b/src/Service/ReportService.php new file mode 100644 index 0000000..0fc51ca --- /dev/null +++ b/src/Service/ReportService.php @@ -0,0 +1,116 @@ + Slide, 'number' => int (position in the poll, 1-based), + * 'internal' => bool (private slide), 'withheld' => bool (private and left out), + * 'results' => ResultsService::forSlide() shape, where + * open: 'answers' contains all texts (not only the newest ones), and + * scale: 'comments' contains all comments, 'value' only in the complete version or with comment_ratings]. + */ +class ReportService +{ + use LocatorAwareTrait; + + protected SlidesTable $Slides; + + protected ResultsService $results; + + /** + * Constructor + */ + public function __construct() + { + /** @var \App\Model\Table\SlidesTable $slides */ + $slides = $this->fetchTable('Slides'); + $this->Slides = $slides; + $this->results = new ResultsService(); + } + + /** + * @param \App\Model\Entity\Poll $poll Poll + * @param bool $includeInternal Include answers of private slides + * @return list}> + */ + public function build(Poll $poll, bool $includeInternal): array + { + $sections = []; + foreach ($this->Slides->listForPoll($poll->id) as $index => $slide) { + if (!$slide->isInteractive()) { + continue; + } + $internal = $slide->isPrivate(); + $sections[] = [ + 'slide' => $slide, + 'number' => $index + 1, + 'internal' => $internal, + 'withheld' => $internal && !$includeInternal, + 'results' => $this->resultsFor($slide, $includeInternal), + ]; + } + + return $sections; + } + + /** + * Whether the poll has slides whose answers are not public. + * + * @param \App\Model\Entity\Poll $poll Poll + * @return bool + */ + public function hasInternalContent(Poll $poll): bool + { + foreach ($this->Slides->listForPoll($poll->id) as $slide) { + if ($slide->isInteractive() && $slide->isPrivate()) { + return true; + } + } + + return false; + } + + /** + * @param \App\Model\Entity\Slide $slide Slide incl. slide_options + * @param bool $includeInternal Include answers of private slides + * @return array + */ + protected function resultsFor(Slide $slide, bool $includeInternal): array + { + // Public shape first: it never contains private data. + $results = $this->results->forSlide($slide); + $mayRead = !$slide->isPrivate() || $includeInternal; + + if ($slide->type === Slide::TYPE_OPEN && $mayRead) { + $results['answers'] = $this->results->answers($slide); + } + if ($slide->type === Slide::TYPE_SCALE && $mayRead) { + // Ratings next to comments: complete version always, public one only with the setting. + $showRatings = $includeInternal || (bool)$slide->setting('comment_ratings'); + $comments = []; + foreach ($slide->hasComments() ? $this->results->comments($slide) : [] as $comment) { + $comments[] = [ + 'id' => $comment['id'], + 'text' => $comment['text'], + 'value' => $showRatings ? $comment['value'] : null, + ]; + } + $results = $this->results->scaleResults($slide) + ['comments' => $comments] + $results; + } + + return $results; + } +} diff --git a/src/View/PdfView.php b/src/View/PdfView.php new file mode 100644 index 0000000..5de4742 --- /dev/null +++ b/src/View/PdfView.php @@ -0,0 +1,113 @@ +response = $this->response->withType('pdf'); + } + + /** + * @inheritDoc + */ + public function render(?string $template = null, string|false|null $layout = null): string + { + return $this->toPdf(parent::render($template, $layout)); + } + + /** + * Renders the template as HTML only (e.g. for tests). + * + * @param string|null $template Template + * @return string + */ + public function renderHtml(?string $template = null): string + { + return parent::render($template); + } + + /** + * @param string $html Complete HTML document + * @return string PDF data + */ + protected function toPdf(string $html): string + { + $cache = TMP . 'dompdf'; + if (!is_dir($cache)) { + mkdir($cache, 0775, true); + } + $options = new Options([ + 'isRemoteEnabled' => false, + 'isPhpEnabled' => false, + 'isJavascriptEnabled' => false, + 'defaultFont' => 'DejaVu Sans', + 'defaultPaperSize' => 'a4', + 'fontCache' => $cache, + 'tempDir' => $cache, + ]); + $dompdf = new Dompdf($options); + $dompdf->loadHtml($html, 'UTF-8'); + $dompdf->render(); + $this->addPageNumbers($dompdf); + + return (string)$dompdf->output(); + } + + /** + * "Seite X von Y" bottom right on every page (CSS counter(pages) is not supported by Dompdf). + * Matches .page-footer in the layout: 8pt, 16mm right margin, 8mm above the bottom edge. + * + * @param \Dompdf\Dompdf $dompdf Rendered document + * @return void + */ + protected function addPageNumbers(Dompdf $dompdf): void + { + $canvas = $dompdf->getCanvas(); + $metrics = $dompdf->getFontMetrics(); + $font = $metrics->getFont('DejaVu Sans'); + if ($font === null) { + return; + } + $size = 8; + $text = __('Seite {0} von {1}', '{PAGE_NUM}', '{PAGE_COUNT}'); + $mm = 72 / 25.4; + // Placeholders are replaced per page, so the width is estimated with one-digit numbers. + $width = $metrics->getTextWidth(__('Seite {0} von {1}', '0', '0'), $font, $size); + $canvas->page_text( + $canvas->get_width() - 16 * $mm - $width, + $canvas->get_height() - 8 * $mm - $size * 1.45, + $text, + $font, + $size, + [0.365, 0.384, 0.502], + ); + } +} diff --git a/templates/Admin/export.php b/templates/Admin/export.php new file mode 100644 index 0000000..4894446 --- /dev/null +++ b/templates/Admin/export.php @@ -0,0 +1,229 @@ +}> $sections + * @var bool $includeInternal + * @var bool $hasInternal Poll has private slides + * @var \Cake\I18n\DateTime $exportedAt + */ +$this->assign('title', $poll->title); +$number = fn(float $value, int $places = 0) => $this->Number->format($value, [ + 'places' => $places, + 'precision' => max(1, $places), + 'locale' => 'de_DE', +]); +$bar = function (float $percent, bool $ok = false): string { + $width = max(0, min(100, $percent)); + if ($width <= 0) { + // An empty fill would still be drawn as a hairline. + return '
'; + } + + return '
'; +}; +?> + + + +

+

title) ?>

+

+ + · i18nFormat('dd.MM.yyyy')) ?> +

+ + + + + + + + +

+ + +type === 'scale'; + // Short sections stay on one page, long lists may break across pages. + $long = count($r['answers'] ?? []) > 8 || count($r['words'] ?? []) > 15 + || count($r['questions'] ?? []) > 10 || count($r['comments'] ?? []) > 5; + ?> +
+

+ · typeLabel()) ?> + + · + +

+

question) ?>

+ description) : ?> +

description)) ?>

+ +

+ + +

+ +

+ + type === 'choice') : ?> + + + + + + + + + + + + +
%
+ + type === 'quiz') : ?> + +

+ +

+ + + + + + > + + + + + + +
%
+ + + type === 'order') : ?> + +

+ +

+ + + + + + + + + + + + +
. ( %)
+ + + type === 'wordcloud') : + $hasDown = array_sum(array_column($r['words'], 'down')) > 0; ?> + + + + + + + + + + + +
+ + type === 'open') : ?> +

()

+
    + +
  1. + +
+ + +

+ : + + +

+ + + + $bucket) : + $label = match (true) { + $i === 0 => (string)$r['minLabel'], + $i === count($r['buckets']) - 1 => (string)$r['maxLabel'], + default => '', + }; ?> + + + + + + + + +
() %
+ hasComments()) : ?> +

+ +

+ +
    + +
  1. + + () +
  2. + +
+ + + + type === 'qa') : ?> + +

+ + + + + $question) : ?> + + + + + + + +
#
.
+ + +
+ diff --git a/templates/Admin/index.php b/templates/Admin/index.php index 2072adb..35516a3 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -15,6 +15,7 @@ $this->assign('title', $poll->title); $this->assign('noindex', '1'); $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $adminToken] + $params; +$hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $slide->isPrivate()) !== []; ?>
@@ -42,7 +43,7 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad 'title' => __('Keine Folie zeigen – Teilnehmende sehen eine Pause-Seite'), ]) ?> - +
@@ -177,6 +178,33 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad +
+

+

+ Form->create(null, ['url' => $url('admin:export'), 'type' => 'get']) ?> + +
+ + + +
+ + Form->button(__('PDF herunterladen'), ['class' => 'button']) ?> + Form->end() ?> +
+

diff --git a/templates/Slides/answers.php b/templates/Slides/answers.php index 9ba03b3..2af92fb 100644 --- a/templates/Slides/answers.php +++ b/templates/Slides/answers.php @@ -1,7 +1,7 @@ getError('options_text'); 'label' => __('Anonymes Feedback: Antworten nicht öffentlich anzeigen'), 'checked' => (bool)$settings['private'], ]) ?> -

+

type === 'wordcloud') : ?> Form->control('settings.allow_upvotes', [ 'type' => 'checkbox', @@ -182,7 +182,7 @@ $optionsError = $slide->getError('options_text'); 'label' => __('Internes Feedback: Ergebnis nicht öffentlich anzeigen'), 'checked' => (bool)$settings['private'], ]) ?> -

+

type === 'quiz') : $quizError = $slide->getError('quiz_options'); $rows = $quizOptions; diff --git a/templates/layout/pdf.php b/templates/layout/pdf.php new file mode 100644 index 0000000..f2b8547 --- /dev/null +++ b/templates/layout/pdf.php @@ -0,0 +1,55 @@ + + + + + + <?= h($this->fetch('title')) ?> + + + + fetch('content') ?> + + diff --git a/tests/TestCase/Controller/AdminControllerTest.php b/tests/TestCase/Controller/AdminControllerTest.php index a21d4da..d940ea3 100644 --- a/tests/TestCase/Controller/AdminControllerTest.php +++ b/tests/TestCase/Controller/AdminControllerTest.php @@ -291,8 +291,9 @@ class AdminControllerTest extends TestCase $this->assertResponseOk(); $this->assertContentType('image/svg+xml'); - $this->get("/admin/$token/export.csv"); + $this->get("/admin/$token/export.pdf"); $this->assertResponseOk(); + $this->assertContentType('application/pdf'); $this->assertHeaderContains('Content-Disposition', 'attachment'); } } diff --git a/tests/TestCase/Controller/OrderSlideTest.php b/tests/TestCase/Controller/OrderSlideTest.php index 8dd37ad..2b406fb 100644 --- a/tests/TestCase/Controller/OrderSlideTest.php +++ b/tests/TestCase/Controller/OrderSlideTest.php @@ -86,8 +86,8 @@ class OrderSlideTest extends TestCase $this->get('/p/' . $poll->join_code); $this->assertResponseContains('Richtig – deine Reihenfolge stimmt!'); - $this->get("/admin/$token/export.csv"); - $this->assertResponseOk(); - $this->assertResponseContains('Eins → Zwei → Drei (richtig)'); + $html = $this->exportHtml($token); + $this->assertStringContainsString('1 von 1', $html); + $this->assertStringContainsString('komplett richtig sortiert', $html); } } diff --git a/tests/TestCase/Controller/PdfExportTest.php b/tests/TestCase/Controller/PdfExportTest.php new file mode 100644 index 0000000..0576410 --- /dev/null +++ b/tests/TestCase/Controller/PdfExportTest.php @@ -0,0 +1,169 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + protected function hash(string $char, Poll $poll): string + { + return VoteService::participantHash(str_repeat($char, 32), $poll->id); + } + + /** + * Poll with a public choice, a public open question, anonymous feedback and an internal scale with comments. + * + * @return array{0: \App\Model\Entity\Poll, 1: string} + */ + protected function pollWithPrivateSlides(): array + { + [$poll, $token] = $this->createPoll('Teamrunde'); + $votes = new VoteService(); + $choice = $this->createSlide($poll, Slide::TYPE_CHOICE, ['question' => 'Pizza oder Pasta?'], ['Pizza', 'Pasta']); + $open = $this->createSlide($poll, Slide::TYPE_OPEN, ['question' => 'Wünsche?']); + $anonymous = $this->createSlide($poll, Slide::TYPE_OPEN, [ + 'question' => 'Was läuft schief?', + 'settings' => ['private' => true], + ]); + $scale = $this->createSlide($poll, Slide::TYPE_SCALE, [ + 'question' => 'Wie zufrieden bist du?', + 'settings' => ['scale_min' => 1, 'scale_max' => 5, 'private' => true, 'comments' => true], + ]); + + $poll = $this->goLive($poll, $choice); + $votes->submit($poll, $choice, $this->hash('a', $poll), ['option_id' => $choice->slide_options[0]->id]); + $poll = $this->goLive($poll, $open); + $votes->submit($poll, $open, $this->hash('a', $poll), ['text' => 'Mehr ']); + $poll = $this->goLive($poll, $anonymous); + $votes->submit($poll, $anonymous, $this->hash('a', $poll), ['text' => 'Geheime Kritik']); + $poll = $this->goLive($poll, $scale); + $votes->submit($poll, $scale, $this->hash('a', $poll), ['value' => 2, 'comment' => 'Interner Kommentar']); + $votes->submit($poll, $scale, $this->hash('b', $poll), ['value' => 5]); + + return [$poll, $token]; + } + + public function testDownloadsPdf(): void + { + [$poll, $token] = $this->pollWithPrivateSlides(); + + $this->exportHtml($token); + + $this->assertHeaderContains('Content-Disposition', 'attachment'); + $this->assertHeaderContains('Content-Disposition', 'plenario-' . $poll->join_code . '-' . date('Ymd') . '.pdf'); + $this->assertHeader('Cache-Control', 'no-store, private'); + $this->assertHeader('Referrer-Policy', 'no-referrer'); + } + + public function testPublicVersionLeavesOutInternalContent(): void + { + [, $token] = $this->pollWithPrivateSlides(); + + $html = $this->exportHtml($token); + + $this->assertStringContainsString('Pizza oder Pasta?', $html); + $this->assertStringContainsString('Mehr <Pausen>', $html); + $this->assertStringContainsString('Fassung ohne interne Inhalte', $html); + // Private slides are listed with their number of participants only. + $this->assertStringContainsString('Was läuft schief?', $html); + $this->assertStringContainsString('Wie zufrieden bist du?', $html); + $this->assertStringContainsString('2 Personen haben teilgenommen', $html); + $this->assertStringNotContainsString('Geheime Kritik', $html); + $this->assertStringNotContainsString('Interner Kommentar', $html); + $this->assertStringNotContainsString('Bewertung 2', $html); + $this->assertStringNotContainsString('3,5', $html); + $this->assertStringNotContainsString('Vertraulich', $html); + } + + public function testCompleteVersionContainsInternalContent(): void + { + [, $token] = $this->pollWithPrivateSlides(); + + $html = $this->exportHtml($token, true); + + $this->assertHeaderContains('Content-Disposition', '-intern.pdf'); + $this->assertStringContainsString('Vertraulich', $html); + $this->assertStringContainsString('Geheime Kritik', $html); + $this->assertStringContainsString('Interner Kommentar', $html); + $this->assertStringContainsString('Bewertung 2', $html); + $this->assertStringContainsString('3,5', $html, 'average of 2 and 5'); + $this->assertStringContainsString('Mehr <Pausen>', $html); + } + + public function testInternalFlagWithoutPrivateSlidesIsIgnored(): void + { + [$poll, $token] = $this->createPoll(); + $this->createSlide($poll, Slide::TYPE_CHOICE); + + $html = $this->exportHtml($token, true); + + $this->assertHeaderContains('Content-Disposition', 'plenario-' . $poll->join_code . '-' . date('Ymd') . '.pdf'); + $this->assertStringNotContainsString('Vertraulich', $html); + $this->assertStringNotContainsString('Fassung', $html); + } + + public function testUnfinishedQuizRevealsNothing(): void + { + [$poll, $token] = $this->createPoll(); + $quiz = $this->createSlide($poll, Slide::TYPE_QUIZ, ['question' => 'Hauptstadt?', 'is_voting_open' => false], ['Berlin', 'Bonn']); + $poll = $this->goLive($poll, $quiz); + $this->post("/admin/$token/control", ['action' => 'open']); + $quiz = $this->slidesTable()->get($quiz->id, contain: ['SlideOptions']); + $this->assertSame(Slide::QUIZ_RUNNING, $quiz->quizPhase()); + (new VoteService())->submit($poll, $quiz, $this->hash('a', $poll), ['option_id' => $quiz->slide_options[0]->id]); + + $html = $this->exportHtml($token, true); + + $this->assertStringContainsString('Hauptstadt?', $html); + $this->assertStringContainsString('nicht beendet', $html); + $this->assertStringNotContainsString('✓', $html); + $this->assertStringNotContainsString('richtig beantwortet', $html); + + // Once finished, the solution and counts are part of the report. + $this->post("/admin/$token/control", ['action' => 'close']); + $html = $this->exportHtml($token); + $this->assertStringContainsString('✓ Berlin', $html); + $this->assertStringContainsString('1 von 1', $html); + } + + public function testDashboardOffersVersionsOnlyWithPrivateSlides(): void + { + [$poll, $token] = $this->createPoll(); + $this->createSlide($poll, Slide::TYPE_CHOICE); + + $this->get("/admin/$token"); + $this->assertResponseContains('PDF herunterladen'); + $this->assertResponseContains("/admin/$token/export.pdf"); + $this->assertResponseNotContains('name="internal"'); + $this->assertResponseNotContains('CSV'); + + $this->createSlide($poll, Slide::TYPE_OPEN, ['settings' => ['private' => true]]); + $this->get("/admin/$token"); + $this->assertResponseContains('name="internal" value="1"'); + $this->assertResponseContains('Ohne interne Inhalte'); + } +} diff --git a/tests/TestCase/Controller/QaSlideTest.php b/tests/TestCase/Controller/QaSlideTest.php index 5fcd6b6..f2956a1 100644 --- a/tests/TestCase/Controller/QaSlideTest.php +++ b/tests/TestCase/Controller/QaSlideTest.php @@ -134,10 +134,8 @@ class QaSlideTest extends TestCase $state = $this->control($token, ['action' => 'next']); $this->assertSame($next->id, $state['slide']['id']); - $this->get("/admin/$token/export.csv"); - $this->assertResponseOk(); - $this->assertResponseContains('Upvote: Andere Frage'); - $this->assertResponseContains('Meine Frage'); + $html = $this->exportHtml($token); + $this->assertMatchesRegularExpression('/Andere Frage.*Meine Frage/s', $html, 'ranked by upvotes'); } public function testResetStartsOver(): void diff --git a/tests/TestCase/Controller/ScaleCommentsTest.php b/tests/TestCase/Controller/ScaleCommentsTest.php index a56daeb..ad97c8e 100644 --- a/tests/TestCase/Controller/ScaleCommentsTest.php +++ b/tests/TestCase/Controller/ScaleCommentsTest.php @@ -216,9 +216,9 @@ class ScaleCommentsTest extends TestCase { [, $token] = $this->scaleWithComments(); - $this->get("/admin/$token/export.csv"); + $html = $this->exportHtml($token); - $this->assertResponseContains('4 (Kommentar: Sehr )'); - $this->assertResponseContains(';2;'); + $this->assertStringContainsString('2 Kommentare', $html); + $this->assertStringContainsString('Sehr <gut>', $html); } } diff --git a/tests/TestCase/PlenarioTestTrait.php b/tests/TestCase/PlenarioTestTrait.php index 3ef30f0..7f5be02 100644 --- a/tests/TestCase/PlenarioTestTrait.php +++ b/tests/TestCase/PlenarioTestTrait.php @@ -7,6 +7,7 @@ use App\Model\Entity\Poll; use App\Model\Entity\Slide; use App\Model\Table\PollsTable; use App\Model\Table\SlidesTable; +use App\View\PdfView; use Cake\ORM\TableRegistry; /** @@ -85,4 +86,26 @@ trait PlenarioTestTrait return $table; } + + /** + * Requests the PDF export (needs IntegrationTestTrait) and returns the HTML it was rendered from, + * since the PDF itself is compressed and not searchable. + * + * @param string $token Admin token + * @param bool $internal Complete version incl. internal content + * @return string + */ + protected function exportHtml(string $token, bool $internal = false): string + { + $this->get("/admin/$token/export.pdf" . ($internal ? '?internal=1' : '')); + $this->assertResponseOk(); + $this->assertContentType('application/pdf'); + $this->assertStringStartsWith('%PDF-', (string)$this->_response->getBody()); + + $view = new PdfView(); + $view->set($this->_controller->viewBuilder()->getVars()); + $view->setTemplatePath('Admin'); + + return $view->renderHtml('export'); + } } diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index bf7b20b..566bfa6 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -298,6 +298,15 @@ textarea { resize: vertical; } .order-option__pos { min-width: 2em; text-align: right; font-weight: 700; color: var(--muted); font-variant-numeric: tabular-nums; } .order-options.error .order-options__list input[type=text] { border-color: var(--danger); } +/* dashboard: PDF export, choice between public and complete version */ +.export-choice { border: 0; padding: 0; margin: 0 0 12px; display: grid; gap: 8px; } +.export-choice legend { font-weight: 600; margin-bottom: 4px; } +.export-choice label { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border: 2px solid var(--border); border-radius: 8px; cursor: pointer; } +.export-choice label:has(input:checked) { border-color: var(--primary); background: var(--primary-soft); } +.export-choice input { width: 18px; height: 18px; margin: 2px 0 0; flex: none; accent-color: var(--primary); } +.export-choice strong { display: block; } +.export-choice .hint { display: block; margin: 2px 0 0; } + /* shared by sortable form lists */ .is-sorting, .is-sorting * { cursor: grabbing !important; user-select: none; } .is-dragging { position: relative; z-index: 2; box-shadow: 0 10px 30px rgba(0, 0, 0, .18); }