]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
5458779e943906db62a58cce8f12587a248d5139
[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 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 FilesystemManager $fileSystem;
33
34     protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
35
36     public function __construct(ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
37     {
38         $this->imageTool = $imageTool;
39         $this->fileSystem = $fileSystem;
40         $this->cache = $cache;
41     }
42
43     /**
44      * Get the storage that will be used for storing images.
45      */
46     protected function getStorageDisk(string $imageType = ''): Storage
47     {
48         return $this->fileSystem->disk($this->getStorageDiskName($imageType));
49     }
50
51     /**
52      * Check if local secure image storage (Fetched behind authentication)
53      * is currently active in the instance.
54      */
55     protected function usingSecureImages(string $imageType = 'gallery'): bool
56     {
57         return $this->getStorageDiskName($imageType) === 'local_secure_images';
58     }
59
60     /**
61      * Check if "local secure restricted" (Fetched behind auth, with permissions enforced)
62      * is currently active in the instance.
63      */
64     protected function usingSecureRestrictedImages()
65     {
66         return config('filesystems.images') === 'local_secure_restricted';
67     }
68
69     /**
70      * Change the originally provided path to fit any disk-specific requirements.
71      * This also ensures the path is kept to the expected root folders.
72      */
73     protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
74     {
75         $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/images/', '', $path));
76
77         if ($this->usingSecureImages($imageType)) {
78             return $path;
79         }
80
81         return 'uploads/images/' . $path;
82     }
83
84     /**
85      * Get the name of the storage disk to use.
86      */
87     protected function getStorageDiskName(string $imageType): string
88     {
89         $storageType = config('filesystems.images');
90         $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted');
91
92         // Ensure system images (App logo) are uploaded to a public space
93         if ($imageType === 'system' && $localSecureInUse) {
94             return '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 ($localSecureInUse) {
100             return '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                 /** @var Image $image */
466                 foreach ($images as $image) {
467                     $searchQuery = '%' . basename($image->path) . '%';
468                     $inPage = DB::table('pages')
469                             ->where('html', 'like', $searchQuery)->count() > 0;
470
471                     $inRevision = false;
472                     if ($checkRevisions) {
473                         $inRevision = DB::table('page_revisions')
474                                 ->where('html', 'like', $searchQuery)->count() > 0;
475                     }
476
477                     if (!$inPage && !$inRevision) {
478                         $deletedPaths[] = $image->path;
479                         if (!$dryRun) {
480                             $this->destroy($image);
481                         }
482                     }
483                 }
484             });
485
486         return $deletedPaths;
487     }
488
489     /**
490      * Convert an image URI to a Base64 encoded string.
491      * Attempts to convert the URL to a system storage url then
492      * fetch the data from the disk or storage location.
493      * Returns null if the image data cannot be fetched from storage.
494      *
495      * @throws FileNotFoundException
496      */
497     public function imageUriToBase64(string $uri): ?string
498     {
499         $storagePath = $this->imageUrlToStoragePath($uri);
500         if (empty($uri) || is_null($storagePath)) {
501             return null;
502         }
503
504         $storagePath = $this->adjustPathForStorageDisk($storagePath);
505
506         // Apply access control when local_secure_restricted images are active
507         if ($this->usingSecureRestrictedImages()) {
508             if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
509                 return null;
510             }
511         }
512
513         $storage = $this->getStorageDisk();
514         $imageData = null;
515         if ($storage->exists($storagePath)) {
516             $imageData = $storage->get($storagePath);
517         }
518
519         if (is_null($imageData)) {
520             return null;
521         }
522
523         $extension = pathinfo($uri, PATHINFO_EXTENSION);
524         if ($extension === 'svg') {
525             $extension = 'svg+xml';
526         }
527
528         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
529     }
530
531     /**
532      * Check if the given path exists and is accessible in the local secure image system.
533      * Returns false if local_secure is not in use, if the file does not exist, if the
534      * file is likely not a valid image, or if permission does not allow access.
535      */
536     public function pathAccessibleInLocalSecure(string $imagePath): bool
537     {
538         /** @var FilesystemAdapter $disk */
539         $disk = $this->getStorageDisk('gallery');
540
541         if ($this->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
542             return false;
543         }
544
545         // Check local_secure is active
546         return $this->usingSecureImages()
547             && $disk instanceof FilesystemAdapter
548             // Check the image file exists
549             && $disk->exists($imagePath)
550             // Check the file is likely an image file
551             && strpos($disk->mimeType($imagePath), 'image/') === 0;
552     }
553
554     /**
555      * Check that the current user has access to the relation
556      * of the image at the given path.
557      */
558     protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
559     {
560         if (strpos($path, '/uploads/images/') === 0) {
561             $path = substr($path, 15);
562         }
563
564         // Strip thumbnail element from path if existing
565         $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
566             $resizedDir = (strpos($part, 'thumbs-') === 0 || strpos($part, 'scaled-') === 0);
567             $missingExtension = strpos($part, '.') === false;
568
569             return !($resizedDir && $missingExtension);
570         });
571
572         // Build a database-format image path and search for the image entry
573         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
574         $image = Image::query()->where('path', '=', $fullPath)->first();
575
576         if (is_null($image)) {
577             return false;
578         }
579
580         $imageType = $image->type;
581
582         // Allow user or system (logo) images
583         // (No specific relation control but may still have access controlled by auth)
584         if ($imageType === 'user' || $imageType === 'system') {
585             return true;
586         }
587
588         if ($imageType === 'gallery' || $imageType === 'drawio') {
589             return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
590         }
591
592         if ($imageType === 'cover_book') {
593             return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
594         }
595
596         if ($imageType === 'cover_bookshelf') {
597             return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
598         }
599
600         return false;
601     }
602
603     /**
604      * For the given path, if existing, provide a response that will stream the image contents.
605      */
606     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
607     {
608         $disk = $this->getStorageDisk($imageType);
609
610         return $disk->response($path);
611     }
612
613     /**
614      * Check if the given image extension is supported by BookStack.
615      * The extension must not be altered in this function. This check should provide a guarantee
616      * that the provided extension is safe to use for the image to be saved.
617      */
618     public static function isExtensionSupported(string $extension): bool
619     {
620         return in_array($extension, static::$supportedExtensions);
621     }
622
623     /**
624      * Get a storage path for the given image URL.
625      * Ensures the path will start with "uploads/images".
626      * Returns null if the url cannot be resolved to a local URL.
627      */
628     private function imageUrlToStoragePath(string $url): ?string
629     {
630         $url = ltrim(trim($url), '/');
631
632         // Handle potential relative paths
633         $isRelative = strpos($url, 'http') !== 0;
634         if ($isRelative) {
635             if (strpos(strtolower($url), 'uploads/images') === 0) {
636                 return trim($url, '/');
637             }
638
639             return null;
640         }
641
642         // Handle local images based on paths on the same domain
643         $potentialHostPaths = [
644             url('uploads/images/'),
645             $this->getPublicUrl('/uploads/images/'),
646         ];
647
648         foreach ($potentialHostPaths as $potentialBasePath) {
649             $potentialBasePath = strtolower($potentialBasePath);
650             if (strpos(strtolower($url), $potentialBasePath) === 0) {
651                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
652             }
653         }
654
655         return null;
656     }
657
658     /**
659      * Gets a public facing url for an image by checking relevant environment variables.
660      * If s3-style store is in use it will default to guessing a public bucket URL.
661      */
662     private function getPublicUrl(string $filePath): string
663     {
664         $storageUrl = config('filesystems.url');
665
666         // Get the standard public s3 url if s3 is set as storage type
667         // Uses the nice, short URL if bucket name has no periods in otherwise the longer
668         // region-based url will be used to prevent http issues.
669         if (!$storageUrl && config('filesystems.images') === 's3') {
670             $storageDetails = config('filesystems.disks.s3');
671             if (strpos($storageDetails['bucket'], '.') === false) {
672                 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
673             } else {
674                 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
675             }
676         }
677
678         $basePath = $storageUrl ?: url('/');
679
680         return rtrim($basePath, '/') . $filePath;
681     }
682 }