]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
3cdcdf3fd6cf658bfc84b31fc0607d6b64514980
[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\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::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::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->assertJson([
75             'id' => $image->id,
76             'name' => $newName,
77             'type' => 'gallery',
78         ]);
79
80         $this->deleteImage($imgDetails['path']);
81
82         $this->assertDatabaseHas('images', [
83             'type' => 'gallery',
84             'name' => $newName
85         ]);
86     }
87
88     public function test_gallery_get_list_format()
89     {
90         $this->asEditor();
91
92         $imgDetails = $this->uploadGalleryImage();
93         $image = Image::query()->first();
94
95         $emptyJson = ['images' => [], 'has_more' => false];
96         $resultJson = [
97             'images' => [
98                 [
99                     'id' => $image->id,
100                     'name' => $imgDetails['name'],
101                 ]
102             ],
103             'has_more' => false,
104         ];
105
106         $pageId = $imgDetails['page']->id;
107         $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
108         $firstPageRequest->assertSuccessful()->assertJson($resultJson);
109
110         $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
111         $secondPageRequest->assertSuccessful()->assertExactJson($emptyJson);
112
113         $namePartial = substr($imgDetails['name'], 0, 3);
114         $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
115         $searchHitRequest->assertSuccessful()->assertJson($resultJson);
116
117         $namePartial = Str::random(16);
118         $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
119         $searchHitRequest->assertSuccessful()->assertExactJson($emptyJson);
120     }
121
122     public function test_image_usage()
123     {
124         $page = Page::first();
125         $editor = $this->getEditor();
126         $this->actingAs($editor);
127
128         $imgDetails = $this->uploadGalleryImage($page);
129
130         $image = Image::query()->first();
131         $page->html = '<img src="'.$image->url.'">';
132         $page->save();
133
134         $usage = $this->get('/images/usage/' . $image->id);
135         $usage->assertSuccessful();
136         $usage->assertJson([
137             [
138                 'id' => $page->id,
139                 'name' => $page->name
140             ]
141         ]);
142
143         $this->deleteImage($imgDetails['path']);
144     }
145
146     public function test_php_files_cannot_be_uploaded()
147     {
148         $page = Page::first();
149         $admin = $this->getAdmin();
150         $this->actingAs($admin);
151
152         $fileName = 'bad.php';
153         $relPath = $this->getTestImagePath('gallery', $fileName);
154         $this->deleteImage($relPath);
155
156         $file = $this->getTestImage($fileName);
157         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
158         $upload->assertStatus(302);
159
160         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
161
162         $this->assertDatabaseMissing('images', [
163             'type' => 'gallery',
164             'name' => $fileName
165         ]);
166     }
167
168     public function test_php_like_files_cannot_be_uploaded()
169     {
170         $page = Page::first();
171         $admin = $this->getAdmin();
172         $this->actingAs($admin);
173
174         $fileName = 'bad.phtml';
175         $relPath = $this->getTestImagePath('gallery', $fileName);
176         $this->deleteImage($relPath);
177
178         $file = $this->getTestImage($fileName);
179         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
180         $upload->assertStatus(302);
181
182         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
183     }
184
185     public function test_files_with_double_extensions_cannot_be_uploaded()
186     {
187         $page = Page::first();
188         $admin = $this->getAdmin();
189         $this->actingAs($admin);
190
191         $fileName = 'bad.phtml.png';
192         $relPath = $this->getTestImagePath('gallery', $fileName);
193         $this->deleteImage($relPath);
194
195         $file = $this->getTestImage($fileName);
196         $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
197         $upload->assertStatus(302);
198
199         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded double extension file was uploaded but should have been stopped');
200     }
201
202     public function test_secure_images_uploads_to_correct_place()
203     {
204         config()->set('filesystems.images', 'local_secure');
205         $this->asEditor();
206         $galleryFile = $this->getTestImage('my-secure-test-upload.png');
207         $page = Page::first();
208         $expectedPath = storage_path('uploads/images/gallery/' . Date('Y-m') . '/my-secure-test-upload.png');
209
210         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
211         $upload->assertStatus(200);
212
213         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '. $expectedPath);
214
215         if (file_exists($expectedPath)) {
216             unlink($expectedPath);
217         }
218     }
219
220     public function test_secure_images_included_in_exports()
221     {
222         config()->set('filesystems.images', 'local_secure');
223         $this->asEditor();
224         $galleryFile = $this->getTestImage('my-secure-test-upload.png');
225         $page = Page::first();
226         $expectedPath = storage_path('uploads/images/gallery/' . Date('Y-m') . '/my-secure-test-upload.png');
227
228         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
229         $imageUrl = json_decode($upload->getContent(), true)['url'];
230         $page->html .= "<img src=\"{$imageUrl}\">";
231         $page->save();
232         $upload->assertStatus(200);
233
234         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
235         $export = $this->get($page->getUrl('/export/html'));
236         $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
237
238         if (file_exists($expectedPath)) {
239             unlink($expectedPath);
240         }
241     }
242
243     public function test_system_images_remain_public()
244     {
245         config()->set('filesystems.images', 'local_secure');
246         $this->asAdmin();
247         $galleryFile = $this->getTestImage('my-system-test-upload.png');
248         $expectedPath = public_path('uploads/images/system/' . Date('Y-m') . '/my-system-test-upload.png');
249
250         $upload = $this->call('POST', '/settings', [], [], ['app_logo' => $galleryFile], []);
251         $upload->assertRedirect('/settings');
252
253         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '. $expectedPath);
254
255         if (file_exists($expectedPath)) {
256             unlink($expectedPath);
257         }
258     }
259
260     public function test_image_delete()
261     {
262         $page = Page::first();
263         $this->asAdmin();
264         $imageName = 'first-image.png';
265         $relPath = $this->getTestImagePath('gallery', $imageName);
266         $this->deleteImage($relPath);
267
268         $this->uploadImage($imageName, $page->id);
269         $image = Image::first();
270
271         $delete = $this->delete( '/images/' . $image->id);
272         $delete->assertStatus(200);
273
274         $this->assertDatabaseMissing('images', [
275             'url' => $this->baseUrl . $relPath,
276             'type' => 'gallery'
277         ]);
278
279         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
280     }
281
282     public function test_image_delete_does_not_delete_similar_images()
283     {
284         $page = Page::first();
285         $this->asAdmin();
286         $imageName = 'first-image.png';
287
288         $relPath = $this->getTestImagePath('gallery', $imageName);
289         $this->deleteImage($relPath);
290
291         $this->uploadImage($imageName, $page->id);
292         $this->uploadImage($imageName, $page->id);
293         $this->uploadImage($imageName, $page->id);
294
295         $image = Image::first();
296         $folder = public_path(dirname($relPath));
297         $imageCount = count(glob($folder . '/*'));
298
299         $delete = $this->delete( '/images/' . $image->id);
300         $delete->assertStatus(200);
301
302         $newCount = count(glob($folder . '/*'));
303         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
304         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
305     }
306
307     protected function getTestProfileImage()
308     {
309         $imageName = 'profile.png';
310         $relPath = $this->getTestImagePath('user', $imageName);
311         $this->deleteImage($relPath);
312
313         return $this->getTestImage($imageName);
314     }
315
316     public function test_user_image_upload()
317     {
318         $editor = $this->getEditor();
319         $admin = $this->getAdmin();
320         $this->actingAs($admin);
321
322         $file = $this->getTestProfileImage();
323         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
324
325         $this->assertDatabaseHas('images', [
326             'type' => 'user',
327             'uploaded_to' => $editor->id,
328             'created_by' => $admin->id,
329         ]);
330     }
331
332     public function test_user_images_deleted_on_user_deletion()
333     {
334         $editor = $this->getEditor();
335         $this->actingAs($editor);
336
337         $file = $this->getTestProfileImage();
338         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
339
340         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
341         $this->assertTrue($profileImages->count() === 1, "Found profile images does not match upload count");
342
343         $imagePath = public_path($profileImages->first()->path);
344         $this->assertTrue(file_exists($imagePath));
345
346         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
347         $userDelete->assertStatus(302);
348
349         $this->assertDatabaseMissing('images', [
350             'type' => 'user',
351             'created_by' => $editor->id
352         ]);
353         $this->assertDatabaseMissing('images', [
354             'type' => 'user',
355             'uploaded_to' => $editor->id
356         ]);
357
358         $this->assertFalse(file_exists($imagePath));
359     }
360
361     public function test_deleted_unused_images()
362     {
363         $page = Page::first();
364         $admin = $this->getAdmin();
365         $this->actingAs($admin);
366
367         $imageName = 'unused-image.png';
368         $relPath = $this->getTestImagePath('gallery', $imageName);
369         $this->deleteImage($relPath);
370
371         $upload = $this->uploadImage($imageName, $page->id);
372         $upload->assertStatus(200);
373         $image = Image::where('type', '=', 'gallery')->first();
374
375         $pageRepo = app(PageRepo::class);
376         $pageRepo->update($page, [
377             'name' => $page->name,
378             'html' => $page->html . "<img src=\"{$image->url}\">",
379             'summary' => ''
380         ]);
381
382         // Ensure no images are reported as deletable
383         $imageService = app(ImageService::class);
384         $toDelete = $imageService->deleteUnusedImages(true, true);
385         $this->assertCount(0, $toDelete);
386
387         // Save a revision of our page without the image;
388         $pageRepo->update($page, [
389             'name' => $page->name,
390             'html' => "<p>Hello</p>",
391             'summary' => ''
392         ]);
393
394         // Ensure revision images are picked up okay
395         $imageService = app(ImageService::class);
396         $toDelete = $imageService->deleteUnusedImages(true, true);
397         $this->assertCount(0, $toDelete);
398         $toDelete = $imageService->deleteUnusedImages(false, true);
399         $this->assertCount(1, $toDelete);
400
401         // Check image is found when revisions are destroyed
402         $page->revisions()->delete();
403         $toDelete = $imageService->deleteUnusedImages(true, true);
404         $this->assertCount(1, $toDelete);
405
406         // Check the image is deleted
407         $absPath = public_path($relPath);
408         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
409         $toDelete = $imageService->deleteUnusedImages(true, false);
410         $this->assertCount(1, $toDelete);
411         $this->assertFalse(file_exists($absPath));
412
413         $this->deleteImage($relPath);
414     }
415
416 }