Files
Plenario/src/Service/VoteService.php
T
gnilebeinandClaude Opus 5.5 9c532d164f
CI / Deploy / test (push) Successful in 51s
CI / Deploy / deploy (push) Skipped
Store answers atomically and limit word cloud input
- Run the checks and the insert of VoteService::submit() in one transaction
  with the slide row locked, so double clicks or retries cannot store a vote
  twice (also covers the Q&A upvote budget and word cloud duplicates).
- Limit word cloud terms per request and per participant, and throttle
  answers per IP and minute (THROTTLE_VOTES_PER_MINUTE, 429 with message).
- Treat array values in text fields as empty instead of storing "Array".
- Move the throttle helper to AppController for reuse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:01:19 +01:00

494 lines
20 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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\Database\Expression\IdentifierExpression;
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,
* any number of words). 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).
* At most MAX_WORDS_PER_REQUEST terms per request and MAX_WORDS per participant and slide.
* - checks and insert run in one transaction with the slide row locked (see lockSlide()),
* so concurrent or repeated requests cannot store an answer twice.
* - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen()
* includes the deadline of a timed quiz).
* - Q&A (see QaService for the stages): `question` (text) only while collecting,
* at most MAX_QA_QUESTIONS per participant, the same question (case-insensitive)
* only once per slide. `vote=up|remove` + `question_id` only while voting: upvote
* questions of others (own ones too with setting `allow_self_upvote`), at most
* `max_upvotes` in total, freely distributed (several on one question are allowed);
* `remove` withdraws one own upvote of the question.
* - ordering: `order` = all option ids, each exactly once, in the participant's order.
* Stored as one row with the ids comma separated in `text_value` (see parseOrder()).
*/
class VoteService
{
use LocatorAwareTrait;
public const MAX_WORD_LENGTH = 40;
public const MAX_TEXT_LENGTH = 500;
public const MAX_QA_QUESTIONS = 10;
/**
* Word cloud: terms per request and terms a participant may name or upvote per slide.
*/
public const MAX_WORDS_PER_REQUEST = 10;
public const MAX_WORDS = 50;
/**
* `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->isVotingOpen()) {
throw new VoteException(match (true) {
$slide->isQuiz() && $slide->voting_started_at === null => __('Das Quiz hat noch nicht begonnen.'),
$slide->isQuiz() => __('Die Zeit für dieses Quiz ist abgelaufen.'),
$slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'),
default => __('Die Abstimmung zu dieser Frage ist geschlossen.'),
});
}
// Checks (answered already, upvote budget, duplicates) and the insert run as one unit,
// so a double click or a retried request cannot store an answer twice.
$this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $data): void {
$this->lockSlide($slide);
if (!$slide->allowsMultipleResponses() && $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),
Slide::TYPE_QUIZ => $this->quizRows($slide, $data),
Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data),
Slide::TYPE_ORDER => $this->orderRows($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,
]);
}
if ($entities !== []) {
$this->Responses->saveManyOrFail($entities);
}
});
}
/**
* Serialises answers to one slide for the rest of the transaction.
*
* A no-op write on the slide row (`position = position`) is the portable lock: MySQL/MariaDB
* and PostgreSQL lock the row until commit, SQLite takes its write lock before anything is
* read. Must be the first statement of the transaction, so later reads see committed answers
* of concurrent requests. Neither `modified` nor any value changes.
*
* @param \App\Model\Entity\Slide $slide Slide
* @return void
*/
protected function lockSlide(Slide $slide): void
{
$this->fetchTable('Slides')->updateQuery()
->set(['position' => new IdentifierExpression('position')])
->where(['id' => $slide->id])
->execute()
->closeCursor();
}
/**
* A request field as string; arrays and other non-scalar values count as empty
* (instead of being stored as "Array").
*
* @param array<string, mixed> $data Request data
* @param string $key Field
* @return string
*/
protected static function stringField(array $data, string $key): string
{
$value = $data[$key] ?? '';
return is_scalar($value) ? (string)$value : '';
}
/**
* @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);
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function quizRows(Slide $slide, array $data): array
{
$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 ?? []);
if ($id === false || !in_array($id, $validIds, true)) {
throw new VoteException(__('Bitte wähle eine Antwort aus.'));
}
return [['slide_option_id' => $id]];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function orderRows(Slide $slide, array $data): array
{
$given = [];
foreach ((array)($data['order'] ?? []) as $id) {
$id = is_scalar($id) ? filter_var($id, FILTER_VALIDATE_INT) : false;
if ($id === false) {
$given = [];
break;
}
$given[] = $id;
}
$validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []);
$sortedGiven = $given;
sort($sortedGiven);
sort($validIds);
if ($validIds === [] || $sortedGiven !== $validIds) {
throw new VoteException(__('Bitte bring alle Einträge in eine Reihenfolge und sende sie erneut.'));
}
return [['text_value' => implode(',', $given)]];
}
/**
* Option ids of a stored ordering answer (`responses.text_value`), in the participant's order.
*
* @param string|null $text Stored answer
* @return list<int>
*/
public static function parseOrder(?string $text): array
{
$ids = [];
foreach (explode(',', (string)$text) as $id) {
if (ctype_digit(trim($id))) {
$ids[] = (int)$id;
}
}
return $ids;
}
/**
* Q&A: a new question while collecting, an upvote (or its withdrawal) while voting.
* Withdrawing deletes one upvote row and returns no new rows.
*
* @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 qaRows(Slide $slide, string $participantHash, array $data): array
{
$stage = $slide->qaStage();
$vote = $data['vote'] ?? null;
$own = $this->Responses->qaVotesOf($slide->id, $participantHash);
if ($vote === null) {
if ($stage !== Slide::QA_COLLECT) {
throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.'));
}
$text = trim((string)preg_replace('/\s+/u', ' ', self::stringField($data, 'question')));
if ($text === '') {
throw new VoteException(__('Bitte gib eine Frage ein.'));
}
if (mb_strlen($text) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Die Frage darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
}
$key = mb_strtolower($text);
foreach ($this->Responses->questionsOf($slide->id)->select(['text_value'])->disableHydration() as $row) {
if (mb_strtolower((string)$row['text_value']) === $key) {
throw new VoteException(__('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.'));
}
}
if (count($own['questions']) >= self::MAX_QA_QUESTIONS) {
throw new VoteException(__('Du kannst höchstens {0} Fragen stellen.', self::MAX_QA_QUESTIONS));
}
return [['text_value' => $text]];
}
if ($stage !== Slide::QA_VOTE) {
throw new VoteException(__('Die Abstimmung über die Fragen hat noch nicht begonnen.'));
}
$id = is_scalar($data['question_id'] ?? null) ? filter_var($data['question_id'], FILTER_VALIDATE_INT) : false;
if ($id === false || !$this->Responses->questionsOf($slide->id)->where(['Responses.id' => $id])->count()) {
throw new VoteException(__('Diese Frage gibt es nicht.'));
}
if ($vote === 'remove') {
// Withdraws one of possibly several own upvotes on the question.
$upvote = $this->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash, 'parent_id' => $id])
->orderBy(['id' => 'DESC'])
->first();
if ($upvote === null) {
throw new VoteException(__('Du hast diese Frage nicht unterstützt.'));
}
$this->Responses->deleteOrFail($upvote);
return [];
}
if ($vote !== 'up') {
throw new VoteException(__('Ungültige Stimme.'));
}
if (!$slide->setting('allow_self_upvote') && in_array($id, $own['questions'], true)) {
throw new VoteException(__('Deine eigene Frage kannst du nicht unterstützen.'));
}
// Several upvotes on the same question are allowed (push important questions).
$max = (int)$slide->setting('max_upvotes');
if (count($own['upvotes']) >= $max) {
throw new VoteException(__n(
'Du hast deine Stimme schon vergeben. Nimm sie zurück, um eine andere Frage zu unterstützen.',
'Du hast alle {0} Stimmen vergeben. Nimm eine zurück, um eine andere Frage zu unterstützen.',
$max,
$max,
));
}
return [['parent_id' => $id]];
}
/**
* 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.
*
* @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, self::stringField($data, 'word'), $existing, $downvoted);
}
$input = array_filter(
array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? [])),
fn($word) => is_scalar($word) && trim((string)$word) !== '',
);
if (count($input) > self::MAX_WORDS_PER_REQUEST) {
throw new VoteException(__('Bitte gib höchstens {0} Begriffe auf einmal ein.', self::MAX_WORDS_PER_REQUEST));
}
$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;
}
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.'),
});
}
if (count($existing) + count($words) > self::MAX_WORDS) {
throw new VoteException(__('Du kannst bei dieser Frage höchstens {0} Begriffe nennen oder unterstützen.', self::MAX_WORDS));
}
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(self::stringField($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));
}
// The optional comment is stored in the same row; ignored if the slide has no comment field.
$comment = $slide->hasComments() ? trim(self::stringField($data, 'comment')) : '';
if (mb_strlen($comment) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Der Kommentar darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
}
return [['numeric_value' => $value, 'text_value' => $comment === '' ? null : $comment]];
}
}