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