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