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