]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Fixed app logo visibility with secure_restricted images
[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         $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted');
92
93         // Ensure system images (App logo) are uploaded to a public space
94         if ($imageType === 'system' && $localSecureInUse) {
95             return 'local';
96         }
97
98         // Rename local_secure options to get our image specific storage driver which
99         // is scoped to the relevant image directories.
100         if ($localSecureInUse) {
101             return 'local_secure_images';
102         }
103
104         return $storageType;
105     }
106
107     /**
108      * Saves a new image from an upload.
109      *
110      * @throws ImageUploadException
111      *
112      * @return mixed
113      */
114     public function saveNewFromUpload(
115         UploadedFile $uploadedFile,
116         string $type,
117         int $uploadedTo = 0,
118         int $resizeWidth = null,
119         int $resizeHeight = null,
120         bool $keepRatio = true
121     ) {
122         $imageName = $uploadedFile->getClientOriginalName();
123         $imageData = file_get_contents($uploadedFile->getRealPath());
124
125         if ($resizeWidth !== null || $resizeHeight !== null) {
126             $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
127         }
128
129         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
130     }
131
132     /**
133      * Save a new image from a uri-encoded base64 string of data.
134      *
135      * @throws ImageUploadException
136      */
137     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
138     {
139         $splitData = explode(';base64,', $base64Uri);
140         if (count($splitData) < 2) {
141             throw new ImageUploadException('Invalid base64 image data provided');
142         }
143         $data = base64_decode($splitData[1]);
144
145         return $this->saveNew($name, $data, $type, $uploadedTo);
146     }
147
148     /**
149      * Save a new image into storage.
150      *
151      * @throws ImageUploadException
152      */
153     public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
154     {
155         $storage = $this->getStorageDisk($type);
156         $secureUploads = setting('app-secure-images');
157         $fileName = $this->cleanImageFileName($imageName);
158
159         $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
160
161         while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
162             $fileName = Str::random(3) . $fileName;
163         }
164
165         $fullPath = $imagePath . $fileName;
166         if ($secureUploads) {
167             $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
168         }
169
170         try {
171             $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
172         } catch (Exception $e) {
173             Log::error('Error when attempting image upload:' . $e->getMessage());
174
175             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
176         }
177
178         $imageDetails = [
179             'name'        => $imageName,
180             'path'        => $fullPath,
181             'url'         => $this->getPublicUrl($fullPath),
182             'type'        => $type,
183             'uploaded_to' => $uploadedTo,
184         ];
185
186         if (user()->id !== 0) {
187             $userId = user()->id;
188             $imageDetails['created_by'] = $userId;
189             $imageDetails['updated_by'] = $userId;
190         }
191
192         $image = (new Image())->forceFill($imageDetails);
193         $image->save();
194
195         return $image;
196     }
197
198     /**
199      * Save image data for the given path in the public space, if possible,
200      * for the provided storage mechanism.
201      */
202     protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
203     {
204         $storage->put($path, $data);
205
206         // Set visibility when a non-AWS-s3, s3-like storage option is in use.
207         // Done since this call can break s3-like services but desired for other image stores.
208         // Attempting to set ACL during above put request requires different permissions
209         // hence would technically be a breaking change for actual s3 usage.
210         $usingS3 = strtolower(config('filesystems.images')) === 's3';
211         $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
212         if (!$usingS3Like) {
213             $storage->setVisibility($path, 'public');
214         }
215     }
216
217     /**
218      * Clean up an image file name to be both URL and storage safe.
219      */
220     protected function cleanImageFileName(string $name): string
221     {
222         $name = str_replace(' ', '-', $name);
223         $nameParts = explode('.', $name);
224         $extension = array_pop($nameParts);
225         $name = implode('-', $nameParts);
226         $name = Str::slug($name);
227
228         if (strlen($name) === 0) {
229             $name = Str::random(10);
230         }
231
232         return $name . '.' . $extension;
233     }
234
235     /**
236      * Checks if the image is a gif. Returns true if it is, else false.
237      */
238     protected function isGif(Image $image): bool
239     {
240         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
241     }
242
243     /**
244      * Check if the given image and image data is apng.
245      */
246     protected function isApngData(Image $image, string &$imageData): bool
247     {
248         $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
249         if (!$isPng) {
250             return false;
251         }
252
253         $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
254
255         return strpos($initialHeader, 'acTL') !== false;
256     }
257
258     /**
259      * Get the thumbnail for an image.
260      * If $keepRatio is true only the width will be used.
261      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
262      *
263      * @throws Exception
264      * @throws InvalidArgumentException
265      */
266     public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false): string
267     {
268         // Do not resize GIF images where we're not cropping
269         if ($keepRatio && $this->isGif($image)) {
270             return $this->getPublicUrl($image->path);
271         }
272
273         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
274         $imagePath = $image->path;
275         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
276
277         $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
278
279         // Return path if in cache
280         $cachedThumbPath = $this->cache->get($thumbCacheKey);
281         if ($cachedThumbPath) {
282             return $this->getPublicUrl($cachedThumbPath);
283         }
284
285         // If thumbnail has already been generated, serve that and cache path
286         $storage = $this->getStorageDisk($image->type);
287         if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
288             $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
289
290             return $this->getPublicUrl($thumbFilePath);
291         }
292
293         $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
294
295         // Do not resize apng images where we're not cropping
296         if ($keepRatio && $this->isApngData($image, $imageData)) {
297             $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
298
299             return $this->getPublicUrl($image->path);
300         }
301
302         // If not in cache and thumbnail does not exist, generate thumb and cache path
303         $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
304         $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
305         $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
306
307         return $this->getPublicUrl($thumbFilePath);
308     }
309
310     /**
311      * Resize the image of given data to the specified size, and return the new image data.
312      *
313      * @throws ImageUploadException
314      */
315     protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
316     {
317         try {
318             $thumb = $this->imageTool->make($imageData);
319         } catch (ErrorException | NotSupportedException $e) {
320             throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
321         }
322
323         $this->orientImageToOriginalExif($thumb, $imageData);
324
325         if ($keepRatio) {
326             $thumb->resize($width, $height, function ($constraint) {
327                 $constraint->aspectRatio();
328                 $constraint->upsize();
329             });
330         } else {
331             $thumb->fit($width, $height);
332         }
333
334         $thumbData = (string) $thumb->encode();
335
336         // Use original image data if we're keeping the ratio
337         // and the resizing does not save any space.
338         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
339             return $imageData;
340         }
341
342         return $thumbData;
343     }
344
345     /**
346      * Orientate the given intervention image based upon the given original image data.
347      * Intervention does have an `orientate` method but the exif data it needs is lost before it
348      * can be used (At least when created using binary string data) so we need to do some
349      * implementation on our side to use the original image data.
350      * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
351      * Copyright (c) Oliver Vogel, MIT License.
352      */
353     protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
354     {
355         if (!extension_loaded('exif')) {
356             return;
357         }
358
359         $stream = Utils::streamFor($originalData)->detach();
360         $exif = @exif_read_data($stream);
361         $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
362
363         switch ($orientation) {
364             case 2:
365                 $image->flip();
366                 break;
367             case 3:
368                 $image->rotate(180);
369                 break;
370             case 4:
371                 $image->rotate(180)->flip();
372                 break;
373             case 5:
374                 $image->rotate(270)->flip();
375                 break;
376             case 6:
377                 $image->rotate(270);
378                 break;
379             case 7:
380                 $image->rotate(90)->flip();
381                 break;
382             case 8:
383                 $image->rotate(90);
384                 break;
385         }
386     }
387
388     /**
389      * Get the raw data content from an image.
390      *
391      * @throws FileNotFoundException
392      */
393     public function getImageData(Image $image): string
394     {
395         $storage = $this->getStorageDisk();
396
397         return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
398     }
399
400     /**
401      * Destroy an image along with its revisions, thumbnails and remaining folders.
402      *
403      * @throws Exception
404      */
405     public function destroy(Image $image)
406     {
407         $this->destroyImagesFromPath($image->path, $image->type);
408         $image->delete();
409     }
410
411     /**
412      * Destroys an image at the given path.
413      * Searches for image thumbnails in addition to main provided path.
414      */
415     protected function destroyImagesFromPath(string $path, string $imageType): bool
416     {
417         $path = $this->adjustPathForStorageDisk($path, $imageType);
418         $storage = $this->getStorageDisk($imageType);
419
420         $imageFolder = dirname($path);
421         $imageFileName = basename($path);
422         $allImages = collect($storage->allFiles($imageFolder));
423
424         // Delete image files
425         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
426             return basename($imagePath) === $imageFileName;
427         });
428         $storage->delete($imagesToDelete->all());
429
430         // Cleanup of empty folders
431         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
432         foreach ($foldersInvolved as $directory) {
433             if ($this->isFolderEmpty($storage, $directory)) {
434                 $storage->deleteDirectory($directory);
435             }
436         }
437
438         return true;
439     }
440
441     /**
442      * Check whether a folder is empty.
443      */
444     protected function isFolderEmpty(Storage $storage, string $path): bool
445     {
446         $files = $storage->files($path);
447         $folders = $storage->directories($path);
448
449         return count($files) === 0 && count($folders) === 0;
450     }
451
452     /**
453      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
454      * Checks based off of only the image name.
455      * Could be much improved to be more specific but kept it generic for now to be safe.
456      *
457      * Returns the path of the images that would be/have been deleted.
458      */
459     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
460     {
461         $types = ['gallery', 'drawio'];
462         $deletedPaths = [];
463
464         Image::query()->whereIn('type', $types)
465             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
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->getMimetype($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         if (is_null($this->storageUrl)) {
665             $storageUrl = config('filesystems.url');
666
667             // Get the standard public s3 url if s3 is set as storage type
668             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
669             // region-based url will be used to prevent http issues.
670             if ($storageUrl == false && config('filesystems.images') === 's3') {
671                 $storageDetails = config('filesystems.disks.s3');
672                 if (strpos($storageDetails['bucket'], '.') === false) {
673                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
674                 } else {
675                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
676                 }
677             }
678
679             $this->storageUrl = $storageUrl;
680         }
681
682         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
683
684         return rtrim($basePath, '/') . $filePath;
685     }
686 }