]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Done a round of phpstan fixes
[bookstack] / app / Uploads / ImageService.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Exceptions\ImageUploadException;
6 use ErrorException;
7 use Exception;
8 use Illuminate\Contracts\Cache\Repository as Cache;
9 use Illuminate\Contracts\Filesystem\FileNotFoundException;
10 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
11 use Illuminate\Filesystem\FilesystemAdapter;
12 use Illuminate\Filesystem\FilesystemManager;
13 use Illuminate\Support\Facades\DB;
14 use Illuminate\Support\Facades\Log;
15 use Illuminate\Support\Str;
16 use Intervention\Image\Exception\NotSupportedException;
17 use Intervention\Image\ImageManager;
18 use League\Flysystem\Util;
19 use Psr\SimpleCache\InvalidArgumentException;
20 use Symfony\Component\HttpFoundation\File\UploadedFile;
21 use Symfony\Component\HttpFoundation\StreamedResponse;
22
23 class ImageService
24 {
25     protected $imageTool;
26     protected $cache;
27     protected $storageUrl;
28     protected $image;
29     protected $fileSystem;
30
31     protected static $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
32
33     /**
34      * ImageService constructor.
35      */
36     public function __construct(Image $image, ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
37     {
38         $this->image = $image;
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(): bool
57     {
58         return $this->getStorageDiskName('gallery') === 'local_secure_images';
59     }
60
61     /**
62      * Change the originally provided path to fit any disk-specific requirements.
63      * This also ensures the path is kept to the expected root folders.
64      */
65     protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
66     {
67         $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
68
69         if ($this->getStorageDiskName($imageType) === 'local_secure_images') {
70             return $path;
71         }
72
73         return 'uploads/images/' . $path;
74     }
75
76     /**
77      * Get the name of the storage disk to use.
78      */
79     protected function getStorageDiskName(string $imageType): string
80     {
81         $storageType = config('filesystems.images');
82
83         // Ensure system images (App logo) are uploaded to a public space
84         if ($imageType === 'system' && $storageType === 'local_secure') {
85             $storageType = 'local';
86         }
87
88         if ($storageType === 'local_secure') {
89             $storageType = 'local_secure_images';
90         }
91
92         return $storageType;
93     }
94
95     /**
96      * Saves a new image from an upload.
97      *
98      * @throws ImageUploadException
99      *
100      * @return mixed
101      */
102     public function saveNewFromUpload(
103         UploadedFile $uploadedFile,
104         string $type,
105         int $uploadedTo = 0,
106         int $resizeWidth = null,
107         int $resizeHeight = null,
108         bool $keepRatio = true
109     ) {
110         $imageName = $uploadedFile->getClientOriginalName();
111         $imageData = file_get_contents($uploadedFile->getRealPath());
112
113         if ($resizeWidth !== null || $resizeHeight !== null) {
114             $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
115         }
116
117         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
118     }
119
120     /**
121      * Save a new image from a uri-encoded base64 string of data.
122      *
123      * @throws ImageUploadException
124      */
125     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
126     {
127         $splitData = explode(';base64,', $base64Uri);
128         if (count($splitData) < 2) {
129             throw new ImageUploadException('Invalid base64 image data provided');
130         }
131         $data = base64_decode($splitData[1]);
132
133         return $this->saveNew($name, $data, $type, $uploadedTo);
134     }
135
136     /**
137      * Save a new image into storage.
138      *
139      * @throws ImageUploadException
140      */
141     public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
142     {
143         $storage = $this->getStorageDisk($type);
144         $secureUploads = setting('app-secure-images');
145         $fileName = $this->cleanImageFileName($imageName);
146
147         $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
148
149         while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
150             $fileName = Str::random(3) . $fileName;
151         }
152
153         $fullPath = $imagePath . $fileName;
154         if ($secureUploads) {
155             $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
156         }
157
158         try {
159             $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
160         } catch (Exception $e) {
161             Log::error('Error when attempting image upload:' . $e->getMessage());
162
163             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
164         }
165
166         $imageDetails = [
167             'name'        => $imageName,
168             'path'        => $fullPath,
169             'url'         => $this->getPublicUrl($fullPath),
170             'type'        => $type,
171             'uploaded_to' => $uploadedTo,
172         ];
173
174         if (user()->id !== 0) {
175             $userId = user()->id;
176             $imageDetails['created_by'] = $userId;
177             $imageDetails['updated_by'] = $userId;
178         }
179
180         $image = $this->image->newInstance();
181         $image->forceFill($imageDetails)->save();
182
183         return $image;
184     }
185
186     /**
187      * Save image data for the given path in the public space, if possible,
188      * for the provided storage mechanism.
189      */
190     protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
191     {
192         $storage->put($path, $data);
193
194         // Set visibility when a non-AWS-s3, s3-like storage option is in use.
195         // Done since this call can break s3-like services but desired for other image stores.
196         // Attempting to set ACL during above put request requires different permissions
197         // hence would technically be a breaking change for actual s3 usage.
198         $usingS3 = strtolower(config('filesystems.images')) === 's3';
199         $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
200         if (!$usingS3Like) {
201             $storage->setVisibility($path, 'public');
202         }
203     }
204
205     /**
206      * Clean up an image file name to be both URL and storage safe.
207      */
208     protected function cleanImageFileName(string $name): string
209     {
210         $name = str_replace(' ', '-', $name);
211         $nameParts = explode('.', $name);
212         $extension = array_pop($nameParts);
213         $name = implode('-', $nameParts);
214         $name = Str::slug($name);
215
216         if (strlen($name) === 0) {
217             $name = Str::random(10);
218         }
219
220         return $name . '.' . $extension;
221     }
222
223     /**
224      * Checks if the image is a gif. Returns true if it is, else false.
225      */
226     protected function isGif(Image $image): bool
227     {
228         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
229     }
230
231     /**
232      * Get the thumbnail for an image.
233      * If $keepRatio is true only the width will be used.
234      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
235      *
236      * @throws Exception
237      * @throws InvalidArgumentException
238      */
239     public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false): string
240     {
241         if ($keepRatio && $this->isGif($image)) {
242             return $this->getPublicUrl($image->path);
243         }
244
245         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
246         $imagePath = $image->path;
247         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
248
249         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
250             return $this->getPublicUrl($thumbFilePath);
251         }
252
253         $storage = $this->getStorageDisk($image->type);
254         if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
255             return $this->getPublicUrl($thumbFilePath);
256         }
257
258         $thumbData = $this->resizeImage($storage->get($this->adjustPathForStorageDisk($imagePath, $image->type)), $width, $height, $keepRatio);
259
260         $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
261         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
262
263         return $this->getPublicUrl($thumbFilePath);
264     }
265
266     /**
267      * Resize the image of given data to the specified size, and return the new image data.
268      *
269      * @throws ImageUploadException
270      */
271     protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
272     {
273         try {
274             $thumb = $this->imageTool->make($imageData);
275         } catch (ErrorException|NotSupportedException $e) {
276             throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
277         }
278
279         if ($keepRatio) {
280             $thumb->resize($width, $height, function ($constraint) {
281                 $constraint->aspectRatio();
282                 $constraint->upsize();
283             });
284         } else {
285             $thumb->fit($width, $height);
286         }
287
288         $thumbData = (string) $thumb->encode();
289
290         // Use original image data if we're keeping the ratio
291         // and the resizing does not save any space.
292         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
293             return $imageData;
294         }
295
296         return $thumbData;
297     }
298
299     /**
300      * Get the raw data content from an image.
301      *
302      * @throws FileNotFoundException
303      */
304     public function getImageData(Image $image): string
305     {
306         $storage = $this->getStorageDisk();
307
308         return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
309     }
310
311     /**
312      * Destroy an image along with its revisions, thumbnails and remaining folders.
313      *
314      * @throws Exception
315      */
316     public function destroy(Image $image)
317     {
318         $this->destroyImagesFromPath($image->path, $image->type);
319         $image->delete();
320     }
321
322     /**
323      * Destroys an image at the given path.
324      * Searches for image thumbnails in addition to main provided path.
325      */
326     protected function destroyImagesFromPath(string $path, string $imageType): bool
327     {
328         $path = $this->adjustPathForStorageDisk($path, $imageType);
329         $storage = $this->getStorageDisk($imageType);
330
331         $imageFolder = dirname($path);
332         $imageFileName = basename($path);
333         $allImages = collect($storage->allFiles($imageFolder));
334
335         // Delete image files
336         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
337             return basename($imagePath) === $imageFileName;
338         });
339         $storage->delete($imagesToDelete->all());
340
341         // Cleanup of empty folders
342         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
343         foreach ($foldersInvolved as $directory) {
344             if ($this->isFolderEmpty($storage, $directory)) {
345                 $storage->deleteDirectory($directory);
346             }
347         }
348
349         return true;
350     }
351
352     /**
353      * Check whether a folder is empty.
354      */
355     protected function isFolderEmpty(Storage $storage, string $path): bool
356     {
357         $files = $storage->files($path);
358         $folders = $storage->directories($path);
359
360         return count($files) === 0 && count($folders) === 0;
361     }
362
363     /**
364      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
365      * Checks based off of only the image name.
366      * Could be much improved to be more specific but kept it generic for now to be safe.
367      *
368      * Returns the path of the images that would be/have been deleted.
369      */
370     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
371     {
372         $types = ['gallery', 'drawio'];
373         $deletedPaths = [];
374
375         $this->image->newQuery()->whereIn('type', $types)
376             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
377                 foreach ($images as $image) {
378                     $searchQuery = '%' . basename($image->path) . '%';
379                     $inPage = DB::table('pages')
380                             ->where('html', 'like', $searchQuery)->count() > 0;
381
382                     $inRevision = false;
383                     if ($checkRevisions) {
384                         $inRevision = DB::table('page_revisions')
385                                 ->where('html', 'like', $searchQuery)->count() > 0;
386                     }
387
388                     if (!$inPage && !$inRevision) {
389                         $deletedPaths[] = $image->path;
390                         if (!$dryRun) {
391                             $this->destroy($image);
392                         }
393                     }
394                 }
395             });
396
397         return $deletedPaths;
398     }
399
400     /**
401      * Convert an image URI to a Base64 encoded string.
402      * Attempts to convert the URL to a system storage url then
403      * fetch the data from the disk or storage location.
404      * Returns null if the image data cannot be fetched from storage.
405      *
406      * @throws FileNotFoundException
407      */
408     public function imageUriToBase64(string $uri): ?string
409     {
410         $storagePath = $this->imageUrlToStoragePath($uri);
411         if (empty($uri) || is_null($storagePath)) {
412             return null;
413         }
414
415         $storagePath = $this->adjustPathForStorageDisk($storagePath);
416         $storage = $this->getStorageDisk();
417         $imageData = null;
418         if ($storage->exists($storagePath)) {
419             $imageData = $storage->get($storagePath);
420         }
421
422         if (is_null($imageData)) {
423             return null;
424         }
425
426         $extension = pathinfo($uri, PATHINFO_EXTENSION);
427         if ($extension === 'svg') {
428             $extension = 'svg+xml';
429         }
430
431         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
432     }
433
434     /**
435      * Check if the given path exists in the local secure image system.
436      * Returns false if local_secure is not in use.
437      */
438     public function pathExistsInLocalSecure(string $imagePath): bool
439     {
440         /** @var FilesystemAdapter $disk */
441         $disk = $this->getStorageDisk('gallery');
442
443         // Check local_secure is active
444         return $this->usingSecureImages()
445             && $disk instanceof FilesystemAdapter
446             // Check the image file exists
447             && $disk->exists($imagePath)
448             // Check the file is likely an image file
449             && strpos($disk->getMimetype($imagePath), 'image/') === 0;
450     }
451
452     /**
453      * For the given path, if existing, provide a response that will stream the image contents.
454      */
455     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
456     {
457         $disk = $this->getStorageDisk($imageType);
458
459         return $disk->response($path);
460     }
461
462     /**
463      * Check if the given image extension is supported by BookStack.
464      * The extension must not be altered in this function. This check should provide a guarantee
465      * that the provided extension is safe to use for the image to be saved.
466      */
467     public static function isExtensionSupported(string $extension): bool
468     {
469         return in_array($extension, static::$supportedExtensions);
470     }
471
472     /**
473      * Get a storage path for the given image URL.
474      * Ensures the path will start with "uploads/images".
475      * Returns null if the url cannot be resolved to a local URL.
476      */
477     private function imageUrlToStoragePath(string $url): ?string
478     {
479         $url = ltrim(trim($url), '/');
480
481         // Handle potential relative paths
482         $isRelative = strpos($url, 'http') !== 0;
483         if ($isRelative) {
484             if (strpos(strtolower($url), 'uploads/images') === 0) {
485                 return trim($url, '/');
486             }
487
488             return null;
489         }
490
491         // Handle local images based on paths on the same domain
492         $potentialHostPaths = [
493             url('uploads/images/'),
494             $this->getPublicUrl('/uploads/images/'),
495         ];
496
497         foreach ($potentialHostPaths as $potentialBasePath) {
498             $potentialBasePath = strtolower($potentialBasePath);
499             if (strpos(strtolower($url), $potentialBasePath) === 0) {
500                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
501             }
502         }
503
504         return null;
505     }
506
507     /**
508      * Gets a public facing url for an image by checking relevant environment variables.
509      * If s3-style store is in use it will default to guessing a public bucket URL.
510      */
511     private function getPublicUrl(string $filePath): string
512     {
513         if (is_null($this->storageUrl)) {
514             $storageUrl = config('filesystems.url');
515
516             // Get the standard public s3 url if s3 is set as storage type
517             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
518             // region-based url will be used to prevent http issues.
519             if ($storageUrl == false && config('filesystems.images') === 's3') {
520                 $storageDetails = config('filesystems.disks.s3');
521                 if (strpos($storageDetails['bucket'], '.') === false) {
522                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
523                 } else {
524                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
525                 }
526             }
527
528             $this->storageUrl = $storageUrl;
529         }
530
531         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
532
533         return rtrim($basePath, '/') . $filePath;
534     }
535 }