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