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