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