3 namespace Tests\Uploads;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Repos\PageRepo;
7 use BookStack\Uploads\Image;
8 use BookStack\Uploads\ImageService;
9 use Illuminate\Support\Str;
12 class ImageTest extends TestCase
16 public function test_image_upload()
18 $page = Page::query()->first();
19 $admin = $this->getAdmin();
20 $this->actingAs($admin);
22 $imgDetails = $this->uploadGalleryImage($page);
23 $relPath = $imgDetails['path'];
25 $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
27 $this->deleteImage($relPath);
29 $this->assertDatabaseHas('images', [
30 'url' => $this->baseUrl . $relPath,
32 'uploaded_to' => $page->id,
34 'created_by' => $admin->id,
35 'updated_by' => $admin->id,
36 'name' => $imgDetails['name'],
40 public function test_image_display_thumbnail_generation_does_not_increase_image_size()
42 $page = Page::query()->first();
43 $admin = $this->getAdmin();
44 $this->actingAs($admin);
46 $originalFile = $this->getTestImageFilePath('compressed.png');
47 $originalFileSize = filesize($originalFile);
48 $imgDetails = $this->uploadGalleryImage($page, 'compressed.png');
49 $relPath = $imgDetails['path'];
51 $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
52 $displayImage = $imgDetails['response']->thumbs->display;
54 $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3));
55 $displayImagePath = public_path($displayImageRelPath);
56 $displayFileSize = filesize($displayImagePath);
58 $this->deleteImage($relPath);
59 $this->deleteImage($displayImageRelPath);
61 $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size');
64 public function test_image_display_thumbnail_generation_for_apng_images_uses_original_file()
66 $page = Page::query()->first();
67 $admin = $this->getAdmin();
68 $this->actingAs($admin);
70 $imgDetails = $this->uploadGalleryImage($page, 'animated.png');
71 $this->deleteImage($imgDetails['path']);
73 $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery);
74 $this->assertStringNotContainsString('thumbs-', $imgDetails['response']->thumbs->display);
77 public function test_image_edit()
79 $editor = $this->getEditor();
80 $this->actingAs($editor);
82 $imgDetails = $this->uploadGalleryImage();
83 $image = Image::query()->first();
85 $newName = Str::random();
86 $update = $this->put('/images/' . $image->id, ['name' => $newName]);
87 $update->assertSuccessful();
88 $update->assertSee($newName);
90 $this->deleteImage($imgDetails['path']);
92 $this->assertDatabaseHas('images', [
98 public function test_gallery_get_list_format()
102 $imgDetails = $this->uploadGalleryImage();
103 $image = Image::query()->first();
105 $pageId = $imgDetails['page']->id;
106 $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
107 $firstPageRequest->assertSuccessful()->assertElementExists('div');
108 $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
110 $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
111 $secondPageRequest->assertSuccessful()->assertElementNotExists('div');
113 $namePartial = substr($imgDetails['name'], 0, 3);
114 $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
115 $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
117 $namePartial = Str::random(16);
118 $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
119 $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
120 $searchFailRequest->assertSuccessful()->assertElementNotExists('div');
123 public function test_image_usage()
125 $page = Page::query()->first();
126 $editor = $this->getEditor();
127 $this->actingAs($editor);
129 $imgDetails = $this->uploadGalleryImage($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->deleteImage($imgDetails['path']);
143 public function test_php_files_cannot_be_uploaded()
145 $page = Page::query()->first();
146 $admin = $this->getAdmin();
147 $this->actingAs($admin);
149 $fileName = 'bad.php';
150 $relPath = $this->getTestImagePath('gallery', $fileName);
151 $this->deleteImage($relPath);
153 $file = $this->newTestImageFromBase64('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 = Page::query()->first();
168 $admin = $this->getAdmin();
169 $this->actingAs($admin);
171 $fileName = 'bad.phtml';
172 $relPath = $this->getTestImagePath('gallery', $fileName);
173 $this->deleteImage($relPath);
175 $file = $this->newTestImageFromBase64('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 = Page::query()->first();
185 $admin = $this->getAdmin();
186 $this->actingAs($admin);
188 $fileName = 'bad.phtml.png';
189 $relPath = $this->getTestImagePath('gallery', $fileName);
190 $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
191 $this->deleteImage($expectedRelPath);
193 $file = $this->newTestImageFromBase64('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->deleteImage($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->getTestImage($name);
219 $page = Page::query()->first();
220 $badPath = $this->getTestImagePath('gallery', $name);
221 $this->deleteImage($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->deleteImage($lastImage->path);
239 public function test_secure_images_uploads_to_correct_place()
241 config()->set('filesystems.images', 'local_secure');
243 $galleryFile = $this->getTestImage('my-secure-test-upload.png');
244 $page = Page::query()->first();
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->getTestImage('my-secure-test-upload.png');
292 $page = Page::query()->first();
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()
312 config()->set('filesystems.images', 'local_secure');
314 $galleryFile = $this->getTestImage('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', [], [], ['app_logo' => $galleryFile], []);
318 $upload->assertRedirect('/settings');
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_image_delete()
329 $page = Page::query()->first();
331 $imageName = 'first-image.png';
332 $relPath = $this->getTestImagePath('gallery', $imageName);
333 $this->deleteImage($relPath);
335 $this->uploadImage($imageName, $page->id);
336 $image = Image::first();
338 $delete = $this->delete('/images/' . $image->id);
339 $delete->assertStatus(200);
341 $this->assertDatabaseMissing('images', [
342 'url' => $this->baseUrl . $relPath,
346 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
349 public function test_image_delete_does_not_delete_similar_images()
351 $page = Page::query()->first();
353 $imageName = 'first-image.png';
355 $relPath = $this->getTestImagePath('gallery', $imageName);
356 $this->deleteImage($relPath);
358 $this->uploadImage($imageName, $page->id);
359 $this->uploadImage($imageName, $page->id);
360 $this->uploadImage($imageName, $page->id);
362 $image = Image::first();
363 $folder = public_path(dirname($relPath));
364 $imageCount = count(glob($folder . '/*'));
366 $delete = $this->delete('/images/' . $image->id);
367 $delete->assertStatus(200);
369 $newCount = count(glob($folder . '/*'));
370 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
371 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
374 protected function getTestProfileImage()
376 $imageName = 'profile.png';
377 $relPath = $this->getTestImagePath('user', $imageName);
378 $this->deleteImage($relPath);
380 return $this->getTestImage($imageName);
383 public function test_user_image_upload()
385 $editor = $this->getEditor();
386 $admin = $this->getAdmin();
387 $this->actingAs($admin);
389 $file = $this->getTestProfileImage();
390 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
392 $this->assertDatabaseHas('images', [
394 'uploaded_to' => $editor->id,
395 'created_by' => $admin->id,
399 public function test_user_images_deleted_on_user_deletion()
401 $editor = $this->getEditor();
402 $this->actingAs($editor);
404 $file = $this->getTestProfileImage();
405 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
407 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
408 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
410 $imagePath = public_path($profileImages->first()->path);
411 $this->assertTrue(file_exists($imagePath));
413 $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
414 $userDelete->assertStatus(302);
416 $this->assertDatabaseMissing('images', [
418 'created_by' => $editor->id,
420 $this->assertDatabaseMissing('images', [
422 'uploaded_to' => $editor->id,
425 $this->assertFalse(file_exists($imagePath));
428 public function test_deleted_unused_images()
430 $page = Page::query()->first();
431 $admin = $this->getAdmin();
432 $this->actingAs($admin);
434 $imageName = 'unused-image.png';
435 $relPath = $this->getTestImagePath('gallery', $imageName);
436 $this->deleteImage($relPath);
438 $upload = $this->uploadImage($imageName, $page->id);
439 $upload->assertStatus(200);
440 $image = Image::where('type', '=', 'gallery')->first();
442 $pageRepo = app(PageRepo::class);
443 $pageRepo->update($page, [
444 'name' => $page->name,
445 'html' => $page->html . "<img src=\"{$image->url}\">",
449 // Ensure no images are reported as deletable
450 $imageService = app(ImageService::class);
451 $toDelete = $imageService->deleteUnusedImages(true, true);
452 $this->assertCount(0, $toDelete);
454 // Save a revision of our page without the image;
455 $pageRepo->update($page, [
456 'name' => $page->name,
457 'html' => '<p>Hello</p>',
461 // Ensure revision images are picked up okay
462 $imageService = app(ImageService::class);
463 $toDelete = $imageService->deleteUnusedImages(true, true);
464 $this->assertCount(0, $toDelete);
465 $toDelete = $imageService->deleteUnusedImages(false, true);
466 $this->assertCount(1, $toDelete);
468 // Check image is found when revisions are destroyed
469 $page->revisions()->delete();
470 $toDelete = $imageService->deleteUnusedImages(true, true);
471 $this->assertCount(1, $toDelete);
473 // Check the image is deleted
474 $absPath = public_path($relPath);
475 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
476 $toDelete = $imageService->deleteUnusedImages(true, false);
477 $this->assertCount(1, $toDelete);
478 $this->assertFalse(file_exists($absPath));
480 $this->deleteImage($relPath);