]> BookStack Code Mirror - bookstack/blob - app/Uploads/Controllers/ImageGalleryApiController.php
Merge pull request #5860 from BookStackApp/api_image_data_endpoint
[bookstack] / app / Uploads / Controllers / ImageGalleryApiController.php
1 <?php
2
3 namespace BookStack\Uploads\Controllers;
4
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;
14
15 class ImageGalleryApiController extends ApiController
16 {
17     protected array $fieldsToExpose = [
18         'id', 'name', 'url', 'path', 'type', 'uploaded_to', 'created_by', 'updated_by',  'created_at', 'updated_at',
19     ];
20
21     public function __construct(
22         protected ImageRepo $imageRepo,
23         protected ImageResizer $imageResizer,
24         protected PageQueries $pageQueries,
25         protected ImageService $imageService,
26     ) {
27     }
28
29     protected function rules(): array
30     {
31         return [
32             'create' => [
33                 'type'  => ['required', 'string', 'in:gallery,drawio'],
34                 'uploaded_to' => ['required', 'integer'],
35                 'image' => ['required', 'file', ...$this->getImageValidationRules()],
36                 'name'  => ['string', 'max:180'],
37             ],
38             'readDataForUrl' => [
39                 'url' => ['required', 'string', 'url'],
40             ],
41             'update' => [
42                 'name'  => ['string', 'max:180'],
43                 'image' => ['file', ...$this->getImageValidationRules()],
44             ]
45         ];
46     }
47
48     /**
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.
51      */
52     public function list()
53     {
54         $images = Image::query()->scopes(['visible'])
55             ->select($this->fieldsToExpose)
56             ->whereIn('type', ['gallery', 'drawio']);
57
58         return $this->apiListingResponse($images, [
59             ...$this->fieldsToExpose
60         ]);
61     }
62
63     /**
64      * Create a new image in the system.
65      *
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.
68      *
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.
72      */
73     public function create(Request $request)
74     {
75         $this->checkPermission(Permission::ImageCreateAll);
76         $data = $this->validate($request, $this->rules()['create']);
77         $page = $this->pageQueries->findVisibleByIdOrFail($data['uploaded_to']);
78
79         $image = $this->imageRepo->saveNew($data['image'], $data['type'], $page->id);
80
81         if (isset($data['name'])) {
82             $image->refresh();
83             $image->update(['name' => $data['name']]);
84         }
85
86         return response()->json($this->formatForSingleResponse($image));
87     }
88
89     /**
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.
96      */
97     public function read(string $id)
98     {
99         $image = Image::query()->scopes(['visible'])->findOrFail($id);
100
101         return response()->json($this->formatForSingleResponse($image));
102     }
103
104     /**
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.
107      */
108     public function readData(string $id)
109     {
110         $image = Image::query()->scopes(['visible'])->findOrFail($id);
111
112         return $this->imageService->streamImageFromStorageResponse('gallery', $image->path);
113     }
114
115     /**
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.
119      */
120     public function readDataForUrl(Request $request)
121     {
122         $data = $this->validate($request, $this->rules()['readDataForUrl']);
123         $basePath = url('/uploads/images/');
124         $imagePath = str_replace($basePath, '', $data['url']);
125
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'));
130         }
131
132         return $this->imageService->streamImageFromStorageResponse('gallery', $imagePath);
133     }
134
135     /**
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.
139      */
140     public function update(Request $request, string $id)
141     {
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);
146
147         $this->imageRepo->updateImageDetails($image, $data);
148         if (isset($data['image'])) {
149             $this->imageRepo->updateImageFile($image, $data['image']);
150         }
151
152         return response()->json($this->formatForSingleResponse($image));
153     }
154
155     /**
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.
159      */
160     public function delete(string $id)
161     {
162         $image = $this->imageRepo->getById($id);
163         $this->checkOwnablePermission(Permission::PageView, $image->getPage());
164         $this->checkOwnablePermission(Permission::ImageDelete, $image);
165         $this->imageRepo->destroyImage($image);
166
167         return response('', 204);
168     }
169
170     /**
171      * Format the given image model for single-result display.
172      */
173     protected function formatForSingleResponse(Image $image): array
174     {
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'] = [];
180
181         $escapedUrl = htmlentities($image->url);
182         $escapedName = htmlentities($image->name);
183
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'];
187         } else {
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'] = "![{$mdEscapedName}]({$mdEscapedThumb})";
193         }
194
195         return $data;
196     }
197 }