]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Added tests and translations for dark-mode components
[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      * Saves a new image
128      * @param string $imageName
129      * @param string $imageData
130      * @param string $type
131      * @param int $uploadedTo
132      * @return Image
133      * @throws ImageUploadException
134      */
135     private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
136     {
137         $storage = $this->getStorage($type);
138         $secureUploads = setting('app-secure-images');
139         $imageName = str_replace(' ', '-', $imageName);
140
141         $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
142
143         while ($storage->exists($imagePath . $imageName)) {
144             $imageName = Str::random(3) . $imageName;
145         }
146
147         $fullPath = $imagePath . $imageName;
148         if ($secureUploads) {
149             $fullPath = $imagePath . Str::random(16) . '-' . $imageName;
150         }
151
152         try {
153             $storage->put($fullPath, $imageData);
154             $storage->setVisibility($fullPath, 'public');
155         } catch (Exception $e) {
156             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
157         }
158
159         $imageDetails = [
160             'name'       => $imageName,
161             'path'       => $fullPath,
162             'url'        => $this->getPublicUrl($fullPath),
163             'type'       => $type,
164             'uploaded_to' => $uploadedTo
165         ];
166
167         if (user()->id !== 0) {
168             $userId = user()->id;
169             $imageDetails['created_by'] = $userId;
170             $imageDetails['updated_by'] = $userId;
171         }
172
173         $image = $this->image->newInstance();
174         $image->forceFill($imageDetails)->save();
175         return $image;
176     }
177
178
179     /**
180      * Checks if the image is a gif. Returns true if it is, else false.
181      * @param Image $image
182      * @return boolean
183      */
184     protected function isGif(Image $image)
185     {
186         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
187     }
188
189     /**
190      * Get the thumbnail for an image.
191      * If $keepRatio is true only the width will be used.
192      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
193      * @param Image $image
194      * @param int $width
195      * @param int $height
196      * @param bool $keepRatio
197      * @return string
198      * @throws Exception
199      * @throws ImageUploadException
200      */
201     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
202     {
203         if ($keepRatio && $this->isGif($image)) {
204             return $this->getPublicUrl($image->path);
205         }
206
207         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
208         $imagePath = $image->path;
209         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
210
211         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
212             return $this->getPublicUrl($thumbFilePath);
213         }
214
215         $storage = $this->getStorage($image->type);
216         if ($storage->exists($thumbFilePath)) {
217             return $this->getPublicUrl($thumbFilePath);
218         }
219
220         $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
221
222         $storage->put($thumbFilePath, $thumbData);
223         $storage->setVisibility($thumbFilePath, 'public');
224         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
225
226         return $this->getPublicUrl($thumbFilePath);
227     }
228
229     /**
230      * Resize image data.
231      * @param string $imageData
232      * @param int $width
233      * @param int $height
234      * @param bool $keepRatio
235      * @return string
236      * @throws ImageUploadException
237      */
238     protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
239     {
240         try {
241             $thumb = $this->imageTool->make($imageData);
242         } catch (Exception $e) {
243             if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
244                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
245             }
246             throw $e;
247         }
248
249         if ($keepRatio) {
250             $thumb->resize($width, $height, function ($constraint) {
251                 $constraint->aspectRatio();
252                 $constraint->upsize();
253             });
254         } else {
255             $thumb->fit($width, $height);
256         }
257
258         $thumbData = (string)$thumb->encode();
259
260         // Use original image data if we're keeping the ratio
261         // and the resizing does not save any space.
262         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
263             return $imageData;
264         }
265
266         return $thumbData;
267     }
268
269     /**
270      * Get the raw data content from an image.
271      * @param Image $image
272      * @return string
273      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
274      */
275     public function getImageData(Image $image)
276     {
277         $imagePath = $image->path;
278         $storage = $this->getStorage();
279         return $storage->get($imagePath);
280     }
281
282     /**
283      * Destroy an image along with its revisions, thumbnails and remaining folders.
284      * @param Image $image
285      * @throws Exception
286      */
287     public function destroy(Image $image)
288     {
289         $this->destroyImagesFromPath($image->path);
290         $image->delete();
291     }
292
293     /**
294      * Destroys an image at the given path.
295      * Searches for image thumbnails in addition to main provided path..
296      * @param string $path
297      * @return bool
298      */
299     protected function destroyImagesFromPath(string $path)
300     {
301         $storage = $this->getStorage();
302
303         $imageFolder = dirname($path);
304         $imageFileName = basename($path);
305         $allImages = collect($storage->allFiles($imageFolder));
306
307         // Delete image files
308         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
309             $expectedIndex = strlen($imagePath) - strlen($imageFileName);
310             return strpos($imagePath, $imageFileName) === $expectedIndex;
311         });
312         $storage->delete($imagesToDelete->all());
313
314         // Cleanup of empty folders
315         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
316         foreach ($foldersInvolved as $directory) {
317             if ($this->isFolderEmpty($directory)) {
318                 $storage->deleteDirectory($directory);
319             }
320         }
321
322         return true;
323     }
324
325     /**
326      * Save an avatar image from an external service.
327      * @param \BookStack\Auth\User $user
328      * @param int $size
329      * @return Image
330      * @throws Exception
331      */
332     public function saveUserAvatar(User $user, $size = 500)
333     {
334         $avatarUrl = $this->getAvatarUrl();
335         $email = strtolower(trim($user->email));
336
337         $replacements = [
338             '${hash}' => md5($email),
339             '${size}' => $size,
340             '${email}' => urlencode($email),
341         ];
342
343         $userAvatarUrl = strtr($avatarUrl, $replacements);
344         $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
345         $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
346         $image->created_by = $user->id;
347         $image->updated_by = $user->id;
348         $image->uploaded_to = $user->id;
349         $image->save();
350
351         return $image;
352     }
353
354     /**
355      * Check if fetching external avatars is enabled.
356      * @return bool
357      */
358     public function avatarFetchEnabled()
359     {
360         $fetchUrl = $this->getAvatarUrl();
361         return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
362     }
363
364     /**
365      * Get the URL to fetch avatars from.
366      * @return string|mixed
367      */
368     protected function getAvatarUrl()
369     {
370         $url = trim(config('services.avatar_url'));
371
372         if (empty($url) && !config('services.disable_services')) {
373             $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
374         }
375
376         return $url;
377     }
378
379     /**
380      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
381      * Checks based off of only the image name.
382      * Could be much improved to be more specific but kept it generic for now to be safe.
383      *
384      * Returns the path of the images that would be/have been deleted.
385      * @param bool $checkRevisions
386      * @param bool $dryRun
387      * @param array $types
388      * @return array
389      */
390     public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
391     {
392         $types = array_intersect($types, ['gallery', 'drawio']);
393         $deletedPaths = [];
394
395         $this->image->newQuery()->whereIn('type', $types)
396             ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
397                 foreach ($images as $image) {
398                     $searchQuery = '%' . basename($image->path) . '%';
399                     $inPage = DB::table('pages')
400                          ->where('html', 'like', $searchQuery)->count() > 0;
401                     $inRevision = false;
402                     if ($checkRevisions) {
403                         $inRevision =  DB::table('page_revisions')
404                              ->where('html', 'like', $searchQuery)->count() > 0;
405                     }
406
407                     if (!$inPage && !$inRevision) {
408                         $deletedPaths[] = $image->path;
409                         if (!$dryRun) {
410                             $this->destroy($image);
411                         }
412                     }
413                 }
414             });
415         return $deletedPaths;
416     }
417
418     /**
419      * Convert a image URI to a Base64 encoded string.
420      * Attempts to find locally via set storage method first.
421      * @param string $uri
422      * @return null|string
423      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
424      */
425     public function imageUriToBase64(string $uri)
426     {
427         $isLocal = strpos(trim($uri), 'http') !== 0;
428
429         // Attempt to find local files even if url not absolute
430         $base = url('/');
431         if (!$isLocal && strpos($uri, $base) === 0) {
432             $isLocal = true;
433             $uri = str_replace($base, '', $uri);
434         }
435
436         $imageData = null;
437
438         if ($isLocal) {
439             $uri = trim($uri, '/');
440             $storage = $this->getStorage();
441             if ($storage->exists($uri)) {
442                 $imageData = $storage->get($uri);
443             }
444         } else {
445             try {
446                 $imageData = $this->http->fetch($uri);
447             } catch (\Exception $e) {
448             }
449         }
450
451         if ($imageData === null) {
452             return null;
453         }
454
455         $extension = pathinfo($uri, PATHINFO_EXTENSION);
456         if ($extension === 'svg') {
457             $extension = 'svg+xml';
458         }
459
460         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
461     }
462
463     /**
464      * Gets a public facing url for an image by checking relevant environment variables.
465      * @param string $filePath
466      * @return string
467      */
468     private function getPublicUrl($filePath)
469     {
470         if ($this->storageUrl === null) {
471             $storageUrl = config('filesystems.url');
472
473             // Get the standard public s3 url if s3 is set as storage type
474             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
475             // region-based url will be used to prevent http issues.
476             if ($storageUrl == false && config('filesystems.images') === 's3') {
477                 $storageDetails = config('filesystems.disks.s3');
478                 if (strpos($storageDetails['bucket'], '.') === false) {
479                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
480                 } else {
481                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
482                 }
483             }
484             $this->storageUrl = $storageUrl;
485         }
486
487         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
488         return rtrim($basePath, '/') . $filePath;
489     }
490 }