]> BookStack Code Mirror - bookstack/blob - app/Services/ImageService.php
Added drawing update ability
[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\Filesystem\Filesystem as FileSystemInstance;
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      * Saves a new image from an upload.
36      * @param UploadedFile $uploadedFile
37      * @param  string $type
38      * @param int $uploadedTo
39      * @return mixed
40      * @throws ImageUploadException
41      */
42     public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
43     {
44         $imageName = $uploadedFile->getClientOriginalName();
45         $imageData = file_get_contents($uploadedFile->getRealPath());
46         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
47     }
48
49     /**
50      * Save a new image from a uri-encoded base64 string of data.
51      * @param string $base64Uri
52      * @param string $name
53      * @param string $type
54      * @param int $uploadedTo
55      * @return Image
56      * @throws ImageUploadException
57      */
58     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
59     {
60         $splitData = explode(';base64,', $base64Uri);
61         if (count($splitData) < 2) {
62             throw new ImageUploadException("Invalid base64 image data provided");
63         }
64         $data = base64_decode($splitData[1]);
65         return $this->saveNew($name, $data, $type, $uploadedTo);
66     }
67
68     /**
69      * Replace the data for an image via a Base64 encoded string.
70      * @param Image $image
71      * @param string $base64Uri
72      * @return Image
73      * @throws ImageUploadException
74      */
75     public function replaceImageDataFromBase64Uri(Image $image, string $base64Uri)
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         $storage = $this->getStorage();
83
84         try {
85             $storage->put($image->path, $data);
86         } catch (Exception $e) {
87             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $image->path]));
88         }
89
90         return $image;
91     }
92
93     /**
94      * Gets an image from url and saves it to the database.
95      * @param             $url
96      * @param string      $type
97      * @param bool|string $imageName
98      * @return mixed
99      * @throws \Exception
100      */
101     private function saveNewFromUrl($url, $type, $imageName = false)
102     {
103         $imageName = $imageName ? $imageName : basename($url);
104         $imageData = file_get_contents($url);
105         if($imageData === false) throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
106         return $this->saveNew($imageName, $imageData, $type);
107     }
108
109     /**
110      * Saves a new image
111      * @param string $imageName
112      * @param string $imageData
113      * @param string $type
114      * @param int $uploadedTo
115      * @return Image
116      * @throws ImageUploadException
117      */
118     private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
119     {
120         $storage = $this->getStorage();
121         $secureUploads = setting('app-secure-images');
122         $imageName = str_replace(' ', '-', $imageName);
123
124         if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
125
126         $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
127
128         if ($this->isLocal()) $imagePath = '/public' . $imagePath;
129
130         while ($storage->exists($imagePath . $imageName)) {
131             $imageName = str_random(3) . $imageName;
132         }
133         $fullPath = $imagePath . $imageName;
134
135         try {
136             $storage->put($fullPath, $imageData);
137             $storage->setVisibility($fullPath, 'public');
138         } catch (Exception $e) {
139             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
140         }
141
142         if ($this->isLocal()) $fullPath = str_replace_first('/public', '', $fullPath);
143
144         $imageDetails = [
145             'name'       => $imageName,
146             'path'       => $fullPath,
147             'url'        => $this->getPublicUrl($fullPath),
148             'type'       => $type,
149             'uploaded_to' => $uploadedTo
150         ];
151
152         if (user()->id !== 0) {
153             $userId = user()->id;
154             $imageDetails['created_by'] = $userId;
155             $imageDetails['updated_by'] = $userId;
156         }
157
158         $image = Image::forceCreate($imageDetails);
159
160         return $image;
161     }
162
163     /**
164      * Get the storage path, Dependant of storage type.
165      * @param Image $image
166      * @return mixed|string
167      */
168     protected function getPath(Image $image)
169     {
170         return ($this->isLocal()) ? ('public/' . $image->path) : $image->path;
171     }
172
173     /**
174      * Get the thumbnail for an image.
175      * If $keepRatio is true only the width will be used.
176      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
177      *
178      * @param Image $image
179      * @param int $width
180      * @param int $height
181      * @param bool $keepRatio
182      * @return string
183      * @throws Exception
184      * @throws ImageUploadException
185      */
186     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
187     {
188         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
189         $imagePath = $this->getPath($image);
190         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
191
192         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
193             return $this->getPublicUrl($thumbFilePath);
194         }
195
196         $storage = $this->getStorage();
197
198         if ($storage->exists($thumbFilePath)) {
199             return $this->getPublicUrl($thumbFilePath);
200         }
201
202         try {
203             $thumb = $this->imageTool->make($storage->get($imagePath));
204         } catch (Exception $e) {
205             if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
206                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
207             } else {
208                 throw $e;
209             }
210         }
211
212         if ($keepRatio) {
213             $thumb->resize($width, null, function ($constraint) {
214                 $constraint->aspectRatio();
215                 $constraint->upsize();
216             });
217         } else {
218             $thumb->fit($width, $height);
219         }
220
221         $thumbData = (string)$thumb->encode();
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      * Get the raw data content from an image.
231      * @param Image $image
232      * @return string
233      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
234      */
235     public function getImageData(Image $image)
236     {
237         $imagePath = $this->getPath($image);
238         $storage = $this->getStorage();
239         return $storage->get($imagePath);
240     }
241
242     /**
243      * Destroys an Image object along with its files and thumbnails.
244      * @param Image $image
245      * @return bool
246      */
247     public function destroyImage(Image $image)
248     {
249         $storage = $this->getStorage();
250
251         $imageFolder = dirname($this->getPath($image));
252         $imageFileName = basename($this->getPath($image));
253         $allImages = collect($storage->allFiles($imageFolder));
254
255         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
256             $expectedIndex = strlen($imagePath) - strlen($imageFileName);
257             return strpos($imagePath, $imageFileName) === $expectedIndex;
258         });
259
260         $storage->delete($imagesToDelete->all());
261
262         // Cleanup of empty folders
263         foreach ($storage->directories($imageFolder) as $directory) {
264             if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
265         }
266         if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
267
268         $image->delete();
269         return true;
270     }
271
272     /**
273      * Save a gravatar image and set a the profile image for a user.
274      * @param User $user
275      * @param int  $size
276      * @return mixed
277      */
278     public function saveUserGravatar(User $user, $size = 500)
279     {
280         $emailHash = md5(strtolower(trim($user->email)));
281         $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
282         $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
283         $image = $this->saveNewFromUrl($url, 'user', $imageName);
284         $image->created_by = $user->id;
285         $image->updated_by = $user->id;
286         $image->save();
287         return $image;
288     }
289
290     /**
291      * Gets a public facing url for an image by checking relevant environment variables.
292      * @param string $filePath
293      * @return string
294      */
295     private function getPublicUrl($filePath)
296     {
297         if ($this->storageUrl === null) {
298             $storageUrl = config('filesystems.url');
299
300             // Get the standard public s3 url if s3 is set as storage type
301             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
302             // region-based url will be used to prevent http issues.
303             if ($storageUrl == false && config('filesystems.default') === 's3') {
304                 $storageDetails = config('filesystems.disks.s3');
305                 if (strpos($storageDetails['bucket'], '.') === false) {
306                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
307                 } else {
308                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
309                 }
310             }
311
312             $this->storageUrl = $storageUrl;
313         }
314
315         if ($this->isLocal()) $filePath = str_replace_first('public/', '', $filePath);
316
317         return ($this->storageUrl == false ? rtrim(baseUrl(''), '/') : rtrim($this->storageUrl, '/')) . $filePath;
318     }
319
320
321 }