]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Updated showImage file serving to not be traversable
[bookstack] / app / Uploads / ImageService.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Exceptions\ImageUploadException;
6 use ErrorException;
7 use Exception;
8 use Illuminate\Contracts\Cache\Repository as Cache;
9 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
10 use Illuminate\Contracts\Filesystem\FileNotFoundException;
11 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
12 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
13 use Illuminate\Support\Facades\DB;
14 use Illuminate\Support\Str;
15 use Intervention\Image\Exception\NotSupportedException;
16 use Intervention\Image\ImageManager;
17 use League\Flysystem\Util;
18 use Symfony\Component\HttpFoundation\File\UploadedFile;
19 use Symfony\Component\HttpFoundation\StreamedResponse;
20
21 class ImageService
22 {
23     protected $imageTool;
24     protected $cache;
25     protected $storageUrl;
26     protected $image;
27     protected $fileSystem;
28
29     /**
30      * ImageService constructor.
31      */
32     public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
33     {
34         $this->image = $image;
35         $this->imageTool = $imageTool;
36         $this->fileSystem = $fileSystem;
37         $this->cache = $cache;
38     }
39
40     /**
41      * Get the storage that will be used for storing images.
42      */
43     protected function getStorageDisk(string $imageType = ''): FileSystemInstance
44     {
45         return $this->fileSystem->disk($this->getStorageDiskName($imageType));
46     }
47
48     /**
49      * Check if local secure image storage (Fetched behind authentication)
50      * is currently active in the instance.
51      */
52     protected function usingSecureImages(): bool
53     {
54         return $this->getStorageDiskName('gallery') === 'local_secure_images';
55     }
56
57     /**
58      * Change the originally provided path to fit any disk-specific requirements.
59      * This also ensures the path is kept to the expected root folders.
60      */
61     protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
62     {
63         $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
64
65         if ($this->getStorageDiskName($imageType) === 'local_secure_images') {
66             return $path;
67         }
68
69         return 'uploads/images/' . $path;
70     }
71
72     /**
73      * Get the name of the storage disk to use.
74      */
75     protected function getStorageDiskName(string $imageType): string
76     {
77         $storageType = config('filesystems.images');
78
79         // Ensure system images (App logo) are uploaded to a public space
80         if ($imageType === 'system' && $storageType === 'local_secure') {
81             $storageType = 'local';
82         }
83
84         if ($storageType === 'local_secure') {
85             $storageType = 'local_secure_images';
86         }
87
88         return $storageType;
89     }
90
91     /**
92      * Saves a new image from an upload.
93      *
94      * @throws ImageUploadException
95      *
96      * @return mixed
97      */
98     public function saveNewFromUpload(
99         UploadedFile $uploadedFile,
100         string $type,
101         int $uploadedTo = 0,
102         int $resizeWidth = null,
103         int $resizeHeight = null,
104         bool $keepRatio = true
105     ) {
106         $imageName = $uploadedFile->getClientOriginalName();
107         $imageData = file_get_contents($uploadedFile->getRealPath());
108
109         if ($resizeWidth !== null || $resizeHeight !== null) {
110             $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
111         }
112
113         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
114     }
115
116     /**
117      * Save a new image from a uri-encoded base64 string of data.
118      *
119      * @throws ImageUploadException
120      */
121     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
122     {
123         $splitData = explode(';base64,', $base64Uri);
124         if (count($splitData) < 2) {
125             throw new ImageUploadException('Invalid base64 image data provided');
126         }
127         $data = base64_decode($splitData[1]);
128
129         return $this->saveNew($name, $data, $type, $uploadedTo);
130     }
131
132     /**
133      * Save a new image into storage.
134      *
135      * @throws ImageUploadException
136      */
137     public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
138     {
139         $storage = $this->getStorageDisk($type);
140         $secureUploads = setting('app-secure-images');
141         $fileName = $this->cleanImageFileName($imageName);
142
143         $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
144
145         while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
146             $fileName = Str::random(3) . $fileName;
147         }
148
149         $fullPath = $imagePath . $fileName;
150         if ($secureUploads) {
151             $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
152         }
153
154         try {
155             $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
156         } catch (Exception $e) {
157             \Log::error('Error when attempting image upload:' . $e->getMessage());
158
159             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
160         }
161
162         $imageDetails = [
163             'name'        => $imageName,
164             'path'        => $fullPath,
165             'url'         => $this->getPublicUrl($fullPath),
166             'type'        => $type,
167             'uploaded_to' => $uploadedTo,
168         ];
169
170         if (user()->id !== 0) {
171             $userId = user()->id;
172             $imageDetails['created_by'] = $userId;
173             $imageDetails['updated_by'] = $userId;
174         }
175
176         $image = $this->image->newInstance();
177         $image->forceFill($imageDetails)->save();
178
179         return $image;
180     }
181
182     /**
183      * Save image data for the given path in the public space, if possible,
184      * for the provided storage mechanism.
185      */
186     protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
187     {
188         $storage->put($path, $data);
189
190         // Set visibility when a non-AWS-s3, s3-like storage option is in use.
191         // Done since this call can break s3-like services but desired for other image stores.
192         // Attempting to set ACL during above put request requires different permissions
193         // hence would technically be a breaking change for actual s3 usage.
194         $usingS3 = strtolower(config('filesystems.images')) === 's3';
195         $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
196         if (!$usingS3Like) {
197             $storage->setVisibility($path, 'public');
198         }
199     }
200
201     /**
202      * Clean up an image file name to be both URL and storage safe.
203      */
204     protected function cleanImageFileName(string $name): string
205     {
206         $name = str_replace(' ', '-', $name);
207         $nameParts = explode('.', $name);
208         $extension = array_pop($nameParts);
209         $name = implode('-', $nameParts);
210         $name = Str::slug($name);
211
212         if (strlen($name) === 0) {
213             $name = Str::random(10);
214         }
215
216         return $name . '.' . $extension;
217     }
218
219     /**
220      * Checks if the image is a gif. Returns true if it is, else false.
221      */
222     protected function isGif(Image $image): bool
223     {
224         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
225     }
226
227     /**
228      * Get the thumbnail for an image.
229      * If $keepRatio is true only the width will be used.
230      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
231      *
232      * @param Image $image
233      * @param int   $width
234      * @param int   $height
235      * @param bool  $keepRatio
236      *
237      * @throws Exception
238      * @throws ImageUploadException
239      *
240      * @return string
241      */
242     public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
243     {
244         if ($keepRatio && $this->isGif($image)) {
245             return $this->getPublicUrl($image->path);
246         }
247
248         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
249         $imagePath = $image->path;
250         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
251
252         if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
253             return $this->getPublicUrl($thumbFilePath);
254         }
255
256         $storage = $this->getStorageDisk($image->type);
257         if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
258             return $this->getPublicUrl($thumbFilePath);
259         }
260
261         $thumbData = $this->resizeImage($storage->get($this->adjustPathForStorageDisk($imagePath, $image->type)), $width, $height, $keepRatio);
262
263         $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
264         $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
265
266         return $this->getPublicUrl($thumbFilePath);
267     }
268
269     /**
270      * Resize image data.
271      *
272      * @param string $imageData
273      * @param int    $width
274      * @param int    $height
275      * @param bool   $keepRatio
276      *
277      * @throws ImageUploadException
278      *
279      * @return string
280      */
281     protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
282     {
283         try {
284             $thumb = $this->imageTool->make($imageData);
285         } catch (Exception $e) {
286             if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
287                 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
288             }
289
290             throw $e;
291         }
292
293         if ($keepRatio) {
294             $thumb->resize($width, $height, function ($constraint) {
295                 $constraint->aspectRatio();
296                 $constraint->upsize();
297             });
298         } else {
299             $thumb->fit($width, $height);
300         }
301
302         $thumbData = (string) $thumb->encode();
303
304         // Use original image data if we're keeping the ratio
305         // and the resizing does not save any space.
306         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
307             return $imageData;
308         }
309
310         return $thumbData;
311     }
312
313     /**
314      * Get the raw data content from an image.
315      *
316      * @throws FileNotFoundException
317      */
318     public function getImageData(Image $image): string
319     {
320         $storage = $this->getStorageDisk();
321
322         return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
323     }
324
325     /**
326      * Destroy an image along with its revisions, thumbnails and remaining folders.
327      *
328      * @throws Exception
329      */
330     public function destroy(Image $image)
331     {
332         $this->destroyImagesFromPath($image->path, $image->type);
333         $image->delete();
334     }
335
336     /**
337      * Destroys an image at the given path.
338      * Searches for image thumbnails in addition to main provided path.
339      */
340     protected function destroyImagesFromPath(string $path, string $imageType): bool
341     {
342         $path = $this->adjustPathForStorageDisk($path, $imageType);
343         $storage = $this->getStorageDisk($imageType);
344
345         $imageFolder = dirname($path);
346         $imageFileName = basename($path);
347         $allImages = collect($storage->allFiles($imageFolder));
348
349         // Delete image files
350         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
351             return basename($imagePath) === $imageFileName;
352         });
353         $storage->delete($imagesToDelete->all());
354
355         // Cleanup of empty folders
356         $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
357         foreach ($foldersInvolved as $directory) {
358             if ($this->isFolderEmpty($storage, $directory)) {
359                 $storage->deleteDirectory($directory);
360             }
361         }
362
363         return true;
364     }
365
366     /**
367      * Check whether a folder is empty.
368      */
369     protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
370     {
371         $files = $storage->files($path);
372         $folders = $storage->directories($path);
373
374         return count($files) === 0 && count($folders) === 0;
375     }
376
377     /**
378      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
379      * Checks based off of only the image name.
380      * Could be much improved to be more specific but kept it generic for now to be safe.
381      *
382      * Returns the path of the images that would be/have been deleted.
383      */
384     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
385     {
386         $types = ['gallery', 'drawio'];
387         $deletedPaths = [];
388
389         $this->image->newQuery()->whereIn('type', $types)
390             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
391                 foreach ($images as $image) {
392                     $searchQuery = '%' . basename($image->path) . '%';
393                     $inPage = DB::table('pages')
394                             ->where('html', 'like', $searchQuery)->count() > 0;
395
396                     $inRevision = false;
397                     if ($checkRevisions) {
398                         $inRevision = DB::table('page_revisions')
399                                 ->where('html', 'like', $searchQuery)->count() > 0;
400                     }
401
402                     if (!$inPage && !$inRevision) {
403                         $deletedPaths[] = $image->path;
404                         if (!$dryRun) {
405                             $this->destroy($image);
406                         }
407                     }
408                 }
409             });
410
411         return $deletedPaths;
412     }
413
414     /**
415      * Convert an image URI to a Base64 encoded string.
416      * Attempts to convert the URL to a system storage url then
417      * fetch the data from the disk or storage location.
418      * Returns null if the image data cannot be fetched from storage.
419      *
420      * @throws FileNotFoundException
421      */
422     public function imageUriToBase64(string $uri): ?string
423     {
424         $storagePath = $this->imageUrlToStoragePath($uri);
425         if (empty($uri) || is_null($storagePath)) {
426             return null;
427         }
428
429         $storagePath = $this->adjustPathForStorageDisk($storagePath);
430         $storage = $this->getStorageDisk();
431         $imageData = null;
432         if ($storage->exists($storagePath)) {
433             $imageData = $storage->get($storagePath);
434         }
435
436         if (is_null($imageData)) {
437             return null;
438         }
439
440         $extension = pathinfo($uri, PATHINFO_EXTENSION);
441         if ($extension === 'svg') {
442             $extension = 'svg+xml';
443         }
444
445         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
446     }
447
448     /**
449      * Check if the given path exists in the local secure image system.
450      * Returns false if local_secure is not in use.
451      */
452     public function pathExistsInLocalSecure(string $imagePath): bool
453     {
454         $disk = $this->getStorageDisk('gallery');
455
456         // Check local_secure is active
457         return $this->usingSecureImages()
458             // Check the image file exists
459             && $disk->exists($imagePath)
460             // Check the file is likely an image file
461             && strpos($disk->getMimetype($imagePath), 'image/') === 0;
462     }
463
464     /**
465      * For the given path, if existing, provide a response that will stream the image contents.
466      */
467     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
468     {
469         $disk = $this->getStorageDisk($imageType);
470         return $disk->response($path);
471     }
472
473     /**
474      * Get a storage path for the given image URL.
475      * Ensures the path will start with "uploads/images".
476      * Returns null if the url cannot be resolved to a local URL.
477      */
478     private function imageUrlToStoragePath(string $url): ?string
479     {
480         $url = ltrim(trim($url), '/');
481
482         // Handle potential relative paths
483         $isRelative = strpos($url, 'http') !== 0;
484         if ($isRelative) {
485             if (strpos(strtolower($url), 'uploads/images') === 0) {
486                 return trim($url, '/');
487             }
488
489             return null;
490         }
491
492         // Handle local images based on paths on the same domain
493         $potentialHostPaths = [
494             url('uploads/images/'),
495             $this->getPublicUrl('/uploads/images/'),
496         ];
497
498         foreach ($potentialHostPaths as $potentialBasePath) {
499             $potentialBasePath = strtolower($potentialBasePath);
500             if (strpos(strtolower($url), $potentialBasePath) === 0) {
501                 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
502             }
503         }
504
505         return null;
506     }
507
508     /**
509      * Gets a public facing url for an image by checking relevant environment variables.
510      * If s3-style store is in use it will default to guessing a public bucket URL.
511      */
512     private function getPublicUrl(string $filePath): string
513     {
514         if ($this->storageUrl === null) {
515             $storageUrl = config('filesystems.url');
516
517             // Get the standard public s3 url if s3 is set as storage type
518             // Uses the nice, short URL if bucket name has no periods in otherwise the longer
519             // region-based url will be used to prevent http issues.
520             if ($storageUrl == false && config('filesystems.images') === 's3') {
521                 $storageDetails = config('filesystems.disks.s3');
522                 if (strpos($storageDetails['bucket'], '.') === false) {
523                     $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
524                 } else {
525                     $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
526                 }
527             }
528             $this->storageUrl = $storageUrl;
529         }
530
531         $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
532
533         return rtrim($basePath, '/') . $filePath;
534     }
535 }