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