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