]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Merge branch 'footer-links' of git://github.com/james-geiger/BookStack into james...
[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::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->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::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::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->getTestImage($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::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->getTestImage($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_cannot_be_uploaded()
169     {
170         $page = Page::first();
171         $admin = $this->getAdmin();
172         $this->actingAs($admin);
173
174         $fileName = 'bad.phtml.png';
175         $relPath = $this->getTestImagePath('gallery', $fileName);
176         $this->deleteImage($relPath);
177
178         $file = $this->getTestImage($fileName);
179         $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
180         $upload->assertStatus(302);
181
182         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded double extension file was uploaded but should have been stopped');
183     }
184
185     public function test_url_entities_removed_from_filenames()
186     {
187         $this->asEditor();
188         $badNames = [
189             "bad-char-#-image.png",
190             "bad-char-?-image.png",
191             "?#.png",
192             "?.png",
193             "#.png",
194         ];
195         foreach ($badNames as $name) {
196             $galleryFile = $this->getTestImage($name);
197             $page = Page::first();
198             $badPath = $this->getTestImagePath('gallery', $name);
199             $this->deleteImage($badPath);
200
201             $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
202             $upload->assertStatus(200);
203
204             $lastImage = Image::query()->latest('id')->first();
205             $newFileName = explode('.', basename($lastImage->path))[0];
206
207             $this->assertEquals($lastImage->name, $name);
208             $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
209             $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
210
211             $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
212
213             $this->deleteImage($lastImage->path);
214         }
215     }
216
217     public function test_secure_images_uploads_to_correct_place()
218     {
219         config()->set('filesystems.images', 'local_secure');
220         $this->asEditor();
221         $galleryFile = $this->getTestImage('my-secure-test-upload.png');
222         $page = Page::first();
223         $expectedPath = storage_path('uploads/images/gallery/' . Date('Y-m') . '/my-secure-test-upload.png');
224
225         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
226         $upload->assertStatus(200);
227
228         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '. $expectedPath);
229
230         if (file_exists($expectedPath)) {
231             unlink($expectedPath);
232         }
233     }
234
235     public function test_secure_images_included_in_exports()
236     {
237         config()->set('filesystems.images', 'local_secure');
238         $this->asEditor();
239         $galleryFile = $this->getTestImage('my-secure-test-upload.png');
240         $page = Page::first();
241         $expectedPath = storage_path('uploads/images/gallery/' . Date('Y-m') . '/my-secure-test-upload.png');
242
243         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
244         $imageUrl = json_decode($upload->getContent(), true)['url'];
245         $page->html .= "<img src=\"{$imageUrl}\">";
246         $page->save();
247         $upload->assertStatus(200);
248
249         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
250         $export = $this->get($page->getUrl('/export/html'));
251         $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
252
253         if (file_exists($expectedPath)) {
254             unlink($expectedPath);
255         }
256     }
257
258     public function test_system_images_remain_public()
259     {
260         config()->set('filesystems.images', 'local_secure');
261         $this->asAdmin();
262         $galleryFile = $this->getTestImage('my-system-test-upload.png');
263         $expectedPath = public_path('uploads/images/system/' . Date('Y-m') . '/my-system-test-upload.png');
264
265         $upload = $this->call('POST', '/settings', [], [], ['app_logo' => $galleryFile], []);
266         $upload->assertRedirect('/settings');
267
268         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: '. $expectedPath);
269
270         if (file_exists($expectedPath)) {
271             unlink($expectedPath);
272         }
273     }
274
275     public function test_image_delete()
276     {
277         $page = Page::first();
278         $this->asAdmin();
279         $imageName = 'first-image.png';
280         $relPath = $this->getTestImagePath('gallery', $imageName);
281         $this->deleteImage($relPath);
282
283         $this->uploadImage($imageName, $page->id);
284         $image = Image::first();
285
286         $delete = $this->delete( '/images/' . $image->id);
287         $delete->assertStatus(200);
288
289         $this->assertDatabaseMissing('images', [
290             'url' => $this->baseUrl . $relPath,
291             'type' => 'gallery'
292         ]);
293
294         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
295     }
296
297     public function test_image_delete_does_not_delete_similar_images()
298     {
299         $page = Page::first();
300         $this->asAdmin();
301         $imageName = 'first-image.png';
302
303         $relPath = $this->getTestImagePath('gallery', $imageName);
304         $this->deleteImage($relPath);
305
306         $this->uploadImage($imageName, $page->id);
307         $this->uploadImage($imageName, $page->id);
308         $this->uploadImage($imageName, $page->id);
309
310         $image = Image::first();
311         $folder = public_path(dirname($relPath));
312         $imageCount = count(glob($folder . '/*'));
313
314         $delete = $this->delete( '/images/' . $image->id);
315         $delete->assertStatus(200);
316
317         $newCount = count(glob($folder . '/*'));
318         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
319         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
320     }
321
322     protected function getTestProfileImage()
323     {
324         $imageName = 'profile.png';
325         $relPath = $this->getTestImagePath('user', $imageName);
326         $this->deleteImage($relPath);
327
328         return $this->getTestImage($imageName);
329     }
330
331     public function test_user_image_upload()
332     {
333         $editor = $this->getEditor();
334         $admin = $this->getAdmin();
335         $this->actingAs($admin);
336
337         $file = $this->getTestProfileImage();
338         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
339
340         $this->assertDatabaseHas('images', [
341             'type' => 'user',
342             'uploaded_to' => $editor->id,
343             'created_by' => $admin->id,
344         ]);
345     }
346
347     public function test_user_images_deleted_on_user_deletion()
348     {
349         $editor = $this->getEditor();
350         $this->actingAs($editor);
351
352         $file = $this->getTestProfileImage();
353         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
354
355         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
356         $this->assertTrue($profileImages->count() === 1, "Found profile images does not match upload count");
357
358         $imagePath = public_path($profileImages->first()->path);
359         $this->assertTrue(file_exists($imagePath));
360
361         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
362         $userDelete->assertStatus(302);
363
364         $this->assertDatabaseMissing('images', [
365             'type' => 'user',
366             'created_by' => $editor->id
367         ]);
368         $this->assertDatabaseMissing('images', [
369             'type' => 'user',
370             'uploaded_to' => $editor->id
371         ]);
372
373         $this->assertFalse(file_exists($imagePath));
374     }
375
376     public function test_deleted_unused_images()
377     {
378         $page = Page::first();
379         $admin = $this->getAdmin();
380         $this->actingAs($admin);
381
382         $imageName = 'unused-image.png';
383         $relPath = $this->getTestImagePath('gallery', $imageName);
384         $this->deleteImage($relPath);
385
386         $upload = $this->uploadImage($imageName, $page->id);
387         $upload->assertStatus(200);
388         $image = Image::where('type', '=', 'gallery')->first();
389
390         $pageRepo = app(PageRepo::class);
391         $pageRepo->update($page, [
392             'name' => $page->name,
393             'html' => $page->html . "<img src=\"{$image->url}\">",
394             'summary' => ''
395         ]);
396
397         // Ensure no images are reported as deletable
398         $imageService = app(ImageService::class);
399         $toDelete = $imageService->deleteUnusedImages(true, true);
400         $this->assertCount(0, $toDelete);
401
402         // Save a revision of our page without the image;
403         $pageRepo->update($page, [
404             'name' => $page->name,
405             'html' => "<p>Hello</p>",
406             'summary' => ''
407         ]);
408
409         // Ensure revision images are picked up okay
410         $imageService = app(ImageService::class);
411         $toDelete = $imageService->deleteUnusedImages(true, true);
412         $this->assertCount(0, $toDelete);
413         $toDelete = $imageService->deleteUnusedImages(false, true);
414         $this->assertCount(1, $toDelete);
415
416         // Check image is found when revisions are destroyed
417         $page->revisions()->delete();
418         $toDelete = $imageService->deleteUnusedImages(true, true);
419         $this->assertCount(1, $toDelete);
420
421         // Check the image is deleted
422         $absPath = public_path($relPath);
423         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
424         $toDelete = $imageService->deleteUnusedImages(true, false);
425         $this->assertCount(1, $toDelete);
426         $this->assertFalse(file_exists($absPath));
427
428         $this->deleteImage($relPath);
429     }
430
431 }