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;
10 use Illuminate\Support\Facades\DB;
11 use Illuminate\Support\Facades\Log;
12 use Illuminate\Support\Str;
13 use Symfony\Component\HttpFoundation\File\UploadedFile;
14 use Symfony\Component\HttpFoundation\StreamedResponse;
18 protected static array $supportedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
20 public function __construct(
21 protected ImageStorage $storage,
22 protected ImageResizer $resizer,
27 * Saves a new image from an upload.
29 * @throws ImageUploadException
31 public function saveNewFromUpload(
32 UploadedFile $uploadedFile,
35 int $resizeWidth = null,
36 int $resizeHeight = null,
37 bool $keepRatio = true
39 $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 * Destroy an image along with its revisions, thumbnails and remaining folders.
142 public function destroy(Image $image): void
144 $disk = $this->storage->getDisk($image->type);
145 $disk->destroyAllMatchingNameFromPath($image->path);
150 * Delete gallery and drawings that are not within HTML content of pages or page revisions.
151 * Checks based off of only the image name.
152 * Could be much improved to be more specific but kept it generic for now to be safe.
154 * Returns the path of the images that would be/have been deleted.
156 public function deleteUnusedImages(bool $checkRevisions = true, bool $dryRun = true): array
158 $types = ['gallery', 'drawio'];
161 Image::query()->whereIn('type', $types)
162 ->chunk(1000, function ($images) use ($checkRevisions, &$deletedPaths, $dryRun) {
163 /** @var Image $image */
164 foreach ($images as $image) {
165 $searchQuery = '%' . basename($image->path) . '%';
166 $inPage = DB::table('pages')
167 ->where('html', 'like', $searchQuery)->count() > 0;
170 if ($checkRevisions) {
171 $inRevision = DB::table('page_revisions')
172 ->where('html', 'like', $searchQuery)->count() > 0;
175 if (!$inPage && !$inRevision) {
176 $deletedPaths[] = $image->path;
178 $this->destroy($image);
184 return $deletedPaths;
188 * Convert an image URI to a Base64 encoded string.
189 * Attempts to convert the URL to a system storage url then
190 * fetch the data from the disk or storage location.
191 * Returns null if the image data cannot be fetched from storage.
193 public function imageUrlToBase64(string $url): ?string
195 $storagePath = $this->storage->urlToPath($url);
196 if (empty($url) || is_null($storagePath)) {
200 // Apply access control when local_secure_restricted images are active
201 if ($this->storage->usingSecureRestrictedImages()) {
202 if (!$this->checkUserHasAccessToRelationOfImageAtPath($storagePath)) {
207 $disk = $this->storage->getDisk();
209 if ($disk->exists($storagePath)) {
210 $imageData = $disk->get($storagePath);
213 if (is_null($imageData)) {
217 $extension = pathinfo($url, PATHINFO_EXTENSION);
218 if ($extension === 'svg') {
219 $extension = 'svg+xml';
222 return 'data:image/' . $extension . ';base64,' . base64_encode($imageData);
226 * Check if the given path exists and is accessible in the local secure image system.
227 * Returns false if local_secure is not in use, if the file does not exist, if the
228 * file is likely not a valid image, or if permission does not allow access.
230 public function pathAccessibleInLocalSecure(string $imagePath): bool
232 $disk = $this->storage->getDisk('gallery');
234 if ($this->storage->usingSecureRestrictedImages() && !$this->checkUserHasAccessToRelationOfImageAtPath($imagePath)) {
238 // Check local_secure is active
239 return $disk->usingSecureImages()
240 // Check the image file exists
241 && $disk->exists($imagePath)
242 // Check the file is likely an image file
243 && str_starts_with($disk->mimeType($imagePath), 'image/');
247 * Check that the current user has access to the relation
248 * of the image at the given path.
250 protected function checkUserHasAccessToRelationOfImageAtPath(string $path): bool
252 if (str_starts_with($path, 'uploads/images/')) {
253 $path = substr($path, 15);
256 // Strip thumbnail element from path if existing
257 $originalPathSplit = array_filter(explode('/', $path), function (string $part) {
258 $resizedDir = (str_starts_with($part, 'thumbs-') || str_starts_with($part, 'scaled-'));
259 $missingExtension = !str_contains($part, '.');
261 return !($resizedDir && $missingExtension);
264 // Build a database-format image path and search for the image entry
265 $fullPath = '/uploads/images/' . ltrim(implode('/', $originalPathSplit), '/');
266 $image = Image::query()->where('path', '=', $fullPath)->first();
268 if (is_null($image)) {
272 $imageType = $image->type;
274 // Allow user or system (logo) images
275 // (No specific relation control but may still have access controlled by auth)
276 if ($imageType === 'user' || $imageType === 'system') {
280 if ($imageType === 'gallery' || $imageType === 'drawio') {
281 return Page::visible()->where('id', '=', $image->uploaded_to)->exists();
284 if ($imageType === 'cover_book') {
285 return Book::visible()->where('id', '=', $image->uploaded_to)->exists();
288 if ($imageType === 'cover_bookshelf') {
289 return Bookshelf::visible()->where('id', '=', $image->uploaded_to)->exists();
296 * For the given path, if existing, provide a response that will stream the image contents.
298 public function streamImageFromStorageResponse(string $imageType, string $path): StreamedResponse
300 $disk = $this->storage->getDisk($imageType);
302 return $disk->response($path);
306 * Check if the given image extension is supported by BookStack.
307 * The extension must not be altered in this function. This check should provide a guarantee
308 * that the provided extension is safe to use for the image to be saved.
310 public static function isExtensionSupported(string $extension): bool
312 return in_array($extension, static::$supportedExtensions);