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;
21 use Illuminate\Pagination\LengthAwarePaginator;
25 protected BaseRepo $baseRepo;
26 protected RevisionRepo $revisionRepo;
27 protected ReferenceStore $references;
30 * PageRepo constructor.
32 public function __construct(BaseRepo $baseRepo, RevisionRepo $revisionRepo, ReferenceStore $references)
34 $this->baseRepo = $baseRepo;
35 $this->revisionRepo = $revisionRepo;
36 $this->references = $references;
42 * @throws NotFoundException
44 public function getById(int $id, array $relations = ['book']): Page
46 /** @var Page $page */
47 $page = Page::visible()->with($relations)->find($id);
50 throw new NotFoundException(trans('errors.page_not_found'));
57 * Get a page its book and own slug.
59 * @throws NotFoundException
61 public function getBySlug(string $bookSlug, string $pageSlug): Page
63 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
66 throw new NotFoundException(trans('errors.page_not_found'));
73 * Get a page by its old slug but checking the revisions table
74 * for the last revision that matched the given page and book slug.
76 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
78 $revision = $this->revisionRepo->getBySlugs($bookSlug, $pageSlug);
80 return $revision->page ?? null;
84 * Get pages that have been marked as a template.
86 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
88 $query = Page::visible()
89 ->where('template', '=', true)
90 ->orderBy('name', 'asc')
91 ->skip(($page - 1) * $count)
95 $query->where('name', 'like', '%' . $search . '%');
98 $paginator = $query->paginate($count, ['*'], 'page', $page);
99 $paginator->withPath('/templates');
105 * Get a parent item via slugs.
107 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
109 if ($chapterSlug !== null) {
110 return Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
113 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
117 * Get the draft copy of the given page for the current user.
119 public function getUserDraft(Page $page): ?PageRevision
121 return $this->revisionRepo->getLatestDraftForCurrentUser($page);
125 * Get a new draft page belonging to the given parent entity.
127 public function getNewDraftPage(Entity $parent)
129 $page = (new Page())->forceFill([
130 'name' => trans('entities.pages_initial_name'),
131 'created_by' => user()->id,
132 'owned_by' => user()->id,
133 'updated_by' => user()->id,
137 if ($parent instanceof Chapter) {
138 $page->chapter_id = $parent->id;
139 $page->book_id = $parent->book_id;
141 $page->book_id = $parent->id;
145 $page->refresh()->rebuildPermissions();
151 * Publish a draft page to make it a live, non-draft page.
153 public function publishDraft(Page $draft, array $input): Page
155 $this->updateTemplateStatusAndContentFromInput($draft, $input);
156 $this->baseRepo->update($draft, $input);
158 $draft->draft = false;
159 $draft->revision_count = 1;
160 $draft->priority = $this->getNewPriority($draft);
161 $draft->refreshSlug();
164 $this->revisionRepo->storeNewForPage($draft, trans('entities.pages_initial_revision'));
165 $draft->indexForSearch();
166 $this->references->updateForPage($draft);
169 Activity::add(ActivityType::PAGE_CREATE, $draft);
175 * Update a page in the system.
177 public function update(Page $page, array $input): Page
179 // Hold the old details to compare later
180 $oldHtml = $page->html;
181 $oldName = $page->name;
182 $oldMarkdown = $page->markdown;
184 $this->updateTemplateStatusAndContentFromInput($page, $input);
185 $this->baseRepo->update($page, $input);
186 $this->references->updateForPage($page);
188 // Update with new details
189 $page->revision_count++;
192 // Remove all update drafts for this user & page.
193 $this->revisionRepo->deleteDraftsForCurrentUser($page);
195 // Save a revision after updating
196 $summary = trim($input['summary'] ?? '');
197 $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
198 $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
199 $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
200 if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
201 $this->revisionRepo->storeNewForPage($page, $summary);
204 Activity::add(ActivityType::PAGE_UPDATE, $page);
209 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
211 if (isset($input['template']) && userCan('templates-manage')) {
212 $page->template = ($input['template'] === 'true');
215 $pageContent = new PageContent($page);
216 $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
217 $newEditor = $currentEditor;
219 $haveInput = isset($input['markdown']) || isset($input['html']);
220 $inputEmpty = empty($input['markdown']) && empty($input['html']);
222 if ($haveInput && $inputEmpty) {
223 $pageContent->setNewHTML('');
224 } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
225 $newEditor = 'markdown';
226 $pageContent->setNewMarkdown($input['markdown']);
227 } elseif (isset($input['html'])) {
228 $newEditor = 'wysiwyg';
229 $pageContent->setNewHTML($input['html']);
232 if ($newEditor !== $currentEditor && userCan('editor-change')) {
233 $page->editor = $newEditor;
238 * Save a page update draft.
240 public function updatePageDraft(Page $page, array $input)
242 // If the page itself is a draft simply update that
244 $this->updateTemplateStatusAndContentFromInput($page, $input);
251 // Otherwise, save the data to a revision
252 $draft = $this->revisionRepo->getNewDraftForCurrentUser($page);
253 $draft->fill($input);
255 if (!empty($input['markdown'])) {
256 $draft->markdown = $input['markdown'];
259 $draft->html = $input['html'];
260 $draft->markdown = '';
269 * Destroy a page from the system.
273 public function destroy(Page $page)
275 $trashCan = new TrashCan();
276 $trashCan->softDestroyPage($page);
277 Activity::add(ActivityType::PAGE_DELETE, $page);
278 $trashCan->autoClearOld();
282 * Restores a revision's content back into a page.
284 public function restoreRevision(Page $page, int $revisionId): Page
286 $page->revision_count++;
288 /** @var PageRevision $revision */
289 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
291 $page->fill($revision->toArray());
292 $content = new PageContent($page);
294 if (!empty($revision->markdown)) {
295 $content->setNewMarkdown($revision->markdown);
297 $content->setNewHTML($revision->html);
300 $page->updated_by = user()->id;
301 $page->refreshSlug();
303 $page->indexForSearch();
304 $this->references->updateForPage($page);
306 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
307 $this->revisionRepo->storeNewForPage($page, $summary);
309 Activity::add(ActivityType::PAGE_RESTORE, $page);
310 Activity::add(ActivityType::REVISION_RESTORE, $revision);
316 * Move the given page into a new parent book or chapter.
317 * The $parentIdentifier must be a string of the following format:
318 * 'book:<id>' (book:5).
320 * @throws MoveOperationException
321 * @throws PermissionsException
323 public function move(Page $page, string $parentIdentifier): Entity
325 $parent = $this->findParentByIdentifier($parentIdentifier);
326 if (is_null($parent)) {
327 throw new MoveOperationException('Book or chapter to move page into not found');
330 if (!userCan('page-create', $parent)) {
331 throw new PermissionsException('User does not have permission to create a page within the new parent');
334 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
335 $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
336 $page->changeBook($newBookId);
337 $page->rebuildPermissions();
339 Activity::add(ActivityType::PAGE_MOVE, $page);
345 * Find a page parent entity via an identifier string in the format:
349 * @throws MoveOperationException
351 public function findParentByIdentifier(string $identifier): ?Entity
353 $stringExploded = explode(':', $identifier);
354 $entityType = $stringExploded[0];
355 $entityId = intval($stringExploded[1]);
357 if ($entityType !== 'book' && $entityType !== 'chapter') {
358 throw new MoveOperationException('Pages can only be in books or chapters');
361 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
363 return $parentClass::visible()->where('id', '=', $entityId)->first();
367 * Get a new priority for a page.
369 protected function getNewPriority(Page $page): int
371 $parent = $page->getParent();
372 if ($parent instanceof Chapter) {
373 /** @var ?Page $lastPage */
374 $lastPage = $parent->pages('desc')->first();
376 return $lastPage ? $lastPage->priority + 1 : 0;
379 return (new BookContents($page->book))->getLastPriority() + 1;