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; // A quiz is started by the presenter (that also starts its timer). $slide->is_voting_open = $type !== Slide::TYPE_QUIZ; // Q&A starts by collecting questions. $slide->stage = $type === Slide::TYPE_QA ? Slide::QA_COLLECT : null; $optionsText = $type === Slide::TYPE_CHOICE ? "\n" : ''; $quizOptions = []; if ($this->request->is('post')) { $optionsText = (string)$this->request->getData('options_text', ''); $quizOptions = $this->postedQuizOptions(); if ($this->saveSlide($slide, $optionsText)) { $this->Flash->success(__('Folie angelegt.')); return $this->redirect($this->adminUrl()); } } $this->set(compact('slide', 'optionsText', 'quizOptions')); $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 ?? []); if ($this->request->is(['post', 'put', 'patch'])) { $optionsText = (string)$this->request->getData('options_text', ''); $quizOptions = $this->postedQuizOptions(); 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', '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()); } /** * 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); $this->Slides->Responses->deleteAll(['slide_id' => $slide->id]); if ($slide->isQuiz()) { // Back to "not started" so the quiz can be played again. $slide->is_voting_open = false; $slide->voting_started_at = null; $slide->voting_ends_at = null; $this->Slides->saveOrFail($slide); } if ($slide->isQa()) { (new QaService())->reset($slide); } $this->Flash->success(__('Antworten der Folie „{0}“ wurden gelöscht.', $slide->question)); return $this->redirect($this->adminUrl()); } /** * All answers of an open question (also anonymous 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 ($slide->type !== Slide::TYPE_OPEN) { throw new NotFoundException(__('Folie nicht gefunden.')); } $this->set('slide', $slide); $this->set('answers', (new ResultsService())->answers($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 */ 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; } /** * 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->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()) { $this->Slides->syncOptions($slide, $labels, $correct); } 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 $data Request data (question may be filled in) * @return array{errors: array, 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.'); } }