]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Added test and handling for local_secure_restricted in exports
[bookstack] / app / Uploads / ImageService.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Exceptions\ImageUploadException;
9 use ErrorException;
10 use Exception;
11 use GuzzleHttp\Psr7\Utils;
12 use Illuminate\Contracts\Cache\Repository as Cache;
13 use Illuminate\Contracts\Filesystem\FileNotFoundException;
14 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
15 use Illuminate\Filesystem\FilesystemAdapter;
16 use Illuminate\Filesystem\FilesystemManager;
17 use Illuminate\Support\Facades\DB;
18 use Illuminate\Support\Facades\Log;
19 use Illuminate\Support\Str;
20 use Intervention\Image\Exception\NotSupportedException;
21 use Intervention\Image\Image as InterventionImage;
22 use Intervention\Image\ImageManager;
23 use League\Flysystem\Util;
24 use Psr\SimpleCache\InvalidArgumentException;
25 use Symfony\Component\HttpFoundation\File\UploadedFile;
26 use Symfony\Component\HttpFoundation\StreamedResponse;
27
28 class ImageService
29 {
30     protected ImageManager $imageTool;
31     protected Cache $cache;
32     protected $storageUrl;
33     protected FilesystemManager $fileSystem;
34
35     protected static $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
36
37     public function __construct(ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
38     {
39         $this->imageTool = $imageTool;
40         $this->fileSystem = $fileSystem;
41         $this->cache = $cache;
42     }
43
44     /**
45      * Get the storage that will be used for storing images.
46      */
47     protected function getStorageDisk(string $imageType = ''): Storage
48     {
49         return $this->fileSystem->disk($this->getStorageDiskName($imageType));
50     }
51
52     /**
53      * Check if local secure image storage (Fetched behind authentication)
54      * is currently active in the instance.
55      */
56     protected function usingSecureImages(string $imageType = 'gallery'): bool
57     {
58         return $this->getStorageDiskName($imageType) === 'local_secure_images';
59     }
60
61     /**
62      * Check if "local secure restricted" (Fetched behind auth, with permissions enforced)
63      * is currently active in the instance.
64      */
65     protected function usingSecureRestrictedImages()
66     {
67         return config('filesystems.images') === 'local_secure_restricted';
68     }
69
70     /**
71      * Change the originally provided path to fit any disk-specific requirements.
72      * This also ensures the path is kept to the expected root folders.
73      */
74     protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
75     {
76         $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
77
78         if ($this->usingSecureImages($imageType)) {
79             return $path;
80         }
81
82         return 'uploads/images/' . $path;
83     }
84
85     /**
86      * Get the name of the storage disk to use.
87      */
88     protected function getStorageDiskName(string $imageType): string
89     {
90         $storageType = config('filesystems.images');
91
92         // Ensure system images (App logo) are uploaded to a public space
93         if ($imageType === 'system' && $storageType === 'local_secure') {
94             $storageType = 'local';
95         }
96
97         // Rename local_secure options to get our image specific storage driver which
98         // is scoped to the relevant image directories.
99         if ($storageType === 'local_secure' || $storageType === 'local_secure_restricted') {
100             $storageType = 'local_secure_images';
101         }
102
103         return $storageType;
104     }
105
106     /**
107      * Saves a new image from an upload.
108      *
109      * @throws ImageUploadException
110      *
111      * @return mixed
112      */
113     public function saveNewFromUpload(
114         UploadedFile $uploadedFile,
115         string $type,
116         int $uploadedTo = 0,
117         int $resizeWidth = null,
118         int $resizeHeight = null,
119         bool $keepRatio = true
120     ) {
121         $imageName = $uploadedFile->getClientOriginalName();
122         $imageData = file_get_contents($uploadedFile->getRealPath());
123
124         if ($resizeWidth !== null || $resizeHeight !== null) {
125             $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
126         }
127
128         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
129     }
130
131     /**
132      * Save a new image from a uri-encoded base64 string of data.
133      *
134      * @throws ImageUploadException
135      */
136     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
137     {
138         $splitData = explode(';base64,', $base64Uri);
139         if (count($splitData) < 2) {
140             throw new ImageUploadException('Invalid base64 image data provided');
141         }
142         $data = base64_decode($splitData[1]);
143
144         return $this->saveNew($name, $data, $type, $uploadedTo);
145     }
146
147     /**
148      * Save a new image into storage.
149      *
150      * @throws ImageUploadException
151      */
152     public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
153     {
154         $storage = $this->getStorageDisk($type);
155         $secureUploads = setting('app-secure-images');
156         $fileName = $this->cleanImageFileName($imageName);
157
158         $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
159
160         while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
161             $fileName = Str::random(3) . $fileName;
162         }
163
164         $fullPath = $imagePath . $fileName;
165         if ($secureUploads) {
166             $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
167         }
168
169         try {
170             $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
171         } catch (Exception $e) {
172             Log::error('Error when attempting image upload:' . $e->getMessage());
173
174             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
175         }
176
177         $imageDetails = [
178             'name'        => $imageName,
179             'path'        => $fullPath,
180             'url'         => $this->getPublicUrl($fullPath),
181             'type'        => $type,
182             'uploaded_to' => $uploadedTo,
183         ];
184
185         if (user()->id !== 0) {
186             $userId = user()->id;
187             $imageDetails['created_by'] = $userId;
188             $imageDetails['updated_by'] = $userId;
189         }
190
191         $image = (new Image())->forceFill($imageDetails);
192         $image->save();
193
194         return $image;
195     }
196
197     /**
198      * Save image data for the given path in the public space, if possible,
199      * for the provided storage mechanism.
200      */
201     protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
202     {
203         $storage->put($path, $data);
204
205         // Set visibility when a non-AWS-s3, s3-like storage option is in use.
206         // Done since this call can break s3-like services but desired for other image stores.
207         // Attempting to set ACL during above put request requires different permissions
208         // hence would technically be a breaking change for actual s3 usage.
209         $usingS3 = strtolower(config('filesystems.images')) === 's3';
210         $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
211         if (!$usingS3Like) {
212             $storage->setVisibility($path, 'public');
213         }
214     }
215
216     /**
217      * Clean up an image file name to be both URL and storage safe.
218      */
219     protected function cleanImageFileName(string $name): string
220     {
221         $name = str_replace(' ', '-', $name);
222         $nameParts = explode('.', $name);
223         $extension = array_pop($nameParts);
224         $name = implode('-', $nameParts);
225         $name = Str::slug($name);
226
227         if (strlen($name) === 0) {
228             $name = Str::random(10);
229         }
230
231         return $name . '.' . $extension;
232     }
233
234     /**
235      * Checks if the image is a gif. Returns true if it is, else false.
236      */
237     protected function isGif(Image $image): bool
238     {
239         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
240     }
241
242     /**
243      * Check if the given image and image data is apng.
244      */
245     protected function isApngData(Image $image, string &$imageData): bool
246     {
247         $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
248         if (!$isPng) {
249             return false;
250         }
251
252         $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
253
254         return strpos($initialHeader, 'acTL') !== false;
255     }
256
257     /**
258      * Get the thumbnail for an image.
259      * If $keepRatio is true only the width will be used.
260      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
261      *
262      * @throws Exception
263      * @throws InvalidArgumentException
264      */
265     public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false): string
266     {
267         // Do not resize GIF images where we're not cropping
268         if ($keepRatio && $this->isGif($image)) {
269             return $this->getPublicUrl($image->path);
270         }
271
272         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
273         $imagePath = $image->path;
274         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
275
276         $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
277
278         // Return path if in cache
279         $cachedThumbPath = $this->cache->get($thumbCacheKey);
280         if ($cachedThumbPath) {
281             return $this->getPublicUrl($cachedThumbPath);
282         }
283
284         // If thumbnail has already been generated, serve that and cache path
285         $storage = $this->getStorageDisk($image->type);
286         if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
287             $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
288
289             return $this->getPublicUrl($thumbFilePath);
290         }
291
292         $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
293
294         // Do not resize apng images where we're not cropping
295         if ($keepRatio && $this->isApngData($image, $imageData)) {
296             $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
297
298             return $this->getPublicUrl($image->path);
299         }
300
301         // If not in cache and thumbnail does not exist, generate thumb and cache path
302         $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
303         $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
304         $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
305
306         return $this->getPublicUrl($thumbFilePath);
307     }
308
309     /**
310      * Resize the image of given data to the specified size, and return the new image data.
311      *
312      * @throws ImageUploadException
313      */
314     protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
315     {
316         try {
317             $thumb = $this->imageTool->make($imageData);
318         } catch (ErrorException|NotSupportedException $e) {
319             throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
320         }
321
322         $this->orientImageToOriginalExif($thumb, $imageData);
323
324         if ($keepRatio) {
325             $thumb->resize($width, $height, function ($constraint) {
326                 $constraint->aspectRatio();
327                 $constraint->upsize();
328             });
329         } else {
330             $thumb->fit($width, $height);
331         }
332
333         $thumbData = (string) $thumb->encode();
334
335         // Use original image data if we're keeping the ratio
336         // and the resizing does not save any space.
337         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
338             return $imageData;
339         }
340
341         return $thumbData;
342     }
343
344     /**
345      * Orientate the given intervention image based upon the given original image data.
346      * Intervention does have an `orientate` method but the exif data it needs is lost before it
347      * can be used (At least when created using binary string data) so we need to do some
348      * implementation on our side to use the original image data.
349      * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
350      * Copyright (c) Oliver Vogel, MIT License.
351      */
352     protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
353     {
354         if (!extension_loaded('exif')) {
355             return;
356         }
357
358         $stream = Utils::streamFor($originalData)->detach();
359         $exif = @exif_read_data($stream);
360         $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
361
362         switch ($orientation) {
363             case 2:
364                 $image->flip();
365                 break;
366             case 3:
367                 $image->rotate(180);
368                 break;
369             case 4:
370                 $image->rotate(180)->flip();
371                 break;
372             case 5:
373                 $image->rotate(270)->flip();
374                 break;
375             case 6:
376                 $image->rotate(270);
377                 break;
378             case 7:
379                 $image->rotate(90)->flip();
380                 break;
381             case 8:
382                 $image->rotate(90);
383                 break;
384         }
385     }
386
387     /**
388      * Get the raw data content from an image.
389      *
390      * @throws FileNotFoundException
391      */
392     public function getImageData(Image $image): string
393     {
394         $storage = $this->getStorageDisk();
395
396         return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
397     }
398
399     /**
400      * Destroy an image along with its revisions, thumbnails and remaining folders.
401      *
402      * @throws Exception
403      */
404     public function destroy(Image $image)
405     {
406         $this->destroyImagesFromPath($image->path, $image->type);
407         $image->delete();
408     }
409
410     /**
411      * Destroys an image at the given path.
412      * Searches for image thumbnails in addition to main provided path.
413      */
414     protected function destroyImagesFromPath(string $path, string $imageType): bool
415     {
416         $path = $this->adjustPathForStorageDisk($path, $imageType);
417         $storage = $this->getStorageDisk($imageType);
418
419         $imageFolder = dirname($path);
420         $imageFileName = basename($path);
421         $allImages = collect($storage->allFiles($imageFolder));
422
423         // Delete image files
424         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
425             return basename($imagePath) === $imageFileName;
426         });
427         $storage->delete($imagesToDelete->all());
428
429         // Cleanup of empty folders
430         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
431         foreach ($foldersInvolved as $directory) {
432             if ($this->isFolderEmpty($storage, $directory)) {
433                 $storage->deleteDirectory($directory);
434             }
435         }
436
437         return true;
438     }
439
440     /**
441      * Check whether a folder is empty.
442      */
443     protected function isFolderEmpty(Storage $storage, string $path): bool
444     {
445         $files = $storage->files($path);
446         $folders = $storage->directories($path);
447
448         return count($files) === 0 && count($folders) === 0;
449     }
450
451     /**
452      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
453      * Checks based off of only the image name.
454      * Could be much improved to be more specific but kept it generic for now to be safe.
455      *
456      * Returns the path of the images that would be/have been deleted.
457      */
458     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
459     {
460         $types = ['gallery', 'drawio'];
461         $deletedPaths = [];
462
463         Image::query()->whereIn('type', $types)
464             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
465                 foreach ($images as $image) {
466                     $searchQuery = '%' . basename($image->path) . '%';
467                     $inPage = DB::table('pages')
468                             ->where('html', 'like', $searchQuery)->count() > 0;
469
470                     $inRevision = false;
471                     if ($checkRevisions) {
472                         $inRevision = DB::table('page_revisions')
473                                 ->where('html', 'like', $searchQuery)->count() > 0;
474                     }
475
476                     if (!$inPage && !$inRevision) {
477                         $deletedPaths[] = $image->path;
478                         if (!$dryRun) {
479                             $this->destroy($image);
480                         }
481                     }
482                 }
483             });
484
485         return $deletedPaths;
486     }
487
488     /**
489      * Convert an image URI to a Base64 encoded string.
490      * Attempts to convert the URL to a system storage url then
491      * fetch the data from the disk or storage location.
492      * Returns null if the image data cannot be fetched from storage.
493      *
494      * @throws FileNotFoundException
495      */
496     public function imageUriToBase64(string $uri): ?string
497     {
498         $storagePath = $this->imageUrlToStoragePath($uri);
499         if (empty($uri) || is_null($storagePath)) {
500             return null;
501         }
502
503         $storagePath = $this->adjustPathForStorageDisk($storagePath);
504
505         // Apply access control when local_secure_restricted images are active
506         if ($this->usingSecureRestrictedImages()) {
507             if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
508                 return null;
509             }
510         }
511
512         $storage = $this->getStorageDisk();
513         $imageData = null;
514         if ($storage->exists($storagePath)) {
515             $imageData = $storage->get($storagePath);
516         }
517
518         if (is_null($imageData)) {
519             return null;
520         }
521
522         $extension = pathinfo($uri, PATHINFO_EXTENSION);
523         if ($extension === 'svg') {
524             $extension = 'svg+xml';
525         }
526
527         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
528     }
529
530     /**
531      * Check if the given path exists and is accessible in the local secure image system.
532      * Returns false if local_secure is not in use, if the file does not exist, if the
533      * file is likely not a valid image, or if permission does not allow access.
534      */
535     public function pathAccessibleInLocalSecure(string $imagePath): bool
536     {
537         /** @var FilesystemAdapter $disk */
538         $disk = $this->getStorageDisk('gallery');
539
540         if ($this->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
541             return false;
542         }
543
544         // Check local_secure is active
545         return $this->usingSecureImages()
546             && $disk instanceof FilesystemAdapter
547             // Check the image file exists
548             && $disk->exists($imagePath)
549             // Check the file is likely an image file
550             && strpos($disk->getMimetype($imagePath), 'image/') === 0;
551     }
552
553     /**
554      * Check that the current user has access to the relation
555      * of the image at the given path.
556      */
557     protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
558     {
559         if (strpos($path, '/uploads/images/') === 0) {
560             $path = substr($path, 15);
561         }
562
563         // Strip thumbnail element from path if existing
564         $originalPathSplit = array_filter(explode('/', $path), function(string $part) {
565             $resizedDir = (strpos($part, 'thumbs-') === 0 || strpos($part, 'scaled-') === 0);
566             $missingExtension = strpos($part, '.') === false;
567             return !($resizedDir && $missingExtension);
568         });
569
570         // Build a database-format image path and search for the image entry
571         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
572         $image = Image::query()->where('path', '=', $fullPath)->first();
573
574         if (is_null($image)) {
575             return false;
576         }
577
578         $imageType = $image->type;
579
580         // Allow user or system (logo) images
581         // (No specific relation control but may still have access controlled by auth)
582         if ($imageType === 'user' || $imageType === 'system') {
583             return true;
584         }
585
586         if ($imageType === 'gallery' || $imageType === 'drawio') {
587             return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
588         }
589
590         if ($imageType === 'cover_book') {
591             return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
592         }
593
594         if ($imageType === 'cover_bookshelf') {
595             return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
596         }
597
598         return false;
599     }
600
601     /**
602      * For the given path, if existing, provide a response that will stream the image contents.
603      */
604     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
605     {
606         $disk = $this->getStorageDisk($imageType);
607
608         return $disk->response($path);
609     }
610
611     /**
612      * Check if the given image extension is supported by BookStack.
613      * The extension must not be altered in this function. This check should provide a guarantee
614      * that the provided extension is safe to use for the image to be saved.
615      */
616     public static function isExtensionSupported(string $extension): bool
617     {
618         return in_array($extension, static::$supportedExtensions);
619     }
620
621     /**
622      * Get a storage path for the given image URL.
623      * Ensures the path will start with "uploads/images".
624      * Returns null if the url cannot be resolved to a local URL.
625      */
626     private function imageUrlToStoragePath(string $url): ?string
627     {
628         $url = ltrim(trim($url), '/');
629
630         // Handle potential relative paths
631         $isRelative = strpos($url, 'http') !== 0;
632         if ($isRelative) {
633             if (strpos(strtolower($url), 'uploads/images') === 0) {
634                 return trim($url, '/');
635             }
636
637             return null;
638         }
639
640         // Handle local images based on paths on the same domain
641         $potentialHostPaths = [
642             url('uploads/images/'),
643             $this->getPublicUrl('/uploads/images/'),
644         ];
645
646         foreach ($potentialHostPaths as $potentialBasePath) {
647             $potentialBasePath = strtolower($potentialBasePath);
648             if (strpos(strtolower($url), $potentialBasePath) === 0) {
649                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
650             }
651         }
652
653         return null;
654     }
655
656     /**
657      * Gets a public facing url for an image by checking relevant environment variables.
658      * If s3-style store is in use it will default to guessing a public bucket URL.
659      */
660     private function getPublicUrl(string $filePath): string
661     {
662         if (is_null($this->storageUrl)) {
663             $storageUrl = config('filesystems.url');
664
665             // Get the standard public s3 url if s3 is set as storage type
666             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
667             // region-based url will be used to prevent http issues.
668             if ($storageUrl == false && config('filesystems.images') === 's3') {
669                 $storageDetails = config('filesystems.disks.s3');
670                 if (strpos($storageDetails['bucket'], '.') === false) {
671                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
672                 } else {
673                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
674                 }
675             }
676
677             $this->storageUrl = $storageUrl;
678         }
679
680         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
681
682         return rtrim($basePath, '/') . $filePath;
683     }
684 }