]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Added config to change Gravatar URL
[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 a gravatar image and set a the profile image for a user.
283      * @param \BookStack\Auth\User $user
284      * @param null|string $gravatarUrl
285      * @param int $size
286      * @return mixed
287      * @throws Exception
288      */
289     public function saveUserGravatar(User $user, $gravatarUrl, $size = 500)
290     {
291         if (!is_string($gravatarUrl) || empty($gravatarUrl)) {
292             $gravatarUrl = 'https://www.gravatar.com/avatar/%{hash}?s=%{size}&d=identicon';
293         }
294         $email = strtolower(trim($user->email));
295         $gravatarUrl = str_replace('%{hash}', md5($email), $gravatarUrl);
296         $gravatarUrl = str_replace('%{size}', $size, $gravatarUrl);
297         $gravatarUrl = str_replace('%{email}', urlencode($email), $gravatarUrl);
298         $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
299         $image = $this->saveNewFromUrl($gravatarUrl, 'user', $imageName);
300         $image->created_by = $user->id;
301         $image->updated_by = $user->id;
302         $image->save();
303         return $image;
304     }
305
306
307     /**
308      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
309      * Checks based off of only the image name.
310      * Could be much improved to be more specific but kept it generic for now to be safe.
311      *
312      * Returns the path of the images that would be/have been deleted.
313      * @param bool $checkRevisions
314      * @param bool $dryRun
315      * @param array $types
316      * @return array
317      */
318     public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
319     {
320         $types = array_intersect($types, ['gallery', 'drawio']);
321         $deletedPaths = [];
322
323         $this->image->newQuery()->whereIn('type', $types)
324             ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
325                 foreach ($images as $image) {
326                     $searchQuery = '%' . basename($image->path) . '%';
327                     $inPage = DB::table('pages')
328                          ->where('html', 'like', $searchQuery)->count() > 0;
329                     $inRevision = false;
330                     if ($checkRevisions) {
331                         $inRevision =  DB::table('page_revisions')
332                              ->where('html', 'like', $searchQuery)->count() > 0;
333                     }
334
335                     if (!$inPage && !$inRevision) {
336                         $deletedPaths[] = $image->path;
337                         if (!$dryRun) {
338                             $this->destroy($image);
339                         }
340                     }
341                 }
342             });
343         return $deletedPaths;
344     }
345
346     /**
347      * Convert a image URI to a Base64 encoded string.
348      * Attempts to find locally via set storage method first.
349      * @param string $uri
350      * @return null|string
351      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
352      */
353     public function imageUriToBase64(string $uri)
354     {
355         $isLocal = strpos(trim($uri), 'http') !== 0;
356
357         // Attempt to find local files even if url not absolute
358         $base = baseUrl('/');
359         if (!$isLocal && strpos($uri, $base) === 0) {
360             $isLocal = true;
361             $uri = str_replace($base, '', $uri);
362         }
363
364         $imageData = null;
365
366         if ($isLocal) {
367             $uri = trim($uri, '/');
368             $storage = $this->getStorage();
369             if ($storage->exists($uri)) {
370                 $imageData = $storage->get($uri);
371             }
372         } else {
373             try {
374                 $ch = curl_init();
375                 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
376                 $imageData = curl_exec($ch);
377                 $err = curl_error($ch);
378                 curl_close($ch);
379                 if ($err) {
380                     throw new \Exception("Image fetch failed, Received error: " . $err);
381                 }
382             } catch (\Exception $e) {
383             }
384         }
385
386         if ($imageData === null) {
387             return null;
388         }
389
390         return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
391     }
392
393     /**
394      * Gets a public facing url for an image by checking relevant environment variables.
395      * @param string $filePath
396      * @return string
397      */
398     private function getPublicUrl($filePath)
399     {
400         if ($this->storageUrl === null) {
401             $storageUrl = config('filesystems.url');
402
403             // Get the standard public s3 url if s3 is set as storage type
404             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
405             // region-based url will be used to prevent http issues.
406             if ($storageUrl == false && config('filesystems.default') === 's3') {
407                 $storageDetails = config('filesystems.disks.s3');
408                 if (strpos($storageDetails['bucket'], '.') === false) {
409                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
410                 } else {
411                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
412                 }
413             }
414             $this->storageUrl = $storageUrl;
415         }
416
417         $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
418         return rtrim($basePath, '/') . $filePath;
419     }
420 }