]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Updated existing image tests to reflect changes
[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.default');
49
50         // Override default location if set to local public to ensure not visible.
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     {
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 * 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         return (string)$thumb->encode();
258     }
259
260     /**
261      * Get the raw data content from an image.
262      * @param Image $image
263      * @return string
264      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
265      */
266     public function getImageData(Image $image)
267     {
268         $imagePath = $image->path;
269         $storage = $this->getStorage();
270         return $storage->get($imagePath);
271     }
272
273     /**
274      * Destroy an image along with its revisions, thumbnails and remaining folders.
275      * @param Image $image
276      * @throws Exception
277      */
278     public function destroy(Image $image)
279     {
280         $this->destroyImagesFromPath($image->path);
281         $image->delete();
282     }
283
284     /**
285      * Destroys an image at the given path.
286      * Searches for image thumbnails in addition to main provided path..
287      * @param string $path
288      * @return bool
289      */
290     protected function destroyImagesFromPath(string $path)
291     {
292         $storage = $this->getStorage();
293
294         $imageFolder = dirname($path);
295         $imageFileName = basename($path);
296         $allImages = collect($storage->allFiles($imageFolder));
297
298         // Delete image files
299         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
300             $expectedIndex = strlen($imagePath) - strlen($imageFileName);
301             return strpos($imagePath, $imageFileName) === $expectedIndex;
302         });
303         $storage->delete($imagesToDelete->all());
304
305         // Cleanup of empty folders
306         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
307         foreach ($foldersInvolved as $directory) {
308             if ($this->isFolderEmpty($directory)) {
309                 $storage->deleteDirectory($directory);
310             }
311         }
312
313         return true;
314     }
315
316     /**
317      * Save an avatar image from an external service.
318      * @param \BookStack\Auth\User $user
319      * @param int $size
320      * @return Image
321      * @throws Exception
322      */
323     public function saveUserAvatar(User $user, $size = 500)
324     {
325         $avatarUrl = $this->getAvatarUrl();
326         $email = strtolower(trim($user->email));
327
328         $replacements = [
329             '${hash}' => md5($email),
330             '${size}' => $size,
331             '${email}' => urlencode($email),
332         ];
333
334         $userAvatarUrl = strtr($avatarUrl, $replacements);
335         $imageName = str_replace(' ', '-', $user->name . '-avatar.png');
336         $image = $this->saveNewFromUrl($userAvatarUrl, 'user', $imageName);
337         $image->created_by = $user->id;
338         $image->updated_by = $user->id;
339         $image->uploaded_to = $user->id;
340         $image->save();
341
342         return $image;
343     }
344
345     /**
346      * Check if fetching external avatars is enabled.
347      * @return bool
348      */
349     public function avatarFetchEnabled()
350     {
351         $fetchUrl = $this->getAvatarUrl();
352         return is_string($fetchUrl) && strpos($fetchUrl, 'http') === 0;
353     }
354
355     /**
356      * Get the URL to fetch avatars from.
357      * @return string|mixed
358      */
359     protected function getAvatarUrl()
360     {
361         $url = trim(config('services.avatar_url'));
362
363         if (empty($url) && !config('services.disable_services')) {
364             $url = 'https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon';
365         }
366
367         return $url;
368     }
369
370     /**
371      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
372      * Checks based off of only the image name.
373      * Could be much improved to be more specific but kept it generic for now to be safe.
374      *
375      * Returns the path of the images that would be/have been deleted.
376      * @param bool $checkRevisions
377      * @param bool $dryRun
378      * @param array $types
379      * @return array
380      */
381     public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
382     {
383         $types = array_intersect($types, ['gallery', 'drawio']);
384         $deletedPaths = [];
385
386         $this->image->newQuery()->whereIn('type', $types)
387             ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
388                 foreach ($images as $image) {
389                     $searchQuery = '%' . basename($image->path) . '%';
390                     $inPage = DB::table('pages')
391                          ->where('html', 'like', $searchQuery)->count() > 0;
392                     $inRevision = false;
393                     if ($checkRevisions) {
394                         $inRevision =  DB::table('page_revisions')
395                              ->where('html', 'like', $searchQuery)->count() > 0;
396                     }
397
398                     if (!$inPage && !$inRevision) {
399                         $deletedPaths[] = $image->path;
400                         if (!$dryRun) {
401                             $this->destroy($image);
402                         }
403                     }
404                 }
405             });
406         return $deletedPaths;
407     }
408
409     /**
410      * Convert a image URI to a Base64 encoded string.
411      * Attempts to find locally via set storage method first.
412      * @param string $uri
413      * @return null|string
414      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
415      */
416     public function imageUriToBase64(string $uri)
417     {
418         $isLocal = strpos(trim($uri), 'http') !== 0;
419
420         // Attempt to find local files even if url not absolute
421         $base = baseUrl('/');
422         if (!$isLocal && strpos($uri, $base) === 0) {
423             $isLocal = true;
424             $uri = str_replace($base, '', $uri);
425         }
426
427         $imageData = null;
428
429         if ($isLocal) {
430             $uri = trim($uri, '/');
431             $storage = $this->getStorage();
432             if ($storage->exists($uri)) {
433                 $imageData = $storage->get($uri);
434             }
435         } else {
436             try {
437                 $imageData = $this->http->fetch($uri);
438             } catch (\Exception $e) {
439             }
440         }
441
442         if ($imageData === null) {
443             return null;
444         }
445
446         return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
447     }
448
449     /**
450      * Gets a public facing url for an image by checking relevant environment variables.
451      * @param string $filePath
452      * @return string
453      */
454     private function getPublicUrl($filePath)
455     {
456         if ($this->storageUrl === null) {
457             $storageUrl = config('filesystems.url');
458
459             // Get the standard public s3 url if s3 is set as storage type
460             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
461             // region-based url will be used to prevent http issues.
462             if ($storageUrl == false && config('filesystems.default') === 's3') {
463                 $storageDetails = config('filesystems.disks.s3');
464                 if (strpos($storageDetails['bucket'], '.') === false) {
465                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
466                 } else {
467                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
468                 }
469             }
470             $this->storageUrl = $storageUrl;
471         }
472
473         $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
474         return rtrim($basePath, '/') . $filePath;
475     }
476 }