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