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\Entities\Queries\EntityQueries;
9 use BookStack\Exceptions\ImageUploadException;
11 use Illuminate\Support\Facades\DB;
12 use Illuminate\Support\Facades\Log;
13 use Illuminate\Support\Str;
14 use Symfony\Component\HttpFoundation\File\UploadedFile;
15 use Symfony\Component\HttpFoundation\StreamedResponse;
19 protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
21 public function __construct(
22 protected ImageStorage $storage,
23 protected ImageResizer $resizer,
24 protected EntityQueries $queries,
29 * Saves a new image from an upload.
31 * @throws ImageUploadException
33 public function saveNewFromUpload(
34 UploadedFile $uploadedFile,
37 int $resizeWidth = null,
38 int $resizeHeight = null,
39 bool $keepRatio = true
41 $imageName = $uploadedFile->getClientOriginalName();
42 $imageData = file_get_contents($uploadedFile->getRealPath());
44 if ($resizeWidth !== null || $resizeHeight !== null) {
45 $imageData = $this->resizer->resizeImageData($imageData, $resizeWidth, $resizeHeight, $keepRatio);
48 return $this->saveNew($imageName, $imageData, $type, $uploadedTo);
52 * Save a new image from a uri-encoded base64 string of data.
54 * @throws ImageUploadException
56 public function saveNewFromBase64Uri(string $base64Uri, string $name, string $type, int $uploadedTo = 0): Image
58 $splitData = explode(';base64,', $base64Uri);
59 if (count($splitData) < 2) {
60 throw new ImageUploadException('Invalid base64 image data provided');
62 $data = base64_decode($splitData[1]);
64 return $this->saveNew($name, $data, $type, $uploadedTo);
68 * Save a new image into storage.
70 * @throws ImageUploadException
72 public function saveNew(string $imageName, string $imageData, string $type, int $uploadedTo = 0): Image
74 $disk = $this->storage->getDisk($type);
75 $secureUploads = setting('app-secure-images');
76 $fileName = $this->storage->cleanImageFileName($imageName);
78 $imagePath = '/uploads/images/' . $type . '/' . date('Y-m') . '/';
80 while ($disk->exists($imagePath . $fileName)) {
81 $fileName = Str::random(3) . $fileName;
84 $fullPath = $imagePath . $fileName;
86 $fullPath = $imagePath . Str::random(16) . '-' . $fileName;
90 $disk->put($fullPath, $imageData, true);
91 } catch (Exception $e) {
92 Log::error('Error when attempting image upload:' . $e->getMessage());
94 throw new ImageUploadException(trans('errors.path_not_writable', ['filePath' => $fullPath]));
100 'url' => $this->storage->getPublicUrl($fullPath),
102 'uploaded_to' => $uploadedTo,
105 if (user()->id !== 0) {
106 $userId = user()->id;
107 $imageDetails['created_by'] = $userId;
108 $imageDetails['updated_by'] = $userId;
111 $image = (new Image())->forceFill($imageDetails);
118 * Replace an existing image file in the system using the given file.
120 public function replaceExistingFromUpload(string $path, string $type, UploadedFile $file): void
122 $imageData = file_get_contents($file->getRealPath());
123 $disk = $this->storage->getDisk($type);
124 $disk->put($path, $imageData);
128 * Get the raw data content from an image.
132 public function getImageData(Image $image): string
134 $disk = $this->storage->getDisk();
136 return $disk->get($image->path);
140 * Destroy an image along with its revisions, thumbnails and remaining folders.
144 public function destroy(Image $image): void
146 $disk = $this->storage->getDisk($image->type);
147 $disk->destroyAllMatchingNameFromPath($image->path);
152 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
153 * Checks based off of only the image name.
154 * Could be much improved to be more specific but kept it generic for now to be safe.
156 * Returns the path of the images that would be/have been deleted.
158 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
160 $types = ['gallery', 'drawio'];
163 Image::query()->whereIn('type', $types)
164 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
165 /** @var Image $image */
166 foreach ($images as $image) {
167 $searchQuery = '%' . basename($image->path) . '%';
168 $inPage = DB::table('pages')
169 ->where('html', 'like', $searchQuery)->count() > 0;
172 if ($checkRevisions) {
173 $inRevision = DB::table('page_revisions')
174 ->where('html', 'like', $searchQuery)->count() > 0;
177 if (!$inPage && !$inRevision) {
178 $deletedPaths[] = $image->path;
180 $this->destroy($image);
186 return $deletedPaths;
190 * Convert an image URI to a Base64 encoded string.
191 * Attempts to convert the URL to a system storage url then
192 * fetch the data from the disk or storage location.
193 * Returns null if the image data cannot be fetched from storage.
195 public function imageUrlToBase64(string $url): ?string
197 $storagePath = $this->storage->urlToPath($url);
198 if (empty($url) || is_null($storagePath)) {
202 // Apply access control when local_secure_restricted images are active
203 if ($this->storage->usingSecureRestrictedImages()) {
204 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
209 $disk = $this->storage->getDisk();
211 if ($disk->exists($storagePath)) {
212 $imageData = $disk->get($storagePath);
215 if (is_null($imageData)) {
219 $extension = pathinfo($url, PATHINFO_EXTENSION);
220 if ($extension === 'svg') {
221 $extension = 'svg+xml';
224 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
228 * Check if the given path exists and is accessible in the local secure image system.
229 * Returns false if local_secure is not in use, if the file does not exist, if the
230 * file is likely not a valid image, or if permission does not allow access.
232 public function pathAccessibleInLocalSecure(string $imagePath): bool
234 $disk = $this->storage->getDisk('gallery');
236 if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
240 // Check local_secure is active
241 return $disk->usingSecureImages()
242 // Check the image file exists
243 && $disk->exists($imagePath)
244 // Check the file is likely an image file
245 && str_starts_with($disk->mimeType($imagePath), 'image/');
249 * Check that the current user has access to the relation
250 * of the image at the given path.
252 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
254 if (str_starts_with($path, 'uploads/images/')) {
255 $path = substr($path, 15);
258 // Strip thumbnail element from path if existing
259 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
260 $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
261 $missingExtension = !str_contains($part, '.');
263 return !($resizedDir && $missingExtension);
266 // Build a database-format image path and search for the image entry
267 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
268 $image = Image::query()->where('path', '=', $fullPath)->first();
270 if (is_null($image)) {
274 $imageType = $image->type;
276 // Allow user or system (logo) images
277 // (No specific relation control but may still have access controlled by auth)
278 if ($imageType === 'user' || $imageType === 'system') {
282 if ($imageType === 'gallery' || $imageType === 'drawio') {
283 return $this->queries->pages->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
286 if ($imageType === 'cover_book') {
287 return $this->queries->books->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
290 if ($imageType === 'cover_bookshelf') {
291 return $this->queries->shelves->visibleForList()->where('id', '=', $image->uploaded_to)->exists();
298 * For the given path, if existing, provide a response that will stream the image contents.
300 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
302 $disk = $this->storage->getDisk($imageType);
304 return $disk->response($path);
308 * Check if the given image extension is supported by BookStack.
309 * The extension must not be altered in this function. This check should provide a guarantee
310 * that the provided extension is safe to use for the image to be saved.
312 public static function isExtensionSupported(string $extension): bool
314 return in_array($extension, static::$supportedExtensions);