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