3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\ImageUploadException;
8 use Illuminate\Contracts\Cache\Repository as Cache;
9 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
10 use Illuminate\Contracts\Filesystem\FileNotFoundException;
11 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
12 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
13 use Illuminate\Support\Facades\DB;
14 use Illuminate\Support\Str;
15 use Intervention\Image\Exception\NotSupportedException;
16 use Intervention\Image\ImageManager;
17 use League\Flysystem\Util;
18 use Symfony\Component\HttpFoundation\File\UploadedFile;
19 use Symfony\Component\HttpFoundation\StreamedResponse;
25 protected $storageUrl;
27 protected $fileSystem;
30 * ImageService constructor.
32 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
34 $this->image = $image;
35 $this->imageTool = $imageTool;
36 $this->fileSystem = $fileSystem;
37 $this->cache = $cache;
41 * Get the storage that will be used for storing images.
43 protected function getStorageDisk(string $imageType = ''): FileSystemInstance
45 return $this->fileSystem->disk($this->getStorageDiskName($imageType));
49 * Check if local secure image storage (Fetched behind authentication)
50 * is currently active in the instance.
52 protected function usingSecureImages(): bool
54 return $this->getStorageDiskName('gallery') === 'local_secure_images';
58 * Change the originally provided path to fit any disk-specific requirements.
59 * This also ensures the path is kept to the expected root folders.
61 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
63 $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
65 if ($this->getStorageDiskName($imageType) === 'local_secure_images') {
69 return 'uploads/images/' . $path;
73 * Get the name of the storage disk to use.
75 protected function getStorageDiskName(string $imageType): string
77 $storageType = config('filesystems.images');
79 // Ensure system images (App logo) are uploaded to a public space
80 if ($imageType === 'system' && $storageType === 'local_secure') {
81 $storageType = 'local';
84 if ($storageType === 'local_secure') {
85 $storageType = 'local_secure_images';
92 * Saves a new image from an upload.
94 * @throws ImageUploadException
98 public function saveNewFromUpload(
99 UploadedFile $uploadedFile,
102 int $resizeWidth = null,
103 int $resizeHeight = null,
104 bool $keepRatio = true
106 $imageName = $uploadedFile->getClientOriginalName();
107 $imageData = file_get_contents($uploadedFile->getRealPath());
109 if ($resizeWidth !== null || $resizeHeight !== null) {
110 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
113 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
117 * Save a new image from a uri-encoded base64 string of data.
119 * @throws ImageUploadException
121 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
123 $splitData = explode(';base64,', $base64Uri);
124 if (count($splitData) < 2) {
125 throw new ImageUploadException('Invalid base64 image data provided');
127 $data = base64_decode($splitData[1]);
129 return $this->saveNew($name, $data, $type, $uploadedTo);
133 * Save a new image into storage.
135 * @throws ImageUploadException
137 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
139 $storage = $this->getStorageDisk($type);
140 $secureUploads = setting('app-secure-images');
141 $fileName = $this->cleanImageFileName($imageName);
143 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
145 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
146 $fileName = Str::random(3) . $fileName;
149 $fullPath = $imagePath . $fileName;
150 if ($secureUploads) {
151 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
155 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
156 } catch (Exception $e) {
157 \Log::error('Error when attempting image upload:' . $e->getMessage());
159 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
163 'name' => $imageName,
165 'url' => $this->getPublicUrl($fullPath),
167 'uploaded_to' => $uploadedTo,
170 if (user()->id !== 0) {
171 $userId = user()->id;
172 $imageDetails['created_by'] = $userId;
173 $imageDetails['updated_by'] = $userId;
176 $image = $this->image->newInstance();
177 $image->forceFill($imageDetails)->save();
183 * Save image data for the given path in the public space, if possible,
184 * for the provided storage mechanism.
186 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
188 $storage->put($path, $data);
190 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
191 // Done since this call can break s3-like services but desired for other image stores.
192 // Attempting to set ACL during above put request requires different permissions
193 // hence would technically be a breaking change for actual s3 usage.
194 $usingS3 = strtolower(config('filesystems.images')) === 's3';
195 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
197 $storage->setVisibility($path, 'public');
202 * Clean up an image file name to be both URL and storage safe.
204 protected function cleanImageFileName(string $name): string
206 $name = str_replace(' ', '-', $name);
207 $nameParts = explode('.', $name);
208 $extension = array_pop($nameParts);
209 $name = implode('-', $nameParts);
210 $name = Str::slug($name);
212 if (strlen($name) === 0) {
213 $name = Str::random(10);
216 return $name . '.' . $extension;
220 * Checks if the image is a gif. Returns true if it is, else false.
222 protected function isGif(Image $image): bool
224 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
228 * Get the thumbnail for an image.
229 * If $keepRatio is true only the width will be used.
230 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
232 * @param Image $image
235 * @param bool $keepRatio
238 * @throws ImageUploadException
242 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
244 if ($keepRatio && $this->isGif($image)) {
245 return $this->getPublicUrl($image->path);
248 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
249 $imagePath = $image->path;
250 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
252 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
253 return $this->getPublicUrl($thumbFilePath);
256 $storage = $this->getStorageDisk($image->type);
257 if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
258 return $this->getPublicUrl($thumbFilePath);
261 $thumbData = $this->resizeImage($storage->get($this->adjustPathForStorageDisk($imagePath, $image->type)), $width, $height, $keepRatio);
263 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
264 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
266 return $this->getPublicUrl($thumbFilePath);
272 * @param string $imageData
275 * @param bool $keepRatio
277 * @throws ImageUploadException
281 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
284 $thumb = $this->imageTool->make($imageData);
285 } catch (Exception $e) {
286 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
287 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
294 $thumb->resize($width, $height, function ($constraint) {
295 $constraint->aspectRatio();
296 $constraint->upsize();
299 $thumb->fit($width, $height);
302 $thumbData = (string) $thumb->encode();
304 // Use original image data if we're keeping the ratio
305 // and the resizing does not save any space.
306 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
314 * Get the raw data content from an image.
316 * @throws FileNotFoundException
318 public function getImageData(Image $image): string
320 $storage = $this->getStorageDisk();
322 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
326 * Destroy an image along with its revisions, thumbnails and remaining folders.
330 public function destroy(Image $image)
332 $this->destroyImagesFromPath($image->path, $image->type);
337 * Destroys an image at the given path.
338 * Searches for image thumbnails in addition to main provided path.
340 protected function destroyImagesFromPath(string $path, string $imageType): bool
342 $path = $this->adjustPathForStorageDisk($path, $imageType);
343 $storage = $this->getStorageDisk($imageType);
345 $imageFolder = dirname($path);
346 $imageFileName = basename($path);
347 $allImages = collect($storage->allFiles($imageFolder));
349 // Delete image files
350 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
351 return basename($imagePath) === $imageFileName;
353 $storage->delete($imagesToDelete->all());
355 // Cleanup of empty folders
356 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
357 foreach ($foldersInvolved as $directory) {
358 if ($this->isFolderEmpty($storage, $directory)) {
359 $storage->deleteDirectory($directory);
367 * Check whether a folder is empty.
369 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
371 $files = $storage->files($path);
372 $folders = $storage->directories($path);
374 return count($files) === 0 && count($folders) === 0;
378 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
379 * Checks based off of only the image name.
380 * Could be much improved to be more specific but kept it generic for now to be safe.
382 * Returns the path of the images that would be/have been deleted.
384 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
386 $types = ['gallery', 'drawio'];
389 $this->image->newQuery()->whereIn('type', $types)
390 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
391 foreach ($images as $image) {
392 $searchQuery = '%' . basename($image->path) . '%';
393 $inPage = DB::table('pages')
394 ->where('html', 'like', $searchQuery)->count() > 0;
397 if ($checkRevisions) {
398 $inRevision = DB::table('page_revisions')
399 ->where('html', 'like', $searchQuery)->count() > 0;
402 if (!$inPage && !$inRevision) {
403 $deletedPaths[] = $image->path;
405 $this->destroy($image);
411 return $deletedPaths;
415 * Convert an image URI to a Base64 encoded string.
416 * Attempts to convert the URL to a system storage url then
417 * fetch the data from the disk or storage location.
418 * Returns null if the image data cannot be fetched from storage.
420 * @throws FileNotFoundException
422 public function imageUriToBase64(string $uri): ?string
424 $storagePath = $this->imageUrlToStoragePath($uri);
425 if (empty($uri) || is_null($storagePath)) {
429 $storagePath = $this->adjustPathForStorageDisk($storagePath);
430 $storage = $this->getStorageDisk();
432 if ($storage->exists($storagePath)) {
433 $imageData = $storage->get($storagePath);
436 if (is_null($imageData)) {
440 $extension = pathinfo($uri, PATHINFO_EXTENSION);
441 if ($extension === 'svg') {
442 $extension = 'svg+xml';
445 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
449 * Check if the given path exists in the local secure image system.
450 * Returns false if local_secure is not in use.
452 public function pathExistsInLocalSecure(string $imagePath): bool
454 $disk = $this->getStorageDisk('gallery');
456 // Check local_secure is active
457 return $this->usingSecureImages()
458 // Check the image file exists
459 && $disk->exists($imagePath)
460 // Check the file is likely an image file
461 && strpos($disk->getMimetype($imagePath), 'image/') === 0;
465 * For the given path, if existing, provide a response that will stream the image contents.
467 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
469 $disk = $this->getStorageDisk($imageType);
470 return $disk->response($path);
474 * Get a storage path for the given image URL.
475 * Ensures the path will start with "uploads/images".
476 * Returns null if the url cannot be resolved to a local URL.
478 private function imageUrlToStoragePath(string $url): ?string
480 $url = ltrim(trim($url), '/');
482 // Handle potential relative paths
483 $isRelative = strpos($url, 'http') !== 0;
485 if (strpos(strtolower($url), 'uploads/images') === 0) {
486 return trim($url, '/');
492 // Handle local images based on paths on the same domain
493 $potentialHostPaths = [
494 url('uploads/images/'),
495 $this->getPublicUrl('/uploads/images/'),
498 foreach ($potentialHostPaths as $potentialBasePath) {
499 $potentialBasePath = strtolower($potentialBasePath);
500 if (strpos(strtolower($url), $potentialBasePath) === 0) {
501 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
509 * Gets a public facing url for an image by checking relevant environment variables.
510 * If s3-style store is in use it will default to guessing a public bucket URL.
512 private function getPublicUrl(string $filePath): string
514 if ($this->storageUrl === null) {
515 $storageUrl = config('filesystems.url');
517 // Get the standard public s3 url if s3 is set as storage type
518 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
519 // region-based url will be used to prevent http issues.
520 if ($storageUrl == false && config('filesystems.images') === 's3') {
521 $storageDetails = config('filesystems.disks.s3');
522 if (strpos($storageDetails['bucket'], '.') === false) {
523 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
525 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
528 $this->storageUrl = $storageUrl;
531 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
533 return rtrim($basePath, '/') . $filePath;