]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Apply fixes from StyleCI
[bookstack] / tests / Uploads / ImageTest.php
1 <?php
2
3 namespace Tests\Uploads;
4
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;
10 use Tests\TestCase;
11
12 class ImageTest extends TestCase
13 {
14     use UsesImages;
15
16     public function test_image_upload()
17     {
18         $page = Page::query()->first();
19         $admin = $this->getAdmin();
20         $this->actingAs($admin);
21
22         $imgDetails = $this->uploadGalleryImage($page);
23         $relPath = $imgDetails['path'];
24
25         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
26
27         $this->deleteImage($relPath);
28
29         $this->assertDatabaseHas('images', [
30             'url'         => $this->baseUrl . $relPath,
31             'type'        => 'gallery',
32             'uploaded_to' => $page->id,
33             'path'        => $relPath,
34             'created_by'  => $admin->id,
35             'updated_by'  => $admin->id,
36             'name'        => $imgDetails['name'],
37         ]);
38     }
39
40     public function test_image_display_thumbnail_generation_does_not_increase_image_size()
41     {
42         $page = Page::query()->first();
43         $admin = $this->getAdmin();
44         $this->actingAs($admin);
45
46         $originalFile = $this->getTestImageFilePath('compressed.png');
47         $originalFileSize = filesize($originalFile);
48         $imgDetails = $this->uploadGalleryImage($page, 'compressed.png');
49         $relPath = $imgDetails['path'];
50
51         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
52         $displayImage = $imgDetails['response']->thumbs->display;
53
54         $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3));
55         $displayImagePath = public_path($displayImageRelPath);
56         $displayFileSize = filesize($displayImagePath);
57
58         $this->deleteImage($relPath);
59         $this->deleteImage($displayImageRelPath);
60
61         $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size');
62     }
63
64     public function test_image_edit()
65     {
66         $editor = $this->getEditor();
67         $this->actingAs($editor);
68
69         $imgDetails = $this->uploadGalleryImage();
70         $image = Image::query()->first();
71
72         $newName = Str::random();
73         $update = $this->put('/images/' . $image->id, ['name' => $newName]);
74         $update->assertSuccessful();
75         $update->assertSee($newName);
76
77         $this->deleteImage($imgDetails['path']);
78
79         $this->assertDatabaseHas('images', [
80             'type' => 'gallery',
81             'name' => $newName,
82         ]);
83     }
84
85     public function test_gallery_get_list_format()
86     {
87         $this->asEditor();
88
89         $imgDetails = $this->uploadGalleryImage();
90         $image = Image::query()->first();
91
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);
96
97         $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
98         $secondPageRequest->assertSuccessful()->assertElementNotExists('div');
99
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']);
103
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');
108     }
109
110     public function test_image_usage()
111     {
112         $page = Page::query()->first();
113         $editor = $this->getEditor();
114         $this->actingAs($editor);
115
116         $imgDetails = $this->uploadGalleryImage($page);
117
118         $image = Image::query()->first();
119         $page->html = '<img src="' . $image->url . '">';
120         $page->save();
121
122         $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
123         $usage->assertSuccessful();
124         $usage->assertSeeText($page->name);
125         $usage->assertSee($page->getUrl());
126
127         $this->deleteImage($imgDetails['path']);
128     }
129
130     public function test_php_files_cannot_be_uploaded()
131     {
132         $page = Page::query()->first();
133         $admin = $this->getAdmin();
134         $this->actingAs($admin);
135
136         $fileName = 'bad.php';
137         $relPath = $this->getTestImagePath('gallery', $fileName);
138         $this->deleteImage($relPath);
139
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);
143
144         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
145
146         $this->assertDatabaseMissing('images', [
147             'type' => 'gallery',
148             'name' => $fileName,
149         ]);
150     }
151
152     public function test_php_like_files_cannot_be_uploaded()
153     {
154         $page = Page::query()->first();
155         $admin = $this->getAdmin();
156         $this->actingAs($admin);
157
158         $fileName = 'bad.phtml';
159         $relPath = $this->getTestImagePath('gallery', $fileName);
160         $this->deleteImage($relPath);
161
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);
165
166         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
167     }
168
169     public function test_files_with_double_extensions_will_get_sanitized()
170     {
171         $page = Page::query()->first();
172         $admin = $this->getAdmin();
173         $this->actingAs($admin);
174
175         $fileName = 'bad.phtml.png';
176         $relPath = $this->getTestImagePath('gallery', $fileName);
177         $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
178         $this->deleteImage($expectedRelPath);
179
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);
183
184         $lastImage = Image::query()->latest('id')->first();
185
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));
190
191         $this->deleteImage($lastImage->path);
192     }
193
194     public function test_url_entities_removed_from_filenames()
195     {
196         $this->asEditor();
197         $badNames = [
198             'bad-char-#-image.png',
199             'bad-char-?-image.png',
200             '?#.png',
201             '?.png',
202             '#.png',
203         ];
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);
209
210             $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
211             $upload->assertStatus(200);
212
213             $lastImage = Image::query()->latest('id')->first();
214             $newFileName = explode('.', basename($lastImage->path))[0];
215
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');
219
220             $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
221
222             $this->deleteImage($lastImage->path);
223         }
224     }
225
226     public function test_secure_images_uploads_to_correct_place()
227     {
228         config()->set('filesystems.images', 'local_secure');
229         $this->asEditor();
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');
233
234         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
235         $upload->assertStatus(200);
236
237         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
238
239         if (file_exists($expectedPath)) {
240             unlink($expectedPath);
241         }
242     }
243
244     public function test_secure_images_included_in_exports()
245     {
246         config()->set('filesystems.images', 'local_secure');
247         $this->asEditor();
248         $galleryFile = $this->getTestImage('my-secure-test-upload.png');
249         $page = Page::query()->first();
250         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
251
252         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
253         $imageUrl = json_decode($upload->getContent(), true)['url'];
254         $page->html .= "<img src=\"{$imageUrl}\">";
255         $page->save();
256         $upload->assertStatus(200);
257
258         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
259         $export = $this->get($page->getUrl('/export/html'));
260         $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
261
262         if (file_exists($expectedPath)) {
263             unlink($expectedPath);
264         }
265     }
266
267     public function test_system_images_remain_public()
268     {
269         config()->set('filesystems.images', 'local_secure');
270         $this->asAdmin();
271         $galleryFile = $this->getTestImage('my-system-test-upload.png');
272         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
273
274         $upload = $this->call('POST', '/settings', [], [], ['app_logo' => $galleryFile], []);
275         $upload->assertRedirect('/settings');
276
277         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
278
279         if (file_exists($expectedPath)) {
280             unlink($expectedPath);
281         }
282     }
283
284     public function test_image_delete()
285     {
286         $page = Page::query()->first();
287         $this->asAdmin();
288         $imageName = 'first-image.png';
289         $relPath = $this->getTestImagePath('gallery', $imageName);
290         $this->deleteImage($relPath);
291
292         $this->uploadImage($imageName, $page->id);
293         $image = Image::first();
294
295         $delete = $this->delete('/images/' . $image->id);
296         $delete->assertStatus(200);
297
298         $this->assertDatabaseMissing('images', [
299             'url'  => $this->baseUrl . $relPath,
300             'type' => 'gallery',
301         ]);
302
303         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
304     }
305
306     public function test_image_delete_does_not_delete_similar_images()
307     {
308         $page = Page::query()->first();
309         $this->asAdmin();
310         $imageName = 'first-image.png';
311
312         $relPath = $this->getTestImagePath('gallery', $imageName);
313         $this->deleteImage($relPath);
314
315         $this->uploadImage($imageName, $page->id);
316         $this->uploadImage($imageName, $page->id);
317         $this->uploadImage($imageName, $page->id);
318
319         $image = Image::first();
320         $folder = public_path(dirname($relPath));
321         $imageCount = count(glob($folder . '/*'));
322
323         $delete = $this->delete('/images/' . $image->id);
324         $delete->assertStatus(200);
325
326         $newCount = count(glob($folder . '/*'));
327         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
328         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
329     }
330
331     protected function getTestProfileImage()
332     {
333         $imageName = 'profile.png';
334         $relPath = $this->getTestImagePath('user', $imageName);
335         $this->deleteImage($relPath);
336
337         return $this->getTestImage($imageName);
338     }
339
340     public function test_user_image_upload()
341     {
342         $editor = $this->getEditor();
343         $admin = $this->getAdmin();
344         $this->actingAs($admin);
345
346         $file = $this->getTestProfileImage();
347         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
348
349         $this->assertDatabaseHas('images', [
350             'type'        => 'user',
351             'uploaded_to' => $editor->id,
352             'created_by'  => $admin->id,
353         ]);
354     }
355
356     public function test_user_images_deleted_on_user_deletion()
357     {
358         $editor = $this->getEditor();
359         $this->actingAs($editor);
360
361         $file = $this->getTestProfileImage();
362         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
363
364         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
365         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
366
367         $imagePath = public_path($profileImages->first()->path);
368         $this->assertTrue(file_exists($imagePath));
369
370         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
371         $userDelete->assertStatus(302);
372
373         $this->assertDatabaseMissing('images', [
374             'type'       => 'user',
375             'created_by' => $editor->id,
376         ]);
377         $this->assertDatabaseMissing('images', [
378             'type'        => 'user',
379             'uploaded_to' => $editor->id,
380         ]);
381
382         $this->assertFalse(file_exists($imagePath));
383     }
384
385     public function test_deleted_unused_images()
386     {
387         $page = Page::query()->first();
388         $admin = $this->getAdmin();
389         $this->actingAs($admin);
390
391         $imageName = 'unused-image.png';
392         $relPath = $this->getTestImagePath('gallery', $imageName);
393         $this->deleteImage($relPath);
394
395         $upload = $this->uploadImage($imageName, $page->id);
396         $upload->assertStatus(200);
397         $image = Image::where('type', '=', 'gallery')->first();
398
399         $pageRepo = app(PageRepo::class);
400         $pageRepo->update($page, [
401             'name'    => $page->name,
402             'html'    => $page->html . "<img src=\"{$image->url}\">",
403             'summary' => '',
404         ]);
405
406         // Ensure no images are reported as deletable
407         $imageService = app(ImageService::class);
408         $toDelete = $imageService->deleteUnusedImages(true, true);
409         $this->assertCount(0, $toDelete);
410
411         // Save a revision of our page without the image;
412         $pageRepo->update($page, [
413             'name'    => $page->name,
414             'html'    => '<p>Hello</p>',
415             'summary' => '',
416         ]);
417
418         // Ensure revision images are picked up okay
419         $imageService = app(ImageService::class);
420         $toDelete = $imageService->deleteUnusedImages(true, true);
421         $this->assertCount(0, $toDelete);
422         $toDelete = $imageService->deleteUnusedImages(false, true);
423         $this->assertCount(1, $toDelete);
424
425         // Check image is found when revisions are destroyed
426         $page->revisions()->delete();
427         $toDelete = $imageService->deleteUnusedImages(true, true);
428         $this->assertCount(1, $toDelete);
429
430         // Check the image is deleted
431         $absPath = public_path($relPath);
432         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
433         $toDelete = $imageService->deleteUnusedImages(true, false);
434         $this->assertCount(1, $toDelete);
435         $this->assertFalse(file_exists($absPath));
436
437         $this->deleteImage($relPath);
438     }
439 }