Quiz slides have predefined answers with one or more marked as correct. The presenter starts the quiz, which then runs until its optional time limit expires or the presenter ends it. Counts and correct answers are only revealed once the quiz is finished; participants then see whether their answer was right. - migration: slide_options.is_correct, slides.voting_started_at/voting_ends_at - Slide::isVotingOpen() includes the quiz deadline, expired quizzes are closed lazily when the state is read - presenter countdown, quiz tiles and reveal with correct-answer summary - CSV export marks quiz answers as right/wrong Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
291 lines
11 KiB
PHP
291 lines
11 KiB
PHP
<?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,
|
||
* 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).
|
||
* - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen()
|
||
* includes the deadline of a timed quiz).
|
||
*/
|
||
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->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.'),
|
||
default => __('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),
|
||
Slide::TYPE_QUIZ => $this->quizRows($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);
|
||
}
|
||
|
||
/**
|
||
* @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]];
|
||
}
|
||
|
||
/**
|
||
* 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, (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;
|
||
}
|
||
|
||
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]];
|
||
}
|
||
}
|