]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Altered ldap_connect usage, cleaned up LDAP classes
[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     public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
198     {
199         $imageData = file_get_contents($file->getRealPath());
200         $storage = $this->getStorageDisk($type);
201         $adjustedPath = $this->adjustPathForStorageDisk($path, $type);
202         $storage->put($adjustedPath, $imageData);
203     }
204
205     /**
206      * Save image data for the given path in the public space, if possible,
207      * for the provided storage mechanism.
208      */
209     protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
210     {
211         $storage->put($path, $data);
212
213         // Set visibility when a non-AWS-s3, s3-like storage option is in use.
214         // Done since this call can break s3-like services but desired for other image stores.
215         // Attempting to set ACL during above put request requires different permissions
216         // hence would technically be a breaking change for actual s3 usage.
217         $usingS3 = strtolower(config('filesystems.images')) === 's3';
218         $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
219         if (!$usingS3Like) {
220             $storage->setVisibility($path, 'public');
221         }
222     }
223
224     /**
225      * Clean up an image file name to be both URL and storage safe.
226      */
227     protected function cleanImageFileName(string $name): string
228     {
229         $name = str_replace(' ', '-', $name);
230         $nameParts = explode('.', $name);
231         $extension = array_pop($nameParts);
232         $name = implode('-', $nameParts);
233         $name = Str::slug($name);
234
235         if (strlen($name) === 0) {
236             $name = Str::random(10);
237         }
238
239         return $name . '.' . $extension;
240     }
241
242     /**
243      * Checks if the image is a gif. Returns true if it is, else false.
244      */
245     protected function isGif(Image $image): bool
246     {
247         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
248     }
249
250     /**
251      * Check if the given image and image data is apng.
252      */
253     protected function isApngData(Image $image, string &$imageData): bool
254     {
255         $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
256         if (!$isPng) {
257             return false;
258         }
259
260         $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
261
262         return strpos($initialHeader, 'acTL') !== false;
263     }
264
265     /**
266      * Get the thumbnail for an image.
267      * If $keepRatio is true only the width will be used.
268      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
269      *
270      * @throws Exception
271      * @throws InvalidArgumentException
272      */
273     public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false, bool $forceCreate = false): string
274     {
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 && !$forceCreate) {
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 (!$forceCreate && $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 not in cache and thumbnail does not exist, generate thumb and cache path
310         $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
311         $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
312         $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
313
314         return $this->getPublicUrl($thumbFilePath);
315     }
316
317     /**
318      * Resize the image of given data to the specified size, and return the new image data.
319      *
320      * @throws ImageUploadException
321      */
322     protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
323     {
324         try {
325             $thumb = $this->imageTool->make($imageData);
326         } catch (ErrorException | NotSupportedException $e) {
327             throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
328         }
329
330         $this->orientImageToOriginalExif($thumb, $imageData);
331
332         if ($keepRatio) {
333             $thumb->resize($width, $height, function ($constraint) {
334                 $constraint->aspectRatio();
335                 $constraint->upsize();
336             });
337         } else {
338             $thumb->fit($width, $height);
339         }
340
341         $thumbData = (string) $thumb->encode();
342
343         // Use original image data if we're keeping the ratio
344         // and the resizing does not save any space.
345         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
346             return $imageData;
347         }
348
349         return $thumbData;
350     }
351
352     /**
353      * Orientate the given intervention image based upon the given original image data.
354      * Intervention does have an `orientate` method but the exif data it needs is lost before it
355      * can be used (At least when created using binary string data) so we need to do some
356      * implementation on our side to use the original image data.
357      * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
358      * Copyright (c) Oliver Vogel, MIT License.
359      */
360     protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
361     {
362         if (!extension_loaded('exif')) {
363             return;
364         }
365
366         $stream = Utils::streamFor($originalData)->detach();
367         $exif = @exif_read_data($stream);
368         $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
369
370         switch ($orientation) {
371             case 2:
372                 $image->flip();
373                 break;
374             case 3:
375                 $image->rotate(180);
376                 break;
377             case 4:
378                 $image->rotate(180)->flip();
379                 break;
380             case 5:
381                 $image->rotate(270)->flip();
382                 break;
383             case 6:
384                 $image->rotate(270);
385                 break;
386             case 7:
387                 $image->rotate(90)->flip();
388                 break;
389             case 8:
390                 $image->rotate(90);
391                 break;
392         }
393     }
394
395     /**
396      * Get the raw data content from an image.
397      *
398      * @throws FileNotFoundException
399      */
400     public function getImageData(Image $image): string
401     {
402         $storage = $this->getStorageDisk();
403
404         return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
405     }
406
407     /**
408      * Destroy an image along with its revisions, thumbnails and remaining folders.
409      *
410      * @throws Exception
411      */
412     public function destroy(Image $image)
413     {
414         $this->destroyImagesFromPath($image->path, $image->type);
415         $image->delete();
416     }
417
418     /**
419      * Destroys an image at the given path.
420      * Searches for image thumbnails in addition to main provided path.
421      */
422     protected function destroyImagesFromPath(string $path, string $imageType): bool
423     {
424         $path = $this->adjustPathForStorageDisk($path, $imageType);
425         $storage = $this->getStorageDisk($imageType);
426
427         $imageFolder = dirname($path);
428         $imageFileName = basename($path);
429         $allImages = collect($storage->allFiles($imageFolder));
430
431         // Delete image files
432         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
433             return basename($imagePath) === $imageFileName;
434         });
435         $storage->delete($imagesToDelete->all());
436
437         // Cleanup of empty folders
438         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
439         foreach ($foldersInvolved as $directory) {
440             if ($this->isFolderEmpty($storage, $directory)) {
441                 $storage->deleteDirectory($directory);
442             }
443         }
444
445         return true;
446     }
447
448     /**
449      * Check whether a folder is empty.
450      */
451     protected function isFolderEmpty(Storage $storage, string $path): bool
452     {
453         $files = $storage->files($path);
454         $folders = $storage->directories($path);
455
456         return count($files) === 0 && count($folders) === 0;
457     }
458
459     /**
460      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
461      * Checks based off of only the image name.
462      * Could be much improved to be more specific but kept it generic for now to be safe.
463      *
464      * Returns the path of the images that would be/have been deleted.
465      */
466     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
467     {
468         $types = ['gallery', 'drawio'];
469         $deletedPaths = [];
470
471         Image::query()->whereIn('type', $types)
472             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
473                 /** @var Image $image */
474                 foreach ($images as $image) {
475                     $searchQuery = '%' . basename($image->path) . '%';
476                     $inPage = DB::table('pages')
477                             ->where('html', 'like', $searchQuery)->count() > 0;
478
479                     $inRevision = false;
480                     if ($checkRevisions) {
481                         $inRevision = DB::table('page_revisions')
482                                 ->where('html', 'like', $searchQuery)->count() > 0;
483                     }
484
485                     if (!$inPage && !$inRevision) {
486                         $deletedPaths[] = $image->path;
487                         if (!$dryRun) {
488                             $this->destroy($image);
489                         }
490                     }
491                 }
492             });
493
494         return $deletedPaths;
495     }
496
497     /**
498      * Convert an image URI to a Base64 encoded string.
499      * Attempts to convert the URL to a system storage url then
500      * fetch the data from the disk or storage location.
501      * Returns null if the image data cannot be fetched from storage.
502      *
503      * @throws FileNotFoundException
504      */
505     public function imageUriToBase64(string $uri): ?string
506     {
507         $storagePath = $this->imageUrlToStoragePath($uri);
508         if (empty($uri) || is_null($storagePath)) {
509             return null;
510         }
511
512         $storagePath = $this->adjustPathForStorageDisk($storagePath);
513
514         // Apply access control when local_secure_restricted images are active
515         if ($this->usingSecureRestrictedImages()) {
516             if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
517                 return null;
518             }
519         }
520
521         $storage = $this->getStorageDisk();
522         $imageData = null;
523         if ($storage->exists($storagePath)) {
524             $imageData = $storage->get($storagePath);
525         }
526
527         if (is_null($imageData)) {
528             return null;
529         }
530
531         $extension = pathinfo($uri, PATHINFO_EXTENSION);
532         if ($extension === 'svg') {
533             $extension = 'svg+xml';
534         }
535
536         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
537     }
538
539     /**
540      * Check if the given path exists and is accessible in the local secure image system.
541      * Returns false if local_secure is not in use, if the file does not exist, if the
542      * file is likely not a valid image, or if permission does not allow access.
543      */
544     public function pathAccessibleInLocalSecure(string $imagePath): bool
545     {
546         /** @var FilesystemAdapter $disk */
547         $disk = $this->getStorageDisk('gallery');
548
549         if ($this->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
550             return false;
551         }
552
553         // Check local_secure is active
554         return $this->usingSecureImages()
555             && $disk instanceof FilesystemAdapter
556             // Check the image file exists
557             && $disk->exists($imagePath)
558             // Check the file is likely an image file
559             && strpos($disk->mimeType($imagePath), 'image/') === 0;
560     }
561
562     /**
563      * Check that the current user has access to the relation
564      * of the image at the given path.
565      */
566     protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
567     {
568         if (strpos($path, '/uploads/images/') === 0) {
569             $path = substr($path, 15);
570         }
571
572         // Strip thumbnail element from path if existing
573         $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
574             $resizedDir = (strpos($part, 'thumbs-') === 0 || strpos($part, 'scaled-') === 0);
575             $missingExtension = strpos($part, '.') === false;
576
577             return !($resizedDir && $missingExtension);
578         });
579
580         // Build a database-format image path and search for the image entry
581         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
582         $image = Image::query()->where('path', '=', $fullPath)->first();
583
584         if (is_null($image)) {
585             return false;
586         }
587
588         $imageType = $image->type;
589
590         // Allow user or system (logo) images
591         // (No specific relation control but may still have access controlled by auth)
592         if ($imageType === 'user' || $imageType === 'system') {
593             return true;
594         }
595
596         if ($imageType === 'gallery' || $imageType === 'drawio') {
597             return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
598         }
599
600         if ($imageType === 'cover_book') {
601             return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
602         }
603
604         if ($imageType === 'cover_bookshelf') {
605             return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
606         }
607
608         return false;
609     }
610
611     /**
612      * For the given path, if existing, provide a response that will stream the image contents.
613      */
614     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
615     {
616         $disk = $this->getStorageDisk($imageType);
617
618         return $disk->response($path);
619     }
620
621     /**
622      * Check if the given image extension is supported by BookStack.
623      * The extension must not be altered in this function. This check should provide a guarantee
624      * that the provided extension is safe to use for the image to be saved.
625      */
626     public static function isExtensionSupported(string $extension): bool
627     {
628         return in_array($extension, static::$supportedExtensions);
629     }
630
631     /**
632      * Get a storage path for the given image URL.
633      * Ensures the path will start with "uploads/images".
634      * Returns null if the url cannot be resolved to a local URL.
635      */
636     private function imageUrlToStoragePath(string $url): ?string
637     {
638         $url = ltrim(trim($url), '/');
639
640         // Handle potential relative paths
641         $isRelative = strpos($url, 'http') !== 0;
642         if ($isRelative) {
643             if (strpos(strtolower($url), 'uploads/images') === 0) {
644                 return trim($url, '/');
645             }
646
647             return null;
648         }
649
650         // Handle local images based on paths on the same domain
651         $potentialHostPaths = [
652             url('uploads/images/'),
653             $this->getPublicUrl('/uploads/images/'),
654         ];
655
656         foreach ($potentialHostPaths as $potentialBasePath) {
657             $potentialBasePath = strtolower($potentialBasePath);
658             if (strpos(strtolower($url), $potentialBasePath) === 0) {
659                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
660             }
661         }
662
663         return null;
664     }
665
666     /**
667      * Gets a public facing url for an image by checking relevant environment variables.
668      * If s3-style store is in use it will default to guessing a public bucket URL.
669      */
670     private function getPublicUrl(string $filePath): string
671     {
672         $storageUrl = config('filesystems.url');
673
674         // Get the standard public s3 url if s3 is set as storage type
675         // Uses the nice, short URL if bucket name has no periods in otherwise the longer
676         // region-based url will be used to prevent http issues.
677         if (!$storageUrl && config('filesystems.images') === 's3') {
678             $storageDetails = config('filesystems.disks.s3');
679             if (strpos($storageDetails['bucket'], '.') === false) {
680                 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
681             } else {
682                 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
683             }
684         }
685
686         $basePath = $storageUrl ?: url('/');
687
688         return rtrim($basePath, '/') . $filePath;
689     }
690 }