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 $data Request data * @return void * @throws \App\Service\VoteException */ public function submit(Poll $poll, Slide $slide, string $participantHash, array $data): void { $this->assertOpen($poll, $slide); // 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); } }); } /** * Whether the participant may change the text of their answer afterwards (e.g. to fix a typo): * the answer of an open question and the comment of a choice or scale slide with comment field. * * @param \App\Model\Entity\Slide $slide Slide * @return bool */ public static function hasEditableText(Slide $slide): bool { return $slide->type === Slide::TYPE_OPEN || $slide->hasComments(); } /** * Replaces the text of the participant's own answer as long as voting on the slide is open * (see hasEditableText()). Open question: `text`, must not be empty. Choice/scale: `comment`, the * selection or rating itself stays unchanged and an empty comment removes it. Same preconditions as submit(). * * @param \App\Model\Entity\Poll $poll Poll * @param \App\Model\Entity\Slide $slide Slide * @param string $participantHash Participant hash * @param array $data Request data (`text` or `comment`) * @return void * @throws \App\Service\VoteException */ public function editText(Poll $poll, Slide $slide, string $participantHash, array $data): void { $this->assertOpen($poll, $slide); if (!self::hasEditableText($slide)) { throw new VoteException(__('Diese Antwort kann nicht mehr geändert werden.')); } $text = $slide->type === Slide::TYPE_OPEN ? $this->openRows($data)[0]['text_value'] : self::comment($data); $this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $text): void { $this->lockSlide($slide); // A multiple choice answer has several rows; the comment always lives in the first one. $row = $this->Responses->find() ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) ->orderBy(['id' => 'ASC']) ->first(); if ($row === null) { throw new VoteException(match ($slide->type) { Slide::TYPE_OPEN => __('Du hast hier noch nicht geantwortet.'), Slide::TYPE_CHOICE => __('Bitte gib zuerst deine Auswahl ab.'), default => __('Bitte gib zuerst deine Bewertung ab.'), }); } if ($slide->type === Slide::TYPE_SCALE && $row->numeric_value === null) { throw new VoteException(__('Zu „Keine Angabe“ gibt es keinen Kommentar.')); } $row->text_value = $text; $this->Responses->saveOrFail($row); }); } /** * Text of the participant's own answer: open answer or choice/scale comment (null: none or not answered yet). * * @param \App\Model\Entity\Slide $slide Slide * @param string $participantHash Participant hash * @return string|null */ public function ownText(Slide $slide, string $participantHash): ?string { $row = $this->Responses->find() ->select(['text_value']) ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) ->orderBy(['id' => 'ASC']) ->disableHydration() ->first(); return $row['text_value'] ?? null; } /** * Whether the participant answered a scale with "Keine Angabe" (a row without rating). * * @param \App\Model\Entity\Slide $slide Slide * @param string $participantHash Participant hash * @return bool */ public function hasSkipped(Slide $slide, string $participantHash): bool { return $slide->type === Slide::TYPE_SCALE && $this->Responses->exists([ 'slide_id' => $slide->id, 'participant_hash' => $participantHash, 'numeric_value IS' => null, ]); } /** * Poll active, slide live and interactive, voting open. * * @param \App\Model\Entity\Poll $poll Poll * @param \App\Model\Entity\Slide $slide Slide * @return void * @throws \App\Service\VoteException */ protected function assertOpen(Poll $poll, Slide $slide): 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->usesPhases() && $slide->voting_started_at === null => __('Die Abstimmung hat noch nicht begonnen.'), $slide->usesPhases() => __('Die Zeit für diese Frage ist abgelaufen.'), $slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'), default => __('Die Abstimmung zu dieser Frage ist geschlossen.'), }); } } /** * 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 $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 $data Request data * @return list> */ 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 = $slide->optionIds(); $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.')); } // The optional comment goes into the first row only, so it is stored once per participant; // counts group by option and ignore text_value. $comment = $slide->hasComments() ? self::comment($data) : null; return array_map( fn(int $id, int $index) => ['slide_option_id' => $id, 'text_value' => $index === 0 ? $comment : null], $selected, array_keys($selected), ); } /** * @param \App\Model\Entity\Slide $slide Slide * @param array $data Request data * @return list> */ 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 = $slide->optionIds(); 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 $data Request data * @return list> */ 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 = $slide->optionIds(); $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 */ 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 $data Request data * @return list> */ 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 === 'edit' || $vote === 'delete') { $this->editQuestion($slide, $own['questions'], $vote, $data); return []; } if ($vote === null) { if ($stage !== Slide::QA_COLLECT) { throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.')); } $text = $this->qaQuestionText($slide, $data); 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 (!$slide->hasQaUpvotes()) { throw new VoteException(__('Bei dieser Fragerunde wird nicht abgestimmt.')); } 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), // up to the limit per question. $max = $slide->qaBudget($this->Responses->questionsOf($slide->id)->count()); $perQuestion = $slide->qaUpvotesPerQuestion($max); if ($perQuestion < $max && count(array_keys($own['upvotes'], $id, true)) >= $perQuestion) { throw new VoteException(__n( 'Du kannst jeder Frage nur eine Stimme geben.', 'Du kannst jeder Frage höchstens {0} Stimmen geben.', $perQuestion, $perQuestion, )); } 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]]; } /** * Q&A: validated question text from `question` (whitespace collapsed), unique on the slide * (case-insensitive; `$except` = id of the question being edited). * * @param \App\Model\Entity\Slide $slide Slide * @param array $data Request data * @param int|null $except Question id to ignore in the duplicate check * @return string * @throws \App\Service\VoteException */ protected function qaQuestionText(Slide $slide, array $data, ?int $except = null): string { $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); $others = $this->Responses->questionsOf($slide->id)->select(['id', 'text_value'])->disableHydration(); foreach ($others as $row) { if ($row['id'] !== $except && mb_strtolower((string)$row['text_value']) === $key) { throw new VoteException(__('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.')); } } return $text; } /** * Q&A: changes (`edit`, new text in `question`) or deletes (`delete`) an own question, * only while collecting – later the question may already carry upvotes or be discussed. * Deleting also removes its upvotes (left over if the presenter stepped back from voting). * * @param \App\Model\Entity\Slide $slide Slide * @param list $ownQuestions Ids of the participant's questions * @param string $action `edit` or `delete` * @param array $data Request data (`question_id`, `question`) * @return void * @throws \App\Service\VoteException */ protected function editQuestion(Slide $slide, array $ownQuestions, string $action, array $data): void { if ($slide->qaStage() !== Slide::QA_COLLECT) { throw new VoteException(__('Fragen können nur geändert werden, solange sie gesammelt werden.')); } $id = is_scalar($data['question_id'] ?? null) ? filter_var($data['question_id'], FILTER_VALIDATE_INT) : false; if ($id === false || !in_array($id, $ownQuestions, true)) { throw new VoteException(__('Diese Frage gibt es nicht mehr oder sie stammt nicht von dir.')); } $question = $this->Responses->get($id); if ($action === 'delete') { $this->Responses->deleteAll(['slide_id' => $slide->id, 'parent_id' => $id]); $this->Responses->deleteOrFail($question); return; } $question->text_value = $this->qaQuestionText($slide, $data, $id); $this->Responses->saveOrFail($question); } /** * 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 $data Request data * @return list> */ 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); } if (($data['vote'] ?? null) === 'remove') { $this->removeWord($slide, $participantHash, self::stringField($data, 'word')); return []; } $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); } /** * Word cloud: withdraws the participant's own entry for a term – named/upvoted or downvoted – * e.g. to fix a typo by entering it again. Only the participant's own rows are touched; the term * stays in the cloud as long as others named it. * * @param \App\Model\Entity\Slide $slide Slide * @param string $participantHash Participant hash * @param string $word Word to withdraw * @return void * @throws \App\Service\VoteException */ protected function removeWord(Slide $slide, string $participantHash, string $word): void { $key = self::wordKey($word); $ids = []; $own = $this->Responses->find() ->select(['id', 'text_value']) ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash, 'text_value IS NOT' => null]) ->disableHydration(); foreach ($own as $row) { if (self::wordKey((string)$row['text_value']) === $key) { $ids[] = $row['id']; } } if ($key === '' || $ids === []) { throw new VoteException(__('Diesen Begriff hast du nicht genannt.')); } $this->Responses->deleteAll(['id IN' => $ids]); } /** * @param \App\Model\Entity\Slide $slide Slide * @param string $word Word to downvote * @param list $own Keys the participant named/upvoted * @param array $downvoted Keys the participant downvoted * @return list> */ 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 $data Request data * @return list> */ 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 $data Request data * @return list> */ protected function scaleRows(Slide $slide, array $data): array { if (self::stringField($data, 'skip') === '1') { if (!$slide->setting('allow_skip')) { throw new VoteException(__('„Keine Angabe“ ist bei dieser Frage nicht möglich.')); } // Counts as taking part, but has no rating and no comment. return [['numeric_value' => null, 'text_value' => null]]; } $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($slide->isStarRating() ? __('Bitte vergib zwischen {0} und {1} Sternen.', $min, $max) : __('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. return [['numeric_value' => $value, 'text_value' => $slide->hasComments() ? self::comment($data) : null]]; } /** * Optional scale comment from the request: trimmed, empty = null. * * @param array $data Request data * @return string|null * @throws \App\Service\VoteException */ protected static function comment(array $data): ?string { $comment = 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 $comment === '' ? null : $comment; } }