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