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 = $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 \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 * Clean up an image file name to be both URL and storage safe.
138 protected function cleanImageFileName(string $name): string
140 $name = str_replace(' ', '-', $name);
141 $nameParts = explode('.', $name);
142 $extension = array_pop($nameParts);
143 $name = implode('-', $nameParts);
144 $name = Str::slug($name);
146 if (strlen($name) === 0) {
147 $name = Str::random(10);
150 return $name . '.' . $extension;
154 * Checks if the image is a gif. Returns true if it is, else false.
156 protected function isGif(Image $image): bool
158 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
162 * Get the thumbnail for an image.
163 * If $keepRatio is true only the width will be used.
164 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
165 * @param Image $image
168 * @param bool $keepRatio
171 * @throws ImageUploadException
173 public function getThumbnail(Image $image, $width = 220, $height = 220, $keepRatio = false)
175 if ($keepRatio && $this->isGif($image)) {
176 return $this->getPublicUrl($image->path);
179 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
180 $imagePath = $image->path;
181 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
183 if ($this->cache->has('images-' . $image->id . '-' . $thumbFilePath) && $this->cache->get('images-' . $thumbFilePath)) {
184 return $this->getPublicUrl($thumbFilePath);
187 $storage = $this->getStorage($image->type);
188 if ($storage->exists($thumbFilePath)) {
189 return $this->getPublicUrl($thumbFilePath);
192 $thumbData = $this->resizeImage($storage->get($imagePath), $width, $height, $keepRatio);
194 $storage->put($thumbFilePath, $thumbData);
195 $storage->setVisibility($thumbFilePath, 'public');
196 $this->cache->put('images-' . $image->id . '-' . $thumbFilePath, $thumbFilePath, 60 * 60 * 72);
199 return $this->getPublicUrl($thumbFilePath);
204 * @param string $imageData
207 * @param bool $keepRatio
209 * @throws ImageUploadException
211 protected function resizeImage(string $imageData, $width = 220, $height = null, bool $keepRatio = true)
214 $thumb = $this->imageTool->make($imageData);
215 } catch (Exception $e) {
216 if ($e instanceof ErrorException || $e instanceof NotSupportedException) {
217 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
223 $thumb->resize($width, $height, function ($constraint) {
224 $constraint->aspectRatio();
225 $constraint->upsize();
228 $thumb->fit($width, $height);
231 $thumbData = (string)$thumb->encode();
233 // Use original image data if we're keeping the ratio
234 // and the resizing does not save any space.
235 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
243 * Get the raw data content from an image.
244 * @throws FileNotFoundException
246 public function getImageData(Image $image): string
248 $imagePath = $image->path;
249 $storage = $this->getStorage();
250 return $storage->get($imagePath);
254 * Destroy an image along with its revisions, thumbnails and remaining folders.
257 public function destroy(Image $image)
259 $this->destroyImagesFromPath($image->path);
264 * Destroys an image at the given path.
265 * Searches for image thumbnails in addition to main provided path.
267 protected function destroyImagesFromPath(string $path): bool
269 $storage = $this->getStorage();
271 $imageFolder = dirname($path);
272 $imageFileName = basename($path);
273 $allImages = collect($storage->allFiles($imageFolder));
275 // Delete image files
276 $imagesToDelete = $allImages->filter(function ($imagePath) use ($imageFileName) {
277 return basename($imagePath) === $imageFileName;
279 $storage->delete($imagesToDelete->all());
281 // Cleanup of empty folders
282 $foldersInvolved = array_merge([$imageFolder], $storage->directories($imageFolder));
283 foreach ($foldersInvolved as $directory) {
284 if ($this->isFolderEmpty($storage, $directory)) {
285 $storage->deleteDirectory($directory);
293 * Check whether or not a folder is empty.
295 protected function isFolderEmpty(FileSystemInstance $storage, string $path): bool
297 $files = $storage->files($path);
298 $folders = $storage->directories($path);
299 return (count($files) === 0 && count($folders) === 0);
303 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
304 * Checks based off of only the image name.
305 * Could be much improved to be more specific but kept it generic for now to be safe.
307 * Returns the path of the images that would be/have been deleted.
309 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true)
311 $types = ['gallery', 'drawio'];
314 $this->image->newQuery()->whereIn('type', $types)
315 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
316 foreach ($images as $image) {
317 $searchQuery = '%' . basename($image->path) . '%';
318 $inPage = DB::table('pages')
319 ->where('html', 'like', $searchQuery)->count() > 0;
322 if ($checkRevisions) {
323 $inRevision = DB::table('page_revisions')
324 ->where('html', 'like', $searchQuery)->count() > 0;
327 if (!$inPage && !$inRevision) {
328 $deletedPaths[] = $image->path;
330 $this->destroy($image);
335 return $deletedPaths;
339 * Convert a image URI to a Base64 encoded string.
340 * Attempts to convert the URL to a system storage url then
341 * fetch the data from the disk or storage location.
342 * Returns null if the image data cannot be fetched from storage.
343 * @throws FileNotFoundException
345 public function imageUriToBase64(string $uri): ?string
347 $storagePath = $this->imageUrlToStoragePath($uri);
348 if (empty($uri) || is_null($storagePath)) {
352 $storage = $this->getStorage();
354 if ($storage->exists($storagePath)) {
355 $imageData = $storage->get($storagePath);
358 if (is_null($imageData)) {
362 $extension = pathinfo($uri, PATHINFO_EXTENSION);
363 if ($extension === 'svg') {
364 $extension = 'svg+xml';
367 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
371 * Get a storage path for the given image URL.
372 * Ensures the path will start with "uploads/images".
373 * Returns null if the url cannot be resolved to a local URL.
375 private function imageUrlToStoragePath(string $url): ?string
377 $url = ltrim(trim($url), '/');
379 // Handle potential relative paths
380 $isRelative = strpos($url, 'http') !== 0;
382 if (strpos(strtolower($url), 'uploads/images') === 0) {
383 return trim($url, '/');
388 // Handle local images based on paths on the same domain
389 $potentialHostPaths = [
390 url('uploads/images/'),
391 $this->getPublicUrl('/uploads/images/'),
394 foreach ($potentialHostPaths as $potentialBasePath) {
395 $potentialBasePath = strtolower($potentialBasePath);
396 if (strpos(strtolower($url), $potentialBasePath) === 0) {
397 return 'uploads/images/' . trim(substr($url, strlen($potentialBasePath)), '/');
405 * Gets a public facing url for an image by checking relevant environment variables.
406 * If s3-style store is in use it will default to guessing a public bucket URL.
408 private function getPublicUrl(string $filePath): string
410 if ($this->storageUrl === null) {
411 $storageUrl = config('filesystems.url');
413 // Get the standard public s3 url if s3 is set as storage type
414 // Uses the nice, short URL if bucket name has no periods in otherwise the longer
415 // region-based url will be used to prevent http issues.
416 if ($storageUrl == false && config('filesystems.images') === 's3') {
417 $storageDetails = config('filesystems.disks.s3');
418 if (strpos($storageDetails['bucket'], '.') === false) {
419 $storageUrl = 'https://' . $storageDetails['bucket'] . '.s3.amazonaws.com';
421 $storageUrl = 'https://s3-' . $storageDetails['region'] . '.amazonaws.com/' . $storageDetails['bucket'];
424 $this->storageUrl = $storageUrl;
427 $basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;
428 return rtrim($basePath, '/') . $filePath;