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