]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
293049f4f8c35e0b55edd76c772d425386079703
[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 when a non-AWS-s3, s3-like storage option is in use.
144         // Done since this call can break s3-like services but desired for other image stores.
145         // Attempting to set ACL during above put request requires different permissions
146         // hence would technically be a breaking change for actual s3 usage.
147         $usingS3 = strtolower(config('filesystems.images')) === 's3';
148         $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
149         if (!$usingS3Like) {
150             $storage->setVisibility($path, 'public');
151         }
152     }
153
154     /**
155      * Clean up an image file name to be both URL and storage safe.
156      */
157     protected function cleanImageFileName(string $name): string
158     {
159         $name = str_replace(' ', '-', $name);
160         $nameParts = explode('.', $name);
161         $extension = array_pop($nameParts);
162         $name = implode('-', $nameParts);
163         $name = Str::slug($name);
164
165         if (strlen($name) === 0) {
166             $name = Str::random(10);
167         }
168
169         return $name . '.' . $extension;
170     }
171
172     /**
173      * Checks if the image is a gif. Returns true if it is, else false.
174      */
175     protected function isGif(Image $image): bool
176     {
177         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
178     }
179
180     /**
181      * Get the thumbnail for an image.
182      * If $keepRatio is true only the width will be used.
183      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
184      * @param Image $image
185      * @param int $width
186      * @param int $height
187      * @param bool $keepRatio
188      * @return string
189      * @throws Exception
190      * @throws ImageUploadException
191      */
192     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
193     {
194         if ($keepRatio && $this->isGif($image)) {
195             return $this->getPublicUrl($image->path);
196         }
197
198         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
199         $imagePath = $image->path;
200         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
201
202         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
203             return $this->getPublicUrl($thumbFilePath);
204         }
205
206         $storage = $this->getStorage($image->type);
207         if ($storage->exists($thumbFilePath)) {
208             return $this->getPublicUrl($thumbFilePath);
209         }
210
211         $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
212
213         $this->saveImageDataInPublicSpace($storage, $thumbFilePath, $thumbData);
214         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
215
216
217         return $this->getPublicUrl($thumbFilePath);
218     }
219
220     /**
221      * Resize image data.
222      * @param string $imageData
223      * @param int $width
224      * @param int $height
225      * @param bool $keepRatio
226      * @return string
227      * @throws ImageUploadException
228      */
229     protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
230     {
231         try {
232             $thumb = $this->imageTool->make($imageData);
233         } catch (Exception $e) {
234             if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
235                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
236             }
237             throw $e;
238         }
239
240         if ($keepRatio) {
241             $thumb->resize($width, $height, function ($constraint) {
242                 $constraint->aspectRatio();
243                 $constraint->upsize();
244             });
245         } else {
246             $thumb->fit($width, $height);
247         }
248
249         $thumbData = (string)$thumb->encode();
250
251         // Use original image data if we're keeping the ratio
252         // and the resizing does not save any space.
253         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
254             return $imageData;
255         }
256
257         return $thumbData;
258     }
259
260     /**
261      * Get the raw data content from an image.
262      * @throws FileNotFoundException
263      */
264     public function getImageData(Image $image): string
265     {
266         $imagePath = $image->path;
267         $storage = $this->getStorage();
268         return $storage->get($imagePath);
269     }
270
271     /**
272      * Destroy an image along with its revisions, thumbnails and remaining folders.
273      * @throws Exception
274      */
275     public function destroy(Image $image)
276     {
277         $this->destroyImagesFromPath($image->path);
278         $image->delete();
279     }
280
281     /**
282      * Destroys an image at the given path.
283      * Searches for image thumbnails in addition to main provided path.
284      */
285     protected function destroyImagesFromPath(string $path): bool
286     {
287         $storage = $this->getStorage();
288
289         $imageFolder = dirname($path);
290         $imageFileName = basename($path);
291         $allImages = collect($storage->allFiles($imageFolder));
292
293         // Delete image files
294         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
295             return basename($imagePath) === $imageFileName;
296         });
297         $storage->delete($imagesToDelete->all());
298
299         // Cleanup of empty folders
300         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
301         foreach ($foldersInvolved as $directory) {
302             if ($this->isFolderEmpty($storage, $directory)) {
303                 $storage->deleteDirectory($directory);
304             }
305         }
306
307         return true;
308     }
309
310     /**
311      * Check whether or not a folder is empty.
312      */
313     protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
314     {
315         $files = $storage->files($path);
316         $folders = $storage->directories($path);
317         return (count($files) === 0 && count($folders) === 0);
318     }
319
320     /**
321      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
322      * Checks based off of only the image name.
323      * Could be much improved to be more specific but kept it generic for now to be safe.
324      *
325      * Returns the path of the images that would be/have been deleted.
326      */
327     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
328     {
329         $types = ['gallery', 'drawio'];
330         $deletedPaths = [];
331
332         $this->image->newQuery()->whereIn('type', $types)
333             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
334                 foreach ($images as $image) {
335                     $searchQuery = '%' . basename($image->path) . '%';
336                     $inPage = DB::table('pages')
337                             ->where('html', 'like', $searchQuery)->count() > 0;
338
339                     $inRevision = false;
340                     if ($checkRevisions) {
341                         $inRevision = DB::table('page_revisions')
342                                 ->where('html', 'like', $searchQuery)->count() > 0;
343                     }
344
345                     if (!$inPage && !$inRevision) {
346                         $deletedPaths[] = $image->path;
347                         if (!$dryRun) {
348                             $this->destroy($image);
349                         }
350                     }
351                 }
352             });
353         return $deletedPaths;
354     }
355
356     /**
357      * Convert a image URI to a Base64 encoded string.
358      * Attempts to convert the URL to a system storage url then
359      * fetch the data from the disk or storage location.
360      * Returns null if the image data cannot be fetched from storage.
361      * @throws FileNotFoundException
362      */
363     public function imageUriToBase64(string $uri): ?string
364     {
365         $storagePath = $this->imageUrlToStoragePath($uri);
366         if (empty($uri) || is_null($storagePath)) {
367             return null;
368         }
369
370         $storage = $this->getStorage();
371         $imageData = null;
372         if ($storage->exists($storagePath)) {
373             $imageData = $storage->get($storagePath);
374         }
375
376         if (is_null($imageData)) {
377             return null;
378         }
379
380         $extension = pathinfo($uri, PATHINFO_EXTENSION);
381         if ($extension === 'svg') {
382             $extension = 'svg+xml';
383         }
384
385         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
386     }
387
388     /**
389      * Get a storage path for the given image URL.
390      * Ensures the path will start with "uploads/images".
391      * Returns null if the url cannot be resolved to a local URL.
392      */
393     private function imageUrlToStoragePath(string $url): ?string
394     {
395         $url = ltrim(trim($url), '/');
396
397         // Handle potential relative paths
398         $isRelative = strpos($url, 'http') !== 0;
399         if ($isRelative) {
400             if (strpos(strtolower($url), 'uploads/images') === 0) {
401                 return trim($url, '/');
402             }
403             return null;
404         }
405
406         // Handle local images based on paths on the same domain
407         $potentialHostPaths = [
408             url('uploads/images/'),
409             $this->getPublicUrl('/uploads/images/'),
410         ];
411
412         foreach ($potentialHostPaths as $potentialBasePath) {
413             $potentialBasePath = strtolower($potentialBasePath);
414             if (strpos(strtolower($url), $potentialBasePath) === 0) {
415                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
416             }
417         }
418
419         return null;
420     }
421
422     /**
423      * Gets a public facing url for an image by checking relevant environment variables.
424      * If s3-style store is in use it will default to guessing a public bucket URL.
425      */
426     private function getPublicUrl(string $filePath): string
427     {
428         if ($this->storageUrl === null) {
429             $storageUrl = config('filesystems.url');
430
431             // Get the standard public s3 url if s3 is set as storage type
432             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
433             // region-based url will be used to prevent http issues.
434             if ($storageUrl == false && config('filesystems.images') === 's3') {
435                 $storageDetails = config('filesystems.disks.s3');
436                 if (strpos($storageDetails['bucket'], '.') === false) {
437                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
438                 } else {
439                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
440                 }
441             }
442             $this->storageUrl = $storageUrl;
443         }
444
445         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
446         return rtrim($basePath, '/') . $filePath;
447     }
448 }