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