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_edit()
66 $editor = $this->getEditor();
67 $this->actingAs($editor);
69 $imgDetails = $this->uploadGalleryImage();
70 $image = Image::query()->first();
72 $newName = Str::random();
73 $update = $this->put('/images/' . $image->id, ['name' => $newName]);
74 $update->assertSuccessful();
75 $update->assertSee($newName);
77 $this->deleteImage($imgDetails['path']);
79 $this->assertDatabaseHas('images', [
85 public function test_gallery_get_list_format()
89 $imgDetails = $this->uploadGalleryImage();
90 $image = Image::query()->first();
92 $pageId = $imgDetails['page']->id;
93 $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
94 $firstPageRequest->assertSuccessful()->assertElementExists('div');
95 $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
97 $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
98 $secondPageRequest->assertSuccessful()->assertElementNotExists('div');
100 $namePartial = substr($imgDetails['name'], 0, 3);
101 $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
102 $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
104 $namePartial = Str::random(16);
105 $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
106 $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
107 $searchFailRequest->assertSuccessful()->assertElementNotExists('div');
110 public function test_image_usage()
112 $page = Page::query()->first();
113 $editor = $this->getEditor();
114 $this->actingAs($editor);
116 $imgDetails = $this->uploadGalleryImage($page);
118 $image = Image::query()->first();
119 $page->html = '<img src="' . $image->url . '">';
122 $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
123 $usage->assertSuccessful();
124 $usage->assertSeeText($page->name);
125 $usage->assertSee($page->getUrl());
127 $this->deleteImage($imgDetails['path']);
130 public function test_php_files_cannot_be_uploaded()
132 $page = Page::query()->first();
133 $admin = $this->getAdmin();
134 $this->actingAs($admin);
136 $fileName = 'bad.php';
137 $relPath = $this->getTestImagePath('gallery', $fileName);
138 $this->deleteImage($relPath);
140 $file = $this->newTestImageFromBase64('bad-php.base64', $fileName);
141 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
142 $upload->assertStatus(302);
144 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
146 $this->assertDatabaseMissing('images', [
152 public function test_php_like_files_cannot_be_uploaded()
154 $page = Page::query()->first();
155 $admin = $this->getAdmin();
156 $this->actingAs($admin);
158 $fileName = 'bad.phtml';
159 $relPath = $this->getTestImagePath('gallery', $fileName);
160 $this->deleteImage($relPath);
162 $file = $this->newTestImageFromBase64('bad-phtml.base64', $fileName);
163 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
164 $upload->assertStatus(302);
166 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
169 public function test_files_with_double_extensions_will_get_sanitized()
171 $page = Page::query()->first();
172 $admin = $this->getAdmin();
173 $this->actingAs($admin);
175 $fileName = 'bad.phtml.png';
176 $relPath = $this->getTestImagePath('gallery', $fileName);
177 $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
178 $this->deleteImage($expectedRelPath);
180 $file = $this->newTestImageFromBase64('bad-phtml-png.base64', $fileName);
181 $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
182 $upload->assertStatus(200);
184 $lastImage = Image::query()->latest('id')->first();
186 $this->assertEquals('bad.phtml.png', $lastImage->name);
187 $this->assertEquals('bad-phtml.png', basename($lastImage->path));
188 $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
189 $this->assertFileExists(public_path($expectedRelPath));
191 $this->deleteImage($lastImage->path);
194 public function test_url_entities_removed_from_filenames()
198 'bad-char-#-image.png',
199 'bad-char-?-image.png',
204 foreach ($badNames as $name) {
205 $galleryFile = $this->getTestImage($name);
206 $page = Page::query()->first();
207 $badPath = $this->getTestImagePath('gallery', $name);
208 $this->deleteImage($badPath);
210 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
211 $upload->assertStatus(200);
213 $lastImage = Image::query()->latest('id')->first();
214 $newFileName = explode('.', basename($lastImage->path))[0];
216 $this->assertEquals($lastImage->name, $name);
217 $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
218 $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
220 $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
222 $this->deleteImage($lastImage->path);
226 public function test_secure_images_uploads_to_correct_place()
228 config()->set('filesystems.images', 'local_secure');
230 $galleryFile = $this->getTestImage('my-secure-test-upload.png');
231 $page = Page::query()->first();
232 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
234 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
235 $upload->assertStatus(200);
237 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
239 if (file_exists($expectedPath)) {
240 unlink($expectedPath);
244 public function test_secure_image_paths_traversal_causes_500()
246 config()->set('filesystems.images', 'local_secure');
249 $resp = $this->get('/uploads/images/../../logs/laravel.log');
250 $resp->assertStatus(500);
253 public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
255 config()->set('filesystems.images', 'local');
258 $resp = $this->get('/uploads/images/../../logs/laravel.log');
259 $resp->assertStatus(404);
262 public function test_secure_image_paths_dont_serve_non_images()
264 config()->set('filesystems.images', 'local_secure');
267 $testFilePath = storage_path('/uploads/images/testing.txt');
268 file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
270 $resp = $this->get('/uploads/images/testing.txt');
271 $resp->assertStatus(404);
274 public function test_secure_images_included_in_exports()
276 config()->set('filesystems.images', 'local_secure');
278 $galleryFile = $this->getTestImage('my-secure-test-upload.png');
279 $page = Page::query()->first();
280 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
282 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
283 $imageUrl = json_decode($upload->getContent(), true)['url'];
284 $page->html .= "<img src=\"{$imageUrl}\">";
286 $upload->assertStatus(200);
288 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
289 $export = $this->get($page->getUrl('/export/html'));
290 $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
292 if (file_exists($expectedPath)) {
293 unlink($expectedPath);
297 public function test_system_images_remain_public()
299 config()->set('filesystems.images', 'local_secure');
301 $galleryFile = $this->getTestImage('my-system-test-upload.png');
302 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
304 $upload = $this->call('POST', '/settings', [], [], ['app_logo' => $galleryFile], []);
305 $upload->assertRedirect('/settings');
307 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
309 if (file_exists($expectedPath)) {
310 unlink($expectedPath);
314 public function test_image_delete()
316 $page = Page::query()->first();
318 $imageName = 'first-image.png';
319 $relPath = $this->getTestImagePath('gallery', $imageName);
320 $this->deleteImage($relPath);
322 $this->uploadImage($imageName, $page->id);
323 $image = Image::first();
325 $delete = $this->delete('/images/' . $image->id);
326 $delete->assertStatus(200);
328 $this->assertDatabaseMissing('images', [
329 'url' => $this->baseUrl . $relPath,
333 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
336 public function test_image_delete_does_not_delete_similar_images()
338 $page = Page::query()->first();
340 $imageName = 'first-image.png';
342 $relPath = $this->getTestImagePath('gallery', $imageName);
343 $this->deleteImage($relPath);
345 $this->uploadImage($imageName, $page->id);
346 $this->uploadImage($imageName, $page->id);
347 $this->uploadImage($imageName, $page->id);
349 $image = Image::first();
350 $folder = public_path(dirname($relPath));
351 $imageCount = count(glob($folder . '/*'));
353 $delete = $this->delete('/images/' . $image->id);
354 $delete->assertStatus(200);
356 $newCount = count(glob($folder . '/*'));
357 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
358 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
361 protected function getTestProfileImage()
363 $imageName = 'profile.png';
364 $relPath = $this->getTestImagePath('user', $imageName);
365 $this->deleteImage($relPath);
367 return $this->getTestImage($imageName);
370 public function test_user_image_upload()
372 $editor = $this->getEditor();
373 $admin = $this->getAdmin();
374 $this->actingAs($admin);
376 $file = $this->getTestProfileImage();
377 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
379 $this->assertDatabaseHas('images', [
381 'uploaded_to' => $editor->id,
382 'created_by' => $admin->id,
386 public function test_user_images_deleted_on_user_deletion()
388 $editor = $this->getEditor();
389 $this->actingAs($editor);
391 $file = $this->getTestProfileImage();
392 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
394 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
395 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
397 $imagePath = public_path($profileImages->first()->path);
398 $this->assertTrue(file_exists($imagePath));
400 $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
401 $userDelete->assertStatus(302);
403 $this->assertDatabaseMissing('images', [
405 'created_by' => $editor->id,
407 $this->assertDatabaseMissing('images', [
409 'uploaded_to' => $editor->id,
412 $this->assertFalse(file_exists($imagePath));
415 public function test_deleted_unused_images()
417 $page = Page::query()->first();
418 $admin = $this->getAdmin();
419 $this->actingAs($admin);
421 $imageName = 'unused-image.png';
422 $relPath = $this->getTestImagePath('gallery', $imageName);
423 $this->deleteImage($relPath);
425 $upload = $this->uploadImage($imageName, $page->id);
426 $upload->assertStatus(200);
427 $image = Image::where('type', '=', 'gallery')->first();
429 $pageRepo = app(PageRepo::class);
430 $pageRepo->update($page, [
431 'name' => $page->name,
432 'html' => $page->html . "<img src=\"{$image->url}\">",
436 // Ensure no images are reported as deletable
437 $imageService = app(ImageService::class);
438 $toDelete = $imageService->deleteUnusedImages(true, true);
439 $this->assertCount(0, $toDelete);
441 // Save a revision of our page without the image;
442 $pageRepo->update($page, [
443 'name' => $page->name,
444 'html' => '<p>Hello</p>',
448 // Ensure revision images are picked up okay
449 $imageService = app(ImageService::class);
450 $toDelete = $imageService->deleteUnusedImages(true, true);
451 $this->assertCount(0, $toDelete);
452 $toDelete = $imageService->deleteUnusedImages(false, true);
453 $this->assertCount(1, $toDelete);
455 // Check image is found when revisions are destroyed
456 $page->revisions()->delete();
457 $toDelete = $imageService->deleteUnusedImages(true, true);
458 $this->assertCount(1, $toDelete);
460 // Check the image is deleted
461 $absPath = public_path($relPath);
462 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
463 $toDelete = $imageService->deleteUnusedImages(true, false);
464 $this->assertCount(1, $toDelete);
465 $this->assertFalse(file_exists($absPath));
467 $this->deleteImage($relPath);