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