3 namespace BookStack\Uploads;
5 use BookStack\Entities\Queries\EntityQueries;
6 use BookStack\Exceptions\ImageUploadException;
8 use Illuminate\Support\Facades\DB;
9 use Illuminate\Support\Facades\Log;
10 use Illuminate\Support\Str;
11 use Symfony\Component\HttpFoundation\File\UploadedFile;
12 use Symfony\Component\HttpFoundation\StreamedResponse;
16 protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
18 public function __construct(
19 protected ImageStorage $storage,
20 protected ImageResizer $resizer,
21 protected EntityQueries $queries,
26 * Saves a new image from an upload.
28 * @throws ImageUploadException
30 public function saveNewFromUpload(
31 UploadedFile $uploadedFile,
34 int $resizeWidth = null,
35 int $resizeHeight = null,
36 bool $keepRatio = true
38 $imageName = $uploadedFile->getClientOriginalName();
39 $imageData = file_get_contents($uploadedFile->getRealPath());
41 if ($resizeWidth !== null || $resizeHeight !== null) {
42 $imageData = $this->resizer->resizeImageData($imageData, $resizeWidth, $resizeHeight, $keepRatio);
45 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
49 * Save a new image from a uri-encoded base64 string of data.
51 * @throws ImageUploadException
53 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
55 $splitData = explode(';base64,', $base64Uri);
56 if (count($splitData) < 2) {
57 throw new ImageUploadException('Invalid base64 image data provided');
59 $data = base64_decode($splitData[1]);
61 return $this->saveNew($name, $data, $type, $uploadedTo);
65 * Save a new image into storage.
67 * @throws ImageUploadException
69 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
71 $disk = $this->storage->getDisk($type);
72 $secureUploads = setting('app-secure-images');
73 $fileName = $this->storage->cleanImageFileName($imageName);
75 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
77 while ($disk->exists($imagePath . $fileName)) {
78 $fileName = Str::random(3) . $fileName;
81 $fullPath = $imagePath . $fileName;
83 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
87 $disk->put($fullPath, $imageData, true);
88 } catch (Exception $e) {
89 Log::error('Error when attempting image upload:' . $e->getMessage());
91 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
97 'url' => $this->storage->getPublicUrl($fullPath),
99 'uploaded_to' => $uploadedTo,
102 if (user()->id !== 0) {
103 $userId = user()->id;
104 $imageDetails['created_by'] = $userId;
105 $imageDetails['updated_by'] = $userId;
108 $image = (new Image())->forceFill($imageDetails);
115 * Replace an existing image file in the system using the given file.
117 public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
119 $imageData = file_get_contents($file->getRealPath());
120 $disk = $this->storage->getDisk($type);
121 $disk->put($path, $imageData);
125 * Get the raw data content from an image.
129 public function getImageData(Image $image): string
131 $disk = $this->storage->getDisk();
133 return $disk->get($image->path);
137 * Get the raw data content from an image.
142 public function getImageStream(Image $image): mixed
144 $disk = $this->storage->getDisk();
146 return $disk->stream($image->path);
150 * Destroy an image along with its revisions, thumbnails and remaining folders.
154 public function destroy(Image $image): void
156 $this->destroyFileAtPath($image->type, $image->path);
161 * Destroy the underlying image file at the given path.
163 public function destroyFileAtPath(string $type, string $path): void
165 $disk = $this->storage->getDisk($type);
166 $disk->destroyAllMatchingNameFromPath($path);
170 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
171 * Checks based off of only the image name.
172 * Could be much improved to be more specific but kept it generic for now to be safe.
174 * Returns the path of the images that would be/have been deleted.
176 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
178 $types = ['gallery', 'drawio'];
181 Image::query()->whereIn('type', $types)
182 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
183 /** @var Image $image */
184 foreach ($images as $image) {
185 $searchQuery = '%' . basename($image->path) . '%';
186 $inPage = DB::table('pages')
187 ->where('html', 'like', $searchQuery)->count() > 0;
190 if ($checkRevisions) {
191 $inRevision = DB::table('page_revisions')
192 ->where('html', 'like', $searchQuery)->count() > 0;
195 if (!$inPage && !$inRevision) {
196 $deletedPaths[] = $image->path;
198 $this->destroy($image);
204 return $deletedPaths;
208 * Convert an image URI to a Base64 encoded string.
209 * Attempts to convert the URL to a system storage url then
210 * fetch the data from the disk or storage location.
211 * Returns null if the image data cannot be fetched from storage.
213 public function imageUrlToBase64(string $url): ?string
215 $storagePath = $this->storage->urlToPath($url);
216 if (empty($url) || is_null($storagePath)) {
220 // Apply access control when local_secure_restricted images are active
221 if ($this->storage->usingSecureRestrictedImages()) {
222 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
227 $disk = $this->storage->getDisk();
229 if ($disk->exists($storagePath)) {
230 $imageData = $disk->get($storagePath);
233 if (is_null($imageData)) {
237 $extension = pathinfo($url, PATHINFO_EXTENSION);
238 if ($extension === 'svg') {
239 $extension = 'svg+xml';
242 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
246 * Check if the given path exists and is accessible in the local secure image system.
247 * Returns false if local_secure is not in use, if the file does not exist, if the
248 * file is likely not a valid image, or if permission does not allow access.
250 public function pathAccessibleInLocalSecure(string $imagePath): bool
252 $disk = $this->storage->getDisk('gallery');
254 if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
258 // Check local_secure is active
259 return $disk->usingSecureImages()
260 // Check the image file exists
261 && $disk->exists($imagePath)
262 // Check the file is likely an image file
263 && str_starts_with($disk->mimeType($imagePath), 'image/');
267 * Check that the current user has access to the relation
268 * of the image at the given path.
270 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
272 if (str_starts_with($path, 'uploads/images/')) {
273 $path = substr($path, 15);
276 // Strip thumbnail element from path if existing
277 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
278 $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
279 $missingExtension = !str_contains($part, '.');
281 return !($resizedDir && $missingExtension);
284 // Build a database-format image path and search for the image entry
285 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
286 $image = Image::query()->where('path', '=', $fullPath)->first();
288 if (is_null($image)) {
292 $imageType = $image->type;
294 // Allow user or system (logo) images
295 // (No specific relation control but may still have access controlled by auth)
296 if ($imageType === 'user' || $imageType === 'system') {
300 if ($imageType === 'gallery' || $imageType === 'drawio') {
301 return $this->queries->pages->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
304 if ($imageType === 'cover_book') {
305 return $this->queries->books->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
308 if ($imageType === 'cover_bookshelf') {
309 return $this->queries->shelves->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
316 * For the given path, if existing, provide a response that will stream the image contents.
318 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
320 $disk = $this->storage->getDisk($imageType);
322 return $disk->response($path);
326 * Check if the given image extension is supported by BookStack.
327 * The extension must not be altered in this function. This check should provide a guarantee
328 * that the provided extension is safe to use for the image to be saved.
330 public static function isExtensionSupported(string $extension): bool
332 return in_array($extension, static::$supportedExtensions);