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', 'avif'];
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,
37 string $imageName = '',
39 $imageName = $imageName ?: $uploadedFile->getClientOriginalName();
40 $imageData = file_get_contents($uploadedFile->getRealPath());
42 if ($resizeWidth !== null || $resizeHeight !== null) {
43 $imageData = $this->resizer->resizeImageData($imageData, $resizeWidth, $resizeHeight, $keepRatio);
46 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
50 * Save a new image from a uri-encoded base64 string of data.
52 * @throws ImageUploadException
54 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
56 $splitData = explode(';base64,', $base64Uri);
57 if (count($splitData) < 2) {
58 throw new ImageUploadException('Invalid base64 image data provided');
60 $data = base64_decode($splitData[1]);
62 return $this->saveNew($name, $data, $type, $uploadedTo);
66 * Save a new image into storage.
68 * @throws ImageUploadException
70 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
72 $disk = $this->storage->getDisk($type);
73 $secureUploads = setting('app-secure-images');
74 $fileName = $this->storage->cleanImageFileName($imageName);
76 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
78 while ($disk->exists($imagePath . $fileName)) {
79 $fileName = Str::random(3) . $fileName;
82 $fullPath = $imagePath . $fileName;
84 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
88 $disk->put($fullPath, $imageData, true);
89 } catch (Exception $e) {
90 Log::error('Error when attempting image upload:' . $e->getMessage());
92 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
98 'url' => $this->storage->getPublicUrl($fullPath),
100 'uploaded_to' => $uploadedTo,
103 if (user()->id !== 0) {
104 $userId = user()->id;
105 $imageDetails['created_by'] = $userId;
106 $imageDetails['updated_by'] = $userId;
109 $image = (new Image())->forceFill($imageDetails);
116 * Replace an existing image file in the system using the given file.
118 public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
120 $imageData = file_get_contents($file->getRealPath());
121 $disk = $this->storage->getDisk($type);
122 $disk->put($path, $imageData);
126 * Get the raw data content from an image.
130 public function getImageData(Image $image): string
132 $disk = $this->storage->getDisk();
134 return $disk->get($image->path);
138 * Get the raw data content from an image.
143 public function getImageStream(Image $image): mixed
145 $disk = $this->storage->getDisk();
147 return $disk->stream($image->path);
151 * Destroy an image along with its revisions, thumbnails and remaining folders.
155 public function destroy(Image $image): void
157 $this->destroyFileAtPath($image->type, $image->path);
162 * Destroy the underlying image file at the given path.
164 public function destroyFileAtPath(string $type, string $path): void
166 $disk = $this->storage->getDisk($type);
167 $disk->destroyAllMatchingNameFromPath($path);
171 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
172 * Checks based off of only the image name.
173 * Could be much improved to be more specific but kept it generic for now to be safe.
175 * Returns the path of the images that would be/have been deleted.
177 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
179 $types = ['gallery', 'drawio'];
182 Image::query()->whereIn('type', $types)
183 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
184 /** @var Image $image */
185 foreach ($images as $image) {
186 $searchQuery = '%' . basename($image->path) . '%';
187 $inPage = DB::table('pages')
188 ->where('html', 'like', $searchQuery)->count() > 0;
191 if ($checkRevisions) {
192 $inRevision = DB::table('page_revisions')
193 ->where('html', 'like', $searchQuery)->count() > 0;
196 if (!$inPage && !$inRevision) {
197 $deletedPaths[] = $image->path;
199 $this->destroy($image);
205 return $deletedPaths;
209 * Convert an image URI to a Base64 encoded string.
210 * Attempts to convert the URL to a system storage url then
211 * fetch the data from the disk or storage location.
212 * Returns null if the image data cannot be fetched from storage.
214 public function imageUrlToBase64(string $url): ?string
216 $storagePath = $this->storage->urlToPath($url);
217 if (empty($url) || is_null($storagePath)) {
221 // Apply access control when local_secure_restricted images are active
222 if ($this->storage->usingSecureRestrictedImages()) {
223 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
228 $disk = $this->storage->getDisk();
230 if ($disk->exists($storagePath)) {
231 $imageData = $disk->get($storagePath);
234 if (is_null($imageData)) {
238 $extension = pathinfo($url, PATHINFO_EXTENSION);
239 if ($extension === 'svg') {
240 $extension = 'svg+xml';
243 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
247 * Check if the given path exists and is accessible in the local secure image system.
248 * Returns false if local_secure is not in use, if the file does not exist, if the
249 * file is likely not a valid image, or if permission does not allow access.
251 public function pathAccessibleInLocalSecure(string $imagePath): bool
253 $disk = $this->storage->getDisk('gallery');
255 if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
259 // Check local_secure is active
260 return $disk->usingSecureImages()
261 // Check the image file exists
262 && $disk->exists($imagePath)
263 // Check the file is likely an image file
264 && str_starts_with($disk->mimeType($imagePath), 'image/');
268 * Check that the current user has access to the relation
269 * of the image at the given path.
271 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
273 if (str_starts_with($path, 'uploads/images/')) {
274 $path = substr($path, 15);
277 // Strip thumbnail element from path if existing
278 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
279 $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
280 $missingExtension = !str_contains($part, '.');
282 return !($resizedDir && $missingExtension);
285 // Build a database-format image path and search for the image entry
286 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
287 $image = Image::query()->where('path', '=', $fullPath)->first();
289 if (is_null($image)) {
293 $imageType = $image->type;
295 // Allow user or system (logo) images
296 // (No specific relation control but may still have access controlled by auth)
297 if ($imageType === 'user' || $imageType === 'system') {
301 if ($imageType === 'gallery' || $imageType === 'drawio') {
302 return $this->queries->pages->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
305 if ($imageType === 'cover_book') {
306 return $this->queries->books->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
309 if ($imageType === 'cover_bookshelf') {
310 return $this->queries->shelves->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
317 * For the given path, if existing, provide a response that will stream the image contents.
319 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
321 $disk = $this->storage->getDisk($imageType);
323 return $disk->response($path);
327 * Check if the given image extension is supported by BookStack.
328 * The extension must not be altered in this function. This check should provide a guarantee
329 * that the provided extension is safe to use for the image to be saved.
331 public static function isExtensionSupported(string $extension): bool
333 return in_array($extension, static::$supportedExtensions);