Files
Plenario/src/Service/ImageService.php
T
gnilebeinandClaude Sonnet 5.5 bd57f23be6
CI / Deploy / PHP 8.5 (push) Successful in 1m51s
CI / Deploy / PHP 8.4 (push) Successful in 1m51s
CI / Deploy / test (push) Successful in 2s
CI / Deploy / deploy (push) Skipped
Add admin menu drawer and poll cloning, drop participant screen tools
- Remove fullscreen and wake lock buttons from the participant view.
- Turn the admin sidebar into a drawer below 900px, opened from a header
  menu button next to the theme switch (progressive enhancement).
- Add "Umfrage kopieren": clone a poll with all slides, options and images
  but without responses, with its own join code and admin link.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 10:57:33 +01:00

399 lines
14 KiB
PHP

<?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 that receives the copy
* @param string $name Source file name
* @param int|null $sourcePollId Poll id of the source file (default: the same poll)
* @return string|null Name of the copy, null if the source file is gone or the copy failed
*/
public function copy(int $pollId, string $name, ?int $sourcePollId = null): ?string
{
$source = $this->path($sourcePollId ?? $pollId, $name);
if ($source === null) {
return null;
}
$directory = $this->directory($pollId);
if (!is_dir($directory) && !@mkdir($directory, 0775, true) && !is_dir($directory)) {
return null;
}
$copy = bin2hex(random_bytes(12)) . '.webp';
return @copy($source, $directory . 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;
}
}