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