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