Add optional images to slides
CI / Deploy / PHP 8.4 (push) Successful in 1m10s
CI / Deploy / PHP 8.5 (push) Successful in 1m16s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Skipped

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 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Sonnet 5.5 committed 2026-11-14 23:17:37 +01:00
1 parent 8c7818ee40
commit a395b50894
30 files changed
+1705 -11

No files matched your search

+13
View File
@@ -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
{
}
+393
View File
@@ -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;
}
}
+14 -4
View File
@@ -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,
];
}
}