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