3 namespace BookStack\Uploads;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Exceptions\ImageUploadException;
11 use GuzzleHttp\Psr7\Utils;
12 use Illuminate\Contracts\Cache\Repository as Cache;
13 use Illuminate\Contracts\Filesystem\FileNotFoundException;
14 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
15 use Illuminate\Filesystem\FilesystemAdapter;
16 use Illuminate\Filesystem\FilesystemManager;
17 use Illuminate\Support\Facades\DB;
18 use Illuminate\Support\Facades\Log;
19 use Illuminate\Support\Str;
20 use Intervention\Image\Exception\NotSupportedException;
21 use Intervention\Image\Image as InterventionImage;
22 use Intervention\Image\ImageManager;
23 use League\Flysystem\Util;
24 use Psr\SimpleCache\InvalidArgumentException;
25 use Symfony\Component\HttpFoundation\File\UploadedFile;
26 use Symfony\Component\HttpFoundation\StreamedResponse;
30 protected ImageManager $imageTool;
31 protected Cache $cache;
32 protected $storageUrl;
33 protected FilesystemManager $fileSystem;
35 protected static $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
37 public function __construct(ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
39 $this->imageTool = $imageTool;
40 $this->fileSystem = $fileSystem;
41 $this->cache = $cache;
45 * Get the storage that will be used for storing images.
47 protected function getStorageDisk(string $imageType = ''): Storage
49 return $this->fileSystem->disk($this->getStorageDiskName($imageType));
53 * Check if local secure image storage (Fetched behind authentication)
54 * is currently active in the instance.
56 protected function usingSecureImages(string $imageType = 'gallery'): bool
58 return $this->getStorageDiskName($imageType) === 'local_secure_images';
62 * Check if "local secure restricted" (Fetched behind auth, with permissions enforced)
63 * is currently active in the instance.
65 protected function usingSecureRestrictedImages()
67 return config('filesystems.images') === 'local_secure_restricted';
71 * Change the originally provided path to fit any disk-specific requirements.
72 * This also ensures the path is kept to the expected root folders.
74 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
76 $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
78 if ($this->usingSecureImages($imageType)) {
82 return 'uploads/images/' . $path;
86 * Get the name of the storage disk to use.
88 protected function getStorageDiskName(string $imageType): string
90 $storageType = config('filesystems.images');
91 $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted');
93 // Ensure system images (App logo) are uploaded to a public space
94 if ($imageType === 'system' && $localSecureInUse) {
98 // Rename local_secure options to get our image specific storage driver which
99 // is scoped to the relevant image directories.
100 if ($localSecureInUse) {
101 return 'local_secure_images';
108 * Saves a new image from an upload.
110 * @throws ImageUploadException
114 public function saveNewFromUpload(
115 UploadedFile $uploadedFile,
118 int $resizeWidth = null,
119 int $resizeHeight = null,
120 bool $keepRatio = true
122 $imageName = $uploadedFile->getClientOriginalName();
123 $imageData = file_get_contents($uploadedFile->getRealPath());
125 if ($resizeWidth !== null || $resizeHeight !== null) {
126 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
129 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
133 * Save a new image from a uri-encoded base64 string of data.
135 * @throws ImageUploadException
137 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
139 $splitData = explode(';base64,', $base64Uri);
140 if (count($splitData) < 2) {
141 throw new ImageUploadException('Invalid base64 image data provided');
143 $data = base64_decode($splitData[1]);
145 return $this->saveNew($name, $data, $type, $uploadedTo);
149 * Save a new image into storage.
151 * @throws ImageUploadException
153 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
155 $storage = $this->getStorageDisk($type);
156 $secureUploads = setting('app-secure-images');
157 $fileName = $this->cleanImageFileName($imageName);
159 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
161 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
162 $fileName = Str::random(3) . $fileName;
165 $fullPath = $imagePath . $fileName;
166 if ($secureUploads) {
167 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
171 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
172 } catch (Exception $e) {
173 Log::error('Error when attempting image upload:' . $e->getMessage());
175 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
179 'name' => $imageName,
181 'url' => $this->getPublicUrl($fullPath),
183 'uploaded_to' => $uploadedTo,
186 if (user()->id !== 0) {
187 $userId = user()->id;
188 $imageDetails['created_by'] = $userId;
189 $imageDetails['updated_by'] = $userId;
192 $image = (new Image())->forceFill($imageDetails);
199 * Save image data for the given path in the public space, if possible,
200 * for the provided storage mechanism.
202 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
204 $storage->put($path, $data);
206 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
207 // Done since this call can break s3-like services but desired for other image stores.
208 // Attempting to set ACL during above put request requires different permissions
209 // hence would technically be a breaking change for actual s3 usage.
210 $usingS3 = strtolower(config('filesystems.images')) === 's3';
211 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
213 $storage->setVisibility($path, 'public');
218 * Clean up an image file name to be both URL and storage safe.
220 protected function cleanImageFileName(string $name): string
222 $name = str_replace(' ', '-', $name);
223 $nameParts = explode('.', $name);
224 $extension = array_pop($nameParts);
225 $name = implode('-', $nameParts);
226 $name = Str::slug($name);
228 if (strlen($name) === 0) {
229 $name = Str::random(10);
232 return $name . '.' . $extension;
236 * Checks if the image is a gif. Returns true if it is, else false.
238 protected function isGif(Image $image): bool
240 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
244 * Check if the given image and image data is apng.
246 protected function isApngData(Image $image, string &$imageData): bool
248 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
253 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
255 return strpos($initialHeader, 'acTL') !== false;
259 * Get the thumbnail for an image.
260 * If $keepRatio is true only the width will be used.
261 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
264 * @throws InvalidArgumentException
266 public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false): string
268 // Do not resize GIF images where we're not cropping
269 if ($keepRatio && $this->isGif($image)) {
270 return $this->getPublicUrl($image->path);
273 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
274 $imagePath = $image->path;
275 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
277 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
279 // Return path if in cache
280 $cachedThumbPath = $this->cache->get($thumbCacheKey);
281 if ($cachedThumbPath) {
282 return $this->getPublicUrl($cachedThumbPath);
285 // If thumbnail has already been generated, serve that and cache path
286 $storage = $this->getStorageDisk($image->type);
287 if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
288 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
290 return $this->getPublicUrl($thumbFilePath);
293 $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
295 // Do not resize apng images where we're not cropping
296 if ($keepRatio && $this->isApngData($image, $imageData)) {
297 $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
299 return $this->getPublicUrl($image->path);
302 // If not in cache and thumbnail does not exist, generate thumb and cache path
303 $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
304 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
305 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
307 return $this->getPublicUrl($thumbFilePath);
311 * Resize the image of given data to the specified size, and return the new image data.
313 * @throws ImageUploadException
315 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
318 $thumb = $this->imageTool->make($imageData);
319 } catch (ErrorException | NotSupportedException $e) {
320 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
323 $this->orientImageToOriginalExif($thumb, $imageData);
326 $thumb->resize($width, $height, function ($constraint) {
327 $constraint->aspectRatio();
328 $constraint->upsize();
331 $thumb->fit($width, $height);
334 $thumbData = (string) $thumb->encode();
336 // Use original image data if we're keeping the ratio
337 // and the resizing does not save any space.
338 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
346 * Orientate the given intervention image based upon the given original image data.
347 * Intervention does have an `orientate` method but the exif data it needs is lost before it
348 * can be used (At least when created using binary string data) so we need to do some
349 * implementation on our side to use the original image data.
350 * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
351 * Copyright (c) Oliver Vogel, MIT License.
353 protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
355 if (!extension_loaded('exif')) {
359 $stream = Utils::streamFor($originalData)->detach();
360 $exif = @exif_read_data($stream);
361 $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
363 switch ($orientation) {
371 $image->rotate(180)->flip();
374 $image->rotate(270)->flip();
380 $image->rotate(90)->flip();
389 * Get the raw data content from an image.
391 * @throws FileNotFoundException
393 public function getImageData(Image $image): string
395 $storage = $this->getStorageDisk();
397 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
401 * Destroy an image along with its revisions, thumbnails and remaining folders.
405 public function destroy(Image $image)
407 $this->destroyImagesFromPath($image->path, $image->type);
412 * Destroys an image at the given path.
413 * Searches for image thumbnails in addition to main provided path.
415 protected function destroyImagesFromPath(string $path, string $imageType): bool
417 $path = $this->adjustPathForStorageDisk($path, $imageType);
418 $storage = $this->getStorageDisk($imageType);
420 $imageFolder = dirname($path);
421 $imageFileName = basename($path);
422 $allImages = collect($storage->allFiles($imageFolder));
424 // Delete image files
425 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
426 return basename($imagePath) === $imageFileName;
428 $storage->delete($imagesToDelete->all());
430 // Cleanup of empty folders
431 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
432 foreach ($foldersInvolved as $directory) {
433 if ($this->isFolderEmpty($storage, $directory)) {
434 $storage->deleteDirectory($directory);
442 * Check whether a folder is empty.
444 protected function isFolderEmpty(Storage $storage, string $path): bool
446 $files = $storage->files($path);
447 $folders = $storage->directories($path);
449 return count($files) === 0 && count($folders) === 0;
453 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
454 * Checks based off of only the image name.
455 * Could be much improved to be more specific but kept it generic for now to be safe.
457 * Returns the path of the images that would be/have been deleted.
459 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
461 $types = ['gallery', 'drawio'];
464 Image::query()->whereIn('type', $types)
465 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
466 foreach ($images as $image) {
467 $searchQuery = '%' . basename($image->path) . '%';
468 $inPage = DB::table('pages')
469 ->where('html', 'like', $searchQuery)->count() > 0;
472 if ($checkRevisions) {
473 $inRevision = DB::table('page_revisions')
474 ->where('html', 'like', $searchQuery)->count() > 0;
477 if (!$inPage && !$inRevision) {
478 $deletedPaths[] = $image->path;
480 $this->destroy($image);
486 return $deletedPaths;
490 * Convert an image URI to a Base64 encoded string.
491 * Attempts to convert the URL to a system storage url then
492 * fetch the data from the disk or storage location.
493 * Returns null if the image data cannot be fetched from storage.
495 * @throws FileNotFoundException
497 public function imageUriToBase64(string $uri): ?string
499 $storagePath = $this->imageUrlToStoragePath($uri);
500 if (empty($uri) || is_null($storagePath)) {
504 $storagePath = $this->adjustPathForStorageDisk($storagePath);
506 // Apply access control when local_secure_restricted images are active
507 if ($this->usingSecureRestrictedImages()) {
508 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
513 $storage = $this->getStorageDisk();
515 if ($storage->exists($storagePath)) {
516 $imageData = $storage->get($storagePath);
519 if (is_null($imageData)) {
523 $extension = pathinfo($uri, PATHINFO_EXTENSION);
524 if ($extension === 'svg') {
525 $extension = 'svg+xml';
528 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
532 * Check if the given path exists and is accessible in the local secure image system.
533 * Returns false if local_secure is not in use, if the file does not exist, if the
534 * file is likely not a valid image, or if permission does not allow access.
536 public function pathAccessibleInLocalSecure(string $imagePath): bool
538 /** @var FilesystemAdapter $disk */
539 $disk = $this->getStorageDisk('gallery');
541 if ($this->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
545 // Check local_secure is active
546 return $this->usingSecureImages()
547 && $disk instanceof FilesystemAdapter
548 // Check the image file exists
549 && $disk->exists($imagePath)
550 // Check the file is likely an image file
551 && strpos($disk->getMimetype($imagePath), 'image/') === 0;
555 * Check that the current user has access to the relation
556 * of the image at the given path.
558 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
560 if (strpos($path, '/uploads/images/') === 0) {
561 $path = substr($path, 15);
564 // Strip thumbnail element from path if existing
565 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
566 $resizedDir = (strpos($part, 'thumbs-') === 0 || strpos($part, 'scaled-') === 0);
567 $missingExtension = strpos($part, '.') === false;
569 return !($resizedDir && $missingExtension);
572 // Build a database-format image path and search for the image entry
573 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
574 $image = Image::query()->where('path', '=', $fullPath)->first();
576 if (is_null($image)) {
580 $imageType = $image->type;
582 // Allow user or system (logo) images
583 // (No specific relation control but may still have access controlled by auth)
584 if ($imageType === 'user' || $imageType === 'system') {
588 if ($imageType === 'gallery' || $imageType === 'drawio') {
589 return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
592 if ($imageType === 'cover_book') {
593 return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
596 if ($imageType === 'cover_bookshelf') {
597 return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
604 * For the given path, if existing, provide a response that will stream the image contents.
606 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
608 $disk = $this->getStorageDisk($imageType);
610 return $disk->response($path);
614 * Check if the given image extension is supported by BookStack.
615 * The extension must not be altered in this function. This check should provide a guarantee
616 * that the provided extension is safe to use for the image to be saved.
618 public static function isExtensionSupported(string $extension): bool
620 return in_array($extension, static::$supportedExtensions);
624 * Get a storage path for the given image URL.
625 * Ensures the path will start with "uploads/images".
626 * Returns null if the url cannot be resolved to a local URL.
628 private function imageUrlToStoragePath(string $url): ?string
630 $url = ltrim(trim($url), '/');
632 // Handle potential relative paths
633 $isRelative = strpos($url, 'http') !== 0;
635 if (strpos(strtolower($url), 'uploads/images') === 0) {
636 return trim($url, '/');
642 // Handle local images based on paths on the same domain
643 $potentialHostPaths = [
644 url('uploads/images/'),
645 $this->getPublicUrl('/uploads/images/'),
648 foreach ($potentialHostPaths as $potentialBasePath) {
649 $potentialBasePath = strtolower($potentialBasePath);
650 if (strpos(strtolower($url), $potentialBasePath) === 0) {
651 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
659 * Gets a public facing url for an image by checking relevant environment variables.
660 * If s3-style store is in use it will default to guessing a public bucket URL.
662 private function getPublicUrl(string $filePath): string
664 if (is_null($this->storageUrl)) {
665 $storageUrl = config('filesystems.url');
667 // Get the standard public s3 url if s3 is set as storage type
668 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
669 // region-based url will be used to prevent http issues.
670 if ($storageUrl == false && config('filesystems.images') === 's3') {
671 $storageDetails = config('filesystems.disks.s3');
672 if (strpos($storageDetails['bucket'], '.') === false) {
673 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
675 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
679 $this->storageUrl = $storageUrl;
682 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
684 return rtrim($basePath, '/') . $filePath;