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\ReferenceService;
21 use Illuminate\Database\Eloquent\Builder;
22 use Illuminate\Pagination\LengthAwarePaginator;
26 protected BaseRepo $baseRepo;
27 protected ReferenceService $references;
30 * PageRepo constructor.
32 public function __construct(BaseRepo $baseRepo, ReferenceService $references)
34 $this->baseRepo = $baseRepo;
35 $this->references = $references;
41 * @throws NotFoundException
43 public function getById(int $id, array $relations = ['book']): Page
45 $page = Page::visible()->with($relations)->find($id);
48 throw new NotFoundException(trans('errors.page_not_found'));
55 * Get a page its book and own slug.
57 * @throws NotFoundException
59 public function getBySlug(string $bookSlug, string $pageSlug): Page
61 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
64 throw new NotFoundException(trans('errors.page_not_found'));
71 * Get a page by its old slug but checking the revisions table
72 * for the last revision that matched the given page and book slug.
74 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
76 /** @var ?PageRevision $revision */
77 $revision = PageRevision::query()
78 ->whereHas('page', function (Builder $query) {
79 $query->scopes('visible');
81 ->where('slug', '=', $pageSlug)
82 ->where('type', '=', 'version')
83 ->where('book_slug', '=', $bookSlug)
84 ->orderBy('created_at', 'desc')
88 return $revision->page ?? null;
92 * Get pages that have been marked as a template.
94 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
96 $query = Page::visible()
97 ->where('template', '=', true)
98 ->orderBy('name', 'asc')
99 ->skip(($page - 1) * $count)
103 $query->where('name', 'like', '%' . $search . '%');
106 $paginator = $query->paginate($count, ['*'], 'page', $page);
107 $paginator->withPath('/templates');
113 * Get a parent item via slugs.
115 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
117 if ($chapterSlug !== null) {
118 return Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
121 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
125 * Get the draft copy of the given page for the current user.
127 public function getUserDraft(Page $page): ?PageRevision
129 $revision = $this->getUserDraftQuery($page)->first();
135 * Get a new draft page belonging to the given parent entity.
137 public function getNewDraftPage(Entity $parent)
139 $page = (new Page())->forceFill([
140 'name' => trans('entities.pages_initial_name'),
141 'created_by' => user()->id,
142 'owned_by' => user()->id,
143 'updated_by' => user()->id,
147 if ($parent instanceof Chapter) {
148 $page->chapter_id = $parent->id;
149 $page->book_id = $parent->book_id;
151 $page->book_id = $parent->id;
155 $page->refresh()->rebuildPermissions();
161 * Publish a draft page to make it a live, non-draft page.
163 public function publishDraft(Page $draft, array $input): Page
165 $this->updateTemplateStatusAndContentFromInput($draft, $input);
166 $this->baseRepo->update($draft, $input);
168 $draft->draft = false;
169 $draft->revision_count = 1;
170 $draft->priority = $this->getNewPriority($draft);
171 $draft->refreshSlug();
174 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
175 $draft->indexForSearch();
176 $this->references->updateForPage($draft);
179 Activity::add(ActivityType::PAGE_CREATE, $draft);
185 * Update a page in the system.
187 public function update(Page $page, array $input): Page
189 // Hold the old details to compare later
190 $oldHtml = $page->html;
191 $oldName = $page->name;
192 $oldMarkdown = $page->markdown;
194 $this->updateTemplateStatusAndContentFromInput($page, $input);
195 $this->baseRepo->update($page, $input);
196 $this->references->updateForPage($page);
198 // Update with new details
199 $page->revision_count++;
202 // Remove all update drafts for this user & page.
203 $this->getUserDraftQuery($page)->delete();
205 // Save a revision after updating
206 $summary = trim($input['summary'] ?? '');
207 $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
208 $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
209 $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
210 if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
211 $this->savePageRevision($page, $summary);
214 Activity::add(ActivityType::PAGE_UPDATE, $page);
219 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
221 if (isset($input['template']) && userCan('templates-manage')) {
222 $page->template = ($input['template'] === 'true');
225 $pageContent = new PageContent($page);
226 $currentEditor = $page->editor ?: PageEditorData::getSystemDefaultEditor();
227 $newEditor = $currentEditor;
229 $haveInput = isset($input['markdown']) || isset($input['html']);
230 $inputEmpty = empty($input['markdown']) && empty($input['html']);
232 if ($haveInput && $inputEmpty) {
233 $pageContent->setNewHTML('');
234 } elseif (!empty($input['markdown']) && is_string($input['markdown'])) {
235 $newEditor = 'markdown';
236 $pageContent->setNewMarkdown($input['markdown']);
237 } elseif (isset($input['html'])) {
238 $newEditor = 'wysiwyg';
239 $pageContent->setNewHTML($input['html']);
242 if ($newEditor !== $currentEditor && userCan('editor-change')) {
243 $page->editor = $newEditor;
248 * Saves a page revision into the system.
250 protected function savePageRevision(Page $page, string $summary = null): PageRevision
252 $revision = new PageRevision();
254 $revision->name = $page->name;
255 $revision->html = $page->html;
256 $revision->markdown = $page->markdown;
257 $revision->text = $page->text;
258 $revision->page_id = $page->id;
259 $revision->slug = $page->slug;
260 $revision->book_slug = $page->book->slug;
261 $revision->created_by = user()->id;
262 $revision->created_at = $page->updated_at;
263 $revision->type = 'version';
264 $revision->summary = $summary;
265 $revision->revision_number = $page->revision_count;
268 $this->deleteOldRevisions($page);
274 * Save a page update draft.
276 public function updatePageDraft(Page $page, array $input)
278 // If the page itself is a draft simply update that
280 $this->updateTemplateStatusAndContentFromInput($page, $input);
287 // Otherwise, save the data to a revision
288 $draft = $this->getPageRevisionToUpdate($page);
289 $draft->fill($input);
291 if (!empty($input['markdown'])) {
292 $draft->markdown = $input['markdown'];
295 $draft->html = $input['html'];
296 $draft->markdown = '';
305 * Destroy a page from the system.
309 public function destroy(Page $page)
311 $trashCan = new TrashCan();
312 $trashCan->softDestroyPage($page);
313 Activity::add(ActivityType::PAGE_DELETE, $page);
314 $trashCan->autoClearOld();
318 * Restores a revision's content back into a page.
320 public function restoreRevision(Page $page, int $revisionId): Page
322 $page->revision_count++;
324 /** @var PageRevision $revision */
325 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
327 $page->fill($revision->toArray());
328 $content = new PageContent($page);
330 if (!empty($revision->markdown)) {
331 $content->setNewMarkdown($revision->markdown);
333 $content->setNewHTML($revision->html);
336 $page->updated_by = user()->id;
337 $page->refreshSlug();
339 $page->indexForSearch();
340 $this->references->updateForPage($page);
342 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
343 $this->savePageRevision($page, $summary);
345 Activity::add(ActivityType::PAGE_RESTORE, $page);
346 Activity::add(ActivityType::REVISION_RESTORE, $revision);
352 * Move the given page into a new parent book or chapter.
353 * The $parentIdentifier must be a string of the following format:
354 * 'book:<id>' (book:5).
356 * @throws MoveOperationException
357 * @throws PermissionsException
359 public function move(Page $page, string $parentIdentifier): Entity
361 $parent = $this->findParentByIdentifier($parentIdentifier);
362 if (is_null($parent)) {
363 throw new MoveOperationException('Book or chapter to move page into not found');
366 if (!userCan('page-create', $parent)) {
367 throw new PermissionsException('User does not have permission to create a page within the new parent');
370 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
371 $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
372 $page->changeBook($newBookId);
373 $page->rebuildPermissions();
375 Activity::add(ActivityType::PAGE_MOVE, $page);
381 * Find a page parent entity via an identifier string in the format:
385 * @throws MoveOperationException
387 public function findParentByIdentifier(string $identifier): ?Entity
389 $stringExploded = explode(':', $identifier);
390 $entityType = $stringExploded[0];
391 $entityId = intval($stringExploded[1]);
393 if ($entityType !== 'book' && $entityType !== 'chapter') {
394 throw new MoveOperationException('Pages can only be in books or chapters');
397 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
399 return $parentClass::visible()->where('id', '=', $entityId)->first();
403 * Get a page revision to update for the given page.
404 * Checks for an existing revisions before providing a fresh one.
406 protected function getPageRevisionToUpdate(Page $page): PageRevision
408 $drafts = $this->getUserDraftQuery($page)->get();
409 if ($drafts->count() > 0) {
410 return $drafts->first();
413 $draft = new PageRevision();
414 $draft->page_id = $page->id;
415 $draft->slug = $page->slug;
416 $draft->book_slug = $page->book->slug;
417 $draft->created_by = user()->id;
418 $draft->type = 'update_draft';
424 * Delete old revisions, for the given page, from the system.
426 protected function deleteOldRevisions(Page $page)
428 $revisionLimit = config('app.revision_limit');
429 if ($revisionLimit === false) {
433 $revisionsToDelete = PageRevision::query()
434 ->where('page_id', '=', $page->id)
435 ->orderBy('created_at', 'desc')
436 ->skip(intval($revisionLimit))
440 if ($revisionsToDelete->count() > 0) {
441 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
446 * Get a new priority for a page.
448 protected function getNewPriority(Page $page): int
450 $parent = $page->getParent();
451 if ($parent instanceof Chapter) {
452 /** @var ?Page $lastPage */
453 $lastPage = $parent->pages('desc')->first();
455 return $lastPage ? $lastPage->priority + 1 : 0;
458 return (new BookContents($page->book))->getLastPriority() + 1;
462 * Get the query to find the user's draft copies of the given page.
464 protected function getUserDraftQuery(Page $page)
466 return PageRevision::query()->where('created_by', '=', user()->id)
467 ->where('type', 'update_draft')
468 ->where('page_id', '=', $page->id)
469 ->orderBy('created_at', 'desc');