Files
Plenario/src/Controller/AdminController.php
T
gnilebeinandClaude Opus 5.5 547b564e32
CI / Deploy / test (push) Successful in 55s
CI / Deploy / deploy (push) Skipped
Add internal feedback and comments to choice slides
Same options as for scales: "private" shows only the number of votes on
the stage, "comments" adds an optional comment field whose comments
rotate in the presentation, "comment_ratings" shows the chosen answer(s)
next to each comment. With multiple choice the comment is stored on the
participant's first row. Settings and participant fields are shared
elements for scale and choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:57:35 +01:00

374 lines
14 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\SlideControlService;
use App\Service\VoteService;
use Cake\Core\Configure;
use Cake\Http\Exception\BadRequestException;
use Cake\Http\Response;
use Cake\Log\Log;
use Cake\Routing\Router;
use chillerlan\QRCode\Output\QRMarkupSVG;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
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 = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true);
// Created on first visit, so every slide has its embed URL ready to copy.
$embedKey = $this->Polls->ensureEmbedKey($this->poll);
$this->set(compact('slides', 'responseCounts', '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', 'show_results_to_participants'],
]);
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;
$adminUrl = Router::url($this->adminUrl(), true);
$joinUrl = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true);
try {
(new PollMailer())->send('adminLink', [$this->poll, $adminUrl, $joinUrl]);
$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.'));
} catch (Throwable $e) {
Log::error('Mail delivery failed: ' . $e->getMessage());
$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 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])
->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', Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true));
$this->set('joinBaseUrl', Router::url(['_name' => 'join:short'], true));
$this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000));
}
/**
* JSON state for the presenter screen.
*
* @return \Cake\Http\Response
*/
public function state(): Response
{
return $this->json((new PollStateService())->forPresenter($this->poll));
}
/**
* Presenter controls. Field `action`:
* goto (+ slide_id), next, prev, stop (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). 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');
$slides = $this->Slides->listForPoll($this->poll->id);
$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';
}
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;
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 = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true);
$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);
}
/**
* CSV export of all responses (semicolon separated, UTF-8 with BOM for Excel).
*
* @return \Cake\Http\Response
*/
public function export(): Response
{
$slides = $this->Slides->listForPoll($this->poll->id);
$handle = fopen('php://temp', 'r+');
assert($handle !== false);
fwrite($handle, "\xEF\xBB\xBF");
fputcsv($handle, ['Folie', 'Typ', 'Frage', 'Teilnehmer (anonym)', 'Antwort', 'Zeitpunkt'], ';', '"', '');
foreach ($slides as $position => $slide) {
if (!$slide->isInteractive()) {
continue;
}
$labels = [];
foreach ($slide->slide_options ?? [] as $option) {
$labels[$option->id] = $slide->isQuiz()
? __('{0} ({1})', $option->label, $option->is_correct ? __('richtig') : __('falsch'))
: $option->label;
}
$responses = $this->Responses->find()
->where(['slide_id' => $slide->id])
->orderBy(['id' => 'ASC'])
->all();
$texts = [];
foreach ($responses as $response) {
$texts[$response->id] = (string)$response->text_value;
$answer = match (true) {
$slide->isOrder() => $this->orderAnswer($slide, $labels, (string)$response->text_value),
$response->parent_id !== null => __('Upvote: {0}', $texts[$response->parent_id] ?? ''),
$response->slide_option_id !== null && $response->text_value !== null
=> __('{0} (Kommentar: {1})', $labels[$response->slide_option_id] ?? '', $response->text_value),
$response->slide_option_id !== null => $labels[$response->slide_option_id] ?? '',
$response->text_value !== null && $response->numeric_value === VoteService::DOWNVOTE
=> __('Downvote: {0}', $response->text_value),
$slide->type === Slide::TYPE_SCALE && $response->text_value !== null
=> __('{0} (Kommentar: {1})', $response->numeric_value, $response->text_value),
$response->numeric_value !== null => (string)$response->numeric_value,
default => (string)$response->text_value,
};
fputcsv($handle, [
$position + 1,
$slide->typeLabel(),
$slide->question,
substr($response->participant_hash, 0, 8),
$this->csvSafe($answer),
$response->created->i18nFormat('yyyy-MM-dd HH:mm:ss'),
], ';', '"', '');
}
}
rewind($handle);
$csv = (string)stream_get_contents($handle);
fclose($handle);
$filename = 'plenario-' . $this->poll->join_code . '-' . date('Ymd') . '.csv';
return $this->protect($this->response)
->withType('csv')
->withCharset('UTF-8')
->withDownload($filename)
->withStringBody($csv);
}
/**
* Ordering answer for the CSV export, e.g. "A → C → B (falsch)".
*
* @param \App\Model\Entity\Slide $slide Ordering slide incl. slide_options
* @param array<int, string> $labels Option labels by id
* @param string $text Stored answer (option ids)
* @return string
*/
protected function orderAnswer(Slide $slide, array $labels, string $text): string
{
$given = VoteService::parseOrder($text);
$correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? []));
return __(
'{0} ({1})',
implode(' → ', array_map(fn(int $id) => $labels[$id] ?? '?', $given)),
$given === $correct ? __('richtig') : __('falsch'),
);
}
/**
* Prevents CSV/formula injection in spreadsheet programs.
*
* @param string $value Cell value
* @return string
*/
protected function csvSafe(string $value): string
{
return preg_match('/^[=+\-@\t\r]/', $value) ? "'" . $value : $value;
}
}