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