]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Add LDAP_TLS_CACERTFILE to example env file
[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_secure_images_not_tracked_in_session_history()
387     {
388         config()->set('filesystems.images', 'local_secure');
389         $this->asEditor();
390         $page = $this->entities->page();
391         $result = $this->files->uploadGalleryImageToPage($this, $page);
392         $expectedPath = storage_path($result['path']);
393         $this->assertFileExists($expectedPath);
394
395         $this->get('/books');
396         $this->assertEquals(url('/books'), session()->previousUrl());
397
398         $resp = $this->get($result['path']);
399         $resp->assertOk();
400         $resp->assertHeader('Content-Type', 'image/png');
401
402         $this->assertEquals(url('/books'), session()->previousUrl());
403
404         if (file_exists($expectedPath)) {
405             unlink($expectedPath);
406         }
407     }
408
409     public function test_system_images_remain_public_with_local_secure_restricted()
410     {
411         config()->set('filesystems.images', 'local_secure_restricted');
412         $this->asAdmin();
413         $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
414         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
415
416         $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
417         $upload->assertRedirect('/settings/customization');
418
419         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
420
421         if (file_exists($expectedPath)) {
422             unlink($expectedPath);
423         }
424     }
425
426     public function test_secure_restricted_images_inaccessible_without_relation_permission()
427     {
428         config()->set('filesystems.images', 'local_secure_restricted');
429         $this->asEditor();
430         $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
431         $page = $this->entities->page();
432
433         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
434         $upload->assertStatus(200);
435         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
436         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
437
438         $this->get($expectedUrl)->assertOk();
439
440         $this->permissions->setEntityPermissions($page, [], []);
441
442         $resp = $this->get($expectedUrl);
443         $resp->assertNotFound();
444
445         if (file_exists($expectedPath)) {
446             unlink($expectedPath);
447         }
448     }
449
450     public function test_thumbnail_path_handled_by_secure_restricted_images()
451     {
452         config()->set('filesystems.images', 'local_secure_restricted');
453         $this->asEditor();
454         $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
455         $page = $this->entities->page();
456
457         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
458         $upload->assertStatus(200);
459         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
460         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
461
462         $this->get($expectedUrl)->assertOk();
463
464         $this->permissions->setEntityPermissions($page, [], []);
465
466         $resp = $this->get($expectedUrl);
467         $resp->assertNotFound();
468
469         if (file_exists($expectedPath)) {
470             unlink($expectedPath);
471         }
472     }
473
474     public function test_secure_restricted_image_access_controlled_in_exports()
475     {
476         config()->set('filesystems.images', 'local_secure_restricted');
477         $this->asEditor();
478         $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
479
480         $pageA = $this->entities->page();
481         $pageB = $this->entities->page();
482         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
483
484         $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
485         $upload->assertOk();
486
487         $imageUrl = json_decode($upload->getContent(), true)['url'];
488         $pageB->html .= "<img src=\"{$imageUrl}\">";
489         $pageB->save();
490
491         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
492         $export = $this->get($pageB->getUrl('/export/html'));
493         $this->assertStringContainsString($encodedImageContent, $export->getContent());
494
495         $this->permissions->setEntityPermissions($pageA, [], []);
496
497         $export = $this->get($pageB->getUrl('/export/html'));
498         $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
499
500         if (file_exists($expectedPath)) {
501             unlink($expectedPath);
502         }
503     }
504
505     public function test_image_delete()
506     {
507         $page = $this->entities->page();
508         $this->asAdmin();
509         $imageName = 'first-image.png';
510         $relPath = $this->files->expectedImagePath('gallery', $imageName);
511         $this->files->deleteAtRelativePath($relPath);
512
513         $this->files->uploadGalleryImage($this, $imageName, $page->id);
514         $image = Image::first();
515
516         $delete = $this->delete('/images/' . $image->id);
517         $delete->assertStatus(200);
518
519         $this->assertDatabaseMissing('images', [
520             'url'  => $this->baseUrl . $relPath,
521             'type' => 'gallery',
522         ]);
523
524         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
525     }
526
527     public function test_image_delete_does_not_delete_similar_images()
528     {
529         $page = $this->entities->page();
530         $this->asAdmin();
531         $imageName = 'first-image.png';
532
533         $relPath = $this->files->expectedImagePath('gallery', $imageName);
534         $this->files->deleteAtRelativePath($relPath);
535
536         $this->files->uploadGalleryImage($this, $imageName, $page->id);
537         $this->files->uploadGalleryImage($this, $imageName, $page->id);
538         $this->files->uploadGalleryImage($this, $imageName, $page->id);
539
540         $image = Image::first();
541         $folder = public_path(dirname($relPath));
542         $imageCount = count(glob($folder . '/*'));
543
544         $delete = $this->delete('/images/' . $image->id);
545         $delete->assertStatus(200);
546
547         $newCount = count(glob($folder . '/*'));
548         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
549         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
550     }
551
552     public function test_image_manager_delete_button_only_shows_with_permission()
553     {
554         $page = $this->entities->page();
555         $this->asAdmin();
556         $imageName = 'first-image.png';
557         $relPath = $this->files->expectedImagePath('gallery', $imageName);
558         $this->files->deleteAtRelativePath($relPath);
559         $viewer = $this->users->viewer();
560
561         $this->files->uploadGalleryImage($this, $imageName, $page->id);
562         $image = Image::first();
563
564         $resp = $this->get("/images/edit/{$image->id}");
565         $this->withHtml($resp)->assertElementExists('button#image-manager-delete');
566
567         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
568         $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete');
569
570         $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
571
572         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
573         $this->withHtml($resp)->assertElementExists('button#image-manager-delete');
574
575         $this->files->deleteAtRelativePath($relPath);
576     }
577
578     public function test_image_manager_regen_thumbnails()
579     {
580         $this->asEditor();
581         $imageName = 'first-image.png';
582         $relPath = $this->files->expectedImagePath('gallery', $imageName);
583         $this->files->deleteAtRelativePath($relPath);
584
585         $this->files->uploadGalleryImage($this, $imageName, $this->entities->page()->id);
586         $image = Image::first();
587
588         $resp = $this->get("/images/edit/{$image->id}");
589         $this->withHtml($resp)->assertElementExists('button#image-manager-rebuild-thumbs');
590
591         $expectedThumbPath = dirname($relPath) . '/scaled-1680-/' . basename($relPath);
592         $this->files->deleteAtRelativePath($expectedThumbPath);
593         $this->assertFileDoesNotExist($this->files->relativeToFullPath($expectedThumbPath));
594
595         $resp = $this->put("/images/{$image->id}/rebuild-thumbnails");
596         $resp->assertOk();
597
598         $this->assertFileExists($this->files->relativeToFullPath($expectedThumbPath));
599         $this->files->deleteAtRelativePath($relPath);
600     }
601
602     protected function getTestProfileImage()
603     {
604         $imageName = 'profile.png';
605         $relPath = $this->files->expectedImagePath('user', $imageName);
606         $this->files->deleteAtRelativePath($relPath);
607
608         return $this->files->uploadedImage($imageName);
609     }
610
611     public function test_user_image_upload()
612     {
613         $editor = $this->users->editor();
614         $admin = $this->users->admin();
615         $this->actingAs($admin);
616
617         $file = $this->getTestProfileImage();
618         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
619
620         $this->assertDatabaseHas('images', [
621             'type'        => 'user',
622             'uploaded_to' => $editor->id,
623             'created_by'  => $admin->id,
624         ]);
625     }
626
627     public function test_user_images_deleted_on_user_deletion()
628     {
629         $editor = $this->users->editor();
630         $this->actingAs($editor);
631
632         $file = $this->getTestProfileImage();
633         $this->call('PUT', '/my-account/profile', [], [], ['profile_image' => $file], []);
634
635         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
636         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
637
638         $imagePath = public_path($profileImages->first()->path);
639         $this->assertTrue(file_exists($imagePath));
640
641         $userDelete = $this->asAdmin()->delete($editor->getEditUrl());
642         $userDelete->assertStatus(302);
643
644         $this->assertDatabaseMissing('images', [
645             'type'       => 'user',
646             'created_by' => $editor->id,
647         ]);
648         $this->assertDatabaseMissing('images', [
649             'type'        => 'user',
650             'uploaded_to' => $editor->id,
651         ]);
652
653         $this->assertFalse(file_exists($imagePath));
654     }
655
656     public function test_deleted_unused_images()
657     {
658         $page = $this->entities->page();
659         $admin = $this->users->admin();
660         $this->actingAs($admin);
661
662         $imageName = 'unused-image.png';
663         $relPath = $this->files->expectedImagePath('gallery', $imageName);
664         $this->files->deleteAtRelativePath($relPath);
665
666         $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
667         $upload->assertStatus(200);
668         $image = Image::where('type', '=', 'gallery')->first();
669
670         $pageRepo = app(PageRepo::class);
671         $pageRepo->update($page, [
672             'name'    => $page->name,
673             'html'    => $page->html . "<img src=\"{$image->url}\">",
674             'summary' => '',
675         ]);
676
677         // Ensure no images are reported as deletable
678         $imageService = app(ImageService::class);
679         $toDelete = $imageService->deleteUnusedImages(true, true);
680         $this->assertCount(0, $toDelete);
681
682         // Save a revision of our page without the image;
683         $pageRepo->update($page, [
684             'name'    => $page->name,
685             'html'    => '<p>Hello</p>',
686             'summary' => '',
687         ]);
688
689         // Ensure revision images are picked up okay
690         $imageService = app(ImageService::class);
691         $toDelete = $imageService->deleteUnusedImages(true, true);
692         $this->assertCount(0, $toDelete);
693         $toDelete = $imageService->deleteUnusedImages(false, true);
694         $this->assertCount(1, $toDelete);
695
696         // Check image is found when revisions are destroyed
697         $page->revisions()->delete();
698         $toDelete = $imageService->deleteUnusedImages(true, true);
699         $this->assertCount(1, $toDelete);
700
701         // Check the image is deleted
702         $absPath = public_path($relPath);
703         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
704         $toDelete = $imageService->deleteUnusedImages(true, false);
705         $this->assertCount(1, $toDelete);
706         $this->assertFalse(file_exists($absPath));
707
708         $this->files->deleteAtRelativePath($relPath);
709     }
710 }