]> BookStack Code Mirror - bookstack/blob - app/Uploads/Controllers/ImageGalleryApiController.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / Uploads / Controllers / ImageGalleryApiController.php
1 <?php
2
3 namespace BookStack\Uploads\Controllers;
4
5 use BookStack\Entities\Queries\PageQueries;
6 use BookStack\Http\ApiController;
7 use BookStack\Uploads\Image;
8 use BookStack\Uploads\ImageRepo;
9 use BookStack\Uploads\ImageResizer;
10 use Illuminate\Http\Request;
11
12 class ImageGalleryApiController extends ApiController
13 {
14     protected array $fieldsToExpose = [
15         'id', 'name', 'url', 'path', 'type', 'uploaded_to', 'created_by', 'updated_by',  'created_at', 'updated_at',
16     ];
17
18     public function __construct(
19         protected ImageRepo $imageRepo,
20         protected ImageResizer $imageResizer,
21         protected PageQueries $pageQueries,
22     ) {
23     }
24
25     protected function rules(): array
26     {
27         return [
28             'create' => [
29                 'type'  => ['required', 'string', 'in:gallery,drawio'],
30                 'uploaded_to' => ['required', 'integer'],
31                 'image' => ['required', 'file', ...$this->getImageValidationRules()],
32                 'name'  => ['string', 'max:180'],
33             ],
34             'update' => [
35                 'name'  => ['string', 'max:180'],
36                 'image' => ['file', ...$this->getImageValidationRules()],
37             ]
38         ];
39     }
40
41     /**
42      * Get a listing of images in the system. Includes gallery (page content) images and drawings.
43      * Requires visibility of the page they're originally uploaded to.
44      */
45     public function list()
46     {
47         $images = Image::query()->scopes(['visible'])
48             ->select($this->fieldsToExpose)
49             ->whereIn('type', ['gallery', 'drawio']);
50
51         return $this->apiListingResponse($images, [
52             ...$this->fieldsToExpose
53         ]);
54     }
55
56     /**
57      * Create a new image in the system.
58      *
59      * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request.
60      * The provided "uploaded_to" should be an existing page ID in the system.
61      *
62      * If the "name" parameter is omitted, the filename of the provided image file will be used instead.
63      * The "type" parameter should be 'gallery' for page content images, and 'drawio' should only be used
64      * when the file is a PNG file with diagrams.net image data embedded within.
65      */
66     public function create(Request $request)
67     {
68         $this->checkPermission('image-create-all');
69         $data = $this->validate($request, $this->rules()['create']);
70         $page = $this->pageQueries->findVisibleByIdOrFail($data['uploaded_to']);
71
72         $image = $this->imageRepo->saveNew($data['image'], $data['type'], $page->id);
73
74         if (isset($data['name'])) {
75             $image->refresh();
76             $image->update(['name' => $data['name']]);
77         }
78
79         return response()->json($this->formatForSingleResponse($image));
80     }
81
82     /**
83      * View the details of a single image.
84      * The "thumbs" response property contains links to scaled variants that BookStack may use in its UI.
85      * The "content" response property provides HTML and Markdown content, in the format that BookStack
86      * would typically use by default to add the image in page content, as a convenience.
87      * Actual image file data is not provided but can be fetched via the "url" response property.
88      */
89     public function read(string $id)
90     {
91         $image = Image::query()->scopes(['visible'])->findOrFail($id);
92
93         return response()->json($this->formatForSingleResponse($image));
94     }
95
96     /**
97      * Update the details of an existing image in the system.
98      * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request if providing a
99      * new image file. Updated image files should be of the same file type as the original image.
100      */
101     public function update(Request $request, string $id)
102     {
103         $data = $this->validate($request, $this->rules()['update']);
104         $image = $this->imageRepo->getById($id);
105         $this->checkOwnablePermission('page-view', $image->getPage());
106         $this->checkOwnablePermission('image-update', $image);
107
108         $this->imageRepo->updateImageDetails($image, $data);
109         if (isset($data['image'])) {
110             $this->imageRepo->updateImageFile($image, $data['image']);
111         }
112
113         return response()->json($this->formatForSingleResponse($image));
114     }
115
116     /**
117      * Delete an image from the system.
118      * Will also delete thumbnails for the image.
119      * Does not check or handle image usage so this could leave pages with broken image references.
120      */
121     public function delete(string $id)
122     {
123         $image = $this->imageRepo->getById($id);
124         $this->checkOwnablePermission('page-view', $image->getPage());
125         $this->checkOwnablePermission('image-delete', $image);
126         $this->imageRepo->destroyImage($image);
127
128         return response('', 204);
129     }
130
131     /**
132      * Format the given image model for single-result display.
133      */
134     protected function formatForSingleResponse(Image $image): array
135     {
136         $this->imageResizer->loadGalleryThumbnailsForImage($image, false);
137         $data = $image->toArray();
138         $data['created_by'] = $image->createdBy;
139         $data['updated_by'] = $image->updatedBy;
140         $data['content'] = [];
141
142         $escapedUrl = htmlentities($image->url);
143         $escapedName = htmlentities($image->name);
144
145         if ($image->type === 'drawio') {
146             $data['content']['html'] = "<div drawio-diagram=\"{$image->id}\"><img src=\"{$escapedUrl}\"></div>";
147             $data['content']['markdown'] = $data['content']['html'];
148         } else {
149             $escapedDisplayThumb = htmlentities($image->thumbs['display']);
150             $data['content']['html'] = "<a href=\"{$escapedUrl}\" target=\"_blank\"><img src=\"{$escapedDisplayThumb}\" alt=\"{$escapedName}\"></a>";
151             $mdEscapedName = str_replace(']', '', str_replace('[', '', $image->name));
152             $mdEscapedThumb = str_replace(']', '', str_replace('[', '', $image->thumbs['display']));
153             $data['content']['markdown'] = "![{$mdEscapedName}]({$mdEscapedThumb})";
154         }
155
156         return $data;
157     }
158 }