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\FilesystemManager;
12 use Illuminate\Support\Facades\DB;
13 use Illuminate\Support\Facades\Log;
14 use Illuminate\Support\Str;
15 use Intervention\Image\Exception\NotSupportedException;
16 use Intervention\Image\ImageManager;
17 use League\Flysystem\Util;
18 use Psr\SimpleCache\InvalidArgumentException;
19 use Symfony\Component\HttpFoundation\File\UploadedFile;
20 use Symfony\Component\HttpFoundation\StreamedResponse;
26 protected $storageUrl;
28 protected $fileSystem;
30 protected static $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
33 * ImageService constructor.
35 public function __construct(Image $image, ImageManager $imageTool, FilesystemManager $fileSystem, Cache $cache)
37 $this->image = $image;
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(): bool
57 return $this->getStorageDiskName('gallery') === 'local_secure_images';
61 * Change the originally provided path to fit any disk-specific requirements.
62 * This also ensures the path is kept to the expected root folders.
64 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
66 $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
68 if ($this->getStorageDiskName($imageType) === 'local_secure_images') {
72 return 'uploads/images/' . $path;
76 * Get the name of the storage disk to use.
78 protected function getStorageDiskName(string $imageType): string
80 $storageType = config('filesystems.images');
82 // Ensure system images (App logo) are uploaded to a public space
83 if ($imageType === 'system' && $storageType === 'local_secure') {
84 $storageType = 'local';
87 if ($storageType === 'local_secure') {
88 $storageType = 'local_secure_images';
95 * Saves a new image from an upload.
97 * @throws ImageUploadException
101 public function saveNewFromUpload(
102 UploadedFile $uploadedFile,
105 int $resizeWidth = null,
106 int $resizeHeight = null,
107 bool $keepRatio = true
109 $imageName = $uploadedFile->getClientOriginalName();
110 $imageData = file_get_contents($uploadedFile->getRealPath());
112 if ($resizeWidth !== null || $resizeHeight !== null) {
113 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
116 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
120 * Save a new image from a uri-encoded base64 string of data.
122 * @throws ImageUploadException
124 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
126 $splitData = explode(';base64,', $base64Uri);
127 if (count($splitData) < 2) {
128 throw new ImageUploadException('Invalid base64 image data provided');
130 $data = base64_decode($splitData[1]);
132 return $this->saveNew($name, $data, $type, $uploadedTo);
136 * Save a new image into storage.
138 * @throws ImageUploadException
140 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
142 $storage = $this->getStorageDisk($type);
143 $secureUploads = setting('app-secure-images');
144 $fileName = $this->cleanImageFileName($imageName);
146 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
148 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
149 $fileName = Str::random(3) . $fileName;
152 $fullPath = $imagePath . $fileName;
153 if ($secureUploads) {
154 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
158 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
159 } catch (Exception $e) {
160 Log::error('Error when attempting image upload:' . $e->getMessage());
162 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
166 'name' => $imageName,
168 'url' => $this->getPublicUrl($fullPath),
170 'uploaded_to' => $uploadedTo,
173 if (user()->id !== 0) {
174 $userId = user()->id;
175 $imageDetails['created_by'] = $userId;
176 $imageDetails['updated_by'] = $userId;
179 $image = $this->image->newInstance();
180 $image->forceFill($imageDetails)->save();
186 * Save image data for the given path in the public space, if possible,
187 * for the provided storage mechanism.
189 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
191 $storage->put($path, $data);
193 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
194 // Done since this call can break s3-like services but desired for other image stores.
195 // Attempting to set ACL during above put request requires different permissions
196 // hence would technically be a breaking change for actual s3 usage.
197 $usingS3 = strtolower(config('filesystems.images')) === 's3';
198 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
200 $storage->setVisibility($path, 'public');
205 * Clean up an image file name to be both URL and storage safe.
207 protected function cleanImageFileName(string $name): string
209 $name = str_replace(' ', '-', $name);
210 $nameParts = explode('.', $name);
211 $extension = array_pop($nameParts);
212 $name = implode('-', $nameParts);
213 $name = Str::slug($name);
215 if (strlen($name) === 0) {
216 $name = Str::random(10);
219 return $name . '.' . $extension;
223 * Checks if the image is a gif. Returns true if it is, else false.
225 protected function isGif(Image $image): bool
227 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
231 * Get the thumbnail for an image.
232 * If $keepRatio is true only the width will be used.
233 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
236 * @throws InvalidArgumentException
238 public function getThumbnail(Image $image, ?int $width, ?int $height, bool $keepRatio = false): string
240 if ($keepRatio && $this->isGif($image)) {
241 return $this->getPublicUrl($image->path);
244 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
245 $imagePath = $image->path;
246 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
248 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
249 return $this->getPublicUrl($thumbFilePath);
252 $storage = $this->getStorageDisk($image->type);
253 if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
254 return $this->getPublicUrl($thumbFilePath);
257 $thumbData = $this->resizeImage($storage->get($this->adjustPathForStorageDisk($imagePath, $image->type)), $width, $height, $keepRatio);
259 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
260 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
262 return $this->getPublicUrl($thumbFilePath);
266 * Resize the image of given data to the specified size, and return the new image data.
268 * @throws ImageUploadException
270 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
273 $thumb = $this->imageTool->make($imageData);
274 } catch (ErrorException|NotSupportedException $e) {
275 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
279 $thumb->resize($width, $height, function ($constraint) {
280 $constraint->aspectRatio();
281 $constraint->upsize();
284 $thumb->fit($width, $height);
287 $thumbData = (string) $thumb->encode();
289 // Use original image data if we're keeping the ratio
290 // and the resizing does not save any space.
291 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
299 * Get the raw data content from an image.
301 * @throws FileNotFoundException
303 public function getImageData(Image $image): string
305 $storage = $this->getStorageDisk();
307 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
311 * Destroy an image along with its revisions, thumbnails and remaining folders.
315 public function destroy(Image $image)
317 $this->destroyImagesFromPath($image->path, $image->type);
322 * Destroys an image at the given path.
323 * Searches for image thumbnails in addition to main provided path.
325 protected function destroyImagesFromPath(string $path, string $imageType): bool
327 $path = $this->adjustPathForStorageDisk($path, $imageType);
328 $storage = $this->getStorageDisk($imageType);
330 $imageFolder = dirname($path);
331 $imageFileName = basename($path);
332 $allImages = collect($storage->allFiles($imageFolder));
334 // Delete image files
335 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
336 return basename($imagePath) === $imageFileName;
338 $storage->delete($imagesToDelete->all());
340 // Cleanup of empty folders
341 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
342 foreach ($foldersInvolved as $directory) {
343 if ($this->isFolderEmpty($storage, $directory)) {
344 $storage->deleteDirectory($directory);
352 * Check whether a folder is empty.
354 protected function isFolderEmpty(Storage $storage, string $path): bool
356 $files = $storage->files($path);
357 $folders = $storage->directories($path);
359 return count($files) === 0 && count($folders) === 0;
363 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
364 * Checks based off of only the image name.
365 * Could be much improved to be more specific but kept it generic for now to be safe.
367 * Returns the path of the images that would be/have been deleted.
369 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
371 $types = ['gallery', 'drawio'];
374 $this->image->newQuery()->whereIn('type', $types)
375 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
376 foreach ($images as $image) {
377 $searchQuery = '%' . basename($image->path) . '%';
378 $inPage = DB::table('pages')
379 ->where('html', 'like', $searchQuery)->count() > 0;
382 if ($checkRevisions) {
383 $inRevision = DB::table('page_revisions')
384 ->where('html', 'like', $searchQuery)->count() > 0;
387 if (!$inPage && !$inRevision) {
388 $deletedPaths[] = $image->path;
390 $this->destroy($image);
396 return $deletedPaths;
400 * Convert an image URI to a Base64 encoded string.
401 * Attempts to convert the URL to a system storage url then
402 * fetch the data from the disk or storage location.
403 * Returns null if the image data cannot be fetched from storage.
405 * @throws FileNotFoundException
407 public function imageUriToBase64(string $uri): ?string
409 $storagePath = $this->imageUrlToStoragePath($uri);
410 if (empty($uri) || is_null($storagePath)) {
414 $storagePath = $this->adjustPathForStorageDisk($storagePath);
415 $storage = $this->getStorageDisk();
417 if ($storage->exists($storagePath)) {
418 $imageData = $storage->get($storagePath);
421 if (is_null($imageData)) {
425 $extension = pathinfo($uri, PATHINFO_EXTENSION);
426 if ($extension === 'svg') {
427 $extension = 'svg+xml';
430 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
434 * Check if the given path exists in the local secure image system.
435 * Returns false if local_secure is not in use.
437 public function pathExistsInLocalSecure(string $imagePath): bool
439 $disk = $this->getStorageDisk('gallery');
441 // Check local_secure is active
442 return $this->usingSecureImages()
443 // Check the image file exists
444 && $disk->exists($imagePath)
445 // Check the file is likely an image file
446 && strpos($disk->getMimetype($imagePath), 'image/') === 0;
450 * For the given path, if existing, provide a response that will stream the image contents.
452 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
454 $disk = $this->getStorageDisk($imageType);
456 return $disk->response($path);
460 * Check if the given image extension is supported by BookStack.
461 * The extension must not be altered in this function. This check should provide a guarantee
462 * that the provided extension is safe to use for the image to be saved.
464 public static function isExtensionSupported(string $extension): bool
466 return in_array($extension, static::$supportedExtensions);
470 * Get a storage path for the given image URL.
471 * Ensures the path will start with "uploads/images".
472 * Returns null if the url cannot be resolved to a local URL.
474 private function imageUrlToStoragePath(string $url): ?string
476 $url = ltrim(trim($url), '/');
478 // Handle potential relative paths
479 $isRelative = strpos($url, 'http') !== 0;
481 if (strpos(strtolower($url), 'uploads/images') === 0) {
482 return trim($url, '/');
488 // Handle local images based on paths on the same domain
489 $potentialHostPaths = [
490 url('uploads/images/'),
491 $this->getPublicUrl('/uploads/images/'),
494 foreach ($potentialHostPaths as $potentialBasePath) {
495 $potentialBasePath = strtolower($potentialBasePath);
496 if (strpos(strtolower($url), $potentialBasePath) === 0) {
497 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
505 * Gets a public facing url for an image by checking relevant environment variables.
506 * If s3-style store is in use it will default to guessing a public bucket URL.
508 private function getPublicUrl(string $filePath): string
510 if (is_null($this->storageUrl)) {
511 $storageUrl = config('filesystems.url');
513 // Get the standard public s3 url if s3 is set as storage type
514 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
515 // region-based url will be used to prevent http issues.
516 if ($storageUrl == false && config('filesystems.images') === 's3') {
517 $storageDetails = config('filesystems.disks.s3');
518 if (strpos($storageDetails['bucket'], '.') === false) {
519 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
521 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
525 $this->storageUrl = $storageUrl;
528 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
530 return rtrim($basePath, '/') . $filePath;