From ad537b9b34e97f67311fd11227717fa9009a2202 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sun, 8 Nov 2026 22:50:56 +0100 Subject: [PATCH 1/2] Hash client IPs for rate limits with a keyed HMAC A plain sha256 of an IPv4 address can be reversed by trying all addresses. Co-Authored-By: Claude Opus 5.5 --- src/Service/ThrottleService.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Service/ThrottleService.php b/src/Service/ThrottleService.php index 0180cba..1924a42 100644 --- a/src/Service/ThrottleService.php +++ b/src/Service/ThrottleService.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Service; use Cake\Cache\Cache; +use Cake\Utility\Security; /** * Very small fixed-window rate limiter backed by the "throttle" cache config. @@ -29,7 +30,8 @@ class ThrottleService return true; } - $key = 'throttle_' . $bucket . '_' . hash('sha256', $identifier); + // Keyed hash: a plain sha256 of an IPv4 address can be reversed by trying all 2^32 addresses. + $key = 'throttle_' . $bucket . '_' . hash_hmac('sha256', $identifier, 'throttle|' . Security::getSalt()); $now = time(); /** @var array{start: int, hits: int}|null $state */ $state = Cache::read($key, 'throttle'); From 3e44ded107b05aefdc81f0c9b9b56f9ba8d1edb1 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sun, 8 Nov 2026 22:50:56 +0100 Subject: [PATCH 2/2] Share repeated controller and service code - AppController: joinUrl(), adminUrlFor(), setPollInterval() and protect() instead of copies in Admin-, Home-, Participate- and EmbedController. - PollMailer::sendSafely() replaces two try/catch blocks around mail sending. - Slide::optionIds() replaces five identical array_map() calls. - PollStateService: one pollPayload() for presenter and embed; the vote action passes the already loaded slide instead of loading it again. - ResultsService::forSlide() takes the answer/comment limit and the rating flag, so ReportService no longer queries answers, comments and the scale distribution twice and the export loads the slides only once. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- src/Controller/AdminAppController.php | 12 ----- src/Controller/AdminController.php | 26 ++++------ src/Controller/AppController.php | 49 ++++++++++++++++++ src/Controller/EmbedController.php | 14 +----- src/Controller/HomeController.php | 31 ++---------- src/Controller/ParticipateController.php | 7 ++- src/Mailer/PollMailer.php | 23 +++++++++ src/Model/Entity/Slide.php | 13 ++++- src/Service/PollStateService.php | 45 ++++++++++------- src/Service/ReportService.php | 50 ++++++------------- src/Service/ResultsService.php | 24 +++++---- src/Service/VoteService.php | 6 +-- .../TestCase/Controller/ScaleCommentsTest.php | 22 ++++++++ 14 files changed, 189 insertions(+), 137 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2cc8ff5..2f032e8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,8 @@ src/ Captcha/ CaptchaInterface + NoCaptcha / MathCaptcha / RecaptchaCaptcha, CaptchaFactory Error/RedactingErrorLogger maskiert Admin-Token und Embed-Key in allen Log-Einträgen (`Error.logger` in app.php) Controller/ + AppController Basis aller Controller: `joinUrl()`, `adminUrlFor()`, `setPollInterval()`, `throttle()`, `json()`, + `protect()` (no-referrer/noindex/no-store für Seiten mit Geheimnis in der URL: Admin, Embed) HomeController Startseite, Anlegen (/create), Bestätigung, Join, Recover AdminAppController Basis für /admin/{token}: löst Poll über Token-Hash auf (404 sonst), setzt Privacy-Header (no-referrer, no-store) AdminController Dashboard, Settings, Present, State-JSON, Control, QR, PDF-Export, Token rotieren, Zurücksetzen, Löschen @@ -61,7 +63,7 @@ src/ ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control ErrorController Fehlerseiten (Templates unter templates/Error, Layout `error`) - Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal) + Mailer/ PollMailer (adminLink, recovery; `sendSafely()` loggt Transportfehler statt zu werfen), Transport/FileTransport (lokal) Middleware/ HostHeaderMiddleware: prüft in Produktion den Host gegen APP_FULL_BASE_URL; SecurityHeadersMiddleware (äußerste Schicht): CSP mit Nonce, Framing, nosniff, Referrer-/Permissions-Policy für alle Antworten inkl. JSON und Fehlerseiten; vom Controller gesetzte Header gewinnen diff --git a/src/Controller/AdminAppController.php b/src/Controller/AdminAppController.php index c6bd691..008c20f 100644 --- a/src/Controller/AdminAppController.php +++ b/src/Controller/AdminAppController.php @@ -73,18 +73,6 @@ abstract class AdminAppController extends AppController $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 */ diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 1dbb057..dca3478 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -13,16 +13,13 @@ use App\Service\ReportService; use App\Service\ResetService; use App\Service\SlideControlService; 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; use chillerlan\QRCode\QRCode; use chillerlan\QRCode\QROptions; -use Throwable; /** * Poll level admin actions: dashboard, settings, presenter mode, export. @@ -58,7 +55,7 @@ class AdminController extends AdminAppController $responseCounts = $this->Responses->countParticipantsPerSlide($this->poll->id); $typeLabels = Slide::typeLabels(); $typeDescriptions = Slide::typeDescriptions(); - $joinUrl = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true); + $joinUrl = $this->joinUrl($this->poll); // Created on first visit, so every slide has its embed URL ready to copy. $embedKey = $this->Polls->ensureEmbedKey($this->poll); @@ -95,13 +92,10 @@ class AdminController extends AdminAppController $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]); + $sent = (new PollMailer())->sendSafely('adminLink', [$this->poll, $this->adminUrlFor($token), $this->joinUrl($this->poll)]); + if ($sent) { $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()); + } else { $this->Flash->warning(__('Neuer Admin-Link erstellt, die E-Mail konnte aber nicht verschickt werden. Speichere dir diese Seite unbedingt als Lesezeichen!')); } @@ -177,9 +171,9 @@ class AdminController extends AdminAppController } $this->viewBuilder()->setLayout('present'); - $this->set('joinUrl', Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true)); + $this->set('joinUrl', $this->joinUrl($this->poll)); $this->set('joinBaseUrl', Router::url(['_name' => 'join:short'], true)); - $this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000)); + $this->setPollInterval(); } /** @@ -275,7 +269,7 @@ class AdminController extends AdminAppController */ public function qr(): Response { - $url = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true); + $url = $this->joinUrl($this->poll); $options = new QROptions([ 'outputInterface' => QRMarkupSVG::class, 'outputBase64' => false, @@ -301,13 +295,13 @@ class AdminController extends AdminAppController */ public function export(): Response { - $report = new ReportService(); - $hasInternal = $report->hasInternalContent($this->poll); + $sections = (new ReportService())->build($this->poll, $this->request->getQuery('internal') === '1'); + $hasInternal = ReportService::hasInternal($sections); $includeInternal = $hasInternal && $this->request->getQuery('internal') === '1'; $this->viewBuilder()->setClassName(PdfView::class); $this->set([ - 'sections' => $report->build($this->poll, $includeInternal), + 'sections' => $sections, 'includeInternal' => $includeInternal, 'hasInternal' => $hasInternal, 'exportedAt' => DateTime::now(), diff --git a/src/Controller/AppController.php b/src/Controller/AppController.php index ef5d26c..78d2d18 100644 --- a/src/Controller/AppController.php +++ b/src/Controller/AppController.php @@ -3,10 +3,12 @@ declare(strict_types=1); namespace App\Controller; +use App\Model\Entity\Poll; use App\Service\ThrottleService; use Cake\Controller\Controller; use Cake\Core\Configure; use Cake\Http\Response; +use Cake\Routing\Router; /** * Base controller of PlenarIO. Security headers (CSP, framing, nosniff) are set for every @@ -24,6 +26,53 @@ class AppController extends Controller $this->loadComponent('Flash'); } + /** + * Pages whose URL contains a secret (admin token, embed key): never send it as referrer, + * never index them, never cache them. + * + * @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'); + } + + /** + * Absolute participant URL of a poll (QR code, mails, presenter). + * + * @param \App\Model\Entity\Poll $poll Poll + * @return string + */ + protected function joinUrl(Poll $poll): string + { + return Router::url(['_name' => 'participate', 'code' => $poll->join_code], true); + } + + /** + * Absolute admin URL for a plain token (only for mails and the confirmation page). + * + * @param string $token Plain admin token + * @return string + */ + protected function adminUrlFor(string $token): string + { + return Router::url(['_name' => 'admin', 'token' => $token], true); + } + + /** + * Passes the polling interval of live pages to the view (`pollIntervalMs`). + * + * @return void + */ + protected function setPollInterval(): void + { + $this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000)); + } + /** * Registers a hit of the client IP in a throttle bucket (see ThrottleService). * diff --git a/src/Controller/EmbedController.php b/src/Controller/EmbedController.php index c4f674e..20262ee 100644 --- a/src/Controller/EmbedController.php +++ b/src/Controller/EmbedController.php @@ -101,7 +101,7 @@ class EmbedController extends AppController $this->set('slide', $this->slide); $this->set('urls', $urls); $this->set('joinBaseUrl', Router::url(['_name' => 'join:short'], true)); - $this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000)); + $this->setPollInterval(); $this->set('heartbeatMs', max(1, (int)Configure::read('Plenario.embed.heartbeatSeconds', 5)) * 1000); } @@ -188,18 +188,6 @@ class EmbedController extends AppController return $this->protect($this->json((new PollStateService())->forEmbed($this->poll, $this->slide))); } - /** - * @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'); - } - /** * @param string $name Route name * @return array diff --git a/src/Controller/HomeController.php b/src/Controller/HomeController.php index 1a2a74a..2991f2b 100644 --- a/src/Controller/HomeController.php +++ b/src/Controller/HomeController.php @@ -9,9 +9,6 @@ use App\Model\Entity\Slide; use App\Model\Table\PollsTable; 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. @@ -82,9 +79,8 @@ class HomeController extends AppController } elseif (!$poll->hasErrors()) { [$poll, $token] = $this->Polls->insertPoll($poll); if ($token !== null) { - $adminUrl = Router::url(['_name' => 'admin', 'token' => $token], true); - $joinUrl = Router::url(['_name' => 'participate', 'code' => $poll->join_code], true); - $sent = $this->sendMail(fn(PollMailer $mailer) => $mailer->send('adminLink', [$poll, $adminUrl, $joinUrl])); + $adminUrl = $this->adminUrlFor($token); + $sent = (new PollMailer())->sendSafely('adminLink', [$poll, $adminUrl, $this->joinUrl($poll)]); $session = $this->request->getSession(); $session->write('Plenario.created', [ @@ -218,31 +214,12 @@ class HomeController extends AppController } $links[] = [ 'title' => $poll->title, - 'url' => Router::url(['_name' => 'admin', 'token' => $token], true), + 'url' => $this->adminUrlFor($token), 'created' => $poll->created->i18nFormat('dd.MM.yyyy HH:mm'), ]; } if ($links !== []) { - $this->sendMail(fn(PollMailer $mailer) => $mailer->send('recovery', [$email, $links])); - } - } - - /** - * 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; + (new PollMailer())->sendSafely('recovery', [$email, $links]); } } } diff --git a/src/Controller/ParticipateController.php b/src/Controller/ParticipateController.php index 6f7df87..2914fc1 100644 --- a/src/Controller/ParticipateController.php +++ b/src/Controller/ParticipateController.php @@ -8,7 +8,6 @@ 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; @@ -86,10 +85,10 @@ class ParticipateController extends AppController $stateService = new PollStateService(); $slide = $poll->is_active ? $stateService->currentSlide($poll) : null; $participantHash = $this->participantHash($poll); - $state = $stateService->forParticipant($poll, $participantHash); + $state = $stateService->forParticipant($poll, $participantHash, $slide); $this->set(compact('poll', 'slide', 'state', 'participantHash')); - $this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000)); + $this->setPollInterval(); } /** @@ -146,7 +145,7 @@ class ParticipateController extends AppController return $this->json([ 'ok' => $ok, 'message' => $message, - 'state' => $stateService->forParticipant($poll, $this->participantHash($poll)), + 'state' => $stateService->forParticipant($poll, $this->participantHash($poll), $slide), ], $status); } $ok ? $this->Flash->success($message) : $this->Flash->error($message); diff --git a/src/Mailer/PollMailer.php b/src/Mailer/PollMailer.php index e44d33f..a892706 100644 --- a/src/Mailer/PollMailer.php +++ b/src/Mailer/PollMailer.php @@ -4,13 +4,36 @@ declare(strict_types=1); namespace App\Mailer; use App\Model\Entity\Poll; +use Cake\Log\Log; use Cake\Mailer\Mailer; +use Throwable; /** * Mails sent by PlenarIO. Templates: templates/email/{html,text}/. */ class PollMailer extends Mailer { + /** + * Sends a mail like send(), but logs transport errors instead of throwing them, + * so the user gets a friendly hint and the action itself still succeeds. + * + * @param string $action Mailer action, e.g. "adminLink" + * @param array $args Arguments of the action + * @return bool Whether the mail was handed to the transport + */ + public function sendSafely(string $action, array $args): bool + { + try { + $this->send($action, $args); + + return true; + } catch (Throwable $e) { + Log::error(sprintf('Mail delivery failed (%s): %s', $action, $e->getMessage())); + + return false; + } + } + /** * Mail with the secret admin link after a poll was created. * diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index fae229f..57b8820 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -272,6 +272,17 @@ class Slide extends Entity return $this->isOrder() && !$this->isVotingOpen(); } + /** + * Ids of the answer options in their stored order (choice, quiz: display order; + * ordering slides: the correct order). + * + * @return list + */ + public function optionIds(): array + { + return array_map(fn($option) => (int)$option->id, array_values($this->slide_options ?? [])); + } + /** * Options of an ordering slide in a stable pseudo-random order (same seed = * same order, e.g. per participant across reloads). With two or more options @@ -283,7 +294,7 @@ class Slide extends Entity public function shuffledOptions(string $seed): array { $options = array_values($this->slide_options ?? []); - $correct = array_map(fn($option) => $option->id, $options); + $correct = $this->optionIds(); usort($options, fn($a, $b) => strcmp( hash('sha256', $seed . '|' . $a->id), hash('sha256', $seed . '|' . $b->id), diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index 3400372..aba4d18 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -94,13 +94,7 @@ class PollStateService } return [ - 'poll' => [ - 'title' => $poll->title, - 'joinCode' => $poll->join_code, - 'joinCodeFormatted' => $poll->formattedJoinCode(), - 'isActive' => $poll->is_active, - 'isPaused' => $poll->isPaused(), - ], + 'poll' => $this->pollPayload($poll), 'slides' => array_map(fn(Slide $s) => [ 'id' => $s->id, 'type' => $s->type, @@ -127,13 +121,7 @@ class PollStateService $slide = $this->Slides->closeIfExpired($slide); return [ - 'poll' => [ - 'title' => $poll->title, - 'joinCode' => $poll->join_code, - 'joinCodeFormatted' => $poll->formattedJoinCode(), - 'isActive' => $poll->is_active, - 'isPaused' => $poll->isPaused(), - ], + 'poll' => $this->pollPayload($poll), 'isLive' => $poll->current_slide_id === $slide->id, 'index' => null, 'count' => null, @@ -145,11 +133,17 @@ class PollStateService /** * @param \App\Model\Entity\Poll $poll Poll * @param string $participantHash Participant hash + * @param \App\Model\Entity\Slide|false|null $current Current slide if already loaded via currentSlide() + * in this request (null = none is live), false = load it * @return array */ - public function forParticipant(Poll $poll, string $participantHash): array + public function forParticipant(Poll $poll, string $participantHash, Slide|false|null $current = false): array { - $slide = $poll->is_active ? $this->currentSlide($poll) : null; + $slide = match (true) { + !$poll->is_active => null, + $current === false => $this->currentSlide($poll), + default => $current, + }; $words = $slide?->type === Slide::TYPE_WORDCLOUD ? $this->wordState($slide, $participantHash) : null; $quiz = $slide?->isQuiz() ? $this->quizState($slide, $participantHash) : null; $qa = $slide?->isQa() ? $this->qaState($slide, $participantHash) : null; @@ -233,7 +227,7 @@ class PollStateService ->first(); $answer = $response === null ? null : VoteService::parseOrder($response->text_value); } - $correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? [])); + $correct = $slide->optionIds(); return [ 'revealed' => $revealed, @@ -343,6 +337,23 @@ class PollStateService ]; } + /** + * Poll part of the presenter and embed state. + * + * @param \App\Model\Entity\Poll $poll Poll + * @return array{title: string, joinCode: string, joinCodeFormatted: string, isActive: bool, isPaused: bool} + */ + protected function pollPayload(Poll $poll): array + { + return [ + 'title' => $poll->title, + 'joinCode' => $poll->join_code, + 'joinCodeFormatted' => $poll->formattedJoinCode(), + 'isActive' => $poll->is_active, + 'isPaused' => $poll->isPaused(), + ]; + } + /** * @param \App\Model\Entity\Slide $slide Slide * @return array diff --git a/src/Service/ReportService.php b/src/Service/ReportService.php index 251e6eb..03c923b 100644 --- a/src/Service/ReportService.php +++ b/src/Service/ReportService.php @@ -43,13 +43,17 @@ class ReportService /** * @param \App\Model\Entity\Poll $poll Poll - * @param bool $includeInternal Include answers of private slides + * @param bool $includeInternal Include answers of private slides (ignored without private slides, + * so the public and the complete version are identical then) * @return list}> */ public function build(Poll $poll, bool $includeInternal): array { + $slides = $this->Slides->listForPoll($poll->id); + $includeInternal = $includeInternal + && array_filter($slides, fn(Slide $slide) => $slide->isInteractive() && $slide->isPrivate()) !== []; $sections = []; - foreach ($this->Slides->listForPoll($poll->id) as $index => $slide) { + foreach ($slides as $index => $slide) { if (!$slide->isInteractive()) { continue; } @@ -67,20 +71,15 @@ class ReportService } /** - * Whether the poll has slides whose answers are not public. + * Whether a report built by build() contains slides whose answers are not public + * (i.e. whether a complete, internal version exists at all). * - * @param \App\Model\Entity\Poll $poll Poll + * @param list $sections Result of build() * @return bool */ - public function hasInternalContent(Poll $poll): bool + public static function hasInternal(array $sections): bool { - foreach ($this->Slides->listForPoll($poll->id) as $slide) { - if ($slide->isInteractive() && $slide->isPrivate()) { - return true; - } - } - - return false; + return in_array(true, array_column($sections, 'internal'), true); } /** @@ -90,29 +89,12 @@ class ReportService */ protected function resultsFor(Slide $slide, bool $includeInternal): array { - $results = $this->results->forSlide($slide); - $mayRead = !$slide->isPrivate() || $includeInternal; - if (!$mayRead) { - return ResultsService::withoutContents($results); + if ($slide->isPrivate() && !$includeInternal) { + return ResultsService::withoutContents($this->results->forSlide($slide)); } - if ($slide->type === Slide::TYPE_OPEN) { - $results['answers'] = $this->results->answers($slide); - } - if ($slide->type === Slide::TYPE_SCALE) { - // 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; + // All answers and comments. Ratings next to comments: complete version always, + // public one only with the setting comment_ratings. + return $this->results->forSlide($slide, null, $includeInternal); } } diff --git a/src/Service/ResultsService.php b/src/Service/ResultsService.php index 7c0b014..28026a2 100644 --- a/src/Service/ResultsService.php +++ b/src/Service/ResultsService.php @@ -61,9 +61,12 @@ class ResultsService /** * @param \App\Model\Entity\Slide $slide Slide incl. slide_options + * @param int|null $limit Max. answers of open questions / comments of scales (newest), null = all + * @param bool $withRatings Ratings next to scale comments regardless of the setting comment_ratings + * (complete PDF export only) * @return array */ - public function forSlide(Slide $slide): array + public function forSlide(Slide $slide, ?int $limit = self::MAX_ANSWERS, bool $withRatings = false): array { $result = [ 'type' => $slide->type, @@ -73,8 +76,8 @@ class ResultsService 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), + Slide::TYPE_OPEN => $this->open($slide, $limit), + Slide::TYPE_SCALE => $this->scale($slide, $limit, $withRatings), Slide::TYPE_QUIZ => $this->quiz($slide), Slide::TYPE_QA => $this->qa($slide), Slide::TYPE_ORDER => $this->order($slide), @@ -98,7 +101,7 @@ class ResultsService ]; } - $correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? [])); + $correct = $slide->optionIds(); $placed = array_fill_keys($correct, 0); $correctCount = 0; $answers = $this->Responses->find() @@ -272,13 +275,14 @@ class ResultsService /** * @param \App\Model\Entity\Slide $slide Slide + * @param int|null $limit Max. answers, null = all * @return array */ - protected function open(Slide $slide): array + protected function open(Slide $slide, ?int $limit): array { return [ 'private' => $slide->isPrivate(), - 'answers' => $this->answers($slide, self::MAX_ANSWERS), + 'answers' => $this->answers($slide, $limit), ]; } @@ -309,13 +313,15 @@ class ResultsService /** * @param \App\Model\Entity\Slide $slide Slide + * @param int|null $limit Max. comments, null = all + * @param bool $withRatings Ratings regardless of the setting comment_ratings * @return array */ - protected function scale(Slide $slide): array + protected function scale(Slide $slide, ?int $limit, bool $withRatings): array { - $showRatings = (bool)$slide->setting('comment_ratings'); + $showRatings = $withRatings || (bool)$slide->setting('comment_ratings'); $comments = []; - foreach ($slide->hasComments() ? $this->comments($slide, self::MAX_ANSWERS) : [] as $comment) { + foreach ($slide->hasComments() ? $this->comments($slide, $limit) : [] as $comment) { $comments[] = [ 'id' => $comment['id'], 'text' => $comment['text'], diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index 77036c2..6b5836a 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -183,7 +183,7 @@ class VoteService { $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 ?? []); + $validIds = $slide->optionIds(); $selected = array_values(array_intersect($selected, $validIds)); if ($selected === []) { @@ -205,7 +205,7 @@ class VoteService { $selected = $data['option_id'] ?? null; $id = is_scalar($selected) ? filter_var($selected, FILTER_VALIDATE_INT) : false; - $validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []); + $validIds = $slide->optionIds(); if ($id === false || !in_array($id, $validIds, true)) { throw new VoteException(__('Bitte wähle eine Antwort aus.')); } @@ -229,7 +229,7 @@ class VoteService } $given[] = $id; } - $validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []); + $validIds = $slide->optionIds(); $sortedGiven = $given; sort($sortedGiven); sort($validIds); diff --git a/tests/TestCase/Controller/ScaleCommentsTest.php b/tests/TestCase/Controller/ScaleCommentsTest.php index 3ec5421..94ad3c9 100644 --- a/tests/TestCase/Controller/ScaleCommentsTest.php +++ b/tests/TestCase/Controller/ScaleCommentsTest.php @@ -243,5 +243,27 @@ class ScaleCommentsTest extends TestCase $this->assertStringContainsString('2 Kommentare', $html); $this->assertStringContainsString('Sehr <gut>', $html); + $this->assertStringNotContainsString('Bewertung 4', $html, 'ratings only with comment_ratings'); + } + + public function testInternalFlagDoesNotRevealRatingsWithoutPrivateSlides(): void + { + [, $token] = $this->scaleWithComments(); + + $html = $this->exportHtml($token, true); + + $this->assertStringContainsString('Sehr <gut>', $html); + $this->assertStringNotContainsString('Bewertung 4', $html); + $this->assertStringNotContainsString('-intern', (string)$this->_response->getHeaderLine('Content-Disposition')); + } + + public function testCompleteExportShowsRatingsOfAllScales(): void + { + [$poll, $token] = $this->scaleWithComments(); + $this->createSlide($poll, Slide::TYPE_OPEN, ['settings' => ['private' => true]]); + + $html = $this->exportHtml($token, true); + + $this->assertStringContainsString('Bewertung 4', $html); } }