Files
Plenario/src/Controller/AdminController.php
T
gnilebeinandClaude Sonnet 5.5 d1d748f760
CI / Deploy / PHP 8.5 (push) Successful in 1m14s
CI / Deploy / PHP 8.4 (push) Successful in 1m19s
CI / Deploy / test (push) Successful in 2s
CI / Deploy / deploy (push) Skipped
Walk through Q&A stages with "next" before leaving the slide
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 13:47:27 +01:00

470 lines
18 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\AudioService;
use App\Service\ImageException;
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;
use Psr\Http\Message\UploadedFileInterface;
use Throwable;
/**
* 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());
}
/**
* Countdown music of the presentation: uploads a new file (replaces the old one) or, with
* `remove` = 1, deletes it. Old files are deleted after saving, never before.
*
* @return \Cake\Http\Response|null
*/
public function audio(): ?Response
{
$this->request->allowMethod(['post']);
$service = new AudioService();
$old = $this->poll->audio;
$upload = $this->request->getUploadedFile('audio');
$hasUpload = $upload instanceof UploadedFileInterface && $upload->getError() !== UPLOAD_ERR_NO_FILE;
$back = $this->adminUrl() + ['#' => 'audio'];
if ($hasUpload) {
try {
$new = $service->store($upload, $this->poll->id);
} catch (ImageException $e) {
$this->Flash->error($e->getMessage());
return $this->redirect($back);
}
} elseif (filter_var($this->request->getData('remove'), FILTER_VALIDATE_BOOLEAN)) {
$new = null;
} else {
$this->Flash->error(__('Bitte wähle eine Audiodatei aus.'));
return $this->redirect($back);
}
$this->poll->set('audio', $new);
try {
$this->Polls->saveOrFail($this->poll);
} catch (Throwable $e) {
$service->delete($this->poll->id, $new);
throw $e;
}
if ($old !== null && $old !== $new) {
$service->delete($this->poll->id, $old);
}
$this->Flash->success($new === null ? __('Audiodatei entfernt.') : __('Audiodatei gespeichert.'));
return $this->redirect($back);
}
/**
* 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());
}
/**
* Clones the whole presentation (slides, settings, images) without any responses into a new poll with
* its own admin link, which is mailed to the owner like after creating a poll.
*
* @return \Cake\Http\Response|null
*/
public function cloneAll(): ?Response
{
$this->request->allowMethod(['post']);
if (!$this->throttle('create', 'Plenario.throttle.createPerHour')) {
$this->Flash->error(__('Zu viele Umfragen in kurzer Zeit. Bitte versuche es später noch einmal.'));
return $this->redirect($this->adminUrl());
}
try {
[$copy, $token] = $this->Polls->clonePoll($this->poll, $this->Slides->listForPoll($this->poll->id));
} catch (Throwable) {
$token = null;
}
if ($token === null) {
$this->Flash->error(__('Die Umfrage konnte nicht kopiert werden.'));
return $this->redirect($this->adminUrl());
}
$adminUrl = $this->adminUrlFor($token);
$sent = (new PollMailer())->sendSafely('adminLink', [$copy, $adminUrl, $this->joinUrl($copy)]);
if ($sent) {
$this->Flash->success(__('Kopie angelegt, ohne Antworten. Der Admin-Link der Kopie wurde per E-Mail verschickt – speichere dir diese Seite als Lesezeichen.'));
} else {
$this->Flash->warning(__('Kopie angelegt, ohne Antworten. Die E-Mail mit dem Admin-Link konnte nicht verschickt werden – speichere dir diese Seite unbedingt als Lesezeichen!'));
}
return $this->redirect($this->adminUrlFor($token));
}
/**
* 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
{
$this->prepareStage(true);
}
/**
* @param bool $start Show the first slide if the presentation has not been started yet
* @return void
*/
private function prepareStage(bool $start): void
{
if ($start && $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();
}
/**
* Speaker view for a second window or screen: current slide, preview of the next one and the
* same controls as the presenter screen. Unlike present() it never starts the presentation.
*
* @return void
*/
public function speaker(): void
{
$this->prepareStage(false);
$this->set('speaker', true);
$this->viewBuilder()->setTemplate('present');
}
/**
* 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 slide with a countdown (quiz, or any slide with a time limit), next starts it and then ends it
* before moving on, on an open ordering slide next closes it (reveals the solution),
* 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];
// Q&A: forward first walks through the stages (collect → vote → discuss), then through the questions,
// only after the last one it goes to the next slide. Back only steps through the questions.
if ($current !== null && $current->isQa() && in_array($action, ['next', 'prev'], true)) {
$qa = new QaService();
if ($qa->moveFocus($current, $action === 'next' ? 1 : -1) || ($action === 'next' && $qa->advance($current))) {
$action = 'none';
}
}
// Forward on a slide with a countdown (every quiz, any other slide with a time limit) is a build step too:
// start it, then end it, only then the next slide.
// Back never touches it, so a clicker can page through the slides afterwards.
if ($current !== null && $current->usesPhases() && $action === 'next') {
$phase = $current->quizPhase();
if ($phase !== Slide::QUIZ_FINISHED) {
(new SlideControlService())->apply($current, $phase === Slide::QUIZ_READY ? 'open' : 'close');
$action = 'none';
}
}
// An ordering slide without countdown: forward first closes the voting (reveals the solution).
if ($current !== null && $current->isOrder() && $action === 'next' && $current->isVotingOpen()) {
(new SlideControlService())->apply($current, '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);
}
}