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