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