]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Added the ability to replace existing image files
[bookstack] / tests / Uploads / ImageTest.php
1 <?php
2
3 namespace Tests\Uploads;
4
5 use BookStack\Entities\Repos\PageRepo;
6 use BookStack\Uploads\Image;
7 use BookStack\Uploads\ImageService;
8 use Illuminate\Support\Str;
9 use Tests\TestCase;
10
11 class ImageTest extends TestCase
12 {
13     public function test_image_upload()
14     {
15         $page = $this->entities->page();
16         $admin = $this->users->admin();
17         $this->actingAs($admin);
18
19         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
20         $relPath = $imgDetails['path'];
21
22         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
23
24         $this->files->deleteAtRelativePath($relPath);
25
26         $this->assertDatabaseHas('images', [
27             'url'         => $this->baseUrl . $relPath,
28             'type'        => 'gallery',
29             'uploaded_to' => $page->id,
30             'path'        => $relPath,
31             'created_by'  => $admin->id,
32             'updated_by'  => $admin->id,
33             'name'        => $imgDetails['name'],
34         ]);
35     }
36
37     public function test_image_display_thumbnail_generation_does_not_increase_image_size()
38     {
39         $page = $this->entities->page();
40         $admin = $this->users->admin();
41         $this->actingAs($admin);
42
43         $originalFile = $this->files->testFilePath('compressed.png');
44         $originalFileSize = filesize($originalFile);
45         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'compressed.png');
46         $relPath = $imgDetails['path'];
47
48         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
49         $displayImage = $imgDetails['response']->thumbs->display;
50
51         $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3));
52         $displayImagePath = public_path($displayImageRelPath);
53         $displayFileSize = filesize($displayImagePath);
54
55         $this->files->deleteAtRelativePath($relPath);
56         $this->files->deleteAtRelativePath($displayImageRelPath);
57
58         $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size');
59     }
60
61     public function test_image_display_thumbnail_generation_for_apng_images_uses_original_file()
62     {
63         $page = $this->entities->page();
64         $admin = $this->users->admin();
65         $this->actingAs($admin);
66
67         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'animated.png');
68         $this->files->deleteAtRelativePath($imgDetails['path']);
69
70         $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery);
71         $this->assertStringNotContainsString('thumbs-', $imgDetails['response']->thumbs->display);
72     }
73
74     public function test_image_edit()
75     {
76         $editor = $this->users->editor();
77         $this->actingAs($editor);
78
79         $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
80         $image = Image::query()->first();
81
82         $newName = Str::random();
83         $update = $this->put('/images/' . $image->id, ['name' => $newName]);
84         $update->assertSuccessful();
85         $update->assertSee($newName);
86
87         $this->files->deleteAtRelativePath($imgDetails['path']);
88
89         $this->assertDatabaseHas('images', [
90             'type' => 'gallery',
91             'name' => $newName,
92         ]);
93     }
94
95     public function test_image_file_update()
96     {
97         $page = $this->entities->page();
98         $this->asEditor();
99
100         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
101         $relPath = $imgDetails['path'];
102
103         $newUpload = $this->files->uploadedImage('updated-image.png', 'compressed.png');
104         $this->assertFileEquals($this->files->testFilePath('test-image.png'), public_path($relPath));
105
106         $imageId = $imgDetails['response']->id;
107         $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload])
108             ->assertOk();
109
110         $this->assertFileEquals($this->files->testFilePath('compressed.png'), public_path($relPath));
111
112         $this->files->deleteAtRelativePath($relPath);
113     }
114
115     public function test_image_file_update_does_not_allow_change_in_image_extension()
116     {
117         $page = $this->entities->page();
118         $this->asEditor();
119
120         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
121         $relPath = $imgDetails['path'];
122         $newUpload = $this->files->uploadedImage('updated-image.jpg', 'compressed.png');
123
124         $imageId = $imgDetails['response']->id;
125         $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload])
126             ->assertJson([
127                 "message" => "Image file replacements must be of the same type",
128                 "status" => "error",
129             ]);
130
131         $this->files->deleteAtRelativePath($relPath);
132     }
133
134     public function test_gallery_get_list_format()
135     {
136         $this->asEditor();
137
138         $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
139         $image = Image::query()->first();
140
141         $pageId = $imgDetails['page']->id;
142         $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
143         $firstPageRequest->assertSuccessful();
144         $this->withHtml($firstPageRequest)->assertElementExists('div');
145         $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
146
147         $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
148         $secondPageRequest->assertSuccessful();
149         $this->withHtml($secondPageRequest)->assertElementNotExists('div');
150
151         $namePartial = substr($imgDetails['name'], 0, 3);
152         $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
153         $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
154
155         $namePartial = Str::random(16);
156         $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
157         $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
158         $searchFailRequest->assertSuccessful();
159         $this->withHtml($searchFailRequest)->assertElementNotExists('div');
160     }
161
162     public function test_image_gallery_lists_for_draft_page()
163     {
164         $this->actingAs($this->users->editor());
165         $draft = $this->entities->newDraftPage();
166         $this->files->uploadGalleryImageToPage($this, $draft);
167         $image = Image::query()->where('uploaded_to', '=', $draft->id)->firstOrFail();
168
169         $resp = $this->get("/images/gallery?page=1&uploaded_to={$draft->id}");
170         $resp->assertSee($image->getThumb(150, 150));
171     }
172
173     public function test_image_usage()
174     {
175         $page = $this->entities->page();
176         $editor = $this->users->editor();
177         $this->actingAs($editor);
178
179         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
180
181         $image = Image::query()->first();
182         $page->html = '<img src="' . $image->url . '">';
183         $page->save();
184
185         $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
186         $usage->assertSuccessful();
187         $usage->assertSeeText($page->name);
188         $usage->assertSee($page->getUrl());
189
190         $this->files->deleteAtRelativePath($imgDetails['path']);
191     }
192
193     public function test_php_files_cannot_be_uploaded()
194     {
195         $page = $this->entities->page();
196         $admin = $this->users->admin();
197         $this->actingAs($admin);
198
199         $fileName = 'bad.php';
200         $relPath = $this->files->expectedImagePath('gallery', $fileName);
201         $this->files->deleteAtRelativePath($relPath);
202
203         $file = $this->files->imageFromBase64File('bad-php.base64', $fileName);
204         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
205         $upload->assertStatus(500);
206         $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
207
208         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
209
210         $this->assertDatabaseMissing('images', [
211             'type' => 'gallery',
212             'name' => $fileName,
213         ]);
214     }
215
216     public function test_php_like_files_cannot_be_uploaded()
217     {
218         $page = $this->entities->page();
219         $admin = $this->users->admin();
220         $this->actingAs($admin);
221
222         $fileName = 'bad.phtml';
223         $relPath = $this->files->expectedImagePath('gallery', $fileName);
224         $this->files->deleteAtRelativePath($relPath);
225
226         $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName);
227         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
228         $upload->assertStatus(500);
229         $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
230
231         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
232     }
233
234     public function test_files_with_double_extensions_will_get_sanitized()
235     {
236         $page = $this->entities->page();
237         $admin = $this->users->admin();
238         $this->actingAs($admin);
239
240         $fileName = 'bad.phtml.png';
241         $relPath = $this->files->expectedImagePath('gallery', $fileName);
242         $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
243         $this->files->deleteAtRelativePath($expectedRelPath);
244
245         $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName);
246         $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
247         $upload->assertStatus(200);
248
249         $lastImage = Image::query()->latest('id')->first();
250
251         $this->assertEquals('bad.phtml.png', $lastImage->name);
252         $this->assertEquals('bad-phtml.png', basename($lastImage->path));
253         $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
254         $this->assertFileExists(public_path($expectedRelPath));
255
256         $this->files->deleteAtRelativePath($lastImage->path);
257     }
258
259     public function test_url_entities_removed_from_filenames()
260     {
261         $this->asEditor();
262         $badNames = [
263             'bad-char-#-image.png',
264             'bad-char-?-image.png',
265             '?#.png',
266             '?.png',
267             '#.png',
268         ];
269         foreach ($badNames as $name) {
270             $galleryFile = $this->files->uploadedImage($name);
271             $page = $this->entities->page();
272             $badPath = $this->files->expectedImagePath('gallery', $name);
273             $this->files->deleteAtRelativePath($badPath);
274
275             $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
276             $upload->assertStatus(200);
277
278             $lastImage = Image::query()->latest('id')->first();
279             $newFileName = explode('.', basename($lastImage->path))[0];
280
281             $this->assertEquals($lastImage->name, $name);
282             $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
283             $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
284
285             $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
286
287             $this->files->deleteAtRelativePath($lastImage->path);
288         }
289     }
290
291     public function test_secure_images_uploads_to_correct_place()
292     {
293         config()->set('filesystems.images', 'local_secure');
294         $this->asEditor();
295         $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
296         $page = $this->entities->page();
297         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
298
299         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
300         $upload->assertStatus(200);
301
302         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
303
304         if (file_exists($expectedPath)) {
305             unlink($expectedPath);
306         }
307     }
308
309     public function test_secure_image_paths_traversal_causes_500()
310     {
311         config()->set('filesystems.images', 'local_secure');
312         $this->asEditor();
313
314         $resp = $this->get('/uploads/images/../../logs/laravel.log');
315         $resp->assertStatus(500);
316     }
317
318     public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
319     {
320         config()->set('filesystems.images', 'local');
321         $this->asEditor();
322
323         $resp = $this->get('/uploads/images/../../logs/laravel.log');
324         $resp->assertStatus(404);
325     }
326
327     public function test_secure_image_paths_dont_serve_non_images()
328     {
329         config()->set('filesystems.images', 'local_secure');
330         $this->asEditor();
331
332         $testFilePath = storage_path('/uploads/images/testing.txt');
333         file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
334
335         $resp = $this->get('/uploads/images/testing.txt');
336         $resp->assertStatus(404);
337     }
338
339     public function test_secure_images_included_in_exports()
340     {
341         config()->set('filesystems.images', 'local_secure');
342         $this->asEditor();
343         $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
344         $page = $this->entities->page();
345         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
346
347         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
348         $imageUrl = json_decode($upload->getContent(), true)['url'];
349         $page->html .= "<img src=\"{$imageUrl}\">";
350         $page->save();
351         $upload->assertStatus(200);
352
353         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
354         $export = $this->get($page->getUrl('/export/html'));
355         $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
356
357         if (file_exists($expectedPath)) {
358             unlink($expectedPath);
359         }
360     }
361
362     public function test_system_images_remain_public_with_local_secure()
363     {
364         config()->set('filesystems.images', 'local_secure');
365         $this->asAdmin();
366         $galleryFile = $this->files->uploadedImage('my-system-test-upload.png');
367         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
368
369         $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
370         $upload->assertRedirect('/settings/customization');
371
372         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
373
374         if (file_exists($expectedPath)) {
375             unlink($expectedPath);
376         }
377     }
378
379     public function test_system_images_remain_public_with_local_secure_restricted()
380     {
381         config()->set('filesystems.images', 'local_secure_restricted');
382         $this->asAdmin();
383         $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
384         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
385
386         $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
387         $upload->assertRedirect('/settings/customization');
388
389         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
390
391         if (file_exists($expectedPath)) {
392             unlink($expectedPath);
393         }
394     }
395
396     public function test_secure_restricted_images_inaccessible_without_relation_permission()
397     {
398         config()->set('filesystems.images', 'local_secure_restricted');
399         $this->asEditor();
400         $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
401         $page = $this->entities->page();
402
403         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
404         $upload->assertStatus(200);
405         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
406         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
407
408         $this->get($expectedUrl)->assertOk();
409
410         $this->permissions->setEntityPermissions($page, [], []);
411
412         $resp = $this->get($expectedUrl);
413         $resp->assertNotFound();
414
415         if (file_exists($expectedPath)) {
416             unlink($expectedPath);
417         }
418     }
419
420     public function test_thumbnail_path_handled_by_secure_restricted_images()
421     {
422         config()->set('filesystems.images', 'local_secure_restricted');
423         $this->asEditor();
424         $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
425         $page = $this->entities->page();
426
427         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
428         $upload->assertStatus(200);
429         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
430         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
431
432         $this->get($expectedUrl)->assertOk();
433
434         $this->permissions->setEntityPermissions($page, [], []);
435
436         $resp = $this->get($expectedUrl);
437         $resp->assertNotFound();
438
439         if (file_exists($expectedPath)) {
440             unlink($expectedPath);
441         }
442     }
443
444     public function test_secure_restricted_image_access_controlled_in_exports()
445     {
446         config()->set('filesystems.images', 'local_secure_restricted');
447         $this->asEditor();
448         $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
449
450         $pageA = $this->entities->page();
451         $pageB = $this->entities->page();
452         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
453
454         $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
455         $upload->assertOk();
456
457         $imageUrl = json_decode($upload->getContent(), true)['url'];
458         $pageB->html .= "<img src=\"{$imageUrl}\">";
459         $pageB->save();
460
461         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
462         $export = $this->get($pageB->getUrl('/export/html'));
463         $this->assertStringContainsString($encodedImageContent, $export->getContent());
464
465         $this->permissions->setEntityPermissions($pageA, [], []);
466
467         $export = $this->get($pageB->getUrl('/export/html'));
468         $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
469
470         if (file_exists($expectedPath)) {
471             unlink($expectedPath);
472         }
473     }
474
475     public function test_image_delete()
476     {
477         $page = $this->entities->page();
478         $this->asAdmin();
479         $imageName = 'first-image.png';
480         $relPath = $this->files->expectedImagePath('gallery', $imageName);
481         $this->files->deleteAtRelativePath($relPath);
482
483         $this->files->uploadGalleryImage($this, $imageName, $page->id);
484         $image = Image::first();
485
486         $delete = $this->delete('/images/' . $image->id);
487         $delete->assertStatus(200);
488
489         $this->assertDatabaseMissing('images', [
490             'url'  => $this->baseUrl . $relPath,
491             'type' => 'gallery',
492         ]);
493
494         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
495     }
496
497     public function test_image_delete_does_not_delete_similar_images()
498     {
499         $page = $this->entities->page();
500         $this->asAdmin();
501         $imageName = 'first-image.png';
502
503         $relPath = $this->files->expectedImagePath('gallery', $imageName);
504         $this->files->deleteAtRelativePath($relPath);
505
506         $this->files->uploadGalleryImage($this, $imageName, $page->id);
507         $this->files->uploadGalleryImage($this, $imageName, $page->id);
508         $this->files->uploadGalleryImage($this, $imageName, $page->id);
509
510         $image = Image::first();
511         $folder = public_path(dirname($relPath));
512         $imageCount = count(glob($folder . '/*'));
513
514         $delete = $this->delete('/images/' . $image->id);
515         $delete->assertStatus(200);
516
517         $newCount = count(glob($folder . '/*'));
518         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
519         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
520     }
521
522     public function test_image_manager_delete_button_only_shows_with_permission()
523     {
524         $page = $this->entities->page();
525         $this->asAdmin();
526         $imageName = 'first-image.png';
527         $relPath = $this->files->expectedImagePath('gallery', $imageName);
528         $this->files->deleteAtRelativePath($relPath);
529         $viewer = $this->users->viewer();
530
531         $this->files->uploadGalleryImage($this, $imageName, $page->id);
532         $image = Image::first();
533
534         $resp = $this->get("/images/edit/{$image->id}");
535         $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
536
537         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
538         $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete[title="Delete"]');
539
540         $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
541
542         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
543         $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
544
545         $this->files->deleteAtRelativePath($relPath);
546     }
547
548     protected function getTestProfileImage()
549     {
550         $imageName = 'profile.png';
551         $relPath = $this->files->expectedImagePath('user', $imageName);
552         $this->files->deleteAtRelativePath($relPath);
553
554         return $this->files->uploadedImage($imageName);
555     }
556
557     public function test_user_image_upload()
558     {
559         $editor = $this->users->editor();
560         $admin = $this->users->admin();
561         $this->actingAs($admin);
562
563         $file = $this->getTestProfileImage();
564         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
565
566         $this->assertDatabaseHas('images', [
567             'type'        => 'user',
568             'uploaded_to' => $editor->id,
569             'created_by'  => $admin->id,
570         ]);
571     }
572
573     public function test_user_images_deleted_on_user_deletion()
574     {
575         $editor = $this->users->editor();
576         $this->actingAs($editor);
577
578         $file = $this->getTestProfileImage();
579         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
580
581         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
582         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
583
584         $imagePath = public_path($profileImages->first()->path);
585         $this->assertTrue(file_exists($imagePath));
586
587         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
588         $userDelete->assertStatus(302);
589
590         $this->assertDatabaseMissing('images', [
591             'type'       => 'user',
592             'created_by' => $editor->id,
593         ]);
594         $this->assertDatabaseMissing('images', [
595             'type'        => 'user',
596             'uploaded_to' => $editor->id,
597         ]);
598
599         $this->assertFalse(file_exists($imagePath));
600     }
601
602     public function test_deleted_unused_images()
603     {
604         $page = $this->entities->page();
605         $admin = $this->users->admin();
606         $this->actingAs($admin);
607
608         $imageName = 'unused-image.png';
609         $relPath = $this->files->expectedImagePath('gallery', $imageName);
610         $this->files->deleteAtRelativePath($relPath);
611
612         $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
613         $upload->assertStatus(200);
614         $image = Image::where('type', '=', 'gallery')->first();
615
616         $pageRepo = app(PageRepo::class);
617         $pageRepo->update($page, [
618             'name'    => $page->name,
619             'html'    => $page->html . "<img src=\"{$image->url}\">",
620             'summary' => '',
621         ]);
622
623         // Ensure no images are reported as deletable
624         $imageService = app(ImageService::class);
625         $toDelete = $imageService->deleteUnusedImages(true, true);
626         $this->assertCount(0, $toDelete);
627
628         // Save a revision of our page without the image;
629         $pageRepo->update($page, [
630             'name'    => $page->name,
631             'html'    => '<p>Hello</p>',
632             'summary' => '',
633         ]);
634
635         // Ensure revision images are picked up okay
636         $imageService = app(ImageService::class);
637         $toDelete = $imageService->deleteUnusedImages(true, true);
638         $this->assertCount(0, $toDelete);
639         $toDelete = $imageService->deleteUnusedImages(false, true);
640         $this->assertCount(1, $toDelete);
641
642         // Check image is found when revisions are destroyed
643         $page->revisions()->delete();
644         $toDelete = $imageService->deleteUnusedImages(true, true);
645         $this->assertCount(1, $toDelete);
646
647         // Check the image is deleted
648         $absPath = public_path($relPath);
649         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
650         $toDelete = $imageService->deleteUnusedImages(true, false);
651         $this->assertCount(1, $toDelete);
652         $this->assertFalse(file_exists($absPath));
653
654         $this->files->deleteAtRelativePath($relPath);
655     }
656 }