]> BookStack Code Mirror - bookstack/blob - app/Uploads/ImageService.php
Images: Started refactor of image service
[bookstack] / app / Uploads / ImageService.php
1 <?php
2
3 namespace BookStack\Uploads;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Exceptions\ImageUploadException;
9 use ErrorException;
10 use Exception;
11 use Illuminate\Contracts\Cache\Repository as Cache;
12 use Illuminate\Contracts\Filesystem\FileNotFoundException;
13 use Illuminate\Contracts\Filesystem\Filesystem as StorageDisk;
14 use Illuminate\Filesystem\FilesystemAdapter;
15 use Illuminate\Filesystem\FilesystemManager;
16 use Illuminate\Support\Facades\DB;
17 use Illuminate\Support\Facades\Log;
18 use Illuminate\Support\Str;
19 use Intervention\Image\Exception\NotSupportedException;
20 use Intervention\Image\ImageManager;
21 use Symfony\Component\HttpFoundation\File\UploadedFile;
22 use Symfony\Component\HttpFoundation\StreamedResponse;
23
24 class ImageService
25 {
26     protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
27
28     public function __construct(
29         protected ImageManager $imageTool,
30         protected FilesystemManager $fileSystem,
31         protected Cache $cache,
32         protected ImageStorage $storage,
33     ) {
34     }
35
36     /**
37      * Saves a new image from an upload.
38      *
39      * @throws ImageUploadException
40      */
41     public function saveNewFromUpload(
42         UploadedFile $uploadedFile,
43         string $type,
44         int $uploadedTo = 0,
45         int $resizeWidth = null,
46         int $resizeHeight = null,
47         bool $keepRatio = true
48     ): Image {
49         $imageName = $uploadedFile->getClientOriginalName();
50         $imageData = file_get_contents($uploadedFile->getRealPath());
51
52         if ($resizeWidth !== null || $resizeHeight !== null) {
53             $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
54         }
55
56         return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
57     }
58
59     /**
60      * Save a new image from a uri-encoded base64 string of data.
61      *
62      * @throws ImageUploadException
63      */
64     public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
65     {
66         $splitData = explode(';base64,', $base64Uri);
67         if (count($splitData) < 2) {
68             throw new ImageUploadException('Invalid base64 image data provided');
69         }
70         $data = base64_decode($splitData[1]);
71
72         return $this->saveNew($name, $data, $type, $uploadedTo);
73     }
74
75     /**
76      * Save a new image into storage.
77      *
78      * @throws ImageUploadException
79      */
80     public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
81     {
82         $disk = $this->storage->getDisk($type);
83         $secureUploads = setting('app-secure-images');
84         $fileName = $this->storage->cleanImageFileName($imageName);
85
86         $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
87
88         while ($disk->exists($this->storage->adjustPathForDisk($imagePath . $fileName, $type))) {
89             $fileName = Str::random(3) . $fileName;
90         }
91
92         $fullPath = $imagePath . $fileName;
93         if ($secureUploads) {
94             $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
95         }
96
97         try {
98             $this->storage->storeInPublicSpace($disk, $this->storage->adjustPathForDisk($fullPath, $type), $imageData);
99         } catch (Exception $e) {
100             Log::error('Error when attempting image upload:' . $e->getMessage());
101
102             throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
103         }
104
105         $imageDetails = [
106             'name'        => $imageName,
107             'path'        => $fullPath,
108             'url'         => $this->storage->getPublicUrl($fullPath),
109             'type'        => $type,
110             'uploaded_to' => $uploadedTo,
111         ];
112
113         if (user()->id !== 0) {
114             $userId = user()->id;
115             $imageDetails['created_by'] = $userId;
116             $imageDetails['updated_by'] = $userId;
117         }
118
119         $image = (new Image())->forceFill($imageDetails);
120         $image->save();
121
122         return $image;
123     }
124
125     /**
126      * Replace an existing image file in the system using the given file.
127      */
128     public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
129     {
130         $imageData = file_get_contents($file->getRealPath());
131         $disk = $this->storage->getDisk($type);
132         $adjustedPath = $this->storage->adjustPathForDisk($path, $type);
133         $disk->put($adjustedPath, $imageData);
134     }
135
136
137     /**
138      * Checks if the image is a gif. Returns true if it is, else false.
139      */
140     protected function isGif(Image $image): bool
141     {
142         return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
143     }
144
145     /**
146      * Check if the given image and image data is apng.
147      */
148     protected function isApngData(Image $image, string &$imageData): bool
149     {
150         $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
151         if (!$isPng) {
152             return false;
153         }
154
155         $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
156
157         return str_contains($initialHeader, 'acTL');
158     }
159
160     /**
161      * Get the thumbnail for an image.
162      * If $keepRatio is true only the width will be used.
163      * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
164      *
165      * @throws Exception
166      */
167     public function getThumbnail(
168         Image $image,
169         ?int $width,
170         ?int $height,
171         bool $keepRatio = false,
172         bool $shouldCreate = false,
173         bool $canCreate = false,
174     ): ?string {
175         // Do not resize GIF images where we're not cropping
176         if ($keepRatio && $this->isGif($image)) {
177             return $this->storage->getPublicUrl($image->path);
178         }
179
180         $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
181         $imagePath = $image->path;
182         $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
183
184         $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
185
186         // Return path if in cache
187         $cachedThumbPath = $this->cache->get($thumbCacheKey);
188         if ($cachedThumbPath && !$shouldCreate) {
189             return $this->storage->getPublicUrl($cachedThumbPath);
190         }
191
192         // If thumbnail has already been generated, serve that and cache path
193         $disk = $this->storage->getDisk($image->type);
194         if (!$shouldCreate && $disk->exists($this->storage->adjustPathForDisk($thumbFilePath, $image->type))) {
195             $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
196
197             return $this->storage->getPublicUrl($thumbFilePath);
198         }
199
200         $imageData = $disk->get($this->storage->adjustPathForDisk($imagePath, $image->type));
201
202         // Do not resize apng images where we're not cropping
203         if ($keepRatio && $this->isApngData($image, $imageData)) {
204             $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
205
206             return $this->storage->getPublicUrl($image->path);
207         }
208
209         if (!$shouldCreate && !$canCreate) {
210             return null;
211         }
212
213         // If not in cache and thumbnail does not exist, generate thumb and cache path
214         $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
215         $this->storage->storeInPublicSpace($disk, $this->storage->adjustPathForDisk($thumbFilePath, $image->type), $thumbData);
216         $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
217
218         return $this->storage->getPublicUrl($thumbFilePath);
219     }
220
221     /**
222      * Resize the image of given data to the specified size, and return the new image data.
223      *
224      * @throws ImageUploadException
225      */
226     protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
227     {
228         try {
229             $thumb = $this->imageTool->make($imageData);
230         } catch (ErrorException | NotSupportedException $e) {
231             throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
232         }
233
234         $this->orientImageToOriginalExif($thumb, $imageData);
235
236         if ($keepRatio) {
237             $thumb->resize($width, $height, function ($constraint) {
238                 $constraint->aspectRatio();
239                 $constraint->upsize();
240             });
241         } else {
242             $thumb->fit($width, $height);
243         }
244
245         $thumbData = (string) $thumb->encode();
246
247         // Use original image data if we're keeping the ratio
248         // and the resizing does not save any space.
249         if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
250             return $imageData;
251         }
252
253         return $thumbData;
254     }
255
256
257     /**
258      * Get the raw data content from an image.
259      *
260      * @throws Exception
261      */
262     public function getImageData(Image $image): string
263     {
264         $disk = $this->storage->getDisk();
265
266         return $disk->get($this->storage->adjustPathForDisk($image->path, $image->type));
267     }
268
269     /**
270      * Destroy an image along with its revisions, thumbnails and remaining folders.
271      *
272      * @throws Exception
273      */
274     public function destroy(Image $image)
275     {
276         $this->destroyImagesFromPath($image->path, $image->type);
277         $image->delete();
278     }
279
280     /**
281      * Destroys an image at the given path.
282      * Searches for image thumbnails in addition to main provided path.
283      */
284     protected function destroyImagesFromPath(string $path, string $imageType): bool
285     {
286         $path = $this->storage->adjustPathForDisk($path, $imageType);
287         $disk = $this->storage->getDisk($imageType);
288
289         $imageFolder = dirname($path);
290         $imageFileName = basename($path);
291         $allImages = collect($disk->allFiles($imageFolder));
292
293         // Delete image files
294         $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
295             return basename($imagePath) === $imageFileName;
296         });
297         $disk->delete($imagesToDelete->all());
298
299         // Cleanup of empty folders
300         $foldersInvolved = array_merge([$imageFolder], $disk->directories($imageFolder));
301         foreach ($foldersInvolved as $directory) {
302             if ($this->isFolderEmpty($disk, $directory)) {
303                 $disk->deleteDirectory($directory);
304             }
305         }
306
307         return true;
308     }
309
310     /**
311      * Check whether a folder is empty.
312      */
313     protected function isFolderEmpty(StorageDisk $storage, string $path): bool
314     {
315         $files = $storage->files($path);
316         $folders = $storage->directories($path);
317
318         return count($files) === 0 && count($folders) === 0;
319     }
320
321     /**
322      * Delete gallery and drawings that are not within HTML content of pages or page revisions.
323      * Checks based off of only the image name.
324      * Could be much improved to be more specific but kept it generic for now to be safe.
325      *
326      * Returns the path of the images that would be/have been deleted.
327      */
328     public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
329     {
330         $types = ['gallery', 'drawio'];
331         $deletedPaths = [];
332
333         Image::query()->whereIn('type', $types)
334             ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
335                 /** @var Image $image */
336                 foreach ($images as $image) {
337                     $searchQuery = '%' . basename($image->path) . '%';
338                     $inPage = DB::table('pages')
339                             ->where('html', 'like', $searchQuery)->count() > 0;
340
341                     $inRevision = false;
342                     if ($checkRevisions) {
343                         $inRevision = DB::table('page_revisions')
344                                 ->where('html', 'like', $searchQuery)->count() > 0;
345                     }
346
347                     if (!$inPage && !$inRevision) {
348                         $deletedPaths[] = $image->path;
349                         if (!$dryRun) {
350                             $this->destroy($image);
351                         }
352                     }
353                 }
354             });
355
356         return $deletedPaths;
357     }
358
359     /**
360      * Convert an image URI to a Base64 encoded string.
361      * Attempts to convert the URL to a system storage url then
362      * fetch the data from the disk or storage location.
363      * Returns null if the image data cannot be fetched from storage.
364      *
365      * @throws FileNotFoundException
366      */
367     public function imageUrlToBase64(string $url): ?string
368     {
369         $storagePath = $this->storage->urlToPath($url);
370         if (empty($url) || is_null($storagePath)) {
371             return null;
372         }
373
374         $storagePath = $this->storage->adjustPathForDisk($storagePath);
375
376         // Apply access control when local_secure_restricted images are active
377         if ($this->storage->usingSecureRestrictedImages()) {
378             if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
379                 return null;
380             }
381         }
382
383         $disk = $this->storage->getDisk();
384         $imageData = null;
385         if ($disk->exists($storagePath)) {
386             $imageData = $disk->get($storagePath);
387         }
388
389         if (is_null($imageData)) {
390             return null;
391         }
392
393         $extension = pathinfo($url, PATHINFO_EXTENSION);
394         if ($extension === 'svg') {
395             $extension = 'svg+xml';
396         }
397
398         return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
399     }
400
401     /**
402      * Check if the given path exists and is accessible in the local secure image system.
403      * Returns false if local_secure is not in use, if the file does not exist, if the
404      * file is likely not a valid image, or if permission does not allow access.
405      */
406     public function pathAccessibleInLocalSecure(string $imagePath): bool
407     {
408         $disk = $this->storage->getDisk('gallery');
409
410         if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
411             return false;
412         }
413
414         // Check local_secure is active
415         return $this->storage->usingSecureImages()
416             && $disk instanceof FilesystemAdapter
417             // Check the image file exists
418             && $disk->exists($imagePath)
419             // Check the file is likely an image file
420             && str_starts_with($disk->mimeType($imagePath), 'image/');
421     }
422
423     /**
424      * Check that the current user has access to the relation
425      * of the image at the given path.
426      */
427     protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
428     {
429         if (str_starts_with($path, '/uploads/images/')) {
430             $path = substr($path, 15);
431         }
432
433         // Strip thumbnail element from path if existing
434         $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
435             $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
436             $missingExtension = !str_contains($part, '.');
437
438             return !($resizedDir && $missingExtension);
439         });
440
441         // Build a database-format image path and search for the image entry
442         $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
443         $image = Image::query()->where('path', '=', $fullPath)->first();
444
445         if (is_null($image)) {
446             return false;
447         }
448
449         $imageType = $image->type;
450
451         // Allow user or system (logo) images
452         // (No specific relation control but may still have access controlled by auth)
453         if ($imageType === 'user' || $imageType === 'system') {
454             return true;
455         }
456
457         if ($imageType === 'gallery' || $imageType === 'drawio') {
458             return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
459         }
460
461         if ($imageType === 'cover_book') {
462             return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
463         }
464
465         if ($imageType === 'cover_bookshelf') {
466             return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
467         }
468
469         return false;
470     }
471
472     /**
473      * For the given path, if existing, provide a response that will stream the image contents.
474      */
475     public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
476     {
477         $disk = $this->storage->getDisk($imageType);
478
479         return $disk->response($path);
480     }
481
482     /**
483      * Check if the given image extension is supported by BookStack.
484      * The extension must not be altered in this function. This check should provide a guarantee
485      * that the provided extension is safe to use for the image to be saved.
486      */
487     public static function isExtensionSupported(string $extension): bool
488     {
489         return in_array($extension, static::$supportedExtensions);
490     }
491 }