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;
24 protected $storageUrl;
26 protected $fileSystem;
29 * ImageService constructor.
31 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
33 $this->image = $image;
34 $this->imageTool = $imageTool;
35 $this->fileSystem = $fileSystem;
36 $this->cache = $cache;
40 * Get the storage that will be used for storing images.
42 protected function getStorage(string $imageType = ''): FileSystemInstance
44 return $this->fileSystem->disk($this->getStorageDiskName($imageType));
48 * Change the originally provided path to fit any disk-specific requirements.
49 * This also ensures the path is kept to the expected root folders.
51 protected function adjustPathForStorageDisk(string $path, string $imageType = ''): string
53 $path = Util::normalizePath(str_replace('uploads/images/', '', $path));
55 if ($this->getStorageDiskName($imageType) === 'local_secure_images') {
59 return 'uploads/images/' . $path;
63 * Get the name of the storage disk to use.
65 protected function getStorageDiskName(string $imageType): string
67 $storageType = config('filesystems.images');
69 // Ensure system images (App logo) are uploaded to a public space
70 if ($imageType === 'system' && $storageType === 'local_secure') {
71 $storageType = 'local';
74 if ($storageType === 'local_secure') {
75 $storageType = 'local_secure_images';
82 * Saves a new image from an upload.
84 * @throws ImageUploadException
88 public function saveNewFromUpload(
89 UploadedFile $uploadedFile,
92 int $resizeWidth = null,
93 int $resizeHeight = null,
94 bool $keepRatio = true
96 $imageName = $uploadedFile->getClientOriginalName();
97 $imageData = file_get_contents($uploadedFile->getRealPath());
99 if ($resizeWidth !== null || $resizeHeight !== null) {
100 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
103 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
107 * Save a new image from a uri-encoded base64 string of data.
109 * @throws ImageUploadException
111 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
113 $splitData = explode(';base64,', $base64Uri);
114 if (count($splitData) < 2) {
115 throw new ImageUploadException('Invalid base64 image data provided');
117 $data = base64_decode($splitData[1]);
119 return $this->saveNew($name, $data, $type, $uploadedTo);
123 * Save a new image into storage.
125 * @throws ImageUploadException
127 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
129 $storage = $this->getStorage($type);
130 $secureUploads = setting('app-secure-images');
131 $fileName = $this->cleanImageFileName($imageName);
133 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
135 while ($storage->exists($this->adjustPathForStorageDisk($imagePath . $fileName, $type))) {
136 $fileName = Str::random(3) . $fileName;
139 $fullPath = $imagePath . $fileName;
140 if ($secureUploads) {
141 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
145 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($fullPath, $type), $imageData);
146 } catch (Exception $e) {
147 \Log::error('Error when attempting image upload:' . $e->getMessage());
149 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
153 'name' => $imageName,
155 'url' => $this->getPublicUrl($fullPath),
157 'uploaded_to' => $uploadedTo,
160 if (user()->id !== 0) {
161 $userId = user()->id;
162 $imageDetails['created_by'] = $userId;
163 $imageDetails['updated_by'] = $userId;
166 $image = $this->image->newInstance();
167 $image->forceFill($imageDetails)->save();
173 * Save image data for the given path in the public space, if possible,
174 * for the provided storage mechanism.
176 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
178 $storage->put($path, $data);
180 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
181 // Done since this call can break s3-like services but desired for other image stores.
182 // Attempting to set ACL during above put request requires different permissions
183 // hence would technically be a breaking change for actual s3 usage.
184 $usingS3 = strtolower(config('filesystems.images')) === 's3';
185 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
187 $storage->setVisibility($path, 'public');
192 * Clean up an image file name to be both URL and storage safe.
194 protected function cleanImageFileName(string $name): string
196 $name = str_replace(' ', '-', $name);
197 $nameParts = explode('.', $name);
198 $extension = array_pop($nameParts);
199 $name = implode('-', $nameParts);
200 $name = Str::slug($name);
202 if (strlen($name) === 0) {
203 $name = Str::random(10);
206 return $name . '.' . $extension;
210 * Checks if the image is a gif. Returns true if it is, else false.
212 protected function isGif(Image $image): bool
214 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
218 * Get the thumbnail for an image.
219 * If $keepRatio is true only the width will be used.
220 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
222 * @param Image $image
225 * @param bool $keepRatio
228 * @throws ImageUploadException
232 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
234 if ($keepRatio && $this->isGif($image)) {
235 return $this->getPublicUrl($image->path);
238 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
239 $imagePath = $image->path;
240 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
242 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
243 return $this->getPublicUrl($thumbFilePath);
246 $storage = $this->getStorage($image->type);
247 if ($storage->exists($this->adjustPathForStorageDisk($thumbFilePath, $image->type))) {
248 return $this->getPublicUrl($thumbFilePath);
251 $thumbData = $this->resizeImage($storage->get($this->adjustPathForStorageDisk($imagePath, $image->type)), $width, $height, $keepRatio);
253 $this->saveImageDataInPublicSpace($storage, $this->adjustPathForStorageDisk($thumbFilePath, $image->type), $thumbData);
254 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
256 return $this->getPublicUrl($thumbFilePath);
262 * @param string $imageData
265 * @param bool $keepRatio
267 * @throws ImageUploadException
271 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
274 $thumb = $this->imageTool->make($imageData);
275 } catch (Exception $e) {
276 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
277 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
284 $thumb->resize($width, $height, function ($constraint) {
285 $constraint->aspectRatio();
286 $constraint->upsize();
289 $thumb->fit($width, $height);
292 $thumbData = (string) $thumb->encode();
294 // Use original image data if we're keeping the ratio
295 // and the resizing does not save any space.
296 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
304 * Get the raw data content from an image.
306 * @throws FileNotFoundException
308 public function getImageData(Image $image): string
310 $storage = $this->getStorage();
311 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
315 * Destroy an image along with its revisions, thumbnails and remaining folders.
319 public function destroy(Image $image)
321 $this->destroyImagesFromPath($image->path, $image->type);
326 * Destroys an image at the given path.
327 * Searches for image thumbnails in addition to main provided path.
329 protected function destroyImagesFromPath(string $path, string $imageType): bool
331 $path = $this->adjustPathForStorageDisk($path, $imageType);
332 $storage = $this->getStorage($imageType);
334 $imageFolder = dirname($path);
335 $imageFileName = basename($path);
336 $allImages = collect($storage->allFiles($imageFolder));
338 // Delete image files
339 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
340 return basename($imagePath) === $imageFileName;
342 $storage->delete($imagesToDelete->all());
344 // Cleanup of empty folders
345 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
346 foreach ($foldersInvolved as $directory) {
347 if ($this->isFolderEmpty($storage, $directory)) {
348 $storage->deleteDirectory($directory);
356 * Check whether a folder is empty.
358 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
360 $files = $storage->files($path);
361 $folders = $storage->directories($path);
363 return count($files) === 0 && count($folders) === 0;
367 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
368 * Checks based off of only the image name.
369 * Could be much improved to be more specific but kept it generic for now to be safe.
371 * Returns the path of the images that would be/have been deleted.
373 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
375 $types = ['gallery', 'drawio'];
378 $this->image->newQuery()->whereIn('type', $types)
379 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
380 foreach ($images as $image) {
381 $searchQuery = '%' . basename($image->path) . '%';
382 $inPage = DB::table('pages')
383 ->where('html', 'like', $searchQuery)->count() > 0;
386 if ($checkRevisions) {
387 $inRevision = DB::table('page_revisions')
388 ->where('html', 'like', $searchQuery)->count() > 0;
391 if (!$inPage && !$inRevision) {
392 $deletedPaths[] = $image->path;
394 $this->destroy($image);
400 return $deletedPaths;
404 * Convert an image URI to a Base64 encoded string.
405 * Attempts to convert the URL to a system storage url then
406 * fetch the data from the disk or storage location.
407 * Returns null if the image data cannot be fetched from storage.
409 * @throws FileNotFoundException
411 public function imageUriToBase64(string $uri): ?string
413 $storagePath = $this->imageUrlToStoragePath($uri);
414 if (empty($uri) || is_null($storagePath)) {
418 $storagePath = $this->adjustPathForStorageDisk($storagePath);
419 $storage = $this->getStorage();
421 if ($storage->exists($storagePath)) {
422 $imageData = $storage->get($storagePath);
425 if (is_null($imageData)) {
429 $extension = pathinfo($uri, PATHINFO_EXTENSION);
430 if ($extension === 'svg') {
431 $extension = 'svg+xml';
434 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
438 * Get a storage path for the given image URL.
439 * Ensures the path will start with "uploads/images".
440 * Returns null if the url cannot be resolved to a local URL.
442 private function imageUrlToStoragePath(string $url): ?string
444 $url = ltrim(trim($url), '/');
446 // Handle potential relative paths
447 $isRelative = strpos($url, 'http') !== 0;
449 if (strpos(strtolower($url), 'uploads/images') === 0) {
450 return trim($url, '/');
456 // Handle local images based on paths on the same domain
457 $potentialHostPaths = [
458 url('uploads/images/'),
459 $this->getPublicUrl('/uploads/images/'),
462 foreach ($potentialHostPaths as $potentialBasePath) {
463 $potentialBasePath = strtolower($potentialBasePath);
464 if (strpos(strtolower($url), $potentialBasePath) === 0) {
465 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
473 * Gets a public facing url for an image by checking relevant environment variables.
474 * If s3-style store is in use it will default to guessing a public bucket URL.
476 private function getPublicUrl(string $filePath): string
478 if ($this->storageUrl === null) {
479 $storageUrl = config('filesystems.url');
481 // Get the standard public s3 url if s3 is set as storage type
482 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
483 // region-based url will be used to prevent http issues.
484 if ($storageUrl == false && config('filesystems.images') === 's3') {
485 $storageDetails = config('filesystems.disks.s3');
486 if (strpos($storageDetails['bucket'], '.') === false) {
487 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
489 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
492 $this->storageUrl = $storageUrl;
495 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
497 return rtrim($basePath, '/') . $filePath;