]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Api/ImageGalleryApiController.php
Added phpunit tests to cover image API endpoints
[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 gallery images and drawings in the system.
38      * Requires visibility of the content 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      */
54     public function create(Request $request)
55     {
56         $this->checkPermission('image-create-all');
57         $data = $this->validate($request, $this->rules()['create']);
58         Page::visible()->findOrFail($data['uploaded_to']);
59
60         $image = $this->imageRepo->saveNew($data['image'], $data['type'], $data['uploaded_to']);
61
62         if (isset($data['name'])) {
63             $image->refresh();
64             $image->update(['name' => $data['name']]);
65         }
66
67         return response()->json($this->formatForSingleResponse($image));
68     }
69
70     /**
71      * View the details of a single image.
72      */
73     public function read(string $id)
74     {
75         $image = Image::query()->scopes(['visible'])->findOrFail($id);
76
77         return response()->json($this->formatForSingleResponse($image));
78     }
79
80     /**
81      * Update an existing image in the system.
82      */
83     public function update(Request $request, string $id)
84     {
85         $data = $this->validate($request, $this->rules()['update']);
86         $image = $this->imageRepo->getById($id);
87         $this->checkOwnablePermission('page-view', $image->getPage());
88         $this->checkOwnablePermission('image-update', $image);
89
90         $this->imageRepo->updateImageDetails($image, $data);
91
92         return response()->json($this->formatForSingleResponse($image));
93     }
94
95     /**
96      * Delete an image from the system.
97      */
98     public function delete(string $id)
99     {
100         $image = $this->imageRepo->getById($id);
101         $this->checkOwnablePermission('page-view', $image->getPage());
102         $this->checkOwnablePermission('image-delete', $image);
103         $this->imageRepo->destroyImage($image);
104
105         return response('', 204);
106     }
107
108     /**
109      * Format the given image model for single-result display.
110      */
111     protected function formatForSingleResponse(Image $image): array
112     {
113         $this->imageRepo->loadThumbs($image);
114         $data = $image->getAttributes();
115         $data['created_by'] = $image->createdBy;
116         $data['updated_by'] = $image->updatedBy;
117         $data['content'] = [];
118
119         $escapedUrl = htmlentities($image->url);
120         $escapedName = htmlentities($image->name);
121         if ($image->type === 'drawio') {
122             $data['content']['html'] = "<div drawio-diagram=\"{$image->id}\"><img src=\"{$escapedUrl}\"></div>";
123             $data['content']['markdown'] = $data['content']['html'];
124         } else {
125             $escapedDisplayThumb = htmlentities($image->thumbs['display']);
126             $data['content']['html'] = "<a href=\"{$escapedUrl}\" target=\"_blank\"><img src=\"{$escapedDisplayThumb}\" alt=\"{$escapedName}\"></a>";
127             $mdEscapedName = str_replace(']', '', str_replace('[', '', $image->name));
128             $mdEscapedThumb = str_replace(']', '', str_replace('[', '', $image->thumbs['display']));
129             $data['content']['markdown'] = "![{$mdEscapedName}]({$mdEscapedThumb})";
130         }
131
132         return $data;
133     }
134 }