]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Merge pull request #5917 from BookStackApp/copy_references
[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 BookStack\Uploads\UserAvatars;
9 use BookStack\Users\Models\Role;
10 use Illuminate\Support\Str;
11 use Tests\TestCase;
12
13 class ImageTest extends TestCase
14 {
15     public function test_image_upload()
16     {
17         $page = $this->entities->page();
18         $admin = $this->users->admin();
19         $this->actingAs($admin);
20
21         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
22         $relPath = $imgDetails['path'];
23
24         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
25
26         $this->files->deleteAtRelativePath($relPath);
27
28         $this->assertDatabaseHas('images', [
29             'url'         => $this->baseUrl . $relPath,
30             'type'        => 'gallery',
31             'uploaded_to' => $page->id,
32             'path'        => $relPath,
33             'created_by'  => $admin->id,
34             'updated_by'  => $admin->id,
35             'name'        => $imgDetails['name'],
36         ]);
37     }
38
39     public function test_image_display_thumbnail_generation_does_not_increase_image_size()
40     {
41         $page = $this->entities->page();
42         $admin = $this->users->admin();
43         $this->actingAs($admin);
44
45         $originalFile = $this->files->testFilePath('compressed.png');
46         $originalFileSize = filesize($originalFile);
47         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'compressed.png');
48         $relPath = $imgDetails['path'];
49
50         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
51         $displayImage = $imgDetails['response']->thumbs->display;
52
53         $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3));
54         $displayImagePath = public_path($displayImageRelPath);
55         $displayFileSize = filesize($displayImagePath);
56
57         $this->files->deleteAtRelativePath($relPath);
58         $this->files->deleteAtRelativePath($displayImageRelPath);
59
60         $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size');
61     }
62
63     public function test_image_display_thumbnail_generation_for_apng_images_uses_original_file()
64     {
65         $page = $this->entities->page();
66         $admin = $this->users->admin();
67         $this->actingAs($admin);
68
69         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'animated.png');
70         $this->files->deleteAtRelativePath($imgDetails['path']);
71
72         $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery);
73         $this->assertStringNotContainsString('scaled-', $imgDetails['response']->thumbs->display);
74     }
75
76     public function test_image_display_thumbnail_generation_for_animated_avif_images_uses_original_file()
77     {
78         if (! function_exists('imageavif')) {
79             $this->markTestSkipped('imageavif() is not available');
80         }
81
82         $page = $this->entities->page();
83         $admin = $this->users->admin();
84         $this->actingAs($admin);
85
86         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'animated.avif');
87         $this->files->deleteAtRelativePath($imgDetails['path']);
88
89         $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery);
90         $this->assertStringNotContainsString('scaled-', $imgDetails['response']->thumbs->display);
91     }
92
93     public function test_image_edit()
94     {
95         $editor = $this->users->editor();
96         $this->actingAs($editor);
97
98         $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
99         $image = Image::query()->first();
100
101         $newName = Str::random();
102         $update = $this->put('/images/' . $image->id, ['name' => $newName]);
103         $update->assertSuccessful();
104         $update->assertSee($newName);
105
106         $this->files->deleteAtRelativePath($imgDetails['path']);
107
108         $this->assertDatabaseHas('images', [
109             'type' => 'gallery',
110             'name' => $newName,
111         ]);
112     }
113
114     public function test_image_file_update()
115     {
116         $page = $this->entities->page();
117         $this->asEditor();
118
119         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
120         $relPath = $imgDetails['path'];
121
122         $newUpload = $this->files->uploadedImage('updated-image.png', 'compressed.png');
123         $this->assertFileEquals($this->files->testFilePath('test-image.png'), public_path($relPath));
124
125         $imageId = $imgDetails['response']->id;
126         $image = Image::findOrFail($imageId);
127         $image->updated_at = now()->subMonth();
128         $image->save();
129
130         $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload])
131             ->assertOk();
132
133         $this->assertFileEquals($this->files->testFilePath('compressed.png'), public_path($relPath));
134
135         $image->refresh();
136         $this->assertTrue($image->updated_at->gt(now()->subMinute()));
137
138         $this->files->deleteAtRelativePath($relPath);
139     }
140
141     public function test_image_file_update_allows_case_differences()
142     {
143         $page = $this->entities->page();
144         $this->asEditor();
145
146         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
147         $relPath = $imgDetails['path'];
148
149         $newUpload = $this->files->uploadedImage('updated-image.PNG', 'compressed.png');
150         $this->assertFileEquals($this->files->testFilePath('test-image.png'), public_path($relPath));
151
152         $imageId = $imgDetails['response']->id;
153         $image = Image::findOrFail($imageId);
154         $image->updated_at = now()->subMonth();
155         $image->save();
156
157         $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload])
158             ->assertOk();
159
160         $this->assertFileEquals($this->files->testFilePath('compressed.png'), public_path($relPath));
161
162         $image->refresh();
163         $this->assertTrue($image->updated_at->gt(now()->subMinute()));
164
165         $this->files->deleteAtRelativePath($relPath);
166     }
167
168     public function test_image_file_update_does_not_allow_change_in_image_extension()
169     {
170         $page = $this->entities->page();
171         $this->asEditor();
172
173         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
174         $relPath = $imgDetails['path'];
175         $newUpload = $this->files->uploadedImage('updated-image.jpg', 'compressed.png');
176
177         $imageId = $imgDetails['response']->id;
178         $this->call('PUT', "/images/{$imageId}/file", [], [], ['file' => $newUpload])
179             ->assertJson([
180                 "message" => "Image file replacements must be of the same type",
181                 "status" => "error",
182             ]);
183
184         $this->files->deleteAtRelativePath($relPath);
185     }
186
187     public function test_gallery_get_list_format()
188     {
189         $this->asEditor();
190
191         $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
192         $image = Image::query()->first();
193
194         $pageId = $imgDetails['page']->id;
195         $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
196         $firstPageRequest->assertSuccessful();
197         $this->withHtml($firstPageRequest)->assertElementExists('div');
198         $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
199
200         $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
201         $secondPageRequest->assertSuccessful();
202         $this->withHtml($secondPageRequest)->assertElementNotExists('div');
203
204         $namePartial = substr($imgDetails['name'], 0, 3);
205         $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
206         $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
207
208         $namePartial = Str::random(16);
209         $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
210         $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
211         $searchFailRequest->assertSuccessful();
212         $this->withHtml($searchFailRequest)->assertElementNotExists('div');
213     }
214
215     public function test_image_gallery_lists_for_draft_page()
216     {
217         $this->actingAs($this->users->editor());
218         $draft = $this->entities->newDraftPage();
219         $this->files->uploadGalleryImageToPage($this, $draft);
220         $image = Image::query()->where('uploaded_to', '=', $draft->id)->firstOrFail();
221
222         $resp = $this->get("/images/gallery?page=1&uploaded_to={$draft->id}");
223         $resp->assertSee($image->getThumb(150, 150));
224     }
225
226     public function test_image_usage()
227     {
228         $page = $this->entities->page();
229         $editor = $this->users->editor();
230         $this->actingAs($editor);
231
232         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
233
234         $image = Image::query()->first();
235         $page->html = '<img src="' . $image->url . '">';
236         $page->save();
237
238         $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
239         $usage->assertSuccessful();
240         $usage->assertSeeText($page->name);
241         $usage->assertSee($page->getUrl());
242
243         $this->files->deleteAtRelativePath($imgDetails['path']);
244     }
245
246     public function test_php_files_cannot_be_uploaded()
247     {
248         $page = $this->entities->page();
249         $admin = $this->users->admin();
250         $this->actingAs($admin);
251
252         $fileName = 'bad.php';
253         $relPath = $this->files->expectedImagePath('gallery', $fileName);
254         $this->files->deleteAtRelativePath($relPath);
255
256         $file = $this->files->imageFromBase64File('bad-php.base64', $fileName);
257         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
258         $upload->assertStatus(500);
259         $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
260
261         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
262
263         $this->assertDatabaseMissing('images', [
264             'type' => 'gallery',
265             'name' => $fileName,
266         ]);
267     }
268
269     public function test_php_like_files_cannot_be_uploaded()
270     {
271         $page = $this->entities->page();
272         $admin = $this->users->admin();
273         $this->actingAs($admin);
274
275         $fileName = 'bad.phtml';
276         $relPath = $this->files->expectedImagePath('gallery', $fileName);
277         $this->files->deleteAtRelativePath($relPath);
278
279         $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName);
280         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
281         $upload->assertStatus(500);
282         $this->assertStringContainsString('The file must have a valid & supported image extension', $upload->json('message'));
283
284         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
285     }
286
287     public function test_files_with_double_extensions_will_get_sanitized()
288     {
289         $page = $this->entities->page();
290         $admin = $this->users->admin();
291         $this->actingAs($admin);
292
293         $fileName = 'bad.phtml.png';
294         $relPath = $this->files->expectedImagePath('gallery', $fileName);
295         $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
296         $this->files->deleteAtRelativePath($expectedRelPath);
297
298         $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName);
299         $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
300         $upload->assertStatus(200);
301
302         $lastImage = Image::query()->latest('id')->first();
303
304         $this->assertEquals('bad.phtml.png', $lastImage->name);
305         $this->assertEquals('bad-phtml.png', basename($lastImage->path));
306         $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
307         $this->assertFileExists(public_path($expectedRelPath));
308
309         $this->files->deleteAtRelativePath($lastImage->path);
310     }
311
312     public function test_url_entities_removed_from_filenames()
313     {
314         $this->asEditor();
315         $badNames = [
316             'bad-char-#-image.png',
317             'bad-char-?-image.png',
318             '?#.png',
319             '?.png',
320             '#.png',
321         ];
322         foreach ($badNames as $name) {
323             $galleryFile = $this->files->uploadedImage($name);
324             $page = $this->entities->page();
325             $badPath = $this->files->expectedImagePath('gallery', $name);
326             $this->files->deleteAtRelativePath($badPath);
327
328             $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
329             $upload->assertStatus(200);
330
331             $lastImage = Image::query()->latest('id')->first();
332             $newFileName = explode('.', basename($lastImage->path))[0];
333
334             $this->assertEquals($lastImage->name, $name);
335             $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
336             $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
337
338             $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
339
340             $this->files->deleteAtRelativePath($lastImage->path);
341         }
342     }
343
344     public function test_secure_images_uploads_to_correct_place()
345     {
346         config()->set('filesystems.images', 'local_secure');
347         $this->asEditor();
348         $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
349         $page = $this->entities->page();
350         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
351
352         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
353         $upload->assertStatus(200);
354
355         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
356
357         if (file_exists($expectedPath)) {
358             unlink($expectedPath);
359         }
360     }
361
362     public function test_secure_image_paths_traversal_causes_500()
363     {
364         config()->set('filesystems.images', 'local_secure');
365         $this->asEditor();
366
367         $resp = $this->get('/uploads/images/../../logs/laravel.log');
368         $resp->assertStatus(500);
369     }
370
371     public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
372     {
373         config()->set('filesystems.images', 'local');
374         $this->asEditor();
375
376         $resp = $this->get('/uploads/images/../../logs/laravel.log');
377         $resp->assertStatus(404);
378     }
379
380     public function test_secure_image_paths_dont_serve_non_images()
381     {
382         config()->set('filesystems.images', 'local_secure');
383         $this->asEditor();
384
385         $testFilePath = storage_path('/uploads/images/testing.txt');
386         file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
387
388         $resp = $this->get('/uploads/images/testing.txt');
389         $resp->assertStatus(404);
390     }
391
392     public function test_secure_images_included_in_exports()
393     {
394         config()->set('filesystems.images', 'local_secure');
395         $this->asEditor();
396         $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
397         $page = $this->entities->page();
398         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
399
400         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
401         $imageUrl = json_decode($upload->getContent(), true)['url'];
402         $page->html .= "<img src=\"{$imageUrl}\">";
403         $page->save();
404         $upload->assertStatus(200);
405
406         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
407         $export = $this->get($page->getUrl('/export/html'));
408         $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
409
410         if (file_exists($expectedPath)) {
411             unlink($expectedPath);
412         }
413     }
414
415     public function test_system_images_remain_public_with_local_secure()
416     {
417         config()->set('filesystems.images', 'local_secure');
418         $this->asAdmin();
419         $galleryFile = $this->files->uploadedImage('my-system-test-upload.png');
420         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
421
422         $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
423         $upload->assertRedirect('/settings/customization');
424
425         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
426
427         if (file_exists($expectedPath)) {
428             unlink($expectedPath);
429         }
430     }
431
432     public function test_secure_images_not_tracked_in_session_history()
433     {
434         config()->set('filesystems.images', 'local_secure');
435         $this->asEditor();
436         $page = $this->entities->page();
437         $result = $this->files->uploadGalleryImageToPage($this, $page);
438         $expectedPath = storage_path($result['path']);
439         $this->assertFileExists($expectedPath);
440
441         $this->get('/books');
442         $this->assertEquals(url('/books'), session()->previousUrl());
443
444         $resp = $this->get($result['path']);
445         $resp->assertOk();
446         $resp->assertHeader('Content-Type', 'image/png');
447
448         $this->assertEquals(url('/books'), session()->previousUrl());
449
450         if (file_exists($expectedPath)) {
451             unlink($expectedPath);
452         }
453     }
454
455     public function test_system_images_remain_public_with_local_secure_restricted()
456     {
457         config()->set('filesystems.images', 'local_secure_restricted');
458         $this->asAdmin();
459         $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
460         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
461
462         $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
463         $upload->assertRedirect('/settings/customization');
464
465         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
466
467         if (file_exists($expectedPath)) {
468             unlink($expectedPath);
469         }
470     }
471
472     public function test_avatar_images_visible_only_when_public_access_enabled_with_local_secure_restricted()
473     {
474         config()->set('filesystems.images', 'local_secure_restricted');
475         $user = $this->users->admin();
476         $avatars = $this->app->make(UserAvatars::class);
477         $avatars->assignToUserFromExistingData($user, $this->files->pngImageData(), 'png');
478
479         $avatarUrl = $user->getAvatar();
480
481         $resp = $this->get($avatarUrl);
482         $resp->assertRedirect('/login');
483
484         $this->permissions->makeAppPublic();
485
486         $resp = $this->get($avatarUrl);
487         $resp->assertOk();
488
489         $this->files->deleteAtRelativePath($user->avatar->path);
490     }
491
492     public function test_secure_restricted_images_inaccessible_without_relation_permission()
493     {
494         config()->set('filesystems.images', 'local_secure_restricted');
495         $this->asEditor();
496         $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
497         $page = $this->entities->page();
498
499         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
500         $upload->assertStatus(200);
501         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
502         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
503
504         $this->get($expectedUrl)->assertOk();
505
506         $this->permissions->setEntityPermissions($page, [], []);
507
508         $resp = $this->get($expectedUrl);
509         $resp->assertNotFound();
510
511         if (file_exists($expectedPath)) {
512             unlink($expectedPath);
513         }
514     }
515
516     public function test_secure_restricted_images_accessible_with_public_guest_access()
517     {
518         config()->set('filesystems.images', 'local_secure_restricted');
519         $this->permissions->makeAppPublic();
520
521         $this->asEditor();
522         $page = $this->entities->page();
523         $this->files->uploadGalleryImageToPage($this, $page);
524         $image = Image::query()->where('type', '=', 'gallery')
525             ->where('uploaded_to', '=', $page->id)
526             ->first();
527
528         $expectedUrl = url($image->path);
529         $expectedPath = storage_path($image->path);
530         auth()->logout();
531
532         $this->get($expectedUrl)->assertOk();
533
534         $this->permissions->setEntityPermissions($page, [], []);
535
536         $resp = $this->get($expectedUrl);
537         $resp->assertNotFound();
538
539         $this->permissions->setEntityPermissions($page, ['view'], [Role::getSystemRole('public')]);
540
541         $this->get($expectedUrl)->assertOk();
542
543         if (file_exists($expectedPath)) {
544             unlink($expectedPath);
545         }
546     }
547
548     public function test_thumbnail_path_handled_by_secure_restricted_images()
549     {
550         config()->set('filesystems.images', 'local_secure_restricted');
551         $this->asEditor();
552         $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
553         $page = $this->entities->page();
554
555         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
556         $upload->assertStatus(200);
557         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
558         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
559
560         $this->get($expectedUrl)->assertOk();
561
562         $this->permissions->setEntityPermissions($page, [], []);
563
564         $resp = $this->get($expectedUrl);
565         $resp->assertNotFound();
566
567         if (file_exists($expectedPath)) {
568             unlink($expectedPath);
569         }
570     }
571
572     public function test_secure_restricted_image_access_controlled_in_exports()
573     {
574         config()->set('filesystems.images', 'local_secure_restricted');
575         $this->asEditor();
576         $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
577
578         $pageA = $this->entities->page();
579         $pageB = $this->entities->page();
580         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
581
582         $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
583         $upload->assertOk();
584
585         $imageUrl = json_decode($upload->getContent(), true)['url'];
586         $pageB->html .= "<img src=\"{$imageUrl}\">";
587         $pageB->save();
588
589         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
590         $export = $this->get($pageB->getUrl('/export/html'));
591         $this->assertStringContainsString($encodedImageContent, $export->getContent());
592
593         $this->permissions->setEntityPermissions($pageA, [], []);
594
595         $export = $this->get($pageB->getUrl('/export/html'));
596         $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
597
598         if (file_exists($expectedPath)) {
599             unlink($expectedPath);
600         }
601     }
602
603     public function test_image_delete()
604     {
605         $page = $this->entities->page();
606         $this->asAdmin();
607         $imageName = 'first-image.png';
608         $relPath = $this->files->expectedImagePath('gallery', $imageName);
609         $this->files->deleteAtRelativePath($relPath);
610
611         $this->files->uploadGalleryImage($this, $imageName, $page->id);
612         $image = Image::first();
613
614         $delete = $this->delete('/images/' . $image->id);
615         $delete->assertStatus(200);
616
617         $this->assertDatabaseMissing('images', [
618             'url'  => $this->baseUrl . $relPath,
619             'type' => 'gallery',
620         ]);
621
622         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
623     }
624
625     public function test_image_delete_does_not_delete_similar_images()
626     {
627         $page = $this->entities->page();
628         $this->asAdmin();
629         $imageName = 'first-image.png';
630
631         $relPath = $this->files->expectedImagePath('gallery', $imageName);
632         $this->files->deleteAtRelativePath($relPath);
633
634         $this->files->uploadGalleryImage($this, $imageName, $page->id);
635         $this->files->uploadGalleryImage($this, $imageName, $page->id);
636         $this->files->uploadGalleryImage($this, $imageName, $page->id);
637
638         $image = Image::first();
639         $folder = public_path(dirname($relPath));
640         $imageCount = count(glob($folder . '/*'));
641
642         $delete = $this->delete('/images/' . $image->id);
643         $delete->assertStatus(200);
644
645         $newCount = count(glob($folder . '/*'));
646         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
647         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
648     }
649
650     public function test_image_manager_delete_button_only_shows_with_permission()
651     {
652         $page = $this->entities->page();
653         $this->asAdmin();
654         $imageName = 'first-image.png';
655         $relPath = $this->files->expectedImagePath('gallery', $imageName);
656         $this->files->deleteAtRelativePath($relPath);
657         $viewer = $this->users->viewer();
658
659         $this->files->uploadGalleryImage($this, $imageName, $page->id);
660         $image = Image::first();
661
662         $resp = $this->get("/images/edit/{$image->id}");
663         $this->withHtml($resp)->assertElementExists('button#image-manager-delete');
664
665         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
666         $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete');
667
668         $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
669
670         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
671         $this->withHtml($resp)->assertElementExists('button#image-manager-delete');
672
673         $this->files->deleteAtRelativePath($relPath);
674     }
675
676     public function test_image_manager_regen_thumbnails()
677     {
678         $this->asEditor();
679         $imageName = 'first-image.png';
680         $relPath = $this->files->expectedImagePath('gallery', $imageName);
681         $this->files->deleteAtRelativePath($relPath);
682
683         $this->files->uploadGalleryImage($this, $imageName, $this->entities->page()->id);
684         $image = Image::first();
685
686         $resp = $this->get("/images/edit/{$image->id}");
687         $this->withHtml($resp)->assertElementExists('button#image-manager-rebuild-thumbs');
688
689         $expectedThumbPath = dirname($relPath) . '/scaled-1680-/' . basename($relPath);
690         $this->files->deleteAtRelativePath($expectedThumbPath);
691         $this->assertFileDoesNotExist($this->files->relativeToFullPath($expectedThumbPath));
692
693         $resp = $this->put("/images/{$image->id}/rebuild-thumbnails");
694         $resp->assertOk();
695
696         $this->assertFileExists($this->files->relativeToFullPath($expectedThumbPath));
697         $this->files->deleteAtRelativePath($relPath);
698     }
699
700     public function test_gif_thumbnail_generation()
701     {
702         $this->asAdmin();
703         $originalFile = $this->files->testFilePath('animated.gif');
704         $originalFileSize = filesize($originalFile);
705
706         $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page(), 'animated.gif');
707         $relPath = $imgDetails['path'];
708
709         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
710         $galleryThumb = $imgDetails['response']->thumbs->gallery;
711         $displayThumb = $imgDetails['response']->thumbs->display;
712
713         // Ensure display thumbnail is original image
714         $this->assertStringEndsWith($imgDetails['path'], $displayThumb);
715         $this->assertStringNotContainsString('thumbs', $displayThumb);
716
717         // Ensure gallery thumbnail is reduced image (single frame)
718         $galleryThumbRelPath = implode('/', array_slice(explode('/', $galleryThumb), 3));
719         $galleryThumbPath = public_path($galleryThumbRelPath);
720         $galleryFileSize = filesize($galleryThumbPath);
721
722         // Basic scan of GIF content to check frame count
723         $originalFrameCount = count(explode("\x00\x21\xF9", file_get_contents($originalFile))) - 1;
724         $galleryFrameCount = count(explode("\x00\x21\xF9", file_get_contents($galleryThumbPath))) - 1;
725
726         $this->files->deleteAtRelativePath($relPath);
727         $this->files->deleteAtRelativePath($galleryThumbRelPath);
728
729         $this->assertNotEquals($originalFileSize, $galleryFileSize);
730         $this->assertEquals(2, $originalFrameCount);
731         $this->assertLessThan(2, $galleryFrameCount);
732     }
733
734     protected function getTestProfileImage()
735     {
736         $imageName = 'profile.png';
737         $relPath = $this->files->expectedImagePath('user', $imageName);
738         $this->files->deleteAtRelativePath($relPath);
739
740         return $this->files->uploadedImage($imageName);
741     }
742
743     public function test_user_image_upload()
744     {
745         $editor = $this->users->editor();
746         $admin = $this->users->admin();
747         $this->actingAs($admin);
748
749         $file = $this->getTestProfileImage();
750         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
751
752         $this->assertDatabaseHas('images', [
753             'type'        => 'user',
754             'uploaded_to' => $editor->id,
755             'created_by'  => $admin->id,
756         ]);
757     }
758
759     public function test_user_images_deleted_on_user_deletion()
760     {
761         $editor = $this->users->editor();
762         $this->actingAs($editor);
763
764         $file = $this->getTestProfileImage();
765         $this->call('PUT', '/my-account/profile', [], [], ['profile_image' => $file], []);
766
767         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
768         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
769
770         $imagePath = public_path($profileImages->first()->path);
771         $this->assertTrue(file_exists($imagePath));
772
773         $userDelete = $this->asAdmin()->delete($editor->getEditUrl());
774         $userDelete->assertStatus(302);
775
776         $this->assertDatabaseMissing('images', [
777             'type'       => 'user',
778             'created_by' => $editor->id,
779         ]);
780         $this->assertDatabaseMissing('images', [
781             'type'        => 'user',
782             'uploaded_to' => $editor->id,
783         ]);
784
785         $this->assertFalse(file_exists($imagePath));
786     }
787
788     public function test_deleted_unused_images()
789     {
790         $page = $this->entities->page();
791         $admin = $this->users->admin();
792         $this->actingAs($admin);
793
794         $imageName = 'unused-image.png';
795         $relPath = $this->files->expectedImagePath('gallery', $imageName);
796         $this->files->deleteAtRelativePath($relPath);
797
798         $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
799         $upload->assertStatus(200);
800         $image = Image::where('type', '=', 'gallery')->first();
801
802         $pageRepo = app(PageRepo::class);
803         $pageRepo->update($page, [
804             'name'    => $page->name,
805             'html'    => $page->html . "<img src=\"{$image->url}\">",
806             'summary' => '',
807         ]);
808
809         // Ensure no images are reported as deletable
810         $imageService = app(ImageService::class);
811         $toDelete = $imageService->deleteUnusedImages(true, true);
812         $this->assertCount(0, $toDelete);
813
814         // Save a revision of our page without the image;
815         $pageRepo->update($page, [
816             'name'    => $page->name,
817             'html'    => '<p>Hello</p>',
818             'summary' => '',
819         ]);
820
821         // Ensure revision images are picked up okay
822         $imageService = app(ImageService::class);
823         $toDelete = $imageService->deleteUnusedImages(true, true);
824         $this->assertCount(0, $toDelete);
825         $toDelete = $imageService->deleteUnusedImages(false, true);
826         $this->assertCount(1, $toDelete);
827
828         // Check image is found when revisions are destroyed
829         $page->revisions()->delete();
830         $toDelete = $imageService->deleteUnusedImages(true, true);
831         $this->assertCount(1, $toDelete);
832
833         // Check the image is deleted
834         $absPath = public_path($relPath);
835         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
836         $toDelete = $imageService->deleteUnusedImages(true, false);
837         $this->assertCount(1, $toDelete);
838         $this->assertFalse(file_exists($absPath));
839
840         $this->files->deleteAtRelativePath($relPath);
841     }
842 }