3 namespace Tests\Uploads;
5 use BookStack\Entities\Repos\PageRepo;
6 use BookStack\Uploads\Image;
7 use BookStack\Uploads\ImageService;
8 use Illuminate\Support\Str;
11 class ImageTest extends TestCase
13 public function test_image_upload()
15 $page = $this->entities->page();
16 $admin = $this->users->admin();
17 $this->actingAs($admin);
19 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
20 $relPath = $imgDetails['path'];
22 $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
24 $this->files->deleteAtRelativePath($relPath);
26 $this->assertDatabaseHas('images', [
27 'url' => $this->baseUrl . $relPath,
29 'uploaded_to' => $page->id,
31 'created_by' => $admin->id,
32 'updated_by' => $admin->id,
33 'name' => $imgDetails['name'],
37 public function test_image_display_thumbnail_generation_does_not_increase_image_size()
39 $page = $this->entities->page();
40 $admin = $this->users->admin();
41 $this->actingAs($admin);
43 $originalFile = $this->files->testFilePath('compressed.png');
44 $originalFileSize = filesize($originalFile);
45 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'compressed.png');
46 $relPath = $imgDetails['path'];
48 $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
49 $displayImage = $imgDetails['response']->thumbs->display;
51 $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3));
52 $displayImagePath = public_path($displayImageRelPath);
53 $displayFileSize = filesize($displayImagePath);
55 $this->files->deleteAtRelativePath($relPath);
56 $this->files->deleteAtRelativePath($displayImageRelPath);
58 $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size');
61 public function test_image_display_thumbnail_generation_for_apng_images_uses_original_file()
63 $page = $this->entities->page();
64 $admin = $this->users->admin();
65 $this->actingAs($admin);
67 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'animated.png');
68 $this->files->deleteAtRelativePath($imgDetails['path']);
70 $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery);
71 $this->assertStringNotContainsString('thumbs-', $imgDetails['response']->thumbs->display);
74 public function test_image_edit()
76 $editor = $this->users->editor();
77 $this->actingAs($editor);
79 $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
80 $image = Image::query()->first();
82 $newName = Str::random();
83 $update = $this->put('/images/' . $image->id, ['name' => $newName]);
84 $update->assertSuccessful();
85 $update->assertSee($newName);
87 $this->files->deleteAtRelativePath($imgDetails['path']);
89 $this->assertDatabaseHas('images', [
95 public function test_gallery_get_list_format()
99 $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
100 $image = Image::query()->first();
102 $pageId = $imgDetails['page']->id;
103 $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
104 $firstPageRequest->assertSuccessful();
105 $this->withHtml($firstPageRequest)->assertElementExists('div');
106 $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
108 $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
109 $secondPageRequest->assertSuccessful();
110 $this->withHtml($secondPageRequest)->assertElementNotExists('div');
112 $namePartial = substr($imgDetails['name'], 0, 3);
113 $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
114 $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
116 $namePartial = Str::random(16);
117 $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
118 $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
119 $searchFailRequest->assertSuccessful();
120 $this->withHtml($searchFailRequest)->assertElementNotExists('div');
123 public function test_image_gallery_lists_for_draft_page()
125 $this->actingAs($this->users->editor());
126 $draft = $this->entities->newDraftPage();
127 $this->files->uploadGalleryImageToPage($this, $draft);
128 $image = Image::query()->where('uploaded_to', '=', $draft->id)->firstOrFail();
130 $resp = $this->get("/images/gallery?page=1&uploaded_to={$draft->id}");
131 $resp->assertSee($image->getThumb(150, 150));
134 public function test_image_usage()
136 $page = $this->entities->page();
137 $editor = $this->users->editor();
138 $this->actingAs($editor);
140 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
142 $image = Image::query()->first();
143 $page->html = '<img src="' . $image->url . '">';
146 $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
147 $usage->assertSuccessful();
148 $usage->assertSeeText($page->name);
149 $usage->assertSee($page->getUrl());
151 $this->files->deleteAtRelativePath($imgDetails['path']);
154 public function test_php_files_cannot_be_uploaded()
156 $page = $this->entities->page();
157 $admin = $this->users->admin();
158 $this->actingAs($admin);
160 $fileName = 'bad.php';
161 $relPath = $this->files->expectedImagePath('gallery', $fileName);
162 $this->files->deleteAtRelativePath($relPath);
164 $file = $this->files->imageFromBase64File('bad-php.base64', $fileName);
165 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
166 $upload->assertStatus(500);
167 $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
169 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
171 $this->assertDatabaseMissing('images', [
177 public function test_php_like_files_cannot_be_uploaded()
179 $page = $this->entities->page();
180 $admin = $this->users->admin();
181 $this->actingAs($admin);
183 $fileName = 'bad.phtml';
184 $relPath = $this->files->expectedImagePath('gallery', $fileName);
185 $this->files->deleteAtRelativePath($relPath);
187 $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName);
188 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
189 $upload->assertStatus(500);
190 $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
192 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
195 public function test_files_with_double_extensions_will_get_sanitized()
197 $page = $this->entities->page();
198 $admin = $this->users->admin();
199 $this->actingAs($admin);
201 $fileName = 'bad.phtml.png';
202 $relPath = $this->files->expectedImagePath('gallery', $fileName);
203 $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
204 $this->files->deleteAtRelativePath($expectedRelPath);
206 $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName);
207 $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
208 $upload->assertStatus(200);
210 $lastImage = Image::query()->latest('id')->first();
212 $this->assertEquals('bad.phtml.png', $lastImage->name);
213 $this->assertEquals('bad-phtml.png', basename($lastImage->path));
214 $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
215 $this->assertFileExists(public_path($expectedRelPath));
217 $this->files->deleteAtRelativePath($lastImage->path);
220 public function test_url_entities_removed_from_filenames()
224 'bad-char-#-image.png',
225 'bad-char-?-image.png',
230 foreach ($badNames as $name) {
231 $galleryFile = $this->files->uploadedImage($name);
232 $page = $this->entities->page();
233 $badPath = $this->files->expectedImagePath('gallery', $name);
234 $this->files->deleteAtRelativePath($badPath);
236 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
237 $upload->assertStatus(200);
239 $lastImage = Image::query()->latest('id')->first();
240 $newFileName = explode('.', basename($lastImage->path))[0];
242 $this->assertEquals($lastImage->name, $name);
243 $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
244 $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
246 $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
248 $this->files->deleteAtRelativePath($lastImage->path);
252 public function test_secure_images_uploads_to_correct_place()
254 config()->set('filesystems.images', 'local_secure');
256 $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
257 $page = $this->entities->page();
258 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
260 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
261 $upload->assertStatus(200);
263 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
265 if (file_exists($expectedPath)) {
266 unlink($expectedPath);
270 public function test_secure_image_paths_traversal_causes_500()
272 config()->set('filesystems.images', 'local_secure');
275 $resp = $this->get('/uploads/images/../../logs/laravel.log');
276 $resp->assertStatus(500);
279 public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
281 config()->set('filesystems.images', 'local');
284 $resp = $this->get('/uploads/images/../../logs/laravel.log');
285 $resp->assertStatus(404);
288 public function test_secure_image_paths_dont_serve_non_images()
290 config()->set('filesystems.images', 'local_secure');
293 $testFilePath = storage_path('/uploads/images/testing.txt');
294 file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
296 $resp = $this->get('/uploads/images/testing.txt');
297 $resp->assertStatus(404);
300 public function test_secure_images_included_in_exports()
302 config()->set('filesystems.images', 'local_secure');
304 $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
305 $page = $this->entities->page();
306 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
308 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
309 $imageUrl = json_decode($upload->getContent(), true)['url'];
310 $page->html .= "<img src=\"{$imageUrl}\">";
312 $upload->assertStatus(200);
314 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
315 $export = $this->get($page->getUrl('/export/html'));
316 $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
318 if (file_exists($expectedPath)) {
319 unlink($expectedPath);
323 public function test_system_images_remain_public_with_local_secure()
325 config()->set('filesystems.images', 'local_secure');
327 $galleryFile = $this->files->uploadedImage('my-system-test-upload.png');
328 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
330 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
331 $upload->assertRedirect('/settings/customization');
333 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
335 if (file_exists($expectedPath)) {
336 unlink($expectedPath);
340 public function test_system_images_remain_public_with_local_secure_restricted()
342 config()->set('filesystems.images', 'local_secure_restricted');
344 $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
345 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
347 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
348 $upload->assertRedirect('/settings/customization');
350 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
352 if (file_exists($expectedPath)) {
353 unlink($expectedPath);
357 public function test_secure_restricted_images_inaccessible_without_relation_permission()
359 config()->set('filesystems.images', 'local_secure_restricted');
361 $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
362 $page = $this->entities->page();
364 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
365 $upload->assertStatus(200);
366 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
367 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
369 $this->get($expectedUrl)->assertOk();
371 $this->permissions->setEntityPermissions($page, [], []);
373 $resp = $this->get($expectedUrl);
374 $resp->assertNotFound();
376 if (file_exists($expectedPath)) {
377 unlink($expectedPath);
381 public function test_thumbnail_path_handled_by_secure_restricted_images()
383 config()->set('filesystems.images', 'local_secure_restricted');
385 $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
386 $page = $this->entities->page();
388 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
389 $upload->assertStatus(200);
390 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
391 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
393 $this->get($expectedUrl)->assertOk();
395 $this->permissions->setEntityPermissions($page, [], []);
397 $resp = $this->get($expectedUrl);
398 $resp->assertNotFound();
400 if (file_exists($expectedPath)) {
401 unlink($expectedPath);
405 public function test_secure_restricted_image_access_controlled_in_exports()
407 config()->set('filesystems.images', 'local_secure_restricted');
409 $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
411 $pageA = $this->entities->page();
412 $pageB = $this->entities->page();
413 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
415 $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
418 $imageUrl = json_decode($upload->getContent(), true)['url'];
419 $pageB->html .= "<img src=\"{$imageUrl}\">";
422 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
423 $export = $this->get($pageB->getUrl('/export/html'));
424 $this->assertStringContainsString($encodedImageContent, $export->getContent());
426 $this->permissions->setEntityPermissions($pageA, [], []);
428 $export = $this->get($pageB->getUrl('/export/html'));
429 $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
431 if (file_exists($expectedPath)) {
432 unlink($expectedPath);
436 public function test_image_delete()
438 $page = $this->entities->page();
440 $imageName = 'first-image.png';
441 $relPath = $this->files->expectedImagePath('gallery', $imageName);
442 $this->files->deleteAtRelativePath($relPath);
444 $this->files->uploadGalleryImage($this, $imageName, $page->id);
445 $image = Image::first();
447 $delete = $this->delete('/images/' . $image->id);
448 $delete->assertStatus(200);
450 $this->assertDatabaseMissing('images', [
451 'url' => $this->baseUrl . $relPath,
455 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
458 public function test_image_delete_does_not_delete_similar_images()
460 $page = $this->entities->page();
462 $imageName = 'first-image.png';
464 $relPath = $this->files->expectedImagePath('gallery', $imageName);
465 $this->files->deleteAtRelativePath($relPath);
467 $this->files->uploadGalleryImage($this, $imageName, $page->id);
468 $this->files->uploadGalleryImage($this, $imageName, $page->id);
469 $this->files->uploadGalleryImage($this, $imageName, $page->id);
471 $image = Image::first();
472 $folder = public_path(dirname($relPath));
473 $imageCount = count(glob($folder . '/*'));
475 $delete = $this->delete('/images/' . $image->id);
476 $delete->assertStatus(200);
478 $newCount = count(glob($folder . '/*'));
479 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
480 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
483 public function test_image_manager_delete_button_only_shows_with_permission()
485 $page = $this->entities->page();
487 $imageName = 'first-image.png';
488 $relPath = $this->files->expectedImagePath('gallery', $imageName);
489 $this->files->deleteAtRelativePath($relPath);
490 $viewer = $this->users->viewer();
492 $this->files->uploadGalleryImage($this, $imageName, $page->id);
493 $image = Image::first();
495 $resp = $this->get("/images/edit/{$image->id}");
496 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
498 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
499 $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete[title="Delete"]');
501 $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
503 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
504 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
506 $this->files->deleteAtRelativePath($relPath);
509 protected function getTestProfileImage()
511 $imageName = 'profile.png';
512 $relPath = $this->files->expectedImagePath('user', $imageName);
513 $this->files->deleteAtRelativePath($relPath);
515 return $this->files->uploadedImage($imageName);
518 public function test_user_image_upload()
520 $editor = $this->users->editor();
521 $admin = $this->users->admin();
522 $this->actingAs($admin);
524 $file = $this->getTestProfileImage();
525 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
527 $this->assertDatabaseHas('images', [
529 'uploaded_to' => $editor->id,
530 'created_by' => $admin->id,
534 public function test_user_images_deleted_on_user_deletion()
536 $editor = $this->users->editor();
537 $this->actingAs($editor);
539 $file = $this->getTestProfileImage();
540 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
542 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
543 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
545 $imagePath = public_path($profileImages->first()->path);
546 $this->assertTrue(file_exists($imagePath));
548 $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
549 $userDelete->assertStatus(302);
551 $this->assertDatabaseMissing('images', [
553 'created_by' => $editor->id,
555 $this->assertDatabaseMissing('images', [
557 'uploaded_to' => $editor->id,
560 $this->assertFalse(file_exists($imagePath));
563 public function test_deleted_unused_images()
565 $page = $this->entities->page();
566 $admin = $this->users->admin();
567 $this->actingAs($admin);
569 $imageName = 'unused-image.png';
570 $relPath = $this->files->expectedImagePath('gallery', $imageName);
571 $this->files->deleteAtRelativePath($relPath);
573 $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
574 $upload->assertStatus(200);
575 $image = Image::where('type', '=', 'gallery')->first();
577 $pageRepo = app(PageRepo::class);
578 $pageRepo->update($page, [
579 'name' => $page->name,
580 'html' => $page->html . "<img src=\"{$image->url}\">",
584 // Ensure no images are reported as deletable
585 $imageService = app(ImageService::class);
586 $toDelete = $imageService->deleteUnusedImages(true, true);
587 $this->assertCount(0, $toDelete);
589 // Save a revision of our page without the image;
590 $pageRepo->update($page, [
591 'name' => $page->name,
592 'html' => '<p>Hello</p>',
596 // Ensure revision images are picked up okay
597 $imageService = app(ImageService::class);
598 $toDelete = $imageService->deleteUnusedImages(true, true);
599 $this->assertCount(0, $toDelete);
600 $toDelete = $imageService->deleteUnusedImages(false, true);
601 $this->assertCount(1, $toDelete);
603 // Check image is found when revisions are destroyed
604 $page->revisions()->delete();
605 $toDelete = $imageService->deleteUnusedImages(true, true);
606 $this->assertCount(1, $toDelete);
608 // Check the image is deleted
609 $absPath = public_path($relPath);
610 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
611 $toDelete = $imageService->deleteUnusedImages(true, false);
612 $this->assertCount(1, $toDelete);
613 $this->assertFalse(file_exists($absPath));
615 $this->files->deleteAtRelativePath($relPath);