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