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\WhitespacePathNormalizer;
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 FilesystemManager $fileSystem;
34 protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
36 public function __construct(ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
38 $this->imageTool = $imageTool;
39 $this->fileSystem = $fileSystem;
40 $this->cache = $cache;
44 * Get the storage that will be used for storing images.
46 protected function getStorageDisk(string $imageType = ''): Storage
48 return $this->fileSystem->disk($this->getStorageDiskName($imageType));
52 * Check if local secure image storage (Fetched behind authentication)
53 * is currently active in the instance.
55 protected function usingSecureImages(string $imageType = 'gallery'): bool
57 return $this->getStorageDiskName($imageType) === 'local_secure_images';
61 * Check if "local secure restricted" (Fetched behind auth, with permissions enforced)
62 * is currently active in the instance.
64 protected function usingSecureRestrictedImages()
66 return config('filesystems.images') === 'local_secure_restricted';
70 * Change the originally provided path to fit any disk-specific requirements.
71 * This also ensures the path is kept to the expected root folders.
73 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
75 $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/images/', '', $path));
77 if ($this->usingSecureImages($imageType)) {
81 return 'uploads/images/' . $path;
85 * Get the name of the storage disk to use.
87 protected function getStorageDiskName(string $imageType): string
89 $storageType = config('filesystems.images');
90 $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted');
92 // Ensure system images (App logo) are uploaded to a public space
93 if ($imageType === 'system' && $localSecureInUse) {
97 // Rename local_secure options to get our image specific storage driver which
98 // is scoped to the relevant image directories.
99 if ($localSecureInUse) {
100 return 'local_secure_images';
107 * Saves a new image from an upload.
109 * @throws ImageUploadException
113 public function saveNewFromUpload(
114 UploadedFile $uploadedFile,
117 int $resizeWidth = null,
118 int $resizeHeight = null,
119 bool $keepRatio = true
121 $imageName = $uploadedFile->getClientOriginalName();
122 $imageData = file_get_contents($uploadedFile->getRealPath());
124 if ($resizeWidth !== null || $resizeHeight !== null) {
125 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
128 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
132 * Save a new image from a uri-encoded base64 string of data.
134 * @throws ImageUploadException
136 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
138 $splitData = explode(';base64,', $base64Uri);
139 if (count($splitData) < 2) {
140 throw new ImageUploadException('Invalid base64 image data provided');
142 $data = base64_decode($splitData[1]);
144 return $this->saveNew($name, $data, $type, $uploadedTo);
148 * Save a new image into storage.
150 * @throws ImageUploadException
152 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
154 $storage = $this->getStorageDisk($type);
155 $secureUploads = setting('app-secure-images');
156 $fileName = $this->cleanImageFileName($imageName);
158 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
160 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
161 $fileName = Str::random(3) . $fileName;
164 $fullPath = $imagePath . $fileName;
165 if ($secureUploads) {
166 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
170 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
171 } catch (Exception $e) {
172 Log::error('Error when attempting image upload:' . $e->getMessage());
174 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
178 'name' => $imageName,
180 'url' => $this->getPublicUrl($fullPath),
182 'uploaded_to' => $uploadedTo,
185 if (user()->id !== 0) {
186 $userId = user()->id;
187 $imageDetails['created_by'] = $userId;
188 $imageDetails['updated_by'] = $userId;
191 $image = (new Image())->forceFill($imageDetails);
197 public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
199 $imageData = file_get_contents($file->getRealPath());
200 $storage = $this->getStorageDisk($type);
201 $adjustedPath = $this->adjustPathForStorageDisk($path, $type);
202 $storage->put($adjustedPath, $imageData);
206 * Save image data for the given path in the public space, if possible,
207 * for the provided storage mechanism.
209 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
211 $storage->put($path, $data);
213 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
214 // Done since this call can break s3-like services but desired for other image stores.
215 // Attempting to set ACL during above put request requires different permissions
216 // hence would technically be a breaking change for actual s3 usage.
217 $usingS3 = strtolower(config('filesystems.images')) === 's3';
218 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
220 $storage->setVisibility($path, 'public');
225 * Clean up an image file name to be both URL and storage safe.
227 protected function cleanImageFileName(string $name): string
229 $name = str_replace(' ', '-', $name);
230 $nameParts = explode('.', $name);
231 $extension = array_pop($nameParts);
232 $name = implode('-', $nameParts);
233 $name = Str::slug($name);
235 if (strlen($name) === 0) {
236 $name = Str::random(10);
239 return $name . '.' . $extension;
243 * Checks if the image is a gif. Returns true if it is, else false.
245 protected function isGif(Image $image): bool
247 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
251 * Check if the given image and image data is apng.
253 protected function isApngData(Image $image, string &$imageData): bool
255 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
260 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
262 return strpos($initialHeader, 'acTL') !== false;
266 * Get the thumbnail for an image.
267 * If $keepRatio is true only the width will be used.
268 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
271 * @throws InvalidArgumentException
273 public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false, bool $forceCreate = false): string
275 // Do not resize GIF images where we're not cropping
276 if ($keepRatio && $this->isGif($image)) {
277 return $this->getPublicUrl($image->path);
280 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
281 $imagePath = $image->path;
282 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
284 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
286 // Return path if in cache
287 $cachedThumbPath = $this->cache->get($thumbCacheKey);
288 if ($cachedThumbPath && !$forceCreate) {
289 return $this->getPublicUrl($cachedThumbPath);
292 // If thumbnail has already been generated, serve that and cache path
293 $storage = $this->getStorageDisk($image->type);
294 if (!$forceCreate && $storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
295 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
297 return $this->getPublicUrl($thumbFilePath);
300 $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
302 // Do not resize apng images where we're not cropping
303 if ($keepRatio && $this->isApngData($image, $imageData)) {
304 $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
306 return $this->getPublicUrl($image->path);
309 // If not in cache and thumbnail does not exist, generate thumb and cache path
310 $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
311 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
312 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
314 return $this->getPublicUrl($thumbFilePath);
318 * Resize the image of given data to the specified size, and return the new image data.
320 * @throws ImageUploadException
322 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
325 $thumb = $this->imageTool->make($imageData);
326 } catch (ErrorException | NotSupportedException $e) {
327 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
330 $this->orientImageToOriginalExif($thumb, $imageData);
333 $thumb->resize($width, $height, function ($constraint) {
334 $constraint->aspectRatio();
335 $constraint->upsize();
338 $thumb->fit($width, $height);
341 $thumbData = (string) $thumb->encode();
343 // Use original image data if we're keeping the ratio
344 // and the resizing does not save any space.
345 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
353 * Orientate the given intervention image based upon the given original image data.
354 * Intervention does have an `orientate` method but the exif data it needs is lost before it
355 * can be used (At least when created using binary string data) so we need to do some
356 * implementation on our side to use the original image data.
357 * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
358 * Copyright (c) Oliver Vogel, MIT License.
360 protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
362 if (!extension_loaded('exif')) {
366 $stream = Utils::streamFor($originalData)->detach();
367 $exif = @exif_read_data($stream);
368 $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
370 switch ($orientation) {
378 $image->rotate(180)->flip();
381 $image->rotate(270)->flip();
387 $image->rotate(90)->flip();
396 * Get the raw data content from an image.
398 * @throws FileNotFoundException
400 public function getImageData(Image $image): string
402 $storage = $this->getStorageDisk();
404 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
408 * Destroy an image along with its revisions, thumbnails and remaining folders.
412 public function destroy(Image $image)
414 $this->destroyImagesFromPath($image->path, $image->type);
419 * Destroys an image at the given path.
420 * Searches for image thumbnails in addition to main provided path.
422 protected function destroyImagesFromPath(string $path, string $imageType): bool
424 $path = $this->adjustPathForStorageDisk($path, $imageType);
425 $storage = $this->getStorageDisk($imageType);
427 $imageFolder = dirname($path);
428 $imageFileName = basename($path);
429 $allImages = collect($storage->allFiles($imageFolder));
431 // Delete image files
432 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
433 return basename($imagePath) === $imageFileName;
435 $storage->delete($imagesToDelete->all());
437 // Cleanup of empty folders
438 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
439 foreach ($foldersInvolved as $directory) {
440 if ($this->isFolderEmpty($storage, $directory)) {
441 $storage->deleteDirectory($directory);
449 * Check whether a folder is empty.
451 protected function isFolderEmpty(Storage $storage, string $path): bool
453 $files = $storage->files($path);
454 $folders = $storage->directories($path);
456 return count($files) === 0 && count($folders) === 0;
460 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
461 * Checks based off of only the image name.
462 * Could be much improved to be more specific but kept it generic for now to be safe.
464 * Returns the path of the images that would be/have been deleted.
466 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
468 $types = ['gallery', 'drawio'];
471 Image::query()->whereIn('type', $types)
472 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
473 /** @var Image $image */
474 foreach ($images as $image) {
475 $searchQuery = '%' . basename($image->path) . '%';
476 $inPage = DB::table('pages')
477 ->where('html', 'like', $searchQuery)->count() > 0;
480 if ($checkRevisions) {
481 $inRevision = DB::table('page_revisions')
482 ->where('html', 'like', $searchQuery)->count() > 0;
485 if (!$inPage && !$inRevision) {
486 $deletedPaths[] = $image->path;
488 $this->destroy($image);
494 return $deletedPaths;
498 * Convert an image URI to a Base64 encoded string.
499 * Attempts to convert the URL to a system storage url then
500 * fetch the data from the disk or storage location.
501 * Returns null if the image data cannot be fetched from storage.
503 * @throws FileNotFoundException
505 public function imageUriToBase64(string $uri): ?string
507 $storagePath = $this->imageUrlToStoragePath($uri);
508 if (empty($uri) || is_null($storagePath)) {
512 $storagePath = $this->adjustPathForStorageDisk($storagePath);
514 // Apply access control when local_secure_restricted images are active
515 if ($this->usingSecureRestrictedImages()) {
516 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
521 $storage = $this->getStorageDisk();
523 if ($storage->exists($storagePath)) {
524 $imageData = $storage->get($storagePath);
527 if (is_null($imageData)) {
531 $extension = pathinfo($uri, PATHINFO_EXTENSION);
532 if ($extension === 'svg') {
533 $extension = 'svg+xml';
536 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
540 * Check if the given path exists and is accessible in the local secure image system.
541 * Returns false if local_secure is not in use, if the file does not exist, if the
542 * file is likely not a valid image, or if permission does not allow access.
544 public function pathAccessibleInLocalSecure(string $imagePath): bool
546 /** @var FilesystemAdapter $disk */
547 $disk = $this->getStorageDisk('gallery');
549 if ($this->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
553 // Check local_secure is active
554 return $this->usingSecureImages()
555 && $disk instanceof FilesystemAdapter
556 // Check the image file exists
557 && $disk->exists($imagePath)
558 // Check the file is likely an image file
559 && strpos($disk->mimeType($imagePath), 'image/') === 0;
563 * Check that the current user has access to the relation
564 * of the image at the given path.
566 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
568 if (strpos($path, '/uploads/images/') === 0) {
569 $path = substr($path, 15);
572 // Strip thumbnail element from path if existing
573 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
574 $resizedDir = (strpos($part, 'thumbs-') === 0 || strpos($part, 'scaled-') === 0);
575 $missingExtension = strpos($part, '.') === false;
577 return !($resizedDir && $missingExtension);
580 // Build a database-format image path and search for the image entry
581 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
582 $image = Image::query()->where('path', '=', $fullPath)->first();
584 if (is_null($image)) {
588 $imageType = $image->type;
590 // Allow user or system (logo) images
591 // (No specific relation control but may still have access controlled by auth)
592 if ($imageType === 'user' || $imageType === 'system') {
596 if ($imageType === 'gallery' || $imageType === 'drawio') {
597 return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
600 if ($imageType === 'cover_book') {
601 return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
604 if ($imageType === 'cover_bookshelf') {
605 return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
612 * For the given path, if existing, provide a response that will stream the image contents.
614 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
616 $disk = $this->getStorageDisk($imageType);
618 return $disk->response($path);
622 * Check if the given image extension is supported by BookStack.
623 * The extension must not be altered in this function. This check should provide a guarantee
624 * that the provided extension is safe to use for the image to be saved.
626 public static function isExtensionSupported(string $extension): bool
628 return in_array($extension, static::$supportedExtensions);
632 * Get a storage path for the given image URL.
633 * Ensures the path will start with "uploads/images".
634 * Returns null if the url cannot be resolved to a local URL.
636 private function imageUrlToStoragePath(string $url): ?string
638 $url = ltrim(trim($url), '/');
640 // Handle potential relative paths
641 $isRelative = strpos($url, 'http') !== 0;
643 if (strpos(strtolower($url), 'uploads/images') === 0) {
644 return trim($url, '/');
650 // Handle local images based on paths on the same domain
651 $potentialHostPaths = [
652 url('uploads/images/'),
653 $this->getPublicUrl('/uploads/images/'),
656 foreach ($potentialHostPaths as $potentialBasePath) {
657 $potentialBasePath = strtolower($potentialBasePath);
658 if (strpos(strtolower($url), $potentialBasePath) === 0) {
659 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
667 * Gets a public facing url for an image by checking relevant environment variables.
668 * If s3-style store is in use it will default to guessing a public bucket URL.
670 private function getPublicUrl(string $filePath): string
672 $storageUrl = config('filesystems.url');
674 // Get the standard public s3 url if s3 is set as storage type
675 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
676 // region-based url will be used to prevent http issues.
677 if (!$storageUrl && config('filesystems.images') === 's3') {
678 $storageDetails = config('filesystems.disks.s3');
679 if (strpos($storageDetails['bucket'], '.') === false) {
680 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
682 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
686 $basePath = $storageUrl ?: url('/');
688 return rtrim($basePath, '/') . $filePath;