From a395b50894476a8b86d3156fea3f9ecbfa722634 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sat, 14 Nov 2026 23:17:37 +0100 Subject: [PATCH] Add optional images to slides Slides (except YouTube) can carry one image. Uploads are validated, rotated by EXIF orientation, scaled to 1600 px and stored as WebP outside webroot, which also strips camera metadata. Images have an alt text (or are marked decorative) and a layout: top, side or full screen (content slides). Files are removed after the commit when a slide is deleted or its image is replaced, with the poll, and `bin/cake images_cleanup` sweeps leftovers. Duplicated slides get their own file. Docker image gains gd with WebP. Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 2 + AGENTS.md | 24 ++ Dockerfile | 11 +- README.md | 13 +- config/.env.example | 5 + .../20261114120000_AddImageToSlides.php | 53 +++ config/app.php | 12 + config/routes.php | 4 + src/Command/ImagesCleanupCommand.php | 72 ++++ src/Controller/ParticipateController.php | 29 ++ src/Controller/SlidesController.php | 143 ++++++- src/Model/Entity/Slide.php | 54 +++ src/Model/Table/PollsTable.php | 18 + src/Model/Table/SlidesTable.php | 43 ++ src/Service/ImageException.php | 13 + src/Service/ImageService.php | 393 ++++++++++++++++++ src/Service/PollStateService.php | 18 +- templates/Admin/index.php | 1 + templates/Admin/present.php | 1 + templates/Embed/view.php | 1 + templates/Participate/view.php | 2 + templates/Slides/form.php | 4 +- templates/element/slide_image.php | 19 + templates/element/slide_image_fields.php | 94 +++++ tests/TestCase/Controller/SlideImageTest.php | 339 +++++++++++++++ tests/TestCase/ImageTestTrait.php | 106 +++++ tests/TestCase/Service/ImageServiceTest.php | 188 +++++++++ tests/bootstrap.php | 3 + webroot/css/plenario.css | 22 + webroot/js/plenario.js | 29 ++ 30 files changed, 1705 insertions(+), 11 deletions(-) create mode 100644 config/Migrations/20261114120000_AddImageToSlides.php create mode 100644 src/Command/ImagesCleanupCommand.php create mode 100644 src/Service/ImageException.php create mode 100644 src/Service/ImageService.php create mode 100644 templates/element/slide_image.php create mode 100644 templates/element/slide_image_fields.php create mode 100644 tests/TestCase/Controller/SlideImageTest.php create mode 100644 tests/TestCase/ImageTestTrait.php create mode 100644 tests/TestCase/Service/ImageServiceTest.php diff --git a/.gitignore b/.gitignore index 618b3a9..94ca770 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,8 @@ /webroot/bake # SQLite-Backups aus der Deploy-Pipeline /data/backups/ +# Folienbilder (UPLOADS_PATH) +/data/uploads/ # Composer /composer.phar # Test-/Analyse-Artefakte diff --git a/AGENTS.md b/AGENTS.md index 57fb7f4..817a339 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,6 +33,7 @@ E-Mail anlegen, kein Login, Verwaltung über einen geheimen Admin-Link, Teilnahm | Tests | `vendor/bin/phpunit` | | Coding Standard | `vendor/bin/phpcs` / Autofix `vendor/bin/phpcbf` | | Neue Migration | `bin/cake bake migration NameDerMigration` | +| Verwaiste Folienbilder löschen | `bin/cake images_cleanup [--dry-run]` | **Vor jedem Commit:** `vendor/bin/phpunit` und `vendor/bin/phpcs` müssen grün sein (Warnungen zur Zeilenlänge bei langen deutschen Texten sind ok). @@ -63,6 +64,7 @@ src/ ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen, eigene Antwort/Kommentar bearbeiten; anonymes Cookie plenario_pid EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control ErrorController Fehlerseiten (Templates unter templates/Error, Layout `error`) + Command/ImagesCleanupCommand `images_cleanup`: Bilddateien ohne Folie entfernen (idempotent) Mailer/ PollMailer (adminLink, recovery; `sendSafely()` loggt Transportfehler statt zu werfen), Transport/FileTransport (lokal) Middleware/ HostHeaderMiddleware: prüft in Produktion den Host gegen APP_FULL_BASE_URL; SecurityHeadersMiddleware (äußerste Schicht): CSP mit Nonce, Framing, nosniff, Referrer-/Permissions-Policy @@ -74,6 +76,7 @@ src/ PollStateService State-JSON für Presenter und Teilnehmende ThrottleService Rate-Limit pro IP (Cache 'throttle'), in Controllern über `AppController::throttle()`: Anlegen/Recover pro Stunde, Antworten (`vote`) pro Minute (`THROTTLE_VOTES_PER_MINUTE`, 429) + ImageService Folienbilder: prüfen, drehen (EXIF), auf `maxEdge` verkleinern, als WebP speichern, löschen, aufräumen YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam) @@ -99,6 +102,7 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures `settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open`, `voting_started_at` / `voting_ends_at` (nur Quiz: Start und Deadline, `null` = manuell beenden), `stage` / `focus_response_id` (nur Q&A: Phase und gerade besprochene Frage) +- `slides.image` / `image_alt` / `image_layout` / `image_width` / `image_height`: optionales Bild (siehe „Folienbilder“) - `slide_options`: Antwortoptionen für `choice`, `quiz` und `order`; `is_correct` markiert richtige Quiz-Antworten, bei `order` ist `position` die richtige Reihenfolge - `responses`: `participant_hash`, `slide_option_id` | `text_value` | `numeric_value` | `parent_id`. @@ -204,6 +208,24 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures danach sieht der Presenter die Lösung inkl. „X von N komplett richtig“ und je Eintrag, wie oft er an der richtigen Stelle lag; Teilnehmende nur die Lösung mit eigenen Platzierungen und `order.isCorrect`. Tests: `OrderTest.php`, `OrderSlideTest.php`. +- **Folienbilder** (ein Bild pro Folie, alle Typen außer `youtube`, `Slide::supportsImage()`): Upload im Folienformular (multipart, + `SlidesController::prepareImage()`), verarbeitet von `ImageService::store()`: Format per `getimagesizefromstring` (JPEG/PNG/GIF/WebP, + **kein SVG, keine animierten GIFs**), EXIF-Drehung (eigener Parser, die `exif`-Erweiterung fehlt oft), längste Kante höchstens + `Plenario.images.maxEdge` (1600), Ausgabe immer WebP (entfernt alle Metadaten inkl. GPS). Das Original wird nie gespeichert. + Ablage `{Plenario.images.path}/{poll_id}/{24 Hex}.webp` (Standard `data/uploads`, Docker `/data/uploads`) **außerhalb von `webroot/`**, + ausgeliefert über `participate:image` (`/p/{code}/img/{file}`, auch für Presenter und Einbettung; nur Dateien dieser Umfrage, `immutable` + gecacht, kein Cookie). Jedes neue Bild bekommt einen neuen Namen → neue URL, ersetzte Bilder sind sofort 404. + Alt-Text ist Pflicht (`image_alt`), außer „Reine Dekoration“ (`image_alt = ''`). Layout `image_layout` (`top`|`side`|`full`, `full` nur + Inhaltsfolien, `null` = Standard je Typ: Inhaltsfolie `side`, sonst `top`; `Slide::imageLayout()`); `side` gilt nur für die Bühne + (CSS `stage--img-*`), Teilnehmende sehen das Bild immer oben (`element/slide_image`). Kontingent `Plenario.images.maxPerPoll` Folien mit Bild. + Im State steht `slide.image` = `{url, alt, layout, width, height}` (`PollStateService::slidePayload()`). + **Löschen:** die Datei geht nach dem Commit weg, nie davor. Bild ersetzen/entfernen: alte Datei nach erfolgreichem Speichern; Fehler beim + Speichern: die neue Datei wird verworfen (`discardImage()`). Folie löschen: explizit im Controller nach der Transaktion + (`Model.afterDeleteCommit` feuert **nicht** innerhalb einer äußeren Transaktion). Umfrage löschen: `PollsTable::afterDeleteCommit` räumt das + Verzeichnis. Duplizieren kopiert die Datei (kein geteiltes Bild, keine Referenzzählung). Zurücksetzen lässt Bilder unberührt. + Reste (Absturz) entfernt `bin/cake images_cleanup`. Beim Patchen von Entity-Feldern ist `patch([...], ['guard' => false])` nötig, und + `patch()` setzt Fehler des Feldes zurück: Fehlermeldungen erst danach setzen. Das Upload-Objekt gehört nicht in `patchEntity()` (Marshaller + scheitert an `UploadedFile`). Tests: `SlideImageTest.php`, `ImageServiceTest.php` (`ImageTestTrait`). - **Zurücksetzen** (`ResetService`) löscht **nur Antworten**: Folie (`slides:reset`) bzw. alle Folien der Umfrage (`admin:reset`, Dashboard → „Sicherheit“). Jede Folie geht danach in den Zustand einer neuen Folie (`Slide::startFresh()`: Quiz `ready`, Q&A `collect`, alle anderen offen – bei Reihenfolge bleibt die Lösung so verdeckt); Einstellungen bleiben. Das Zurücksetzen der @@ -310,6 +332,8 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures ### Neuen Folientyp hinzufügen (Checkliste) +0. Bilder: `Slide::supportsImage()` entscheidet, ob der Typ ein Bild tragen kann (Standard ja). + 1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php` 2. Settings-Sanitizing in `SlidesTable::sanitizeSettings()` 3. Validierung/Speicherung in `VoteService::submit()` (eigene `…Rows()`-Methode) diff --git a/Dockerfile b/Dockerfile index 5f7b8fa..d684eec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,10 +2,14 @@ # Configuration only through environment variables (see config/.env.example). FROM php:8.5-cli-alpine AS base -RUN apk add --no-cache icu-libs \ - && apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev \ - && docker-php-ext-install -j"$(nproc)" intl \ +# gd with JPEG/WebP: slide images are scaled and stored as WebP +RUN apk add --no-cache icu-libs libjpeg-turbo libpng libwebp \ + && apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev libjpeg-turbo-dev libpng-dev libwebp-dev \ + && docker-php-ext-configure gd --with-jpeg --with-webp \ + && docker-php-ext-install -j"$(nproc)" intl gd \ && apk del .build-deps +# Image uploads of up to 10 MB (IMAGE_MAX_UPLOAD_MB) must pass PHP's limits +RUN printf 'upload_max_filesize=10M\npost_max_size=12M\n' > /usr/local/etc/php/conf.d/plenario-uploads.ini FROM base AS build COPY --from=composer:2 /usr/bin/composer /usr/bin/composer @@ -25,6 +29,7 @@ COPY docker/entrypoint.sh /usr/local/bin/plenario-entrypoint ENV DEBUG=false \ SHOW_ADMIN_LINK_AFTER_CREATE=false \ DATABASE_URL=sqlite:////data/plenario.sqlite \ + UPLOADS_PATH=/data/uploads \ PHP_CLI_SERVER_WORKERS=8 RUN chmod +x /usr/local/bin/plenario-entrypoint \ diff --git a/README.md b/README.md index d99e797..2e9fadf 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,9 @@ Wichtige Tasten im Präsentationsmodus: `←` / `→` Folie wechseln, `P` Pause, - **Reihenfolge** – Einträge sortieren, aufgelöst wird beim Schließen der Abstimmung - **Fragen & Antworten** – Fragen sammeln, per Upvote priorisieren, nacheinander besprechen - **Inhaltsfolie** und **YouTube-Video** (ohne Abstimmung) +- **Bilder** auf Folien (außer YouTube): werden beim Hochladen auf höchstens 1600 Pixel verkleinert und als WebP + gespeichert (Kameradaten wie der Aufnahmeort fallen dabei weg), mit Bildbeschreibung und Platzierung oben, daneben + oder bildschirmfüllend - Präsentationsmodus: Vollbild, Tastatursteuerung, QR-Code, Pause, Tag-/Nachtmodus, Live-Ergebnisse - Ergebnisse erscheinen auf der Bühne, nicht auf den Geräten der Teilnehmenden – dort nur, wo sie damit arbeiten (Wortwolke) oder ihre eigene Antwort aufgelöst wird (Quiz, Reihenfolge) @@ -76,7 +79,7 @@ Wichtige Tasten im Präsentationsmodus: `←` / `→` Folie wechseln, `P` Pause, ## Lokal starten (Entwicklung) -Voraussetzungen: PHP 8.4+ mit den Erweiterungen `intl`, `mbstring`, `openssl`, `pdo_sqlite`, `curl` +Voraussetzungen: PHP 8.4+ mit den Erweiterungen `intl`, `mbstring`, `openssl`, `pdo_sqlite`, `curl`, `gd` (mit WebP) sowie [Composer](https://getcomposer.org/). ```bash @@ -141,7 +144,8 @@ openssl rand -hex 32 > und SQLite in einem Volume. Für den echten Betrieb siehe [Deployment ohne Docker](#deployment-ohne-docker). Das [Dockerfile](Dockerfile) baut ein schlankes Image (`php:8.5-cli-alpine`, Multi-Stage mit Composer). -Der eingebaute PHP-Server läuft mit 8 Workern auf Port **8765**, die SQLite-Datenbank liegt im Volume `/data`. +Der eingebaute PHP-Server läuft mit 8 Workern auf Port **8765**, die SQLite-Datenbank und die Folienbilder (`/data/uploads`) +liegen im Volume `/data`. Beim Start laufen die Migrationen automatisch (idempotent, mehrfaches Starten ist unproblematisch). Das fertige Image liegt in der Gitea-Registry: @@ -236,6 +240,11 @@ aktivieren oder `docker build -t plenario .` ausführen. Liegt die App direkt im Document-Root (z. B. `public_html`), leiten `.htaccess` und `index.php` im Projektroot alles nach `webroot/` weiter. +Folienbilder landen in `data/uploads` (anderer Ort: `UPLOADS_PATH`), nie unter `webroot/`; das Verzeichnis gehört in die +Datensicherung. Voraussetzungen: PHP-Erweiterung `gd` mit WebP sowie `upload_max_filesize` und `post_max_size` passend zu +`IMAGE_MAX_UPLOAD_MB` (Standard 10 MB, PHP-Standard sind nur 2 MB bzw. 8 MB). Dateien ohne Folie (z. B. nach einem Absturz) +entfernt `bin/cake images_cleanup` (`--dry-run` zeigt sie nur an). + Bei Updates: Code aktualisieren, `composer install --no-dev`, Migrationen und `cache clear_all` wiederholen. ## Automatisches Deployment (Gitea Actions) diff --git a/config/.env.example b/config/.env.example index d3b8cc8..8a54a1d 100644 --- a/config/.env.example +++ b/config/.env.example @@ -43,6 +43,11 @@ THROTTLE_RECOVER_PER_HOUR=5 THROTTLE_VOTES_PER_MINUTE=600 # How often presenter and participant pages poll for updates (ms) POLL_INTERVAL_MS=2000 +# Slide images: directory (default data/uploads; in containers e.g. /data/uploads), largest upload in MB +# (PHP's upload_max_filesize and post_max_size must allow it) and slides with an image per poll +# UPLOADS_PATH=/var/www/plenario-uploads +IMAGE_MAX_UPLOAD_MB=10 +IMAGE_MAX_PER_POLL=20 # Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s) EMBED_HEARTBEAT_SECONDS=5 EMBED_TIMEOUT_SECONDS=20 diff --git a/config/Migrations/20261114120000_AddImageToSlides.php b/config/Migrations/20261114120000_AddImageToSlides.php new file mode 100644 index 0000000..d8a2643 --- /dev/null +++ b/config/Migrations/20261114120000_AddImageToSlides.php @@ -0,0 +1,53 @@ +table('slides'); + $columns = [ + // file name inside the poll's upload directory (null = no image) + 'image' => ['string', ['null' => true, 'default' => null, 'limit' => 40]], + // alternative text, '' = purely decorative image + 'image_alt' => ['string', ['null' => true, 'default' => null, 'limit' => 255]], + // top | side | full (null = default of the slide type) + 'image_layout' => ['string', ['null' => true, 'default' => null, 'limit' => 8]], + 'image_width' => ['integer', ['null' => true, 'default' => null]], + 'image_height' => ['integer', ['null' => true, 'default' => null]], + ]; + $changed = false; + foreach ($columns as $name => [$type, $options]) { + if (!$table->hasColumn($name)) { + $table->addColumn($name, $type, $options); + $changed = true; + } + } + if ($changed) { + $table->update(); + } + } + + /** + * @return void + */ + public function down(): void + { + $table = $this->table('slides'); + foreach (['image', 'image_alt', 'image_layout', 'image_width', 'image_height'] as $name) { + if ($table->hasColumn($name)) { + $table->removeColumn($name); + } + } + $table->update(); + } +} diff --git a/config/app.php b/config/app.php index c0ecff4..1fae32f 100644 --- a/config/app.php +++ b/config/app.php @@ -50,6 +50,18 @@ return [ 'votesPerMinute' => (int)env('THROTTLE_VOTES_PER_MINUTE', 600), ], 'pollIntervalMs' => (int)env('POLL_INTERVAL_MS', 2000), + // Slide images (see \App\Service\ImageService): scaled and re-encoded as WebP, stored outside webroot. + 'images' => [ + // One sub directory per poll. In containers keep it on the volume, e.g. /data/uploads. + 'path' => (string)env('UPLOADS_PATH', ROOT . DS . 'data' . DS . 'uploads'), + // Largest accepted upload (the original, before scaling). PHP's upload_max_filesize/post_max_size must allow it. + 'maxUploadBytes' => (int)env('IMAGE_MAX_UPLOAD_MB', 10) * 1024 * 1024, + // Longest edge after scaling, in pixels. + 'maxEdge' => 1600, + 'quality' => 82, + // Slides with an image per poll. + 'maxPerPoll' => (int)env('IMAGE_MAX_PER_POLL', 20), + ], // Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva). 'embed' => [ // A visible embedded slide reports every N seconds that it is still on screen ... diff --git a/config/routes.php b/config/routes.php index e418efd..ed16c91 100644 --- a/config/routes.php +++ b/config/routes.php @@ -33,6 +33,10 @@ return function (RouteBuilder $routes): void { $builder->connect('/p/{code}/state', 'Participate::state', ['_name' => 'participate:state']) ->setPatterns(['code' => '[A-Za-z0-9-]{4,16}']) ->setPass(['code']); + // Slide images (also used by presenter and embed): random file name, only images of this poll. + $builder->connect('/p/{code}/img/{file}', 'Participate::image', ['_name' => 'participate:image']) + ->setPatterns(['code' => '[A-Za-z0-9-]{4,16}', 'file' => '[a-f0-9]{24}\.webp']) + ->setPass(['code', 'file']); $builder->connect('/p/{code}/vote', 'Participate::vote', ['_name' => 'participate:vote']) ->setPatterns(['code' => '[A-Za-z0-9-]{4,16}']) ->setPass(['code']) diff --git a/src/Command/ImagesCleanupCommand.php b/src/Command/ImagesCleanupCommand.php new file mode 100644 index 0000000..1da39a0 --- /dev/null +++ b/src/Command/ImagesCleanupCommand.php @@ -0,0 +1,72 @@ +setDescription(__('Löscht Bilddateien, die zu keiner Folie mehr gehören.')) + ->addOption('dry-run', [ + 'help' => __('Nur anzeigen, nichts löschen.'), + 'boolean' => true, + ]); + } + + /** + * @param \Cake\Console\Arguments $args Arguments + * @param \Cake\Console\ConsoleIo $io Console + * @return int + */ + public function execute(Arguments $args, ConsoleIo $io): int + { + /** @var \App\Model\Table\SlidesTable $slides */ + $slides = $this->fetchTable('Slides'); + $referenced = []; + $rows = $slides->find() + ->select(['poll_id', 'image']) + ->where(['image IS NOT' => null]) + ->disableHydration() + ->all(); + foreach ($rows as $row) { + $referenced[(int)$row['poll_id']][] = (string)$row['image']; + } + + $dryRun = (bool)$args->getOption('dry-run'); + $removed = (new ImageService())->cleanup($referenced, $dryRun); + foreach ($removed as $path) { + $io->out(($dryRun ? __('Verwaist: {0}', $path) : __('Gelöscht: {0}', $path))); + } + $io->success($dryRun + ? __('{0} verwaiste Datei(en) gefunden (nichts gelöscht).', count($removed)) + : __('{0} verwaiste Datei(en) entfernt.', count($removed))); + + return static::CODE_SUCCESS; + } +} diff --git a/src/Controller/ParticipateController.php b/src/Controller/ParticipateController.php index 8da85f2..704b390 100644 --- a/src/Controller/ParticipateController.php +++ b/src/Controller/ParticipateController.php @@ -6,6 +6,7 @@ namespace App\Controller; use App\Model\Entity\Poll; use App\Model\Entity\Slide; use App\Model\Table\PollsTable; +use App\Service\ImageService; use App\Service\PollStateService; use App\Service\VoteException; use App\Service\VoteService; @@ -49,6 +50,10 @@ class ParticipateController extends AppController public function beforeFilter(EventInterface $event): void { parent::beforeFilter($event); + if ($this->request->getParam('action') === 'image') { + // Cacheable static content: no participant id, no cookie. + return; + } $pid = (string)$this->request->getCookie(self::COOKIE, ''); if (!preg_match('/^[a-f0-9]{32}$/', $pid)) { @@ -95,6 +100,30 @@ class ParticipateController extends AppController $this->setPollInterval(); } + /** + * Serves the image of a slide of this poll. The file name is random and changes with every new + * image, so the answer can be cached for good; unknown or replaced images are 404. + * + * @param string $code Join code + * @param string $file Stored file name + * @return \Cake\Http\Response + */ + public function image(string $code, string $file): Response + { + $poll = $this->loadPoll($code); + $path = $this->fetchTable('Slides')->exists(['poll_id' => $poll->id, 'image' => $file]) + ? (new ImageService())->path($poll->id, $file) + : null; + if ($path === null) { + throw new NotFoundException(__('Bild nicht gefunden.')); + } + + return $this->response + ->withFile($path) + ->withHeader('Content-Type', 'image/webp') + ->withHeader('Cache-Control', 'private, max-age=31536000, immutable'); + } + /** * @param string $code Join code * @return \Cake\Http\Response diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index 6c99227..ebd6585 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -5,12 +5,17 @@ namespace App\Controller; use App\Model\Entity\Slide; use App\Model\Table\SlidesTable; +use App\Service\ImageException; +use App\Service\ImageService; use App\Service\QaService; use App\Service\ResetService; use App\Service\ResultsService; use App\Service\YouTubeService; +use Cake\Core\Configure; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; +use Psr\Http\Message\UploadedFileInterface; +use Throwable; /** * Slide CRUD below /admin/{token}/slides. @@ -115,6 +120,9 @@ class SlidesController extends AdminAppController $this->Slides->deleteOrFail($slide); $this->Slides->normalizePositions($this->poll->id); }); + // After the commit (a rolled back deletion keeps its image). Model.afterDeleteCommit does not fire + // inside this transaction, so the file is removed here. + (new ImageService())->delete($this->poll->id, $slide->image); $this->Flash->success(__('Folie gelöscht.')); return $this->redirect($this->adminUrl()); @@ -289,6 +297,8 @@ class SlidesController extends AdminAppController $data = (array)$this->request->getData(); // The type of an existing slide cannot change (would invalidate responses). $data['type'] = $slide->type; + // The upload is handled by prepareImage(); the marshaller must not see the file object. + unset($data['image']); $fields = ['type', 'question', 'description', 'settings', 'is_voting_open']; if ($slide->isQuiz() || $slide->isQa()) { // Quiz and Q&A voting is controlled by the presenter only. @@ -299,6 +309,7 @@ class SlidesController extends AdminAppController foreach ($youtube['errors'] as $field => $message) { $slide->setError($field, $message); } + $image = $this->prepareImage($slide, $data); $labels = SlidesTable::parseOptionLines($optionsText); $correct = []; @@ -326,11 +337,141 @@ class SlidesController extends AdminAppController } } if ($slide->hasErrors()) { - $this->Flash->error(__('Bitte prüfe deine Eingaben.')); + $this->discardImage($slide, $image); + $this->Flash->error(__('Bitte prüfe deine Eingaben.') . ($image['new'] !== null ? ' ' . __('Das Bild musst du danach erneut auswählen.') : '')); return false; } + try { + $saved = $this->persistSlide($slide, $labels, $correct, $youtube); + } catch (Throwable $e) { + $this->discardImage($slide, $image); + + throw $e; + } + if (!$saved) { + $this->discardImage($slide, $image); + + return false; + } + // Committed: the replaced (or removed) image is no longer referenced. + if ($image['old'] !== null && $image['old'] !== $slide->image) { + (new ImageService())->delete($this->poll->id, $image['old']); + } + + return true; + } + + /** + * Prepares the image of a posted slide: stores a new upload (scaled to WebP), takes over alternative + * text and layout, or removes the image (`remove_image`). The values are set on the entity; + * use discardImage() if the slide is not saved after all. + * + * @param \App\Model\Entity\Slide $slide Slide with the posted data patched + * @param array $data Request data + * @return array{new: string|null, old: string|null, original: array} + * `new` = file stored for this request, `old` = file the slide had before + */ + protected function prepareImage(Slide $slide, array $data): array + { + $fields = ['image', 'image_alt', 'image_layout', 'image_width', 'image_height']; + $original = []; + foreach ($fields as $field) { + $original[$field] = $slide->get($field); + } + $state = ['new' => null, 'old' => $slide->image, 'original' => $original]; + if (!Slide::supportsImage($slide->type)) { + return $state; + } + + // Collected and set at the end: patching a field resets its errors. + $errors = []; + $upload = $this->request->getUploadedFile('image'); + $hasUpload = $upload instanceof UploadedFileInterface && $upload->getError() !== UPLOAD_ERR_NO_FILE; + $remove = !$hasUpload && filter_var($data['remove_image'] ?? false, FILTER_VALIDATE_BOOLEAN); + + if ($hasUpload) { + if (!$slide->hasImage() && $this->Slides->countImages($this->poll->id) >= (int)Configure::read('Plenario.images.maxPerPoll', 20)) { + $errors['image'] = __( + 'Pro Umfrage sind höchstens {0} Folien mit Bild möglich. Entferne bei einer anderen Folie das Bild.', + (int)Configure::read('Plenario.images.maxPerPoll', 20), + ); + } else { + try { + $stored = (new ImageService())->store($upload, $this->poll->id); + $state['new'] = $stored['name']; + $slide->patch(['image' => $stored['name'], 'image_width' => $stored['width'], 'image_height' => $stored['height']], ['guard' => false]); + } catch (ImageException $e) { + $errors['image'] = $e->getMessage(); + } + } + } elseif ($remove) { + $slide->patch(['image' => null, 'image_alt' => null, 'image_layout' => null, 'image_width' => null, 'image_height' => null], ['guard' => false]); + } + + if (!$slide->hasImage()) { + $this->setErrors($slide, $errors); + + return $state; + } + // Without an image to describe, accessibility needs either a text or the explicit "decorative". + $alt = mb_substr(trim((string)($data['image_alt'] ?? '')), 0, Slide::IMAGE_ALT_MAX); + $decorative = filter_var($data['image_decorative'] ?? false, FILTER_VALIDATE_BOOLEAN); + if (!$decorative && $alt === '') { + $errors['image_alt'] = __('Bitte beschreibe das Bild kurz (für Menschen mit Screenreader) oder markiere es als reine Dekoration.'); + } + $layout = $data['image_layout'] ?? null; + $slide->patch([ + 'image_alt' => $decorative ? '' : $alt, + 'image_layout' => in_array($layout, Slide::IMAGE_LAYOUTS, true) ? $layout : null, + ], ['guard' => false]); + $this->setErrors($slide, $errors); + + return $state; + } + + /** + * @param \App\Model\Entity\Slide $slide Slide + * @param array $errors Field => message + * @return void + */ + protected function setErrors(Slide $slide, array $errors): void + { + foreach ($errors as $field => $message) { + $slide->setError($field, $message); + } + } + + /** + * Throws away the image stored for this request and restores the previous image values + * of the entity (the slide was not saved, the form is shown again). + * + * @param \App\Model\Entity\Slide $slide Slide + * @param array{new: string|null, old: string|null, original: array} $image State of prepareImage() + * @return void + */ + protected function discardImage(Slide $slide, array $image): void + { + if ($image['new'] !== null) { + (new ImageService())->delete($this->poll->id, $image['new']); + } + $errors = $slide->getErrors(); + $slide->patch($image['original'], ['guard' => false]); + $slide->setErrors($errors); + } + + /** + * Saves the slide and its options in one transaction. + * + * @param \App\Model\Entity\Slide $slide Slide + * @param list $labels Option labels + * @param list $correct Labels of the correct options + * @param array{errors: array, warning: string|null} $youtube Result of prepareYouTube() + * @return bool + */ + protected function persistSlide(Slide $slide, array $labels, array $correct, array $youtube): bool + { return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels, $correct, $youtube): bool { if (!$this->Slides->save($slide)) { return false; diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index a3a11ef..33154db 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -19,6 +19,11 @@ use Cake\ORM\Entity; * @property int $position * @property bool $is_hidden Prepared, but skipped in the presentation (never live) * @property array|null $settings + * @property string|null $image File name of the slide image in the poll's upload directory (see ImageService) + * @property string|null $image_alt Alternative text of the image, '' = decorative + * @property string|null $image_layout top|side|full, null = default of the type (see imageLayout()) + * @property int|null $image_width Pixels of the stored (scaled) image + * @property int|null $image_height * @property bool $is_voting_open * @property \Cake\I18n\DateTime|null $voting_started_at Quiz: start of the voting window * @property \Cake\I18n\DateTime|null $voting_ends_at Quiz: deadline (null = closed manually) @@ -135,6 +140,20 @@ class Slide extends Entity self::TYPE_ORDER => [], ]; + /** + * Where the image of a slide goes: above the results, next to the text (presenter only, + * participants' phones always show it on top) or - content slides - as large as possible. + */ + public const IMAGE_TOP = 'top'; + public const IMAGE_SIDE = 'side'; + public const IMAGE_FULL = 'full'; + public const IMAGE_LAYOUTS = [self::IMAGE_TOP, self::IMAGE_SIDE, self::IMAGE_FULL]; + + /** + * Longest alternative text. + */ + public const IMAGE_ALT_MAX = 255; + /** * @var array */ @@ -146,6 +165,41 @@ class Slide extends Entity 'is_voting_open' => true, ]; + /** + * Whether slides of this type can carry an image (everything but YouTube, which has its own media). + * + * @param string $type Slide type + * @return bool + */ + public static function supportsImage(string $type): bool + { + return $type !== self::TYPE_YOUTUBE; + } + + /** + * @return bool + */ + public function hasImage(): bool + { + return $this->image !== null && $this->image !== ''; + } + + /** + * Layout of the image: the chosen one, otherwise by type - next to the text on content slides, + * above the question's answers elsewhere. "full" only exists for content slides. + * + * @return string One of IMAGE_LAYOUTS + */ + public function imageLayout(): string + { + $layout = $this->image_layout; + if (!in_array($layout, self::IMAGE_LAYOUTS, true) || ($layout === self::IMAGE_FULL && $this->type !== self::TYPE_CONTENT)) { + return $this->type === self::TYPE_CONTENT ? self::IMAGE_SIDE : self::IMAGE_TOP; + } + + return $layout; + } + /** * @return array type => human readable label */ diff --git a/src/Model/Table/PollsTable.php b/src/Model/Table/PollsTable.php index bc1f329..1270ec7 100644 --- a/src/Model/Table/PollsTable.php +++ b/src/Model/Table/PollsTable.php @@ -4,7 +4,11 @@ declare(strict_types=1); namespace App\Model\Table; use App\Model\Entity\Poll; +use App\Service\ImageService; +use ArrayObject; use Cake\Core\Configure; +use Cake\Datasource\EntityInterface; +use Cake\Event\EventInterface; use Cake\ORM\Query\SelectQuery; use Cake\ORM\RulesChecker; use Cake\ORM\Table; @@ -54,6 +58,20 @@ class PollsTable extends Table ]); } + /** + * After the poll is gone for good, so are the image files of its slides (the slides remove + * their own; this also sweeps what a crash left behind). + * + * @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event + * @param \Cake\Datasource\EntityInterface $entity Deleted poll + * @param \ArrayObject $options Options + * @return void + */ + public function afterDeleteCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options): void + { + (new ImageService())->deletePoll((int)$entity->get('id')); + } + /** * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator diff --git a/src/Model/Table/SlidesTable.php b/src/Model/Table/SlidesTable.php index 96e1ce4..b0408b1 100644 --- a/src/Model/Table/SlidesTable.php +++ b/src/Model/Table/SlidesTable.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Model\Table; use App\Model\Entity\Slide; +use App\Service\ImageService; use App\Service\YouTubeService; use ArrayObject; use Cake\Database\Expression\QueryExpression; @@ -12,6 +13,7 @@ use Cake\Event\EventInterface; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; +use Throwable; /** * @property \App\Model\Table\PollsTable&\Cake\ORM\Association\BelongsTo $Polls @@ -109,6 +111,17 @@ class SlidesTable extends Table } } + /** + * Number of slides of a poll that carry an image (they count against `Plenario.images.maxPerPoll`). + * + * @param int $pollId Poll id + * @return int + */ + public function countImages(int $pollId): int + { + return $this->find()->where(['poll_id' => $pollId, 'image IS NOT' => null])->count(); + } + /** * Assign the next free position for new slides. * @@ -346,6 +359,36 @@ class SlidesTable extends Table $copy->position = $slide->position + 1; $copy->startFresh(); + // The copy gets its own file, so deleting one slide never takes the image of the other. + $images = new ImageService(); + $imageCopy = $slide->hasImage() ? $images->copy($slide->poll_id, (string)$slide->image) : null; + if ($imageCopy !== null) { + $copy->image = $imageCopy; + $copy->image_alt = $slide->image_alt; + $copy->image_layout = $slide->image_layout; + $copy->image_width = $slide->image_width; + $copy->image_height = $slide->image_height; + } + + try { + return $this->persistCopy($slide, $copy); + } catch (Throwable $e) { + // Rolled back: the copied file belongs to no slide. + $images->delete($slide->poll_id, $imageCopy); + + throw $e; + } + } + + /** + * Saves a duplicated slide behind its original, together with the copies of the options. + * + * @param \App\Model\Entity\Slide $slide Original incl. slide_options + * @param \App\Model\Entity\Slide $copy Prepared copy + * @return \App\Model\Entity\Slide + */ + protected function persistCopy(Slide $slide, Slide $copy): Slide + { return $this->getConnection()->transactional(function () use ($slide, $copy): Slide { $this->updateAll( ['position' => new QueryExpression('position + 1')], diff --git a/src/Service/ImageException.php b/src/Service/ImageException.php new file mode 100644 index 0000000..9a5cfc4 --- /dev/null +++ b/src/Service/ImageException.php @@ -0,0 +1,13 @@ + + */ + protected const TYPES = [ + IMAGETYPE_JPEG => 'jpeg', + IMAGETYPE_PNG => 'png', + IMAGETYPE_GIF => 'gif', + IMAGETYPE_WEBP => 'webp', + ]; + + /** + * Decoded pixels, to keep the memory use of the decoder in check (a bitmap needs 4 bytes per pixel). + */ + protected const MAX_PIXELS = 40_000_000; + + /** + * Whether the PHP installation can process images (GD with WebP). + * + * @return bool + */ + public static function isAvailable(): bool + { + return extension_loaded('gd') && function_exists('imagewebp') && function_exists('imagecreatefromstring'); + } + + /** + * Whether a stored name has the shape generated by store() (guards file system access). + * + * @param string $name File name + * @return bool + */ + public static function isValidName(string $name): bool + { + return (bool)preg_match('/^[a-f0-9]{24}\.webp$/', $name); + } + + /** + * Validates, scales and stores an upload. + * + * @param \Psr\Http\Message\UploadedFileInterface $file Uploaded file + * @param int $pollId Poll the image belongs to + * @return array{name: string, width: int, height: int} + * @throws \App\Service\ImageException If the file cannot be used + */ + public function store(UploadedFileInterface $file, int $pollId): array + { + if (!self::isAvailable()) { + throw new ImageException(__('Auf diesem Server können keine Bilder verarbeitet werden (PHP-Erweiterung GD mit WebP fehlt).')); + } + $this->assertUploaded($file); + + $bytes = (string)$file->getStream(); + $info = @getimagesizefromstring($bytes); + $type = $info === false ? null : (self::TYPES[$info[2]] ?? null); + if ($info === false || $type === null) { + throw new ImageException(__('Bitte wähle ein Bild im Format JPEG, PNG, WebP oder GIF aus.')); + } + if ($info[0] < 1 || $info[1] < 1 || $info[0] * $info[1] > self::MAX_PIXELS) { + throw new ImageException(__('Das Bild hat zu viele Pixel. Bitte wähle ein kleineres Bild (höchstens 40 Megapixel).')); + } + if ($type === 'gif') { + $this->assertNotAnimated($bytes); + } + + $image = @imagecreatefromstring($bytes); + if (!$image instanceof GdImage) { + throw new ImageException(__('Das Bild konnte nicht gelesen werden. Ist die Datei beschädigt?')); + } + if ($type === 'jpeg') { + $image = $this->orient($image, self::jpegOrientation($bytes)); + } + $image = $this->scale($image, (int)Configure::read('Plenario.images.maxEdge', 1600)); + + $name = bin2hex(random_bytes(12)) . '.webp'; + $directory = $this->directory($pollId); + if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) { + throw new ImageException(__('Das Bild konnte nicht gespeichert werden (Upload-Verzeichnis nicht beschreibbar).')); + } + // Write under a temporary name first: a half written file must never be served. + $temporary = $directory . DS . $name . '.tmp'; + $written = @imagewebp($image, $temporary, (int)Configure::read('Plenario.images.quality', 82)); + $width = imagesx($image); + $height = imagesy($image); + if (!$written || !@rename($temporary, $directory . DS . $name)) { + @unlink($temporary); + throw new ImageException(__('Das Bild konnte nicht gespeichert werden.')); + } + + return ['name' => $name, 'width' => $width, 'height' => $height]; + } + + /** + * Copies a stored image (duplicated slides get their own file, so deleting one never affects the other). + * + * @param int $pollId Poll id + * @param string $name Source file name + * @return string|null Name of the copy, null if the source file is gone + */ + public function copy(int $pollId, string $name): ?string + { + $source = $this->path($pollId, $name); + if ($source === null) { + return null; + } + $copy = bin2hex(random_bytes(12)) . '.webp'; + + return @copy($source, $this->directory($pollId) . DS . $copy) ? $copy : null; + } + + /** + * Absolute path of a stored image, null if the name is invalid or the file does not exist. + * + * @param int $pollId Poll id + * @param string $name File name + * @return string|null + */ + public function path(int $pollId, string $name): ?string + { + if (!self::isValidName($name)) { + return null; + } + $path = $this->directory($pollId) . DS . $name; + + return is_file($path) ? $path : null; + } + + /** + * Deletes one image file. Idempotent, ignores unknown names and missing files. + * + * @param int $pollId Poll id + * @param string|null $name File name + * @return void + */ + public function delete(int $pollId, ?string $name): void + { + if ($name === null || !self::isValidName($name)) { + return; + } + @unlink($this->directory($pollId) . DS . $name); + } + + /** + * Deletes all images of a poll (and its directory). + * + * @param int $pollId Poll id + * @return void + */ + public function deletePoll(int $pollId): void + { + $directory = $this->directory($pollId); + foreach (glob($directory . DS . '*') ?: [] as $file) { + if (is_file($file)) { + @unlink($file); + } + } + @rmdir($directory); + } + + /** + * Removes files that no slide refers to (left behind by aborted uploads, crashes or deleted polls). + * + * @param array> $referenced Used file names per poll id + * @param bool $dryRun Only report, delete nothing + * @return list Removed paths relative to the upload directory + */ + public function cleanup(array $referenced, bool $dryRun = false): array + { + $removed = []; + $root = $this->root(); + foreach (glob($root . DS . '*', GLOB_ONLYDIR) ?: [] as $directory) { + $pollId = basename($directory); + if (!ctype_digit($pollId)) { + continue; + } + $used = $referenced[(int)$pollId] ?? []; + foreach (glob($directory . DS . '*') ?: [] as $file) { + if (is_file($file) && !in_array(basename($file), $used, true)) { + if (!$dryRun) { + @unlink($file); + } + $removed[] = $pollId . '/' . basename($file); + } + } + if (!$dryRun) { + // Only succeeds for an empty directory. + @rmdir($directory); + } + } + + return $removed; + } + + /** + * @return string Upload root directory + */ + protected function root(): string + { + return rtrim((string)Configure::read('Plenario.images.path'), '/\\'); + } + + /** + * @param int $pollId Poll id + * @return string + */ + protected function directory(int $pollId): string + { + return $this->root() . DS . $pollId; + } + + /** + * @param \Psr\Http\Message\UploadedFileInterface $file Uploaded file + * @return void + */ + protected function assertUploaded(UploadedFileInterface $file): void + { + switch ($file->getError()) { + case UPLOAD_ERR_OK: + break; + case UPLOAD_ERR_INI_SIZE: + case UPLOAD_ERR_FORM_SIZE: + throw new ImageException(__( + 'Die Datei ist größer, als der Server erlaubt ({0}). Bitte wähle ein kleineres Bild.', + (string)ini_get('upload_max_filesize'), + )); + default: + throw new ImageException(__('Das Bild konnte nicht hochgeladen werden. Bitte versuche es noch einmal.')); + } + $max = (int)Configure::read('Plenario.images.maxUploadBytes', 10 * 1024 * 1024); + if (($file->getSize() ?? 0) > $max) { + throw new ImageException(__('Das Bild ist zu groß (höchstens {0} MB).', (int)round($max / 1024 / 1024))); + } + if (($file->getSize() ?? 0) === 0) { + throw new ImageException(__('Die Datei ist leer.')); + } + } + + /** + * GD cannot keep animations, so an animated GIF would silently become a still image. + * + * @param string $bytes GIF file + * @return void + */ + protected function assertNotAnimated(string $bytes): void + { + // Every frame starts with a graphic control extension followed by an image descriptor. + if (preg_match_all('/\x21\xF9\x04.{4}\x00[\x2C\x21]/s', $bytes) > 1) { + throw new ImageException(__('Animierte GIFs werden nicht unterstützt. Bitte wähle ein Standbild (JPEG, PNG oder WebP).')); + } + } + + /** + * Rotates/flips a decoded image according to the EXIF orientation (1-8). + * + * @param \GdImage $image Image + * @param int $orientation EXIF orientation + * @return \GdImage + */ + protected function orient(GdImage $image, int $orientation): GdImage + { + // GD rotates counter-clockwise, EXIF names the rotation that is needed to display it upright. + // 5 and 7 are mirrored first (flip, then rotate), 2 and 4 are plain mirrors. + $angle = [3 => 180, 4 => 180, 5 => 90, 6 => 270, 7 => 270, 8 => 90][$orientation] ?? 0; + $mirror = in_array($orientation, [2, 4, 5, 7], true); + if ($mirror) { + imageflip($image, IMG_FLIP_HORIZONTAL); + } + if ($angle !== 0) { + $rotated = imagerotate($image, $angle, 0); + if ($rotated instanceof GdImage) { + return $rotated; + } + } + + return $image; + } + + /** + * Scales an image down so that its longer edge is at most `$maxEdge` pixels (never up). + * The result is a true color image with alpha channel, ready for WebP. + * + * @param \GdImage $image Image + * @param int $maxEdge Longest edge in pixels + * @return \GdImage + */ + protected function scale(GdImage $image, int $maxEdge): GdImage + { + imagepalettetotruecolor($image); + imagealphablending($image, false); + imagesavealpha($image, true); + + $width = imagesx($image); + $height = imagesy($image); + $longest = max($width, $height); + if ($longest <= $maxEdge) { + return $image; + } + $factor = $maxEdge / $longest; + $scaled = imagescale($image, max(1, (int)round($width * $factor)), max(1, (int)round($height * $factor)), IMG_BICUBIC); + + if (!$scaled instanceof GdImage) { + return $image; + } + imagealphablending($scaled, false); + imagesavealpha($scaled, true); + + return $scaled; + } + + /** + * Reads the EXIF orientation of a JPEG without the exif extension (it is not always installed). + * + * @param string $bytes JPEG file + * @return int Orientation 1-8, 1 = upright/unknown + */ + public static function jpegOrientation(string $bytes): int + { + $length = strlen($bytes); + $offset = 2; + // Walk the marker segments until the one holding the Exif data (APP1). + while ($offset + 4 <= $length && $bytes[$offset] === "\xFF") { + $marker = ord($bytes[$offset + 1]); + if ($marker === 0xDA || $marker === 0xD9) { + break; + } + $size = unpack('n', substr($bytes, $offset + 2, 2))[1] ?? 0; + if ($marker === 0xE1 && substr($bytes, $offset + 4, 6) === "Exif\0\0") { + return self::tiffOrientation(substr($bytes, $offset + 10, max(0, $size - 8))); + } + $offset += 2 + $size; + } + + return 1; + } + + /** + * @param string $tiff TIFF structure of the Exif segment + * @return int Orientation 1-8 + */ + protected static function tiffOrientation(string $tiff): int + { + if (strlen($tiff) < 14) { + return 1; + } + $little = substr($tiff, 0, 2) === 'II'; + $short = $little ? 'v' : 'n'; + $long = $little ? 'V' : 'N'; + $first = unpack($long, substr($tiff, 4, 4))[1] ?? 0; + if ($first < 8 || $first + 2 > strlen($tiff)) { + return 1; + } + $entries = unpack($short, substr($tiff, $first, 2))[1] ?? 0; + for ($i = 0; $i < $entries; $i++) { + $entry = $first + 2 + $i * 12; + if ($entry + 12 > strlen($tiff)) { + break; + } + if ((unpack($short, substr($tiff, $entry, 2))[1] ?? 0) === 0x0112) { + $value = unpack($short, substr($tiff, $entry + 8, 2))[1] ?? 1; + + return $value >= 1 && $value <= 8 ? $value : 1; + } + } + + return 1; + } +} diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index ecef281..0e42360 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -9,6 +9,7 @@ use App\Model\Table\PollsTable; use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; use Cake\ORM\Locator\LocatorAwareTrait; +use Cake\Routing\Router; /** * Builds the JSON state polled by the presenter screen (/admin/{token}/state) @@ -131,7 +132,7 @@ class PollStateService 'index' => $index, 'count' => count($slides), 'hiddenCount' => $this->Slides->find()->where(['poll_id' => $poll->id, 'is_hidden' => true])->count(), - 'slide' => $current ? $this->slidePayload($current) : null, + 'slide' => $current ? $this->slidePayload($current, $poll) : null, 'results' => $current ? $this->results->forSlide($current) : null, ]; } @@ -155,7 +156,7 @@ class PollStateService 'isHidden' => $slide->is_hidden, 'index' => null, 'count' => null, - 'slide' => $this->slidePayload($slide), + 'slide' => $this->slidePayload($slide, $poll), 'results' => $this->results->forSlide($slide), ]; } @@ -208,7 +209,7 @@ class PollStateService $words !== null || $qa !== null ? 0 : (int)$hasResponded, $slide?->modified?->toUnixString() ?? 0, ]), - 'slide' => $showResults ? $this->slidePayload($slide) : null, + 'slide' => $showResults ? $this->slidePayload($slide, $poll) : null, 'results' => $showResults ? $this->participantResults($slide) : null, 'words' => $words, 'quiz' => $quiz, @@ -398,9 +399,10 @@ class PollStateService /** * @param \App\Model\Entity\Slide $slide Slide + * @param \App\Model\Entity\Poll $poll Poll of the slide (the image URL contains its join code) * @return array */ - public function slidePayload(Slide $slide): array + public function slidePayload(Slide $slide, Poll $poll): array { return [ 'id' => $slide->id, @@ -415,6 +417,14 @@ class PollStateService 'embedUrl' => $slide->youtubeEmbedUrl(), 'watchUrl' => $slide->youtubeWatchUrl(), ] : null, + // Image of the slide: URL (random file name), alternative text ('' = decorative), layout (top|side|full) + 'image' => $slide->hasImage() ? [ + 'url' => Router::url(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image]), + 'alt' => (string)$slide->image_alt, + 'layout' => $slide->imageLayout(), + 'width' => $slide->image_width, + 'height' => $slide->image_height, + ] : null, ]; } } diff --git a/templates/Admin/index.php b/templates/Admin/index.php index 623ed97..8ed9832 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -87,6 +87,7 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
typeLabel()) ?> + hasImage()) : ?>🖼 is_hidden) : ?> isInteractive()) : ?> diff --git a/templates/Admin/present.php b/templates/Admin/present.php index dfc9a84..74e012d 100644 --- a/templates/Admin/present.php +++ b/templates/Admin/present.php @@ -38,6 +38,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);

+
diff --git a/templates/Embed/view.php b/templates/Embed/view.php index e624f71..ca8a6eb 100644 --- a/templates/Embed/view.php +++ b/templates/Embed/view.php @@ -42,6 +42,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);

question) ?>

+
diff --git a/templates/Participate/view.php b/templates/Participate/view.php index 5e6f43b..155b15b 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -110,6 +110,7 @@ $countdown = function (?int $remaining): string { description) : ?>
Format->text($slide->description) ?>
+ element('slide_image', compact('slide', 'poll')) ?> @@ -118,6 +119,7 @@ $countdown = function (?int $remaining): string { description) : ?>
Format->text($slide->description) ?>
+ element('slide_image', compact('slide', 'poll')) ?> diff --git a/templates/Slides/form.php b/templates/Slides/form.php index 2214b6a..9d89d10 100644 --- a/templates/Slides/form.php +++ b/templates/Slides/form.php @@ -31,7 +31,7 @@ $optionsError = $slide->getError('options_text');

typeLabel()) ?>

- Form->create($slide, ['url' => $formUrl]) ?> + Form->create($slide, ['url' => $formUrl, 'type' => 'file']) ?> Form->hidden('type') ?> isYouTube()) : $urlError = $slide->getError('youtube_url'); @@ -116,6 +116,8 @@ $optionsError = $slide->getError('options_text'); ]) ?>

+ element('slide_image_fields', compact('slide', 'poll')) ?> + type === 'choice') : ?>
diff --git a/templates/element/slide_image.php b/templates/element/slide_image.php new file mode 100644 index 0000000..057a347 --- /dev/null +++ b/templates/element/slide_image.php @@ -0,0 +1,19 @@ +hasImage()) { + return; +} +?> +
+ <?= h((string)$slide->image_alt) ?>image_width && $slide->image_height ? 'width="' . (int)$slide->image_width . '" height="' . (int)$slide->image_height . '"' : '' ?> + decoding="async"> +
diff --git a/templates/element/slide_image_fields.php b/templates/element/slide_image_fields.php new file mode 100644 index 0000000..4f8b731 --- /dev/null +++ b/templates/element/slide_image_fields.php @@ -0,0 +1,94 @@ +type)) { + return; +} +$request = $this->getRequest(); +$posted = $request->is(['post', 'put', 'patch']); +$hasImage = $slide->hasImage(); +// After a failed save the posted values are shown again. +$alt = $posted ? (string)$request->getData('image_alt', '') : (string)$slide->image_alt; +$decorative = $posted + ? filter_var($request->getData('image_decorative'), FILTER_VALIDATE_BOOLEAN) + : ($hasImage && $slide->image_alt === ''); +$layout = $posted && in_array($request->getData('image_layout'), Slide::IMAGE_LAYOUTS, true) + ? (string)$request->getData('image_layout') + : $slide->imageLayout(); +$layouts = [ + Slide::IMAGE_TOP => __('Oben (über den Antworten bzw. Ergebnissen)'), + Slide::IMAGE_SIDE => __('Daneben (Bild links, Text und Ergebnis rechts)'), +]; +if ($slide->type === Slide::TYPE_CONTENT) { + $layouts[Slide::IMAGE_FULL] = __('Bildschirm füllen (Bild so groß wie möglich)'); +} +$imageError = $slide->getError('image'); +$altError = $slide->getError('image_alt'); +$maxMb = (int)round((int)Configure::read('Plenario.images.maxUploadBytes', 10 * 1024 * 1024) / 1024 / 1024); +?> +
+ + +

+ + +
+ <?= h((string)$slide->image_alt) ?> +
+ Form->control('remove_image', [ + 'type' => 'checkbox', + 'label' => __('Bild entfernen'), + 'value' => '1', + 'hiddenField' => false, + 'checked' => false, + ]) ?> + +
+ + > +

+ +
+ +
+
+ + > +

+ +
+ +
+ Form->control('image_decorative', [ + 'type' => 'checkbox', + 'label' => __('Reine Dekoration (keine Beschreibung nötig)'), + 'value' => '1', + 'hiddenField' => false, + 'checked' => $decorative, + ]) ?> +
+ + Form->radio('image_layout', array_map( + fn($value, $text) => ['value' => $value, 'text' => $text], + array_keys($layouts), + $layouts, + ), ['value' => $layout]) ?> +

+
+ +
diff --git a/tests/TestCase/Controller/SlideImageTest.php b/tests/TestCase/Controller/SlideImageTest.php new file mode 100644 index 0000000..c9e1ec6 --- /dev/null +++ b/tests/TestCase/Controller/SlideImageTest.php @@ -0,0 +1,339 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + protected function tearDown(): void + { + $this->clearImages(); + parent::tearDown(); + } + + /** + * Creates a content slide with an uploaded image through the form. + * + * @return array{0: \App\Model\Entity\Poll, 1: string, 2: \App\Model\Entity\Slide} + */ + protected function slideWithImage(array $data = []): array + { + [$poll, $token] = $this->createPoll(); + $this->postWithImage("/admin/$token/slides/add?type=content", $data + [ + 'type' => 'content', + 'question' => 'Mit Bild', + 'image_alt' => 'Ein roter Kreis', + ], $this->makeImage(3000, 2000)); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->first(); + + return [$poll, $token, $slide]; + } + + public function testUploadStoresScaledImageWithAltAndLayout(): void + { + [$poll, $token, $slide] = $this->slideWithImage(['image_layout' => 'full']); + + $this->assertRedirect(['_name' => 'admin', 'token' => $token]); + $this->assertNotNull($slide); + $this->assertTrue($slide->hasImage()); + $this->assertSame('Ein roter Kreis', $slide->image_alt); + $this->assertSame([1600, 1067], [$slide->image_width, $slide->image_height]); + $this->assertSame(Slide::IMAGE_FULL, $slide->imageLayout()); + $this->assertSame([$slide->image], $this->storedImages($poll->id)); + } + + public function testLayoutDefaultsByType(): void + { + [$poll, , $content] = $this->slideWithImage(); + $this->assertSame(Slide::IMAGE_SIDE, $content->imageLayout()); + + $choice = $this->createSlide($poll, Slide::TYPE_CHOICE, ['image' => 'a', 'image_layout' => 'full']); + $this->assertSame(Slide::IMAGE_TOP, $choice->imageLayout(), 'full exists for content slides only'); + } + + public function testImageNeedsAltTextOrDecorativeFlag(): void + { + [$poll, $token] = $this->createPoll(); + $this->postWithImage("/admin/$token/slides/add?type=content", [ + 'type' => 'content', + 'question' => 'Ohne Text', + ], $this->makeImage()); + + $this->assertResponseOk(); + $this->assertResponseContains('Bitte beschreibe das Bild'); + $this->assertSame(0, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + $this->assertSame([], $this->storedImages($poll->id), 'no file left behind'); + + $this->postWithImage("/admin/$token/slides/add?type=content", [ + 'type' => 'content', + 'question' => 'Dekoration', + 'image_decorative' => '1', + ], $this->makeImage()); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail(); + $this->assertSame('', $slide->image_alt); + $this->assertTrue($slide->hasImage()); + } + + public function testRejectsFilesThatAreNoImages(): void + { + [$poll, $token] = $this->createPoll(); + $path = tempnam(sys_get_temp_dir(), 'plen'); + $this->imageFiles[] = $path; + file_put_contents($path, 'just text'); + + $this->postWithImage("/admin/$token/slides/add?type=content", [ + 'type' => 'content', + 'question' => 'Kein Bild', + 'image_alt' => 'x', + ], $path, UPLOAD_ERR_OK, 'text.jpg'); + + $this->assertResponseContains('JPEG, PNG, WebP oder GIF'); + $this->assertSame(0, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + } + + public function testFailedSaveKeepsTheOldImage(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + $old = $slide->image; + + $this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [ + 'question' => '', + 'image_alt' => 'neu', + ], $this->makeImage(100, 100)); + + $this->assertResponseContains('Bitte prüfe deine Eingaben'); + $this->assertSame([$old], $this->storedImages($poll->id)); + $this->assertSame($old, $this->slidesTable()->get($slide->id)->image); + } + + public function testQuotaPerPoll(): void + { + Configure::write('Plenario.images.maxPerPoll', 1); + [$poll, $token] = $this->slideWithImage(); + + $this->postWithImage("/admin/$token/slides/add?type=content", [ + 'type' => 'content', + 'question' => 'Zweites Bild', + 'image_alt' => 'x', + ], $this->makeImage()); + + $this->assertResponseContains('höchstens 1 Folien mit Bild'); + $this->assertCount(1, $this->storedImages($poll->id)); + $this->assertSame(1, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + } + + public function testReplacingAnImageDeletesTheOldFile(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + $old = $slide->image; + + $this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [ + 'question' => 'Mit Bild', + 'image_alt' => 'Neu', + ], $this->makeImage(300, 200)); + + $slide = $this->slidesTable()->get($slide->id); + $this->assertNotSame($old, $slide->image); + $this->assertSame([$slide->image], $this->storedImages($poll->id)); + $this->assertSame([300, 200], [$slide->image_width, $slide->image_height]); + } + + public function testEditingWithoutUploadKeepsImageAndAllowsAltChange(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + + $this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [ + 'question' => 'Mit Bild', + 'image_alt' => 'Anderer Text', + 'image_layout' => 'top', + ], $this->makeImage(), UPLOAD_ERR_NO_FILE); + + $after = $this->slidesTable()->get($slide->id); + $this->assertSame($slide->image, $after->image); + $this->assertSame('Anderer Text', $after->image_alt); + $this->assertSame(Slide::IMAGE_TOP, $after->imageLayout()); + $this->assertSame([$slide->image], $this->storedImages($poll->id)); + } + + public function testRemoveImage(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + + $this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Mit Bild', 'remove_image' => '1']); + $this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Mit Bild', 'remove_image' => '1']); + + $after = $this->slidesTable()->get($slide->id); + $this->assertFalse($after->hasImage()); + $this->assertNull($after->image_alt); + $this->assertSame([], $this->storedImages($poll->id)); + } + + public function testDeletingTheSlideDeletesTheFile(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + $other = $this->createSlide($poll, Slide::TYPE_OPEN); + + $this->post("/admin/$token/slides/{$other->id}/delete"); + $this->assertCount(1, $this->storedImages($poll->id), 'another slide does not touch the image'); + + $this->post("/admin/$token/slides/{$slide->id}/delete"); + + $this->assertSame([], $this->storedImages($poll->id)); + } + + public function testDeletingThePollDeletesAllImages(): void + { + [$poll, $token] = $this->slideWithImage(); + $this->postWithImage("/admin/$token/slides/add?type=content", [ + 'type' => 'content', + 'question' => 'Zweites', + 'image_alt' => 'x', + ], $this->makeImage()); + $this->assertCount(2, $this->storedImages($poll->id)); + + $this->post("/admin/$token/delete", ['confirm_code' => $poll->join_code]); + + $this->assertSame([], $this->storedImages($poll->id)); + $this->assertDirectoryDoesNotExist($this->uploadRoot() . DS . $poll->id); + } + + public function testDuplicateGetsItsOwnFile(): void + { + [$poll, $token, $slide] = $this->slideWithImage(['image_layout' => 'top']); + + $this->post("/admin/$token/slides/{$slide->id}/duplicate"); + + $slides = $this->slidesTable()->listForPoll($poll->id); + $copy = $slides[1]; + $this->assertTrue($copy->hasImage()); + $this->assertNotSame($slide->image, $copy->image); + $this->assertSame('Ein roter Kreis', $copy->image_alt); + $this->assertSame(Slide::IMAGE_TOP, $copy->imageLayout()); + $this->assertCount(2, $this->storedImages($poll->id)); + + $this->post("/admin/$token/slides/{$copy->id}/delete"); + + $this->assertSame([$slide->image], $this->storedImages($poll->id), 'the original keeps its image'); + } + + public function testResetKeepsImages(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + + $this->post("/admin/$token/reset"); + + $this->assertTrue($this->slidesTable()->get($slide->id)->hasImage()); + $this->assertCount(1, $this->storedImages($poll->id)); + } + + public function testYouTubeSlidesIgnoreImages(): void + { + $this->assertFalse(Slide::supportsImage(Slide::TYPE_YOUTUBE)); + $this->assertTrue(Slide::supportsImage(Slide::TYPE_QUIZ)); + } + + public function testImageIsServedForTheOwnPollOnly(): void + { + [$poll, , $slide] = $this->slideWithImage(); + [$otherPoll] = $this->createPoll('Andere'); + + $this->get(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image]); + + $this->assertResponseOk(); + $this->assertContentType('image/webp'); + $this->assertHeaderContains('Cache-Control', 'immutable'); + $this->assertHeaderContains('Cache-Control', 'private'); + $this->assertSame(IMAGETYPE_WEBP, getimagesizefromstring((string)$this->_response->getBody())[2]); + $this->assertCookieNotSet('plenario_pid'); + + $this->get(['_name' => 'participate:image', 'code' => $otherPoll->join_code, 'file' => $slide->image]); + $this->assertResponseCode(404); + + $this->get('/p/' . $poll->join_code . '/img/' . str_repeat('a', 24) . '.webp'); + $this->assertResponseCode(404); + $this->get('/p/' . $poll->join_code . '/img/..%2F..%2Fapp.php'); + $this->assertResponseCode(404); + } + + public function testImageIsGoneWhenReplaced(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + $old = $slide->image; + $this->postWithImage("/admin/$token/slides/{$slide->id}/edit", [ + 'question' => 'Mit Bild', + 'image_alt' => 'Neu', + ], $this->makeImage(300, 200)); + + $this->get(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $old]); + + $this->assertResponseCode(404); + } + + public function testPresenterStateAndParticipantPageShowTheImage(): void + { + [$poll, $token, $slide] = $this->slideWithImage(); + $poll = $this->goLive($poll, $slide); + + $this->get("/admin/$token/state"); + $payload = json_decode((string)$this->_response->getBody(), true)['slide']; + $this->assertSame('Ein roter Kreis', $payload['image']['alt']); + $this->assertSame('side', $payload['image']['layout']); + $this->assertSame("/p/{$poll->join_code}/img/{$slide->image}", $payload['image']['url']); + + $this->get('/p/' . $poll->join_code); + $this->assertResponseOk(); + $this->assertResponseContains('/p/' . $poll->join_code . '/img/' . $slide->image); + $this->assertResponseContains('alt="Ein roter Kreis"'); + $this->assertResponseContains('width="1600" height="1067"'); + } + + public function testSlideWithoutImageHasNoImagePayload(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_OPEN); + $this->goLive($poll, $slide); + + $this->get("/admin/$token/state"); + + $this->assertNull(json_decode((string)$this->_response->getBody(), true)['slide']['image']); + } + + public function testEditFormShowsImageFields(): void + { + [, $token, $slide] = $this->slideWithImage(); + + $this->get("/admin/$token/slides/{$slide->id}/edit"); + + $this->assertResponseOk(); + $this->assertResponseContains('enctype="multipart/form-data"'); + $this->assertResponseContains('name="remove_image"'); + $this->assertResponseContains('value="Ein roter Kreis"'); + $this->assertResponseContains('Bildschirm füllen'); + } +} diff --git a/tests/TestCase/ImageTestTrait.php b/tests/TestCase/ImageTestTrait.php new file mode 100644 index 0000000..ae91d37 --- /dev/null +++ b/tests/TestCase/ImageTestTrait.php @@ -0,0 +1,106 @@ + + */ + protected array $imageFiles = []; + + /** + * Writes a picture to a temporary file. + * + * @param int $width Width in pixels + * @param int $height Height in pixels + * @param string $format jpeg|png|gif|webp + * @return string Path + */ + protected function makeImage(int $width = 400, int $height = 300, string $format = 'jpeg'): string + { + $image = imagecreatetruecolor($width, $height); + imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, (int)imagecolorallocate($image, 200, 40, 40)); + imagefilledellipse($image, intdiv($width, 2), intdiv($height, 2), intdiv($width, 2), intdiv($height, 2), (int)imagecolorallocate($image, 250, 250, 250)); + $path = tempnam(sys_get_temp_dir(), 'plen'); + match ($format) { + 'png' => imagepng($image, $path), + 'gif' => imagegif($image, $path), + 'webp' => imagewebp($image, $path), + default => imagejpeg($image, $path), + }; + $this->imageFiles[] = $path; + + return $path; + } + + /** + * Posts a form with an uploaded file in the field `image` (the test request carries files + * separately from the form data). + * + * @param string $url URL + * @param array $data Form data + * @param string|null $path File to upload, null = no upload field at all + * @param int $error Upload error code (UPLOAD_ERR_NO_FILE = field left empty) + * @param string $name Client file name + * @return void + */ + protected function postWithImage(string $url, array $data, ?string $path, int $error = UPLOAD_ERR_OK, string $name = 'bild.jpg'): void + { + $this->_request['files'] = $path === null ? [] : [ + 'image' => new UploadedFile($path, (int)filesize($path), $error, $name, 'image/jpeg'), + ]; + try { + $this->post($url, $data); + } finally { + $this->_request['files'] = []; + } + } + + /** + * @return string The upload directory of the tests + */ + protected function uploadRoot(): string + { + return (string)Configure::read('Plenario.images.path'); + } + + /** + * Files stored for a poll. + * + * @param int $pollId Poll id + * @return list File names + */ + protected function storedImages(int $pollId): array + { + $files = array_map('basename', glob($this->uploadRoot() . DS . $pollId . DS . '*') ?: []); + sort($files); + + return $files; + } + + /** + * Removes temporary pictures and the upload directory of the tests. + * + * @return void + */ + protected function clearImages(): void + { + foreach ($this->imageFiles as $file) { + @unlink($file); + } + $this->imageFiles = []; + foreach (glob($this->uploadRoot() . DS . '*', GLOB_ONLYDIR) ?: [] as $directory) { + array_map('unlink', glob($directory . DS . '*') ?: []); + @rmdir($directory); + } + } +} diff --git a/tests/TestCase/Service/ImageServiceTest.php b/tests/TestCase/Service/ImageServiceTest.php new file mode 100644 index 0000000..5bd6833 --- /dev/null +++ b/tests/TestCase/Service/ImageServiceTest.php @@ -0,0 +1,188 @@ +images = new ImageService(); + } + + protected function tearDown(): void + { + $this->clearImages(); + parent::tearDown(); + } + + protected function file(string $path, int $error = UPLOAD_ERR_OK): UploadedFile + { + return new UploadedFile($path, (int)filesize($path), $error, 'bild.jpg', 'image/jpeg'); + } + + public function testLargeImageIsScaledDownAndStoredAsWebp(): void + { + $stored = $this->images->store($this->file($this->makeImage(3200, 2000)), 7); + + $this->assertSame(1600, $stored['width']); + $this->assertSame(1000, $stored['height']); + $this->assertTrue(ImageService::isValidName($stored['name'])); + $path = $this->images->path(7, $stored['name']); + $this->assertNotNull($path); + $info = getimagesize($path); + $this->assertSame(IMAGETYPE_WEBP, $info[2]); + $this->assertSame([1600, 1000], [$info[0], $info[1]]); + } + + public function testSmallImageIsNotEnlarged(): void + { + $stored = $this->images->store($this->file($this->makeImage(300, 200, 'png')), 7); + + $this->assertSame([300, 200], [$stored['width'], $stored['height']]); + } + + public function testAcceptsGifAndWebp(): void + { + foreach (['gif', 'webp'] as $format) { + $stored = $this->images->store($this->file($this->makeImage(40, 30, $format)), 7); + $this->assertSame([40, 30], [$stored['width'], $stored['height']], $format); + } + } + + public function testExifOrientationIsApplied(): void + { + // A landscape JPEG that says "rotate by 90°" ends up as a portrait picture. + $jpeg = (string)file_get_contents($this->makeImage(200, 100)); + $path = $this->makeImage(1, 1); + file_put_contents($path, substr($jpeg, 0, 2) . $this->exifOrientation(6) . substr($jpeg, 2)); + + $this->assertSame(6, ImageService::jpegOrientation((string)file_get_contents($path))); + $stored = $this->images->store($this->file($path), 7); + + $this->assertSame([100, 200], [$stored['width'], $stored['height']]); + } + + public function testJpegWithoutExifIsUpright(): void + { + $this->assertSame(1, ImageService::jpegOrientation((string)file_get_contents($this->makeImage(20, 10)))); + $this->assertSame(1, ImageService::jpegOrientation('not a jpeg')); + } + + public function testRejectsNonImages(): void + { + $path = tempnam(sys_get_temp_dir(), 'plen'); + $this->imageFiles[] = $path; + file_put_contents($path, 'expectException(ImageException::class); + $this->images->store($this->file($path), 7); + } + + public function testRejectsSvg(): void + { + $path = tempnam(sys_get_temp_dir(), 'plen'); + $this->imageFiles[] = $path; + file_put_contents($path, ''); + + $this->expectException(ImageException::class); + $this->images->store($this->file($path), 7); + } + + public function testRejectsAnimatedGif(): void + { + $header = 'GIF89a' . "\x01\x00\x01\x00" . "\x80\x00\x00" . "\x00\x00\x00\xFF\xFF\xFF"; + $frame = "\x21\xF9\x04\x00\x0A\x00\x00\x00" . "\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00" . "\x02\x02\x44\x01\x00"; + $path = tempnam(sys_get_temp_dir(), 'plen'); + $this->imageFiles[] = $path; + file_put_contents($path, $header . $frame . $frame . "\x3B"); + + $this->expectException(ImageException::class); + $this->expectExceptionMessage('Animierte GIFs'); + $this->images->store($this->file($path), 7); + } + + public function testRejectsUploadErrors(): void + { + $path = $this->makeImage(); + + $this->expectException(ImageException::class); + $this->images->store($this->file($path, UPLOAD_ERR_PARTIAL), 7); + } + + public function testDeleteCopyAndPollCleanup(): void + { + $first = $this->images->store($this->file($this->makeImage()), 7)['name']; + $copy = $this->images->copy(7, $first); + + $this->assertNotNull($copy); + $this->assertNotSame($first, $copy); + $this->assertCount(2, $this->storedImages(7)); + + $this->images->delete(7, $first); + $this->images->delete(7, $first); + $this->images->delete(7, null); + $this->images->delete(7, '../../evil.php'); + $this->assertSame([$copy], $this->storedImages(7)); + $this->assertNull($this->images->copy(7, $first), 'copy of a missing file'); + + $this->images->deletePoll(7); + $this->images->deletePoll(7); + $this->assertSame([], $this->storedImages(7)); + $this->assertDirectoryDoesNotExist($this->uploadRoot() . DS . '7'); + } + + public function testPathRejectsForeignNames(): void + { + $name = $this->images->store($this->file($this->makeImage()), 7)['name']; + + $this->assertNotNull($this->images->path(7, $name)); + $this->assertNull($this->images->path(8, $name), 'other poll'); + $this->assertNull($this->images->path(7, '../7/' . $name)); + $this->assertNull($this->images->path(7, 'image.php')); + } + + public function testCleanupRemovesOrphansOnly(): void + { + $kept = $this->images->store($this->file($this->makeImage()), 7)['name']; + $orphan = $this->images->store($this->file($this->makeImage()), 7)['name']; + $gone = $this->images->store($this->file($this->makeImage()), 8)['name']; + + $this->assertEqualsCanonicalizing(['7/' . $orphan, '8/' . $gone], $this->images->cleanup([7 => [$kept]], true)); + $this->assertCount(2, $this->storedImages(7), 'dry run deletes nothing'); + + $removed = $this->images->cleanup([7 => [$kept]]); + + $this->assertEqualsCanonicalizing(['7/' . $orphan, '8/' . $gone], $removed); + $this->assertSame([$kept], $this->storedImages(7)); + $this->assertSame([], $this->storedImages(8)); + $this->assertSame([], $this->images->cleanup([7 => [$kept]]), 'second run changes nothing'); + } + + /** + * An Exif segment (big endian) that only contains the orientation. + * + * @param int $orientation 1-8 + * @return string + */ + protected function exifOrientation(int $orientation): string + { + $tiff = "MM\x00\x2A\x00\x00\x00\x08" . "\x00\x01" . "\x01\x12\x00\x03\x00\x00\x00\x01" . pack('n', $orientation) . "\x00\x00" . "\x00\x00\x00\x00"; + + return "\xFF\xE1" . pack('n', 2 + 6 + strlen($tiff)) . "Exif\x00\x00" . $tiff; + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 6a36a98..0ed35da 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -34,6 +34,9 @@ if (empty($_SERVER['HTTP_HOST']) && !Configure::read('App.fullBaseUrl')) { Configure::write('App.fullBaseUrl', 'http://localhost'); } +// Slide images of the tests never touch the real upload directory. +Configure::write('Plenario.images.path', TMP . 'tests-images'); + // Fixate now to avoid one-second-leap-issues Chronos::setTestNow(Chronos::now()); diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 9c1b017..da1d5ee 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -694,6 +694,19 @@ body.present { .stage--video .stage__description { font-size: clamp(1rem, 1.6vw, 1.3rem); } .stage--content .stage__description { color: var(--text); font-size: clamp(1.3rem, 2.6vw, 2.2rem); } .stage__results { font-size: clamp(1rem, 1.8vw, 1.5rem); margin-top: 2vh; } +/* slide images: above the results (default), next to the text (side) or as large as possible (full) */ +.stage__image { margin: 1vh auto 0; } +.stage__image img { display: block; max-width: 100%; max-height: 38vh; width: auto; height: auto; margin: 0 auto; object-fit: contain; border-radius: 8px; } +.stage--img-side .stage__main { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); grid-auto-rows: min-content; align-content: center; column-gap: 4vw; } +.stage--img-side .stage__main > * { grid-column: 2; } +.stage--img-side .stage__main > .stage__image { grid-column: 1; grid-row: 1 / span 5; align-self: center; margin: 0; } +.stage--img-side .stage__image img { max-height: 68vh; } +.stage--img-full .stage__image img { max-height: 66vh; } +.stage--img-full .stage__question { font-size: clamp(1.5rem, 3vw, 2.6rem); } +@media (max-width: 800px) { + .stage--img-side .stage__main { display: flex; } + .stage--img-side .stage__image img { max-height: 38vh; } +} .stage .bar__track { height: 1.1em; } /* scale on stage: big average next to a compact donut */ .stage .scale-results__row { gap: 2vw; } @@ -779,3 +792,12 @@ body.present { body:has(dialog[open]) { overflow: hidden; } .slide-item__actions form { display: contents; } .slide-item__actions button:disabled, .admin-head__actions button:disabled { opacity: .6; cursor: progress; } + +/* slide images: participant page and slide form */ +.slide-image { margin: 1em 0; } +.slide-image img { display: block; max-width: 100%; height: auto; margin: 0 auto; border-radius: 8px; } +.image-fields, .image-fields__layout { border: 0; padding: 0; margin: 0 0 16px; min-width: 0; } +.image-fields > legend { font-weight: 600; padding: 0; margin-bottom: .5em; } +.image-fields__layout > legend { padding: 0; margin-bottom: .25em; } +.image-fields__current { margin: 0 0 .75em; } +.image-fields__current img { display: block; max-width: 100%; max-height: 180px; width: auto; height: auto; border-radius: 6px; } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 46346ca..0282ed9 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -1293,6 +1293,33 @@ } } + /** Shows the image of the slide (layout: top | side | full via stage--img-* classes); the stays while the file stays. */ + function renderImage(slide) { + var figure = q('[data-image]'); + var image = slide && slide.image ? slide.image : null; + ['top', 'side', 'full'].forEach(function (layout) { + root.classList.toggle('stage--img-' + layout, !!image && image.layout === layout); + }); + figure.hidden = !image; + if (!image) { + figure.textContent = ''; + return; + } + var img = figure.querySelector('img'); + if (!img) { + img = document.createElement('img'); + figure.appendChild(img); + } + if (img.getAttribute('src') !== image.url) { + img.setAttribute('src', image.url); + } + img.setAttribute('alt', image.alt || ''); + if (image.width && image.height) { + img.setAttribute('width', image.width); + img.setAttribute('height', image.height); + } + } + function render(newState) { var serialized = JSON.stringify(newState); if (serialized === last) { @@ -1332,6 +1359,7 @@ : 'Drücke → um zu starten.'); q('[data-results]').innerHTML = ''; renderMedia(null); + renderImage(null); root.classList.remove('stage--video'); q('[data-voting]').hidden = true; setText('[data-participants]', ''); @@ -1352,6 +1380,7 @@ root.classList.toggle('stage--content', !slide.isInteractive); root.classList.toggle('stage--video', slide.type === 'youtube'); renderMedia(slide); + renderImage(slide); root.classList.toggle('stage--closed', closed); root.classList.toggle('stage--qa', !!qaStage); -- 2.54.1