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