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(302);
168 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
170 $this->assertDatabaseMissing('images', [
176 public function test_php_like_files_cannot_be_uploaded()
178 $page = $this->entities->page();
179 $admin = $this->users->admin();
180 $this->actingAs($admin);
182 $fileName = 'bad.phtml';
183 $relPath = $this->files->expectedImagePath('gallery', $fileName);
184 $this->files->deleteAtRelativePath($relPath);
186 $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName);
187 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
188 $upload->assertStatus(302);
190 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
193 public function test_files_with_double_extensions_will_get_sanitized()
195 $page = $this->entities->page();
196 $admin = $this->users->admin();
197 $this->actingAs($admin);
199 $fileName = 'bad.phtml.png';
200 $relPath = $this->files->expectedImagePath('gallery', $fileName);
201 $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
202 $this->files->deleteAtRelativePath($expectedRelPath);
204 $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName);
205 $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
206 $upload->assertStatus(200);
208 $lastImage = Image::query()->latest('id')->first();
210 $this->assertEquals('bad.phtml.png', $lastImage->name);
211 $this->assertEquals('bad-phtml.png', basename($lastImage->path));
212 $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
213 $this->assertFileExists(public_path($expectedRelPath));
215 $this->files->deleteAtRelativePath($lastImage->path);
218 public function test_url_entities_removed_from_filenames()
222 'bad-char-#-image.png',
223 'bad-char-?-image.png',
228 foreach ($badNames as $name) {
229 $galleryFile = $this->files->uploadedImage($name);
230 $page = $this->entities->page();
231 $badPath = $this->files->expectedImagePath('gallery', $name);
232 $this->files->deleteAtRelativePath($badPath);
234 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
235 $upload->assertStatus(200);
237 $lastImage = Image::query()->latest('id')->first();
238 $newFileName = explode('.', basename($lastImage->path))[0];
240 $this->assertEquals($lastImage->name, $name);
241 $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
242 $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
244 $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
246 $this->files->deleteAtRelativePath($lastImage->path);
250 public function test_secure_images_uploads_to_correct_place()
252 config()->set('filesystems.images', 'local_secure');
254 $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
255 $page = $this->entities->page();
256 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
258 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
259 $upload->assertStatus(200);
261 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
263 if (file_exists($expectedPath)) {
264 unlink($expectedPath);
268 public function test_secure_image_paths_traversal_causes_500()
270 config()->set('filesystems.images', 'local_secure');
273 $resp = $this->get('/uploads/images/../../logs/laravel.log');
274 $resp->assertStatus(500);
277 public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
279 config()->set('filesystems.images', 'local');
282 $resp = $this->get('/uploads/images/../../logs/laravel.log');
283 $resp->assertStatus(404);
286 public function test_secure_image_paths_dont_serve_non_images()
288 config()->set('filesystems.images', 'local_secure');
291 $testFilePath = storage_path('/uploads/images/testing.txt');
292 file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
294 $resp = $this->get('/uploads/images/testing.txt');
295 $resp->assertStatus(404);
298 public function test_secure_images_included_in_exports()
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 $imageUrl = json_decode($upload->getContent(), true)['url'];
308 $page->html .= "<img src=\"{$imageUrl}\">";
310 $upload->assertStatus(200);
312 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
313 $export = $this->get($page->getUrl('/export/html'));
314 $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
316 if (file_exists($expectedPath)) {
317 unlink($expectedPath);
321 public function test_system_images_remain_public_with_local_secure()
323 config()->set('filesystems.images', 'local_secure');
325 $galleryFile = $this->files->uploadedImage('my-system-test-upload.png');
326 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
328 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
329 $upload->assertRedirect('/settings/customization');
331 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
333 if (file_exists($expectedPath)) {
334 unlink($expectedPath);
338 public function test_system_images_remain_public_with_local_secure_restricted()
340 config()->set('filesystems.images', 'local_secure_restricted');
342 $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
343 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
345 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
346 $upload->assertRedirect('/settings/customization');
348 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
350 if (file_exists($expectedPath)) {
351 unlink($expectedPath);
355 public function test_secure_restricted_images_inaccessible_without_relation_permission()
357 config()->set('filesystems.images', 'local_secure_restricted');
359 $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
360 $page = $this->entities->page();
362 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
363 $upload->assertStatus(200);
364 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
365 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
367 $this->get($expectedUrl)->assertOk();
369 $this->permissions->setEntityPermissions($page, [], []);
371 $resp = $this->get($expectedUrl);
372 $resp->assertNotFound();
374 if (file_exists($expectedPath)) {
375 unlink($expectedPath);
379 public function test_thumbnail_path_handled_by_secure_restricted_images()
381 config()->set('filesystems.images', 'local_secure_restricted');
383 $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
384 $page = $this->entities->page();
386 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
387 $upload->assertStatus(200);
388 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
389 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
391 $this->get($expectedUrl)->assertOk();
393 $this->permissions->setEntityPermissions($page, [], []);
395 $resp = $this->get($expectedUrl);
396 $resp->assertNotFound();
398 if (file_exists($expectedPath)) {
399 unlink($expectedPath);
403 public function test_secure_restricted_image_access_controlled_in_exports()
405 config()->set('filesystems.images', 'local_secure_restricted');
407 $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
409 $pageA = $this->entities->page();
410 $pageB = $this->entities->page();
411 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
413 $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
416 $imageUrl = json_decode($upload->getContent(), true)['url'];
417 $pageB->html .= "<img src=\"{$imageUrl}\">";
420 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
421 $export = $this->get($pageB->getUrl('/export/html'));
422 $this->assertStringContainsString($encodedImageContent, $export->getContent());
424 $this->permissions->setEntityPermissions($pageA, [], []);
426 $export = $this->get($pageB->getUrl('/export/html'));
427 $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
429 if (file_exists($expectedPath)) {
430 unlink($expectedPath);
434 public function test_image_delete()
436 $page = $this->entities->page();
438 $imageName = 'first-image.png';
439 $relPath = $this->files->expectedImagePath('gallery', $imageName);
440 $this->files->deleteAtRelativePath($relPath);
442 $this->files->uploadGalleryImage($this, $imageName, $page->id);
443 $image = Image::first();
445 $delete = $this->delete('/images/' . $image->id);
446 $delete->assertStatus(200);
448 $this->assertDatabaseMissing('images', [
449 'url' => $this->baseUrl . $relPath,
453 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
456 public function test_image_delete_does_not_delete_similar_images()
458 $page = $this->entities->page();
460 $imageName = 'first-image.png';
462 $relPath = $this->files->expectedImagePath('gallery', $imageName);
463 $this->files->deleteAtRelativePath($relPath);
465 $this->files->uploadGalleryImage($this, $imageName, $page->id);
466 $this->files->uploadGalleryImage($this, $imageName, $page->id);
467 $this->files->uploadGalleryImage($this, $imageName, $page->id);
469 $image = Image::first();
470 $folder = public_path(dirname($relPath));
471 $imageCount = count(glob($folder . '/*'));
473 $delete = $this->delete('/images/' . $image->id);
474 $delete->assertStatus(200);
476 $newCount = count(glob($folder . '/*'));
477 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
478 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
481 public function test_image_manager_delete_button_only_shows_with_permission()
483 $page = $this->entities->page();
485 $imageName = 'first-image.png';
486 $relPath = $this->files->expectedImagePath('gallery', $imageName);
487 $this->files->deleteAtRelativePath($relPath);
488 $viewer = $this->users->viewer();
490 $this->files->uploadGalleryImage($this, $imageName, $page->id);
491 $image = Image::first();
493 $resp = $this->get("/images/edit/{$image->id}");
494 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
496 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
497 $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete[title="Delete"]');
499 $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
501 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
502 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
504 $this->files->deleteAtRelativePath($relPath);
507 protected function getTestProfileImage()
509 $imageName = 'profile.png';
510 $relPath = $this->files->expectedImagePath('user', $imageName);
511 $this->files->deleteAtRelativePath($relPath);
513 return $this->files->uploadedImage($imageName);
516 public function test_user_image_upload()
518 $editor = $this->users->editor();
519 $admin = $this->users->admin();
520 $this->actingAs($admin);
522 $file = $this->getTestProfileImage();
523 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
525 $this->assertDatabaseHas('images', [
527 'uploaded_to' => $editor->id,
528 'created_by' => $admin->id,
532 public function test_user_images_deleted_on_user_deletion()
534 $editor = $this->users->editor();
535 $this->actingAs($editor);
537 $file = $this->getTestProfileImage();
538 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
540 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
541 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
543 $imagePath = public_path($profileImages->first()->path);
544 $this->assertTrue(file_exists($imagePath));
546 $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
547 $userDelete->assertStatus(302);
549 $this->assertDatabaseMissing('images', [
551 'created_by' => $editor->id,
553 $this->assertDatabaseMissing('images', [
555 'uploaded_to' => $editor->id,
558 $this->assertFalse(file_exists($imagePath));
561 public function test_deleted_unused_images()
563 $page = $this->entities->page();
564 $admin = $this->users->admin();
565 $this->actingAs($admin);
567 $imageName = 'unused-image.png';
568 $relPath = $this->files->expectedImagePath('gallery', $imageName);
569 $this->files->deleteAtRelativePath($relPath);
571 $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
572 $upload->assertStatus(200);
573 $image = Image::where('type', '=', 'gallery')->first();
575 $pageRepo = app(PageRepo::class);
576 $pageRepo->update($page, [
577 'name' => $page->name,
578 'html' => $page->html . "<img src=\"{$image->url}\">",
582 // Ensure no images are reported as deletable
583 $imageService = app(ImageService::class);
584 $toDelete = $imageService->deleteUnusedImages(true, true);
585 $this->assertCount(0, $toDelete);
587 // Save a revision of our page without the image;
588 $pageRepo->update($page, [
589 'name' => $page->name,
590 'html' => '<p>Hello</p>',
594 // Ensure revision images are picked up okay
595 $imageService = app(ImageService::class);
596 $toDelete = $imageService->deleteUnusedImages(true, true);
597 $this->assertCount(0, $toDelete);
598 $toDelete = $imageService->deleteUnusedImages(false, true);
599 $this->assertCount(1, $toDelete);
601 // Check image is found when revisions are destroyed
602 $page->revisions()->delete();
603 $toDelete = $imageService->deleteUnusedImages(true, true);
604 $this->assertCount(1, $toDelete);
606 // Check the image is deleted
607 $absPath = public_path($relPath);
608 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
609 $toDelete = $imageService->deleteUnusedImages(true, false);
610 $this->assertCount(1, $toDelete);
611 $this->assertFalse(file_exists($absPath));
613 $this->files->deleteAtRelativePath($relPath);