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 $disk = $this->storage->getDisk($image->type);
157 $disk->destroyAllMatchingNameFromPath($image->path);
162 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
163 * Checks based off of only the image name.
164 * Could be much improved to be more specific but kept it generic for now to be safe.
166 * Returns the path of the images that would be/have been deleted.
168 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
170 $types = ['gallery', 'drawio'];
173 Image::query()->whereIn('type', $types)
174 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
175 /** @var Image $image */
176 foreach ($images as $image) {
177 $searchQuery = '%' . basename($image->path) . '%';
178 $inPage = DB::table('pages')
179 ->where('html', 'like', $searchQuery)->count() > 0;
182 if ($checkRevisions) {
183 $inRevision = DB::table('page_revisions')
184 ->where('html', 'like', $searchQuery)->count() > 0;
187 if (!$inPage && !$inRevision) {
188 $deletedPaths[] = $image->path;
190 $this->destroy($image);
196 return $deletedPaths;
200 * Convert an image URI to a Base64 encoded string.
201 * Attempts to convert the URL to a system storage url then
202 * fetch the data from the disk or storage location.
203 * Returns null if the image data cannot be fetched from storage.
205 public function imageUrlToBase64(string $url): ?string
207 $storagePath = $this->storage->urlToPath($url);
208 if (empty($url) || is_null($storagePath)) {
212 // Apply access control when local_secure_restricted images are active
213 if ($this->storage->usingSecureRestrictedImages()) {
214 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
219 $disk = $this->storage->getDisk();
221 if ($disk->exists($storagePath)) {
222 $imageData = $disk->get($storagePath);
225 if (is_null($imageData)) {
229 $extension = pathinfo($url, PATHINFO_EXTENSION);
230 if ($extension === 'svg') {
231 $extension = 'svg+xml';
234 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
238 * Check if the given path exists and is accessible in the local secure image system.
239 * Returns false if local_secure is not in use, if the file does not exist, if the
240 * file is likely not a valid image, or if permission does not allow access.
242 public function pathAccessibleInLocalSecure(string $imagePath): bool
244 $disk = $this->storage->getDisk('gallery');
246 if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
250 // Check local_secure is active
251 return $disk->usingSecureImages()
252 // Check the image file exists
253 && $disk->exists($imagePath)
254 // Check the file is likely an image file
255 && str_starts_with($disk->mimeType($imagePath), 'image/');
259 * Check that the current user has access to the relation
260 * of the image at the given path.
262 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
264 if (str_starts_with($path, 'uploads/images/')) {
265 $path = substr($path, 15);
268 // Strip thumbnail element from path if existing
269 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
270 $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
271 $missingExtension = !str_contains($part, '.');
273 return !($resizedDir && $missingExtension);
276 // Build a database-format image path and search for the image entry
277 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
278 $image = Image::query()->where('path', '=', $fullPath)->first();
280 if (is_null($image)) {
284 $imageType = $image->type;
286 // Allow user or system (logo) images
287 // (No specific relation control but may still have access controlled by auth)
288 if ($imageType === 'user' || $imageType === 'system') {
292 if ($imageType === 'gallery' || $imageType === 'drawio') {
293 return $this->queries->pages->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
296 if ($imageType === 'cover_book') {
297 return $this->queries->books->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
300 if ($imageType === 'cover_bookshelf') {
301 return $this->queries->shelves->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
308 * For the given path, if existing, provide a response that will stream the image contents.
310 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
312 $disk = $this->storage->getDisk($imageType);
314 return $disk->response($path);
318 * Check if the given image extension is supported by BookStack.
319 * The extension must not be altered in this function. This check should provide a guarantee
320 * that the provided extension is safe to use for the image to be saved.
322 public static function isExtensionSupported(string $extension): bool
324 return in_array($extension, static::$supportedExtensions);