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