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