]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/PageRepo.php
Meta: Added lexical licensing info and added TS/JS CI testing
[bookstack] / app / Entities / Repos / PageRepo.php
1 <?php
2
3 namespace BookStack\Entities\Repos;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Models\PageRevision;
11 use BookStack\Entities\Queries\EntityQueries;
12 use BookStack\Entities\Tools\BookContents;
13 use BookStack\Entities\Tools\PageContent;
14 use BookStack\Entities\Tools\PageEditorData;
15 use BookStack\Entities\Tools\PageEditorType;
16 use BookStack\Entities\Tools\TrashCan;
17 use BookStack\Exceptions\MoveOperationException;
18 use BookStack\Exceptions\PermissionsException;
19 use BookStack\Facades\Activity;
20 use BookStack\References\ReferenceStore;
21 use BookStack\References\ReferenceUpdater;
22 use Exception;
23
24 class PageRepo
25 {
26     public function __construct(
27         protected BaseRepo $baseRepo,
28         protected RevisionRepo $revisionRepo,
29         protected EntityQueries $entityQueries,
30         protected ReferenceStore $referenceStore,
31         protected ReferenceUpdater $referenceUpdater,
32         protected TrashCan $trashCan,
33     ) {
34     }
35
36     /**
37      * Get a new draft page belonging to the given parent entity.
38      */
39     public function getNewDraftPage(Entity $parent)
40     {
41         $page = (new Page())->forceFill([
42             'name'       => trans('entities.pages_initial_name'),
43             'created_by' => user()->id,
44             'owned_by'   => user()->id,
45             'updated_by' => user()->id,
46             'draft'      => true,
47         ]);
48
49         if ($parent instanceof Chapter) {
50             $page->chapter_id = $parent->id;
51             $page->book_id = $parent->book_id;
52         } else {
53             $page->book_id = $parent->id;
54         }
55
56         $defaultTemplate = $page->chapter->defaultTemplate ?? $page->book->defaultTemplate;
57         if ($defaultTemplate && userCan('view', $defaultTemplate)) {
58             $page->forceFill([
59                 'html'  => $defaultTemplate->html,
60                 'markdown' => $defaultTemplate->markdown,
61             ]);
62         }
63
64         $page->save();
65         $page->refresh()->rebuildPermissions();
66
67         return $page;
68     }
69
70     /**
71      * Publish a draft page to make it a live, non-draft page.
72      */
73     public function publishDraft(Page $draft, array $input): Page
74     {
75         $draft->draft = false;
76         $draft->revision_count = 1;
77         $draft->priority = $this->getNewPriority($draft);
78         $this->updateTemplateStatusAndContentFromInput($draft, $input);
79         $this->baseRepo->update($draft, $input);
80
81         $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
82         $draft->refresh();
83
84         Activity::add(ActivityType::PAGE_CREATE, $draft);
85
86         return $draft;
87     }
88
89     /**
90      * Update a page in the system.
91      */
92     public function update(Page $page, array $input): Page
93     {
94         // Hold the old details to compare later
95         $oldHtml = $page->html;
96         $oldName = $page->name;
97         $oldMarkdown = $page->markdown;
98
99         $this->updateTemplateStatusAndContentFromInput($page, $input);
100         $this->baseRepo->update($page, $input);
101
102         // Update with new details
103         $page->revision_count++;
104         $page->save();
105
106         // Remove all update drafts for this user & page.
107         $this->revisionRepo->deleteDraftsForCurrentUser($page);
108
109         // Save a revision after updating
110         $summary = trim($input['summary'] ?? '');
111         $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
112         $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
113         $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
114         if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
115             $this->revisionRepo->storeNewForPage($page, $summary);
116         }
117
118         Activity::add(ActivityType::PAGE_UPDATE, $page);
119
120         return $page;
121     }
122
123     protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
124     {
125         if (isset($input['template']) && userCan('templates-manage')) {
126             $page->template = ($input['template'] === 'true');
127         }
128
129         $pageContent = new PageContent($page);
130         $defaultEditor = PageEditorType::getSystemDefault();
131         $currentEditor = PageEditorType::forPage($page) ?: $defaultEditor;
132         $inputEditor = PageEditorType::fromRequestValue($input['editor'] ?? '') ?? $currentEditor;
133         $newEditor = $currentEditor;
134
135         $haveInput = isset($input['markdown']) || isset($input['html']);
136         $inputEmpty = empty($input['markdown']) && empty($input['html']);
137
138         if ($haveInput && $inputEmpty) {
139             $pageContent->setNewHTML('', user());
140         } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
141             $newEditor = PageEditorType::Markdown;
142             $pageContent->setNewMarkdown($input['markdown'], user());
143         } elseif (isset($input['html'])) {
144             $newEditor = ($inputEditor->isHtmlBased() ? $inputEditor : null) ?? ($defaultEditor->isHtmlBased() ? $defaultEditor : null) ?? PageEditorType::WysiwygTinymce;
145             $pageContent->setNewHTML($input['html'], user());
146         }
147
148         if ($newEditor !== $currentEditor && userCan('editor-change')) {
149             $page->editor = $newEditor->value;
150         }
151     }
152
153     /**
154      * Save a page update draft.
155      */
156     public function updatePageDraft(Page $page, array $input)
157     {
158         // If the page itself is a draft simply update that
159         if ($page->draft) {
160             $this->updateTemplateStatusAndContentFromInput($page, $input);
161             $page->fill($input);
162             $page->save();
163
164             return $page;
165         }
166
167         // Otherwise, save the data to a revision
168         $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
169         $draft->fill($input);
170
171         if (!empty($input['markdown'])) {
172             $draft->markdown = $input['markdown'];
173             $draft->html = '';
174         } else {
175             $draft->html = $input['html'];
176             $draft->markdown = '';
177         }
178
179         $draft->save();
180
181         return $draft;
182     }
183
184     /**
185      * Destroy a page from the system.
186      *
187      * @throws Exception
188      */
189     public function destroy(Page $page)
190     {
191         $this->trashCan->softDestroyPage($page);
192         Activity::add(ActivityType::PAGE_DELETE, $page);
193         $this->trashCan->autoClearOld();
194     }
195
196     /**
197      * Restores a revision's content back into a page.
198      */
199     public function restoreRevision(Page $page, int $revisionId): Page
200     {
201         $oldUrl = $page->getUrl();
202         $page->revision_count++;
203
204         /** @var PageRevision $revision */
205         $revision = $page->revisions()->where('id', '=', $revisionId)->first();
206
207         $page->fill($revision->toArray());
208         $content = new PageContent($page);
209
210         if (!empty($revision->markdown)) {
211             $content->setNewMarkdown($revision->markdown, user());
212         } else {
213             $content->setNewHTML($revision->html, user());
214         }
215
216         $page->updated_by = user()->id;
217         $page->refreshSlug();
218         $page->save();
219         $page->indexForSearch();
220         $this->referenceStore->updateForEntity($page);
221
222         $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
223         $this->revisionRepo->storeNewForPage($page, $summary);
224
225         if ($oldUrl !== $page->getUrl()) {
226             $this->referenceUpdater->updateEntityReferences($page, $oldUrl);
227         }
228
229         Activity::add(ActivityType::PAGE_RESTORE, $page);
230         Activity::add(ActivityType::REVISION_RESTORE, $revision);
231
232         return $page;
233     }
234
235     /**
236      * Move the given page into a new parent book or chapter.
237      * The $parentIdentifier must be a string of the following format:
238      * 'book:<id>' (book:5).
239      *
240      * @throws MoveOperationException
241      * @throws PermissionsException
242      */
243     public function move(Page $page, string $parentIdentifier): Entity
244     {
245         $parent = $this->entityQueries->findVisibleByStringIdentifier($parentIdentifier);
246         if (!$parent instanceof Chapter && !$parent instanceof Book) {
247             throw new MoveOperationException('Book or chapter to move page into not found');
248         }
249
250         if (!userCan('page-create', $parent)) {
251             throw new PermissionsException('User does not have permission to create a page within the new parent');
252         }
253
254         $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
255         $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
256         $page->changeBook($newBookId);
257         $page->rebuildPermissions();
258
259         Activity::add(ActivityType::PAGE_MOVE, $page);
260
261         return $parent;
262     }
263
264     /**
265      * Get a new priority for a page.
266      */
267     protected function getNewPriority(Page $page): int
268     {
269         $parent = $page->getParent();
270         if ($parent instanceof Chapter) {
271             /** @var ?Page $lastPage */
272             $lastPage = $parent->pages('desc')->first();
273
274             return $lastPage ? $lastPage->priority + 1 : 0;
275         }
276
277         return (new BookContents($page->book))->getLastPriority() + 1;
278     }
279 }