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