3 namespace BookStack\Uploads\Controllers;
5 use BookStack\Entities\Queries\PageQueries;
6 use BookStack\Exceptions\NotFoundException;
7 use BookStack\Http\ApiController;
8 use BookStack\Permissions\Permission;
9 use BookStack\Uploads\Image;
10 use BookStack\Uploads\ImageRepo;
11 use BookStack\Uploads\ImageResizer;
12 use BookStack\Uploads\ImageService;
13 use Illuminate\Http\Request;
15 class ImageGalleryApiController extends ApiController
17 protected array $fieldsToExpose = [
18 'id', 'name', 'url', 'path', 'type', 'uploaded_to', 'created_by', 'updated_by', 'created_at', 'updated_at',
21 public function __construct(
22 protected ImageRepo $imageRepo,
23 protected ImageResizer $imageResizer,
24 protected PageQueries $pageQueries,
25 protected ImageService $imageService,
29 protected function rules(): array
33 'type' => ['required', 'string', 'in:gallery,drawio'],
34 'uploaded_to' => ['required', 'integer'],
35 'image' => ['required', 'file', ...$this->getImageValidationRules()],
36 'name' => ['string', 'max:180'],
39 'url' => ['required', 'string', 'url'],
42 'name' => ['string', 'max:180'],
43 'image' => ['file', ...$this->getImageValidationRules()],
49 * Get a listing of images in the system. Includes gallery (page content) images and drawings.
50 * Requires visibility of the page they're originally uploaded to.
52 public function list()
54 $images = Image::query()->scopes(['visible'])
55 ->select($this->fieldsToExpose)
56 ->whereIn('type', ['gallery', 'drawio']);
58 return $this->apiListingResponse($images, [
59 ...$this->fieldsToExpose
64 * Create a new image in the system.
66 * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request.
67 * The provided "uploaded_to" should be an existing page ID in the system.
69 * If the "name" parameter is omitted, the filename of the provided image file will be used instead.
70 * The "type" parameter should be 'gallery' for page content images, and 'drawio' should only be used
71 * when the file is a PNG file with diagrams.net image data embedded within.
73 public function create(Request $request)
75 $this->checkPermission(Permission::ImageCreateAll);
76 $data = $this->validate($request, $this->rules()['create']);
77 $page = $this->pageQueries->findVisibleByIdOrFail($data['uploaded_to']);
79 $image = $this->imageRepo->saveNew($data['image'], $data['type'], $page->id);
81 if (isset($data['name'])) {
83 $image->update(['name' => $data['name']]);
86 return response()->json($this->formatForSingleResponse($image));
90 * View the details of a single image.
91 * The "thumbs" response property contains links to scaled variants that BookStack may use in its UI.
92 * The "content" response property provides HTML and Markdown content, in the format that BookStack
93 * would typically use by default to add the image in page content, as a convenience.
94 * Actual image file data is not provided but can be fetched via the "url" response property or by
95 * using the "read-data" endpoint.
97 public function read(string $id)
99 $image = Image::query()->scopes(['visible'])->findOrFail($id);
101 return response()->json($this->formatForSingleResponse($image));
105 * Read the image file data for a single image in the system.
106 * The returned response will be a stream of image data instead of a JSON response.
108 public function readData(string $id)
110 $image = Image::query()->scopes(['visible'])->findOrFail($id);
112 return $this->imageService->streamImageFromStorageResponse('gallery', $image->path);
116 * Read the image file data for a single image in the system, using the provided URL
117 * to identify the image instead of its ID, which is provided as a "URL" query parameter.
118 * The returned response will be a stream of image data instead of a JSON response.
120 public function readDataForUrl(Request $request)
122 $data = $this->validate($request, $this->rules()['readDataForUrl']);
123 $basePath = url('/uploads/images/');
124 $imagePath = str_replace($basePath, '', $data['url']);
126 if (!$this->imageService->pathAccessible($imagePath)) {
127 throw (new NotFoundException(trans('errors.image_not_found')))
128 ->setSubtitle(trans('errors.image_not_found_subtitle'))
129 ->setDetails(trans('errors.image_not_found_details'));
132 return $this->imageService->streamImageFromStorageResponse('gallery', $imagePath);
136 * Update the details of an existing image in the system.
137 * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request if providing a
138 * new image file. Updated image files should be of the same file type as the original image.
140 public function update(Request $request, string $id)
142 $data = $this->validate($request, $this->rules()['update']);
143 $image = $this->imageRepo->getById($id);
144 $this->checkOwnablePermission(Permission::PageView, $image->getPage());
145 $this->checkOwnablePermission(Permission::ImageUpdate, $image);
147 $this->imageRepo->updateImageDetails($image, $data);
148 if (isset($data['image'])) {
149 $this->imageRepo->updateImageFile($image, $data['image']);
152 return response()->json($this->formatForSingleResponse($image));
156 * Delete an image from the system.
157 * Will also delete thumbnails for the image.
158 * Does not check or handle image usage so this could leave pages with broken image references.
160 public function delete(string $id)
162 $image = $this->imageRepo->getById($id);
163 $this->checkOwnablePermission(Permission::PageView, $image->getPage());
164 $this->checkOwnablePermission(Permission::ImageDelete, $image);
165 $this->imageRepo->destroyImage($image);
167 return response('', 204);
171 * Format the given image model for single-result display.
173 protected function formatForSingleResponse(Image $image): array
175 $this->imageResizer->loadGalleryThumbnailsForImage($image, false);
176 $data = $image->toArray();
177 $data['created_by'] = $image->createdBy;
178 $data['updated_by'] = $image->updatedBy;
179 $data['content'] = [];
181 $escapedUrl = htmlentities($image->url);
182 $escapedName = htmlentities($image->name);
184 if ($image->type === 'drawio') {
185 $data['content']['html'] = "<div drawio-diagram=\"{$image->id}\"><img src=\"{$escapedUrl}\"></div>";
186 $data['content']['markdown'] = $data['content']['html'];
188 $escapedDisplayThumb = htmlentities($image->getAttribute('thumbs')['display']);
189 $data['content']['html'] = "<a href=\"{$escapedUrl}\" target=\"_blank\"><img src=\"{$escapedDisplayThumb}\" alt=\"{$escapedName}\"></a>";
190 $mdEscapedName = str_replace(']', '', str_replace('[', '', $image->name));
191 $mdEscapedThumb = str_replace(']', '', str_replace('[', '', $image->getAttribute('thumbs')['display']));
192 $data['content']['markdown'] = "";