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