Add initial Plenario live polling app
CI / Deploy / test (push) Successful in 49s
CI / Deploy / deploy (push) Failing after 5s

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:
gnilebeinandClaude Opus 5.5 committed 2026-11-07 13:24:29 +01:00
commit eb319f8c1e
120 files changed
+15572

No files matched your search

+185
View File
@@ -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(),
];
}
}
+198
View File
@@ -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'),
];
}
}
+45
View File
@@ -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;
}
}
+13
View File
@@ -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
{
}
+280
View File
@@ -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]];
}
}