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