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