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();
312 return $storage->get($this->adjustPathForStorageDisk($image->path, $image->type));
316 * Destroy an image along with its revisions, thumbnails and remaining folders.
320 public function destroy(Image $image)
322 $this->destroyImagesFromPath($image->path, $image->type);
327 * Destroys an image at the given path.
328 * Searches for image thumbnails in addition to main provided path.
330 protected function destroyImagesFromPath(string $path, string $imageType): bool
332 $path = $this->adjustPathForStorageDisk($path, $imageType);
333 $storage = $this->getStorage($imageType);
335 $imageFolder = dirname($path);
336 $imageFileName = basename($path);
337 $allImages = collect($storage->allFiles($imageFolder));
339 // Delete image files
340 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
341 return basename($imagePath) === $imageFileName;
343 $storage->delete($imagesToDelete->all());
345 // Cleanup of empty folders
346 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
347 foreach ($foldersInvolved as $directory) {
348 if ($this->isFolderEmpty($storage, $directory)) {
349 $storage->deleteDirectory($directory);
357 * Check whether a folder is empty.
359 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
361 $files = $storage->files($path);
362 $folders = $storage->directories($path);
364 return count($files) === 0 && count($folders) === 0;
368 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
369 * Checks based off of only the image name.
370 * Could be much improved to be more specific but kept it generic for now to be safe.
372 * Returns the path of the images that would be/have been deleted.
374 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
376 $types = ['gallery', 'drawio'];
379 $this->image->newQuery()->whereIn('type', $types)
380 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
381 foreach ($images as $image) {
382 $searchQuery = '%' . basename($image->path) . '%';
383 $inPage = DB::table('pages')
384 ->where('html', 'like', $searchQuery)->count() > 0;
387 if ($checkRevisions) {
388 $inRevision = DB::table('page_revisions')
389 ->where('html', 'like', $searchQuery)->count() > 0;
392 if (!$inPage && !$inRevision) {
393 $deletedPaths[] = $image->path;
395 $this->destroy($image);
401 return $deletedPaths;
405 * Convert an image URI to a Base64 encoded string.
406 * Attempts to convert the URL to a system storage url then
407 * fetch the data from the disk or storage location.
408 * Returns null if the image data cannot be fetched from storage.
410 * @throws FileNotFoundException
412 public function imageUriToBase64(string $uri): ?string
414 $storagePath = $this->imageUrlToStoragePath($uri);
415 if (empty($uri) || is_null($storagePath)) {
419 $storagePath = $this->adjustPathForStorageDisk($storagePath);
420 $storage = $this->getStorage();
422 if ($storage->exists($storagePath)) {
423 $imageData = $storage->get($storagePath);
426 if (is_null($imageData)) {
430 $extension = pathinfo($uri, PATHINFO_EXTENSION);
431 if ($extension === 'svg') {
432 $extension = 'svg+xml';
435 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
439 * Get a storage path for the given image URL.
440 * Ensures the path will start with "uploads/images".
441 * Returns null if the url cannot be resolved to a local URL.
443 private function imageUrlToStoragePath(string $url): ?string
445 $url = ltrim(trim($url), '/');
447 // Handle potential relative paths
448 $isRelative = strpos($url, 'http') !== 0;
450 if (strpos(strtolower($url), 'uploads/images') === 0) {
451 return trim($url, '/');
457 // Handle local images based on paths on the same domain
458 $potentialHostPaths = [
459 url('uploads/images/'),
460 $this->getPublicUrl('/uploads/images/'),
463 foreach ($potentialHostPaths as $potentialBasePath) {
464 $potentialBasePath = strtolower($potentialBasePath);
465 if (strpos(strtolower($url), $potentialBasePath) === 0) {
466 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
474 * Gets a public facing url for an image by checking relevant environment variables.
475 * If s3-style store is in use it will default to guessing a public bucket URL.
477 private function getPublicUrl(string $filePath): string
479 if ($this->storageUrl === null) {
480 $storageUrl = config('filesystems.url');
482 // Get the standard public s3 url if s3 is set as storage type
483 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
484 // region-based url will be used to prevent http issues.
485 if ($storageUrl == false && config('filesystems.images') === 's3') {
486 $storageDetails = config('filesystems.disks.s3');
487 if (strpos($storageDetails['bucket'], '.') === false) {
488 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
490 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
493 $this->storageUrl = $storageUrl;
496 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
498 return rtrim($basePath, '/') . $filePath;