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 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;
152 $page->refresh()->rebuildPermissions();
158 * Publish a draft page to make it a live, non-draft page.
160 public function publishDraft(Page $draft, array $input): Page
162 $this->updateTemplateStatusAndContentFromInput($draft, $input);
163 $this->baseRepo->update($draft, $input);
165 $draft->draft = false;
166 $draft->revision_count = 1;
167 $draft->priority = $this->getNewPriority($draft);
170 $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
171 $this->referenceStore->updateForPage($draft);
174 Activity::add(ActivityType::PAGE_CREATE, $draft);
180 * Update a page in the system.
182 public function update(Page $page, array $input): Page
184 // Hold the old details to compare later
185 $oldHtml = $page->html;
186 $oldName = $page->name;
187 $oldMarkdown = $page->markdown;
189 $this->updateTemplateStatusAndContentFromInput($page, $input);
190 $this->baseRepo->update($page, $input);
191 $this->referenceStore->updateForPage($page);
193 // Update with new details
194 $page->revision_count++;
197 // Remove all update drafts for this user & page.
198 $this->revisionRepo->deleteDraftsForCurrentUser($page);
200 // Save a revision after updating
201 $summary = trim($input['summary'] ?? '');
202 $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
203 $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
204 $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
205 if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
206 $this->revisionRepo->storeNewForPage($page, $summary);
209 Activity::add(ActivityType::PAGE_UPDATE, $page);
214 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
216 if (isset($input['template']) && userCan('templates-manage')) {
217 $page->template = ($input['template'] === 'true');
220 $pageContent = new PageContent($page);
221 $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
222 $newEditor = $currentEditor;
224 $haveInput = isset($input['markdown']) || isset($input['html']);
225 $inputEmpty = empty($input['markdown']) && empty($input['html']);
227 if ($haveInput && $inputEmpty) {
228 $pageContent->setNewHTML('');
229 } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
230 $newEditor = 'markdown';
231 $pageContent->setNewMarkdown($input['markdown']);
232 } elseif (isset($input['html'])) {
233 $newEditor = 'wysiwyg';
234 $pageContent->setNewHTML($input['html']);
237 if ($newEditor !== $currentEditor && userCan('editor-change')) {
238 $page->editor = $newEditor;
243 * Save a page update draft.
245 public function updatePageDraft(Page $page, array $input)
247 // If the page itself is a draft simply update that
249 $this->updateTemplateStatusAndContentFromInput($page, $input);
256 // Otherwise, save the data to a revision
257 $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
258 $draft->fill($input);
260 if (!empty($input['markdown'])) {
261 $draft->markdown = $input['markdown'];
264 $draft->html = $input['html'];
265 $draft->markdown = '';
274 * Destroy a page from the system.
278 public function destroy(Page $page)
280 $trashCan = new TrashCan();
281 $trashCan->softDestroyPage($page);
282 Activity::add(ActivityType::PAGE_DELETE, $page);
283 $trashCan->autoClearOld();
287 * Restores a revision's content back into a page.
289 public function restoreRevision(Page $page, int $revisionId): Page
291 $oldUrl = $page->getUrl();
292 $page->revision_count++;
294 /** @var PageRevision $revision */
295 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
297 $page->fill($revision->toArray());
298 $content = new PageContent($page);
300 if (!empty($revision->markdown)) {
301 $content->setNewMarkdown($revision->markdown);
303 $content->setNewHTML($revision->html);
306 $page->updated_by = user()->id;
307 $page->refreshSlug();
309 $page->indexForSearch();
310 $this->referenceStore->updateForPage($page);
312 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
313 $this->revisionRepo->storeNewForPage($page, $summary);
315 if ($oldUrl !== $page->getUrl()) {
316 $this->referenceUpdater->updateEntityPageReferences($page, $oldUrl);
319 Activity::add(ActivityType::PAGE_RESTORE, $page);
320 Activity::add(ActivityType::REVISION_RESTORE, $revision);
326 * Move the given page into a new parent book or chapter.
327 * The $parentIdentifier must be a string of the following format:
328 * 'book:<id>' (book:5).
330 * @throws MoveOperationException
331 * @throws PermissionsException
333 public function move(Page $page, string $parentIdentifier): Entity
335 $parent = $this->findParentByIdentifier($parentIdentifier);
336 if (is_null($parent)) {
337 throw new MoveOperationException('Book or chapter to move page into not found');
340 if (!userCan('page-create', $parent)) {
341 throw new PermissionsException('User does not have permission to create a page within the new parent');
344 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
345 $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
346 $page->changeBook($newBookId);
347 $page->rebuildPermissions();
349 Activity::add(ActivityType::PAGE_MOVE, $page);
355 * Find a page parent entity via an identifier string in the format:
359 * @throws MoveOperationException
361 public function findParentByIdentifier(string $identifier): ?Entity
363 $stringExploded = explode(':', $identifier);
364 $entityType = $stringExploded[0];
365 $entityId = intval($stringExploded[1]);
367 if ($entityType !== 'book' && $entityType !== 'chapter') {
368 throw new MoveOperationException('Pages can only be in books or chapters');
371 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
373 return $parentClass::visible()->where('id', '=', $entityId)->first();
377 * Get a new priority for a page.
379 protected function getNewPriority(Page $page): int
381 $parent = $page->getParent();
382 if ($parent instanceof Chapter) {
383 /** @var ?Page $lastPage */
384 $lastPage = $parent->pages('desc')->first();
386 return $lastPage ? $lastPage->priority + 1 : 0;
389 return (new BookContents($page->book))->getLastPriority() + 1;