Participants submit questions, upvote them and the presenter discusses them one by one, most upvoted first. - Stages collect -> vote -> discuss, switched manually by the presenter (V key or stepper, going back is possible) - Configurable upvote budget per participant, freely distributable (several upvotes on one question are allowed), votes can be withdrawn - Participants see all questions while collecting to avoid duplicates; no counts before the discussion - While discussing, next/prev step through the questions before moving to the next slide - Migration: slides.stage, slides.focus_response_id, responses.parent_id Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
348 lines
13 KiB
PHP
348 lines
13 KiB
PHP
<?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\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);
|
||
|
||
$this->set(compact('slides', 'responseCounts', 'typeLabels', 'typeDescriptions', 'joinUrl'));
|
||
}
|
||
|
||
/**
|
||
* @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());
|
||
}
|
||
|
||
/**
|
||
* 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) {
|
||
$first = $this->Slides->find()
|
||
->where(['poll_id' => $this->poll->id])
|
||
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
|
||
->first();
|
||
if ($first !== null) {
|
||
$this->poll->current_slide_id = $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, open, close, toggle, stop,
|
||
* Q&A: stage (+ stage: collect|vote|discuss), question (+ step: 1|-1)
|
||
*
|
||
* On a Q&A slide that is being discussed, next/prev step through the questions
|
||
* first (like builds in presentation software), toggle switches to the next stage.
|
||
*
|
||
* 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];
|
||
$qa = new QaService();
|
||
if ($current !== null && $current->isQa()) {
|
||
if ($action === 'toggle') {
|
||
// No-op while discussing (last stage).
|
||
$qa->advance($current);
|
||
$action = 'none';
|
||
} elseif (in_array($action, ['next', 'prev'], true) && $qa->moveFocus($current, $action === 'next' ? 1 : -1)) {
|
||
$action = 'none';
|
||
}
|
||
}
|
||
|
||
switch ($action) {
|
||
case 'none':
|
||
break;
|
||
case 'stage':
|
||
case 'question':
|
||
if ($current === null || !$current->isQa()) {
|
||
throw new BadRequestException('Not a Q&A slide');
|
||
}
|
||
if ($action === 'question') {
|
||
$qa->moveFocus($current, (int)$this->request->getData('step') < 0 ? -1 : 1);
|
||
break;
|
||
}
|
||
$stage = (string)$this->request->getData('stage');
|
||
if (!in_array($stage, Slide::QA_STAGES, true)) {
|
||
throw new BadRequestException('Unknown stage');
|
||
}
|
||
$qa->setStage($current, $stage);
|
||
break;
|
||
case 'goto':
|
||
$target = (int)$this->request->getData('slide_id');
|
||
if (!in_array($target, $ids, true)) {
|
||
throw new BadRequestException('Unknown slide');
|
||
}
|
||
$this->poll->current_slide_id = $target;
|
||
break;
|
||
case 'next':
|
||
case 'prev':
|
||
if ($ids !== []) {
|
||
$index = $index === false ? 0 : $index + ($action === 'next' ? 1 : -1);
|
||
$this->poll->current_slide_id = $ids[max(0, min(count($ids) - 1, $index))];
|
||
}
|
||
break;
|
||
case 'stop':
|
||
$this->poll->current_slide_id = null;
|
||
break;
|
||
case 'open':
|
||
case 'close':
|
||
case 'toggle':
|
||
if ($index !== false) {
|
||
// Opening a quiz (re)starts its timer, see Slide::setVotingOpen().
|
||
$slide = $slides[$index];
|
||
$slide->setVotingOpen(match ($action) {
|
||
'open' => true,
|
||
'close' => false,
|
||
default => !$slide->isVotingOpen(),
|
||
});
|
||
$this->Slides->saveOrFail($slide);
|
||
}
|
||
break;
|
||
default:
|
||
throw new BadRequestException('Unknown action');
|
||
}
|
||
$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) {
|
||
$response->parent_id !== null => __('Upvote: {0}', $texts[$response->parent_id] ?? ''),
|
||
$response->slide_option_id !== null => $labels[$response->slide_option_id] ?? '',
|
||
$response->text_value !== null && $response->numeric_value === VoteService::DOWNVOTE
|
||
=> __('Downvote: {0}', $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);
|
||
}
|
||
|
||
/**
|
||
* 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;
|
||
}
|
||
}
|