]> BookStack Code Mirror - bookstack/blob - app/Entities/Controllers/ChapterApiController.php
Merge pull request #5846 from BookStackApp/page_image_nullification
[bookstack] / app / Entities / Controllers / ChapterApiController.php
1 <?php
2
3 namespace BookStack\Entities\Controllers;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Queries\ChapterQueries;
8 use BookStack\Entities\Queries\EntityQueries;
9 use BookStack\Entities\Repos\ChapterRepo;
10 use BookStack\Exceptions\PermissionsException;
11 use BookStack\Http\ApiController;
12 use BookStack\Permissions\Permission;
13 use Exception;
14 use Illuminate\Http\Request;
15
16 class ChapterApiController extends ApiController
17 {
18     protected array $rules = [
19         'create' => [
20             'book_id'             => ['required', 'integer'],
21             'name'                => ['required', 'string', 'max:255'],
22             'description'         => ['string', 'max:1900'],
23             'description_html'    => ['string', 'max:2000'],
24             'tags'                => ['array'],
25             'priority'            => ['integer'],
26             'default_template_id' => ['nullable', 'integer'],
27         ],
28         'update' => [
29             'book_id'             => ['integer'],
30             'name'                => ['string', 'min:1', 'max:255'],
31             'description'         => ['string', 'max:1900'],
32             'description_html'    => ['string', 'max:2000'],
33             'tags'                => ['array'],
34             'priority'            => ['integer'],
35             'default_template_id' => ['nullable', 'integer'],
36         ],
37     ];
38
39     public function __construct(
40         protected ChapterRepo $chapterRepo,
41         protected ChapterQueries $queries,
42         protected EntityQueries $entityQueries,
43     ) {
44     }
45
46     /**
47      * Get a listing of chapters visible to the user.
48      */
49     public function list()
50     {
51         $chapters = $this->queries->visibleForList()
52             ->addSelect(['created_by', 'updated_by']);
53
54         return $this->apiListingResponse($chapters, [
55             'id', 'book_id', 'name', 'slug', 'description', 'priority',
56             'created_at', 'updated_at', 'created_by', 'updated_by', 'owned_by',
57         ]);
58     }
59
60     /**
61      * Create a new chapter in the system.
62      */
63     public function create(Request $request)
64     {
65         $requestData = $this->validate($request, $this->rules['create']);
66
67         $bookId = $request->get('book_id');
68         $book = $this->entityQueries->books->findVisibleByIdOrFail(intval($bookId));
69         $this->checkOwnablePermission(Permission::ChapterCreate, $book);
70
71         $chapter = $this->chapterRepo->create($requestData, $book);
72
73         return response()->json($this->forJsonDisplay($chapter));
74     }
75
76     /**
77      * View the details of a single chapter.
78      */
79     public function read(string $id)
80     {
81         $chapter = $this->queries->findVisibleByIdOrFail(intval($id));
82         $chapter = $this->forJsonDisplay($chapter);
83
84         $chapter->load(['createdBy', 'updatedBy', 'ownedBy']);
85
86         // Note: More fields than usual here, for backwards compatibility,
87         // due to previously accidentally including more fields that desired.
88         $pages = $this->entityQueries->pages->visibleForChapterList($chapter->id)
89             ->addSelect(['created_by', 'updated_by', 'revision_count', 'editor'])
90             ->get();
91         $chapter->setRelation('pages', $pages);
92
93         return response()->json($chapter);
94     }
95
96     /**
97      * Update the details of a single chapter.
98      * Providing a 'book_id' property will essentially move the chapter
99      * into that parent element if you have permissions to do so.
100      */
101     public function update(Request $request, string $id)
102     {
103         $requestData = $this->validate($request, $this->rules()['update']);
104         $chapter = $this->queries->findVisibleByIdOrFail(intval($id));
105         $this->checkOwnablePermission(Permission::ChapterUpdate, $chapter);
106
107         if ($request->has('book_id') && $chapter->book_id !== (intval($requestData['book_id']) ?: null)) {
108             $this->checkOwnablePermission(Permission::ChapterDelete, $chapter);
109
110             try {
111                 $this->chapterRepo->move($chapter, "book:{$requestData['book_id']}");
112             } catch (Exception $exception) {
113                 if ($exception instanceof PermissionsException) {
114                     $this->showPermissionError();
115                 }
116
117                 return $this->jsonError(trans('errors.selected_book_not_found'));
118             }
119         }
120
121         $updatedChapter = $this->chapterRepo->update($chapter, $requestData);
122
123         return response()->json($this->forJsonDisplay($updatedChapter));
124     }
125
126     /**
127      * Delete a chapter.
128      * This will typically send the chapter to the recycle bin.
129      */
130     public function delete(string $id)
131     {
132         $chapter = $this->queries->findVisibleByIdOrFail(intval($id));
133         $this->checkOwnablePermission(Permission::ChapterDelete, $chapter);
134
135         $this->chapterRepo->destroy($chapter);
136
137         return response('', 204);
138     }
139
140     protected function forJsonDisplay(Chapter $chapter): Chapter
141     {
142         $chapter = clone $chapter;
143         $chapter->unsetRelations()->refresh();
144
145         $chapter->load(['tags']);
146         $chapter->makeVisible('description_html');
147         $chapter->setAttribute('description_html', $chapter->descriptionInfo()->getHtml());
148
149         /** @var Book $book */
150         $book = $chapter->book()->first();
151         $chapter->setAttribute('book_slug', $book->slug);
152
153         return $chapter;
154     }
155 }