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