fetchTable('Slides'); $this->Slides = $slides; /** @var \App\Model\Table\ResponsesTable $responses */ $responses = $this->fetchTable('Responses'); $this->Responses = $responses; /** @var \App\Model\Table\PollsTable $polls */ $polls = $this->fetchTable('Polls'); $this->Polls = $polls; $this->results = new ResultsService(); } /** * Cheap fingerprint of everything the admin dashboard shows (live/paused slide, slide settings * and status, answer counts). The dashboard polls it and reloads its lists when it changes. * * @param \App\Model\Entity\Poll $poll Poll * @return string */ public function dashboardVersion(Poll $poll): string { $slides = $this->Slides->find() ->select([ 'n' => $this->Slides->find()->func()->count('*'), 'latest' => $this->Slides->find()->func()->max('modified'), ]) ->where(['poll_id' => $poll->id]) ->disableHydration() ->first(); return md5(json_encode([ (int)$poll->is_active, $poll->current_slide_id, $poll->paused_slide_id, $slides, $this->Responses->countParticipantsPerSlide($poll->id), ], JSON_THROW_ON_ERROR)); } /** * @param \App\Model\Entity\Poll $poll Poll * @return \App\Model\Entity\Slide|null */ public function currentSlide(Poll $poll): ?Slide { $this->Polls->pauseIfEmbedStale($poll); 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 ? $this->Slides->closeIfExpired($slide) : null; } /** * @param \App\Model\Entity\Poll $poll Poll * @return array */ public function forPresenter(Poll $poll): array { $this->Polls->pauseIfEmbedStale($poll); // The presentation consists of the visible slides only. $slides = $this->Slides->listForPoll($poll->id, true); $current = null; $index = null; foreach ($slides as $i => $slide) { if ($slide->id === $poll->current_slide_id) { $current = $this->Slides->closeIfExpired($slide); $index = $i; } } return [ 'poll' => $this->pollPayload($poll), 'slides' => array_map(fn(Slide $s) => [ 'id' => $s->id, 'type' => $s->type, 'question' => $s->question, ], $slides), 'index' => $index, 'count' => count($slides), 'next' => $this->nextPreview($poll, $slides, $index), 'hiddenCount' => $this->Slides->find()->where(['poll_id' => $poll->id, 'is_hidden' => true])->count(), 'slide' => $current ? $this->slidePayload($current, $poll) : null, 'results' => $current ? $this->results->forSlide($current) : null, ]; } /** * Preview of the slide that comes next for the speaker view: the one behind the live slide, the * paused one while paused (that is where "continue" goes), the first one before the start. * Labels only: never `is_correct` and never the options of an order slide (they are stored in the * correct order), so nothing leaks that is not allowed in the JSON before the slide is resolved. * * @param \App\Model\Entity\Poll $poll Poll * @param list<\App\Model\Entity\Slide> $slides Visible slides in presentation order * @param int|null $index Index of the live slide in `$slides` * @return array|null Null after the last slide */ private function nextPreview(Poll $poll, array $slides, ?int $index): ?array { if ($index !== null) { $next = $slides[$index + 1] ?? null; } else { $next = $slides[0] ?? null; foreach ($slides as $slide) { if ($poll->paused_slide_id !== null && $slide->id === $poll->paused_slide_id) { $next = $slide; } } } if ($next === null) { return null; } return [ 'id' => $next->id, 'type' => $next->type, 'typeLabel' => $next->typeLabel(), 'question' => $next->question, 'description' => (string)$next->description, 'options' => $next->isOrder() ? [] : array_map(fn($o) => $o->label, $next->slide_options ?? []), 'hasImage' => $next->hasImage(), ]; } /** * State of one embedded slide (/e/{key}/{slide}/state). Same shape as forPresenter(), * but always for this slide, live or not, plus `isLive`. Never contains the slide list. * * @param \App\Model\Entity\Poll $poll Poll * @param \App\Model\Entity\Slide $slide Slide of this poll incl. slide_options * @return array */ public function forEmbed(Poll $poll, Slide $slide): array { $this->Polls->pauseIfEmbedStale($poll); $slide = $this->Slides->closeIfExpired($slide); return [ 'poll' => $this->pollPayload($poll), 'isLive' => $poll->current_slide_id === $slide->id, 'isHidden' => $slide->is_hidden, 'index' => null, 'count' => null, 'slide' => $this->slidePayload($slide, $poll), 'results' => $this->results->forSlide($slide), ]; } /** * @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, Slide|false|null $current = false): array { $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; $order = $slide?->isOrder() ? $this->orderState($slide, $participantHash) : null; $hasResponded = match (true) { $words !== null => $words['mine'] !== [] || $words['down'] !== [], $qa !== null => $qa['mine'] !== [] || $qa['upvoted'] !== [], default => $slide && $slide->isInteractive() && $this->Responses->hasResponded($slide->id, $participantHash), }; $isVotingOpen = $slide?->isVotingOpen() ?? false; // Results reach the device only where participants act on them (upvoting words) // or to resolve their own quiz/ordering answer. $showResults = $slide !== null && !$slide->isPrivate() && (($quiz['phase'] ?? null) === Slide::QUIZ_FINISHED || ($order['revealed'] ?? false) || ($words !== null && $words['allowUpvotes'] && $isVotingOpen)); return [ 'isActive' => $poll->is_active, 'isPaused' => $slide === null && $poll->isPaused(), 'slideId' => $slide?->id, 'isVotingOpen' => $isVotingOpen, 'hasResponded' => $hasResponded, // Changes whenever the participant page must re-render. 'version' => implode(':', [ (int)$poll->is_active, $slide?->id ?? 0, (int)$isVotingOpen, // Word clouds and Q&A are answered item by item without reload. $words !== null || $qa !== null ? 0 : (int)$hasResponded, $slide?->modified?->toUnixString() ?? 0, ]), 'slide' => $showResults ? $this->slidePayload($slide, $poll) : null, 'results' => $showResults ? $this->participantResults($slide) : null, 'words' => $words, 'quiz' => $quiz, 'qa' => $qa, 'order' => $order, ]; } /** * Results as participants see them: a resolved quiz/ordering slide only with the * solution (no counts, no distribution - those are for the stage), a word cloud as is. * * @param \App\Model\Entity\Slide $slide Current slide * @return array */ protected function participantResults(Slide $slide): array { $results = $this->results->forSlide($slide); unset($results['correctCount']); foreach (['options', 'items'] as $list) { foreach ($results[$list] ?? [] as $i => $entry) { unset($entry['count'], $entry['percent'], $entry['placed']); $results[$list][$i] = $entry; } } return $results; } /** * Ordering progress of one participant. Own answer and correctness only once * revealed (voting closed); before that the state must not hint at the solution. * * @param \App\Model\Entity\Slide $slide Ordering slide incl. slide_options * @param string $participantHash Participant hash * @return array{revealed: bool, answer: list|null, isCorrect: bool|null} */ public function orderState(Slide $slide, string $participantHash): array { $revealed = $slide->isOrderRevealed(); $answer = null; if ($revealed) { $response = $this->Responses->find() ->select(['text_value']) ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) ->first(); $answer = $response === null ? null : VoteService::parseOrder($response->text_value); } $correct = $slide->optionIds(); return [ 'revealed' => $revealed, 'answer' => $answer, 'isCorrect' => $answer === null ? null : $answer === $correct, ]; } /** * Quiz progress of one participant. The own answer and its correctness are * only included once the quiz is finished. * * @param \App\Model\Entity\Slide $slide Quiz slide incl. slide_options * @param string $participantHash Participant hash * @return array{phase: string, remaining: int|null, answerId: int|null, isCorrect: bool|null} */ public function quizState(Slide $slide, string $participantHash): array { $phase = $slide->quizPhase(); $answerId = null; $isCorrect = null; if ($phase === Slide::QUIZ_FINISHED) { $response = $this->Responses->find() ->select(['slide_option_id']) ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) ->first(); $answerId = $response?->slide_option_id; if ($answerId !== null) { $isCorrect = false; foreach ($slide->slide_options ?? [] as $option) { if ($option->id === $answerId) { $isCorrect = $option->is_correct; } } } } return [ 'phase' => $phase, 'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null, 'answerId' => $answerId, 'isCorrect' => $isCorrect, ]; } /** * Q&A view of one participant: * - collect: all questions so far in submission order (helps to avoid duplicates), `mine` marks own ones * - vote: all questions in submission order, without counts (no bandwagon effect) * - discuss: all questions ranked with upvotes, `focusId` = question being discussed * `upvoted` = own upvotes per question id (several per question are allowed), * `allowSelfUpvote` = own questions may be upvoted too (setting `allow_self_upvote`). * `maxUpvotes` = upvote budget of the participant (share of the questions), 0: no voting stage; `maxPerQuestion` = own upvotes allowed per question. * * @param \App\Model\Entity\Slide $slide Q&A slide * @param string $participantHash Participant hash * @return array{stage: string, maxUpvotes: int, maxPerQuestion: int, votesLeft: int, allowSelfUpvote: bool, mine: list, upvoted: array, * questions: list, focusId: int|null} */ public function qaState(Slide $slide, string $participantHash): array { $stage = $slide->qaStage(); $own = $this->Responses->qaVotesOf($slide->id, $participantHash); $questions = (new QaService())->rankedQuestions($slide); $max = $slide->qaBudget(count($questions)); if ($stage === Slide::QA_DISCUSS) { $focusId = in_array($slide->focus_response_id, array_column($questions, 'id'), true) ? $slide->focus_response_id : null; } else { $focusId = null; usort($questions, fn($a, $b) => $a['id'] <=> $b['id']); $questions = array_map(fn($q) => ['id' => $q['id'], 'text' => $q['text']], $questions); } return [ 'stage' => $stage, 'maxUpvotes' => $max, 'maxPerQuestion' => $slide->qaUpvotesPerQuestion($max), 'votesLeft' => max(0, $max - count($own['upvotes'])), 'allowSelfUpvote' => (bool)$slide->setting('allow_self_upvote'), 'mine' => $own['questions'], 'upvoted' => array_count_values($own['upvotes']), 'questions' => array_values($questions), 'focusId' => $focusId, ]; } /** * Word cloud progress of one participant. * * @param \App\Model\Entity\Slide $slide Word cloud slide * @param string $participantHash Participant hash * @return array{mine: list, down: list, own: list, allowUpvotes: bool, allowDownvotes: bool} * `mine` (named/upvoted) and `down` are lower case word keys, `own` the same entries as typed */ 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']))); $allowUpvotes = (bool)$slide->setting('allow_upvotes'); // Own entries as typed (first spelling per key), oldest first, so they can be withdrawn. $own = []; foreach (['up' => false, 'down' => true] as $kind => $isDown) { foreach ($votes[$kind] as $text) { $own[VoteService::wordKey($text)] ??= ['text' => $text, 'down' => $isDown]; } } return [ 'mine' => $mine, 'down' => $down, 'own' => array_values($own), 'allowUpvotes' => $allowUpvotes, 'allowDownvotes' => $allowUpvotes && (bool)$slide->setting('allow_downvotes'), ]; } /** * 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(), // Factor for the rotating scale comments on stage (1 = normal, 2 = twice as fast) 'commentSpeed' => ($poll->comment_speed ?? 100) / 100, ]; } /** * @param \App\Model\Entity\Slide $slide Slide * @param \App\Model\Entity\Poll $poll Poll of the slide (the image URL contains its join code) * @return array */ public function slidePayload(Slide $slide, Poll $poll): array { return [ 'id' => $slide->id, 'type' => $slide->type, 'question' => $slide->question, 'description' => (string)$slide->description, 'isVotingOpen' => $slide->isVotingOpen(), 'isInteractive' => $slide->isInteractive(), 'settings' => $slide->getSettings(), // YouTube slides: player URL for the presenter, link for sharing 'video' => $slide->isYouTube() && $slide->youtubeEmbedUrl() !== null ? [ 'embedUrl' => $slide->youtubeEmbedUrl(), 'watchUrl' => $slide->youtubeWatchUrl(), ] : null, // Image of the slide: URL (random file name), alternative text ('' = decorative), layout (top|side|full) 'image' => $slide->hasImage() ? [ 'url' => Router::url(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image]), 'alt' => (string)$slide->image_alt, 'layout' => $slide->imageLayout(), 'width' => $slide->image_width, 'height' => $slide->image_height, ] : null, ]; } }