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