Files
Plenario/src/Model/Table/SlidesTable.php
T
gnilebeinandClaude Sonnet 5.5 61718ed7c6
CI / Deploy / PHP 8.4 (push) Successful in 1m11s
CI / Deploy / PHP 8.5 (push) Successful in 1m11s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped
Add optional comment field to multiple choice slides
Participants can justify their choice; the comment is stored once in the
first response row, rotates on the stage like scale comments and is listed
in the admin area and the PDF export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 09:29:25 +01:00

477 lines
18 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace App\Model\Table;
use App\Model\Entity\Slide;
use App\Service\YouTubeService;
use ArrayObject;
use Cake\Database\Expression\QueryExpression;
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;
public const MAX_QUIZ_OPTIONS = 10;
public const MAX_ORDER_OPTIONS = 10;
/**
* @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);
$settings['comments'] = filter_var($input['comments'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_WORDCLOUD:
$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_OPEN:
$settings['private'] = filter_var($input['private'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_SCALE:
$stars = ($input['style'] ?? null) === Slide::SCALE_STARS;
$settings['style'] = $stars ? Slide::SCALE_STARS : Slide::SCALE_NUMBERS;
// Stars always start at one star (zero stars is no rating).
$min = $stars ? 1 : 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);
$settings['private'] = filter_var($input['private'] ?? false, FILTER_VALIDATE_BOOLEAN);
$settings['comments'] = filter_var($input['comments'] ?? false, FILTER_VALIDATE_BOOLEAN);
$settings['comment_ratings'] = filter_var($input['comment_ratings'] ?? false, FILTER_VALIDATE_BOOLEAN);
$view = $input['scale_view'] ?? null;
$settings['scale_view'] = in_array($view, Slide::SCALE_VIEWS, true) ? $view : Slide::SCALE_VIEW_BOTH;
break;
case Slide::TYPE_QUIZ:
$limit = (int)($input['time_limit'] ?? $settings['time_limit']);
if (in_array($limit, Slide::QUIZ_TIME_LIMITS, true)) {
$settings['time_limit'] = $limit;
}
break;
case Slide::TYPE_QA:
$share = (int)($input['upvote_share'] ?? $settings['upvote_share']);
// 0 = no upvotes (no voting stage)
$settings['upvote_share'] = $share === 0 || in_array($share, Slide::QA_UPVOTE_SHARES, true)
? $share
: Slide::DEFAULT_SETTINGS[Slide::TYPE_QA]['upvote_share'];
$perQuestion = (int)($input['max_upvotes_per_question'] ?? $settings['max_upvotes_per_question']);
// 0 = no limit per question
$settings['max_upvotes_per_question'] = max(0, min(Slide::QA_MAX_UPVOTES, $perQuestion));
$settings['allow_self_upvote'] = filter_var($input['allow_self_upvote'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_YOUTUBE:
$url = mb_substr(trim((string)($input['url'] ?? '')), 0, 500);
$parsed = YouTubeService::parseUrl($url);
$settings['url'] = $url;
$settings['video_id'] = $parsed['videoId'] ?? '';
// Form input "1:30" / "2" (minutes); an int is already seconds. Empty = timecode of the link.
$start = $input['start'] ?? '';
if (!is_int($start)) {
$start = trim((string)$start) === '' ? null : YouTubeService::parseStartInput((string)$start);
}
$settings['start'] = max(0, min($start ?? $parsed['start'] ?? 0, YouTubeService::MAX_START));
$settings['autoplay'] = filter_var($input['autoplay'] ?? false, FILTER_VALIDATE_BOOLEAN);
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);
}
/**
* Parses the quiz option rows of the slide form (`quiz_options[i][label|correct]`).
* Empty rows are skipped, duplicate labels are merged.
*
* @param array<mixed> $rows Raw form rows
* @return array{labels: list<string>, correct: list<string>}
*/
public static function parseQuizOptions(array $rows): array
{
$labels = [];
$correct = [];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$label = mb_substr(trim((string)($row['label'] ?? '')), 0, 255);
if ($label === '' || count($labels) >= self::MAX_QUIZ_OPTIONS) {
continue;
}
if (!in_array($label, $labels, true)) {
$labels[] = $label;
}
if (filter_var($row['correct'] ?? false, FILTER_VALIDATE_BOOLEAN) && !in_array($label, $correct, true)) {
$correct[] = $label;
}
}
return ['labels' => $labels, 'correct' => $correct];
}
/**
* Parses the item rows of an ordering slide (`order_options[]`, in the correct order).
* Empty rows are skipped; a repeated label is reported, because it would make the order ambiguous.
*
* @param array<mixed> $rows Raw form rows (labels)
* @return array{labels: list<string>, duplicate: bool}
*/
public static function parseOrderOptions(array $rows): array
{
$labels = [];
$duplicate = false;
foreach ($rows as $row) {
$label = is_scalar($row) ? mb_substr(trim((string)$row), 0, 255) : '';
if ($label === '' || count($labels) >= self::MAX_ORDER_OPTIONS) {
continue;
}
if (in_array($label, $labels, true)) {
$duplicate = true;
continue;
}
$labels[] = $label;
}
return ['labels' => $labels, 'duplicate' => $duplicate];
}
/**
* Persists the end of a timed quiz once its deadline has passed. Safe to
* call repeatedly (no-op unless the slide is still flagged open).
*
* @param \App\Model\Entity\Slide $slide Slide
* @return \App\Model\Entity\Slide
*/
public function closeIfExpired(Slide $slide): Slide
{
if ($slide->isExpired()) {
$slide->is_voting_open = false;
$this->saveOrFail($slide);
}
return $slide;
}
/**
* 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
* @param list<string> $correct Labels of the correct options (quiz)
* @return void
*/
public function syncOptions(Slide $slide, array $labels, array $correct = []): void
{
$existing = $this->SlideOptions->find()
->where(['slide_id' => $slide->id])
->all()
->indexBy('label')
->toArray();
$this->getConnection()->transactional(function () use ($slide, $labels, $correct, $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);
$option->set('is_correct', in_array($label, $correct, true));
$this->SlideOptions->saveOrFail($option);
unset($existing[$label]);
}
foreach ($existing as $obsolete) {
$this->SlideOptions->deleteOrFail($obsolete);
}
});
}
/**
* Copies a slide incl. its settings and options (with the correct answers) and
* puts the copy directly behind the original. Responses are not copied: the copy
* starts like a new slide (quiz not started, Q&A collecting, others open).
*
* @param \App\Model\Entity\Slide $slide Original incl. slide_options
* @return \App\Model\Entity\Slide The saved copy
*/
public function duplicate(Slide $slide): Slide
{
$copy = $this->newEmptyEntity();
$copy->poll_id = $slide->poll_id;
$copy->type = $slide->type;
$copy->question = mb_substr(__('{0} (Kopie)', $slide->question), 0, 500);
$copy->description = $slide->description;
$copy->settings = $slide->settings;
$copy->position = $slide->position + 1;
$copy->startFresh();
return $this->getConnection()->transactional(function () use ($slide, $copy): Slide {
$this->updateAll(
['position' => new QueryExpression('position + 1')],
['poll_id' => $slide->poll_id, 'position >' => $slide->position],
);
$this->saveOrFail($copy);
foreach ($slide->slide_options ?? [] as $option) {
$newOption = $this->SlideOptions->newEntity([
'label' => $option->label,
'position' => $option->position,
]);
$newOption->set('slide_id', $copy->id);
$newOption->set('is_correct', $option->is_correct);
$this->SlideOptions->saveOrFail($newOption);
}
$this->normalizePositions($slide->poll_id);
return $this->get($copy->id, contain: ['SlideOptions']);
});
}
/**
* Applies a complete new order (e.g. from drag & drop).
*
* The ids must be exactly the slides of the poll, each once – otherwise
* (stale page, foreign ids) nothing is changed. Repeating the same order is a no-op.
*
* @param int $pollId Poll id
* @param list<int> $slideIds Slide ids in their new order
* @return bool Whether the order was valid and is now applied
*/
public function reorder(int $pollId, array $slideIds): bool
{
$current = $this->find('list', valueField: 'position')
->where(['poll_id' => $pollId])
->toArray();
$given = $slideIds;
$existing = array_map('intval', array_keys($current));
sort($given);
sort($existing);
if ($given !== $existing) {
return false;
}
return (bool)$this->getConnection()->transactional(function () use ($slideIds, $current): bool {
foreach ($slideIds as $index => $id) {
if ($current[$id] !== $index + 1) {
$this->updateAll(['position' => $index + 1], ['id' => $id]);
}
}
return true;
});
}
/**
* 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
* @param bool $visibleOnly Only slides that are part of the presentation (not hidden)
* @return list<\App\Model\Entity\Slide>
*/
public function listForPoll(int $pollId, bool $visibleOnly = false): array
{
$query = $this->find()
->where(['Slides.poll_id' => $pollId])
->contain(['SlideOptions'])
->orderBy(['Slides.position' => 'ASC', 'Slides.id' => 'ASC']);
if ($visibleOnly) {
$query->where(['Slides.is_hidden' => false]);
}
/** @var list<\App\Model\Entity\Slide> $slides */
$slides = $query->all()->toList();
return $slides;
}
/**
* The visible slide that takes the place of a slide leaving the presentation
* (deleted or hidden): the next visible one behind it, otherwise the one before.
*
* @param \App\Model\Entity\Slide $slide Slide leaving the presentation
* @return int|null Slide id, null if no other visible slide is left
*/
public function replacementFor(Slide $slide): ?int
{
$rows = $this->find()
->select(['id', 'is_hidden'])
->where(['poll_id' => $slide->poll_id])
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
->disableHydration()
->all()
->toList();
$index = array_search($slide->id, array_column($rows, 'id'), true);
if ($index === false) {
return null;
}
$candidates = array_merge(array_slice($rows, $index + 1), array_reverse(array_slice($rows, 0, $index)));
foreach ($candidates as $row) {
if (!$row['is_hidden']) {
return (int)$row['id'];
}
}
return null;
}
}