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 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;
26 protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
28 public function __construct(
29 protected ImageManager $imageTool,
30 protected FilesystemManager $fileSystem,
31 protected Cache $cache,
32 protected ImageStorage $storage,
37 * Saves a new image from an upload.
39 * @throws ImageUploadException
41 public function saveNewFromUpload(
42 UploadedFile $uploadedFile,
45 int $resizeWidth = null,
46 int $resizeHeight = null,
47 bool $keepRatio = true
49 $imageName = $uploadedFile->getClientOriginalName();
50 $imageData = file_get_contents($uploadedFile->getRealPath());
52 if ($resizeWidth !== null || $resizeHeight !== null) {
53 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
56 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
60 * Save a new image from a uri-encoded base64 string of data.
62 * @throws ImageUploadException
64 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
66 $splitData = explode(';base64,', $base64Uri);
67 if (count($splitData) < 2) {
68 throw new ImageUploadException('Invalid base64 image data provided');
70 $data = base64_decode($splitData[1]);
72 return $this->saveNew($name, $data, $type, $uploadedTo);
76 * Save a new image into storage.
78 * @throws ImageUploadException
80 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
82 $disk = $this->storage->getDisk($type);
83 $secureUploads = setting('app-secure-images');
84 $fileName = $this->storage->cleanImageFileName($imageName);
86 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
88 while ($disk->exists($this->storage->adjustPathForDisk($imagePath . $fileName, $type))) {
89 $fileName = Str::random(3) . $fileName;
92 $fullPath = $imagePath . $fileName;
94 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
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());
102 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
106 'name' => $imageName,
108 'url' => $this->storage->getPublicUrl($fullPath),
110 'uploaded_to' => $uploadedTo,
113 if (user()->id !== 0) {
114 $userId = user()->id;
115 $imageDetails['created_by'] = $userId;
116 $imageDetails['updated_by'] = $userId;
119 $image = (new Image())->forceFill($imageDetails);
126 * Replace an existing image file in the system using the given file.
128 public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
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);
138 * Checks if the image is a gif. Returns true if it is, else false.
140 protected function isGif(Image $image): bool
142 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
146 * Check if the given image and image data is apng.
148 protected function isApngData(Image $image, string &$imageData): bool
150 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
155 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
157 return str_contains($initialHeader, 'acTL');
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.
167 public function getThumbnail(
171 bool $keepRatio = false,
172 bool $shouldCreate = false,
173 bool $canCreate = false,
175 // Do not resize GIF images where we're not cropping
176 if ($keepRatio && $this->isGif($image)) {
177 return $this->storage->getPublicUrl($image->path);
180 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
181 $imagePath = $image->path;
182 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
184 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
186 // Return path if in cache
187 $cachedThumbPath = $this->cache->get($thumbCacheKey);
188 if ($cachedThumbPath && !$shouldCreate) {
189 return $this->storage->getPublicUrl($cachedThumbPath);
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);
197 return $this->storage->getPublicUrl($thumbFilePath);
200 $imageData = $disk->get($this->storage->adjustPathForDisk($imagePath, $image->type));
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);
206 return $this->storage->getPublicUrl($image->path);
209 if (!$shouldCreate && !$canCreate) {
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);
218 return $this->storage->getPublicUrl($thumbFilePath);
222 * Resize the image of given data to the specified size, and return the new image data.
224 * @throws ImageUploadException
226 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
229 $thumb = $this->imageTool->make($imageData);
230 } catch (ErrorException | NotSupportedException $e) {
231 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
234 $this->orientImageToOriginalExif($thumb, $imageData);
237 $thumb->resize($width, $height, function ($constraint) {
238 $constraint->aspectRatio();
239 $constraint->upsize();
242 $thumb->fit($width, $height);
245 $thumbData = (string) $thumb->encode();
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)) {
258 * Get the raw data content from an image.
262 public function getImageData(Image $image): string
264 $disk = $this->storage->getDisk();
266 return $disk->get($this->storage->adjustPathForDisk($image->path, $image->type));
270 * Destroy an image along with its revisions, thumbnails and remaining folders.
274 public function destroy(Image $image)
276 $this->destroyImagesFromPath($image->path, $image->type);
281 * Destroys an image at the given path.
282 * Searches for image thumbnails in addition to main provided path.
284 protected function destroyImagesFromPath(string $path, string $imageType): bool
286 $path = $this->storage->adjustPathForDisk($path, $imageType);
287 $disk = $this->storage->getDisk($imageType);
289 $imageFolder = dirname($path);
290 $imageFileName = basename($path);
291 $allImages = collect($disk->allFiles($imageFolder));
293 // Delete image files
294 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
295 return basename($imagePath) === $imageFileName;
297 $disk->delete($imagesToDelete->all());
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);
311 * Check whether a folder is empty.
313 protected function isFolderEmpty(StorageDisk $storage, string $path): bool
315 $files = $storage->files($path);
316 $folders = $storage->directories($path);
318 return count($files) === 0 && count($folders) === 0;
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.
326 * Returns the path of the images that would be/have been deleted.
328 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
330 $types = ['gallery', 'drawio'];
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;
342 if ($checkRevisions) {
343 $inRevision = DB::table('page_revisions')
344 ->where('html', 'like', $searchQuery)->count() > 0;
347 if (!$inPage && !$inRevision) {
348 $deletedPaths[] = $image->path;
350 $this->destroy($image);
356 return $deletedPaths;
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.
365 * @throws FileNotFoundException
367 public function imageUrlToBase64(string $url): ?string
369 $storagePath = $this->storage->urlToPath($url);
370 if (empty($url) || is_null($storagePath)) {
374 $storagePath = $this->storage->adjustPathForDisk($storagePath);
376 // Apply access control when local_secure_restricted images are active
377 if ($this->storage->usingSecureRestrictedImages()) {
378 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
383 $disk = $this->storage->getDisk();
385 if ($disk->exists($storagePath)) {
386 $imageData = $disk->get($storagePath);
389 if (is_null($imageData)) {
393 $extension = pathinfo($url, PATHINFO_EXTENSION);
394 if ($extension === 'svg') {
395 $extension = 'svg+xml';
398 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
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.
406 public function pathAccessibleInLocalSecure(string $imagePath): bool
408 $disk = $this->storage->getDisk('gallery');
410 if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
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/');
424 * Check that the current user has access to the relation
425 * of the image at the given path.
427 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
429 if (str_starts_with($path, '/uploads/images/')) {
430 $path = substr($path, 15);
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, '.');
438 return !($resizedDir && $missingExtension);
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();
445 if (is_null($image)) {
449 $imageType = $image->type;
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') {
457 if ($imageType === 'gallery' || $imageType === 'drawio') {
458 return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
461 if ($imageType === 'cover_book') {
462 return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
465 if ($imageType === 'cover_bookshelf') {
466 return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
473 * For the given path, if existing, provide a response that will stream the image contents.
475 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
477 $disk = $this->storage->getDisk($imageType);
479 return $disk->response($path);
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.
487 public static function isExtensionSupported(string $extension): bool
489 return in_array($extension, static::$supportedExtensions);