]> BookStack Code Mirror - bookstack/blob - app/Services/ImageService.php
Ensured uploaded system images remain public
[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         return strtolower(pathinfo($this->getPath($image), PATHINFO_EXTENSION)) === 'gif';
197     }
198
199     /**
200      * Get the thumbnail for an image.
201      * If $keepRatio is true only the width will be used.
202      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
203      * @param Image $image
204      * @param int $width
205      * @param int $height
206      * @param bool $keepRatio
207      * @return string
208      * @throws Exception
209      * @throws ImageUploadException
210      */
211     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
212     {
213         if ($keepRatio && $this->isGif($image)) {
214             return $this->getPublicUrl($this->getPath($image));
215         }
216
217         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
218         $imagePath = $this->getPath($image);
219         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
220
221         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
222             return $this->getPublicUrl($thumbFilePath);
223         }
224
225         $storage = $this->getStorage($image->type);
226         if ($storage->exists($thumbFilePath)) {
227             return $this->getPublicUrl($thumbFilePath);
228         }
229
230         try {
231             $thumb = $this->imageTool->make($storage->get($imagePath));
232         } catch (Exception $e) {
233             if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
234                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
235             }
236             throw $e;
237         }
238
239         if ($keepRatio) {
240             $thumb->resize($width, null, function ($constraint) {
241                 $constraint->aspectRatio();
242                 $constraint->upsize();
243             });
244         } else {
245             $thumb->fit($width, $height);
246         }
247
248         $thumbData = (string)$thumb->encode();
249         $storage->put($thumbFilePath, $thumbData);
250         $storage->setVisibility($thumbFilePath, 'public');
251         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
252
253         return $this->getPublicUrl($thumbFilePath);
254     }
255
256     /**
257      * Get the raw data content from an image.
258      * @param Image $image
259      * @return string
260      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
261      */
262     public function getImageData(Image $image)
263     {
264         $imagePath = $this->getPath($image);
265         $storage = $this->getStorage();
266         return $storage->get($imagePath);
267     }
268
269     /**
270      * Destroys an Image object along with its files and thumbnails.
271      * @param Image $image
272      * @return bool
273      * @throws Exception
274      */
275     public function destroyImage(Image $image)
276     {
277         $storage = $this->getStorage();
278
279         $imageFolder = dirname($this->getPath($image));
280         $imageFileName = basename($this->getPath($image));
281         $allImages = collect($storage->allFiles($imageFolder));
282
283         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
284             $expectedIndex = strlen($imagePath) - strlen($imageFileName);
285             return strpos($imagePath, $imageFileName) === $expectedIndex;
286         });
287
288         $storage->delete($imagesToDelete->all());
289
290         // Cleanup of empty folders
291         foreach ($storage->directories($imageFolder) as $directory) {
292             if ($this->isFolderEmpty($directory)) {
293                 $storage->deleteDirectory($directory);
294             }
295         }
296         if ($this->isFolderEmpty($imageFolder)) {
297             $storage->deleteDirectory($imageFolder);
298         }
299
300         $image->delete();
301         return true;
302     }
303
304     /**
305      * Save a gravatar image and set a the profile image for a user.
306      * @param User $user
307      * @param int $size
308      * @return mixed
309      * @throws Exception
310      */
311     public function saveUserGravatar(User $user, $size = 500)
312     {
313         $emailHash = md5(strtolower(trim($user->email)));
314         $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
315         $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
316         $image = $this->saveNewFromUrl($url, 'user', $imageName);
317         $image->created_by = $user->id;
318         $image->updated_by = $user->id;
319         $image->save();
320         return $image;
321     }
322
323     /**
324      * Gets a public facing url for an image by checking relevant environment variables.
325      * @param string $filePath
326      * @return string
327      */
328     private function getPublicUrl($filePath)
329     {
330         if ($this->storageUrl === null) {
331             $storageUrl = config('filesystems.url');
332
333             // Get the standard public s3 url if s3 is set as storage type
334             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
335             // region-based url will be used to prevent http issues.
336             if ($storageUrl == false && config('filesystems.default') === 's3') {
337                 $storageDetails = config('filesystems.disks.s3');
338                 if (strpos($storageDetails['bucket'], '.') === false) {
339                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
340                 } else {
341                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
342                 }
343             }
344             $this->storageUrl = $storageUrl;
345         }
346
347         $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
348         return rtrim($basePath, '/') . $filePath;
349     }
350 }