3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\ImageUploadException;
6 use BookStack\Util\WebSafeMimeSniffer;
9 use Illuminate\Contracts\Cache\Repository as Cache;
10 use Illuminate\Contracts\Filesystem\FileNotFoundException;
11 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
12 use Illuminate\Filesystem\FilesystemAdapter;
13 use Illuminate\Filesystem\FilesystemManager;
14 use Illuminate\Support\Facades\DB;
15 use Illuminate\Support\Facades\Log;
16 use Illuminate\Support\Str;
17 use Intervention\Image\Exception\NotSupportedException;
18 use Intervention\Image\ImageManager;
19 use League\Flysystem\Util;
20 use Psr\SimpleCache\InvalidArgumentException;
21 use Symfony\Component\HttpFoundation\File\UploadedFile;
22 use Symfony\Component\HttpFoundation\StreamedResponse;
28 protected $storageUrl;
30 protected $fileSystem;
32 protected static $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
35 * ImageService constructor.
37 public function __construct(Image $image, ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
39 $this->image = $image;
40 $this->imageTool = $imageTool;
41 $this->fileSystem = $fileSystem;
42 $this->cache = $cache;
46 * Get the storage that will be used for storing images.
48 protected function getStorageDisk(string $imageType = ''): Storage
50 return $this->fileSystem->disk($this->getStorageDiskName($imageType));
54 * Check if local secure image storage (Fetched behind authentication)
55 * is currently active in the instance.
57 protected function usingSecureImages(): bool
59 return $this->getStorageDiskName('gallery') === 'local_secure_images';
63 * Change the originally provided path to fit any disk-specific requirements.
64 * This also ensures the path is kept to the expected root folders.
66 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
68 $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
70 if ($this->getStorageDiskName($imageType) === 'local_secure_images') {
74 return 'uploads/images/' . $path;
78 * Get the name of the storage disk to use.
80 protected function getStorageDiskName(string $imageType): string
82 $storageType = config('filesystems.images');
84 // Ensure system images (App logo) are uploaded to a public space
85 if ($imageType === 'system' && $storageType === 'local_secure') {
86 $storageType = 'local';
89 if ($storageType === 'local_secure') {
90 $storageType = 'local_secure_images';
97 * Saves a new image from an upload.
99 * @throws ImageUploadException
103 public function saveNewFromUpload(
104 UploadedFile $uploadedFile,
107 int $resizeWidth = null,
108 int $resizeHeight = null,
109 bool $keepRatio = true
111 $imageName = $uploadedFile->getClientOriginalName();
112 $imageData = file_get_contents($uploadedFile->getRealPath());
114 if ($resizeWidth !== null || $resizeHeight !== null) {
115 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
118 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
122 * Save a new image from a uri-encoded base64 string of data.
124 * @throws ImageUploadException
126 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
128 $splitData = explode(';base64,', $base64Uri);
129 if (count($splitData) < 2) {
130 throw new ImageUploadException('Invalid base64 image data provided');
132 $data = base64_decode($splitData[1]);
134 return $this->saveNew($name, $data, $type, $uploadedTo);
138 * Save a new image into storage.
140 * @throws ImageUploadException
142 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
144 $storage = $this->getStorageDisk($type);
145 $secureUploads = setting('app-secure-images');
146 $fileName = $this->cleanImageFileName($imageName);
148 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
150 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
151 $fileName = Str::random(3) . $fileName;
154 $fullPath = $imagePath . $fileName;
155 if ($secureUploads) {
156 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
160 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
161 } catch (Exception $e) {
162 Log::error('Error when attempting image upload:' . $e->getMessage());
164 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
168 'name' => $imageName,
170 'url' => $this->getPublicUrl($fullPath),
172 'uploaded_to' => $uploadedTo,
175 if (user()->id !== 0) {
176 $userId = user()->id;
177 $imageDetails['created_by'] = $userId;
178 $imageDetails['updated_by'] = $userId;
181 $image = $this->image->newInstance();
182 $image->forceFill($imageDetails)->save();
188 * Save image data for the given path in the public space, if possible,
189 * for the provided storage mechanism.
191 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
193 $storage->put($path, $data);
195 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
196 // Done since this call can break s3-like services but desired for other image stores.
197 // Attempting to set ACL during above put request requires different permissions
198 // hence would technically be a breaking change for actual s3 usage.
199 $usingS3 = strtolower(config('filesystems.images')) === 's3';
200 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
202 $storage->setVisibility($path, 'public');
207 * Clean up an image file name to be both URL and storage safe.
209 protected function cleanImageFileName(string $name): string
211 $name = str_replace(' ', '-', $name);
212 $nameParts = explode('.', $name);
213 $extension = array_pop($nameParts);
214 $name = implode('-', $nameParts);
215 $name = Str::slug($name);
217 if (strlen($name) === 0) {
218 $name = Str::random(10);
221 return $name . '.' . $extension;
225 * Checks if the image is a gif. Returns true if it is, else false.
227 protected function isGif(Image $image): bool
229 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
233 * Check if the given image and image data is apng.
235 protected function isApngData(Image $image, string &$imageData): bool
237 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
242 $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);
277 return $this->getPublicUrl($thumbFilePath);
280 $imageData = $storage->get($this->adjustPathForStorageDisk($imagePath, $image->type));
282 // Do not resize apng images where we're not cropping
283 if ($keepRatio && $this->isApngData($image, $imageData)) {
284 $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
285 return $this->getPublicUrl($image->path);
288 // If not in cache and thumbnail does not exist, generate thumb and cache path
289 $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
290 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
291 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
293 return $this->getPublicUrl($thumbFilePath);
297 * Resize the image of given data to the specified size, and return the new image data.
299 * @throws ImageUploadException
301 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
304 $thumb = $this->imageTool->make($imageData);
305 } catch (ErrorException|NotSupportedException $e) {
306 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
310 $thumb->resize($width, $height, function ($constraint) {
311 $constraint->aspectRatio();
312 $constraint->upsize();
315 $thumb->fit($width, $height);
318 $thumbData = (string) $thumb->encode();
320 // Use original image data if we're keeping the ratio
321 // and the resizing does not save any space.
322 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
330 * Get the raw data content from an image.
332 * @throws FileNotFoundException
334 public function getImageData(Image $image): string
336 $storage = $this->getStorageDisk();
338 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
342 * Destroy an image along with its revisions, thumbnails and remaining folders.
346 public function destroy(Image $image)
348 $this->destroyImagesFromPath($image->path, $image->type);
353 * Destroys an image at the given path.
354 * Searches for image thumbnails in addition to main provided path.
356 protected function destroyImagesFromPath(string $path, string $imageType): bool
358 $path = $this->adjustPathForStorageDisk($path, $imageType);
359 $storage = $this->getStorageDisk($imageType);
361 $imageFolder = dirname($path);
362 $imageFileName = basename($path);
363 $allImages = collect($storage->allFiles($imageFolder));
365 // Delete image files
366 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
367 return basename($imagePath) === $imageFileName;
369 $storage->delete($imagesToDelete->all());
371 // Cleanup of empty folders
372 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
373 foreach ($foldersInvolved as $directory) {
374 if ($this->isFolderEmpty($storage, $directory)) {
375 $storage->deleteDirectory($directory);
383 * Check whether a folder is empty.
385 protected function isFolderEmpty(Storage $storage, string $path): bool
387 $files = $storage->files($path);
388 $folders = $storage->directories($path);
390 return count($files) === 0 && count($folders) === 0;
394 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
395 * Checks based off of only the image name.
396 * Could be much improved to be more specific but kept it generic for now to be safe.
398 * Returns the path of the images that would be/have been deleted.
400 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
402 $types = ['gallery', 'drawio'];
405 $this->image->newQuery()->whereIn('type', $types)
406 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
407 foreach ($images as $image) {
408 $searchQuery = '%' . basename($image->path) . '%';
409 $inPage = DB::table('pages')
410 ->where('html', 'like', $searchQuery)->count() > 0;
413 if ($checkRevisions) {
414 $inRevision = DB::table('page_revisions')
415 ->where('html', 'like', $searchQuery)->count() > 0;
418 if (!$inPage && !$inRevision) {
419 $deletedPaths[] = $image->path;
421 $this->destroy($image);
427 return $deletedPaths;
431 * Convert an image URI to a Base64 encoded string.
432 * Attempts to convert the URL to a system storage url then
433 * fetch the data from the disk or storage location.
434 * Returns null if the image data cannot be fetched from storage.
436 * @throws FileNotFoundException
438 public function imageUriToBase64(string $uri): ?string
440 $storagePath = $this->imageUrlToStoragePath($uri);
441 if (empty($uri) || is_null($storagePath)) {
445 $storagePath = $this->adjustPathForStorageDisk($storagePath);
446 $storage = $this->getStorageDisk();
448 if ($storage->exists($storagePath)) {
449 $imageData = $storage->get($storagePath);
452 if (is_null($imageData)) {
456 $extension = pathinfo($uri, PATHINFO_EXTENSION);
457 if ($extension === 'svg') {
458 $extension = 'svg+xml';
461 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
465 * Check if the given path exists in the local secure image system.
466 * Returns false if local_secure is not in use.
468 public function pathExistsInLocalSecure(string $imagePath): bool
470 /** @var FilesystemAdapter $disk */
471 $disk = $this->getStorageDisk('gallery');
473 // Check local_secure is active
474 return $this->usingSecureImages()
475 && $disk instanceof FilesystemAdapter
476 // Check the image file exists
477 && $disk->exists($imagePath)
478 // Check the file is likely an image file
479 && strpos($disk->getMimetype($imagePath), 'image/') === 0;
483 * For the given path, if existing, provide a response that will stream the image contents.
485 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
487 $disk = $this->getStorageDisk($imageType);
489 return $disk->response($path);
493 * Check if the given image extension is supported by BookStack.
494 * The extension must not be altered in this function. This check should provide a guarantee
495 * that the provided extension is safe to use for the image to be saved.
497 public static function isExtensionSupported(string $extension): bool
499 return in_array($extension, static::$supportedExtensions);
503 * Get a storage path for the given image URL.
504 * Ensures the path will start with "uploads/images".
505 * Returns null if the url cannot be resolved to a local URL.
507 private function imageUrlToStoragePath(string $url): ?string
509 $url = ltrim(trim($url), '/');
511 // Handle potential relative paths
512 $isRelative = strpos($url, 'http') !== 0;
514 if (strpos(strtolower($url), 'uploads/images') === 0) {
515 return trim($url, '/');
521 // Handle local images based on paths on the same domain
522 $potentialHostPaths = [
523 url('uploads/images/'),
524 $this->getPublicUrl('/uploads/images/'),
527 foreach ($potentialHostPaths as $potentialBasePath) {
528 $potentialBasePath = strtolower($potentialBasePath);
529 if (strpos(strtolower($url), $potentialBasePath) === 0) {
530 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
538 * Gets a public facing url for an image by checking relevant environment variables.
539 * If s3-style store is in use it will default to guessing a public bucket URL.
541 private function getPublicUrl(string $filePath): string
543 if (is_null($this->storageUrl)) {
544 $storageUrl = config('filesystems.url');
546 // Get the standard public s3 url if s3 is set as storage type
547 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
548 // region-based url will be used to prevent http issues.
549 if ($storageUrl == false && config('filesystems.images') === 's3') {
550 $storageDetails = config('filesystems.disks.s3');
551 if (strpos($storageDetails['bucket'], '.') === false) {
552 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
554 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
558 $this->storageUrl = $storageUrl;
561 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
563 return rtrim($basePath, '/') . $filePath;