Replace CSV export with PDF export
CI / Deploy / test (push) Successful in 53s
CI / Deploy / deploy (push) Skipped

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 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-08 19:21:10 +01:00
1 parent 5cd1be1cf8
commit d1facd32a6
21 files changed
+1102 -110

No files matched your search

+18 -86
View File
@@ -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<int, string> $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);
}
}
+1 -1
View File
@@ -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
*/
+116
View File
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Poll;
use App\Model\Entity\Slide;
use App\Model\Table\SlidesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
/**
* Collects the results of all interactive slides of a poll for the PDF export.
*
* Without $includeInternal the report shows exactly what may be shown publicly: private slides
* (anonymous feedback, internal scales) only with their number of participants, like the presenter
* screen. With $includeInternal it also contains their answers, distribution and comments –
* that version is meant for the poll owner only.
*
* Per slide: ['slide' => 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<array{slide: \App\Model\Entity\Slide, number: int, internal: bool, withheld: bool, results: array<string, mixed>}>
*/
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<string, mixed>
*/
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;
}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
declare(strict_types=1);
namespace App\View;
use Dompdf\Dompdf;
use Dompdf\Options;
/**
* Renders the template as HTML (layout "pdf") and converts it to a PDF with Dompdf.
*
* Remote resources are disabled: everything (styles, fonts) must be part of the HTML.
*/
class PdfView extends AppView
{
/**
* @var string
*/
protected string $layout = 'pdf';
/**
* @inheritDoc
*/
public static function contentType(): string
{
return 'application/pdf';
}
/**
* @return void
*/
public function initialize(): void
{
parent::initialize();
$this->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],
);
}
}