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\TrashCan;
14 use BookStack\Exceptions\MoveOperationException;
15 use BookStack\Exceptions\NotFoundException;
16 use BookStack\Exceptions\PermissionsException;
17 use BookStack\Facades\Activity;
19 use Illuminate\Database\Eloquent\Builder;
20 use Illuminate\Pagination\LengthAwarePaginator;
27 * PageRepo constructor.
29 public function __construct(BaseRepo $baseRepo)
31 $this->baseRepo = $baseRepo;
37 * @throws NotFoundException
39 public function getById(int $id, array $relations = ['book']): Page
41 $page = Page::visible()->with($relations)->find($id);
44 throw new NotFoundException(trans('errors.page_not_found'));
51 * Get a page its book and own slug.
53 * @throws NotFoundException
55 public function getBySlug(string $bookSlug, string $pageSlug): Page
57 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
60 throw new NotFoundException(trans('errors.page_not_found'));
67 * Get a page by its old slug but checking the revisions table
68 * for the last revision that matched the given page and book slug.
70 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
72 /** @var ?PageRevision $revision */
73 $revision = PageRevision::query()
74 ->whereHas('page', function (Builder $query) {
75 $query->scopes('visible');
77 ->where('slug', '=', $pageSlug)
78 ->where('type', '=', 'version')
79 ->where('book_slug', '=', $bookSlug)
80 ->orderBy('created_at', 'desc')
84 return $revision->page ?? null;
88 * Get pages that have been marked as a template.
90 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
92 $query = Page::visible()
93 ->where('template', '=', true)
94 ->orderBy('name', 'asc')
95 ->skip(($page - 1) * $count)
99 $query->where('name', 'like', '%' . $search . '%');
102 $paginator = $query->paginate($count, ['*'], 'page', $page);
103 $paginator->withPath('/templates');
109 * Get a parent item via slugs.
111 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
113 if ($chapterSlug !== null) {
114 return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
117 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
121 * Get the draft copy of the given page for the current user.
123 public function getUserDraft(Page $page): ?PageRevision
125 $revision = $this->getUserDraftQuery($page)->first();
131 * Get a new draft page belonging to the given parent entity.
133 public function getNewDraftPage(Entity $parent)
135 $page = (new Page())->forceFill([
136 'name' => trans('entities.pages_initial_name'),
137 'created_by' => user()->id,
138 'owned_by' => user()->id,
139 'updated_by' => user()->id,
143 if ($parent instanceof Chapter) {
144 $page->chapter_id = $parent->id;
145 $page->book_id = $parent->book_id;
147 $page->book_id = $parent->id;
151 $page->refresh()->rebuildPermissions();
157 * Publish a draft page to make it a live, non-draft page.
159 public function publishDraft(Page $draft, array $input): Page
161 $this->updateTemplateStatusAndContentFromInput($draft, $input);
162 $this->baseRepo->update($draft, $input);
164 $draft->draft = false;
165 $draft->revision_count = 1;
166 $draft->priority = $this->getNewPriority($draft);
167 $draft->refreshSlug();
170 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
171 $draft->indexForSearch();
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);
192 // Update with new details
193 $page->revision_count++;
196 // Remove all update drafts for this user & page.
197 $this->getUserDraftQuery($page)->delete();
199 // Save a revision after updating
200 $summary = trim($input['summary'] ?? '');
201 $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
202 $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
203 $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
204 if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
205 $this->savePageRevision($page, $summary);
208 Activity::add(ActivityType::PAGE_UPDATE, $page);
213 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
215 if (isset($input['template']) && userCan('templates-manage')) {
216 $page->template = ($input['template'] === 'true');
219 $pageContent = new PageContent($page);
220 if (!empty($input['markdown'] ?? '')) {
221 $pageContent->setNewMarkdown($input['markdown']);
222 } elseif (isset($input['html'])) {
223 $pageContent->setNewHTML($input['html']);
228 * Saves a page revision into the system.
230 protected function savePageRevision(Page $page, string $summary = null): PageRevision
232 $revision = new PageRevision($page->getAttributes());
234 $revision->page_id = $page->id;
235 $revision->slug = $page->slug;
236 $revision->book_slug = $page->book->slug;
237 $revision->created_by = user()->id;
238 $revision->created_at = $page->updated_at;
239 $revision->type = 'version';
240 $revision->summary = $summary;
241 $revision->revision_number = $page->revision_count;
244 $this->deleteOldRevisions($page);
250 * Save a page update draft.
252 public function updatePageDraft(Page $page, array $input)
254 // If the page itself is a draft simply update that
256 $this->updateTemplateStatusAndContentFromInput($page, $input);
263 // Otherwise save the data to a revision
264 $draft = $this->getPageRevisionToUpdate($page);
265 $draft->fill($input);
266 if (setting('app-editor') !== 'markdown') {
267 $draft->markdown = '';
276 * Destroy a page from the system.
280 public function destroy(Page $page)
282 $trashCan = new TrashCan();
283 $trashCan->softDestroyPage($page);
284 Activity::add(ActivityType::PAGE_DELETE, $page);
285 $trashCan->autoClearOld();
289 * Restores a revision's content back into a page.
291 public function restoreRevision(Page $page, int $revisionId): Page
293 $page->revision_count++;
295 /** @var PageRevision $revision */
296 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
298 $page->fill($revision->toArray());
299 $content = new PageContent($page);
301 if (!empty($revision->markdown)) {
302 $content->setNewMarkdown($revision->markdown);
304 $content->setNewHTML($revision->html);
307 $page->updated_by = user()->id;
308 $page->refreshSlug();
310 $page->indexForSearch();
312 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
313 $this->savePageRevision($page, $summary);
315 Activity::add(ActivityType::PAGE_RESTORE, $page);
321 * Move the given page into a new parent book or chapter.
322 * The $parentIdentifier must be a string of the following format:
323 * 'book:<id>' (book:5).
325 * @throws MoveOperationException
326 * @throws PermissionsException
328 public function move(Page $page, string $parentIdentifier): Entity
330 $parent = $this->findParentByIdentifier($parentIdentifier);
331 if (is_null($parent)) {
332 throw new MoveOperationException('Book or chapter to move page into not found');
335 if (!userCan('page-create', $parent)) {
336 throw new PermissionsException('User does not have permission to create a page within the new parent');
339 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
340 $newBookId = ($parent instanceof Chapter) ? $parent->book->id : $parent->id;
341 $page->changeBook($newBookId);
342 $page->rebuildPermissions();
344 Activity::add(ActivityType::PAGE_MOVE, $page);
350 * Find a page parent entity via an identifier string in the format:
354 * @throws MoveOperationException
356 public function findParentByIdentifier(string $identifier): ?Entity
358 $stringExploded = explode(':', $identifier);
359 $entityType = $stringExploded[0];
360 $entityId = intval($stringExploded[1]);
362 if ($entityType !== 'book' && $entityType !== 'chapter') {
363 throw new MoveOperationException('Pages can only be in books or chapters');
366 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
368 return $parentClass::visible()->where('id', '=', $entityId)->first();
372 * Change the page's parent to the given entity.
374 protected function changeParent(Page $page, Entity $parent)
376 $book = ($parent instanceof Chapter) ? $parent->book : $parent;
377 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
380 if ($page->book->id !== $book->id) {
381 $page->changeBook($book->id);
385 $book->rebuildPermissions();
389 * Get a page revision to update for the given page.
390 * Checks for an existing revisions before providing a fresh one.
392 protected function getPageRevisionToUpdate(Page $page): PageRevision
394 $drafts = $this->getUserDraftQuery($page)->get();
395 if ($drafts->count() > 0) {
396 return $drafts->first();
399 $draft = new PageRevision();
400 $draft->page_id = $page->id;
401 $draft->slug = $page->slug;
402 $draft->book_slug = $page->book->slug;
403 $draft->created_by = user()->id;
404 $draft->type = 'update_draft';
410 * Delete old revisions, for the given page, from the system.
412 protected function deleteOldRevisions(Page $page)
414 $revisionLimit = config('app.revision_limit');
415 if ($revisionLimit === false) {
419 $revisionsToDelete = PageRevision::query()
420 ->where('page_id', '=', $page->id)
421 ->orderBy('created_at', 'desc')
422 ->skip(intval($revisionLimit))
425 if ($revisionsToDelete->count() > 0) {
426 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
431 * Get a new priority for a page.
433 protected function getNewPriority(Page $page): int
435 $parent = $page->getParent();
436 if ($parent instanceof Chapter) {
437 /** @var ?Page $lastPage */
438 $lastPage = $parent->pages('desc')->first();
440 return $lastPage ? $lastPage->priority + 1 : 0;
443 return (new BookContents($page->book))->getLastPriority() + 1;
447 * Get the query to find the user's draft copies of the given page.
449 protected function getUserDraftQuery(Page $page)
451 return PageRevision::query()->where('created_by', '=', user()->id)
452 ->where('type', 'update_draft')
453 ->where('page_id', '=', $page->id)
454 ->orderBy('created_at', 'desc');