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 if using s3 without an endpoint set.
144 // Done since this call can break s3-like services but desired for actual
145 // AWS s3 usage. Attempting to set ACL during above put request requires
146 // different permissions hence would technically be a breaking change.
147 $usingS3 = strtolower(config('filesystems.images')) === 's3';
148 if ($usingS3 && is_null(config('filesystems.disks.s3.endpoint'))) {
149 $storage->setVisibility($path, 'public');
154 * Clean up an image file name to be both URL and storage safe.
156 protected function cleanImageFileName(string $name): string
158 $name = str_replace(' ', '-', $name);
159 $nameParts = explode('.', $name);
160 $extension = array_pop($nameParts);
161 $name = implode('-', $nameParts);
162 $name = Str::slug($name);
164 if (strlen($name) === 0) {
165 $name = Str::random(10);
168 return $name . '.' . $extension;
172 * Checks if the image is a gif. Returns true if it is, else false.
174 protected function isGif(Image $image): bool
176 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
180 * Get the thumbnail for an image.
181 * If $keepRatio is true only the width will be used.
182 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
183 * @param Image $image
186 * @param bool $keepRatio
189 * @throws ImageUploadException
191 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
193 if ($keepRatio && $this->isGif($image)) {
194 return $this->getPublicUrl($image->path);
197 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
198 $imagePath = $image->path;
199 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
201 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
202 return $this->getPublicUrl($thumbFilePath);
205 $storage = $this->getStorage($image->type);
206 if ($storage->exists($thumbFilePath)) {
207 return $this->getPublicUrl($thumbFilePath);
210 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
212 $this->saveImageDataInPublicSpace($storage, $thumbFilePath, $thumbData);
213 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
216 return $this->getPublicUrl($thumbFilePath);
221 * @param string $imageData
224 * @param bool $keepRatio
226 * @throws ImageUploadException
228 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
231 $thumb = $this->imageTool->make($imageData);
232 } catch (Exception $e) {
233 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
234 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
240 $thumb->resize($width, $height, function ($constraint) {
241 $constraint->aspectRatio();
242 $constraint->upsize();
245 $thumb->fit($width, $height);
248 $thumbData = (string)$thumb->encode();
250 // Use original image data if we're keeping the ratio
251 // and the resizing does not save any space.
252 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
260 * Get the raw data content from an image.
261 * @throws FileNotFoundException
263 public function getImageData(Image $image): string
265 $imagePath = $image->path;
266 $storage = $this->getStorage();
267 return $storage->get($imagePath);
271 * Destroy an image along with its revisions, thumbnails and remaining folders.
274 public function destroy(Image $image)
276 $this->destroyImagesFromPath($image->path);
281 * Destroys an image at the given path.
282 * Searches for image thumbnails in addition to main provided path.
284 protected function destroyImagesFromPath(string $path): bool
286 $storage = $this->getStorage();
288 $imageFolder = dirname($path);
289 $imageFileName = basename($path);
290 $allImages = collect($storage->allFiles($imageFolder));
292 // Delete image files
293 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
294 return basename($imagePath) === $imageFileName;
296 $storage->delete($imagesToDelete->all());
298 // Cleanup of empty folders
299 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
300 foreach ($foldersInvolved as $directory) {
301 if ($this->isFolderEmpty($storage, $directory)) {
302 $storage->deleteDirectory($directory);
310 * Check whether or not a folder is empty.
312 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
314 $files = $storage->files($path);
315 $folders = $storage->directories($path);
316 return (count($files) === 0 && count($folders) === 0);
320 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
321 * Checks based off of only the image name.
322 * Could be much improved to be more specific but kept it generic for now to be safe.
324 * Returns the path of the images that would be/have been deleted.
326 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
328 $types = ['gallery', 'drawio'];
331 $this->image->newQuery()->whereIn('type', $types)
332 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
333 foreach ($images as $image) {
334 $searchQuery = '%' . basename($image->path) . '%';
335 $inPage = DB::table('pages')
336 ->where('html', 'like', $searchQuery)->count() > 0;
339 if ($checkRevisions) {
340 $inRevision = DB::table('page_revisions')
341 ->where('html', 'like', $searchQuery)->count() > 0;
344 if (!$inPage && !$inRevision) {
345 $deletedPaths[] = $image->path;
347 $this->destroy($image);
352 return $deletedPaths;
356 * Convert a image URI to a Base64 encoded string.
357 * Attempts to convert the URL to a system storage url then
358 * fetch the data from the disk or storage location.
359 * Returns null if the image data cannot be fetched from storage.
360 * @throws FileNotFoundException
362 public function imageUriToBase64(string $uri): ?string
364 $storagePath = $this->imageUrlToStoragePath($uri);
365 if (empty($uri) || is_null($storagePath)) {
369 $storage = $this->getStorage();
371 if ($storage->exists($storagePath)) {
372 $imageData = $storage->get($storagePath);
375 if (is_null($imageData)) {
379 $extension = pathinfo($uri, PATHINFO_EXTENSION);
380 if ($extension === 'svg') {
381 $extension = 'svg+xml';
384 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
388 * Get a storage path for the given image URL.
389 * Ensures the path will start with "uploads/images".
390 * Returns null if the url cannot be resolved to a local URL.
392 private function imageUrlToStoragePath(string $url): ?string
394 $url = ltrim(trim($url), '/');
396 // Handle potential relative paths
397 $isRelative = strpos($url, 'http') !== 0;
399 if (strpos(strtolower($url), 'uploads/images') === 0) {
400 return trim($url, '/');
405 // Handle local images based on paths on the same domain
406 $potentialHostPaths = [
407 url('uploads/images/'),
408 $this->getPublicUrl('/uploads/images/'),
411 foreach ($potentialHostPaths as $potentialBasePath) {
412 $potentialBasePath = strtolower($potentialBasePath);
413 if (strpos(strtolower($url), $potentialBasePath) === 0) {
414 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
422 * Gets a public facing url for an image by checking relevant environment variables.
423 * If s3-style store is in use it will default to guessing a public bucket URL.
425 private function getPublicUrl(string $filePath): string
427 if ($this->storageUrl === null) {
428 $storageUrl = config('filesystems.url');
430 // Get the standard public s3 url if s3 is set as storage type
431 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
432 // region-based url will be used to prevent http issues.
433 if ($storageUrl == false && config('filesystems.images') === 's3') {
434 $storageDetails = config('filesystems.disks.s3');
435 if (strpos($storageDetails['bucket'], '.') === false) {
436 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
438 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
441 $this->storageUrl = $storageUrl;
444 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
445 return rtrim($basePath, '/') . $filePath;