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;
20 use Illuminate\Database\Eloquent\Builder;
21 use Illuminate\Pagination\LengthAwarePaginator;
28 * PageRepo constructor.
30 public function __construct(BaseRepo $baseRepo)
32 $this->baseRepo = $baseRepo;
38 * @throws NotFoundException
40 public function getById(int $id, array $relations = ['book']): 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 /** @var ?PageRevision $revision */
74 $revision = PageRevision::query()
75 ->whereHas('page', function (Builder $query) {
76 $query->scopes('visible');
78 ->where('slug', '=', $pageSlug)
79 ->where('type', '=', 'version')
80 ->where('book_slug', '=', $bookSlug)
81 ->orderBy('created_at', 'desc')
85 return $revision->page ?? null;
89 * Get pages that have been marked as a template.
91 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
93 $query = Page::visible()
94 ->where('template', '=', true)
95 ->orderBy('name', 'asc')
96 ->skip(($page - 1) * $count)
100 $query->where('name', 'like', '%' . $search . '%');
103 $paginator = $query->paginate($count, ['*'], 'page', $page);
104 $paginator->withPath('/templates');
110 * Get a parent item via slugs.
112 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
114 if ($chapterSlug !== null) {
115 return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
118 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
122 * Get the draft copy of the given page for the current user.
124 public function getUserDraft(Page $page): ?PageRevision
126 $revision = $this->getUserDraftQuery($page)->first();
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);
168 $draft->refreshSlug();
171 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
172 $draft->indexForSearch();
175 Activity::add(ActivityType::PAGE_CREATE, $draft);
181 * Update a page in the system.
183 public function update(Page $page, array $input): Page
185 // Hold the old details to compare later
186 $oldHtml = $page->html;
187 $oldName = $page->name;
188 $oldMarkdown = $page->markdown;
190 $this->updateTemplateStatusAndContentFromInput($page, $input);
191 $this->baseRepo->update($page, $input);
193 // Update with new details
194 $page->revision_count++;
197 // Remove all update drafts for this user & page.
198 $this->getUserDraftQuery($page)->delete();
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->savePageRevision($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 * Saves a page revision into the system.
245 protected function savePageRevision(Page $page, string $summary = null): PageRevision
247 $revision = new PageRevision();
249 $revision->name = $page->name;
250 $revision->html = $page->html;
251 $revision->markdown = $page->markdown;
252 $revision->text = $page->text;
253 $revision->page_id = $page->id;
254 $revision->slug = $page->slug;
255 $revision->book_slug = $page->book->slug;
256 $revision->created_by = user()->id;
257 $revision->created_at = $page->updated_at;
258 $revision->type = 'version';
259 $revision->summary = $summary;
260 $revision->revision_number = $page->revision_count;
263 $this->deleteOldRevisions($page);
269 * Save a page update draft.
271 public function updatePageDraft(Page $page, array $input)
273 // If the page itself is a draft simply update that
275 $this->updateTemplateStatusAndContentFromInput($page, $input);
282 // Otherwise, save the data to a revision
283 $draft = $this->getPageRevisionToUpdate($page);
284 $draft->fill($input);
286 if (!empty($input['markdown'])) {
287 $draft->markdown = $input['markdown'];
290 $draft->html = $input['html'];
291 $draft->markdown = '';
300 * Destroy a page from the system.
304 public function destroy(Page $page)
306 $trashCan = new TrashCan();
307 $trashCan->softDestroyPage($page);
308 Activity::add(ActivityType::PAGE_DELETE, $page);
309 $trashCan->autoClearOld();
313 * Restores a revision's content back into a page.
315 public function restoreRevision(Page $page, int $revisionId): Page
317 $page->revision_count++;
319 /** @var PageRevision $revision */
320 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
322 $page->fill($revision->toArray());
323 $content = new PageContent($page);
325 if (!empty($revision->markdown)) {
326 $content->setNewMarkdown($revision->markdown);
328 $content->setNewHTML($revision->html);
331 $page->updated_by = user()->id;
332 $page->refreshSlug();
334 $page->indexForSearch();
336 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
337 $this->savePageRevision($page, $summary);
339 Activity::add(ActivityType::PAGE_RESTORE, $page);
345 * Move the given page into a new parent book or chapter.
346 * The $parentIdentifier must be a string of the following format:
347 * 'book:<id>' (book:5).
349 * @throws MoveOperationException
350 * @throws PermissionsException
352 public function move(Page $page, string $parentIdentifier): Entity
354 $parent = $this->findParentByIdentifier($parentIdentifier);
355 if (is_null($parent)) {
356 throw new MoveOperationException('Book or chapter to move page into not found');
359 if (!userCan('page-create', $parent)) {
360 throw new PermissionsException('User does not have permission to create a page within the new parent');
363 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
364 $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
365 $page->changeBook($newBookId);
366 $page->rebuildPermissions();
368 Activity::add(ActivityType::PAGE_MOVE, $page);
374 * Find a page parent entity via an identifier string in the format:
378 * @throws MoveOperationException
380 public function findParentByIdentifier(string $identifier): ?Entity
382 $stringExploded = explode(':', $identifier);
383 $entityType = $stringExploded[0];
384 $entityId = intval($stringExploded[1]);
386 if ($entityType !== 'book' && $entityType !== 'chapter') {
387 throw new MoveOperationException('Pages can only be in books or chapters');
390 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
392 return $parentClass::visible()->where('id', '=', $entityId)->first();
396 * Change the page's parent to the given entity.
398 protected function changeParent(Page $page, Entity $parent)
400 $book = ($parent instanceof Chapter) ? $parent->book : $parent;
401 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
404 if ($page->book->id !== $book->id) {
405 $page->changeBook($book->id);
409 $book->rebuildPermissions();
413 * Get a page revision to update for the given page.
414 * Checks for an existing revisions before providing a fresh one.
416 protected function getPageRevisionToUpdate(Page $page): PageRevision
418 $drafts = $this->getUserDraftQuery($page)->get();
419 if ($drafts->count() > 0) {
420 return $drafts->first();
423 $draft = new PageRevision();
424 $draft->page_id = $page->id;
425 $draft->slug = $page->slug;
426 $draft->book_slug = $page->book->slug;
427 $draft->created_by = user()->id;
428 $draft->type = 'update_draft';
434 * Delete old revisions, for the given page, from the system.
436 protected function deleteOldRevisions(Page $page)
438 $revisionLimit = config('app.revision_limit');
439 if ($revisionLimit === false) {
443 $revisionsToDelete = PageRevision::query()
444 ->where('page_id', '=', $page->id)
445 ->orderBy('created_at', 'desc')
446 ->skip(intval($revisionLimit))
449 if ($revisionsToDelete->count() > 0) {
450 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
455 * Get a new priority for a page.
457 protected function getNewPriority(Page $page): int
459 $parent = $page->getParent();
460 if ($parent instanceof Chapter) {
461 /** @var ?Page $lastPage */
462 $lastPage = $parent->pages('desc')->first();
464 return $lastPage ? $lastPage->priority + 1 : 0;
467 return (new BookContents($page->book))->getLastPriority() + 1;
471 * Get the query to find the user's draft copies of the given page.
473 protected function getUserDraftQuery(Page $page)
475 return PageRevision::query()->where('created_by', '=', user()->id)
476 ->where('type', 'update_draft')
477 ->where('page_id', '=', $page->id)
478 ->orderBy('created_at', 'desc');