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\Tools\BookContents;
12 use BookStack\Entities\Tools\PageContent;
13 use BookStack\Entities\Tools\PageEditorData;
14 use BookStack\Entities\Tools\TrashCan;
15 use BookStack\Exceptions\MoveOperationException;
16 use BookStack\Exceptions\NotFoundException;
17 use BookStack\Exceptions\PermissionsException;
18 use BookStack\Facades\Activity;
19 use BookStack\References\ReferenceStore;
20 use BookStack\References\ReferenceUpdater;
22 use Illuminate\Pagination\LengthAwarePaginator;
26 public function __construct(
27 protected BaseRepo $baseRepo,
28 protected RevisionRepo $revisionRepo,
29 protected ReferenceStore $referenceStore,
30 protected ReferenceUpdater $referenceUpdater
37 * @throws NotFoundException
39 public function getById(int $id, array $relations = ['book']): Page
41 /** @var Page $page */
42 $page = Page::visible()->with($relations)->find($id);
45 throw new NotFoundException(trans('errors.page_not_found'));
52 * Get a page its book and own slug.
54 * @throws NotFoundException
56 public function getBySlug(string $bookSlug, string $pageSlug): Page
58 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
61 throw new NotFoundException(trans('errors.page_not_found'));
68 * Get a page by its old slug but checking the revisions table
69 * for the last revision that matched the given page and book slug.
71 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
73 $revision = $this->revisionRepo->getBySlugs($bookSlug, $pageSlug);
75 return $revision->page ?? null;
79 * Get pages that have been marked as a template.
81 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
83 $query = Page::visible()
84 ->where('template', '=', true)
85 ->orderBy('name', 'asc')
86 ->skip(($page - 1) * $count)
90 $query->where('name', 'like', '%' . $search . '%');
93 $paginator = $query->paginate($count, ['*'], 'page', $page);
94 $paginator->withPath('/templates');
100 * Get a parent item via slugs.
102 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
104 if ($chapterSlug !== null) {
105 return Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
108 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
112 * Get the draft copy of the given page for the current user.
114 public function getUserDraft(Page $page): ?PageRevision
116 return $this->revisionRepo->getLatestDraftForCurrentUser($page);
120 * Get a new draft page belonging to the given parent entity.
122 public function getNewDraftPage(Entity $parent)
124 $page = (new Page())->forceFill([
125 'name' => trans('entities.pages_initial_name'),
126 'created_by' => user()->id,
127 'owned_by' => user()->id,
128 'updated_by' => user()->id,
132 if ($parent instanceof Chapter) {
133 $page->chapter_id = $parent->id;
134 $page->book_id = $parent->book_id;
136 $page->book_id = $parent->id;
140 if ($page->chapter_id) {
141 $defaultTemplate = $page->chapter->defaultTemplate;
143 $defaultTemplate = $page->book->defaultTemplate;
146 if ($defaultTemplate && userCan('view', $defaultTemplate)) {
148 'html' => $defaultTemplate->html,
149 'markdown' => $defaultTemplate->markdown,
154 $page->refresh()->rebuildPermissions();
160 * Publish a draft page to make it a live, non-draft page.
162 public function publishDraft(Page $draft, array $input): Page
164 $draft->draft = false;
165 $draft->revision_count = 1;
166 $draft->priority = $this->getNewPriority($draft);
167 $this->updateTemplateStatusAndContentFromInput($draft, $input);
168 $this->baseRepo->update($draft, $input);
170 $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
173 Activity::add(ActivityType::PAGE_CREATE, $draft);
179 * Update a page in the system.
181 public function update(Page $page, array $input): Page
183 // Hold the old details to compare later
184 $oldHtml = $page->html;
185 $oldName = $page->name;
186 $oldMarkdown = $page->markdown;
188 $this->updateTemplateStatusAndContentFromInput($page, $input);
189 $this->baseRepo->update($page, $input);
191 // Update with new details
192 $page->revision_count++;
195 // Remove all update drafts for this user & page.
196 $this->revisionRepo->deleteDraftsForCurrentUser($page);
198 // Save a revision after updating
199 $summary = trim($input['summary'] ?? '');
200 $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
201 $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
202 $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
203 if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
204 $this->revisionRepo->storeNewForPage($page, $summary);
207 Activity::add(ActivityType::PAGE_UPDATE, $page);
212 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
214 if (isset($input['template']) && userCan('templates-manage')) {
215 $page->template = ($input['template'] === 'true');
218 $pageContent = new PageContent($page);
219 $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
220 $newEditor = $currentEditor;
222 $haveInput = isset($input['markdown']) || isset($input['html']);
223 $inputEmpty = empty($input['markdown']) && empty($input['html']);
225 if ($haveInput && $inputEmpty) {
226 $pageContent->setNewHTML('', user());
227 } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
228 $newEditor = 'markdown';
229 $pageContent->setNewMarkdown($input['markdown'], user());
230 } elseif (isset($input['html'])) {
231 $newEditor = 'wysiwyg';
232 $pageContent->setNewHTML($input['html'], user());
235 if ($newEditor !== $currentEditor && userCan('editor-change')) {
236 $page->editor = $newEditor;
241 * Save a page update draft.
243 public function updatePageDraft(Page $page, array $input)
245 // If the page itself is a draft simply update that
247 $this->updateTemplateStatusAndContentFromInput($page, $input);
254 // Otherwise, save the data to a revision
255 $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
256 $draft->fill($input);
258 if (!empty($input['markdown'])) {
259 $draft->markdown = $input['markdown'];
262 $draft->html = $input['html'];
263 $draft->markdown = '';
272 * Destroy a page from the system.
276 public function destroy(Page $page)
278 $trashCan = new TrashCan();
279 $trashCan->softDestroyPage($page);
280 Activity::add(ActivityType::PAGE_DELETE, $page);
281 $trashCan->autoClearOld();
285 * Restores a revision's content back into a page.
287 public function restoreRevision(Page $page, int $revisionId): Page
289 $oldUrl = $page->getUrl();
290 $page->revision_count++;
292 /** @var PageRevision $revision */
293 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
295 $page->fill($revision->toArray());
296 $content = new PageContent($page);
298 if (!empty($revision->markdown)) {
299 $content->setNewMarkdown($revision->markdown, user());
301 $content->setNewHTML($revision->html, user());
304 $page->updated_by = user()->id;
305 $page->refreshSlug();
307 $page->indexForSearch();
308 $this->referenceStore->updateForEntity($page);
310 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
311 $this->revisionRepo->storeNewForPage($page, $summary);
313 if ($oldUrl !== $page->getUrl()) {
314 $this->referenceUpdater->updateEntityReferences($page, $oldUrl);
317 Activity::add(ActivityType::PAGE_RESTORE, $page);
318 Activity::add(ActivityType::REVISION_RESTORE, $revision);
324 * Move the given page into a new parent book or chapter.
325 * The $parentIdentifier must be a string of the following format:
326 * 'book:<id>' (book:5).
328 * @throws MoveOperationException
329 * @throws PermissionsException
331 public function move(Page $page, string $parentIdentifier): Entity
333 $parent = $this->findParentByIdentifier($parentIdentifier);
334 if (is_null($parent)) {
335 throw new MoveOperationException('Book or chapter to move page into not found');
338 if (!userCan('page-create', $parent)) {
339 throw new PermissionsException('User does not have permission to create a page within the new parent');
342 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
343 $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
344 $page->changeBook($newBookId);
345 $page->rebuildPermissions();
347 Activity::add(ActivityType::PAGE_MOVE, $page);
353 * Find a page parent entity via an identifier string in the format:
357 * @throws MoveOperationException
359 public function findParentByIdentifier(string $identifier): ?Entity
361 $stringExploded = explode(':', $identifier);
362 $entityType = $stringExploded[0];
363 $entityId = intval($stringExploded[1]);
365 if ($entityType !== 'book' && $entityType !== 'chapter') {
366 throw new MoveOperationException('Pages can only be in books or chapters');
369 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
371 return $parentClass::visible()->where('id', '=', $entityId)->first();
375 * Get a new priority for a page.
377 protected function getNewPriority(Page $page): int
379 $parent = $page->getParent();
380 if ($parent instanceof Chapter) {
381 /** @var ?Page $lastPage */
382 $lastPage = $parent->pages('desc')->first();
384 return $lastPage ? $lastPage->priority + 1 : 0;
387 return (new BookContents($page->book))->getLastPriority() + 1;