Merge pull request 'Add optional images to slides' (#80) from feature/slide-images into main
Reviewed-on: #80
This commit was merged in pull request #80.
This commit is contained in:
commit
492872750c
30 files changed
+1705
-11
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
+8
-3
@@ -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 \
|
||||
|
||||
@@ -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
|
||||
@@ -149,7 +152,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:
|
||||
@@ -244,6 +248,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Migrations\BaseMigration;
|
||||
|
||||
/**
|
||||
* One optional image per slide. The (scaled) file lives in the upload directory, see
|
||||
* \App\Service\ImageService; the table only holds its random file name and how to show it.
|
||||
*/
|
||||
class AddImageToSlides extends BaseMigration
|
||||
{
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$table = $this->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();
|
||||
}
|
||||
}
|
||||
@@ -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 ...
|
||||
|
||||
@@ -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'])
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Service\ImageService;
|
||||
use Cake\Command\Command;
|
||||
use Cake\Console\Arguments;
|
||||
use Cake\Console\ConsoleIo;
|
||||
use Cake\Console\ConsoleOptionParser;
|
||||
|
||||
/**
|
||||
* Removes image files that no slide refers to any more (aborted uploads, crashes while deleting).
|
||||
* Idempotent, safe to run at any time, e.g. from cron.
|
||||
*
|
||||
* Usage: bin/cake images_cleanup [--dry-run]
|
||||
*/
|
||||
class ImagesCleanupCommand extends Command
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public static function defaultName(): string
|
||||
{
|
||||
return 'images_cleanup';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Cake\Console\ConsoleOptionParser $parser Parser
|
||||
* @return \Cake\Console\ConsoleOptionParser
|
||||
*/
|
||||
protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
|
||||
{
|
||||
return $parser
|
||||
->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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<string, mixed> $data Request data
|
||||
* @return array{new: string|null, old: string|null, original: array<string, mixed>}
|
||||
* `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<string, string> $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<string, mixed>} $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<string> $labels Option labels
|
||||
* @param list<string> $correct Labels of the correct options
|
||||
* @param array{errors: array<string, string>, 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;
|
||||
|
||||
@@ -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<string, mixed>|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<string, bool>
|
||||
*/
|
||||
@@ -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<string, string> type => human readable label
|
||||
*/
|
||||
|
||||
@@ -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<string, mixed> $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
|
||||
|
||||
@@ -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')],
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Thrown when an uploaded image is rejected. The message is safe to show to the admin.
|
||||
*/
|
||||
class ImageException extends RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use GdImage;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
|
||||
/**
|
||||
* Stores the images of slides.
|
||||
*
|
||||
* Uploads are decoded, rotated upright (EXIF orientation), scaled down to `Plenario.images.maxEdge`
|
||||
* and written as WebP. Re-encoding drops all metadata (GPS position of phone photos!) and defuses
|
||||
* files that are valid in two formats. Only the result is kept, never the original.
|
||||
*
|
||||
* Files live outside webroot in `{Plenario.images.path}/{poll id}/{random name}.webp` and are served
|
||||
* by ParticipateController::image(). Replacing an image creates a new random name, so the URL changes
|
||||
* and browsers can cache images forever.
|
||||
*
|
||||
* Deleting is idempotent: a missing file is fine. The database is the source of truth; files left
|
||||
* behind by a crash are removed by `bin/cake images_cleanup`.
|
||||
*/
|
||||
class ImageService
|
||||
{
|
||||
/**
|
||||
* Source formats that are accepted (animated GIFs are not, see assertNotAnimated()).
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
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<int, list<string>> $referenced Used file names per poll id
|
||||
* @param bool $dryRun Only report, delete nothing
|
||||
* @return list<string> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, mixed>
|
||||
*/
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide-
|
||||
<div class="slide-item__meta">
|
||||
<span class="badge badge--type-<?= h($slide->type) ?>"><?= h($slide->typeLabel()) ?></span>
|
||||
<?php if ($isCurrent) : ?><span class="badge badge--live"><?= __('live') ?></span><?php endif; ?>
|
||||
<?php if ($slide->hasImage()) : ?><span class="badge" title="<?= h(__('Die Folie hat ein Bild')) ?>">🖼 <?= __('Bild') ?></span><?php endif; ?>
|
||||
<?php if ($slide->is_hidden) : ?><span class="badge badge--off" title="<?= __('Wird beim Präsentieren übersprungen und fehlt im PDF-Export') ?>"><?= __('ausgeblendet') ?></span><?php endif; ?>
|
||||
<?php if ($slide->isInteractive()) : ?>
|
||||
<span class="muted"><?= __n('{0} Antwort', '{0} Antworten', $count, $count) ?></span>
|
||||
|
||||
@@ -38,6 +38,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);
|
||||
<h1 class="stage__question" data-question><?= __('Lade …') ?></h1>
|
||||
<div class="stage__description formatted" data-description></div>
|
||||
<div class="stage__media" data-media hidden></div>
|
||||
<figure class="stage__image" data-image hidden></figure>
|
||||
<div class="stage__results" data-results></div>
|
||||
</main>
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);
|
||||
<h1 class="stage__question" data-question><?= h($slide->question) ?></h1>
|
||||
<div class="stage__description formatted" data-description></div>
|
||||
<div class="stage__media" data-media hidden></div>
|
||||
<figure class="stage__image" data-image hidden></figure>
|
||||
<div class="stage__results" data-results></div>
|
||||
</main>
|
||||
|
||||
|
||||
@@ -110,6 +110,7 @@ $countdown = function (?int $remaining): string {
|
||||
<?php if ($slide->description) : ?>
|
||||
<div class="prose formatted"><?= $this->Format->text($slide->description) ?></div>
|
||||
<?php endif; ?>
|
||||
<?= $this->element('slide_image', compact('slide', 'poll')) ?>
|
||||
</section>
|
||||
|
||||
<?php else : ?>
|
||||
@@ -118,6 +119,7 @@ $countdown = function (?int $remaining): string {
|
||||
<?php if ($slide->description) : ?>
|
||||
<div class="muted formatted"><?= $this->Format->text($slide->description) ?></div>
|
||||
<?php endif; ?>
|
||||
<?= $this->element('slide_image', compact('slide', 'poll')) ?>
|
||||
|
||||
<?php if ($quiz !== null) : ?>
|
||||
<?php if ($quiz['phase'] === 'ready') : ?>
|
||||
|
||||
@@ -31,7 +31,7 @@ $optionsError = $slide->getError('options_text');
|
||||
<p class="eyebrow"><?= h($slide->typeLabel()) ?></p>
|
||||
<h1 id="modal-title"><?= $isNew ? __('Neue Folie') : __('Folie bearbeiten') ?></h1>
|
||||
|
||||
<?= $this->Form->create($slide, ['url' => $formUrl]) ?>
|
||||
<?= $this->Form->create($slide, ['url' => $formUrl, 'type' => 'file']) ?>
|
||||
<?= $this->Form->hidden('type') ?>
|
||||
<?php if ($slide->isYouTube()) :
|
||||
$urlError = $slide->getError('youtube_url');
|
||||
@@ -116,6 +116,8 @@ $optionsError = $slide->getError('options_text');
|
||||
]) ?>
|
||||
<p class="hint" id="description-format"><?= __('Formatierung wie bei WhatsApp: *fett*, _kursiv_, ~durchgestrichen~, Aufzählung mit „- “ am Zeilenanfang.') ?></p>
|
||||
|
||||
<?= $this->element('slide_image_fields', compact('slide', 'poll')) ?>
|
||||
|
||||
<?php if ($slide->type === 'choice') : ?>
|
||||
<div class="input textarea<?= $optionsError ? ' error' : '' ?>">
|
||||
<label for="options-text"><?= __('Antwortoptionen (eine pro Zeile, max. 20)') ?></label>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
/**
|
||||
* The image of a slide on the participant's page (always above the content, whatever the stage layout).
|
||||
* Width and height reserve the space, so the page does not jump while the image loads.
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Slide $slide
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
*/
|
||||
if (!$slide->hasImage()) {
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<figure class="slide-image">
|
||||
<img src="<?= h($this->Url->build(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image])) ?>"
|
||||
alt="<?= h((string)$slide->image_alt) ?>"
|
||||
<?= $slide->image_width && $slide->image_height ? 'width="' . (int)$slide->image_width . '" height="' . (int)$slide->image_height . '"' : '' ?>
|
||||
decoding="async">
|
||||
</figure>
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
/**
|
||||
* Image fields of the slide form: upload, alternative text, layout, remove.
|
||||
* Not for slide types without image support (YouTube).
|
||||
*
|
||||
* @var \App\View\AppView $this
|
||||
* @var \App\Model\Entity\Slide $slide
|
||||
* @var \App\Model\Entity\Poll $poll
|
||||
*/
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Service\ImageService;
|
||||
use Cake\Core\Configure;
|
||||
|
||||
if (!Slide::supportsImage($slide->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);
|
||||
?>
|
||||
<fieldset class="image-fields" data-image-fields>
|
||||
<legend><?= __('Bild (optional)') ?></legend>
|
||||
<?php if (!ImageService::isAvailable()) : ?>
|
||||
<p class="hint"><?= __('Bilder sind auf diesem Server nicht verfügbar (PHP-Erweiterung GD mit WebP fehlt).') ?></p>
|
||||
<?php else : ?>
|
||||
<?php if ($hasImage) : ?>
|
||||
<figure class="image-fields__current">
|
||||
<img src="<?= h($this->Url->build(['_name' => 'participate:image', 'code' => $poll->join_code, 'file' => $slide->image])) ?>"
|
||||
alt="<?= h((string)$slide->image_alt) ?>" width="<?= (int)$slide->image_width ?>" height="<?= (int)$slide->image_height ?>">
|
||||
</figure>
|
||||
<?= $this->Form->control('remove_image', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Bild entfernen'),
|
||||
'value' => '1',
|
||||
'hiddenField' => false,
|
||||
'checked' => false,
|
||||
]) ?>
|
||||
<?php endif; ?>
|
||||
<div class="input file<?= $imageError ? ' error' : '' ?>">
|
||||
<label for="image-file"><?= $hasImage ? __('Anderes Bild hochladen') : __('Bild hochladen') ?></label>
|
||||
<input type="file" id="image-file" name="image" accept="image/jpeg,image/png,image/webp,image/gif"
|
||||
aria-describedby="image-hint<?= $imageError ? ' image-error' : '' ?>" <?= $imageError ? 'aria-invalid="true"' : '' ?>>
|
||||
<p class="hint" id="image-hint"><?= __('JPEG, PNG, WebP oder GIF (nicht animiert), bis {0} MB. Das Bild wird automatisch auf höchstens 1600 Pixel verkleinert und als WebP gespeichert, Kameradaten wie der Aufnahmeort werden dabei entfernt.', $maxMb) ?></p>
|
||||
<?php if ($imageError) : ?>
|
||||
<div class="error-message" id="image-error"><?= h(implode(' ', (array)$imageError)) ?></div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="input text<?= $altError ? ' error' : '' ?>">
|
||||
<label for="image-alt"><?= __('Bildbeschreibung (für Screenreader)') ?></label>
|
||||
<input type="text" id="image-alt" name="image_alt" maxlength="<?= Slide::IMAGE_ALT_MAX ?>" autocomplete="off"
|
||||
value="<?= h($alt) ?>" placeholder="<?= h(__('z. B. Organigramm des Vereins')) ?>"
|
||||
aria-describedby="image-alt-hint<?= $altError ? ' image-alt-error' : '' ?>" <?= $altError ? 'aria-invalid="true"' : '' ?>>
|
||||
<p class="hint" id="image-alt-hint"><?= __('Pflicht, sobald ein Bild gesetzt ist – oder das Bild ist reine Dekoration.') ?></p>
|
||||
<?php if ($altError) : ?>
|
||||
<div class="error-message" id="image-alt-error"><?= h(implode(' ', (array)$altError)) ?></div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?= $this->Form->control('image_decorative', [
|
||||
'type' => 'checkbox',
|
||||
'label' => __('Reine Dekoration (keine Beschreibung nötig)'),
|
||||
'value' => '1',
|
||||
'hiddenField' => false,
|
||||
'checked' => $decorative,
|
||||
]) ?>
|
||||
<fieldset class="scale-style image-fields__layout">
|
||||
<legend><?= __('Platzierung in der Präsentation') ?></legend>
|
||||
<?= $this->Form->radio('image_layout', array_map(
|
||||
fn($value, $text) => ['value' => $value, 'text' => $text],
|
||||
array_keys($layouts),
|
||||
$layouts,
|
||||
), ['value' => $layout]) ?>
|
||||
<p class="hint"><?= __('Auf dem Smartphone der Teilnehmenden steht das Bild immer oben.') ?></p>
|
||||
</fieldset>
|
||||
<?php endif; ?>
|
||||
</fieldset>
|
||||
@@ -0,0 +1,339 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Controller;
|
||||
|
||||
use App\Model\Entity\Slide;
|
||||
use App\Test\TestCase\ImageTestTrait;
|
||||
use App\Test\TestCase\PlenarioTestTrait;
|
||||
use Cake\Core\Configure;
|
||||
use Cake\TestSuite\IntegrationTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
|
||||
/**
|
||||
* Images on slides: upload and scaling, alternative text, quota, serving, and what happens to the
|
||||
* file when the image is replaced, removed or the slide (or poll) is deleted or duplicated.
|
||||
*/
|
||||
class SlideImageTest extends TestCase
|
||||
{
|
||||
use ImageTestTrait;
|
||||
use IntegrationTestTrait;
|
||||
use PlenarioTestTrait;
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase;
|
||||
|
||||
use Cake\Core\Configure;
|
||||
use Laminas\Diactoros\UploadedFile;
|
||||
|
||||
/**
|
||||
* Helpers for tests with slide images: generated pictures and a throw-away upload directory.
|
||||
* Call clearImages() from tearDown().
|
||||
*/
|
||||
trait ImageTestTrait
|
||||
{
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
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<string, mixed> $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<string> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Test\TestCase\Service;
|
||||
|
||||
use App\Service\ImageException;
|
||||
use App\Service\ImageService;
|
||||
use App\Test\TestCase\ImageTestTrait;
|
||||
use Cake\TestSuite\TestCase;
|
||||
use Laminas\Diactoros\UploadedFile;
|
||||
|
||||
/**
|
||||
* Scaling, validation and file handling of slide images.
|
||||
*/
|
||||
class ImageServiceTest extends TestCase
|
||||
{
|
||||
use ImageTestTrait;
|
||||
|
||||
protected ImageService $images;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->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, '<?php echo 1;');
|
||||
|
||||
$this->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, '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><script>alert(1)</script></svg>');
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
|
||||
@@ -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; }
|
||||
@@ -1293,6 +1293,33 @@
|
||||
}
|
||||
}
|
||||
|
||||
/** Shows the image of the slide (layout: top | side | full via stage--img-* classes); the <img> 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);
|
||||
|
||||
|
||||
Reference in new issue
Block a user