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