]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Added config entry for select account
[bookstack] / app / Uploads / ImageService.php
1 <?php namespace BookStack\Uploads;
2
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\ImageUploadException;
5 use DB;
6 use Exception;
7 use Illuminate\Contracts\Cache\Repository as Cache;
8 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
9 use Intervention\Image\Exception\NotSupportedException;
10 use Intervention\Image\ImageManager;
11 use Symfony\Component\HttpFoundation\File\UploadedFile;
12
13 class ImageService extends UploadService
14 {
15
16     protected $imageTool;
17     protected $cache;
18     protected $storageUrl;
19     protected $image;
20
21     /**
22      * ImageService constructor.
23      * @param Image $image
24      * @param ImageManager $imageTool
25      * @param FileSystem $fileSystem
26      * @param Cache $cache
27      */
28     public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
29     {
30         $this->image = $image;
31         $this->imageTool = $imageTool;
32         $this->cache = $cache;
33         parent::__construct($fileSystem);
34     }
35
36     /**
37      * Get the storage that will be used for storing images.
38      * @param string $type
39      * @return \Illuminate\Contracts\Filesystem\Filesystem
40      */
41     protected function getStorage($type = '')
42     {
43         $storageType = config('filesystems.default');
44
45         // Override default location if set to local public to ensure not visible.
46         if ($type === 'system' && $storageType === 'local_secure') {
47             $storageType = 'local';
48         }
49
50         return $this->fileSystem->disk($storageType);
51     }
52
53     /**
54      * Saves a new image from an upload.
55      * @param UploadedFile $uploadedFile
56      * @param  string $type
57      * @param int $uploadedTo
58      * @return mixed
59      * @throws ImageUploadException
60      */
61     public function saveNewFromUpload(UploadedFile $uploadedFile, $type, $uploadedTo = 0)
62     {
63         $imageName = $uploadedFile->getClientOriginalName();
64         $imageData = file_get_contents($uploadedFile->getRealPath());
65         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
66     }
67
68     /**
69      * Save a new image from a uri-encoded base64 string of data.
70      * @param string $base64Uri
71      * @param string $name
72      * @param string $type
73      * @param int $uploadedTo
74      * @return Image
75      * @throws ImageUploadException
76      */
77     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, $uploadedTo = 0)
78     {
79         $splitData = explode(';base64,', $base64Uri);
80         if (count($splitData) < 2) {
81             throw new ImageUploadException("Invalid base64 image data provided");
82         }
83         $data = base64_decode($splitData[1]);
84         return $this->saveNew($name, $data, $type, $uploadedTo);
85     }
86
87     /**
88      * Gets an image from url and saves it to the database.
89      * @param             $url
90      * @param string      $type
91      * @param bool|string $imageName
92      * @return mixed
93      * @throws \Exception
94      */
95     private function saveNewFromUrl($url, $type, $imageName = false)
96     {
97         $imageName = $imageName ? $imageName : basename($url);
98         $imageData = file_get_contents($url);
99         if ($imageData === false) {
100             throw new \Exception(trans('errors.cannot_get_image_from_url', ['url' => $url]));
101         }
102         return $this->saveNew($imageName, $imageData, $type);
103     }
104
105     /**
106      * Saves a new image
107      * @param string $imageName
108      * @param string $imageData
109      * @param string $type
110      * @param int $uploadedTo
111      * @return Image
112      * @throws ImageUploadException
113      */
114     private function saveNew($imageName, $imageData, $type, $uploadedTo = 0)
115     {
116         $storage = $this->getStorage($type);
117         $secureUploads = setting('app-secure-images');
118         $imageName = str_replace(' ', '-', $imageName);
119
120         $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m-M') . '/';
121
122         while ($storage->exists($imagePath . $imageName)) {
123             $imageName = str_random(3) . $imageName;
124         }
125
126         $fullPath = $imagePath . $imageName;
127         if ($secureUploads) {
128             $fullPath = $imagePath . str_random(16) . '-' . $imageName;
129         }
130
131         try {
132             $storage->put($fullPath, $imageData);
133             $storage->setVisibility($fullPath, 'public');
134         } catch (Exception $e) {
135             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
136         }
137
138         $imageDetails = [
139             'name'       => $imageName,
140             'path'       => $fullPath,
141             'url'        => $this->getPublicUrl($fullPath),
142             'type'       => $type,
143             'uploaded_to' => $uploadedTo
144         ];
145
146         if (user()->id !== 0) {
147             $userId = user()->id;
148             $imageDetails['created_by'] = $userId;
149             $imageDetails['updated_by'] = $userId;
150         }
151
152         $image = $this->image->newInstance();
153         $image->forceFill($imageDetails)->save();
154         return $image;
155     }
156
157
158     /**
159      * Checks if the image is a gif. Returns true if it is, else false.
160      * @param Image $image
161      * @return boolean
162      */
163     protected function isGif(Image $image)
164     {
165         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
166     }
167
168     /**
169      * Get the thumbnail for an image.
170      * If $keepRatio is true only the width will be used.
171      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
172      * @param Image $image
173      * @param int $width
174      * @param int $height
175      * @param bool $keepRatio
176      * @return string
177      * @throws Exception
178      * @throws ImageUploadException
179      */
180     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
181     {
182         if ($keepRatio && $this->isGif($image)) {
183             return $this->getPublicUrl($image->path);
184         }
185
186         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
187         $imagePath = $image->path;
188         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
189
190         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
191             return $this->getPublicUrl($thumbFilePath);
192         }
193
194         $storage = $this->getStorage($image->type);
195         if ($storage->exists($thumbFilePath)) {
196             return $this->getPublicUrl($thumbFilePath);
197         }
198
199         try {
200             $thumb = $this->imageTool->make($storage->get($imagePath));
201         } catch (Exception $e) {
202             if ($e instanceof \ErrorException || $e instanceof NotSupportedException) {
203                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
204             }
205             throw $e;
206         }
207
208         if ($keepRatio) {
209             $thumb->resize($width, null, function ($constraint) {
210                 $constraint->aspectRatio();
211                 $constraint->upsize();
212             });
213         } else {
214             $thumb->fit($width, $height);
215         }
216
217         $thumbData = (string)$thumb->encode();
218         $storage->put($thumbFilePath, $thumbData);
219         $storage->setVisibility($thumbFilePath, 'public');
220         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 72);
221
222         return $this->getPublicUrl($thumbFilePath);
223     }
224
225     /**
226      * Get the raw data content from an image.
227      * @param Image $image
228      * @return string
229      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
230      */
231     public function getImageData(Image $image)
232     {
233         $imagePath = $image->path;
234         $storage = $this->getStorage();
235         return $storage->get($imagePath);
236     }
237
238     /**
239      * Destroy an image along with its revisions, thumbnails and remaining folders.
240      * @param Image $image
241      * @throws Exception
242      */
243     public function destroy(Image $image)
244     {
245         $this->destroyImagesFromPath($image->path);
246         $image->delete();
247     }
248
249     /**
250      * Destroys an image at the given path.
251      * Searches for image thumbnails in addition to main provided path..
252      * @param string $path
253      * @return bool
254      */
255     protected function destroyImagesFromPath(string $path)
256     {
257         $storage = $this->getStorage();
258
259         $imageFolder = dirname($path);
260         $imageFileName = basename($path);
261         $allImages = collect($storage->allFiles($imageFolder));
262
263         // Delete image files
264         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
265             $expectedIndex = strlen($imagePath) - strlen($imageFileName);
266             return strpos($imagePath, $imageFileName) === $expectedIndex;
267         });
268         $storage->delete($imagesToDelete->all());
269
270         // Cleanup of empty folders
271         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
272         foreach ($foldersInvolved as $directory) {
273             if ($this->isFolderEmpty($directory)) {
274                 $storage->deleteDirectory($directory);
275             }
276         }
277
278         return true;
279     }
280
281     /**
282      * Save a gravatar image and set a the profile image for a user.
283      * @param \BookStack\Auth\User $user
284      * @param int $size
285      * @return mixed
286      * @throws Exception
287      */
288     public function saveUserGravatar(User $user, $size = 500)
289     {
290         $emailHash = md5(strtolower(trim($user->email)));
291         $url = 'https://www.gravatar.com/avatar/' . $emailHash . '?s=' . $size . '&d=identicon';
292         $imageName = str_replace(' ', '-', $user->name . '-gravatar.png');
293         $image = $this->saveNewFromUrl($url, 'user', $imageName);
294         $image->created_by = $user->id;
295         $image->updated_by = $user->id;
296         $image->save();
297         return $image;
298     }
299
300
301     /**
302      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
303      * Checks based off of only the image name.
304      * Could be much improved to be more specific but kept it generic for now to be safe.
305      *
306      * Returns the path of the images that would be/have been deleted.
307      * @param bool $checkRevisions
308      * @param bool $dryRun
309      * @param array $types
310      * @return array
311      */
312     public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
313     {
314         $types = array_intersect($types, ['gallery', 'drawio']);
315         $deletedPaths = [];
316
317         $this->image->newQuery()->whereIn('type', $types)
318             ->chunk(1000, function ($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
319                 foreach ($images as $image) {
320                     $searchQuery = '%' . basename($image->path) . '%';
321                     $inPage = DB::table('pages')
322                          ->where('html', 'like', $searchQuery)->count() > 0;
323                     $inRevision = false;
324                     if ($checkRevisions) {
325                         $inRevision =  DB::table('page_revisions')
326                              ->where('html', 'like', $searchQuery)->count() > 0;
327                     }
328
329                     if (!$inPage && !$inRevision) {
330                         $deletedPaths[] = $image->path;
331                         if (!$dryRun) {
332                             $this->destroy($image);
333                         }
334                     }
335                 }
336             });
337         return $deletedPaths;
338     }
339
340     /**
341      * Convert a image URI to a Base64 encoded string.
342      * Attempts to find locally via set storage method first.
343      * @param string $uri
344      * @return null|string
345      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
346      */
347     public function imageUriToBase64(string $uri)
348     {
349         $isLocal = strpos(trim($uri), 'http') !== 0;
350
351         // Attempt to find local files even if url not absolute
352         $base = baseUrl('/');
353         if (!$isLocal && strpos($uri, $base) === 0) {
354             $isLocal = true;
355             $uri = str_replace($base, '', $uri);
356         }
357
358         $imageData = null;
359
360         if ($isLocal) {
361             $uri = trim($uri, '/');
362             $storage = $this->getStorage();
363             if ($storage->exists($uri)) {
364                 $imageData = $storage->get($uri);
365             }
366         } else {
367             try {
368                 $ch = curl_init();
369                 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
370                 $imageData = curl_exec($ch);
371                 $err = curl_error($ch);
372                 curl_close($ch);
373                 if ($err) {
374                     throw new \Exception("Image fetch failed, Received error: " . $err);
375                 }
376             } catch (\Exception $e) {
377             }
378         }
379
380         if ($imageData === null) {
381             return null;
382         }
383
384         return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
385     }
386
387     /**
388      * Gets a public facing url for an image by checking relevant environment variables.
389      * @param string $filePath
390      * @return string
391      */
392     private function getPublicUrl($filePath)
393     {
394         if ($this->storageUrl === null) {
395             $storageUrl = config('filesystems.url');
396
397             // Get the standard public s3 url if s3 is set as storage type
398             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
399             // region-based url will be used to prevent http issues.
400             if ($storageUrl == false && config('filesystems.default') === 's3') {
401                 $storageDetails = config('filesystems.disks.s3');
402                 if (strpos($storageDetails['bucket'], '.') === false) {
403                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
404                 } else {
405                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
406                 }
407             }
408             $this->storageUrl = $storageUrl;
409         }
410
411         $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
412         return rtrim($basePath, '/') . $filePath;
413     }
414 }