3 namespace BookStack\Entities\Repos;
5 use BookStack\Actions\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 protected BaseRepo $baseRepo;
27 protected RevisionRepo $revisionRepo;
28 protected ReferenceStore $referenceStore;
29 protected ReferenceUpdater $referenceUpdater;
32 * PageRepo constructor.
34 public function __construct(
36 RevisionRepo $revisionRepo,
37 ReferenceStore $referenceStore,
38 ReferenceUpdater $referenceUpdater
40 $this->baseRepo = $baseRepo;
41 $this->revisionRepo = $revisionRepo;
42 $this->referenceStore = $referenceStore;
43 $this->referenceUpdater = $referenceUpdater;
49 * @throws NotFoundException
51 public function getById(int $id, array $relations = ['book']): Page
53 /** @var Page $page */
54 $page = Page::visible()->with($relations)->find($id);
57 throw new NotFoundException(trans('errors.page_not_found'));
64 * Get a page its book and own slug.
66 * @throws NotFoundException
68 public function getBySlug(string $bookSlug, string $pageSlug): Page
70 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
73 throw new NotFoundException(trans('errors.page_not_found'));
80 * Get a page by its old slug but checking the revisions table
81 * for the last revision that matched the given page and book slug.
83 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
85 $revision = $this->revisionRepo->getBySlugs($bookSlug, $pageSlug);
87 return $revision->page ?? null;
91 * Get pages that have been marked as a template.
93 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
95 $query = Page::visible()
96 ->where('template', '=', true)
97 ->orderBy('name', 'asc')
98 ->skip(($page - 1) * $count)
102 $query->where('name', 'like', '%' . $search . '%');
105 $paginator = $query->paginate($count, ['*'], 'page', $page);
106 $paginator->withPath('/templates');
112 * Get a parent item via slugs.
114 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
116 if ($chapterSlug !== null) {
117 return Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
120 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
124 * Get the draft copy of the given page for the current user.
126 public function getUserDraft(Page $page): ?PageRevision
128 return $this->revisionRepo->getLatestDraftForCurrentUser($page);
132 * Get a new draft page belonging to the given parent entity.
134 public function getNewDraftPage(Entity $parent)
136 $page = (new Page())->forceFill([
137 'name' => trans('entities.pages_initial_name'),
138 'created_by' => user()->id,
139 'owned_by' => user()->id,
140 'updated_by' => user()->id,
144 if ($parent instanceof Chapter) {
145 $page->chapter_id = $parent->id;
146 $page->book_id = $parent->book_id;
148 $page->book_id = $parent->id;
151 if ($page->book->defaultTemplate) {
153 'html' => $page->book->defaultTemplate->html,
158 $page->refresh()->rebuildPermissions();
164 * Publish a draft page to make it a live, non-draft page.
166 public function publishDraft(Page $draft, array $input): Page
168 $this->updateTemplateStatusAndContentFromInput($draft, $input);
169 $this->baseRepo->update($draft, $input);
171 $draft->draft = false;
172 $draft->revision_count = 1;
173 $draft->priority = $this->getNewPriority($draft);
176 $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
177 $this->referenceStore->updateForPage($draft);
180 Activity::add(ActivityType::PAGE_CREATE, $draft);
186 * Update a page in the system.
188 public function update(Page $page, array $input): Page
190 // Hold the old details to compare later
191 $oldHtml = $page->html;
192 $oldName = $page->name;
193 $oldMarkdown = $page->markdown;
195 $this->updateTemplateStatusAndContentFromInput($page, $input);
196 $this->baseRepo->update($page, $input);
197 $this->referenceStore->updateForPage($page);
199 // Update with new details
200 $page->revision_count++;
203 // Remove all update drafts for this user & page.
204 $this->revisionRepo->deleteDraftsForCurrentUser($page);
206 // Save a revision after updating
207 $summary = trim($input['summary'] ?? '');
208 $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
209 $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
210 $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
211 if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
212 $this->revisionRepo->storeNewForPage($page, $summary);
215 Activity::add(ActivityType::PAGE_UPDATE, $page);
220 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
222 if (isset($input['template']) && userCan('templates-manage')) {
223 $page->template = ($input['template'] === 'true');
226 $pageContent = new PageContent($page);
227 $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
228 $newEditor = $currentEditor;
230 $haveInput = isset($input['markdown']) || isset($input['html']);
231 $inputEmpty = empty($input['markdown']) && empty($input['html']);
233 if ($haveInput && $inputEmpty) {
234 $pageContent->setNewHTML('');
235 } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
236 $newEditor = 'markdown';
237 $pageContent->setNewMarkdown($input['markdown']);
238 } elseif (isset($input['html'])) {
239 $newEditor = 'wysiwyg';
240 $pageContent->setNewHTML($input['html']);
243 if ($newEditor !== $currentEditor && userCan('editor-change')) {
244 $page->editor = $newEditor;
249 * Save a page update draft.
251 public function updatePageDraft(Page $page, array $input)
253 // If the page itself is a draft simply update that
255 $this->updateTemplateStatusAndContentFromInput($page, $input);
262 // Otherwise, save the data to a revision
263 $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
264 $draft->fill($input);
266 if (!empty($input['markdown'])) {
267 $draft->markdown = $input['markdown'];
270 $draft->html = $input['html'];
271 $draft->markdown = '';
280 * Destroy a page from the system.
284 public function destroy(Page $page)
286 $trashCan = new TrashCan();
287 $trashCan->softDestroyPage($page);
288 Activity::add(ActivityType::PAGE_DELETE, $page);
289 $trashCan->autoClearOld();
293 * Restores a revision's content back into a page.
295 public function restoreRevision(Page $page, int $revisionId): Page
297 $oldUrl = $page->getUrl();
298 $page->revision_count++;
300 /** @var PageRevision $revision */
301 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
303 $page->fill($revision->toArray());
304 $content = new PageContent($page);
306 if (!empty($revision->markdown)) {
307 $content->setNewMarkdown($revision->markdown);
309 $content->setNewHTML($revision->html);
312 $page->updated_by = user()->id;
313 $page->refreshSlug();
315 $page->indexForSearch();
316 $this->referenceStore->updateForPage($page);
318 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
319 $this->revisionRepo->storeNewForPage($page, $summary);
321 if ($oldUrl !== $page->getUrl()) {
322 $this->referenceUpdater->updateEntityPageReferences($page, $oldUrl);
325 Activity::add(ActivityType::PAGE_RESTORE, $page);
326 Activity::add(ActivityType::REVISION_RESTORE, $revision);
332 * Move the given page into a new parent book or chapter.
333 * The $parentIdentifier must be a string of the following format:
334 * 'book:<id>' (book:5).
336 * @throws MoveOperationException
337 * @throws PermissionsException
339 public function move(Page $page, string $parentIdentifier): Entity
341 $parent = $this->findParentByIdentifier($parentIdentifier);
342 if (is_null($parent)) {
343 throw new MoveOperationException('Book or chapter to move page into not found');
346 if (!userCan('page-create', $parent)) {
347 throw new PermissionsException('User does not have permission to create a page within the new parent');
350 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
351 $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
352 $page->changeBook($newBookId);
353 $page->rebuildPermissions();
355 Activity::add(ActivityType::PAGE_MOVE, $page);
361 * Find a page parent entity via an identifier string in the format:
365 * @throws MoveOperationException
367 public function findParentByIdentifier(string $identifier): ?Entity
369 $stringExploded = explode(':', $identifier);
370 $entityType = $stringExploded[0];
371 $entityId = intval($stringExploded[1]);
373 if ($entityType !== 'book' && $entityType !== 'chapter') {
374 throw new MoveOperationException('Pages can only be in books or chapters');
377 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
379 return $parentClass::visible()->where('id', '=', $entityId)->first();
383 * Get a new priority for a page.
385 protected function getNewPriority(Page $page): int
387 $parent = $page->getParent();
388 if ($parent instanceof Chapter) {
389 /** @var ?Page $lastPage */
390 $lastPage = $parent->pages('desc')->first();
392 return $lastPage ? $lastPage->priority + 1 : 0;
395 return (new BookContents($page->book))->getLastPriority() + 1;