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

+129
View File
@@ -0,0 +1,129 @@
<?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.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App;
use App\Middleware\HostHeaderMiddleware;
use Cake\Core\Configure;
use Cake\Core\ContainerInterface;
use Cake\Datasource\FactoryLocator;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Event\EventManagerInterface;
use Cake\Http\BaseApplication;
use Cake\Http\Middleware\BodyParserMiddleware;
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Http\MiddlewareQueue;
use Cake\ORM\Locator\TableLocator;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
/**
* Application setup class.
*
* This defines the bootstrapping logic and middleware layers you
* want to use in your application.
*
* @extends \Cake\Http\BaseApplication<\App\Application>
*/
class Application extends BaseApplication
{
/**
* Load all the application configuration and bootstrap logic.
*
* @return void
*/
public function bootstrap(): void
{
// Call parent to load bootstrap from files.
parent::bootstrap();
// By default, does not allow fallback classes.
FactoryLocator::add(
'Table',
(new TableLocator())->allowFallbackClass(false),
);
}
/**
* Setup the middleware queue your application will use.
*
* @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
* @return \Cake\Http\MiddlewareQueue The updated middleware queue.
*/
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
$middlewareQueue
// Catch any exceptions in the lower layers,
// and make an error page/response
->add(new ErrorHandlerMiddleware(Configure::read('Error'), $this))
// Validate Host header to prevent Host Header Injection attacks.
// In production, ensures App.fullBaseUrl is configured and validates
// the incoming Host header against it.
->add(new HostHeaderMiddleware())
// Handle plugin/theme assets like CakePHP normally does.
->add(new AssetMiddleware([
'cacheTime' => Configure::read('Asset.cacheTime'),
]))
// Add routing middleware.
// If you have a large number of routes connected, turning on routes
// caching in production could improve performance.
// See https://github.com/CakeDC/cakephp-cached-routing
->add(new RoutingMiddleware($this))
// Parse various types of encoded request bodies so that they are
// available as array through $request->getData()
// https://book.cakephp.org/5/en/controllers/middleware.html#body-parser-middleware
->add(new BodyParserMiddleware())
// Cross Site Request Forgery (CSRF) Protection Middleware
// https://book.cakephp.org/5/en/security/csrf.html#cross-site-request-forgery-csrf-middleware
->add(new CsrfProtectionMiddleware([
'httponly' => true,
]));
return $middlewareQueue;
}
/**
* Register application container services.
*
* @param \Cake\Core\ContainerInterface $container The Container to update.
* @return void
* @link https://book.cakephp.org/5/en/development/dependency-injection.html#dependency-injection
*/
public function services(ContainerInterface $container): void
{
// Allow your Tables to be dependency injected
//$container->delegate(new \Cake\ORM\Locator\TableContainer());
}
/**
* Register custom event listeners here
*
* @param \Cake\Event\EventManagerInterface $eventManager
* @return \Cake\Event\EventManagerInterface
* @link https://book.cakephp.org/5/en/core-libraries/events.html#registering-listeners
*/
public function events(EventManagerInterface $eventManager): EventManagerInterface
{
// $eventManager->on(new SomeCustomListenerClass());
return $eventManager;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Captcha;
use Cake\Core\Configure;
use InvalidArgumentException;
/**
* Builds the captcha configured in `Plenario.captcha.type`.
*/
class CaptchaFactory
{
/**
* @param string $scope Form scope ("create", "recover", ...)
* @param string|null $type Override the configured type
* @return \App\Captcha\CaptchaInterface
*/
public static function create(string $scope, ?string $type = null): CaptchaInterface
{
$type ??= (string)Configure::read('Plenario.captcha.type', 'math');
return match (strtolower($type)) {
'none', '', 'off', 'false' => new NoCaptcha(),
'math' => new MathCaptcha($scope),
'recaptcha' => new RecaptchaCaptcha(
(string)Configure::read('Plenario.captcha.recaptcha.siteKey', ''),
(string)Configure::read('Plenario.captcha.recaptcha.secretKey', ''),
),
default => throw new InvalidArgumentException(sprintf(
'Unknown captcha type "%s". Use none, math or recaptcha.',
$type,
)),
};
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Captcha;
use Cake\Http\ServerRequest;
/**
* A captcha protects the public forms (create poll, recover links).
*
* Lifecycle: the controller calls challenge() when rendering the form and passes
* the returned array to the `captcha` element; on submit it calls verify().
*/
interface CaptchaInterface
{
/**
* @return string 'none' | 'math' | 'recaptcha'
*/
public function getType(): string;
/**
* Prepares a challenge and returns the data the view element needs.
*
* @param \Cake\Http\ServerRequest $request Current request (session access)
* @return array<string, mixed> Always contains 'type'
*/
public function challenge(ServerRequest $request): array;
/**
* @param \Cake\Http\ServerRequest $request Submitted request
* @return bool
*/
public function verify(ServerRequest $request): bool;
}
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Captcha;
use Cake\Http\ServerRequest;
/**
* Simple arithmetic captcha ("Was ist 4 + 7?"). The expected answer is kept in
* the session per form scope and is valid for a single verification only.
*
* Request field: `captcha_answer`.
*/
class MathCaptcha implements CaptchaInterface
{
public const FIELD = 'captcha_answer';
/**
* @param string $scope Form scope, e.g. "create" or "recover"
*/
public function __construct(protected string $scope)
{
}
/**
* @inheritDoc
*/
public function getType(): string
{
return 'math';
}
/**
* @return string
*/
protected function sessionKey(): string
{
return 'Captcha.math.' . $this->scope;
}
/**
* @inheritDoc
*/
public function challenge(ServerRequest $request): array
{
$a = random_int(1, 12);
$b = random_int(1, 9);
if (random_int(0, 1) === 1 && $a > $b) {
$question = sprintf('%d − %d', $a, $b);
$answer = $a - $b;
} else {
$question = sprintf('%d + %d', $a, $b);
$answer = $a + $b;
}
$request->getSession()->write($this->sessionKey(), $answer);
return ['type' => 'math', 'question' => $question, 'field' => self::FIELD];
}
/**
* @inheritDoc
*/
public function verify(ServerRequest $request): bool
{
$session = $request->getSession();
$expected = $session->read($this->sessionKey());
$session->delete($this->sessionKey());
$given = trim((string)$request->getData(self::FIELD, ''));
if ($expected === null || $given === '' || !preg_match('/^-?\d+$/', $given)) {
return false;
}
return (int)$given === (int)$expected;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Captcha;
use Cake\Http\ServerRequest;
/**
* Captcha disabled (CAPTCHA_TYPE=none).
*/
class NoCaptcha implements CaptchaInterface
{
/**
* @inheritDoc
*/
public function getType(): string
{
return 'none';
}
/**
* @inheritDoc
*/
public function challenge(ServerRequest $request): array
{
return ['type' => 'none'];
}
/**
* @inheritDoc
*/
public function verify(ServerRequest $request): bool
{
return true;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Captcha;
use Cake\Http\Client;
use Cake\Http\ServerRequest;
use Cake\Log\Log;
use Throwable;
/**
* Google reCAPTCHA v2 checkbox. Requires RECAPTCHA_SITE_KEY and RECAPTCHA_SECRET_KEY.
* Fails closed: missing keys or network errors reject the submission.
*
* Request field: `g-recaptcha-response` (set by Google's widget).
*/
class RecaptchaCaptcha implements CaptchaInterface
{
public const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
public const FIELD = 'g-recaptcha-response';
protected Client $client;
/**
* @param string $siteKey Public site key
* @param string $secretKey Secret key
* @param \Cake\Http\Client|null $client HTTP client (injectable for tests)
*/
public function __construct(
protected string $siteKey,
protected string $secretKey,
?Client $client = null,
) {
$this->client = $client ?? new Client(['timeout' => 5]);
}
/**
* @inheritDoc
*/
public function getType(): string
{
return 'recaptcha';
}
/**
* @inheritDoc
*/
public function challenge(ServerRequest $request): array
{
return ['type' => 'recaptcha', 'siteKey' => $this->siteKey];
}
/**
* @inheritDoc
*/
public function verify(ServerRequest $request): bool
{
$token = (string)$request->getData(self::FIELD, '');
if ($token === '') {
return false;
}
if ($this->siteKey === '' || $this->secretKey === '') {
Log::error('reCAPTCHA is enabled but RECAPTCHA_SITE_KEY / RECAPTCHA_SECRET_KEY are not configured.');
return false;
}
try {
$response = $this->client->post(self::VERIFY_URL, [
'secret' => $this->secretKey,
'response' => $token,
'remoteip' => $request->clientIp(),
]);
$json = $response->getJson();
} catch (Throwable $e) {
Log::error('reCAPTCHA verification failed: ' . $e->getMessage());
return false;
}
return is_array($json) && ($json['success'] ?? false) === true;
}
}
+260
View File
@@ -0,0 +1,260 @@
<?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.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Console;
if (!defined('STDIN')) {
define('STDIN', fopen('php://stdin', 'r'));
}
use Cake\Codeception\Console\Installer as CodeceptionInstaller;
use Cake\Utility\Security;
use Composer\IO\IOInterface;
use Composer\Script\Event;
use Exception;
/**
* Provides installation hooks for when this application is installed through
* composer. Customize this class to suit your needs.
*/
class Installer
{
/**
* An array of directories to be made writable
*
* @var list<string>
*/
public const WRITABLE_DIRS = [
'logs',
'tmp',
'tmp/cache',
'tmp/cache/models',
'tmp/cache/persistent',
'tmp/cache/views',
'tmp/sessions',
'tmp/tests',
];
/**
* Does some routine installation tasks so people don't have to.
*
* @param \Composer\Script\Event $event The composer event object.
* @throws \Exception Exception raised by validator.
* @return void
*/
public static function postInstall(Event $event): void
{
$io = $event->getIO();
$rootDir = dirname(__DIR__, 2);
static::createAppLocalConfig($rootDir, $io);
static::createWritableDirectories($rootDir, $io);
static::setFolderPermissions($rootDir, $io);
static::setSecuritySalt($rootDir, $io);
if (class_exists(CodeceptionInstaller::class)) {
CodeceptionInstaller::customizeCodeceptionBinary($event);
}
}
/**
* Create config/app_local.php file if it does not exist.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function createAppLocalConfig(string $dir, IOInterface $io): void
{
$appLocalConfig = $dir . '/config/app_local.php';
$appLocalConfigTemplate = $dir . '/config/app_local.example.php';
if (!file_exists($appLocalConfig)) {
copy($appLocalConfigTemplate, $appLocalConfig);
$io->write('Created `config/app_local.php` file');
}
}
/**
* Create the `logs` and `tmp` directories.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function createWritableDirectories(string $dir, IOInterface $io): void
{
foreach (static::WRITABLE_DIRS as $path) {
$path = $dir . '/' . $path;
if (!file_exists($path)) {
mkdir($path);
$io->write('Created `' . $path . '` directory');
}
}
}
/**
* Set globally writable permissions on the "tmp" and "logs" directory.
*
* This is not the most secure default, but it gets people up and running quickly.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function setFolderPermissions(string $dir, IOInterface $io): void
{
// ask if the permissions should be changed
if ($io->isInteractive()) {
$validator = function (string $arg): string {
if (in_array($arg, ['Y', 'y', 'N', 'n'])) {
return $arg;
}
throw new Exception('This is not a valid answer. Please choose Y or n.');
};
$setFolderPermissions = $io->askAndValidate(
'<info>Set Folder Permissions ? (Default to Y)</info> [<comment>Y,n</comment>]? ',
$validator,
10,
'Y',
);
if (in_array($setFolderPermissions, ['n', 'N'])) {
return;
}
}
// Change the permissions on a path and output the results.
$changePerms = function (string $path) use ($io): void {
$currentPerms = fileperms($path) & 0777;
$worldWritable = $currentPerms | 0007;
if ($worldWritable == $currentPerms) {
return;
}
$res = chmod($path, $worldWritable);
if ($res) {
$io->write('Permissions set on ' . $path);
} else {
$io->write('Failed to set permissions on ' . $path);
}
};
$walker = function (string $dir) use (&$walker, $changePerms): void {
$files = array_diff(scandir($dir) ?: [], ['.', '..']);
foreach ($files as $file) {
$path = $dir . '/' . $file;
if (!is_dir($path)) {
continue;
}
$changePerms($path);
$walker($path);
}
};
$walker($dir . '/tmp');
$changePerms($dir . '/tmp');
$changePerms($dir . '/logs');
}
/**
* Set the security.salt value in the application's config file.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function setSecuritySalt(string $dir, IOInterface $io): void
{
$newKey = hash('sha256', Security::randomBytes(64));
static::setSecuritySaltInFile($dir, $io, $newKey, 'app_local.php');
}
/**
* Set the security.salt value in a given file
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @param string $newKey key to set in the file
* @param string $file A path to a file relative to the application's root
* @return void
*/
public static function setSecuritySaltInFile(string $dir, IOInterface $io, string $newKey, string $file): void
{
$config = $dir . '/config/' . $file;
$content = file_get_contents($config);
if ($content === false) {
$io->write('Config file not readable or not found: config/' . $file);
return;
}
$content = str_replace('__SALT__', $newKey, $content, $count);
if ($count == 0) {
$io->write('No Security.salt placeholder to replace.');
return;
}
$result = file_put_contents($config, $content);
if ($result) {
$io->write('Updated Security.salt value in config/' . $file);
return;
}
$io->write('Unable to update Security.salt value.');
}
/**
* Set the APP_NAME value in a given file
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @param string $appName app name to set in the file
* @param string $file A path to a file relative to the application's root
* @return void
*/
public static function setAppNameInFile(string $dir, IOInterface $io, string $appName, string $file): void
{
$config = $dir . '/config/' . $file;
$content = file_get_contents($config);
if ($content === false) {
$io->write('Config file not readable or not found: config/' . $file);
return;
}
$content = str_replace('__APP_NAME__', $appName, $content, $count);
if ($count == 0) {
$io->write('No __APP_NAME__ placeholder to replace.');
return;
}
$result = file_put_contents($config, $content);
if ($result) {
$io->write('Updated __APP_NAME__ value in config/' . $file);
return;
}
$io->write('Unable to update __APP_NAME__ value.');
}
}
+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;
});
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Mailer;
use App\Model\Entity\Poll;
use Cake\Mailer\Mailer;
/**
* Mails sent by Plenario. Templates: templates/email/{html,text}/.
*/
class PollMailer extends Mailer
{
/**
* Mail with the secret admin link after a poll was created.
*
* @param \App\Model\Entity\Poll $poll Poll
* @param string $adminUrl Absolute admin URL (contains the token)
* @param string $joinUrl Absolute participant URL
* @return void
*/
public function adminLink(Poll $poll, string $adminUrl, string $joinUrl): void
{
$this
->setTo($poll->email)
->setSubject(__('Deine Umfrage „{0}“ – Admin-Link', $poll->title))
->setEmailFormat('both')
->setViewVars(compact('poll', 'adminUrl', 'joinUrl'))
->viewBuilder()
->setTemplate('admin_link');
}
/**
* Recovery mail listing all admin links of an e-mail address.
*
* @param string $email Recipient
* @param list<array{title: string, url: string, created: string}> $links Admin links
* @return void
*/
public function recovery(string $email, array $links): void
{
$this
->setTo($email)
->setSubject(__('Deine Admin-Links bei Plenario'))
->setEmailFormat('both')
->setViewVars(compact('links'))
->viewBuilder()
->setTemplate('recovery');
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Mailer\Transport;
use Cake\Mailer\AbstractTransport;
use Cake\Mailer\Message;
use RuntimeException;
/**
* Development transport: writes every mail as .eml file to tmp/mails/
* instead of sending it. Configure via EmailTransport.default.className.
*
* Options: `path` (default TMP/mails/).
*/
class FileTransport extends AbstractTransport
{
/**
* @var array<string, mixed>
*/
protected array $_defaultConfig = [
'path' => TMP . 'mails' . DS,
];
/**
* @param \Cake\Mailer\Message $message Message
* @return array{headers: string, message: string}
*/
public function send(Message $message): array
{
$this->checkRecipient($message);
$path = rtrim((string)$this->getConfig('path'), '/\\') . DS;
if (!is_dir($path) && !mkdir($path, 0775, true) && !is_dir($path)) {
throw new RuntimeException(sprintf('Could not create mail directory "%s".', $path));
}
$headers = $message->getHeadersString(
['from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'subject'],
);
$body = $message->getBodyString();
$file = $path . date('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.eml';
file_put_contents($file, $headers . "\r\n\r\n" . $body);
return ['headers' => $headers, 'message' => $body];
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Middleware;
use Cake\Core\Configure;
use Cake\Http\Exception\BadRequestException;
use Cake\Http\Exception\InternalErrorException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Middleware to validate Host header and prevent Host Header Injection attacks.
*
* In production, this middleware ensures that App.fullBaseUrl is configured
* and validates incoming Host headers against it. This prevents attackers
* from manipulating password reset links and other security-critical URLs.
*
* @see https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/17-Testing_for_Host_Header_Injection
*/
class HostHeaderMiddleware implements MiddlewareInterface
{
/**
* Process the request and validate the Host header.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
* @return \Psr\Http\Message\ResponseInterface A response.
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if (Configure::read('debug')) {
return $handler->handle($request);
}
$fullBaseUrl = Configure::read('App.fullBaseUrl');
if (!$fullBaseUrl) {
throw new InternalErrorException(
'SECURITY: App.fullBaseUrl is not configured. ' .
'This is required in production to prevent Host Header Injection attacks. ' .
'Set APP_FULL_BASE_URL environment variable or configure App.fullBaseUrl in config/app.php',
);
}
$configuredHost = parse_url($fullBaseUrl, PHP_URL_HOST);
$requestHost = $request->getUri()->getHost();
if ($configuredHost && $requestHost && strtolower($configuredHost) !== strtolower($requestHost)) {
throw new BadRequestException(
'Invalid Host header. Request host does not match configured application host.',
);
}
return $handler->handle($request);
}
}
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* @property int $id
* @property string $title
* @property string $email
* @property string $admin_token_hash
* @property string $admin_token_encrypted
* @property string $join_code
* @property int|null $current_slide_id
* @property bool $is_active
* @property bool $show_results_to_participants
* @property \Cake\I18n\DateTime|null $last_admin_access
* @property \Cake\I18n\DateTime $created
* @property \Cake\I18n\DateTime $modified
* @property array<\App\Model\Entity\Slide> $slides
*/
class Poll extends Entity
{
/**
* Only harmless fields are mass assignable. Tokens, join code and the
* current slide are always set explicitly in code.
*
* @var array<string, bool>
*/
protected array $_accessible = [
'title' => true,
'email' => true,
'is_active' => true,
'show_results_to_participants' => true,
];
/**
* Never leak secrets when an entity is serialised (JSON, debug output).
*
* @var list<string>
*/
protected array $_hidden = [
'admin_token_hash',
'admin_token_encrypted',
'email',
];
/**
* "K7P2QX" -> "K7P 2QX" for nicer display.
*
* @return string
*/
public function formattedJoinCode(): string
{
return trim(chunk_split($this->join_code, 3, ' '));
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* One answer row of a participant. A multi-select vote or a word cloud entry
* with several words results in several rows with the same participant_hash.
*
* @property int $id
* @property int $slide_id
* @property string $participant_hash
* @property int|null $slide_option_id
* @property string|null $text_value
* @property int|null $numeric_value
* @property \Cake\I18n\DateTime $created
*/
class Response extends Entity
{
/**
* Responses are only created by VoteService, never mass assigned from requests.
*
* @var array<string, bool>
*/
protected array $_accessible = [
'slide_id' => true,
'participant_hash' => true,
'slide_option_id' => true,
'text_value' => true,
'numeric_value' => true,
];
/**
* @var list<string>
*/
protected array $_hidden = ['participant_hash'];
}
+126
View File
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* A slide of a poll. `type` decides how participants answer and how results
* are aggregated (see \App\Service\ResultsService and \App\Service\VoteService).
*
* @property int $id
* @property int $poll_id
* @property string $type
* @property string $question
* @property string|null $description
* @property int $position
* @property array<string, mixed>|null $settings
* @property bool $is_voting_open
* @property \Cake\I18n\DateTime $created
* @property \Cake\I18n\DateTime $modified
* @property \App\Model\Entity\Poll $poll
* @property array<\App\Model\Entity\SlideOption> $slide_options
* @property array<\App\Model\Entity\Response> $responses
*/
class Slide extends Entity
{
public const TYPE_CHOICE = 'choice';
public const TYPE_WORDCLOUD = 'wordcloud';
public const TYPE_OPEN = 'open';
public const TYPE_SCALE = 'scale';
public const TYPE_CONTENT = 'content';
/**
* Default settings per type. Unknown keys are dropped on save.
*
* @var array<string, array<string, mixed>>
*/
public const DEFAULT_SETTINGS = [
self::TYPE_CHOICE => ['multiple' => false],
// max_words: words per participant incl. upvotes (not downvotes), 0 = unlimited;
// allow_downvotes only takes effect together with allow_upvotes
self::TYPE_WORDCLOUD => ['max_words' => 0, 'allow_upvotes' => true, 'allow_downvotes' => true],
self::TYPE_OPEN => [],
self::TYPE_SCALE => ['scale_min' => 1, 'scale_max' => 5, 'min_label' => '', 'max_label' => ''],
self::TYPE_CONTENT => [],
];
/**
* @var array<string, bool>
*/
protected array $_accessible = [
'type' => true,
'question' => true,
'description' => true,
'settings' => true,
'is_voting_open' => true,
];
/**
* @return array<string, string> type => human readable label
*/
public static function typeLabels(): array
{
return [
self::TYPE_CHOICE => __('Multiple Choice'),
self::TYPE_WORDCLOUD => __('Wortwolke'),
self::TYPE_OPEN => __('Offene Frage'),
self::TYPE_SCALE => __('Skala'),
self::TYPE_CONTENT => __('Inhaltsfolie'),
];
}
/**
* @return array<string, string> type => short description
*/
public static function typeDescriptions(): array
{
return [
self::TYPE_CHOICE => __('Antwortoptionen vorgeben, Ergebnis als Balkendiagramm.'),
self::TYPE_WORDCLOUD => __('Teilnehmende geben Begriffe ein oder unterstützen vorhandene, häufige werden größer.'),
self::TYPE_OPEN => __('Freitext-Antworten, live als Liste.'),
self::TYPE_SCALE => __('Bewertung auf einer Skala, z. B. 1 bis 5.'),
self::TYPE_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'),
];
}
/**
* @return string
*/
public function typeLabel(): string
{
return static::typeLabels()[$this->type] ?? $this->type;
}
/**
* Whether participants can answer this slide at all.
*
* @return bool
*/
public function isInteractive(): bool
{
return $this->type !== self::TYPE_CONTENT;
}
/**
* Settings merged with the type defaults.
*
* @return array<string, mixed>
*/
public function getSettings(): array
{
$defaults = self::DEFAULT_SETTINGS[$this->type] ?? [];
return array_intersect_key(array_merge($defaults, (array)($this->settings ?? [])), $defaults);
}
/**
* @param string $key Setting name
* @return mixed
*/
public function setting(string $key): mixed
{
return $this->getSettings()[$key] ?? null;
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* @property int $id
* @property int $slide_id
* @property string $label
* @property int $position
*/
class SlideOption extends Entity
{
/**
* @var array<string, bool>
*/
protected array $_accessible = [
'label' => true,
'position' => true,
];
}
View File
Whitespace-only changes.
+233
View File
@@ -0,0 +1,233 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use App\Model\Entity\Poll;
use Cake\ORM\Query\SelectQuery;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Utility\Security;
use Cake\Validation\Validator;
use RuntimeException;
/**
* Polls ("presentations"). Access control works exclusively via the secret
* admin token - there are no user accounts.
*
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\HasMany $Slides
* @method \App\Model\Entity\Poll newEmptyEntity()
* @method \App\Model\Entity\Poll get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
* @method \App\Model\Entity\Poll saveOrFail(\Cake\Datasource\EntityInterface $entity, array $options = [])
*/
class PollsTable extends Table
{
/**
* Characters used for join codes (no 0/O, 1/I/L to avoid confusion).
*/
public const JOIN_CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
public const JOIN_CODE_LENGTH = 6;
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('polls');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Slides', [
'foreignKey' => 'poll_id',
'sort' => ['Slides.position' => 'ASC', 'Slides.id' => 'ASC'],
'dependent' => true,
'cascadeCallbacks' => false,
]);
}
/**
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->scalar('title')
->maxLength('title', 200, __('Der Titel darf maximal 200 Zeichen lang sein.'))
->requirePresence('title', 'create')
->notEmptyString('title', __('Bitte gib einen Titel ein.'));
$validator
->email('email', false, __('Bitte gib eine gültige E-Mail-Adresse ein.'))
->maxLength('email', 255)
->requirePresence('email', 'create')
->notEmptyString('email', __('Bitte gib deine E-Mail-Adresse ein.'));
$validator->boolean('is_active');
$validator->boolean('show_results_to_participants');
return $validator;
}
/**
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules): RulesChecker
{
$rules->add($rules->isUnique(['join_code']), ['errorField' => 'join_code']);
$rules->add($rules->isUnique(['admin_token_hash']), ['errorField' => 'admin_token_hash']);
return $rules;
}
/**
* Creates a new admin token: URL safe, 256 bit entropy.
*
* @return string
*/
public static function generateToken(): string
{
return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
}
/**
* @param string $token Plain admin token
* @return string sha256 hex digest
*/
public static function hashToken(string $token): string
{
return hash('sha256', $token);
}
/**
* Assigns a fresh admin token to the poll (hash + encrypted copy).
*
* @param \App\Model\Entity\Poll $poll Poll entity
* @return string The plain token (only ever shown in the admin URL / mail)
*/
public function assignNewToken(Poll $poll): string
{
$token = static::generateToken();
$poll->admin_token_hash = static::hashToken($token);
$poll->admin_token_encrypted = base64_encode(Security::encrypt($token, static::encryptionKey()));
return $token;
}
/**
* Decrypts the stored admin token (used by the recovery mail).
*
* @param \App\Model\Entity\Poll $poll Poll entity
* @return string|null
*/
public function decryptToken(Poll $poll): ?string
{
$raw = base64_decode((string)$poll->admin_token_encrypted, true);
if ($raw === false) {
return null;
}
$token = Security::decrypt($raw, static::encryptionKey());
if ($token === null || static::hashToken($token) !== $poll->admin_token_hash) {
return null;
}
return $token;
}
/**
* @return string 32 byte key derived from Security.salt
*/
protected static function encryptionKey(): string
{
return hash('sha256', 'plenario-admin-token|' . Security::getSalt());
}
/**
* Generates a join code that is not yet in use.
*
* @return string
*/
public function generateJoinCode(): string
{
$alphabet = self::JOIN_CODE_ALPHABET;
$max = strlen($alphabet) - 1;
for ($attempt = 0; $attempt < 50; $attempt++) {
$code = '';
for ($i = 0; $i < self::JOIN_CODE_LENGTH; $i++) {
$code .= $alphabet[random_int(0, $max)];
}
if (!$this->exists(['join_code' => $code])) {
return $code;
}
}
throw new RuntimeException('Could not generate a unique join code.');
}
/**
* Normalises user input like " k7p-2qx " to "K7P2QX".
*
* @param string $code Raw user input
* @return string
*/
public static function normalizeJoinCode(string $code): string
{
return (string)preg_replace('/[^A-Z0-9]/', '', strtoupper($code));
}
/**
* Creates and persists a new poll.
*
* @param array<string, mixed> $data title + email
* @return array{0: \App\Model\Entity\Poll, 1: string|null} The entity (check getErrors()) and the plain token on success
*/
public function createPoll(array $data): array
{
$poll = $this->newEntity([
'title' => trim((string)($data['title'] ?? '')),
'email' => strtolower(trim((string)($data['email'] ?? ''))),
], ['fields' => ['title', 'email']]);
if ($poll->hasErrors()) {
return [$poll, null];
}
$token = $this->assignNewToken($poll);
$poll->join_code = $this->generateJoinCode();
$poll->is_active = true;
$poll->show_results_to_participants = true;
if (!$this->save($poll)) {
return [$poll, null];
}
return [$poll, $token];
}
/**
* @param \Cake\ORM\Query\SelectQuery $query Query
* @param string $token Plain admin token
* @return \Cake\ORM\Query\SelectQuery
*/
public function findByAdminToken(SelectQuery $query, string $token): SelectQuery
{
return $query->where(['Polls.admin_token_hash' => static::hashToken($token)]);
}
/**
* @param \Cake\ORM\Query\SelectQuery $query Query
* @param string $code Join code (will be normalised)
* @return \Cake\ORM\Query\SelectQuery
*/
public function findByJoinCode(SelectQuery $query, string $code): SelectQuery
{
return $query->where(['Polls.join_code' => static::normalizeJoinCode($code)]);
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use App\Service\VoteService;
use Cake\ORM\Table;
/**
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\BelongsTo $Slides
* @property \App\Model\Table\SlideOptionsTable&\Cake\ORM\Association\BelongsTo $SlideOptions
* @method \App\Model\Entity\Response newEntity(array $data, array $options = [])
*/
class ResponsesTable extends Table
{
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('responses');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp', [
'events' => ['Model.beforeSave' => ['created' => 'new']],
]);
$this->belongsTo('Slides', ['foreignKey' => 'slide_id', 'joinType' => 'INNER']);
$this->belongsTo('SlideOptions', ['foreignKey' => 'slide_option_id']);
}
/**
* @param int $slideId Slide id
* @param string $participantHash Participant hash
* @return bool
*/
public function hasResponded(int $slideId, string $participantHash): bool
{
return $this->exists(['slide_id' => $slideId, 'participant_hash' => $participantHash]);
}
/**
* Word cloud terms a participant named/upvoted and downvoted on a slide.
*
* @param int $slideId Slide id
* @param string $participantHash Participant hash
* @return array{up: list<string>, down: list<string>} raw text values
*/
public function wordVotesOf(int $slideId, string $participantHash): array
{
$rows = $this->find()
->select(['text_value', 'numeric_value'])
->where(['slide_id' => $slideId, 'participant_hash' => $participantHash, 'text_value IS NOT' => null])
->orderBy(['id' => 'ASC'])
->disableHydration()
->all();
$votes = ['up' => [], 'down' => []];
foreach ($rows as $row) {
$votes[(int)$row['numeric_value'] === VoteService::DOWNVOTE ? 'down' : 'up'][] = (string)$row['text_value'];
}
return $votes;
}
/**
* Whether anybody named (or upvoted) a word cloud term on a slide.
*
* @param int $slideId Slide id
* @param string $key Word key, see VoteService::wordKey()
* @return bool
*/
public function wordExists(int $slideId, string $key): bool
{
$rows = $this->find()
->select(['text_value'])
->where([
'slide_id' => $slideId,
'text_value IS NOT' => null,
'numeric_value IS' => null,
])
->disableHydration()
->all();
foreach ($rows as $row) {
if (VoteService::wordKey((string)$row['text_value']) === $key) {
return true;
}
}
return false;
}
/**
* Number of distinct participants that answered a slide.
*
* @param int $slideId Slide id
* @return int
*/
public function countParticipants(int $slideId): int
{
$row = $this->find()
->select(['n' => $this->find()->func()->count('DISTINCT participant_hash')])
->where(['slide_id' => $slideId])
->disableHydration()
->first();
return (int)($row['n'] ?? 0);
}
/**
* Number of responding participants per slide of a poll.
*
* @param int $pollId Poll id
* @return array<int, int> slide_id => participant count
*/
public function countParticipantsPerSlide(int $pollId): array
{
$rows = $this->find()
->select([
'slide_id' => 'Responses.slide_id',
'n' => $this->find()->func()->count('DISTINCT Responses.participant_hash'),
])
->innerJoinWith('Slides')
->where(['Slides.poll_id' => $pollId])
->groupBy(['Responses.slide_id'])
->disableHydration()
->all();
$counts = [];
foreach ($rows as $row) {
$counts[(int)$row['slide_id']] = (int)$row['n'];
}
return $counts;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\BelongsTo $Slides
* @property \App\Model\Table\ResponsesTable&\Cake\ORM\Association\HasMany $Responses
* @method \App\Model\Entity\SlideOption newEntity(array $data, array $options = [])
*/
class SlideOptionsTable extends Table
{
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('slide_options');
$this->setDisplayField('label');
$this->setPrimaryKey('id');
$this->belongsTo('Slides', ['foreignKey' => 'slide_id', 'joinType' => 'INNER']);
$this->hasMany('Responses', ['foreignKey' => 'slide_option_id', 'dependent' => true]);
}
/**
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->scalar('label')
->maxLength('label', 255)
->notEmptyString('label');
return $validator;
}
}
+281
View File
@@ -0,0 +1,281 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use App\Model\Entity\Slide;
use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* @property \App\Model\Table\PollsTable&\Cake\ORM\Association\BelongsTo $Polls
* @property \App\Model\Table\SlideOptionsTable&\Cake\ORM\Association\HasMany $SlideOptions
* @property \App\Model\Table\ResponsesTable&\Cake\ORM\Association\HasMany $Responses
* @method \App\Model\Entity\Slide newEmptyEntity()
* @method \App\Model\Entity\Slide get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
*/
class SlidesTable extends Table
{
public const MAX_OPTIONS = 20;
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('slides');
$this->setDisplayField('question');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->getSchema()->setColumnType('settings', 'json');
$this->belongsTo('Polls', ['foreignKey' => 'poll_id', 'joinType' => 'INNER']);
$this->hasMany('SlideOptions', [
'foreignKey' => 'slide_id',
'sort' => ['SlideOptions.position' => 'ASC', 'SlideOptions.id' => 'ASC'],
'dependent' => true,
]);
$this->hasMany('Responses', [
'foreignKey' => 'slide_id',
'dependent' => true,
]);
}
/**
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->inList('type', array_keys(Slide::typeLabels()))
->requirePresence('type', 'create')
->notEmptyString('type');
$validator
->scalar('question')
->maxLength('question', 500, __('Die Frage darf maximal 500 Zeichen lang sein.'))
->requirePresence('question', 'create')
->notEmptyString('question', __('Bitte gib eine Frage bzw. Überschrift ein.'));
$validator
->scalar('description')
->maxLength('description', 5000)
->allowEmptyString('description');
$validator->boolean('is_voting_open');
return $validator;
}
/**
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules): RulesChecker
{
$rules->add($rules->existsIn(['poll_id'], 'Polls'), ['errorField' => 'poll_id']);
return $rules;
}
/**
* Normalise settings before they are marshalled into the entity.
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event
* @param \ArrayObject<string, mixed> $data Request data
* @param \ArrayObject<string, mixed> $options Options
* @return void
*/
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options): void
{
if (isset($data['question']) && is_string($data['question'])) {
$data['question'] = trim($data['question']);
}
if (isset($data['settings']) && is_array($data['settings']) && isset($data['type'])) {
$data['settings'] = static::sanitizeSettings((string)$data['type'], $data['settings']);
}
}
/**
* Assign the next free position for new slides.
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event
* @param \Cake\Datasource\EntityInterface $entity Slide
* @param \ArrayObject<string, mixed> $options Options
* @return void
*/
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
if ($entity->isNew() && !$entity->has('position')) {
$max = $this->find()
->where(['poll_id' => $entity->get('poll_id')])
->select(['max' => $this->find()->func()->max('position')])
->disableHydration()
->first();
$entity->set('position', (int)($max['max'] ?? 0) + 1);
}
}
/**
* Reduces raw settings input to the known keys of the type, with proper types.
*
* @param string $type Slide type
* @param array<string, mixed> $input Raw settings
* @return array<string, mixed>
*/
public static function sanitizeSettings(string $type, array $input): array
{
$settings = Slide::DEFAULT_SETTINGS[$type] ?? [];
switch ($type) {
case Slide::TYPE_CHOICE:
$settings['multiple'] = filter_var($input['multiple'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_WORDCLOUD:
$settings['max_words'] = max(0, min(50, (int)($input['max_words'] ?? 0)));
$settings['allow_upvotes'] = filter_var($input['allow_upvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
$settings['allow_downvotes'] = filter_var($input['allow_downvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_SCALE:
$min = max(0, min(1, (int)($input['scale_min'] ?? 1)));
$max = max(2, min(10, (int)($input['scale_max'] ?? 5)));
$settings['scale_min'] = $min;
$settings['scale_max'] = $max;
$settings['min_label'] = mb_substr(trim((string)($input['min_label'] ?? '')), 0, 60);
$settings['max_label'] = mb_substr(trim((string)($input['max_label'] ?? '')), 0, 60);
break;
}
return $settings;
}
/**
* Parses a textarea (one option per line) into a clean list of labels.
*
* @param string $raw Textarea content
* @return list<string>
*/
public static function parseOptionLines(string $raw): array
{
$labels = [];
foreach (preg_split('/\R/', $raw) ?: [] as $line) {
$line = mb_substr(trim($line), 0, 255);
if ($line !== '' && !in_array($line, $labels, true)) {
$labels[] = $line;
}
}
return array_slice($labels, 0, self::MAX_OPTIONS);
}
/**
* Synchronises the answer options of a slide with the given labels.
* Options whose label is unchanged keep their id (and therefore their votes);
* removed options are deleted together with their votes.
*
* @param \App\Model\Entity\Slide $slide Saved slide
* @param list<string> $labels New labels in display order
* @return void
*/
public function syncOptions(Slide $slide, array $labels): void
{
$existing = $this->SlideOptions->find()
->where(['slide_id' => $slide->id])
->all()
->indexBy('label')
->toArray();
$this->getConnection()->transactional(function () use ($slide, $labels, $existing): void {
foreach ($labels as $index => $label) {
$option = $existing[$label] ?? $this->SlideOptions->newEntity(['label' => $label]);
$option->set('slide_id', $slide->id);
$option->set('position', $index + 1);
$this->SlideOptions->saveOrFail($option);
unset($existing[$label]);
}
foreach ($existing as $obsolete) {
$this->SlideOptions->deleteOrFail($obsolete);
}
});
}
/**
* Swaps the slide with its neighbour.
*
* @param \App\Model\Entity\Slide $slide Slide to move
* @param string $direction 'up' or 'down'
* @return bool Whether something changed
*/
public function move(Slide $slide, string $direction): bool
{
$this->normalizePositions($slide->poll_id);
$slide = $this->get($slide->id);
$neighbour = $this->find()
->where([
'poll_id' => $slide->poll_id,
'position' . ($direction === 'up' ? ' <' : ' >') => $slide->position,
])
->orderBy(['position' => $direction === 'up' ? 'DESC' : 'ASC'])
->first();
if ($neighbour === null) {
return false;
}
return (bool)$this->getConnection()->transactional(function () use ($slide, $neighbour): bool {
$position = $slide->position;
$slide->position = $neighbour->position;
$neighbour->position = $position;
return $this->save($slide) && $this->save($neighbour);
});
}
/**
* Renumbers positions 1..n (closes gaps after deletions).
*
* @param int $pollId Poll id
* @return void
*/
public function normalizePositions(int $pollId): void
{
$slides = $this->find()
->where(['poll_id' => $pollId])
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
->all();
$position = 1;
foreach ($slides as $slide) {
if ($slide->position !== $position) {
$this->updateAll(['position' => $position], ['id' => $slide->id]);
}
$position++;
}
}
/**
* Ordered slides of a poll including options.
*
* @param int $pollId Poll id
* @return list<\App\Model\Entity\Slide>
*/
public function listForPoll(int $pollId): array
{
/** @var list<\App\Model\Entity\Slide> $slides */
$slides = $this->find()
->where(['Slides.poll_id' => $pollId])
->contain(['SlideOptions'])
->orderBy(['Slides.position' => 'ASC', 'Slides.id' => 'ASC'])
->all()
->toList();
return $slides;
}
}
+185
View File
@@ -0,0 +1,185 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Poll;
use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use App\Model\Table\SlidesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
/**
* Builds the JSON state polled by the presenter screen (/admin/{token}/state)
* and the participant page (/p/{code}/state).
*
* The participant state never contains results unless the poll allows it and
* the participant has answered (or voting is closed). Exception: word clouds
* with upvotes enabled show the live cloud while voting is open, because
* participants upvote by clicking words in it.
*/
class PollStateService
{
use LocatorAwareTrait;
protected SlidesTable $Slides;
protected ResponsesTable $Responses;
protected ResultsService $results;
/**
* Constructor
*/
public function __construct()
{
/** @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;
$this->results = new ResultsService();
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @return \App\Model\Entity\Slide|null
*/
public function currentSlide(Poll $poll): ?Slide
{
if ($poll->current_slide_id === null) {
return null;
}
/** @var \App\Model\Entity\Slide|null $slide */
$slide = $this->Slides->find()
->where(['Slides.id' => $poll->current_slide_id, 'Slides.poll_id' => $poll->id])
->contain(['SlideOptions'])
->first();
return $slide;
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @return array<string, mixed>
*/
public function forPresenter(Poll $poll): array
{
$slides = $this->Slides->listForPoll($poll->id);
$current = null;
$index = null;
foreach ($slides as $i => $slide) {
if ($slide->id === $poll->current_slide_id) {
$current = $slide;
$index = $i;
}
}
return [
'poll' => [
'title' => $poll->title,
'joinCode' => $poll->join_code,
'joinCodeFormatted' => $poll->formattedJoinCode(),
'isActive' => $poll->is_active,
],
'slides' => array_map(fn(Slide $s) => [
'id' => $s->id,
'type' => $s->type,
'question' => $s->question,
], $slides),
'index' => $index,
'count' => count($slides),
'slide' => $current ? $this->slidePayload($current) : null,
'results' => $current ? $this->results->forSlide($current) : null,
];
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @param string $participantHash Participant hash
* @return array<string, mixed>
*/
public function forParticipant(Poll $poll, string $participantHash): array
{
$slide = $poll->is_active ? $this->currentSlide($poll) : null;
$words = $slide?->type === Slide::TYPE_WORDCLOUD ? $this->wordState($slide, $participantHash) : null;
$hasResponded = $words !== null
? $words['mine'] !== [] || $words['down'] !== []
: $slide && $slide->isInteractive() && $this->Responses->hasResponded($slide->id, $participantHash);
$showResults = $slide !== null
&& $slide->isInteractive()
&& (
($poll->show_results_to_participants && ($hasResponded || !$slide->is_voting_open))
|| ($words !== null && $words['allowUpvotes'] && $slide->is_voting_open)
);
return [
'isActive' => $poll->is_active,
'slideId' => $slide?->id,
'isVotingOpen' => $slide?->is_voting_open ?? false,
'hasResponded' => $hasResponded,
// Changes whenever the participant page must re-render.
'version' => implode(':', [
(int)$poll->is_active,
$slide?->id ?? 0,
(int)($slide?->is_voting_open ?? 0),
// Word clouds are answered word by word without reload.
$words !== null ? (int)$words['limitReached'] : (int)$hasResponded,
$slide?->modified?->toUnixString() ?? 0,
]),
'slide' => $showResults ? $this->slidePayload($slide) : null,
'results' => $showResults ? $this->results->forSlide($slide) : null,
'words' => $words,
];
}
/**
* Word cloud progress of one participant.
*
* @param \App\Model\Entity\Slide $slide Word cloud slide
* @param string $participantHash Participant hash
* @return array{mine: list<string>, down: list<string>, max: int, remaining: int|null,
* limitReached: bool, allowUpvotes: bool, allowDownvotes: bool}
* `mine` (named/upvoted) and `down` are lower case word keys, `remaining` is null when unlimited
*/
public function wordState(Slide $slide, string $participantHash): array
{
$votes = $this->Responses->wordVotesOf($slide->id, $participantHash);
$mine = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['up'])));
$down = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['down'])));
$max = (int)$slide->setting('max_words');
$remaining = $max > 0 ? max(0, $max - count($mine)) : null;
$allowUpvotes = (bool)$slide->setting('allow_upvotes');
return [
'mine' => $mine,
'down' => $down,
'max' => $max,
'remaining' => $remaining,
'limitReached' => $remaining === 0,
'allowUpvotes' => $allowUpvotes,
'allowDownvotes' => $allowUpvotes && (bool)$slide->setting('allow_downvotes'),
];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
public function slidePayload(Slide $slide): array
{
return [
'id' => $slide->id,
'type' => $slide->type,
'typeLabel' => $slide->typeLabel(),
'question' => $slide->question,
'description' => (string)$slide->description,
'isVotingOpen' => $slide->is_voting_open,
'isInteractive' => $slide->isInteractive(),
'settings' => $slide->getSettings(),
];
}
}
+198
View File
@@ -0,0 +1,198 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
/**
* Aggregates responses of a slide into a JSON friendly structure that is
* rendered by webroot/js/plenario.js (presenter + participant views).
*
* Shape (always present): ['type' => string, 'participants' => int, ...]
* - choice: 'options' => [['id', 'label', 'count', 'percent']]
* - wordcloud: 'words' => [['key' (lower case), 'text', 'count', 'down', 'weight' (0..1)]]
* (count = participants who named or upvoted the word, down = downvotes,
* weight follows count)
* - open: 'answers' => [['text', 'created']] newest first
* - scale: 'buckets' => [['value', 'count', 'percent']], 'average' => float|null,
* 'min', 'max', 'minLabel', 'maxLabel'
*/
class ResultsService
{
use LocatorAwareTrait;
public const MAX_ANSWERS = 200;
protected ResponsesTable $Responses;
/**
* Constructor
*/
public function __construct()
{
/** @var \App\Model\Table\ResponsesTable $responses */
$responses = $this->fetchTable('Responses');
$this->Responses = $responses;
}
/**
* @param \App\Model\Entity\Slide $slide Slide incl. slide_options
* @return array<string, mixed>
*/
public function forSlide(Slide $slide): array
{
$result = [
'type' => $slide->type,
'participants' => $slide->isInteractive() ? $this->Responses->countParticipants($slide->id) : 0,
];
return $result + match ($slide->type) {
Slide::TYPE_CHOICE => $this->choice($slide),
Slide::TYPE_WORDCLOUD => $this->wordcloud($slide),
Slide::TYPE_OPEN => $this->open($slide),
Slide::TYPE_SCALE => $this->scale($slide),
default => [],
};
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function choice(Slide $slide): array
{
$counts = $this->Responses->find()
->select(['slide_option_id', 'n' => $this->Responses->find()->func()->count('*')])
->where(['slide_id' => $slide->id, 'slide_option_id IS NOT' => null])
->groupBy(['slide_option_id'])
->disableHydration()
->all()
->combine('slide_option_id', 'n')
->toArray();
$total = array_sum(array_map('intval', $counts));
$options = [];
foreach ($slide->slide_options ?? [] as $option) {
$count = (int)($counts[$option->id] ?? 0);
$options[] = [
'id' => $option->id,
'label' => $option->label,
'count' => $count,
'percent' => $total > 0 ? round($count / $total * 100, 1) : 0,
];
}
return ['options' => $options, 'votes' => $total];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function wordcloud(Slide $slide): array
{
$rows = $this->Responses->find()
->select(['text_value', 'numeric_value'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null])
->disableHydration()
->all();
// Group case-insensitively, display the most frequent spelling.
$groups = [];
$downvotes = [];
foreach ($rows as $row) {
$text = (string)$row['text_value'];
$key = VoteService::wordKey($text);
if ((int)$row['numeric_value'] === VoteService::DOWNVOTE) {
$downvotes[$key] = ($downvotes[$key] ?? 0) + 1;
continue;
}
$groups[$key]['count'] = ($groups[$key]['count'] ?? 0) + 1;
$groups[$key]['spellings'][$text] = ($groups[$key]['spellings'][$text] ?? 0) + 1;
}
// Size follows the upvotes (count); downvotes are shown separately.
uasort($groups, fn($a, $b) => $b['count'] <=> $a['count']);
$maxCount = $groups === [] ? 1 : max(array_column($groups, 'count'));
$words = [];
foreach ($groups as $key => $group) {
arsort($group['spellings']);
$words[] = [
'key' => (string)$key,
'text' => (string)array_key_first($group['spellings']),
'count' => $group['count'],
'down' => $downvotes[$key] ?? 0,
'weight' => round($group['count'] / $maxCount, 3),
];
}
return ['words' => $words];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function open(Slide $slide): array
{
$rows = $this->Responses->find()
->select(['text_value', 'created'])
->where(['slide_id' => $slide->id, 'text_value IS NOT' => null])
->orderBy(['id' => 'DESC'])
->limit(self::MAX_ANSWERS)
->all();
$answers = [];
foreach ($rows as $row) {
$answers[] = ['text' => $row->text_value, 'created' => $row->created->toIso8601String()];
}
return ['answers' => $answers];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @return array<string, mixed>
*/
protected function scale(Slide $slide): array
{
$min = (int)$slide->setting('scale_min');
$max = (int)$slide->setting('scale_max');
$counts = $this->Responses->find()
->select(['numeric_value', 'n' => $this->Responses->find()->func()->count('*')])
->where(['slide_id' => $slide->id, 'numeric_value IS NOT' => null])
->groupBy(['numeric_value'])
->disableHydration()
->all()
->combine('numeric_value', 'n')
->toArray();
$total = 0;
$sum = 0;
foreach ($counts as $value => $count) {
$total += (int)$count;
$sum += (int)$value * (int)$count;
}
$buckets = [];
for ($value = $min; $value <= $max; $value++) {
$count = (int)($counts[$value] ?? 0);
$buckets[] = [
'value' => $value,
'count' => $count,
'percent' => $total > 0 ? round($count / $total * 100, 1) : 0,
];
}
return [
'buckets' => $buckets,
'average' => $total > 0 ? round($sum / $total, 2) : null,
'min' => $min,
'max' => $max,
'minLabel' => (string)$slide->setting('min_label'),
'maxLabel' => (string)$slide->setting('max_label'),
];
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Service;
use Cake\Cache\Cache;
/**
* Very small fixed-window rate limiter backed by the "throttle" cache config.
* Used to limit poll creation and recovery mails per client IP.
*/
class ThrottleService
{
public const WINDOW_SECONDS = 3600;
/**
* Registers a hit and returns whether the action is still allowed.
*
* @param string $bucket Logical action, e.g. "create"
* @param string $identifier Client identifier, e.g. IP address
* @param int $limit Allowed hits per window; <= 0 disables throttling
* @return bool
*/
public function attempt(string $bucket, string $identifier, int $limit): bool
{
if ($limit <= 0) {
return true;
}
$key = 'throttle_' . $bucket . '_' . hash('sha256', $identifier);
$now = time();
/** @var array{start: int, hits: int}|null $state */
$state = Cache::read($key, 'throttle');
if (!is_array($state) || $state['start'] + self::WINDOW_SECONDS <= $now) {
$state = ['start' => $now, 'hits' => 0];
}
if ($state['hits'] >= $limit) {
return false;
}
$state['hits']++;
Cache::write($key, $state, 'throttle');
return true;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Service;
use RuntimeException;
/**
* Thrown when a vote is rejected. The message is safe to show to participants.
*/
class VoteException extends RuntimeException
{
}
+280
View File
@@ -0,0 +1,280 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Poll;
use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
use Cake\Utility\Security;
/**
* Validates and stores participant answers.
*
* Rules:
* - the poll must be active and the slide must be the poll's current slide
* - voting on the slide must be open
* - every participant can answer a slide exactly once, except word clouds:
* there words are submitted one by one (each word once per participant,
* at most `max_words` words, 0 = unlimited). Submitting a word that already
* exists in the cloud is an upvote – both are stored as the same row.
* `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing
* word of someone else. Each participant rates a word only once (up or down);
* downvotes do not count towards `max_words`.
*/
class VoteService
{
use LocatorAwareTrait;
public const MAX_WORD_LENGTH = 40;
public const MAX_TEXT_LENGTH = 500;
/**
* `responses.numeric_value` of a word cloud downvote (upvotes/words: null).
*/
public const DOWNVOTE = -1;
protected ResponsesTable $Responses;
/**
* Constructor
*/
public function __construct()
{
/** @var \App\Model\Table\ResponsesTable $responses */
$responses = $this->fetchTable('Responses');
$this->Responses = $responses;
}
/**
* Derives the anonymous participant hash from the cookie id. The poll id is
* part of the HMAC key so participants cannot be correlated across polls.
*
* @param string $participantId Random id from the participant cookie
* @param int $pollId Poll id
* @return string
*/
public static function participantHash(string $participantId, int $pollId): string
{
return hash_hmac('sha256', $participantId, Security::getSalt() . '|poll|' . $pollId);
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @param \App\Model\Entity\Slide $slide Slide (with slide_options for choice slides)
* @param string $participantHash Participant hash
* @param array<string, mixed> $data Request data
* @return void
* @throws \App\Service\VoteException
*/
public function submit(Poll $poll, Slide $slide, string $participantHash, array $data): void
{
if (!$poll->is_active) {
throw new VoteException(__('Diese Umfrage ist derzeit geschlossen.'));
}
if ($slide->poll_id !== $poll->id || $poll->current_slide_id !== $slide->id) {
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
}
if (!$slide->isInteractive()) {
throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.'));
}
if (!$slide->is_voting_open) {
throw new VoteException(__('Die Abstimmung zu dieser Frage ist geschlossen.'));
}
if ($slide->type !== Slide::TYPE_WORDCLOUD && $this->Responses->hasResponded($slide->id, $participantHash)) {
throw new VoteException(__('Du hast bereits abgestimmt.'));
}
$rows = match ($slide->type) {
Slide::TYPE_CHOICE => $this->choiceRows($slide, $data),
Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data),
Slide::TYPE_OPEN => $this->openRows($data),
Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
default => throw new VoteException(__('Unbekannter Folientyp.')),
};
$entities = [];
foreach ($rows as $row) {
$entities[] = $this->Responses->newEntity($row + [
'slide_id' => $slide->id,
'participant_hash' => $participantHash,
]);
}
$this->Responses->saveManyOrFail($entities);
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function choiceRows(Slide $slide, array $data): array
{
$selected = $data['option_ids'] ?? $data['option_id'] ?? [];
$selected = array_values(array_unique(array_map('intval', (array)$selected)));
$validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []);
$selected = array_values(array_intersect($selected, $validIds));
if ($selected === []) {
throw new VoteException(__('Bitte wähle eine Antwort aus.'));
}
if (!$slide->setting('multiple') && count($selected) > 1) {
throw new VoteException(__('Bitte wähle nur eine Antwort aus.'));
}
return array_map(fn(int $id) => ['slide_option_id' => $id], $selected);
}
/**
* Normalized key of a word cloud term: whitespace collapsed, trimmed, cut to
* MAX_WORD_LENGTH. Use wordKey() for case-insensitive comparison.
*
* @param string $word Raw input
* @return string
*/
public static function cleanWord(string $word): string
{
$word = trim((string)preg_replace('/\s+/u', ' ', $word));
return mb_substr($word, 0, self::MAX_WORD_LENGTH);
}
/**
* Case-insensitive grouping key of a word cloud term.
*
* @param string $word Word
* @return string
*/
public static function wordKey(string $word): string
{
return mb_strtolower(self::cleanWord($word));
}
/**
* Accepts `word` (string) or `words` (list). Words the participant already
* submitted are skipped, the rest is cut to the remaining limit.
*
* @param \App\Model\Entity\Slide $slide Slide
* @param string $participantHash Participant hash
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function wordRows(Slide $slide, string $participantHash, array $data): array
{
$votes = $this->Responses->wordVotesOf($slide->id, $participantHash);
$existing = array_values(array_unique(array_map(self::wordKey(...), $votes['up'])));
$downvoted = array_fill_keys(array_map(self::wordKey(...), $votes['down']), true);
if (($data['vote'] ?? null) === 'down') {
return $this->downvoteRows($slide, (string)($data['word'] ?? ''), $existing, $downvoted);
}
$input = array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? []));
$seen = array_fill_keys($existing, true);
$words = [];
$duplicate = false;
$rejected = false;
foreach ($input as $word) {
$word = self::cleanWord((string)$word);
$key = mb_strtolower($word);
if ($word === '') {
continue;
}
if (isset($downvoted[$key])) {
$rejected = true;
continue;
}
if (isset($seen[$key])) {
$duplicate = true;
continue;
}
$seen[$key] = true;
$words[] = $word;
}
$max = (int)$slide->setting('max_words');
if ($max > 0) {
$remaining = max(0, $max - count($existing));
if ($remaining === 0) {
throw new VoteException(__n(
'Du hast deinen Begriff bereits abgegeben.',
'Du hast bereits alle {0} Begriffe abgegeben.',
$max,
$max,
));
}
$words = array_slice($words, 0, $remaining);
}
if ($words === []) {
throw new VoteException(match (true) {
$duplicate => __('Diesen Begriff hast du schon genannt.'),
$rejected => __('Diesen Begriff hast du bereits abgelehnt.'),
default => __('Bitte gib einen Begriff ein.'),
});
}
return array_map(fn(string $word) => ['text_value' => $word], $words);
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param string $word Word to downvote
* @param list<string> $own Keys the participant named/upvoted
* @param array<string, true> $downvoted Keys the participant downvoted
* @return list<array<string, mixed>>
*/
protected function downvoteRows(Slide $slide, string $word, array $own, array $downvoted): array
{
if (!$slide->setting('allow_upvotes') || !$slide->setting('allow_downvotes')) {
throw new VoteException(__('Downvotes sind bei dieser Frage nicht möglich.'));
}
$word = self::cleanWord($word);
$key = mb_strtolower($word);
if ($word === '' || !$this->Responses->wordExists($slide->id, $key)) {
throw new VoteException(__('Diesen Begriff gibt es nicht in der Wortwolke.'));
}
if (in_array($key, $own, true)) {
throw new VoteException(__('Du hast diesen Begriff selbst genannt.'));
}
if (isset($downvoted[$key])) {
throw new VoteException(__('Diesen Begriff hast du bereits abgelehnt.'));
}
return [['text_value' => $word, 'numeric_value' => self::DOWNVOTE]];
}
/**
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function openRows(array $data): array
{
$text = trim((string)($data['text'] ?? ''));
if ($text === '') {
throw new VoteException(__('Bitte gib eine Antwort ein.'));
}
if (mb_strlen($text) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Die Antwort darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
}
return [['text_value' => $text]];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function scaleRows(Slide $slide, array $data): array
{
$value = filter_var($data['value'] ?? null, FILTER_VALIDATE_INT);
$min = (int)$slide->setting('scale_min');
$max = (int)$slide->setting('scale_max');
if ($value === false || $value < $min || $value > $max) {
throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max));
}
return [['numeric_value' => $value]];
}
}
+46
View File
@@ -0,0 +1,46 @@
<?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.0.4
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\View;
/**
* A view class that is used for AJAX responses.
* Currently only switches the default layout and sets the response type -
* which just maps to text/html by default.
*/
class AjaxView extends AppView
{
/**
* The name of the layout file to render the view inside of. The name
* specified is the filename of the layout in /templates/Layout without
* the .php extension.
*
* @var string
*/
protected string $layout = 'ajax';
/**
* Initialization hook method.
*
* @return void
*/
public function initialize(): void
{
parent::initialize();
$this->response = $this->response->withType('ajax');
}
}
+41
View File
@@ -0,0 +1,41 @@
<?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
* 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.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\View;
use Cake\View\View;
/**
* Application View
*
* Your application's default view class
*
* @link https://book.cakephp.org/5/en/views.html#the-app-view
*/
class AppView extends View
{
/**
* Initialization hook method.
*
* Use this method to add common initialization code like adding helpers.
*
* e.g. `$this->addHelper('Html');`
*
* @return void
*/
public function initialize(): void
{
}
}
View File
Whitespace-only changes.
View File
Whitespace-only changes.