Files
Plenario/src/Controller/AdminController.php
T
gnilebeinandClaude Sonnet 5.5 8c7818ee40
CI / Deploy / PHP 8.4 (push) Successful in 1m12s
CI / Deploy / PHP 8.5 (push) Successful in 1m13s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped
Let the dashboard follow the presenter
The live marker in the slide list stayed on the last known slide when the
presenter moved on in another window or with a clicker. The dashboard now
polls a cheap version fingerprint (admin:live) and reloads the lists when it
changes, but never under an open dialog, a pending request or a drag.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 12:19:12 +01:00

352 lines
13 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\Controller;
use App\Mailer\PollMailer;
use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use App\Model\Table\SlidesTable;
use App\Service\PollStateService;
use App\Service\QaService;
use App\Service\ReportService;
use App\Service\ResetService;
use App\Service\SlideControlService;
use App\View\PdfView;
use Cake\Http\Exception\BadRequestException;
use Cake\Http\Response;
use Cake\I18n\DateTime;
use Cake\Routing\Router;
use chillerlan\QRCode\Output\QRMarkupSVG;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
/**
* Poll level admin actions: dashboard, settings, presenter mode, export.
*/
class AdminController extends AdminAppController
{
protected SlidesTable $Slides;
protected ResponsesTable $Responses;
/**
* @return void
*/
public function initialize(): void
{
parent::initialize();
/** @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;
}
/**
* Dashboard: settings + slide list.
*
* @return void
*/
public function index(): void
{
$slides = $this->Slides->listForPoll($this->poll->id);
$responseCounts = $this->Responses->countParticipantsPerSlide($this->poll->id);
$typeLabels = Slide::typeLabels();
$typeDescriptions = Slide::typeDescriptions();
$joinUrl = $this->joinUrl($this->poll);
// Created on first visit, so every slide has its embed URL ready to copy.
$embedKey = $this->Polls->ensureEmbedKey($this->poll);
$hasPrepared = $this->Responses->hasPrepared($this->poll->id);
$this->setPollInterval();
// Answers are not the only thing a reset undoes: a started quiz, closed slides or a running presentation too.
$canReset = $responseCounts !== []
|| $this->poll->isStarted()
|| array_filter($slides, fn(Slide $slide) => !$slide->isFresh()) !== [];
$this->set(compact('slides', 'responseCounts', 'canReset', 'hasPrepared', 'typeLabels', 'typeDescriptions', 'joinUrl', 'embedKey'));
}
/**
* @return \Cake\Http\Response|null
*/
public function settings(): ?Response
{
$this->request->allowMethod(['post']);
$this->Polls->patchEntity($this->poll, (array)$this->request->getData(), [
'fields' => ['title', 'is_active', 'comment_speed'],
]);
if ($this->Polls->save($this->poll)) {
$this->Flash->success(__('Einstellungen gespeichert.'));
} else {
$this->Flash->error(__('Die Einstellungen konnten nicht gespeichert werden.'));
}
return $this->redirect($this->adminUrl());
}
/**
* Invalidates the current admin link and mails a new one.
*
* @return \Cake\Http\Response|null
*/
public function rotateToken(): ?Response
{
$this->request->allowMethod(['post']);
$token = $this->Polls->assignNewToken($this->poll);
$this->Polls->saveOrFail($this->poll);
$this->token = $token;
$sent = (new PollMailer())->sendSafely('adminLink', [$this->poll, $this->adminUrlFor($token), $this->joinUrl($this->poll)]);
if ($sent) {
$this->Flash->success(__('Neuer Admin-Link erstellt und per E-Mail verschickt. Der alte Link ist ab sofort ungültig – speichere dir diese Seite als Lesezeichen.'));
} else {
$this->Flash->warning(__('Neuer Admin-Link erstellt, die E-Mail konnte aber nicht verschickt werden. Speichere dir diese Seite unbedingt als Lesezeichen!'));
}
return $this->redirect($this->adminUrl());
}
/**
* New embed key: all embed URLs (e.g. in Canva) stop working and must be inserted again.
*
* @return \Cake\Http\Response|null
*/
public function rotateEmbedKey(): ?Response
{
$this->request->allowMethod(['post']);
$this->Polls->rotateEmbedKey($this->poll);
$this->Flash->success(__('Neue Einbett-Links erstellt. Die bisherigen Links funktionieren nicht mehr – füge die neuen in deine Präsentation ein.'));
return $this->redirect($this->adminUrl() + ['#' => 'embed']);
}
/**
* Deletes all responses of all slides and puts the presentation back to "not started"; slides and settings
* are kept (e.g. to run the poll with another group). Prepared Q&A questions stay unless
* `keep_prepared` is sent as 0.
*
* @return \Cake\Http\Response|null
*/
public function reset(): ?Response
{
$this->request->allowMethod(['post']);
$keepPrepared = $this->request->getData('keep_prepared', '1') !== '0';
(new ResetService())->poll($this->poll, $keepPrepared);
$this->Flash->success(__('Alle Antworten wurden gelöscht.'));
return $this->redirect($this->adminUrl());
}
/**
* Deletes the whole poll incl. slides and responses.
*
* @return \Cake\Http\Response|null
*/
public function delete(): ?Response
{
$this->request->allowMethod(['post']);
$confirm = strtoupper(trim((string)$this->request->getData('confirm_code')));
if ($confirm !== $this->poll->join_code) {
$this->Flash->error(__('Zum Löschen bitte den Teilnahme-Code {0} eingeben.', $this->poll->join_code));
return $this->redirect($this->adminUrl());
}
$this->Polls->deleteOrFail($this->poll);
$this->Flash->success(__('Die Umfrage „{0}“ wurde gelöscht.', $this->poll->title));
return $this->redirect(['_name' => 'home']);
}
/**
* Full screen presenter mode.
*
* @return void
*/
public function present(): void
{
if ($this->poll->current_slide_id === null && !$this->poll->isPaused()) {
$first = $this->Slides->find()
->where(['poll_id' => $this->poll->id, 'is_hidden' => false])
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
->first();
if ($first !== null) {
$this->poll->showSlide($first->id);
$this->Polls->saveOrFail($this->poll);
}
}
$this->viewBuilder()->setLayout('present');
$this->set('joinUrl', $this->joinUrl($this->poll));
$this->set('joinBaseUrl', Router::url(['_name' => 'join:short'], true));
$this->setPollInterval();
}
/**
* JSON state for the presenter screen.
*
* @return \Cake\Http\Response
*/
public function state(): Response
{
return $this->json((new PollStateService())->forPresenter($this->poll));
}
/**
* Fingerprint of the dashboard content (JSON `{version}`), polled by the dashboard so the
* live marker follows the presenter. See PollStateService::dashboardVersion().
*
* @return \Cake\Http\Response
*/
public function live(): Response
{
return $this->json(['version' => (new PollStateService())->dashboardVersion($this->poll)]);
}
/**
* Presenter controls. Field `action`:
* goto (+ slide_id), next, prev, stop (pause), resume (continue after a pause), and the slide actions of
* SlideControlService (open, close, toggle, stage, question).
*
* On a Q&A slide that is being discussed, next/prev step through the questions
* first (like builds in presentation software); on a quiz, next starts it and then ends it
* before moving on, prev always goes to the previous slide. While paused, next/prev resume
* the slide that was live before.
*
* Answers with the new state as JSON for XHR requests, otherwise redirects back.
*
* @return \Cake\Http\Response|null
*/
public function control(): ?Response
{
$this->request->allowMethod(['post']);
$action = (string)$this->request->getData('action');
// Hidden slides are skipped and can not go live.
$slides = $this->Slides->listForPoll($this->poll->id, true);
$ids = array_map(fn(Slide $s) => $s->id, $slides);
$index = array_search($this->poll->current_slide_id, $ids, true);
$current = $index === false ? null : $slides[$index];
if (
$current !== null
&& $current->isQa()
&& in_array($action, ['next', 'prev'], true)
&& (new QaService())->moveFocus($current, $action === 'next' ? 1 : -1)
) {
$action = 'none';
}
// Forward on a quiz is a build step too: start it, then end it, only then the next slide.
// Back never touches the quiz, so a clicker can page through the slides afterwards.
if ($current !== null && $current->isQuiz() && $action === 'next') {
$phase = $current->quizPhase();
if ($phase !== Slide::QUIZ_FINISHED) {
(new SlideControlService())->apply($current, $phase === Slide::QUIZ_READY ? 'open' : 'close');
$action = 'none';
}
}
switch ($action) {
case 'none':
break;
case 'goto':
$target = (int)$this->request->getData('slide_id');
if (!in_array($target, $ids, true)) {
throw new BadRequestException('Unknown slide');
}
$this->poll->showSlide($target);
break;
case 'next':
case 'prev':
if ($ids === []) {
break;
}
if ($index === false && in_array($this->poll->paused_slide_id, $ids, true)) {
$this->poll->showSlide((int)$this->poll->paused_slide_id);
break;
}
$index = $index === false ? 0 : $index + ($action === 'next' ? 1 : -1);
$this->poll->showSlide($ids[max(0, min(count($ids) - 1, $index))]);
break;
case 'stop':
$this->poll->pause();
break;
case 'resume':
// Explicit (not a toggle), so a repeated click never pauses again.
if ($index === false && in_array($this->poll->paused_slide_id, $ids, true)) {
$this->poll->showSlide((int)$this->poll->paused_slide_id);
}
break;
default:
if (!in_array($action, SlideControlService::ACTIONS, true)) {
throw new BadRequestException('Unknown action');
}
if ($current === null) {
if (in_array($action, ['stage', 'question'], true)) {
throw new BadRequestException('Not a Q&A slide');
}
break;
}
(new SlideControlService())->apply($current, $action, (array)$this->request->getData());
}
$this->Polls->saveOrFail($this->poll);
if ($this->request->is('json') || $this->request->is('ajax')) {
return $this->json((new PollStateService())->forPresenter($this->poll));
}
return $this->redirect($this->referer($this->adminUrl(), true));
}
/**
* QR code (SVG) with the participant URL.
*
* @return \Cake\Http\Response
*/
public function qr(): Response
{
$url = $this->joinUrl($this->poll);
$options = new QROptions([
'outputInterface' => QRMarkupSVG::class,
'outputBase64' => false,
'svgAddXmlHeader' => true,
'addQuietzone' => true,
'quietzoneSize' => 2,
'drawLightModules' => false,
]);
$svg = (new QRCode($options))->render($url);
return $this->protect($this->response)
->withType('image/svg+xml')
->withHeader('Cache-Control', 'private, max-age=3600')
->withStringBody((string)$svg);
}
/**
* PDF report with the results of all interactive slides.
* Query `internal=1` includes anonymous/internal feedback (complete version for the owner),
* otherwise private slides only show their number of participants.
*
* @return \Cake\Http\Response
*/
public function export(): Response
{
$sections = (new ReportService())->build($this->poll, $this->request->getQuery('internal') === '1');
$hasInternal = ReportService::hasInternal($sections);
$includeInternal = $hasInternal && $this->request->getQuery('internal') === '1';
$this->viewBuilder()->setClassName(PdfView::class);
$this->set([
'sections' => $sections,
'includeInternal' => $includeInternal,
'hasInternal' => $hasInternal,
'exportedAt' => DateTime::now(),
]);
$filename = 'plenario-' . $this->poll->join_code . '-' . date('Ymd') . ($includeInternal ? '-intern' : '') . '.pdf';
return $this->render()->withDownload($filename);
}
}