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