Slides (except YouTube) can carry one image. Uploads are validated, rotated by EXIF orientation, scaled to 1600 px and stored as WebP outside webroot, which also strips camera metadata. Images have an alt text (or are marked decorative) and a layout: top, side or full screen (content slides). Files are removed after the commit when a slide is deleted or its image is replaced, with the poll, and `bin/cake images_cleanup` sweeps leftovers. Duplicated slides get their own file. Docker image gains gd with WebP. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
431 lines
17 KiB
PHP
431 lines
17 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Service;
|
|
|
|
use App\Model\Entity\Poll;
|
|
use App\Model\Entity\Slide;
|
|
use App\Model\Table\PollsTable;
|
|
use App\Model\Table\ResponsesTable;
|
|
use App\Model\Table\SlidesTable;
|
|
use Cake\ORM\Locator\LocatorAwareTrait;
|
|
use Cake\Routing\Router;
|
|
|
|
/**
|
|
* Builds the JSON state polled by the presenter screen (/admin/{token}/state)
|
|
* and the participant page (/p/{code}/state).
|
|
*
|
|
* Results are shown on the presentation screen, not on participants' devices. The participant
|
|
* state only contains `results` where participants need them to interact: word clouds with
|
|
* upvotes show the live cloud while voting is open (participants upvote by clicking words).
|
|
*
|
|
* Quiz slides reveal the solution (and the participant's own correctness) once the quiz is
|
|
* finished, without counts or distribution. Timed quizzes are closed lazily here when their
|
|
* deadline has passed. Ordering slides work the same way: solution and the participant's
|
|
* correctness (`order`) once voting is closed, without counts.
|
|
*
|
|
* Q&A slides have their own participant view (`qa`, see qaState()), never `results`.
|
|
* Private slides (anonymous/internal feedback) never show results to participants,
|
|
* even though the presenter can show them on stage.
|
|
*/
|
|
class PollStateService
|
|
{
|
|
use LocatorAwareTrait;
|
|
|
|
protected SlidesTable $Slides;
|
|
|
|
protected ResponsesTable $Responses;
|
|
|
|
protected PollsTable $Polls;
|
|
|
|
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;
|
|
/** @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<string, mixed>
|
|
*/
|
|
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),
|
|
'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,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 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<string, mixed>
|
|
*/
|
|
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<string, mixed>
|
|
*/
|
|
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<string, mixed>
|
|
*/
|
|
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<int>|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<int>, upvoted: array<int, int>,
|
|
* questions: list<array{id: int, text: string, votes?: int}>, 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<string>, down: list<string>, own: list<array{text: string, down: bool}>, 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<string, mixed>
|
|
*/
|
|
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,
|
|
];
|
|
}
|
|
}
|