]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Merge branch 'master' of git://github.com/Binternet/BookStack into Binternet-master
[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
266         $this->uploadImage($imageName, $page->id);
267         $image = Image::first();
268         $relPath = $this->getTestImagePath('gallery', $imageName);
269
270         $delete = $this->delete( '/images/' . $image->id);
271         $delete->assertStatus(200);
272
273         $this->assertDatabaseMissing('images', [
274             'url' => $this->baseUrl . $relPath,
275             'type' => 'gallery'
276         ]);
277
278         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
279     }
280
281     public function testBase64Get()
282     {
283         $page = Page::first();
284         $this->asAdmin();
285         $imageName = 'first-image.png';
286
287         $this->uploadImage($imageName, $page->id);
288         $image = Image::first();
289         $image->type = 'drawio';
290         $image->save();
291
292         $imageGet = $this->getJson("/images/drawio/base64/{$image->id}");
293         $imageGet->assertJson([
294             'content' => 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEcDCo5iYNs+gAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAFElEQVQI12O0jN/KgASYGFABqXwAZtoBV6Sl3hIAAAAASUVORK5CYII='
295         ]);
296     }
297
298     public function test_drawing_base64_upload()
299     {
300         $page = Page::first();
301         $editor = $this->getEditor();
302         $this->actingAs($editor);
303
304         $upload = $this->postJson('images/drawio', [
305             'uploaded_to' => $page->id,
306             'image' => 'image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEcDCo5iYNs+gAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAFElEQVQI12O0jN/KgASYGFABqXwAZtoBV6Sl3hIAAAAASUVORK5CYII='
307         ]);
308
309         $upload->assertStatus(200);
310         $upload->assertJson([
311             'type' => 'drawio',
312             'uploaded_to' => $page->id,
313             'created_by' => $editor->id,
314             'updated_by' => $editor->id,
315         ]);
316
317         $image = Image::where('type', '=', 'drawio')->first();
318         $this->assertTrue(file_exists(public_path($image->path)), 'Uploaded image not found at path: '. public_path($image->path));
319
320         $testImageData = file_get_contents($this->getTestImageFilePath());
321         $uploadedImageData = file_get_contents(public_path($image->path));
322         $this->assertTrue($testImageData === $uploadedImageData, "Uploaded image file data does not match our test image as expected");
323     }
324
325     protected function getTestProfileImage()
326     {
327         $imageName = 'profile.png';
328         $relPath = $this->getTestImagePath('user', $imageName);
329         $this->deleteImage($relPath);
330
331         return $this->getTestImage($imageName);
332     }
333
334     public function test_user_image_upload()
335     {
336         $editor = $this->getEditor();
337         $admin = $this->getAdmin();
338         $this->actingAs($admin);
339
340         $file = $this->getTestProfileImage();
341         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
342
343         $this->assertDatabaseHas('images', [
344             'type' => 'user',
345             'uploaded_to' => $editor->id,
346             'created_by' => $admin->id,
347         ]);
348     }
349
350     public function test_user_images_deleted_on_user_deletion()
351     {
352         $editor = $this->getEditor();
353         $this->actingAs($editor);
354
355         $file = $this->getTestProfileImage();
356         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
357
358         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
359         $this->assertTrue($profileImages->count() === 1, "Found profile images does not match upload count");
360
361         $imagePath = public_path($profileImages->first()->path);
362         $this->assertTrue(file_exists($imagePath));
363
364         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
365         $userDelete->assertStatus(302);
366
367         $this->assertDatabaseMissing('images', [
368             'type' => 'user',
369             'created_by' => $editor->id
370         ]);
371         $this->assertDatabaseMissing('images', [
372             'type' => 'user',
373             'uploaded_to' => $editor->id
374         ]);
375
376         $this->assertFalse(file_exists($imagePath));
377     }
378
379     public function test_deleted_unused_images()
380     {
381         $page = Page::first();
382         $admin = $this->getAdmin();
383         $this->actingAs($admin);
384
385         $imageName = 'unused-image.png';
386         $relPath = $this->getTestImagePath('gallery', $imageName);
387         $this->deleteImage($relPath);
388
389         $upload = $this->uploadImage($imageName, $page->id);
390         $upload->assertStatus(200);
391         $image = Image::where('type', '=', 'gallery')->first();
392
393         $pageRepo = app(PageRepo::class);
394         $pageRepo->update($page, [
395             'name' => $page->name,
396             'html' => $page->html . "<img src=\"{$image->url}\">",
397             'summary' => ''
398         ]);
399
400         // Ensure no images are reported as deletable
401         $imageService = app(ImageService::class);
402         $toDelete = $imageService->deleteUnusedImages(true, true);
403         $this->assertCount(0, $toDelete);
404
405         // Save a revision of our page without the image;
406         $pageRepo->update($page, [
407             'name' => $page->name,
408             'html' => "<p>Hello</p>",
409             'summary' => ''
410         ]);
411
412         // Ensure revision images are picked up okay
413         $imageService = app(ImageService::class);
414         $toDelete = $imageService->deleteUnusedImages(true, true);
415         $this->assertCount(0, $toDelete);
416         $toDelete = $imageService->deleteUnusedImages(false, true);
417         $this->assertCount(1, $toDelete);
418
419         // Check image is found when revisions are destroyed
420         $page->revisions()->delete();
421         $toDelete = $imageService->deleteUnusedImages(true, true);
422         $this->assertCount(1, $toDelete);
423
424         // Check the image is deleted
425         $absPath = public_path($relPath);
426         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
427         $toDelete = $imageService->deleteUnusedImages(true, false);
428         $this->assertCount(1, $toDelete);
429         $this->assertFalse(file_exists($absPath));
430
431         $this->deleteImage($relPath);
432     }
433
434 }