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

+72
View File
@@ -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;
}
}
+29
View File
@@ -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
+142 -1
View File
@@ -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;
+54
View File
@@ -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
*/
+18
View File
@@ -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
+43
View File
@@ -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')],
+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,
];
}
}