]> BookStack Code Mirror - bookstack/blob - app/Uploads/Controllers/ImageGalleryApiController.php
Exceptions: Added some types, simplified some classes
[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      * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request.
56      * The provided "uploaded_to" should be an existing page ID in the system.
57      * If the "name" parameter is omitted, the filename of the provided image file will be used instead.
58      * The "type" parameter should be 'gallery' for page content images, and 'drawio' should only be used
59      * when the file is a PNG file with diagrams.net image data embedded within.
60      */
61     public function create(Request $request)
62     {
63         $this->checkPermission('image-create-all');
64         $data = $this->validate($request, $this->rules()['create']);
65         Page::visible()->findOrFail($data['uploaded_to']);
66
67         $image = $this->imageRepo->saveNew($data['image'], $data['type'], $data['uploaded_to']);
68
69         if (isset($data['name'])) {
70             $image->refresh();
71             $image->update(['name' => $data['name']]);
72         }
73
74         return response()->json($this->formatForSingleResponse($image));
75     }
76
77     /**
78      * View the details of a single image.
79      * The "thumbs" response property contains links to scaled variants that BookStack may use in its UI.
80      * The "content" response property provides HTML and Markdown content, in the format that BookStack
81      * would typically use by default to add the image in page content, as a convenience.
82      * Actual image file data is not provided but can be fetched via the "url" response property.
83      */
84     public function read(string $id)
85     {
86         $image = Image::query()->scopes(['visible'])->findOrFail($id);
87
88         return response()->json($this->formatForSingleResponse($image));
89     }
90
91     /**
92      * Update the details of an existing image in the system.
93      * Since "image" is expected to be a file, this needs to be a 'multipart/form-data' type request if providing a
94      * new image file. Updated image files should be of the same file type as the original image.
95      */
96     public function update(Request $request, string $id)
97     {
98         $data = $this->validate($request, $this->rules()['update']);
99         $image = $this->imageRepo->getById($id);
100         $this->checkOwnablePermission('page-view', $image->getPage());
101         $this->checkOwnablePermission('image-update', $image);
102
103         $this->imageRepo->updateImageDetails($image, $data);
104         if (isset($data['image'])) {
105             $this->imageRepo->updateImageFile($image, $data['image']);
106         }
107
108         return response()->json($this->formatForSingleResponse($image));
109     }
110
111     /**
112      * Delete an image from the system.
113      * Will also delete thumbnails for the image.
114      * Does not check or handle image usage so this could leave pages with broken image references.
115      */
116     public function delete(string $id)
117     {
118         $image = $this->imageRepo->getById($id);
119         $this->checkOwnablePermission('page-view', $image->getPage());
120         $this->checkOwnablePermission('image-delete', $image);
121         $this->imageRepo->destroyImage($image);
122
123         return response('', 204);
124     }
125
126     /**
127      * Format the given image model for single-result display.
128      */
129     protected function formatForSingleResponse(Image $image): array
130     {
131         $this->imageRepo->loadThumbs($image);
132         $data = $image->getAttributes();
133         $data['created_by'] = $image->createdBy;
134         $data['updated_by'] = $image->updatedBy;
135         $data['content'] = [];
136
137         $escapedUrl = htmlentities($image->url);
138         $escapedName = htmlentities($image->name);
139         if ($image->type === 'drawio') {
140             $data['content']['html'] = "<div drawio-diagram=\"{$image->id}\"><img src=\"{$escapedUrl}\"></div>";
141             $data['content']['markdown'] = $data['content']['html'];
142         } else {
143             $escapedDisplayThumb = htmlentities($image->thumbs['display']);
144             $data['content']['html'] = "<a href=\"{$escapedUrl}\" target=\"_blank\"><img src=\"{$escapedDisplayThumb}\" alt=\"{$escapedName}\"></a>";
145             $mdEscapedName = str_replace(']', '', str_replace('[', '', $image->name));
146             $mdEscapedThumb = str_replace(']', '', str_replace('[', '', $image->thumbs['display']));
147             $data['content']['markdown'] = "![{$mdEscapedName}]({$mdEscapedThumb})";
148         }
149
150         return $data;
151     }
152 }