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);
198 * Save image data for the given path in the public space, if possible,
199 * for the provided storage mechanism.
201 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
203 $storage->put($path, $data);
205 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
206 // Done since this call can break s3-like services but desired for other image stores.
207 // Attempting to set ACL during above put request requires different permissions
208 // hence would technically be a breaking change for actual s3 usage.
209 $usingS3 = strtolower(config('filesystems.images')) === 's3';
210 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
212 $storage->setVisibility($path, 'public');
217 * Clean up an image file name to be both URL and storage safe.
219 protected function cleanImageFileName(string $name): string
221 $name = str_replace(' ', '-', $name);
222 $nameParts = explode('.', $name);
223 $extension = array_pop($nameParts);
224 $name = implode('-', $nameParts);
225 $name = Str::slug($name);
227 if (strlen($name) === 0) {
228 $name = Str::random(10);
231 return $name . '.' . $extension;
235 * Checks if the image is a gif. Returns true if it is, else false.
237 protected function isGif(Image $image): bool
239 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
243 * Check if the given image and image data is apng.
245 protected function isApngData(Image $image, string &$imageData): bool
247 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
252 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
254 return strpos($initialHeader, 'acTL') !== false;
258 * Get the thumbnail for an image.
259 * If $keepRatio is true only the width will be used.
260 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
263 * @throws InvalidArgumentException
265 public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false): string
267 // Do not resize GIF images where we're not cropping
268 if ($keepRatio && $this->isGif($image)) {
269 return $this->getPublicUrl($image->path);
272 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
273 $imagePath = $image->path;
274 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
276 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
278 // Return path if in cache
279 $cachedThumbPath = $this->cache->get($thumbCacheKey);
280 if ($cachedThumbPath) {
281 return $this->getPublicUrl($cachedThumbPath);
284 // If thumbnail has already been generated, serve that and cache path
285 $storage = $this->getStorageDisk($image->type);
286 if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
287 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
289 return $this->getPublicUrl($thumbFilePath);
292 $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
294 // Do not resize apng images where we're not cropping
295 if ($keepRatio && $this->isApngData($image, $imageData)) {
296 $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
298 return $this->getPublicUrl($image->path);
301 // If not in cache and thumbnail does not exist, generate thumb and cache path
302 $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
303 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
304 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
306 return $this->getPublicUrl($thumbFilePath);
310 * Resize the image of given data to the specified size, and return the new image data.
312 * @throws ImageUploadException
314 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
317 $thumb = $this->imageTool->make($imageData);
318 } catch (ErrorException | NotSupportedException $e) {
319 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
322 $this->orientImageToOriginalExif($thumb, $imageData);
325 $thumb->resize($width, $height, function ($constraint) {
326 $constraint->aspectRatio();
327 $constraint->upsize();
330 $thumb->fit($width, $height);
333 $thumbData = (string) $thumb->encode();
335 // Use original image data if we're keeping the ratio
336 // and the resizing does not save any space.
337 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
345 * Orientate the given intervention image based upon the given original image data.
346 * Intervention does have an `orientate` method but the exif data it needs is lost before it
347 * can be used (At least when created using binary string data) so we need to do some
348 * implementation on our side to use the original image data.
349 * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
350 * Copyright (c) Oliver Vogel, MIT License.
352 protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
354 if (!extension_loaded('exif')) {
358 $stream = Utils::streamFor($originalData)->detach();
359 $exif = @exif_read_data($stream);
360 $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
362 switch ($orientation) {
370 $image->rotate(180)->flip();
373 $image->rotate(270)->flip();
379 $image->rotate(90)->flip();
388 * Get the raw data content from an image.
390 * @throws FileNotFoundException
392 public function getImageData(Image $image): string
394 $storage = $this->getStorageDisk();
396 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
400 * Destroy an image along with its revisions, thumbnails and remaining folders.
404 public function destroy(Image $image)
406 $this->destroyImagesFromPath($image->path, $image->type);
411 * Destroys an image at the given path.
412 * Searches for image thumbnails in addition to main provided path.
414 protected function destroyImagesFromPath(string $path, string $imageType): bool
416 $path = $this->adjustPathForStorageDisk($path, $imageType);
417 $storage = $this->getStorageDisk($imageType);
419 $imageFolder = dirname($path);
420 $imageFileName = basename($path);
421 $allImages = collect($storage->allFiles($imageFolder));
423 // Delete image files
424 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
425 return basename($imagePath) === $imageFileName;
427 $storage->delete($imagesToDelete->all());
429 // Cleanup of empty folders
430 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
431 foreach ($foldersInvolved as $directory) {
432 if ($this->isFolderEmpty($storage, $directory)) {
433 $storage->deleteDirectory($directory);
441 * Check whether a folder is empty.
443 protected function isFolderEmpty(Storage $storage, string $path): bool
445 $files = $storage->files($path);
446 $folders = $storage->directories($path);
448 return count($files) === 0 && count($folders) === 0;
452 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
453 * Checks based off of only the image name.
454 * Could be much improved to be more specific but kept it generic for now to be safe.
456 * Returns the path of the images that would be/have been deleted.
458 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
460 $types = ['gallery', 'drawio'];
463 Image::query()->whereIn('type', $types)
464 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
465 /** @var Image $image */
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->mimeType($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 $storageUrl = config('filesystems.url');
666 // Get the standard public s3 url if s3 is set as storage type
667 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
668 // region-based url will be used to prevent http issues.
669 if (!$storageUrl && config('filesystems.images') === 's3') {
670 $storageDetails = config('filesystems.disks.s3');
671 if (strpos($storageDetails['bucket'], '.') === false) {
672 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
674 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
678 $basePath = $storageUrl ?: url('/');
680 return rtrim($basePath, '/') . $filePath;