Add initial Plenario live polling app
CI / Deploy / test (push) Successful in 49s
CI / Deploy / deploy (push) Failing after 5s

CakePHP 5.4 app for live polls: create via email without login, manage
via secret admin link, join via code. Includes slide types (choice,
wordcloud, open, scale, content), presenter mode, CSV export, captcha,
throttling, tests and Gitea CI/deploy workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-07 13:24:29 +01:00
commit eb319f8c1e
120 files changed
+15572

No files matched your search

+107
View File
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Model\Entity\Poll;
use App\Model\Table\PollsTable;
use Cake\Event\EventInterface;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\I18n\DateTime;
/**
* Base class for everything under /admin/{token}.
*
* "Authentication" = possession of the secret token. The poll is resolved via
* the sha256 hash of the token in beforeFilter(); unknown tokens yield a 404.
* Subclasses use $this->poll and $this->token.
*/
abstract class AdminAppController extends AppController
{
protected PollsTable $Polls;
protected Poll $poll;
protected string $token;
/**
* @return void
*/
public function initialize(): void
{
parent::initialize();
/** @var \App\Model\Table\PollsTable $polls */
$polls = $this->fetchTable('Polls');
$this->Polls = $polls;
}
/**
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
* @return void
*/
public function beforeFilter(EventInterface $event): void
{
parent::beforeFilter($event);
$this->token = (string)$this->request->getParam('token');
/** @var \App\Model\Entity\Poll|null $poll */
$poll = $this->Polls->find('byAdminToken', token: $this->token)->first();
if ($poll === null) {
throw new NotFoundException(__('Diese Admin-URL ist ungültig.'));
}
$this->poll = $poll;
// Track usage at most every 10 minutes to avoid a write per request.
if ($poll->last_admin_access === null || $poll->last_admin_access->wasWithinLast('10 minutes') === false) {
$this->Polls->updateAll(['last_admin_access' => DateTime::now()], ['id' => $poll->id]);
}
$this->set('poll', $poll);
$this->set('adminToken', $this->token);
}
/**
* The token is part of the URL: never send it as referrer, never index it, never cache it.
*
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
* @return void
*/
public function beforeRender(EventInterface $event): void
{
parent::beforeRender($event);
$this->response = $this->protect($this->response);
}
/**
* @param \Cake\Http\Response $response Response
* @return \Cake\Http\Response
*/
protected function protect(Response $response): Response
{
return $response
->withHeader('Referrer-Policy', 'no-referrer')
->withHeader('X-Robots-Tag', 'noindex, nofollow')
->withHeader('Cache-Control', 'no-store, private');
}
/**
* @inheritDoc
*/
protected function json(array $data, int $status = 200): Response
{
return $this->protect(parent::json($data, $status));
}
/**
* URL array for a named admin route of the current poll.
*
* @param string $name Route name
* @param array<string, mixed> $params Extra params
* @return array<string, mixed>
*/
protected function adminUrl(string $name = 'admin', array $params = []): array
{
return ['_name' => $name, 'token' => $this->token] + $params;
}
}
+308
View File
@@ -0,0 +1,308 @@
<?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\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
*
* 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);
switch ($action) {
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) {
$slide = $slides[$index];
$slide->is_voting_open = match ($action) {
'open' => true,
'close' => false,
default => !$slide->is_voting_open,
};
$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] = $option->label;
}
$responses = $this->Responses->find()
->where(['slide_id' => $slide->id])
->orderBy(['id' => 'ASC'])
->all();
foreach ($responses as $response) {
$answer = match (true) {
$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;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\EventInterface;
use Cake\Http\Response;
/**
* Base controller of Plenario.
*/
class AppController extends Controller
{
/**
* @return void
*/
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Flash');
}
/**
* Security headers for every HTML response.
*
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
* @return void
*/
public function beforeRender(EventInterface $event): void
{
parent::beforeRender($event);
$this->response = $this->response
->withHeader('X-Content-Type-Options', 'nosniff')
->withHeader('X-Frame-Options', 'SAMEORIGIN')
->withHeader('Referrer-Policy', 'same-origin');
}
/**
* Returns a JSON response without going through the view layer.
*
* @param array<string, mixed> $data Payload
* @param int $status HTTP status
* @return \Cake\Http\Response
*/
protected function json(array $data, int $status = 200): Response
{
return $this->response
->withStatus($status)
->withType('application/json')
->withHeader('Cache-Control', 'no-store')
->withStringBody((string)json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
}
View File
Whitespace-only changes.
+70
View File
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.3.4
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Controller;
use Cake\Event\EventInterface;
/**
* Error Handling Controller
*
* Controller used by ExceptionRenderer to render error responses.
*/
class ErrorController extends AppController
{
/**
* Initialization hook method.
*
* @return void
*/
public function initialize(): void
{
// Only add parent::initialize() if you are confident your `AppController` is safe.
}
/**
* beforeFilter callback.
*
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event.
* @return void
*/
public function beforeFilter(EventInterface $event): void
{
}
/**
* beforeRender callback.
*
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event.
* @return void
*/
public function beforeRender(EventInterface $event): void
{
parent::beforeRender($event);
$this->viewBuilder()->setTemplatePath('Error');
}
/**
* afterFilter callback.
*
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event.
* @return void
*/
public function afterFilter(EventInterface $event): void
{
}
}
+229
View File
@@ -0,0 +1,229 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Captcha\CaptchaFactory;
use App\Mailer\PollMailer;
use App\Model\Table\PollsTable;
use App\Service\ThrottleService;
use Cake\Core\Configure;
use Cake\Http\Response;
use Cake\Log\Log;
use Cake\Routing\Router;
use Throwable;
/**
* Public pages: start page, poll creation, joining by code, link recovery.
*/
class HomeController extends AppController
{
protected PollsTable $Polls;
/**
* @return void
*/
public function initialize(): void
{
parent::initialize();
/** @var \App\Model\Table\PollsTable $polls */
$polls = $this->fetchTable('Polls');
$this->Polls = $polls;
}
/**
* Start page with "create poll" and "join" forms.
*
* @return void
*/
public function index(): void
{
$poll = $this->Polls->newEmptyEntity();
$captcha = CaptchaFactory::create('create')->challenge($this->request);
$this->set(compact('poll', 'captcha'));
}
/**
* Creates a poll and mails the admin link.
*
* @return \Cake\Http\Response|null
*/
public function create(): ?Response
{
$this->request->allowMethod(['post']);
$captcha = CaptchaFactory::create('create');
$poll = $this->Polls->newEmptyEntity();
$poll = $this->Polls->patchEntity($poll, (array)$this->request->getData(), ['fields' => ['title', 'email']]);
if (!$captcha->verify($this->request)) {
$this->Flash->error(__('Die Sicherheitsabfrage war nicht korrekt. Bitte versuche es erneut.'));
} elseif (!$poll->hasErrors() && !$this->throttle('create', 'Plenario.throttle.createPerHour')) {
$this->Flash->error(__('Zu viele Umfragen in kurzer Zeit. Bitte versuche es später noch einmal.'));
} elseif (!$poll->hasErrors()) {
[$poll, $token] = $this->Polls->createPoll((array)$this->request->getData());
if ($token !== null) {
$adminUrl = Router::url(['_name' => 'admin', 'token' => $token], true);
$joinUrl = Router::url(['_name' => 'participate', 'code' => $poll->join_code], true);
$sent = $this->sendMail(fn(PollMailer $mailer) => $mailer->send('adminLink', [$poll, $adminUrl, $joinUrl]));
$session = $this->request->getSession();
$session->write('Plenario.created', [
'email' => $poll->email,
'title' => $poll->title,
'mailSent' => $sent,
'adminUrl' => Configure::read('Plenario.showAdminLinkAfterCreate') ? $adminUrl : null,
]);
return $this->redirect(['_name' => 'created']);
}
$this->Flash->error(__('Die Umfrage konnte nicht angelegt werden.'));
}
// Re-render the start page with errors.
$this->set('poll', $poll);
$this->set('captcha', $captcha->challenge($this->request));
$this->render('index');
return null;
}
/**
* Confirmation page after creating a poll.
*
* @return \Cake\Http\Response|null
*/
public function created(): ?Response
{
$created = $this->request->getSession()->consume('Plenario.created');
if (!is_array($created)) {
return $this->redirect(['_name' => 'home']);
}
$this->set('created', $created);
return null;
}
/**
* Join by code: GET /join?code=XYZ or POST from the start page form.
*
* @return \Cake\Http\Response|null
*/
public function join(): ?Response
{
$code = (string)($this->request->getData('code') ?? $this->request->getQuery('code') ?? '');
if ($code === '') {
$this->set('code', '');
return null;
}
$poll = $this->Polls->find('byJoinCode', code: $code)->first();
if ($poll === null) {
$this->Flash->error(__('Zu diesem Code wurde keine Umfrage gefunden.'));
$this->set('code', $code);
return null;
}
return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]);
}
/**
* Sends all admin links of an e-mail address. Always answers with the same
* message to avoid leaking which addresses exist.
*
* @return \Cake\Http\Response|null
*/
public function recover(): ?Response
{
$captcha = CaptchaFactory::create('recover');
if ($this->request->is('post')) {
$email = strtolower(trim((string)$this->request->getData('email')));
if (!$captcha->verify($this->request)) {
$this->Flash->error(__('Die Sicherheitsabfrage war nicht korrekt. Bitte versuche es erneut.'));
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->Flash->error(__('Bitte gib eine gültige E-Mail-Adresse ein.'));
} elseif (!$this->throttle('recover', 'Plenario.throttle.recoverPerHour')) {
$this->Flash->error(__('Zu viele Anfragen. Bitte versuche es später noch einmal.'));
} else {
$this->sendRecoveryMail($email);
$this->Flash->success(__(
'Falls zu {0} Umfragen existieren, haben wir dir die Admin-Links per E-Mail geschickt.',
$email,
));
return $this->redirect(['_name' => 'recover']);
}
}
$this->set('captcha', $captcha->challenge($this->request));
return null;
}
/**
* @param string $email Normalised e-mail
* @return void
*/
protected function sendRecoveryMail(string $email): void
{
/** @var list<\App\Model\Entity\Poll> $polls */
$polls = $this->Polls->find()
->where(['email' => $email])
->orderBy(['created' => 'DESC'])
->limit(50)
->all()
->toList();
$links = [];
foreach ($polls as $poll) {
$token = $this->Polls->decryptToken($poll);
if ($token === null) {
continue;
}
$links[] = [
'title' => $poll->title,
'url' => Router::url(['_name' => 'admin', 'token' => $token], true),
'created' => $poll->created->i18nFormat('dd.MM.yyyy HH:mm'),
];
}
if ($links !== []) {
$this->sendMail(fn(PollMailer $mailer) => $mailer->send('recovery', [$email, $links]));
}
}
/**
* @param string $bucket Throttle bucket
* @param string $configKey Configure key holding the hourly limit
* @return bool
*/
protected function throttle(string $bucket, string $configKey): bool
{
return (new ThrottleService())->attempt(
$bucket,
(string)$this->request->clientIp(),
(int)Configure::read($configKey, 0),
);
}
/**
* Sends a mail and logs (instead of throwing) transport errors.
*
* @param callable(\App\Mailer\PollMailer): mixed $send Callback
* @return bool
*/
protected function sendMail(callable $send): bool
{
try {
$send(new PollMailer());
return true;
} catch (Throwable $e) {
Log::error('Mail delivery failed: ' . $e->getMessage());
return false;
}
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Model\Entity\Poll;
use App\Model\Table\PollsTable;
use App\Service\PollStateService;
use App\Service\VoteException;
use App\Service\VoteService;
use Cake\Core\Configure;
use Cake\Event\EventInterface;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
use Cake\I18n\DateTime;
/**
* Participant pages under /p/{code}.
*
* Participants are anonymous. A random id is stored in the cookie
* `plenario_pid`; only an HMAC of it (scoped per poll) ends up in the database.
*/
class ParticipateController extends AppController
{
public const COOKIE = 'plenario_pid';
protected PollsTable $Polls;
protected string $participantId;
protected bool $newParticipant = false;
/**
* @return void
*/
public function initialize(): void
{
parent::initialize();
/** @var \App\Model\Table\PollsTable $polls */
$polls = $this->fetchTable('Polls');
$this->Polls = $polls;
}
/**
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
* @return void
*/
public function beforeFilter(EventInterface $event): void
{
parent::beforeFilter($event);
$pid = (string)$this->request->getCookie(self::COOKIE, '');
if (!preg_match('/^[a-f0-9]{32}$/', $pid)) {
$pid = bin2hex(random_bytes(16));
$this->newParticipant = true;
}
$this->participantId = $pid;
}
/**
* @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event
* @return void
*/
public function afterFilter(EventInterface $event): void
{
parent::afterFilter($event);
if ($this->newParticipant) {
$this->response = $this->response->withCookie(Cookie::create(self::COOKIE, $this->participantId, [
'expires' => new DateTime('+1 year'),
'path' => '/',
'httponly' => true,
'secure' => $this->request->is('https'),
'samesite' => 'Lax',
]));
}
}
/**
* @param string $code Join code
* @return void
*/
public function view(string $code): void
{
$poll = $this->loadPoll($code);
$stateService = new PollStateService();
$slide = $poll->is_active ? $stateService->currentSlide($poll) : null;
$state = $stateService->forParticipant($poll, $this->participantHash($poll));
$this->set(compact('poll', 'slide', 'state'));
$this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000));
}
/**
* @param string $code Join code
* @return \Cake\Http\Response
*/
public function state(string $code): Response
{
$poll = $this->loadPoll($code);
return $this->json((new PollStateService())->forParticipant($poll, $this->participantHash($poll)));
}
/**
* Stores an answer. AJAX requests (word cloud entries and upvotes) get JSON
* `{ok, message, state}` instead of a redirect with flash message.
*
* @param string $code Join code
* @return \Cake\Http\Response|null
*/
public function vote(string $code): ?Response
{
$this->request->allowMethod(['post']);
$poll = $this->loadPoll($code);
$stateService = new PollStateService();
$slide = $stateService->currentSlide($poll);
$submittedSlideId = (int)$this->request->getData('slide_id');
$ajax = $this->request->is('ajax');
try {
if ($slide === null || $slide->id !== $submittedSlideId) {
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
}
(new VoteService())->submit($poll, $slide, $this->participantHash($poll), (array)$this->request->getData());
$ok = true;
$message = __('Danke für deine Antwort!');
} catch (VoteException $e) {
$ok = false;
$message = $e->getMessage();
}
if ($ajax) {
return $this->json([
'ok' => $ok,
'message' => $message,
'state' => $stateService->forParticipant($poll, $this->participantHash($poll)),
]);
}
$ok ? $this->Flash->success($message) : $this->Flash->error($message);
return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]);
}
/**
* @param string $code Join code
* @return \App\Model\Entity\Poll
*/
protected function loadPoll(string $code): Poll
{
/** @var \App\Model\Entity\Poll|null $poll */
$poll = $this->Polls->find('byJoinCode', code: $code)->first();
if ($poll === null) {
throw new NotFoundException(__('Zu diesem Code wurde keine Umfrage gefunden.'));
}
return $poll;
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @return string
*/
protected function participantHash(Poll $poll): string
{
return VoteService::participantHash($this->participantId, $poll->id);
}
}
+191
View File
@@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Model\Entity\Slide;
use App\Model\Table\SlidesTable;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Response;
/**
* Slide CRUD below /admin/{token}/slides.
*/
class SlidesController extends AdminAppController
{
protected SlidesTable $Slides;
/**
* @return void
*/
public function initialize(): void
{
parent::initialize();
/** @var \App\Model\Table\SlidesTable $slides */
$slides = $this->fetchTable('Slides');
$this->Slides = $slides;
}
/**
* @return \Cake\Http\Response|null
*/
public function add(): ?Response
{
$type = (string)($this->request->getData('type') ?? $this->request->getQuery('type', Slide::TYPE_CHOICE));
if (!array_key_exists($type, Slide::typeLabels())) {
$type = Slide::TYPE_CHOICE;
}
$slide = $this->Slides->newEntity(['type' => $type, 'settings' => Slide::DEFAULT_SETTINGS[$type]], [
'validate' => false,
]);
$slide->setNew(true);
$slide->poll_id = $this->poll->id;
$optionsText = $type === Slide::TYPE_CHOICE ? "\n" : '';
if ($this->request->is('post')) {
$optionsText = (string)$this->request->getData('options_text', '');
if ($this->saveSlide($slide, $optionsText)) {
$this->Flash->success(__('Folie angelegt.'));
return $this->redirect($this->adminUrl());
}
}
$this->set(compact('slide', 'optionsText'));
$this->render('form');
return null;
}
/**
* @param string $id Slide id
* @return \Cake\Http\Response|null
*/
public function edit(string $id): ?Response
{
$slide = $this->loadSlide($id);
$optionsText = implode("\n", array_map(fn($o) => $o->label, $slide->slide_options ?? []));
if ($this->request->is(['post', 'put', 'patch'])) {
$optionsText = (string)$this->request->getData('options_text', '');
if ($this->saveSlide($slide, $optionsText)) {
$this->Flash->success(__('Folie gespeichert.'));
return $this->redirect($this->adminUrl());
}
}
$hasResponses = $this->Slides->Responses->exists(['slide_id' => $slide->id]);
$this->set(compact('slide', 'optionsText', 'hasResponses'));
$this->render('form');
return null;
}
/**
* @param string $id Slide id
* @return \Cake\Http\Response|null
*/
public function delete(string $id): ?Response
{
$this->request->allowMethod(['post']);
$slide = $this->loadSlide($id);
if ($this->poll->current_slide_id === $slide->id) {
$this->poll->current_slide_id = null;
$this->Polls->saveOrFail($this->poll);
}
$this->Slides->deleteOrFail($slide);
$this->Slides->normalizePositions($this->poll->id);
$this->Flash->success(__('Folie gelöscht.'));
return $this->redirect($this->adminUrl());
}
/**
* @param string $id Slide id
* @param string $direction up|down
* @return \Cake\Http\Response|null
*/
public function move(string $id, string $direction): ?Response
{
$this->request->allowMethod(['post']);
$this->Slides->move($this->loadSlide($id), $direction);
return $this->redirect($this->adminUrl());
}
/**
* Deletes all responses of a slide.
*
* @param string $id Slide id
* @return \Cake\Http\Response|null
*/
public function reset(string $id): ?Response
{
$this->request->allowMethod(['post']);
$slide = $this->loadSlide($id);
$this->Slides->Responses->deleteAll(['slide_id' => $slide->id]);
$this->Flash->success(__('Antworten der Folie „{0}“ wurden gelöscht.', $slide->question));
return $this->redirect($this->adminUrl());
}
/**
* Loads a slide that belongs to the current poll (404 otherwise).
*
* @param string $id Slide id
* @return \App\Model\Entity\Slide
*/
protected function loadSlide(string $id): Slide
{
/** @var \App\Model\Entity\Slide|null $slide */
$slide = $this->Slides->find()
->where(['Slides.id' => (int)$id, 'Slides.poll_id' => $this->poll->id])
->contain(['SlideOptions'])
->first();
if ($slide === null) {
throw new NotFoundException(__('Folie nicht gefunden.'));
}
return $slide;
}
/**
* Patches and saves a slide incl. its options.
*
* @param \App\Model\Entity\Slide $slide Slide (new or existing)
* @param string $optionsText Options textarea (choice slides)
* @return bool
*/
protected function saveSlide(Slide $slide, string $optionsText): bool
{
$data = (array)$this->request->getData();
// The type of an existing slide cannot change (would invalidate responses).
$data['type'] = $slide->type;
$this->Slides->patchEntity($slide, $data, [
'fields' => ['type', 'question', 'description', 'settings', 'is_voting_open'],
'associated' => [],
]);
$labels = SlidesTable::parseOptionLines($optionsText);
if ($slide->type === Slide::TYPE_CHOICE && count($labels) < 2) {
$slide->setError('options_text', __('Bitte gib mindestens zwei Antwortoptionen an (eine pro Zeile).'));
}
if ($slide->hasErrors()) {
$this->Flash->error(__('Bitte prüfe deine Eingaben.'));
return false;
}
return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels): bool {
if (!$this->Slides->save($slide)) {
return false;
}
if ($slide->type === Slide::TYPE_CHOICE) {
$this->Slides->syncOptions($slide, $labels);
}
return true;
});
}
}