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