1 <?php namespace BookStack\Entities\Repos;
3 use BookStack\Entities\Book;
4 use BookStack\Entities\Chapter;
5 use BookStack\Entities\Entity;
6 use BookStack\Entities\Managers\BookContents;
7 use BookStack\Entities\Managers\PageContent;
8 use BookStack\Entities\Managers\TrashCan;
9 use BookStack\Entities\Page;
10 use BookStack\Entities\PageRevision;
11 use BookStack\Exceptions\MoveOperationException;
12 use BookStack\Exceptions\NotFoundException;
13 use BookStack\Exceptions\NotifyException;
14 use BookStack\Exceptions\PermissionsException;
15 use Illuminate\Database\Eloquent\Builder;
16 use Illuminate\Pagination\LengthAwarePaginator;
17 use Illuminate\Support\Collection;
25 * PageRepo constructor.
27 public function __construct(BaseRepo $baseRepo)
29 $this->baseRepo = $baseRepo;
34 * @throws NotFoundException
36 public function getById(int $id): Page
38 $page = Page::visible()->with(['book'])->find($id);
41 throw new NotFoundException(trans('errors.page_not_found'));
48 * Get a page its book and own slug.
49 * @throws NotFoundException
51 public function getBySlug(string $bookSlug, string $pageSlug): Page
53 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
56 throw new NotFoundException(trans('errors.page_not_found'));
63 * Get a page by its old slug but checking the revisions table
64 * for the last revision that matched the given page and book slug.
66 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
68 $revision = PageRevision::query()
69 ->whereHas('page', function (Builder $query) {
72 ->where('slug', '=', $pageSlug)
73 ->where('type', '=', 'version')
74 ->where('book_slug', '=', $bookSlug)
75 ->orderBy('created_at', 'desc')
78 return $revision ? $revision->page : null;
82 * Get pages that have been marked as a template.
84 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
86 $query = Page::visible()
87 ->where('template', '=', true)
88 ->orderBy('name', 'asc')
89 ->skip(($page - 1) * $count)
93 $query->where('name', 'like', '%' . $search . '%');
96 $paginator = $query->paginate($count, ['*'], 'page', $page);
97 $paginator->withPath('/templates');
103 * Get a parent item via slugs.
105 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
107 if ($chapterSlug !== null) {
108 return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
111 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
115 * Get the draft copy of the given page for the current user.
117 public function getUserDraft(Page $page): ?PageRevision
119 $revision = $this->getUserDraftQuery($page)->first();
124 * Get a new draft page belonging to the given parent entity.
126 public function getNewDraftPage(Entity $parent)
128 $page = (new Page())->forceFill([
129 'name' => trans('entities.pages_initial_name'),
130 'created_by' => user()->id,
131 'updated_by' => user()->id,
135 if ($parent instanceof Chapter) {
136 $page->chapter_id = $parent->id;
137 $page->book_id = $parent->book_id;
139 $page->book_id = $parent->id;
143 $page->refresh()->rebuildPermissions();
148 * Publish a draft page to make it a live, non-draft page.
150 public function publishDraft(Page $draft, array $input): Page
152 $this->baseRepo->update($draft, $input);
153 if (isset($input['template']) && userCan('templates-manage')) {
154 $draft->template = ($input['template'] === 'true');
157 $pageContent = new PageContent($draft);
158 $pageContent->setNewHTML($input['html']);
159 $draft->draft = false;
160 $draft->revision_count = 1;
161 $draft->priority = $this->getNewPriority($draft);
162 $draft->refreshSlug();
165 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
166 $draft->indexForSearch();
167 return $draft->refresh();
171 * Update a page in the system.
173 public function update(Page $page, array $input): Page
175 // Hold the old details to compare later
176 $oldHtml = $page->html;
177 $oldName = $page->name;
179 if (isset($input['template']) && userCan('templates-manage')) {
180 $page->template = ($input['template'] === 'true');
183 $this->baseRepo->update($page, $input);
185 // Update with new details
187 $pageContent = new PageContent($page);
188 $pageContent->setNewHTML($input['html']);
189 $page->revision_count++;
191 if (setting('app-editor') !== 'markdown') {
192 $page->markdown = '';
197 // Remove all update drafts for this user & page.
198 $this->getUserDraftQuery($page)->delete();
200 // Save a revision after updating
201 $summary = $input['summary'] ?? null;
202 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
203 $this->savePageRevision($page, $summary);
210 * Saves a page revision into the system.
212 protected function savePageRevision(Page $page, string $summary = null)
214 $revision = new PageRevision($page->toArray());
216 if (setting('app-editor') !== 'markdown') {
217 $revision->markdown = '';
220 $revision->page_id = $page->id;
221 $revision->slug = $page->slug;
222 $revision->book_slug = $page->book->slug;
223 $revision->created_by = user()->id;
224 $revision->created_at = $page->updated_at;
225 $revision->type = 'version';
226 $revision->summary = $summary;
227 $revision->revision_number = $page->revision_count;
230 $this->deleteOldRevisions($page);
235 * Save a page update draft.
237 public function updatePageDraft(Page $page, array $input)
239 // If the page itself is a draft simply update that
242 if (isset($input['html'])) {
243 $content = new PageContent($page);
244 $content->setNewHTML($input['html']);
250 // Otherwise save the data to a revision
251 $draft = $this->getPageRevisionToUpdate($page);
252 $draft->fill($input);
253 if (setting('app-editor') !== 'markdown') {
254 $draft->markdown = '';
262 * Destroy a page from the system.
263 * @throws NotifyException
265 public function destroy(Page $page)
267 $trashCan = new TrashCan();
268 $trashCan->destroyPage($page);
272 * Restores a revision's content back into a page.
274 public function restoreRevision(Page $page, int $revisionId): Page
276 $page->revision_count++;
277 $this->savePageRevision($page);
279 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
280 $page->fill($revision->toArray());
281 $content = new PageContent($page);
282 $content->setNewHTML($page->html);
283 $page->updated_by = user()->id;
284 $page->refreshSlug();
287 $page->indexForSearch();
292 * Move the given page into a new parent book or chapter.
293 * The $parentIdentifier must be a string of the following format:
294 * 'book:<id>' (book:5)
295 * @throws MoveOperationException
296 * @throws PermissionsException
298 public function move(Page $page, string $parentIdentifier): Book
300 $parent = $this->findParentByIdentifier($parentIdentifier);
301 if ($parent === null) {
302 throw new MoveOperationException('Book or chapter to move page into not found');
305 if (!userCan('page-create', $parent)) {
306 throw new PermissionsException('User does not have permission to create a page within the new parent');
309 if ($parent instanceof Chapter) {
310 $page->chapter_id = $parent->id;
313 $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
314 $page->rebuildPermissions();
316 return ($parent instanceof Book ? $parent : $parent->book);
320 * Copy an existing page in the system.
321 * Optionally providing a new parent via string identifier and a new name.
322 * @throws MoveOperationException
323 * @throws PermissionsException
325 public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
327 $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->parent();
328 if ($parent === null) {
329 throw new MoveOperationException('Book or chapter to move page into not found');
332 if (!userCan('page-create', $parent)) {
333 throw new PermissionsException('User does not have permission to create a page within the new parent');
336 $copyPage = $this->getNewDraftPage($parent);
337 $pageData = $page->getAttributes();
340 if (!empty($newName)) {
341 $pageData['name'] = $newName;
344 // Copy tags from previous page if set
346 $pageData['tags'] = [];
347 foreach ($page->tags as $tag) {
348 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
352 return $this->publishDraft($copyPage, $pageData);
356 * Find a page parent entity via a identifier string in the format:
359 * @throws MoveOperationException
361 protected function findParentByIdentifier(string $identifier): ?Entity
363 $stringExploded = explode(':', $identifier);
364 $entityType = $stringExploded[0];
365 $entityId = intval($stringExploded[1]);
367 if ($entityType !== 'book' && $entityType !== 'chapter') {
368 throw new MoveOperationException('Pages can only be in books or chapters');
371 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
372 return $parentClass::visible()->where('id', '=', $entityId)->first();
376 * Update the permissions of a page.
378 public function updatePermissions(Page $page, bool $restricted, Collection $permissions = null)
380 $this->baseRepo->updatePermissions($page, $restricted, $permissions);
384 * Change the page's parent to the given entity.
386 protected function changeParent(Page $page, Entity $parent)
388 $book = ($parent instanceof Book) ? $parent : $parent->book;
389 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
392 if ($page->book->id !== $book->id) {
393 $page->changeBook($book->id);
397 $book->rebuildPermissions();
401 * Get a page revision to update for the given page.
402 * Checks for an existing revisions before providing a fresh one.
404 protected function getPageRevisionToUpdate(Page $page): PageRevision
406 $drafts = $this->getUserDraftQuery($page)->get();
407 if ($drafts->count() > 0) {
408 return $drafts->first();
411 $draft = new PageRevision();
412 $draft->page_id = $page->id;
413 $draft->slug = $page->slug;
414 $draft->book_slug = $page->book->slug;
415 $draft->created_by = user()->id;
416 $draft->type = 'update_draft';
421 * Delete old revisions, for the given page, from the system.
423 protected function deleteOldRevisions(Page $page)
425 $revisionLimit = config('app.revision_limit');
426 if ($revisionLimit === false) {
430 $revisionsToDelete = PageRevision::query()
431 ->where('page_id', '=', $page->id)
432 ->orderBy('created_at', 'desc')
433 ->skip(intval($revisionLimit))
436 if ($revisionsToDelete->count() > 0) {
437 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
442 * Get a new priority for a page
444 protected function getNewPriority(Page $page): int
446 if ($page->parent() instanceof Chapter) {
447 $lastPage = $page->parent()->pages('desc')->first();
448 return $lastPage ? $lastPage->priority + 1 : 0;
451 return (new BookContents($page->book))->getLastPriority() + 1;
455 * Get the query to find the user's draft copies of the given page.
457 protected function getUserDraftQuery(Page $page)
459 return PageRevision::query()->where('created_by', '=', user()->id)
460 ->where('type', 'update_draft')
461 ->where('page_id', '=', $page->id)
462 ->orderBy('created_at', 'desc');