3 namespace BookStack\Uploads;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Exceptions\ImageUploadException;
11 use Illuminate\Contracts\Cache\Repository as Cache;
12 use Illuminate\Filesystem\FilesystemManager;
13 use Illuminate\Support\Facades\DB;
14 use Illuminate\Support\Facades\Log;
15 use Illuminate\Support\Str;
16 use Intervention\Image\Exception\NotSupportedException;
17 use Intervention\Image\ImageManager;
18 use Symfony\Component\HttpFoundation\File\UploadedFile;
19 use Symfony\Component\HttpFoundation\StreamedResponse;
23 protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
25 public function __construct(
26 protected ImageManager $imageTool,
27 protected FilesystemManager $fileSystem,
28 protected Cache $cache,
29 protected ImageStorage $storage,
34 * Saves a new image from an upload.
36 * @throws ImageUploadException
38 public function saveNewFromUpload(
39 UploadedFile $uploadedFile,
42 int $resizeWidth = null,
43 int $resizeHeight = null,
44 bool $keepRatio = true
46 $imageName = $uploadedFile->getClientOriginalName();
47 $imageData = file_get_contents($uploadedFile->getRealPath());
49 if ($resizeWidth !== null || $resizeHeight !== null) {
50 $imageData = $this->resizeImage($imageData, $resizeWidth, $resizeHeight, $keepRatio);
53 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
57 * Save a new image from a uri-encoded base64 string of data.
59 * @throws ImageUploadException
61 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
63 $splitData = explode(';base64,', $base64Uri);
64 if (count($splitData) < 2) {
65 throw new ImageUploadException('Invalid base64 image data provided');
67 $data = base64_decode($splitData[1]);
69 return $this->saveNew($name, $data, $type, $uploadedTo);
73 * Save a new image into storage.
75 * @throws ImageUploadException
77 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
79 $disk = $this->storage->getDisk($type);
80 $secureUploads = setting('app-secure-images');
81 $fileName = $this->storage->cleanImageFileName($imageName);
83 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
85 while ($disk->exists($imagePath . $fileName)) {
86 $fileName = Str::random(3) . $fileName;
89 $fullPath = $imagePath . $fileName;
91 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
95 $disk->put($fullPath, $imageData, true);
96 } catch (Exception $e) {
97 Log::error('Error when attempting image upload:' . $e->getMessage());
99 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
103 'name' => $imageName,
105 'url' => $this->storage->getPublicUrl($fullPath),
107 'uploaded_to' => $uploadedTo,
110 if (user()->id !== 0) {
111 $userId = user()->id;
112 $imageDetails['created_by'] = $userId;
113 $imageDetails['updated_by'] = $userId;
116 $image = (new Image())->forceFill($imageDetails);
123 * Replace an existing image file in the system using the given file.
125 public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
127 $imageData = file_get_contents($file->getRealPath());
128 $disk = $this->storage->getDisk($type);
129 $disk->put($path, $imageData);
133 * Checks if the image is a gif. Returns true if it is, else false.
135 protected function isGif(Image $image): bool
137 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
141 * Check if the given image and image data is apng.
143 protected function isApngData(Image $image, string &$imageData): bool
145 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
150 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
152 return str_contains($initialHeader, 'acTL');
156 * Get the thumbnail for an image.
157 * If $keepRatio is true only the width will be used.
158 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
162 public function getThumbnail(
166 bool $keepRatio = false,
167 bool $shouldCreate = false,
168 bool $canCreate = false,
170 // Do not resize GIF images where we're not cropping
171 if ($keepRatio && $this->isGif($image)) {
172 return $this->storage->getPublicUrl($image->path);
175 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
176 $imagePath = $image->path;
177 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
179 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
181 // Return path if in cache
182 $cachedThumbPath = $this->cache->get($thumbCacheKey);
183 if ($cachedThumbPath && !$shouldCreate) {
184 return $this->storage->getPublicUrl($cachedThumbPath);
187 // If thumbnail has already been generated, serve that and cache path
188 $disk = $this->storage->getDisk($image->type);
189 if (!$shouldCreate && $disk->exists($thumbFilePath)) {
190 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
192 return $this->storage->getPublicUrl($thumbFilePath);
195 $imageData = $disk->get($imagePath);
197 // Do not resize apng images where we're not cropping
198 if ($keepRatio && $this->isApngData($image, $imageData)) {
199 $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
201 return $this->storage->getPublicUrl($image->path);
204 if (!$shouldCreate && !$canCreate) {
208 // If not in cache and thumbnail does not exist, generate thumb and cache path
209 $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
210 $disk->put($thumbFilePath, $thumbData, true);
211 $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
213 return $this->storage->getPublicUrl($thumbFilePath);
217 * Resize the image of given data to the specified size, and return the new image data.
219 * @throws ImageUploadException
221 protected function resizeImage(string $imageData, ?int $width, ?int $height, bool $keepRatio): string
224 $thumb = $this->imageTool->make($imageData);
225 } catch (ErrorException | NotSupportedException $e) {
226 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
229 $this->orientImageToOriginalExif($thumb, $imageData);
232 $thumb->resize($width, $height, function ($constraint) {
233 $constraint->aspectRatio();
234 $constraint->upsize();
237 $thumb->fit($width, $height);
240 $thumbData = (string) $thumb->encode();
242 // Use original image data if we're keeping the ratio
243 // and the resizing does not save any space.
244 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
252 * Get the raw data content from an image.
256 public function getImageData(Image $image): string
258 $disk = $this->storage->getDisk();
260 return $disk->get($image->path);
264 * Destroy an image along with its revisions, thumbnails and remaining folders.
268 public function destroy(Image $image): void
270 $disk = $this->storage->getDisk($image->type);
271 $disk->destroyAllMatchingNameFromPath($image->path);
276 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
277 * Checks based off of only the image name.
278 * Could be much improved to be more specific but kept it generic for now to be safe.
280 * Returns the path of the images that would be/have been deleted.
282 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
284 $types = ['gallery', 'drawio'];
287 Image::query()->whereIn('type', $types)
288 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
289 /** @var Image $image */
290 foreach ($images as $image) {
291 $searchQuery = '%' . basename($image->path) . '%';
292 $inPage = DB::table('pages')
293 ->where('html', 'like', $searchQuery)->count() > 0;
296 if ($checkRevisions) {
297 $inRevision = DB::table('page_revisions')
298 ->where('html', 'like', $searchQuery)->count() > 0;
301 if (!$inPage && !$inRevision) {
302 $deletedPaths[] = $image->path;
304 $this->destroy($image);
310 return $deletedPaths;
314 * Convert an image URI to a Base64 encoded string.
315 * Attempts to convert the URL to a system storage url then
316 * fetch the data from the disk or storage location.
317 * Returns null if the image data cannot be fetched from storage.
319 public function imageUrlToBase64(string $url): ?string
321 $storagePath = $this->storage->urlToPath($url);
322 if (empty($url) || is_null($storagePath)) {
326 // Apply access control when local_secure_restricted images are active
327 if ($this->storage->usingSecureRestrictedImages()) {
328 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
333 $disk = $this->storage->getDisk();
335 if ($disk->exists($storagePath)) {
336 $imageData = $disk->get($storagePath);
339 if (is_null($imageData)) {
343 $extension = pathinfo($url, PATHINFO_EXTENSION);
344 if ($extension === 'svg') {
345 $extension = 'svg+xml';
348 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
352 * Check if the given path exists and is accessible in the local secure image system.
353 * Returns false if local_secure is not in use, if the file does not exist, if the
354 * file is likely not a valid image, or if permission does not allow access.
356 public function pathAccessibleInLocalSecure(string $imagePath): bool
358 $disk = $this->storage->getDisk('gallery');
360 if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
364 // Check local_secure is active
365 return $disk->usingSecureImages()
366 // Check the image file exists
367 && $disk->exists($imagePath)
368 // Check the file is likely an image file
369 && str_starts_with($disk->mimeType($imagePath), 'image/');
373 * Check that the current user has access to the relation
374 * of the image at the given path.
376 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
378 if (str_starts_with($path, '/uploads/images/')) {
379 $path = substr($path, 15);
382 // Strip thumbnail element from path if existing
383 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
384 $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
385 $missingExtension = !str_contains($part, '.');
387 return !($resizedDir && $missingExtension);
390 // Build a database-format image path and search for the image entry
391 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
392 $image = Image::query()->where('path', '=', $fullPath)->first();
394 if (is_null($image)) {
398 $imageType = $image->type;
400 // Allow user or system (logo) images
401 // (No specific relation control but may still have access controlled by auth)
402 if ($imageType === 'user' || $imageType === 'system') {
406 if ($imageType === 'gallery' || $imageType === 'drawio') {
407 return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
410 if ($imageType === 'cover_book') {
411 return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
414 if ($imageType === 'cover_bookshelf') {
415 return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
422 * For the given path, if existing, provide a response that will stream the image contents.
424 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
426 $disk = $this->storage->getDisk($imageType);
428 return $disk->response($path);
432 * Check if the given image extension is supported by BookStack.
433 * The extension must not be altered in this function. This check should provide a guarantee
434 * that the provided extension is safe to use for the image to be saved.
436 public static function isExtensionSupported(string $extension): bool
438 return in_array($extension, static::$supportedExtensions);