]> BookStack Code Mirror - bookstack/blob - app/Entities/Controllers/BookApiController.php
Merge pull request #5846 from BookStackApp/page_image_nullification
[bookstack] / app / Entities / Controllers / BookApiController.php
1 <?php
2
3 namespace BookStack\Entities\Controllers;
4
5 use BookStack\Api\ApiEntityListFormatter;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Queries\BookQueries;
10 use BookStack\Entities\Queries\PageQueries;
11 use BookStack\Entities\Repos\BookRepo;
12 use BookStack\Entities\Tools\BookContents;
13 use BookStack\Http\ApiController;
14 use BookStack\Permissions\Permission;
15 use Illuminate\Http\Request;
16 use Illuminate\Validation\ValidationException;
17
18 class BookApiController extends ApiController
19 {
20     public function __construct(
21         protected BookRepo $bookRepo,
22         protected BookQueries $queries,
23         protected PageQueries $pageQueries,
24     ) {
25     }
26
27     /**
28      * Get a listing of books visible to the user.
29      */
30     public function list()
31     {
32         $books = $this->queries
33             ->visibleForList()
34             ->with(['cover:id,name,url'])
35             ->addSelect(['created_by', 'updated_by']);
36
37         return $this->apiListingResponse($books, [
38             'id', 'name', 'slug', 'description', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by',
39         ]);
40     }
41
42     /**
43      * Create a new book in the system.
44      * The cover image of a book can be set by sending a file via an 'image' property within a 'multipart/form-data' request.
45      * If the 'image' property is null then the book cover image will be removed.
46      *
47      * @throws ValidationException
48      */
49     public function create(Request $request)
50     {
51         $this->checkPermission(Permission::BookCreateAll);
52         $requestData = $this->validate($request, $this->rules()['create']);
53
54         $book = $this->bookRepo->create($requestData);
55
56         return response()->json($this->forJsonDisplay($book));
57     }
58
59     /**
60      * View the details of a single book.
61      * The response data will contain 'content' property listing the chapter and pages directly within, in
62      * the same structure as you'd see within the BookStack interface when viewing a book. Top-level
63      * contents will have a 'type' property to distinguish between pages & chapters.
64      */
65     public function read(string $id)
66     {
67         $book = $this->queries->findVisibleByIdOrFail(intval($id));
68         $book = $this->forJsonDisplay($book);
69         $book->load(['createdBy', 'updatedBy', 'ownedBy']);
70
71         $contents = (new BookContents($book))->getTree(true, false)->all();
72         $contentsApiData = (new ApiEntityListFormatter($contents))
73             ->withType()
74             ->withField('pages', function (Entity $entity) {
75                 if ($entity instanceof Chapter) {
76                     $pages = $this->pageQueries->visibleForChapterList($entity->id)->get()->all();
77                     return (new ApiEntityListFormatter($pages))->format();
78                 }
79                 return null;
80             })->format();
81         $book->setAttribute('contents', $contentsApiData);
82
83         return response()->json($book);
84     }
85
86     /**
87      * Update the details of a single book.
88      * The cover image of a book can be set by sending a file via an 'image' property within a 'multipart/form-data' request.
89      * If the 'image' property is null then the book cover image will be removed.
90      *
91      * @throws ValidationException
92      */
93     public function update(Request $request, string $id)
94     {
95         $book = $this->queries->findVisibleByIdOrFail(intval($id));
96         $this->checkOwnablePermission(Permission::BookUpdate, $book);
97
98         $requestData = $this->validate($request, $this->rules()['update']);
99         $book = $this->bookRepo->update($book, $requestData);
100
101         return response()->json($this->forJsonDisplay($book));
102     }
103
104     /**
105      * Delete a single book.
106      * This will typically send the book to the recycle bin.
107      *
108      * @throws \Exception
109      */
110     public function delete(string $id)
111     {
112         $book = $this->queries->findVisibleByIdOrFail(intval($id));
113         $this->checkOwnablePermission(Permission::BookDelete, $book);
114
115         $this->bookRepo->destroy($book);
116
117         return response('', 204);
118     }
119
120     protected function forJsonDisplay(Book $book): Book
121     {
122         $book = clone $book;
123         $book->unsetRelations()->refresh();
124
125         $book->load(['tags']);
126         $book->makeVisible(['cover', 'description_html'])
127             ->setAttribute('description_html', $book->descriptionInfo()->getHtml())
128             ->setAttribute('cover', $book->coverInfo()->getImage());
129
130         return $book;
131     }
132
133     protected function rules(): array
134     {
135         return [
136             'create' => [
137                 'name'                => ['required', 'string', 'max:255'],
138                 'description'         => ['string', 'max:1900'],
139                 'description_html'    => ['string', 'max:2000'],
140                 'tags'                => ['array'],
141                 'image'               => array_merge(['nullable'], $this->getImageValidationRules()),
142                 'default_template_id' => ['nullable', 'integer'],
143             ],
144             'update' => [
145                 'name'                => ['string', 'min:1', 'max:255'],
146                 'description'         => ['string', 'max:1900'],
147                 'description_html'    => ['string', 'max:2000'],
148                 'tags'                => ['array'],
149                 'image'               => array_merge(['nullable'], $this->getImageValidationRules()),
150                 'default_template_id' => ['nullable', 'integer'],
151             ],
152         ];
153     }
154 }