3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\ImageUploadException;
8 use Illuminate\Contracts\Cache\Repository as Cache;
9 use Illuminate\Contracts\Filesystem\FileNotFoundException;
10 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
11 use Illuminate\Filesystem\FilesystemAdapter;
12 use Illuminate\Filesystem\FilesystemManager;
13 use Illuminate\Support\Facades\DB;
14 use Illuminate\Support\Facades\Log;
15 use Illuminate\Support\Str;
16 use Intervention\Image\Exception\NotSupportedException;
17 use Intervention\Image\ImageManager;
18 use League\Flysystem\Util;
19 use Psr\SimpleCache\InvalidArgumentException;
20 use Symfony\Component\HttpFoundation\File\UploadedFile;
21 use Symfony\Component\HttpFoundation\StreamedResponse;
27 protected $storageUrl;
29 protected $fileSystem;
31 protected static $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
34 * ImageService constructor.
36 public function __construct(Image $image, ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
38 $this->image = $image;
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(): bool
58 return $this->getStorageDiskName('gallery') === 'local_secure_images';
62 * Change the originally provided path to fit any disk-specific requirements.
63 * This also ensures the path is kept to the expected root folders.
65 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
67 $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
69 if ($this->getStorageDiskName($imageType) === 'local_secure_images') {
73 return 'uploads/images/' . $path;
77 * Get the name of the storage disk to use.
79 protected function getStorageDiskName(string $imageType): string
81 $storageType = config('filesystems.images');
83 // Ensure system images (App logo) are uploaded to a public space
84 if ($imageType === 'system' && $storageType === 'local_secure') {
85 $storageType = 'local';
88 if ($storageType === 'local_secure') {
89 $storageType = 'local_secure_images';
96 * Saves a new image from an upload.
98 * @throws ImageUploadException
102 public function saveNewFromUpload(
103 UploadedFile $uploadedFile,
106 int $resizeWidth = null,
107 int $resizeHeight = null,
108 bool $keepRatio = true
110 $imageName = $uploadedFile->getClientOriginalName();
111 $imageData = file_get_contents($uploadedFile->getRealPath());
113 if ($resizeWidth !== null || $resizeHeight !== null) {
114 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
117 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
121 * Save a new image from a uri-encoded base64 string of data.
123 * @throws ImageUploadException
125 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
127 $splitData = explode(';base64,', $base64Uri);
128 if (count($splitData) < 2) {
129 throw new ImageUploadException('Invalid base64 image data provided');
131 $data = base64_decode($splitData[1]);
133 return $this->saveNew($name, $data, $type, $uploadedTo);
137 * Save a new image into storage.
139 * @throws ImageUploadException
141 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
143 $storage = $this->getStorageDisk($type);
144 $secureUploads = setting('app-secure-images');
145 $fileName = $this->cleanImageFileName($imageName);
147 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
149 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
150 $fileName = Str::random(3) . $fileName;
153 $fullPath = $imagePath . $fileName;
154 if ($secureUploads) {
155 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
159 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
160 } catch (Exception $e) {
161 Log::error('Error when attempting image upload:' . $e->getMessage());
163 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
167 'name' => $imageName,
169 'url' => $this->getPublicUrl($fullPath),
171 'uploaded_to' => $uploadedTo,
174 if (user()->id !== 0) {
175 $userId = user()->id;
176 $imageDetails['created_by'] = $userId;
177 $imageDetails['updated_by'] = $userId;
180 $image = $this->image->newInstance();
181 $image->forceFill($imageDetails)->save();
187 * Save image data for the given path in the public space, if possible,
188 * for the provided storage mechanism.
190 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
192 $storage->put($path, $data);
194 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
195 // Done since this call can break s3-like services but desired for other image stores.
196 // Attempting to set ACL during above put request requires different permissions
197 // hence would technically be a breaking change for actual s3 usage.
198 $usingS3 = strtolower(config('filesystems.images')) === 's3';
199 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
201 $storage->setVisibility($path, 'public');
206 * Clean up an image file name to be both URL and storage safe.
208 protected function cleanImageFileName(string $name): string
210 $name = str_replace(' ', '-', $name);
211 $nameParts = explode('.', $name);
212 $extension = array_pop($nameParts);
213 $name = implode('-', $nameParts);
214 $name = Str::slug($name);
216 if (strlen($name) === 0) {
217 $name = Str::random(10);
220 return $name . '.' . $extension;
224 * Checks if the image is a gif. Returns true if it is, else false.
226 protected function isGif(Image $image): bool
228 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
232 * Check if the given image and image data is apng.
234 protected function isApngData(Image $image, string &$imageData): bool
236 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
241 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
243 return strpos($initialHeader, 'acTL') !== false;
247 * Get the thumbnail for an image.
248 * If $keepRatio is true only the width will be used.
249 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
252 * @throws InvalidArgumentException
254 public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false): string
256 // Do not resize GIF images where we're not cropping
257 if ($keepRatio && $this->isGif($image)) {
258 return $this->getPublicUrl($image->path);
261 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
262 $imagePath = $image->path;
263 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
265 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
267 // Return path if in cache
268 $cachedThumbPath = $this->cache->get($thumbCacheKey);
269 if ($cachedThumbPath) {
270 return $this->getPublicUrl($cachedThumbPath);
273 // If thumbnail has already been generated, serve that and cache path
274 $storage = $this->getStorageDisk($image->type);
275 if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
276 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
278 return $this->getPublicUrl($thumbFilePath);
281 $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
283 // Do not resize apng images where we're not cropping
284 if ($keepRatio && $this->isApngData($image, $imageData)) {
285 $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
287 return $this->getPublicUrl($image->path);
290 // If not in cache and thumbnail does not exist, generate thumb and cache path
291 $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
292 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
293 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
295 return $this->getPublicUrl($thumbFilePath);
299 * Resize the image of given data to the specified size, and return the new image data.
301 * @throws ImageUploadException
303 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
306 $thumb = $this->imageTool->make($imageData);
307 } catch (ErrorException|NotSupportedException $e) {
308 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
312 $thumb->resize($width, $height, function ($constraint) {
313 $constraint->aspectRatio();
314 $constraint->upsize();
317 $thumb->fit($width, $height);
320 $thumbData = (string) $thumb->encode();
322 // Use original image data if we're keeping the ratio
323 // and the resizing does not save any space.
324 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
332 * Get the raw data content from an image.
334 * @throws FileNotFoundException
336 public function getImageData(Image $image): string
338 $storage = $this->getStorageDisk();
340 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
344 * Destroy an image along with its revisions, thumbnails and remaining folders.
348 public function destroy(Image $image)
350 $this->destroyImagesFromPath($image->path, $image->type);
355 * Destroys an image at the given path.
356 * Searches for image thumbnails in addition to main provided path.
358 protected function destroyImagesFromPath(string $path, string $imageType): bool
360 $path = $this->adjustPathForStorageDisk($path, $imageType);
361 $storage = $this->getStorageDisk($imageType);
363 $imageFolder = dirname($path);
364 $imageFileName = basename($path);
365 $allImages = collect($storage->allFiles($imageFolder));
367 // Delete image files
368 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
369 return basename($imagePath) === $imageFileName;
371 $storage->delete($imagesToDelete->all());
373 // Cleanup of empty folders
374 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
375 foreach ($foldersInvolved as $directory) {
376 if ($this->isFolderEmpty($storage, $directory)) {
377 $storage->deleteDirectory($directory);
385 * Check whether a folder is empty.
387 protected function isFolderEmpty(Storage $storage, string $path): bool
389 $files = $storage->files($path);
390 $folders = $storage->directories($path);
392 return count($files) === 0 && count($folders) === 0;
396 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
397 * Checks based off of only the image name.
398 * Could be much improved to be more specific but kept it generic for now to be safe.
400 * Returns the path of the images that would be/have been deleted.
402 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
404 $types = ['gallery', 'drawio'];
407 $this->image->newQuery()->whereIn('type', $types)
408 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
409 foreach ($images as $image) {
410 $searchQuery = '%' . basename($image->path) . '%';
411 $inPage = DB::table('pages')
412 ->where('html', 'like', $searchQuery)->count() > 0;
415 if ($checkRevisions) {
416 $inRevision = DB::table('page_revisions')
417 ->where('html', 'like', $searchQuery)->count() > 0;
420 if (!$inPage && !$inRevision) {
421 $deletedPaths[] = $image->path;
423 $this->destroy($image);
429 return $deletedPaths;
433 * Convert an image URI to a Base64 encoded string.
434 * Attempts to convert the URL to a system storage url then
435 * fetch the data from the disk or storage location.
436 * Returns null if the image data cannot be fetched from storage.
438 * @throws FileNotFoundException
440 public function imageUriToBase64(string $uri): ?string
442 $storagePath = $this->imageUrlToStoragePath($uri);
443 if (empty($uri) || is_null($storagePath)) {
447 $storagePath = $this->adjustPathForStorageDisk($storagePath);
448 $storage = $this->getStorageDisk();
450 if ($storage->exists($storagePath)) {
451 $imageData = $storage->get($storagePath);
454 if (is_null($imageData)) {
458 $extension = pathinfo($uri, PATHINFO_EXTENSION);
459 if ($extension === 'svg') {
460 $extension = 'svg+xml';
463 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
467 * Check if the given path exists in the local secure image system.
468 * Returns false if local_secure is not in use.
470 public function pathExistsInLocalSecure(string $imagePath): bool
472 /** @var FilesystemAdapter $disk */
473 $disk = $this->getStorageDisk('gallery');
475 // Check local_secure is active
476 return $this->usingSecureImages()
477 && $disk instanceof FilesystemAdapter
478 // Check the image file exists
479 && $disk->exists($imagePath)
480 // Check the file is likely an image file
481 && strpos($disk->getMimetype($imagePath), 'image/') === 0;
485 * For the given path, if existing, provide a response that will stream the image contents.
487 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
489 $disk = $this->getStorageDisk($imageType);
491 return $disk->response($path);
495 * Check if the given image extension is supported by BookStack.
496 * The extension must not be altered in this function. This check should provide a guarantee
497 * that the provided extension is safe to use for the image to be saved.
499 public static function isExtensionSupported(string $extension): bool
501 return in_array($extension, static::$supportedExtensions);
505 * Get a storage path for the given image URL.
506 * Ensures the path will start with "uploads/images".
507 * Returns null if the url cannot be resolved to a local URL.
509 private function imageUrlToStoragePath(string $url): ?string
511 $url = ltrim(trim($url), '/');
513 // Handle potential relative paths
514 $isRelative = strpos($url, 'http') !== 0;
516 if (strpos(strtolower($url), 'uploads/images') === 0) {
517 return trim($url, '/');
523 // Handle local images based on paths on the same domain
524 $potentialHostPaths = [
525 url('uploads/images/'),
526 $this->getPublicUrl('/uploads/images/'),
529 foreach ($potentialHostPaths as $potentialBasePath) {
530 $potentialBasePath = strtolower($potentialBasePath);
531 if (strpos(strtolower($url), $potentialBasePath) === 0) {
532 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
540 * Gets a public facing url for an image by checking relevant environment variables.
541 * If s3-style store is in use it will default to guessing a public bucket URL.
543 private function getPublicUrl(string $filePath): string
545 if (is_null($this->storageUrl)) {
546 $storageUrl = config('filesystems.url');
548 // Get the standard public s3 url if s3 is set as storage type
549 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
550 // region-based url will be used to prevent http issues.
551 if ($storageUrl == false && config('filesystems.images') === 's3') {
552 $storageDetails = config('filesystems.disks.s3');
553 if (strpos($storageDetails['bucket'], '.') === false) {
554 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
556 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
560 $this->storageUrl = $storageUrl;
563 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
565 return rtrim($basePath, '/') . $filePath;