3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\ImageUploadException;
9 use Illuminate\Contracts\Cache\Repository as Cache;
10 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
11 use Illuminate\Contracts\Filesystem\FileNotFoundException;
12 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
13 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
14 use Illuminate\Support\Str;
15 use Intervention\Image\Exception\NotSupportedException;
16 use Intervention\Image\ImageManager;
17 use Symfony\Component\HttpFoundation\File\UploadedFile;
23 protected $storageUrl;
25 protected $fileSystem;
28 * ImageService constructor.
30 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
32 $this->image = $image;
33 $this->imageTool = $imageTool;
34 $this->fileSystem = $fileSystem;
35 $this->cache = $cache;
39 * Get the storage that will be used for storing images.
41 protected function getStorage(string $type = ''): FileSystemInstance
43 $storageType = config('filesystems.images');
45 // Ensure system images (App logo) are uploaded to a public space
46 if ($type === 'system' && $storageType === 'local_secure') {
47 $storageType = 'local';
50 return $this->fileSystem->disk($storageType);
54 * Saves a new image from an upload.
56 * @throws ImageUploadException
60 public function saveNewFromUpload(
61 UploadedFile $uploadedFile,
64 int $resizeWidth = null,
65 int $resizeHeight = null,
66 bool $keepRatio = true
68 $imageName = $uploadedFile->getClientOriginalName();
69 $imageData = file_get_contents($uploadedFile->getRealPath());
71 if ($resizeWidth !== null || $resizeHeight !== null) {
72 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
75 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
79 * Save a new image from a uri-encoded base64 string of data.
81 * @throws ImageUploadException
83 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
85 $splitData = explode(';base64,', $base64Uri);
86 if (count($splitData) < 2) {
87 throw new ImageUploadException('Invalid base64 image data provided');
89 $data = base64_decode($splitData[1]);
91 return $this->saveNew($name, $data, $type, $uploadedTo);
95 * Save a new image into storage.
97 * @throws ImageUploadException
99 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
101 $storage = $this->getStorage($type);
102 $secureUploads = setting('app-secure-images');
103 $fileName = $this->cleanImageFileName($imageName);
105 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
107 while ($storage->exists($imagePath . $fileName)) {
108 $fileName = Str::random(3) . $fileName;
111 $fullPath = $imagePath . $fileName;
112 if ($secureUploads) {
113 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
117 $this->saveImageDataInPublicSpace($storage, $fullPath, $imageData);
118 } catch (Exception $e) {
119 \Log::error('Error when attempting image upload:' . $e->getMessage());
121 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
125 'name' => $imageName,
127 'url' => $this->getPublicUrl($fullPath),
129 'uploaded_to' => $uploadedTo,
132 if (user()->id !== 0) {
133 $userId = user()->id;
134 $imageDetails['created_by'] = $userId;
135 $imageDetails['updated_by'] = $userId;
138 $image = $this->image->newInstance();
139 $image->forceFill($imageDetails)->save();
145 * Save image data for the given path in the public space, if possible,
146 * for the provided storage mechanism.
148 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
150 $storage->put($path, $data);
152 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
153 // Done since this call can break s3-like services but desired for other image stores.
154 // Attempting to set ACL during above put request requires different permissions
155 // hence would technically be a breaking change for actual s3 usage.
156 $usingS3 = strtolower(config('filesystems.images')) === 's3';
157 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
159 $storage->setVisibility($path, 'public');
164 * Clean up an image file name to be both URL and storage safe.
166 protected function cleanImageFileName(string $name): string
168 $name = str_replace(' ', '-', $name);
169 $nameParts = explode('.', $name);
170 $extension = array_pop($nameParts);
171 $name = implode('-', $nameParts);
172 $name = Str::slug($name);
174 if (strlen($name) === 0) {
175 $name = Str::random(10);
178 return $name . '.' . $extension;
182 * Checks if the image is a gif. Returns true if it is, else false.
184 protected function isGif(Image $image): bool
186 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
190 * Get the thumbnail for an image.
191 * If $keepRatio is true only the width will be used.
192 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
194 * @param Image $image
197 * @param bool $keepRatio
200 * @throws ImageUploadException
204 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
206 if ($keepRatio && $this->isGif($image)) {
207 return $this->getPublicUrl($image->path);
210 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
211 $imagePath = $image->path;
212 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
214 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
215 return $this->getPublicUrl($thumbFilePath);
218 $storage = $this->getStorage($image->type);
219 if ($storage->exists($thumbFilePath)) {
220 return $this->getPublicUrl($thumbFilePath);
223 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
225 $this->saveImageDataInPublicSpace($storage, $thumbFilePath, $thumbData);
226 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
228 return $this->getPublicUrl($thumbFilePath);
234 * @param string $imageData
237 * @param bool $keepRatio
239 * @throws ImageUploadException
243 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
246 $thumb = $this->imageTool->make($imageData);
247 } catch (Exception $e) {
248 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
249 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
256 $thumb->resize($width, $height, function ($constraint) {
257 $constraint->aspectRatio();
258 $constraint->upsize();
261 $thumb->fit($width, $height);
264 $thumbData = (string) $thumb->encode();
266 // Use original image data if we're keeping the ratio
267 // and the resizing does not save any space.
268 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
276 * Get the raw data content from an image.
278 * @throws FileNotFoundException
280 public function getImageData(Image $image): string
282 $imagePath = $image->path;
283 $storage = $this->getStorage();
285 return $storage->get($imagePath);
289 * Destroy an image along with its revisions, thumbnails and remaining folders.
293 public function destroy(Image $image)
295 $this->destroyImagesFromPath($image->path);
300 * Destroys an image at the given path.
301 * Searches for image thumbnails in addition to main provided path.
303 protected function destroyImagesFromPath(string $path): bool
305 $storage = $this->getStorage();
307 $imageFolder = dirname($path);
308 $imageFileName = basename($path);
309 $allImages = collect($storage->allFiles($imageFolder));
311 // Delete image files
312 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
313 return basename($imagePath) === $imageFileName;
315 $storage->delete($imagesToDelete->all());
317 // Cleanup of empty folders
318 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
319 foreach ($foldersInvolved as $directory) {
320 if ($this->isFolderEmpty($storage, $directory)) {
321 $storage->deleteDirectory($directory);
329 * Check whether or not a folder is empty.
331 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
333 $files = $storage->files($path);
334 $folders = $storage->directories($path);
336 return count($files) === 0 && count($folders) === 0;
340 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
341 * Checks based off of only the image name.
342 * Could be much improved to be more specific but kept it generic for now to be safe.
344 * Returns the path of the images that would be/have been deleted.
346 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
348 $types = ['gallery', 'drawio'];
351 $this->image->newQuery()->whereIn('type', $types)
352 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
353 foreach ($images as $image) {
354 $searchQuery = '%' . basename($image->path) . '%';
355 $inPage = DB::table('pages')
356 ->where('html', 'like', $searchQuery)->count() > 0;
359 if ($checkRevisions) {
360 $inRevision = DB::table('page_revisions')
361 ->where('html', 'like', $searchQuery)->count() > 0;
364 if (!$inPage && !$inRevision) {
365 $deletedPaths[] = $image->path;
367 $this->destroy($image);
373 return $deletedPaths;
377 * Convert a image URI to a Base64 encoded string.
378 * Attempts to convert the URL to a system storage url then
379 * fetch the data from the disk or storage location.
380 * Returns null if the image data cannot be fetched from storage.
382 * @throws FileNotFoundException
384 public function imageUriToBase64(string $uri): ?string
386 $storagePath = $this->imageUrlToStoragePath($uri);
387 if (empty($uri) || is_null($storagePath)) {
391 $storage = $this->getStorage();
393 if ($storage->exists($storagePath)) {
394 $imageData = $storage->get($storagePath);
397 if (is_null($imageData)) {
401 $extension = pathinfo($uri, PATHINFO_EXTENSION);
402 if ($extension === 'svg') {
403 $extension = 'svg+xml';
406 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
410 * Get a storage path for the given image URL.
411 * Ensures the path will start with "uploads/images".
412 * Returns null if the url cannot be resolved to a local URL.
414 private function imageUrlToStoragePath(string $url): ?string
416 $url = ltrim(trim($url), '/');
418 // Handle potential relative paths
419 $isRelative = strpos($url, 'http') !== 0;
421 if (strpos(strtolower($url), 'uploads/images') === 0) {
422 return trim($url, '/');
428 // Handle local images based on paths on the same domain
429 $potentialHostPaths = [
430 url('uploads/images/'),
431 $this->getPublicUrl('/uploads/images/'),
434 foreach ($potentialHostPaths as $potentialBasePath) {
435 $potentialBasePath = strtolower($potentialBasePath);
436 if (strpos(strtolower($url), $potentialBasePath) === 0) {
437 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
445 * Gets a public facing url for an image by checking relevant environment variables.
446 * If s3-style store is in use it will default to guessing a public bucket URL.
448 private function getPublicUrl(string $filePath): string
450 if ($this->storageUrl === null) {
451 $storageUrl = config('filesystems.url');
453 // Get the standard public s3 url if s3 is set as storage type
454 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
455 // region-based url will be used to prevent http issues.
456 if ($storageUrl == false && config('filesystems.images') === 's3') {
457 $storageDetails = config('filesystems.disks.s3');
458 if (strpos($storageDetails['bucket'], '.') === false) {
459 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
461 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
464 $this->storageUrl = $storageUrl;
467 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
469 return rtrim($basePath, '/') . $filePath;