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_image_file_update()
97 $page = $this->entities->page();
100 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
101 $relPath = $imgDetails['path'];
103 $newUpload = $this->files->uploadedImage('updated-image.png', 'compressed.png');
104 $this->assertFileEquals($this->files->testFilePath('test-image.png'), public_path($relPath));
106 $imageId = $imgDetails['response']->id;
107 $image = Image::findOrFail($imageId);
108 $image->updated_at = now()->subMonth();
111 $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload])
114 $this->assertFileEquals($this->files->testFilePath('compressed.png'), public_path($relPath));
117 $this->assertTrue($image->updated_at->gt(now()->subMinute()));
119 $this->files->deleteAtRelativePath($relPath);
122 public function test_image_file_update_does_not_allow_change_in_image_extension()
124 $page = $this->entities->page();
127 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
128 $relPath = $imgDetails['path'];
129 $newUpload = $this->files->uploadedImage('updated-image.jpg', 'compressed.png');
131 $imageId = $imgDetails['response']->id;
132 $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload])
134 "message" => "Image file replacements must be of the same type",
138 $this->files->deleteAtRelativePath($relPath);
141 public function test_gallery_get_list_format()
145 $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
146 $image = Image::query()->first();
148 $pageId = $imgDetails['page']->id;
149 $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
150 $firstPageRequest->assertSuccessful();
151 $this->withHtml($firstPageRequest)->assertElementExists('div');
152 $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
154 $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
155 $secondPageRequest->assertSuccessful();
156 $this->withHtml($secondPageRequest)->assertElementNotExists('div');
158 $namePartial = substr($imgDetails['name'], 0, 3);
159 $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
160 $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
162 $namePartial = Str::random(16);
163 $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
164 $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
165 $searchFailRequest->assertSuccessful();
166 $this->withHtml($searchFailRequest)->assertElementNotExists('div');
169 public function test_image_gallery_lists_for_draft_page()
171 $this->actingAs($this->users->editor());
172 $draft = $this->entities->newDraftPage();
173 $this->files->uploadGalleryImageToPage($this, $draft);
174 $image = Image::query()->where('uploaded_to', '=', $draft->id)->firstOrFail();
176 $resp = $this->get("/images/gallery?page=1&uploaded_to={$draft->id}");
177 $resp->assertSee($image->getThumb(150, 150));
180 public function test_image_usage()
182 $page = $this->entities->page();
183 $editor = $this->users->editor();
184 $this->actingAs($editor);
186 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
188 $image = Image::query()->first();
189 $page->html = '<img src="' . $image->url . '">';
192 $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
193 $usage->assertSuccessful();
194 $usage->assertSeeText($page->name);
195 $usage->assertSee($page->getUrl());
197 $this->files->deleteAtRelativePath($imgDetails['path']);
200 public function test_php_files_cannot_be_uploaded()
202 $page = $this->entities->page();
203 $admin = $this->users->admin();
204 $this->actingAs($admin);
206 $fileName = 'bad.php';
207 $relPath = $this->files->expectedImagePath('gallery', $fileName);
208 $this->files->deleteAtRelativePath($relPath);
210 $file = $this->files->imageFromBase64File('bad-php.base64', $fileName);
211 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
212 $upload->assertStatus(500);
213 $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
215 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
217 $this->assertDatabaseMissing('images', [
223 public function test_php_like_files_cannot_be_uploaded()
225 $page = $this->entities->page();
226 $admin = $this->users->admin();
227 $this->actingAs($admin);
229 $fileName = 'bad.phtml';
230 $relPath = $this->files->expectedImagePath('gallery', $fileName);
231 $this->files->deleteAtRelativePath($relPath);
233 $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName);
234 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
235 $upload->assertStatus(500);
236 $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
238 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
241 public function test_files_with_double_extensions_will_get_sanitized()
243 $page = $this->entities->page();
244 $admin = $this->users->admin();
245 $this->actingAs($admin);
247 $fileName = 'bad.phtml.png';
248 $relPath = $this->files->expectedImagePath('gallery', $fileName);
249 $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
250 $this->files->deleteAtRelativePath($expectedRelPath);
252 $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName);
253 $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
254 $upload->assertStatus(200);
256 $lastImage = Image::query()->latest('id')->first();
258 $this->assertEquals('bad.phtml.png', $lastImage->name);
259 $this->assertEquals('bad-phtml.png', basename($lastImage->path));
260 $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
261 $this->assertFileExists(public_path($expectedRelPath));
263 $this->files->deleteAtRelativePath($lastImage->path);
266 public function test_url_entities_removed_from_filenames()
270 'bad-char-#-image.png',
271 'bad-char-?-image.png',
276 foreach ($badNames as $name) {
277 $galleryFile = $this->files->uploadedImage($name);
278 $page = $this->entities->page();
279 $badPath = $this->files->expectedImagePath('gallery', $name);
280 $this->files->deleteAtRelativePath($badPath);
282 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
283 $upload->assertStatus(200);
285 $lastImage = Image::query()->latest('id')->first();
286 $newFileName = explode('.', basename($lastImage->path))[0];
288 $this->assertEquals($lastImage->name, $name);
289 $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
290 $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
292 $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
294 $this->files->deleteAtRelativePath($lastImage->path);
298 public function test_secure_images_uploads_to_correct_place()
300 config()->set('filesystems.images', 'local_secure');
302 $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
303 $page = $this->entities->page();
304 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
306 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
307 $upload->assertStatus(200);
309 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
311 if (file_exists($expectedPath)) {
312 unlink($expectedPath);
316 public function test_secure_image_paths_traversal_causes_500()
318 config()->set('filesystems.images', 'local_secure');
321 $resp = $this->get('/uploads/images/../../logs/laravel.log');
322 $resp->assertStatus(500);
325 public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
327 config()->set('filesystems.images', 'local');
330 $resp = $this->get('/uploads/images/../../logs/laravel.log');
331 $resp->assertStatus(404);
334 public function test_secure_image_paths_dont_serve_non_images()
336 config()->set('filesystems.images', 'local_secure');
339 $testFilePath = storage_path('/uploads/images/testing.txt');
340 file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
342 $resp = $this->get('/uploads/images/testing.txt');
343 $resp->assertStatus(404);
346 public function test_secure_images_included_in_exports()
348 config()->set('filesystems.images', 'local_secure');
350 $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
351 $page = $this->entities->page();
352 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
354 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
355 $imageUrl = json_decode($upload->getContent(), true)['url'];
356 $page->html .= "<img src=\"{$imageUrl}\">";
358 $upload->assertStatus(200);
360 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
361 $export = $this->get($page->getUrl('/export/html'));
362 $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
364 if (file_exists($expectedPath)) {
365 unlink($expectedPath);
369 public function test_system_images_remain_public_with_local_secure()
371 config()->set('filesystems.images', 'local_secure');
373 $galleryFile = $this->files->uploadedImage('my-system-test-upload.png');
374 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
376 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
377 $upload->assertRedirect('/settings/customization');
379 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
381 if (file_exists($expectedPath)) {
382 unlink($expectedPath);
386 public function test_system_images_remain_public_with_local_secure_restricted()
388 config()->set('filesystems.images', 'local_secure_restricted');
390 $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
391 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
393 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
394 $upload->assertRedirect('/settings/customization');
396 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
398 if (file_exists($expectedPath)) {
399 unlink($expectedPath);
403 public function test_secure_restricted_images_inaccessible_without_relation_permission()
405 config()->set('filesystems.images', 'local_secure_restricted');
407 $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
408 $page = $this->entities->page();
410 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
411 $upload->assertStatus(200);
412 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
413 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
415 $this->get($expectedUrl)->assertOk();
417 $this->permissions->setEntityPermissions($page, [], []);
419 $resp = $this->get($expectedUrl);
420 $resp->assertNotFound();
422 if (file_exists($expectedPath)) {
423 unlink($expectedPath);
427 public function test_thumbnail_path_handled_by_secure_restricted_images()
429 config()->set('filesystems.images', 'local_secure_restricted');
431 $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
432 $page = $this->entities->page();
434 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
435 $upload->assertStatus(200);
436 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
437 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
439 $this->get($expectedUrl)->assertOk();
441 $this->permissions->setEntityPermissions($page, [], []);
443 $resp = $this->get($expectedUrl);
444 $resp->assertNotFound();
446 if (file_exists($expectedPath)) {
447 unlink($expectedPath);
451 public function test_secure_restricted_image_access_controlled_in_exports()
453 config()->set('filesystems.images', 'local_secure_restricted');
455 $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
457 $pageA = $this->entities->page();
458 $pageB = $this->entities->page();
459 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
461 $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
464 $imageUrl = json_decode($upload->getContent(), true)['url'];
465 $pageB->html .= "<img src=\"{$imageUrl}\">";
468 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
469 $export = $this->get($pageB->getUrl('/export/html'));
470 $this->assertStringContainsString($encodedImageContent, $export->getContent());
472 $this->permissions->setEntityPermissions($pageA, [], []);
474 $export = $this->get($pageB->getUrl('/export/html'));
475 $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
477 if (file_exists($expectedPath)) {
478 unlink($expectedPath);
482 public function test_image_delete()
484 $page = $this->entities->page();
486 $imageName = 'first-image.png';
487 $relPath = $this->files->expectedImagePath('gallery', $imageName);
488 $this->files->deleteAtRelativePath($relPath);
490 $this->files->uploadGalleryImage($this, $imageName, $page->id);
491 $image = Image::first();
493 $delete = $this->delete('/images/' . $image->id);
494 $delete->assertStatus(200);
496 $this->assertDatabaseMissing('images', [
497 'url' => $this->baseUrl . $relPath,
501 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
504 public function test_image_delete_does_not_delete_similar_images()
506 $page = $this->entities->page();
508 $imageName = 'first-image.png';
510 $relPath = $this->files->expectedImagePath('gallery', $imageName);
511 $this->files->deleteAtRelativePath($relPath);
513 $this->files->uploadGalleryImage($this, $imageName, $page->id);
514 $this->files->uploadGalleryImage($this, $imageName, $page->id);
515 $this->files->uploadGalleryImage($this, $imageName, $page->id);
517 $image = Image::first();
518 $folder = public_path(dirname($relPath));
519 $imageCount = count(glob($folder . '/*'));
521 $delete = $this->delete('/images/' . $image->id);
522 $delete->assertStatus(200);
524 $newCount = count(glob($folder . '/*'));
525 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
526 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
529 public function test_image_manager_delete_button_only_shows_with_permission()
531 $page = $this->entities->page();
533 $imageName = 'first-image.png';
534 $relPath = $this->files->expectedImagePath('gallery', $imageName);
535 $this->files->deleteAtRelativePath($relPath);
536 $viewer = $this->users->viewer();
538 $this->files->uploadGalleryImage($this, $imageName, $page->id);
539 $image = Image::first();
541 $resp = $this->get("/images/edit/{$image->id}");
542 $this->withHtml($resp)->assertElementExists('button#image-manager-delete');
544 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
545 $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete');
547 $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
549 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
550 $this->withHtml($resp)->assertElementExists('button#image-manager-delete');
552 $this->files->deleteAtRelativePath($relPath);
555 public function test_image_manager_regen_thumbnails()
558 $imageName = 'first-image.png';
559 $relPath = $this->files->expectedImagePath('gallery', $imageName);
560 $this->files->deleteAtRelativePath($relPath);
562 $this->files->uploadGalleryImage($this, $imageName, $this->entities->page()->id);
563 $image = Image::first();
565 $resp = $this->get("/images/edit/{$image->id}");
566 $this->withHtml($resp)->assertElementExists('button#image-manager-rebuild-thumbs');
568 $expectedThumbPath = dirname($relPath) . '/scaled-1680-/' . basename($relPath);
569 $this->files->deleteAtRelativePath($expectedThumbPath);
570 $this->assertFileDoesNotExist($this->files->relativeToFullPath($expectedThumbPath));
572 $resp = $this->put("/images/{$image->id}/rebuild-thumbnails");
575 $this->assertFileExists($this->files->relativeToFullPath($expectedThumbPath));
576 $this->files->deleteAtRelativePath($relPath);
579 protected function getTestProfileImage()
581 $imageName = 'profile.png';
582 $relPath = $this->files->expectedImagePath('user', $imageName);
583 $this->files->deleteAtRelativePath($relPath);
585 return $this->files->uploadedImage($imageName);
588 public function test_user_image_upload()
590 $editor = $this->users->editor();
591 $admin = $this->users->admin();
592 $this->actingAs($admin);
594 $file = $this->getTestProfileImage();
595 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
597 $this->assertDatabaseHas('images', [
599 'uploaded_to' => $editor->id,
600 'created_by' => $admin->id,
604 public function test_user_images_deleted_on_user_deletion()
606 $editor = $this->users->editor();
607 $this->actingAs($editor);
609 $file = $this->getTestProfileImage();
610 $this->call('PUT', '/my-account/profile', [], [], ['profile_image' => $file], []);
612 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
613 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
615 $imagePath = public_path($profileImages->first()->path);
616 $this->assertTrue(file_exists($imagePath));
618 $userDelete = $this->asAdmin()->delete($editor->getEditUrl());
619 $userDelete->assertStatus(302);
621 $this->assertDatabaseMissing('images', [
623 'created_by' => $editor->id,
625 $this->assertDatabaseMissing('images', [
627 'uploaded_to' => $editor->id,
630 $this->assertFalse(file_exists($imagePath));
633 public function test_deleted_unused_images()
635 $page = $this->entities->page();
636 $admin = $this->users->admin();
637 $this->actingAs($admin);
639 $imageName = 'unused-image.png';
640 $relPath = $this->files->expectedImagePath('gallery', $imageName);
641 $this->files->deleteAtRelativePath($relPath);
643 $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
644 $upload->assertStatus(200);
645 $image = Image::where('type', '=', 'gallery')->first();
647 $pageRepo = app(PageRepo::class);
648 $pageRepo->update($page, [
649 'name' => $page->name,
650 'html' => $page->html . "<img src=\"{$image->url}\">",
654 // Ensure no images are reported as deletable
655 $imageService = app(ImageService::class);
656 $toDelete = $imageService->deleteUnusedImages(true, true);
657 $this->assertCount(0, $toDelete);
659 // Save a revision of our page without the image;
660 $pageRepo->update($page, [
661 'name' => $page->name,
662 'html' => '<p>Hello</p>',
666 // Ensure revision images are picked up okay
667 $imageService = app(ImageService::class);
668 $toDelete = $imageService->deleteUnusedImages(true, true);
669 $this->assertCount(0, $toDelete);
670 $toDelete = $imageService->deleteUnusedImages(false, true);
671 $this->assertCount(1, $toDelete);
673 // Check image is found when revisions are destroyed
674 $page->revisions()->delete();
675 $toDelete = $imageService->deleteUnusedImages(true, true);
676 $this->assertCount(1, $toDelete);
678 // Check the image is deleted
679 $absPath = public_path($relPath);
680 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
681 $toDelete = $imageService->deleteUnusedImages(true, false);
682 $this->assertCount(1, $toDelete);
683 $this->assertFalse(file_exists($absPath));
685 $this->files->deleteAtRelativePath($relPath);