1 <?php namespace BookStack\Uploads;
3 use BookStack\Exceptions\ImageUploadException;
7 use Illuminate\Contracts\Cache\Repository as Cache;
8 use Illuminate\Contracts\Filesystem\Factory as FileSystem;
9 use Illuminate\Contracts\Filesystem\Filesystem as FileSystemInstance;
10 use Illuminate\Contracts\Filesystem\FileNotFoundException;
11 use Illuminate\Contracts\Filesystem\Filesystem as Storage;
12 use Illuminate\Support\Str;
13 use Intervention\Image\Exception\NotSupportedException;
14 use Intervention\Image\ImageManager;
15 use Symfony\Component\HttpFoundation\File\UploadedFile;
21 protected $storageUrl;
23 protected $fileSystem;
26 * ImageService constructor.
28 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
30 $this->image = $image;
31 $this->imageTool = $imageTool;
32 $this->fileSystem = $fileSystem;
33 $this->cache = $cache;
37 * Get the storage that will be used for storing images.
39 protected function getStorage(string $type = ''): FileSystemInstance
41 $storageType = config('filesystems.images');
43 // Ensure system images (App logo) are uploaded to a public space
44 if ($type === 'system' && $storageType === 'local_secure') {
45 $storageType = 'local';
48 return $this->fileSystem->disk($storageType);
52 * Saves a new image from an upload.
54 * @throws ImageUploadException
56 public function saveNewFromUpload(
57 UploadedFile $uploadedFile,
60 int $resizeWidth = null,
61 int $resizeHeight = null,
62 bool $keepRatio = true
64 $imageName = $uploadedFile->getClientOriginalName();
65 $imageData = file_get_contents($uploadedFile->getRealPath());
67 if ($resizeWidth !== null || $resizeHeight !== null) {
68 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
71 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
75 * Save a new image from a uri-encoded base64 string of data.
76 * @throws ImageUploadException
78 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
80 $splitData = explode(';base64,', $base64Uri);
81 if (count($splitData) < 2) {
82 throw new ImageUploadException("Invalid base64 image data provided");
84 $data = base64_decode($splitData[1]);
85 return $this->saveNew($name, $data, $type, $uploadedTo);
89 * Save a new image into storage.
90 * @throws ImageUploadException
92 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
94 $storage = $this->getStorage($type);
95 $secureUploads = setting('app-secure-images');
96 $fileName = $this->cleanImageFileName($imageName);
98 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
100 while ($storage->exists($imagePath . $fileName)) {
101 $fileName = Str::random(3) . $fileName;
104 $fullPath = $imagePath . $fileName;
105 if ($secureUploads) {
106 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
110 $this->saveImageDataInPublicSpace($storage, $fullPath, $imageData);
111 } catch (Exception $e) {
112 \Log::error('Error when attempting image upload:' . $e->getMessage());
113 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
117 'name' => $imageName,
119 'url' => $this->getPublicUrl($fullPath),
121 'uploaded_to' => $uploadedTo
124 if (user()->id !== 0) {
125 $userId = user()->id;
126 $imageDetails['created_by'] = $userId;
127 $imageDetails['updated_by'] = $userId;
130 $image = $this->image->newInstance();
131 $image->forceFill($imageDetails)->save();
136 * Save image data for the given path in the public space, if possible,
137 * for the provided storage mechanism.
139 protected function saveImageDataInPublicSpace(Storage $storage, string $path, string $data)
141 $storage->put($path, $data);
143 // Set visibility when a non-AWS-s3, s3-like storage option is in use.
144 // Done since this call can break s3-like services but desired for other image stores.
145 // Attempting to set ACL during above put request requires different permissions
146 // hence would technically be a breaking change for actual s3 usage.
147 $usingS3 = strtolower(config('filesystems.images')) === 's3';
148 $usingS3Like = $usingS3 && !is_null(config('filesystems.disks.s3.endpoint'));
150 $storage->setVisibility($path, 'public');
155 * Clean up an image file name to be both URL and storage safe.
157 protected function cleanImageFileName(string $name): string
159 $name = str_replace(' ', '-', $name);
160 $nameParts = explode('.', $name);
161 $extension = array_pop($nameParts);
162 $name = implode('-', $nameParts);
163 $name = Str::slug($name);
165 if (strlen($name) === 0) {
166 $name = Str::random(10);
169 return $name . '.' . $extension;
173 * Checks if the image is a gif. Returns true if it is, else false.
175 protected function isGif(Image $image): bool
177 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
181 * Get the thumbnail for an image.
182 * If $keepRatio is true only the width will be used.
183 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
184 * @param Image $image
187 * @param bool $keepRatio
190 * @throws ImageUploadException
192 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
194 if ($keepRatio && $this->isGif($image)) {
195 return $this->getPublicUrl($image->path);
198 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
199 $imagePath = $image->path;
200 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
202 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
203 return $this->getPublicUrl($thumbFilePath);
206 $storage = $this->getStorage($image->type);
207 if ($storage->exists($thumbFilePath)) {
208 return $this->getPublicUrl($thumbFilePath);
211 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
213 $this->saveImageDataInPublicSpace($storage, $thumbFilePath, $thumbData);
214 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
217 return $this->getPublicUrl($thumbFilePath);
222 * @param string $imageData
225 * @param bool $keepRatio
227 * @throws ImageUploadException
229 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
232 $thumb = $this->imageTool->make($imageData);
233 } catch (Exception $e) {
234 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
235 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
241 $thumb->resize($width, $height, function ($constraint) {
242 $constraint->aspectRatio();
243 $constraint->upsize();
246 $thumb->fit($width, $height);
249 $thumbData = (string)$thumb->encode();
251 // Use original image data if we're keeping the ratio
252 // and the resizing does not save any space.
253 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
261 * Get the raw data content from an image.
262 * @throws FileNotFoundException
264 public function getImageData(Image $image): string
266 $imagePath = $image->path;
267 $storage = $this->getStorage();
268 return $storage->get($imagePath);
272 * Destroy an image along with its revisions, thumbnails and remaining folders.
275 public function destroy(Image $image)
277 $this->destroyImagesFromPath($image->path);
282 * Destroys an image at the given path.
283 * Searches for image thumbnails in addition to main provided path.
285 protected function destroyImagesFromPath(string $path): bool
287 $storage = $this->getStorage();
289 $imageFolder = dirname($path);
290 $imageFileName = basename($path);
291 $allImages = collect($storage->allFiles($imageFolder));
293 // Delete image files
294 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
295 return basename($imagePath) === $imageFileName;
297 $storage->delete($imagesToDelete->all());
299 // Cleanup of empty folders
300 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
301 foreach ($foldersInvolved as $directory) {
302 if ($this->isFolderEmpty($storage, $directory)) {
303 $storage->deleteDirectory($directory);
311 * Check whether or not a folder is empty.
313 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
315 $files = $storage->files($path);
316 $folders = $storage->directories($path);
317 return (count($files) === 0 && count($folders) === 0);
321 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
322 * Checks based off of only the image name.
323 * Could be much improved to be more specific but kept it generic for now to be safe.
325 * Returns the path of the images that would be/have been deleted.
327 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
329 $types = ['gallery', 'drawio'];
332 $this->image->newQuery()->whereIn('type', $types)
333 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
334 foreach ($images as $image) {
335 $searchQuery = '%' . basename($image->path) . '%';
336 $inPage = DB::table('pages')
337 ->where('html', 'like', $searchQuery)->count() > 0;
340 if ($checkRevisions) {
341 $inRevision = DB::table('page_revisions')
342 ->where('html', 'like', $searchQuery)->count() > 0;
345 if (!$inPage && !$inRevision) {
346 $deletedPaths[] = $image->path;
348 $this->destroy($image);
353 return $deletedPaths;
357 * Convert a image URI to a Base64 encoded string.
358 * Attempts to convert the URL to a system storage url then
359 * fetch the data from the disk or storage location.
360 * Returns null if the image data cannot be fetched from storage.
361 * @throws FileNotFoundException
363 public function imageUriToBase64(string $uri): ?string
365 $storagePath = $this->imageUrlToStoragePath($uri);
366 if (empty($uri) || is_null($storagePath)) {
370 $storage = $this->getStorage();
372 if ($storage->exists($storagePath)) {
373 $imageData = $storage->get($storagePath);
376 if (is_null($imageData)) {
380 $extension = pathinfo($uri, PATHINFO_EXTENSION);
381 if ($extension === 'svg') {
382 $extension = 'svg+xml';
385 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
389 * Get a storage path for the given image URL.
390 * Ensures the path will start with "uploads/images".
391 * Returns null if the url cannot be resolved to a local URL.
393 private function imageUrlToStoragePath(string $url): ?string
395 $url = ltrim(trim($url), '/');
397 // Handle potential relative paths
398 $isRelative = strpos($url, 'http') !== 0;
400 if (strpos(strtolower($url), 'uploads/images') === 0) {
401 return trim($url, '/');
406 // Handle local images based on paths on the same domain
407 $potentialHostPaths = [
408 url('uploads/images/'),
409 $this->getPublicUrl('/uploads/images/'),
412 foreach ($potentialHostPaths as $potentialBasePath) {
413 $potentialBasePath = strtolower($potentialBasePath);
414 if (strpos(strtolower($url), $potentialBasePath) === 0) {
415 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
423 * Gets a public facing url for an image by checking relevant environment variables.
424 * If s3-style store is in use it will default to guessing a public bucket URL.
426 private function getPublicUrl(string $filePath): string
428 if ($this->storageUrl === null) {
429 $storageUrl = config('filesystems.url');
431 // Get the standard public s3 url if s3 is set as storage type
432 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
433 // region-based url will be used to prevent http issues.
434 if ($storageUrl == false && config('filesystems.images') === 's3') {
435 $storageDetails = config('filesystems.disks.s3');
436 if (strpos($storageDetails['bucket'], '.') === false) {
437 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
439 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
442 $this->storageUrl = $storageUrl;
445 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
446 return rtrim($basePath, '/') . $filePath;