]> BookStack Code Mirror - bookstack/blob - app/Services/ImageService.php
Fixes a corner case with exclamation in the ID.
[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      * Checks based off of only the image name.
305      * Could be much improved to be more specific but kept it generic for now to be safe.
306      *
307      * Returns the path of the images that would be/have been deleted.
308      * @param bool $checkRevisions
309      * @param bool $dryRun
310      * @param array $types
311      * @return array
312      */
313     public function deleteUnusedImages($checkRevisions = true, $dryRun = true, $types = ['gallery', 'drawio'])
314     {
315         $types = array_intersect($types, ['gallery', 'drawio']);
316         $deletedPaths = [];
317
318         $this->image->newQuery()->whereIn('type', $types)
319             ->chunk(1000, function($images) use ($types, $checkRevisions, &$deletedPaths, $dryRun) {
320              foreach ($images as $image) {
321                  $searchQuery = '%' . basename($image->path) . '%';
322                  $inPage = DB::table('pages')
323                          ->where('html', 'like', $searchQuery)->count() > 0;
324                  $inRevision = false;
325                  if ($checkRevisions) {
326                      $inRevision =  DB::table('page_revisions')
327                              ->where('html', 'like', $searchQuery)->count() > 0;
328                  }
329
330                  if (!$inPage && !$inRevision) {
331                      $deletedPaths[] = $image->path;
332                      if (!$dryRun) {
333                          $this->destroy($image);
334                      }
335                  }
336              }
337         });
338         return $deletedPaths;
339     }
340
341     /**
342      * Convert a image URI to a Base64 encoded string.
343      * Attempts to find locally via set storage method first.
344      * @param string $uri
345      * @return null|string
346      * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
347      */
348     public function imageUriToBase64(string $uri)
349     {
350         $isLocal = strpos(trim($uri), 'http') !== 0;
351
352         // Attempt to find local files even if url not absolute
353         $base = baseUrl('/');
354         if (!$isLocal && strpos($uri, $base) === 0) {
355             $isLocal = true;
356             $uri = str_replace($base, '', $uri);
357         }
358
359         $imageData = null;
360
361         if ($isLocal) {
362             $uri = trim($uri, '/');
363             $storage = $this->getStorage();
364             if ($storage->exists($uri)) {
365                 $imageData = $storage->get($uri);
366             }
367         } else {
368             try {
369                 $ch = curl_init();
370                 curl_setopt_array($ch, [CURLOPT_URL => $uri, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 5]);
371                 $imageData = curl_exec($ch);
372                 $err = curl_error($ch);
373                 curl_close($ch);
374                 if ($err) {
375                     throw new \Exception("Image fetch failed, Received error: " . $err);
376                 }
377             } catch (\Exception $e) {
378             }
379         }
380
381         if ($imageData === null) {
382             return null;
383         }
384
385         return 'data:image/' . pathinfo($uri, PATHINFO_EXTENSION) . ';base64,' . base64_encode($imageData);
386     }
387
388     /**
389      * Gets a public facing url for an image by checking relevant environment variables.
390      * @param string $filePath
391      * @return string
392      */
393     private function getPublicUrl($filePath)
394     {
395         if ($this->storageUrl === null) {
396             $storageUrl = config('filesystems.url');
397
398             // Get the standard public s3 url if s3 is set as storage type
399             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
400             // region-based url will be used to prevent http issues.
401             if ($storageUrl == false && config('filesystems.default') === 's3') {
402                 $storageDetails = config('filesystems.disks.s3');
403                 if (strpos($storageDetails['bucket'], '.') === false) {
404                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
405                 } else {
406                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
407                 }
408             }
409             $this->storageUrl = $storageUrl;
410         }
411
412         $basePath = ($this->storageUrl == false) ? baseUrl('/') : $this->storageUrl;
413         return rtrim($basePath, '/') . $filePath;
414     }
415 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.