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