Hidden slides stay prepared in the dashboard but are skipped when presenting (start, next/prev, goto), can not go live via embed and are left out of the PDF export. Hiding the live or paused slide pauses the poll like deleting it and resumes with the next visible slide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
437 lines
16 KiB
PHP
437 lines
16 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Controller;
|
|
|
|
use App\Model\Entity\Slide;
|
|
use App\Model\Table\SlidesTable;
|
|
use App\Service\QaService;
|
|
use App\Service\ResetService;
|
|
use App\Service\ResultsService;
|
|
use App\Service\YouTubeService;
|
|
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->poll_id = $this->poll->id;
|
|
// A quiz is started by the presenter (that also starts its timer), Q&A starts by collecting questions.
|
|
$slide->startFresh();
|
|
$optionsText = $type === Slide::TYPE_CHOICE ? "\n" : '';
|
|
$quizOptions = [];
|
|
$orderOptions = [];
|
|
|
|
if ($this->request->is('post')) {
|
|
$optionsText = (string)$this->request->getData('options_text', '');
|
|
$quizOptions = $this->postedQuizOptions();
|
|
$orderOptions = $this->postedOrderOptions();
|
|
if ($this->saveSlide($slide, $optionsText)) {
|
|
$this->Flash->success(__('Folie angelegt.'));
|
|
|
|
return $this->redirect($this->adminUrl());
|
|
}
|
|
}
|
|
|
|
$this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions'));
|
|
$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 ?? []));
|
|
$quizOptions = array_map(fn($o) => ['label' => $o->label, 'correct' => $o->is_correct], $slide->slide_options ?? []);
|
|
$orderOptions = array_map(fn($o) => $o->label, $slide->slide_options ?? []);
|
|
|
|
if ($this->request->is(['post', 'put', 'patch'])) {
|
|
$optionsText = (string)$this->request->getData('options_text', '');
|
|
$quizOptions = $this->postedQuizOptions();
|
|
$orderOptions = $this->postedOrderOptions();
|
|
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', 'quizOptions', 'orderOptions', '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);
|
|
// Deleting the live (or paused) slide pauses the poll; → resumes with the slide taking its place.
|
|
$this->poll->forgetSlide($slide->id, $this->Slides->replacementFor($slide));
|
|
|
|
$this->Slides->getConnection()->transactional(function () use ($slide): void {
|
|
$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());
|
|
}
|
|
|
|
/**
|
|
* Hides a slide from the presentation or shows it again. Field `hidden` (1|0) is explicit
|
|
* (not a toggle), so repeating the request changes nothing. Hiding the live (or paused)
|
|
* slide pauses the poll like deleting it.
|
|
*
|
|
* @param string $id Slide id
|
|
* @return \Cake\Http\Response|null
|
|
*/
|
|
public function visibility(string $id): ?Response
|
|
{
|
|
$this->request->allowMethod(['post']);
|
|
$slide = $this->loadSlide($id);
|
|
$hidden = filter_var($this->request->getData('hidden'), FILTER_VALIDATE_BOOLEAN);
|
|
|
|
$this->Slides->getConnection()->transactional(function () use ($slide, $hidden): void {
|
|
if ($hidden) {
|
|
$this->poll->forgetSlide($slide->id, $this->Slides->replacementFor($slide));
|
|
$this->Polls->saveOrFail($this->poll);
|
|
}
|
|
$this->Slides->updateAll(['is_hidden' => $hidden], ['id' => $slide->id]);
|
|
});
|
|
$this->Flash->success($hidden
|
|
? __('Folie „{0}“ ist ausgeblendet und wird beim Präsentieren übersprungen.', $slide->question)
|
|
: __('Folie „{0}“ ist wieder eingeblendet.', $slide->question));
|
|
|
|
return $this->redirect($this->adminUrl());
|
|
}
|
|
|
|
/**
|
|
* Copies a slide (without responses) directly behind the original and opens the copy for editing.
|
|
*
|
|
* @param string $id Slide id
|
|
* @return \Cake\Http\Response|null
|
|
*/
|
|
public function duplicate(string $id): ?Response
|
|
{
|
|
$this->request->allowMethod(['post']);
|
|
$copy = $this->Slides->duplicate($this->loadSlide($id));
|
|
$this->Flash->success(__('Folie dupliziert. Du bearbeitest jetzt die Kopie.'));
|
|
|
|
return $this->redirect($this->adminUrl('slides:edit', ['id' => $copy->id]));
|
|
}
|
|
|
|
/**
|
|
* Saves a complete new slide order (drag & drop), expects `ids[]` and answers with JSON.
|
|
*
|
|
* @return \Cake\Http\Response
|
|
*/
|
|
public function reorder(): Response
|
|
{
|
|
$this->request->allowMethod(['post']);
|
|
$ids = $this->request->getData('ids');
|
|
$ids = is_array($ids) ? array_values(array_map('intval', array_filter($ids, 'is_numeric'))) : [];
|
|
|
|
if (!$this->Slides->reorder($this->poll->id, $ids)) {
|
|
return $this->json([
|
|
'ok' => false,
|
|
'message' => __('Die Reihenfolge konnte nicht gespeichert werden. Bitte lade die Seite neu.'),
|
|
], 409);
|
|
}
|
|
|
|
return $this->json(['ok' => true, 'message' => __('Reihenfolge gespeichert.')]);
|
|
}
|
|
|
|
/**
|
|
* 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);
|
|
(new ResetService())->slide($slide);
|
|
$this->Flash->success(__('Antworten der Folie „{0}“ wurden gelöscht.', $slide->question));
|
|
|
|
return $this->redirect($this->adminUrl());
|
|
}
|
|
|
|
/**
|
|
* All answers of an open question or the ratings of a scale
|
|
* (also anonymous/internal feedback, which is never shown on the stage).
|
|
*
|
|
* @param string $id Slide id
|
|
* @return void
|
|
*/
|
|
public function answers(string $id): void
|
|
{
|
|
$slide = $this->loadSlide($id);
|
|
if (!in_array($slide->type, [Slide::TYPE_OPEN, Slide::TYPE_SCALE], true)) {
|
|
throw new NotFoundException(__('Folie nicht gefunden.'));
|
|
}
|
|
$results = new ResultsService();
|
|
$this->set('slide', $slide);
|
|
$this->set('answers', $slide->type === Slide::TYPE_OPEN ? $results->answers($slide) : []);
|
|
$this->set('scale', $slide->type === Slide::TYPE_SCALE ? $results->scaleResults($slide) : null);
|
|
$this->set('comments', $slide->hasComments() ? $results->comments($slide) : []);
|
|
}
|
|
|
|
/**
|
|
* 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;
|
|
}
|
|
|
|
/**
|
|
* Quiz option rows as posted by the form (for re-rendering after errors).
|
|
*
|
|
* @return list<array{label: string, correct: bool}>
|
|
*/
|
|
protected function postedQuizOptions(): array
|
|
{
|
|
$rows = [];
|
|
foreach ((array)$this->request->getData('quiz_options', []) as $row) {
|
|
if (is_array($row)) {
|
|
$rows[] = [
|
|
'label' => (string)($row['label'] ?? ''),
|
|
'correct' => filter_var($row['correct'] ?? false, FILTER_VALIDATE_BOOLEAN),
|
|
];
|
|
}
|
|
}
|
|
|
|
return $rows;
|
|
}
|
|
|
|
/**
|
|
* Item rows of an ordering slide as posted by the form (for re-rendering after errors).
|
|
*
|
|
* @return list<string>
|
|
*/
|
|
protected function postedOrderOptions(): array
|
|
{
|
|
$rows = [];
|
|
foreach ((array)$this->request->getData('order_options', []) as $label) {
|
|
if (is_scalar($label)) {
|
|
$rows[] = (string)$label;
|
|
}
|
|
}
|
|
|
|
return $rows;
|
|
}
|
|
|
|
/**
|
|
* 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;
|
|
$fields = ['type', 'question', 'description', 'settings', 'is_voting_open'];
|
|
if ($slide->isQuiz() || $slide->isQa()) {
|
|
// Quiz and Q&A voting is controlled by the presenter only.
|
|
$fields = array_values(array_diff($fields, ['is_voting_open']));
|
|
}
|
|
$youtube = $slide->isYouTube() ? $this->prepareYouTube($data) : ['errors' => [], 'warning' => null];
|
|
$this->Slides->patchEntity($slide, $data, ['fields' => $fields, 'associated' => []]);
|
|
foreach ($youtube['errors'] as $field => $message) {
|
|
$slide->setError($field, $message);
|
|
}
|
|
|
|
$labels = SlidesTable::parseOptionLines($optionsText);
|
|
$correct = [];
|
|
if ($slide->type === Slide::TYPE_CHOICE && count($labels) < 2) {
|
|
$slide->setError('options_text', __('Bitte gib mindestens zwei Antwortoptionen an (eine pro Zeile).'));
|
|
}
|
|
if ($slide->isQuiz()) {
|
|
['labels' => $labels, 'correct' => $correct] = SlidesTable::parseQuizOptions(
|
|
(array)$this->request->getData('quiz_options', []),
|
|
);
|
|
if (count($labels) < 2) {
|
|
$slide->setError('quiz_options', __('Bitte gib mindestens zwei Antworten an.'));
|
|
} elseif ($correct === []) {
|
|
$slide->setError('quiz_options', __('Bitte markiere mindestens eine Antwort als richtig.'));
|
|
}
|
|
}
|
|
if ($slide->isOrder()) {
|
|
['labels' => $labels, 'duplicate' => $duplicate] = SlidesTable::parseOrderOptions(
|
|
(array)$this->request->getData('order_options', []),
|
|
);
|
|
if ($duplicate) {
|
|
$slide->setError('order_options', __('Jeder Eintrag darf nur einmal vorkommen, sonst ist die Reihenfolge nicht eindeutig.'));
|
|
} elseif (count($labels) < 2) {
|
|
$slide->setError('order_options', __('Bitte gib mindestens zwei Einträge an.'));
|
|
}
|
|
}
|
|
if ($slide->hasErrors()) {
|
|
$this->Flash->error(__('Bitte prüfe deine Eingaben.'));
|
|
|
|
return false;
|
|
}
|
|
|
|
return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels, $correct, $youtube): bool {
|
|
if (!$this->Slides->save($slide)) {
|
|
return false;
|
|
}
|
|
if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz() || $slide->isOrder()) {
|
|
$this->Slides->syncOptions($slide, $labels, $correct);
|
|
}
|
|
if ($slide->isQa() && $slide->qaStage() === Slide::QA_VOTE && !$slide->hasQaUpvotes()) {
|
|
// Upvotes were switched off while voting: continue with the discussion.
|
|
(new QaService())->setStage($slide, Slide::QA_DISCUSS);
|
|
}
|
|
if ($youtube['warning'] !== null) {
|
|
$this->Flash->warning($youtube['warning']);
|
|
}
|
|
|
|
return true;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Checks a YouTube link (AJAX, "Link prüfen" in the slide form). Expects `url`
|
|
* and optionally `start`, answers with JSON.
|
|
*
|
|
* @return \Cake\Http\Response
|
|
*/
|
|
public function youtubeCheck(): Response
|
|
{
|
|
$this->request->allowMethod(['post']);
|
|
$url = trim((string)$this->request->getData('url', ''));
|
|
$parsed = YouTubeService::parseUrl($url);
|
|
if ($parsed === null) {
|
|
return $this->json([
|
|
'ok' => false,
|
|
'message' => $url === '' ? __('Bitte gib einen YouTube-Link ein.') : $this->invalidYouTubeMessage(),
|
|
]);
|
|
}
|
|
|
|
$check = (new YouTubeService())->check($parsed['videoId']);
|
|
$ok = $check['status'] === YouTubeService::STATUS_OK || $check['status'] === YouTubeService::STATUS_UNREACHABLE;
|
|
$settings = SlidesTable::sanitizeSettings(Slide::TYPE_YOUTUBE, [
|
|
'url' => $url,
|
|
'start' => (string)$this->request->getData('start', ''),
|
|
]);
|
|
|
|
return $this->json([
|
|
'ok' => $ok,
|
|
'status' => $check['status'],
|
|
'message' => YouTubeService::statusMessage($check['status']),
|
|
'title' => $check['title'],
|
|
'linkStart' => $parsed['start'] !== null ? YouTubeService::formatTime($parsed['start']) : null,
|
|
'start' => YouTubeService::formatTime($settings['start']),
|
|
'embedUrl' => $ok ? YouTubeService::embedUrl($parsed['videoId'], $settings['start']) : null,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Validates the YouTube settings of the posted slide data and asks YouTube
|
|
* whether the video can be embedded. An empty title is filled with the video title.
|
|
*
|
|
* @param array<string, mixed> $data Request data (question may be filled in)
|
|
* @return array{errors: array<string, string>, warning: string|null}
|
|
*/
|
|
protected function prepareYouTube(array &$data): array
|
|
{
|
|
$settings = is_array($data['settings'] ?? null) ? $data['settings'] : [];
|
|
$url = trim((string)($settings['url'] ?? ''));
|
|
$start = trim((string)($settings['start'] ?? ''));
|
|
$errors = [];
|
|
$warning = null;
|
|
|
|
if ($start !== '' && YouTubeService::parseStartInput($start) === null) {
|
|
$errors['youtube_start'] = __('Bitte gib die Startzeit als Minute:Sekunde an, z. B. 1:30 (oder nur die Minute).');
|
|
}
|
|
|
|
$parsed = YouTubeService::parseUrl($url);
|
|
if ($parsed === null) {
|
|
$errors['youtube_url'] = $url === '' ? __('Bitte gib einen YouTube-Link ein.') : $this->invalidYouTubeMessage();
|
|
|
|
return ['errors' => $errors, 'warning' => null];
|
|
}
|
|
|
|
$check = (new YouTubeService())->check($parsed['videoId']);
|
|
switch ($check['status']) {
|
|
case YouTubeService::STATUS_OK:
|
|
if (trim((string)($data['question'] ?? '')) === '' && $check['title'] !== null) {
|
|
$data['question'] = mb_substr($check['title'], 0, 500);
|
|
}
|
|
break;
|
|
case YouTubeService::STATUS_UNREACHABLE:
|
|
$warning = YouTubeService::statusMessage($check['status'])
|
|
. ' ' . __('Bitte teste das Video vor deiner Präsentation.');
|
|
break;
|
|
default:
|
|
$errors['youtube_url'] = YouTubeService::statusMessage($check['status']);
|
|
}
|
|
|
|
return ['errors' => $errors, 'warning' => $warning];
|
|
}
|
|
|
|
/**
|
|
* @return string
|
|
*/
|
|
protected function invalidYouTubeMessage(): string
|
|
{
|
|
return __('Das ist kein gültiger YouTube-Link. Kopiere die Adresse des Videos, z. B. https://www.youtube.com/watch?v=dQw4w9WgXcQ oder https://youtu.be/dQw4w9WgXcQ.');
|
|
}
|
|
}
|