3 namespace BookStack\Entities\Repos;
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;
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,
38 * Get a new draft page belonging to the given parent entity.
40 public function getNewDraftPage(Entity $parent): Page
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,
48 'editor' => PageEditorType::getSystemDefault()->value,
54 if ($parent instanceof Chapter) {
55 $page->chapter_id = $parent->id;
56 $page->book_id = $parent->book_id;
58 $page->book_id = $parent->id;
61 $defaultTemplate = $page->chapter?->defaultTemplate()->get() ?? $page->book?->defaultTemplate()->get();
62 if ($defaultTemplate) {
64 'html' => $defaultTemplate->html,
65 'markdown' => $defaultTemplate->markdown,
67 $page->text = (new PageContent($page))->toPlainText();
70 (new DatabaseTransaction(function () use ($page) {
72 $page->rebuildPermissions();
79 * Publish a draft page to make it a live, non-draft page.
81 public function publishDraft(Page $draft, array $input): Page
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);
89 $draft = $this->baseRepo->update($draft, $input);
90 $draft->rebuildPermissions();
92 $summary = trim($input['summary'] ?? '') ?: trans('entities.pages_initial_revision');
93 $this->revisionRepo->storeNewForPage($draft, $summary);
96 Activity::add(ActivityType::PAGE_CREATE, $draft);
97 $this->baseRepo->sortParent($draft);
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.
108 public function setContentFromInput(Page $page, array $input): void
110 $this->updateTemplateStatusAndContentFromInput($page, $input);
111 $this->baseRepo->update($page, []);
115 * Update a page in the system.
117 public function update(Page $page, array $input): Page
119 // Hold the old details to compare later
120 $oldName = $page->name;
121 $oldHtml = $page->html;
122 $oldMarkdown = $page->markdown;
124 $this->updateTemplateStatusAndContentFromInput($page, $input);
125 $page = $this->baseRepo->update($page, $input);
127 // Update with new details
128 $page->revision_count++;
131 // Remove all update drafts for this user and page.
132 $this->revisionRepo->deleteDraftsForCurrentUser($page);
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);
143 Activity::add(ActivityType::PAGE_UPDATE, $page);
144 $this->baseRepo->sortParent($page);
149 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input): void
151 if (isset($input['template']) && userCan(Permission::TemplatesManage)) {
152 $page->template = ($input['template'] === 'true');
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;
161 $haveInput = isset($input['markdown']) || isset($input['html']);
162 $inputEmpty = empty($input['markdown']) && empty($input['html']);
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());
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;
182 * Save a page update draft.
184 public function updatePageDraft(Page $page, array $input): Page|PageRevision
186 // If the page itself is a draft, simply update that
188 $this->updateTemplateStatusAndContentFromInput($page, $input);
189 $page->forceFill(array_intersect_key($input, array_flip(['name'])))->save();
195 // Otherwise, save the data to a revision
196 $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
197 $draft->fill($input);
199 if (!empty($input['markdown'])) {
200 $draft->markdown = $input['markdown'];
203 $draft->html = $input['html'];
204 $draft->markdown = '';
213 * Destroy a page from the system.
217 public function destroy(Page $page): void
219 $this->trashCan->softDestroyPage($page);
220 Activity::add(ActivityType::PAGE_DELETE, $page);
221 $this->trashCan->autoClearOld();
225 * Restores a revision's content back into a page.
227 public function restoreRevision(Page $page, int $revisionId): Page
229 $oldUrl = $page->getUrl();
230 $page->revision_count++;
232 /** @var PageRevision $revision */
233 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
235 $page->fill($revision->toArray());
236 $content = new PageContent($page);
238 if (!empty($revision->markdown)) {
239 $content->setNewMarkdown($revision->markdown, user());
241 $content->setNewHTML($revision->html, user());
244 $page->updated_by = user()->id;
245 $page->refreshSlug();
247 $page->indexForSearch();
248 $this->referenceStore->updateForEntity($page);
250 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
251 $this->revisionRepo->storeNewForPage($page, $summary);
253 if ($oldUrl !== $page->getUrl()) {
254 $this->referenceUpdater->updateEntityReferences($page, $oldUrl);
257 Activity::add(ActivityType::PAGE_RESTORE, $page);
258 Activity::add(ActivityType::REVISION_RESTORE, $revision);
260 $this->baseRepo->sortParent($page);
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).
270 * @throws MoveOperationException
271 * @throws PermissionsException
273 public function move(Page $page, string $parentIdentifier): Entity
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');
280 if (!userCan(Permission::PageCreate, $parent)) {
281 throw new PermissionsException('User does not have permission to create a page within the new parent');
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();
290 Activity::add(ActivityType::PAGE_MOVE, $page);
292 $this->baseRepo->sortParent($page);
299 * Get a new priority for a page.
301 protected function getNewPriority(Page $page): int
303 $parent = $page->getParent();
304 if ($parent instanceof Chapter) {
305 /** @var ?Page $lastPage */
306 $lastPage = $parent->pages('desc')->first();
308 return $lastPage ? $lastPage->priority + 1 : 0;
311 return (new BookContents($page->book))->getLastPriority() + 1;