1 <?php namespace BookStack\Entities\Repos;
3 use BookStack\Actions\ActivityType;
4 use BookStack\Entities\Models\Book;
5 use BookStack\Entities\Models\Chapter;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Tools\BookContents;
8 use BookStack\Entities\Tools\PageContent;
9 use BookStack\Entities\Tools\TrashCan;
10 use BookStack\Entities\Models\Page;
11 use BookStack\Entities\Models\PageRevision;
12 use BookStack\Exceptions\MoveOperationException;
13 use BookStack\Exceptions\NotFoundException;
14 use BookStack\Exceptions\PermissionsException;
15 use BookStack\Facades\Activity;
17 use Illuminate\Database\Eloquent\Builder;
18 use Illuminate\Pagination\LengthAwarePaginator;
19 use Illuminate\Support\Collection;
27 * PageRepo constructor.
29 public function __construct(BaseRepo $baseRepo)
31 $this->baseRepo = $baseRepo;
36 * @throws NotFoundException
38 public function getById(int $id, array $relations = ['book']): Page
40 $page = Page::visible()->with($relations)->find($id);
43 throw new NotFoundException(trans('errors.page_not_found'));
50 * Get a page its book and own slug.
51 * @throws NotFoundException
53 public function getBySlug(string $bookSlug, string $pageSlug): Page
55 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
58 throw new NotFoundException(trans('errors.page_not_found'));
65 * Get a page by its old slug but checking the revisions table
66 * for the last revision that matched the given page and book slug.
68 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
70 $revision = PageRevision::query()
71 ->whereHas('page', function (Builder $query) {
74 ->where('slug', '=', $pageSlug)
75 ->where('type', '=', 'version')
76 ->where('book_slug', '=', $bookSlug)
77 ->orderBy('created_at', 'desc')
80 return $revision ? $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 = 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 $revision = $this->getUserDraftQuery($page)->first();
126 * Get a new draft page belonging to the given parent entity.
128 public function getNewDraftPage(Entity $parent)
130 $page = (new Page())->forceFill([
131 'name' => trans('entities.pages_initial_name'),
132 'created_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();
150 * Publish a draft page to make it a live, non-draft page.
152 public function publishDraft(Page $draft, array $input): Page
154 $this->baseRepo->update($draft, $input);
155 $this->updateTemplateStatusAndContentFromInput($draft, $input);
157 $draft->draft = false;
158 $draft->revision_count = 1;
159 $draft->priority = $this->getNewPriority($draft);
160 $draft->refreshSlug();
163 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
164 $draft->indexForSearch();
167 Activity::addForEntity($draft, ActivityType::PAGE_CREATE);
172 * Update a page in the system.
174 public function update(Page $page, array $input): Page
176 // Hold the old details to compare later
177 $oldHtml = $page->html;
178 $oldName = $page->name;
180 $this->updateTemplateStatusAndContentFromInput($page, $input);
181 $this->baseRepo->update($page, $input);
183 // Update with new details
184 $page->revision_count++;
186 if (setting('app-editor') !== 'markdown') {
187 $page->markdown = '';
192 // Remove all update drafts for this user & page.
193 $this->getUserDraftQuery($page)->delete();
195 // Save a revision after updating
196 $summary = $input['summary'] ?? null;
197 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
198 $this->savePageRevision($page, $summary);
201 Activity::addForEntity($page, ActivityType::PAGE_UPDATE);
205 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
207 if (isset($input['template']) && userCan('templates-manage')) {
208 $page->template = ($input['template'] === 'true');
211 $pageContent = new PageContent($page);
212 if (isset($input['html'])) {
213 $pageContent->setNewHTML($input['html']);
215 $pageContent->setNewMarkdown($input['markdown']);
220 * Saves a page revision into the system.
222 protected function savePageRevision(Page $page, string $summary = null)
224 $revision = new PageRevision($page->getAttributes());
226 if (setting('app-editor') !== 'markdown') {
227 $revision->markdown = '';
230 $revision->page_id = $page->id;
231 $revision->slug = $page->slug;
232 $revision->book_slug = $page->book->slug;
233 $revision->created_by = user()->id;
234 $revision->created_at = $page->updated_at;
235 $revision->type = 'version';
236 $revision->summary = $summary;
237 $revision->revision_number = $page->revision_count;
240 $this->deleteOldRevisions($page);
245 * Save a page update draft.
247 public function updatePageDraft(Page $page, array $input)
249 // If the page itself is a draft simply update that
251 if (isset($input['html'])) {
252 (new PageContent($page))->setNewHTML($input['html']);
259 // Otherwise save the data to a revision
260 $draft = $this->getPageRevisionToUpdate($page);
261 $draft->fill($input);
262 if (setting('app-editor') !== 'markdown') {
263 $draft->markdown = '';
271 * Destroy a page from the system.
274 public function destroy(Page $page)
276 $trashCan = new TrashCan();
277 $trashCan->softDestroyPage($page);
278 Activity::addForEntity($page, ActivityType::PAGE_DELETE);
279 $trashCan->autoClearOld();
283 * Restores a revision's content back into a page.
285 public function restoreRevision(Page $page, int $revisionId): Page
287 $page->revision_count++;
288 $this->savePageRevision($page);
290 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
291 $page->fill($revision->toArray());
292 $content = new PageContent($page);
293 $content->setNewHTML($revision->html);
294 $page->updated_by = user()->id;
295 $page->refreshSlug();
298 $page->indexForSearch();
299 Activity::addForEntity($page, ActivityType::PAGE_RESTORE);
304 * Move the given page into a new parent book or chapter.
305 * The $parentIdentifier must be a string of the following format:
306 * 'book:<id>' (book:5)
307 * @throws MoveOperationException
308 * @throws PermissionsException
310 public function move(Page $page, string $parentIdentifier): Entity
312 $parent = $this->findParentByIdentifier($parentIdentifier);
313 if ($parent === null) {
314 throw new MoveOperationException('Book or chapter to move page into not found');
317 if (!userCan('page-create', $parent)) {
318 throw new PermissionsException('User does not have permission to create a page within the new parent');
321 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
322 $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
323 $page->rebuildPermissions();
325 Activity::addForEntity($page, ActivityType::PAGE_MOVE);
330 * Copy an existing page in the system.
331 * Optionally providing a new parent via string identifier and a new name.
332 * @throws MoveOperationException
333 * @throws PermissionsException
335 public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
337 $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
338 if ($parent === null) {
339 throw new MoveOperationException('Book or chapter to move page into not found');
342 if (!userCan('page-create', $parent)) {
343 throw new PermissionsException('User does not have permission to create a page within the new parent');
346 $copyPage = $this->getNewDraftPage($parent);
347 $pageData = $page->getAttributes();
350 if (!empty($newName)) {
351 $pageData['name'] = $newName;
354 // Copy tags from previous page if set
356 $pageData['tags'] = [];
357 foreach ($page->tags as $tag) {
358 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
362 return $this->publishDraft($copyPage, $pageData);
366 * Find a page parent entity via a identifier string in the format:
369 * @throws MoveOperationException
371 protected function findParentByIdentifier(string $identifier): ?Entity
373 $stringExploded = explode(':', $identifier);
374 $entityType = $stringExploded[0];
375 $entityId = intval($stringExploded[1]);
377 if ($entityType !== 'book' && $entityType !== 'chapter') {
378 throw new MoveOperationException('Pages can only be in books or chapters');
381 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
382 return $parentClass::visible()->where('id', '=', $entityId)->first();
386 * Update the permissions of a page.
388 public function updatePermissions(Page $page, bool $restricted, Collection $permissions = null)
390 $this->baseRepo->updatePermissions($page, $restricted, $permissions);
394 * Change the page's parent to the given entity.
396 protected function changeParent(Page $page, Entity $parent)
398 $book = ($parent instanceof Book) ? $parent : $parent->book;
399 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
402 if ($page->book->id !== $book->id) {
403 $page->changeBook($book->id);
407 $book->rebuildPermissions();
411 * Get a page revision to update for the given page.
412 * Checks for an existing revisions before providing a fresh one.
414 protected function getPageRevisionToUpdate(Page $page): PageRevision
416 $drafts = $this->getUserDraftQuery($page)->get();
417 if ($drafts->count() > 0) {
418 return $drafts->first();
421 $draft = new PageRevision();
422 $draft->page_id = $page->id;
423 $draft->slug = $page->slug;
424 $draft->book_slug = $page->book->slug;
425 $draft->created_by = user()->id;
426 $draft->type = 'update_draft';
431 * Delete old revisions, for the given page, from the system.
433 protected function deleteOldRevisions(Page $page)
435 $revisionLimit = config('app.revision_limit');
436 if ($revisionLimit === false) {
440 $revisionsToDelete = PageRevision::query()
441 ->where('page_id', '=', $page->id)
442 ->orderBy('created_at', 'desc')
443 ->skip(intval($revisionLimit))
446 if ($revisionsToDelete->count() > 0) {
447 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
452 * Get a new priority for a page
454 protected function getNewPriority(Page $page): int
456 $parent = $page->getParent();
457 if ($parent instanceof Chapter) {
458 $lastPage = $parent->pages('desc')->first();
459 return $lastPage ? $lastPage->priority + 1 : 0;
462 return (new BookContents($page->book))->getLastPriority() + 1;
466 * Get the query to find the user's draft copies of the given page.
468 protected function getUserDraftQuery(Page $page)
470 return PageRevision::query()->where('created_by', '=', user()->id)
471 ->where('type', 'update_draft')
472 ->where('page_id', '=', $page->id)
473 ->orderBy('created_at', 'desc');