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