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