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

@@ -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');
}
}
+106
View File
@@ -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);
}
}
}
+188
View File
@@ -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;
}
}