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