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_usage()
125 $page = $this->entities->page();
126 $editor = $this->users->editor();
127 $this->actingAs($editor);
129 $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
131 $image = Image::query()->first();
132 $page->html = '<img src="' . $image->url . '">';
135 $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
136 $usage->assertSuccessful();
137 $usage->assertSeeText($page->name);
138 $usage->assertSee($page->getUrl());
140 $this->files->deleteAtRelativePath($imgDetails['path']);
143 public function test_php_files_cannot_be_uploaded()
145 $page = $this->entities->page();
146 $admin = $this->users->admin();
147 $this->actingAs($admin);
149 $fileName = 'bad.php';
150 $relPath = $this->files->expectedImagePath('gallery', $fileName);
151 $this->files->deleteAtRelativePath($relPath);
153 $file = $this->files->imageFromBase64File('bad-php.base64', $fileName);
154 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
155 $upload->assertStatus(302);
157 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
159 $this->assertDatabaseMissing('images', [
165 public function test_php_like_files_cannot_be_uploaded()
167 $page = $this->entities->page();
168 $admin = $this->users->admin();
169 $this->actingAs($admin);
171 $fileName = 'bad.phtml';
172 $relPath = $this->files->expectedImagePath('gallery', $fileName);
173 $this->files->deleteAtRelativePath($relPath);
175 $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName);
176 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
177 $upload->assertStatus(302);
179 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
182 public function test_files_with_double_extensions_will_get_sanitized()
184 $page = $this->entities->page();
185 $admin = $this->users->admin();
186 $this->actingAs($admin);
188 $fileName = 'bad.phtml.png';
189 $relPath = $this->files->expectedImagePath('gallery', $fileName);
190 $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
191 $this->files->deleteAtRelativePath($expectedRelPath);
193 $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName);
194 $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
195 $upload->assertStatus(200);
197 $lastImage = Image::query()->latest('id')->first();
199 $this->assertEquals('bad.phtml.png', $lastImage->name);
200 $this->assertEquals('bad-phtml.png', basename($lastImage->path));
201 $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
202 $this->assertFileExists(public_path($expectedRelPath));
204 $this->files->deleteAtRelativePath($lastImage->path);
207 public function test_url_entities_removed_from_filenames()
211 'bad-char-#-image.png',
212 'bad-char-?-image.png',
217 foreach ($badNames as $name) {
218 $galleryFile = $this->files->uploadedImage($name);
219 $page = $this->entities->page();
220 $badPath = $this->files->expectedImagePath('gallery', $name);
221 $this->files->deleteAtRelativePath($badPath);
223 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
224 $upload->assertStatus(200);
226 $lastImage = Image::query()->latest('id')->first();
227 $newFileName = explode('.', basename($lastImage->path))[0];
229 $this->assertEquals($lastImage->name, $name);
230 $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
231 $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
233 $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
235 $this->files->deleteAtRelativePath($lastImage->path);
239 public function test_secure_images_uploads_to_correct_place()
241 config()->set('filesystems.images', 'local_secure');
243 $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
244 $page = $this->entities->page();
245 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
247 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
248 $upload->assertStatus(200);
250 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
252 if (file_exists($expectedPath)) {
253 unlink($expectedPath);
257 public function test_secure_image_paths_traversal_causes_500()
259 config()->set('filesystems.images', 'local_secure');
262 $resp = $this->get('/uploads/images/../../logs/laravel.log');
263 $resp->assertStatus(500);
266 public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
268 config()->set('filesystems.images', 'local');
271 $resp = $this->get('/uploads/images/../../logs/laravel.log');
272 $resp->assertStatus(404);
275 public function test_secure_image_paths_dont_serve_non_images()
277 config()->set('filesystems.images', 'local_secure');
280 $testFilePath = storage_path('/uploads/images/testing.txt');
281 file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
283 $resp = $this->get('/uploads/images/testing.txt');
284 $resp->assertStatus(404);
287 public function test_secure_images_included_in_exports()
289 config()->set('filesystems.images', 'local_secure');
291 $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
292 $page = $this->entities->page();
293 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
295 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
296 $imageUrl = json_decode($upload->getContent(), true)['url'];
297 $page->html .= "<img src=\"{$imageUrl}\">";
299 $upload->assertStatus(200);
301 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
302 $export = $this->get($page->getUrl('/export/html'));
303 $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
305 if (file_exists($expectedPath)) {
306 unlink($expectedPath);
310 public function test_system_images_remain_public_with_local_secure()
312 config()->set('filesystems.images', 'local_secure');
314 $galleryFile = $this->files->uploadedImage('my-system-test-upload.png');
315 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
317 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
318 $upload->assertRedirect('/settings/customization');
320 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
322 if (file_exists($expectedPath)) {
323 unlink($expectedPath);
327 public function test_system_images_remain_public_with_local_secure_restricted()
329 config()->set('filesystems.images', 'local_secure_restricted');
331 $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
332 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
334 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
335 $upload->assertRedirect('/settings/customization');
337 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
339 if (file_exists($expectedPath)) {
340 unlink($expectedPath);
344 public function test_secure_restricted_images_inaccessible_without_relation_permission()
346 config()->set('filesystems.images', 'local_secure_restricted');
348 $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
349 $page = $this->entities->page();
351 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
352 $upload->assertStatus(200);
353 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
354 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
356 $this->get($expectedUrl)->assertOk();
358 $this->permissions->setEntityPermissions($page, [], []);
360 $resp = $this->get($expectedUrl);
361 $resp->assertNotFound();
363 if (file_exists($expectedPath)) {
364 unlink($expectedPath);
368 public function test_thumbnail_path_handled_by_secure_restricted_images()
370 config()->set('filesystems.images', 'local_secure_restricted');
372 $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
373 $page = $this->entities->page();
375 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
376 $upload->assertStatus(200);
377 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
378 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
380 $this->get($expectedUrl)->assertOk();
382 $this->permissions->setEntityPermissions($page, [], []);
384 $resp = $this->get($expectedUrl);
385 $resp->assertNotFound();
387 if (file_exists($expectedPath)) {
388 unlink($expectedPath);
392 public function test_secure_restricted_image_access_controlled_in_exports()
394 config()->set('filesystems.images', 'local_secure_restricted');
396 $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
398 $pageA = $this->entities->page();
399 $pageB = $this->entities->page();
400 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
402 $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
405 $imageUrl = json_decode($upload->getContent(), true)['url'];
406 $pageB->html .= "<img src=\"{$imageUrl}\">";
409 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
410 $export = $this->get($pageB->getUrl('/export/html'));
411 $this->assertStringContainsString($encodedImageContent, $export->getContent());
413 $this->permissions->setEntityPermissions($pageA, [], []);
415 $export = $this->get($pageB->getUrl('/export/html'));
416 $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
418 if (file_exists($expectedPath)) {
419 unlink($expectedPath);
423 public function test_image_delete()
425 $page = $this->entities->page();
427 $imageName = 'first-image.png';
428 $relPath = $this->files->expectedImagePath('gallery', $imageName);
429 $this->files->deleteAtRelativePath($relPath);
431 $this->files->uploadGalleryImage($this, $imageName, $page->id);
432 $image = Image::first();
434 $delete = $this->delete('/images/' . $image->id);
435 $delete->assertStatus(200);
437 $this->assertDatabaseMissing('images', [
438 'url' => $this->baseUrl . $relPath,
442 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
445 public function test_image_delete_does_not_delete_similar_images()
447 $page = $this->entities->page();
449 $imageName = 'first-image.png';
451 $relPath = $this->files->expectedImagePath('gallery', $imageName);
452 $this->files->deleteAtRelativePath($relPath);
454 $this->files->uploadGalleryImage($this, $imageName, $page->id);
455 $this->files->uploadGalleryImage($this, $imageName, $page->id);
456 $this->files->uploadGalleryImage($this, $imageName, $page->id);
458 $image = Image::first();
459 $folder = public_path(dirname($relPath));
460 $imageCount = count(glob($folder . '/*'));
462 $delete = $this->delete('/images/' . $image->id);
463 $delete->assertStatus(200);
465 $newCount = count(glob($folder . '/*'));
466 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
467 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
470 public function test_image_manager_delete_button_only_shows_with_permission()
472 $page = $this->entities->page();
474 $imageName = 'first-image.png';
475 $relPath = $this->files->expectedImagePath('gallery', $imageName);
476 $this->files->deleteAtRelativePath($relPath);
477 $viewer = $this->users->viewer();
479 $this->files->uploadGalleryImage($this, $imageName, $page->id);
480 $image = Image::first();
482 $resp = $this->get("/images/edit/{$image->id}");
483 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
485 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
486 $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete[title="Delete"]');
488 $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
490 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
491 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
493 $this->files->deleteAtRelativePath($relPath);
496 protected function getTestProfileImage()
498 $imageName = 'profile.png';
499 $relPath = $this->files->expectedImagePath('user', $imageName);
500 $this->files->deleteAtRelativePath($relPath);
502 return $this->files->uploadedImage($imageName);
505 public function test_user_image_upload()
507 $editor = $this->users->editor();
508 $admin = $this->users->admin();
509 $this->actingAs($admin);
511 $file = $this->getTestProfileImage();
512 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
514 $this->assertDatabaseHas('images', [
516 'uploaded_to' => $editor->id,
517 'created_by' => $admin->id,
521 public function test_user_images_deleted_on_user_deletion()
523 $editor = $this->users->editor();
524 $this->actingAs($editor);
526 $file = $this->getTestProfileImage();
527 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
529 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
530 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
532 $imagePath = public_path($profileImages->first()->path);
533 $this->assertTrue(file_exists($imagePath));
535 $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
536 $userDelete->assertStatus(302);
538 $this->assertDatabaseMissing('images', [
540 'created_by' => $editor->id,
542 $this->assertDatabaseMissing('images', [
544 'uploaded_to' => $editor->id,
547 $this->assertFalse(file_exists($imagePath));
550 public function test_deleted_unused_images()
552 $page = $this->entities->page();
553 $admin = $this->users->admin();
554 $this->actingAs($admin);
556 $imageName = 'unused-image.png';
557 $relPath = $this->files->expectedImagePath('gallery', $imageName);
558 $this->files->deleteAtRelativePath($relPath);
560 $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
561 $upload->assertStatus(200);
562 $image = Image::where('type', '=', 'gallery')->first();
564 $pageRepo = app(PageRepo::class);
565 $pageRepo->update($page, [
566 'name' => $page->name,
567 'html' => $page->html . "<img src=\"{$image->url}\">",
571 // Ensure no images are reported as deletable
572 $imageService = app(ImageService::class);
573 $toDelete = $imageService->deleteUnusedImages(true, true);
574 $this->assertCount(0, $toDelete);
576 // Save a revision of our page without the image;
577 $pageRepo->update($page, [
578 'name' => $page->name,
579 'html' => '<p>Hello</p>',
583 // Ensure revision images are picked up okay
584 $imageService = app(ImageService::class);
585 $toDelete = $imageService->deleteUnusedImages(true, true);
586 $this->assertCount(0, $toDelete);
587 $toDelete = $imageService->deleteUnusedImages(false, true);
588 $this->assertCount(1, $toDelete);
590 // Check image is found when revisions are destroyed
591 $page->revisions()->delete();
592 $toDelete = $imageService->deleteUnusedImages(true, true);
593 $this->assertCount(1, $toDelete);
595 // Check the image is deleted
596 $absPath = public_path($relPath);
597 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
598 $toDelete = $imageService->deleteUnusedImages(true, false);
599 $this->assertCount(1, $toDelete);
600 $this->assertFalse(file_exists($absPath));
602 $this->files->deleteAtRelativePath($relPath);