]> BookStack Code Mirror - bookstack/blob - app/Services/ImageService.php
Updated folder permissions installation instructions & fixed issue with handling...
[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\ImageManager;
8 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
9 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
10 use Illuminate\Contracts\Cache\Repository as Cache;
11 use Setting;
12 use Symfony\Component\HttpFoundation\File\UploadedFile;
13
14 class ImageService
15 {
16
17     protected $imageTool;
18     protected $fileSystem;
19     protected $cache;
20
21     /**
22      * @var FileSystemInstance
23      */
24     protected $storageInstance;
25     protected $storageUrl;
26
27     /**
28      * ImageService constructor.
29      * @param $imageTool
30      * @param $fileSystem
31      * @param $cache
32      */
33     public function __construct(ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
34     {
35         $this->imageTool = $imageTool;
36         $this->fileSystem = $fileSystem;
37         $this->cache = $cache;
38     }
39
40     /**
41      * Saves a new image from an upload.
42      * @param UploadedFile $uploadedFile
43      * @param  string      $type
44      * @return mixed
45      */
46     public function saveNewFromUpload(UploadedFile $uploadedFile, $type)
47     {
48         $imageName = $uploadedFile->getClientOriginalName();
49         $imageData = file_get_contents($uploadedFile->getRealPath());
50         return $this->saveNew($imageName, $imageData, $type);
51     }
52
53
54     /**
55      * Gets an image from url and saves it to the database.
56      * @param             $url
57      * @param string      $type
58      * @param bool|string $imageName
59      * @return mixed
60      * @throws \Exception
61      */
62     private function saveNewFromUrl($url, $type, $imageName = false)
63     {
64         $imageName = $imageName ? $imageName : basename($url);
65         $imageData = file_get_contents($url);
66         if($imageData === false) throw new \Exception('Cannot get image from ' . $url);
67         return $this->saveNew($imageName, $imageData, $type);
68     }
69
70     /**
71      * Saves a new image
72      * @param string $imageName
73      * @param string $imageData
74      * @param string $type
75      * @return Image
76      * @throws ImageUploadException
77      */
78     private function saveNew($imageName, $imageData, $type)
79     {
80         $storage = $this->getStorage();
81         $secureUploads = Setting::get('app-secure-images');
82         $imageName = str_replace(' ', '-', $imageName);
83
84         if ($secureUploads) $imageName = str_random(16) . '-' . $imageName;
85
86         $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
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         } catch (Exception $e) {
95             throw new ImageUploadException('Image Path ' . $fullPath . ' is not writable by the server.');
96         }
97
98         $imageDetails = [
99             'name'       => $imageName,
100             'path'       => $fullPath,
101             'url'        => $this->getPublicUrl($fullPath),
102             'type'       => $type
103         ];
104
105         if (auth()->user() && auth()->user()->id !== 0) {
106             $userId = auth()->user()->id;
107             $imageDetails['created_by'] = $userId;
108             $imageDetails['updated_by'] = $userId;
109         }
110
111         $image = Image::forceCreate($imageDetails);
112
113         return $image;
114     }
115
116     /**
117      * Get the thumbnail for an image.
118      * If $keepRatio is true only the width will be used.
119      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
120      *
121      * @param Image $image
122      * @param int   $width
123      * @param int   $height
124      * @param bool  $keepRatio
125      * @return string
126      */
127     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
128     {
129         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
130         $thumbFilePath = dirname($image->path) . $thumbDirName . basename($image->path);
131
132         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
133             return $this->getPublicUrl($thumbFilePath);
134         }
135
136         $storage = $this->getStorage();
137
138         if ($storage->exists($thumbFilePath)) {
139             return $this->getPublicUrl($thumbFilePath);
140         }
141
142         // Otherwise create the thumbnail
143         $thumb = $this->imageTool->make($storage->get($image->path));
144         if ($keepRatio) {
145             $thumb->resize($width, null, function ($constraint) {
146                 $constraint->aspectRatio();
147                 $constraint->upsize();
148             });
149         } else {
150             $thumb->fit($width, $height);
151         }
152
153         $thumbData = (string)$thumb->encode();
154         $storage->put($thumbFilePath, $thumbData);
155         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
156
157         return $this->getPublicUrl($thumbFilePath);
158     }
159
160     /**
161      * Destroys an Image object along with its files and thumbnails.
162      * @param Image $image
163      * @return bool
164      */
165     public function destroyImage(Image $image)
166     {
167         $storage = $this->getStorage();
168
169         $imageFolder = dirname($image->path);
170         $imageFileName = basename($image->path);
171         $allImages = collect($storage->allFiles($imageFolder));
172
173         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
174             $expectedIndex = strlen($imagePath) - strlen($imageFileName);
175             return strpos($imagePath, $imageFileName) === $expectedIndex;
176         });
177
178         $storage->delete($imagesToDelete->all());
179
180         // Cleanup of empty folders
181         foreach ($storage->directories($imageFolder) as $directory) {
182             if ($this->isFolderEmpty($directory)) $storage->deleteDirectory($directory);
183         }
184         if ($this->isFolderEmpty($imageFolder)) $storage->deleteDirectory($imageFolder);
185
186         $image->delete();
187         return true;
188     }
189
190     /**
191      * Save a gravatar image and set a the profile image for a user.
192      * @param User $user
193      * @param int  $size
194      * @return mixed
195      */
196     public function saveUserGravatar(User $user, $size = 500)
197     {
198         $emailHash = md5(strtolower(trim($user->email)));
199         $url = 'http://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
200         $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
201         $image = $this->saveNewFromUrl($url, 'user', $imageName);
202         $image->created_by = $user->id;
203         $image->updated_by = $user->id;
204         $image->save();
205         return $image;
206     }
207
208     /**
209      * Get the storage that will be used for storing images.
210      * @return FileSystemInstance
211      */
212     private function getStorage()
213     {
214         if ($this->storageInstance !== null) return $this->storageInstance;
215
216         $storageType = config('filesystems.default');
217         $this->storageInstance = $this->fileSystem->disk($storageType);
218
219         return $this->storageInstance;
220     }
221
222     /**
223      * Check whether or not a folder is empty.
224      * @param $path
225      * @return int
226      */
227     private function isFolderEmpty($path)
228     {
229         $files = $this->getStorage()->files($path);
230         $folders = $this->getStorage()->directories($path);
231         return count($files) === 0 && count($folders) === 0;
232     }
233
234     /**
235      * Gets a public facing url for an image by checking relevant environment variables.
236      * @param $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             if ($storageUrl == false && config('filesystems.default') === 's3') {
246                 $storageDetails = config('filesystems.disks.s3');
247                 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
248             }
249
250             $this->storageUrl = $storageUrl;
251         }
252
253         return ($this->storageUrl == false ? '' : rtrim($this->storageUrl, '/')) . $filePath;
254     }
255
256
257 }