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