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