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\Support\Str;
12 use Intervention\Image\Exception\NotSupportedException;
13 use Intervention\Image\ImageManager;
14 use Symfony\Component\HttpFoundation\File\UploadedFile;
20 protected $storageUrl;
22 protected $fileSystem;
25 * ImageService constructor.
27 public function __construct(Image $image, ImageManager $imageTool, FileSystem $fileSystem, Cache $cache)
29 $this->image = $image;
30 $this->imageTool = $imageTool;
31 $this->fileSystem = $fileSystem;
32 $this->cache = $cache;
36 * Get the storage that will be used for storing images.
38 protected function getStorage(string $type = ''): FileSystemInstance
40 $storageType = config('filesystems.images');
42 // Ensure system images (App logo) are uploaded to a public space
43 if ($type === 'system' && $storageType === 'local_secure') {
44 $storageType = 'local';
47 return $this->fileSystem->disk($storageType);
51 * Saves a new image from an upload.
53 * @throws ImageUploadException
55 public function saveNewFromUpload(
56 UploadedFile $uploadedFile,
59 int $resizeWidth = null,
60 int $resizeHeight = null,
61 bool $keepRatio = true
63 $imageName = $this->sanitizeFileName($uploadedFile->getClientOriginalName());
64 $imageData = file_get_contents($uploadedFile->getRealPath());
66 if ($resizeWidth !== null || $resizeHeight !== null) {
67 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
70 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
74 * Save a new image from a uri-encoded base64 string of data.
75 * @throws ImageUploadException
77 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
79 $splitData = explode(';base64,', $base64Uri);
80 if (count($splitData) < 2) {
81 throw new ImageUploadException("Invalid base64 image data provided");
83 $data = base64_decode($splitData[1]);
84 return $this->saveNew($name, $data, $type, $uploadedTo);
88 * Save a new image into storage.
89 * @throws ImageUploadException
91 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
93 $storage = $this->getStorage($type);
94 $secureUploads = setting('app-secure-images');
95 $fileName = $this->cleanImageFileName($imageName);
97 $imagePath = '/uploads/images/' . $type . '/' . Date('Y-m') . '/';
99 while ($storage->exists($imagePath . $fileName)) {
100 $fileName = Str::random(3) . $fileName;
103 $fullPath = $imagePath . $fileName;
104 if ($secureUploads) {
105 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
109 $storage->put($fullPath, $imageData);
110 $storage->setVisibility($fullPath, 'public');
111 } catch (Exception $e) {
112 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
116 'name' => $imageName,
118 'url' => $this->getPublicUrl($fullPath),
120 'uploaded_to' => $uploadedTo
123 if (user()->id !== 0) {
124 $userId = user()->id;
125 $imageDetails['created_by'] = $userId;
126 $imageDetails['updated_by'] = $userId;
129 $image = $this->image->newInstance();
130 $image->forceFill($imageDetails)->save();
135 * Clean up an image file name to be both URL and storage safe.
137 protected function cleanImageFileName(string $name): string
139 $name = str_replace(' ', '-', $name);
140 $nameParts = explode('.', $name);
141 $extension = array_pop($nameParts);
142 $name = implode('.', $nameParts);
143 $name = Str::slug($name);
145 if (strlen($name) === 0) {
146 $name = Str::random(10);
149 return $name . '.' . $extension;
153 * Checks if the image is a gif. Returns true if it is, else false.
155 protected function isGif(Image $image): bool
157 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
161 * Get the thumbnail for an image.
162 * If $keepRatio is true only the width will be used.
163 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
164 * @param Image $image
167 * @param bool $keepRatio
170 * @throws ImageUploadException
172 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
174 if ($keepRatio && $this->isGif($image)) {
175 return $this->getPublicUrl($image->path);
178 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
179 $imagePath = $image->path;
180 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
182 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
183 return $this->getPublicUrl($thumbFilePath);
186 $storage = $this->getStorage($image->type);
187 if ($storage->exists($thumbFilePath)) {
188 return $this->getPublicUrl($thumbFilePath);
191 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
193 $storage->put($thumbFilePath, $thumbData);
194 $storage->setVisibility($thumbFilePath, 'public');
195 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
198 return $this->getPublicUrl($thumbFilePath);
203 * @param string $imageData
206 * @param bool $keepRatio
208 * @throws ImageUploadException
210 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
213 $thumb = $this->imageTool->make($imageData);
214 } catch (Exception $e) {
215 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
216 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
222 $thumb->resize($width, $height, function ($constraint) {
223 $constraint->aspectRatio();
224 $constraint->upsize();
227 $thumb->fit($width, $height);
230 $thumbData = (string)$thumb->encode();
232 // Use original image data if we're keeping the ratio
233 // and the resizing does not save any space.
234 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
242 * Get the raw data content from an image.
243 * @throws FileNotFoundException
245 public function getImageData(Image $image): string
247 $imagePath = $image->path;
248 $storage = $this->getStorage();
249 return $storage->get($imagePath);
253 * Destroy an image along with its revisions, thumbnails and remaining folders.
256 public function destroy(Image $image)
258 $this->destroyImagesFromPath($image->path);
263 * Destroys an image at the given path.
264 * Searches for image thumbnails in addition to main provided path.
266 protected function destroyImagesFromPath(string $path): bool
268 $storage = $this->getStorage();
270 $imageFolder = dirname($path);
271 $imageFileName = basename($path);
272 $allImages = collect($storage->allFiles($imageFolder));
274 // Delete image files
275 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
276 return basename($imagePath) === $imageFileName;
278 $storage->delete($imagesToDelete->all());
280 // Cleanup of empty folders
281 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
282 foreach ($foldersInvolved as $directory) {
283 if ($this->isFolderEmpty($storage, $directory)) {
284 $storage->deleteDirectory($directory);
292 * Check whether or not a folder is empty.
294 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
296 $files = $storage->files($path);
297 $folders = $storage->directories($path);
298 return (count($files) === 0 && count($folders) === 0);
302 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
303 * Checks based off of only the image name.
304 * Could be much improved to be more specific but kept it generic for now to be safe.
306 * Returns the path of the images that would be/have been deleted.
308 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
310 $types = ['gallery', 'drawio'];
313 $this->image->newQuery()->whereIn('type', $types)
314 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
315 foreach ($images as $image) {
316 $searchQuery = '%' . basename($image->path) . '%';
317 $inPage = DB::table('pages')
318 ->where('html', 'like', $searchQuery)->count() > 0;
321 if ($checkRevisions) {
322 $inRevision = DB::table('page_revisions')
323 ->where('html', 'like', $searchQuery)->count() > 0;
326 if (!$inPage && !$inRevision) {
327 $deletedPaths[] = $image->path;
329 $this->destroy($image);
334 return $deletedPaths;
338 * Convert a image URI to a Base64 encoded string.
339 * Attempts to convert the URL to a system storage url then
340 * fetch the data from the disk or storage location.
341 * Returns null if the image data cannot be fetched from storage.
342 * @throws FileNotFoundException
344 public function imageUriToBase64(string $uri): ?string
346 $storagePath = $this->imageUrlToStoragePath($uri);
347 if (empty($uri) || is_null($storagePath)) {
351 $storage = $this->getStorage();
353 if ($storage->exists($storagePath)) {
354 $imageData = $storage->get($storagePath);
357 if (is_null($imageData)) {
361 $extension = pathinfo($uri, PATHINFO_EXTENSION);
362 if ($extension === 'svg') {
363 $extension = 'svg+xml';
366 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
370 * Get a storage path for the given image URL.
371 * Ensures the path will start with "uploads/images".
372 * Returns null if the url cannot be resolved to a local URL.
374 private function imageUrlToStoragePath(string $url): ?string
376 $url = ltrim(trim($url), '/');
378 // Handle potential relative paths
379 $isRelative = strpos($url, 'http') !== 0;
381 if (strpos(strtolower($url), 'uploads/images') === 0) {
382 return trim($url, '/');
387 // Handle local images based on paths on the same domain
388 $potentialHostPaths = [
389 url('uploads/images/'),
390 $this->getPublicUrl('/uploads/images/'),
393 foreach ($potentialHostPaths as $potentialBasePath) {
394 $potentialBasePath = strtolower($potentialBasePath);
395 if (strpos(strtolower($url), $potentialBasePath) === 0) {
396 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
404 * Gets a public facing url for an image by checking relevant environment variables.
405 * If s3-style store is in use it will default to guessing a public bucket URL.
407 private function getPublicUrl(string $filePath): string
409 if ($this->storageUrl === null) {
410 $storageUrl = config('filesystems.url');
412 // Get the standard public s3 url if s3 is set as storage type
413 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
414 // region-based url will be used to prevent http issues.
415 if ($storageUrl == false && config('filesystems.images') === 's3') {
416 $storageDetails = config('filesystems.disks.s3');
417 if (strpos($storageDetails['bucket'], '.') === false) {
418 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
420 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
423 $this->storageUrl = $storageUrl;
426 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
427 return rtrim($basePath, '/') . $filePath;
431 * Returns a sanitized filename with only one file extension
433 private function sanitizeFileName(string $fileName): string
435 $parts = explode('.', $fileName);
436 $extension = array_pop($parts);
438 return sprintf('%s.%s', implode('-', $parts), $extension);