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 Symfony\Component\HttpFoundation\File\UploadedFile;
25 use Symfony\Component\HttpFoundation\StreamedResponse;
29 protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
31 public function __construct(
32 protected ImageManager $imageTool,
33 protected FilesystemManager $fileSystem,
34 protected Cache $cache
39 * Get the storage that will be used for storing images.
41 protected function getStorageDisk(string $imageType = ''): Storage
43 return $this->fileSystem->disk($this->getStorageDiskName($imageType));
47 * Check if local secure image storage (Fetched behind authentication)
48 * is currently active in the instance.
50 protected function usingSecureImages(string $imageType = 'gallery'): bool
52 return $this->getStorageDiskName($imageType) === 'local_secure_images';
56 * Check if "local secure restricted" (Fetched behind auth, with permissions enforced)
57 * is currently active in the instance.
59 protected function usingSecureRestrictedImages()
61 return config('filesystems.images') === 'local_secure_restricted';
65 * Change the originally provided path to fit any disk-specific requirements.
66 * This also ensures the path is kept to the expected root folders.
68 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
70 $path = (new WhitespacePathNormalizer())->normalizePath(str_replace('uploads/images/', '', $path));
72 if ($this->usingSecureImages($imageType)) {
76 return 'uploads/images/' . $path;
80 * Get the name of the storage disk to use.
82 protected function getStorageDiskName(string $imageType): string
84 $storageType = config('filesystems.images');
85 $localSecureInUse = ($storageType === 'local_secure' || $storageType === 'local_secure_restricted');
87 // Ensure system images (App logo) are uploaded to a public space
88 if ($imageType === 'system' && $localSecureInUse) {
92 // Rename local_secure options to get our image specific storage driver which
93 // is scoped to the relevant image directories.
94 if ($localSecureInUse) {
95 return 'local_secure_images';
102 * Saves a new image from an upload.
104 * @throws ImageUploadException
108 public function saveNewFromUpload(
109 UploadedFile $uploadedFile,
112 int $resizeWidth = null,
113 int $resizeHeight = null,
114 bool $keepRatio = true
116 $imageName = $uploadedFile->getClientOriginalName();
117 $imageData = file_get_contents($uploadedFile->getRealPath());
119 if ($resizeWidth !== null || $resizeHeight !== null) {
120 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
123 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
127 * Save a new image from a uri-encoded base64 string of data.
129 * @throws ImageUploadException
131 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
133 $splitData = explode(';base64,', $base64Uri);
134 if (count($splitData) < 2) {
135 throw new ImageUploadException('Invalid base64 image data provided');
137 $data = base64_decode($splitData[1]);
139 return $this->saveNew($name, $data, $type, $uploadedTo);
143 * Save a new image into storage.
145 * @throws ImageUploadException
147 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
149 $storage = $this->getStorageDisk($type);
150 $secureUploads = setting('app-secure-images');
151 $fileName = $this->cleanImageFileName($imageName);
153 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
155 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
156 $fileName = Str::random(3) . $fileName;
159 $fullPath = $imagePath . $fileName;
160 if ($secureUploads) {
161 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
165 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
166 } catch (Exception $e) {
167 Log::error('Error when attempting image upload:' . $e->getMessage());
169 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
173 'name' => $imageName,
175 'url' => $this->getPublicUrl($fullPath),
177 'uploaded_to' => $uploadedTo,
180 if (user()->id !== 0) {
181 $userId = user()->id;
182 $imageDetails['created_by'] = $userId;
183 $imageDetails['updated_by'] = $userId;
186 $image = (new Image())->forceFill($imageDetails);
192 public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
194 $imageData = file_get_contents($file->getRealPath());
195 $storage = $this->getStorageDisk($type);
196 $adjustedPath = $this->adjustPathForStorageDisk($path, $type);
197 $storage->put($adjustedPath, $imageData);
201 * Save image data for the given path in the public space, if possible,
202 * for the provided storage mechanism.
204 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data): void
206 $storage->put($path, $data);
208 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
209 // Done since this call can break s3-like services but desired for other image stores.
210 // Attempting to set ACL during above put request requires different permissions
211 // hence would technically be a breaking change for actual s3 usage.
212 $usingS3 = strtolower(config('filesystems.images')) === 's3';
213 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
215 $storage->setVisibility($path, 'public');
220 * Clean up an image file name to be both URL and storage safe.
222 protected function cleanImageFileName(string $name): string
224 $name = str_replace(' ', '-', $name);
225 $nameParts = explode('.', $name);
226 $extension = array_pop($nameParts);
227 $name = implode('-', $nameParts);
228 $name = Str::slug($name);
230 if (strlen($name) === 0) {
231 $name = Str::random(10);
234 return $name . '.' . $extension;
238 * Checks if the image is a gif. Returns true if it is, else false.
240 protected function isGif(Image $image): bool
242 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
246 * Check if the given image and image data is apng.
248 protected function isApngData(Image $image, string &$imageData): bool
250 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
255 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
257 return str_contains($initialHeader, 'acTL');
261 * Get the thumbnail for an image.
262 * If $keepRatio is true only the width will be used.
263 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
267 public function getThumbnail(
271 bool $keepRatio = false,
272 bool $shouldCreate = false,
273 bool $canCreate = false,
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 && !$shouldCreate) {
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 (!$shouldCreate && $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 (!$shouldCreate && !$canCreate) {
313 // If not in cache and thumbnail does not exist, generate thumb and cache path
314 $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
315 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
316 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
318 return $this->getPublicUrl($thumbFilePath);
322 * Resize the image of given data to the specified size, and return the new image data.
324 * @throws ImageUploadException
326 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
329 $thumb = $this->imageTool->make($imageData);
330 } catch (ErrorException | NotSupportedException $e) {
331 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
334 $this->orientImageToOriginalExif($thumb, $imageData);
337 $thumb->resize($width, $height, function ($constraint) {
338 $constraint->aspectRatio();
339 $constraint->upsize();
342 $thumb->fit($width, $height);
345 $thumbData = (string) $thumb->encode();
347 // Use original image data if we're keeping the ratio
348 // and the resizing does not save any space.
349 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
357 * Orientate the given intervention image based upon the given original image data.
358 * Intervention does have an `orientate` method but the exif data it needs is lost before it
359 * can be used (At least when created using binary string data) so we need to do some
360 * implementation on our side to use the original image data.
361 * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
362 * Copyright (c) Oliver Vogel, MIT License.
364 protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
366 if (!extension_loaded('exif')) {
370 $stream = Utils::streamFor($originalData)->detach();
371 $exif = @exif_read_data($stream);
372 $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
374 switch ($orientation) {
382 $image->rotate(180)->flip();
385 $image->rotate(270)->flip();
391 $image->rotate(90)->flip();
400 * Get the raw data content from an image.
402 * @throws FileNotFoundException
404 public function getImageData(Image $image): string
406 $storage = $this->getStorageDisk();
408 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
412 * Destroy an image along with its revisions, thumbnails and remaining folders.
416 public function destroy(Image $image)
418 $this->destroyImagesFromPath($image->path, $image->type);
423 * Destroys an image at the given path.
424 * Searches for image thumbnails in addition to main provided path.
426 protected function destroyImagesFromPath(string $path, string $imageType): bool
428 $path = $this->adjustPathForStorageDisk($path, $imageType);
429 $storage = $this->getStorageDisk($imageType);
431 $imageFolder = dirname($path);
432 $imageFileName = basename($path);
433 $allImages = collect($storage->allFiles($imageFolder));
435 // Delete image files
436 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
437 return basename($imagePath) === $imageFileName;
439 $storage->delete($imagesToDelete->all());
441 // Cleanup of empty folders
442 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
443 foreach ($foldersInvolved as $directory) {
444 if ($this->isFolderEmpty($storage, $directory)) {
445 $storage->deleteDirectory($directory);
453 * Check whether a folder is empty.
455 protected function isFolderEmpty(Storage $storage, string $path): bool
457 $files = $storage->files($path);
458 $folders = $storage->directories($path);
460 return count($files) === 0 && count($folders) === 0;
464 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
465 * Checks based off of only the image name.
466 * Could be much improved to be more specific but kept it generic for now to be safe.
468 * Returns the path of the images that would be/have been deleted.
470 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
472 $types = ['gallery', 'drawio'];
475 Image::query()->whereIn('type', $types)
476 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
477 /** @var Image $image */
478 foreach ($images as $image) {
479 $searchQuery = '%' . basename($image->path) . '%';
480 $inPage = DB::table('pages')
481 ->where('html', 'like', $searchQuery)->count() > 0;
484 if ($checkRevisions) {
485 $inRevision = DB::table('page_revisions')
486 ->where('html', 'like', $searchQuery)->count() > 0;
489 if (!$inPage && !$inRevision) {
490 $deletedPaths[] = $image->path;
492 $this->destroy($image);
498 return $deletedPaths;
502 * Convert an image URI to a Base64 encoded string.
503 * Attempts to convert the URL to a system storage url then
504 * fetch the data from the disk or storage location.
505 * Returns null if the image data cannot be fetched from storage.
507 * @throws FileNotFoundException
509 public function imageUriToBase64(string $uri): ?string
511 $storagePath = $this->imageUrlToStoragePath($uri);
512 if (empty($uri) || is_null($storagePath)) {
516 $storagePath = $this->adjustPathForStorageDisk($storagePath);
518 // Apply access control when local_secure_restricted images are active
519 if ($this->usingSecureRestrictedImages()) {
520 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
525 $storage = $this->getStorageDisk();
527 if ($storage->exists($storagePath)) {
528 $imageData = $storage->get($storagePath);
531 if (is_null($imageData)) {
535 $extension = pathinfo($uri, PATHINFO_EXTENSION);
536 if ($extension === 'svg') {
537 $extension = 'svg+xml';
540 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
544 * Check if the given path exists and is accessible in the local secure image system.
545 * Returns false if local_secure is not in use, if the file does not exist, if the
546 * file is likely not a valid image, or if permission does not allow access.
548 public function pathAccessibleInLocalSecure(string $imagePath): bool
550 /** @var FilesystemAdapter $disk */
551 $disk = $this->getStorageDisk('gallery');
553 if ($this->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
557 // Check local_secure is active
558 return $this->usingSecureImages()
559 && $disk instanceof FilesystemAdapter
560 // Check the image file exists
561 && $disk->exists($imagePath)
562 // Check the file is likely an image file
563 && str_starts_with($disk->mimeType($imagePath), 'image/');
567 * Check that the current user has access to the relation
568 * of the image at the given path.
570 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
572 if (str_starts_with($path, '/uploads/images/')) {
573 $path = substr($path, 15);
576 // Strip thumbnail element from path if existing
577 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
578 $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
579 $missingExtension = !str_contains($part, '.');
581 return !($resizedDir && $missingExtension);
584 // Build a database-format image path and search for the image entry
585 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
586 $image = Image::query()->where('path', '=', $fullPath)->first();
588 if (is_null($image)) {
592 $imageType = $image->type;
594 // Allow user or system (logo) images
595 // (No specific relation control but may still have access controlled by auth)
596 if ($imageType === 'user' || $imageType === 'system') {
600 if ($imageType === 'gallery' || $imageType === 'drawio') {
601 return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
604 if ($imageType === 'cover_book') {
605 return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
608 if ($imageType === 'cover_bookshelf') {
609 return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
616 * For the given path, if existing, provide a response that will stream the image contents.
618 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
620 $disk = $this->getStorageDisk($imageType);
622 return $disk->response($path);
626 * Check if the given image extension is supported by BookStack.
627 * The extension must not be altered in this function. This check should provide a guarantee
628 * that the provided extension is safe to use for the image to be saved.
630 public static function isExtensionSupported(string $extension): bool
632 return in_array($extension, static::$supportedExtensions);
636 * Get a storage path for the given image URL.
637 * Ensures the path will start with "uploads/images".
638 * Returns null if the url cannot be resolved to a local URL.
640 private function imageUrlToStoragePath(string $url): ?string
642 $url = ltrim(trim($url), '/');
644 // Handle potential relative paths
645 $isRelative = !str_starts_with($url, 'http');
647 if (str_starts_with(strtolower($url), 'uploads/images')) {
648 return trim($url, '/');
654 // Handle local images based on paths on the same domain
655 $potentialHostPaths = [
656 url('uploads/images/'),
657 $this->getPublicUrl('/uploads/images/'),
660 foreach ($potentialHostPaths as $potentialBasePath) {
661 $potentialBasePath = strtolower($potentialBasePath);
662 if (str_starts_with(strtolower($url), $potentialBasePath)) {
663 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
671 * Gets a public facing url for an image by checking relevant environment variables.
672 * If s3-style store is in use it will default to guessing a public bucket URL.
674 private function getPublicUrl(string $filePath): string
676 $storageUrl = config('filesystems.url');
678 // Get the standard public s3 url if s3 is set as storage type
679 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
680 // region-based url will be used to prevent http issues.
681 if (!$storageUrl && config('filesystems.images') === 's3') {
682 $storageDetails = config('filesystems.disks.s3');
683 if (!str_contains($storageDetails['bucket'], '.')) {
684 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
686 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
690 $basePath = $storageUrl ?: url('/');
692 return rtrim($basePath, '/') . $filePath;