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;
16 use Illuminate\Database\Eloquent\Builder;
17 use Illuminate\Pagination\LengthAwarePaginator;
18 use Illuminate\Support\Collection;
26 * PageRepo constructor.
28 public function __construct(BaseRepo $baseRepo)
30 $this->baseRepo = $baseRepo;
35 * @throws NotFoundException
37 public function getById(int $id): Page
39 $page = Page::visible()->with(['book'])->find($id);
42 throw new NotFoundException(trans('errors.page_not_found'));
49 * Get a page its book and own slug.
50 * @throws NotFoundException
52 public function getBySlug(string $bookSlug, string $pageSlug): Page
54 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
57 throw new NotFoundException(trans('errors.page_not_found'));
64 * Get a page by its old slug but checking the revisions table
65 * for the last revision that matched the given page and book slug.
67 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
69 $revision = PageRevision::query()
70 ->whereHas('page', function (Builder $query) {
73 ->where('slug', '=', $pageSlug)
74 ->where('type', '=', 'version')
75 ->where('book_slug', '=', $bookSlug)
76 ->orderBy('created_at', 'desc')
79 return $revision ? $revision->page : null;
83 * Get pages that have been marked as a template.
85 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
87 $query = Page::visible()
88 ->where('template', '=', true)
89 ->orderBy('name', 'asc')
90 ->skip(($page - 1) * $count)
94 $query->where('name', 'like', '%' . $search . '%');
97 $paginator = $query->paginate($count, ['*'], 'page', $page);
98 $paginator->withPath('/templates');
104 * Get a parent item via slugs.
106 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
108 if ($chapterSlug !== null) {
109 return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
112 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
116 * Get the draft copy of the given page for the current user.
118 public function getUserDraft(Page $page): ?PageRevision
120 $revision = $this->getUserDraftQuery($page)->first();
125 * Get a new draft page belonging to the given parent entity.
127 public function getNewDraftPage(Entity $parent)
129 $page = (new Page())->forceFill([
130 'name' => trans('entities.pages_initial_name'),
131 'created_by' => user()->id,
132 'updated_by' => user()->id,
136 if ($parent instanceof Chapter) {
137 $page->chapter_id = $parent->id;
138 $page->book_id = $parent->book_id;
140 $page->book_id = $parent->id;
144 $page->refresh()->rebuildPermissions();
149 * Publish a draft page to make it a live, non-draft page.
151 public function publishDraft(Page $draft, array $input): Page
153 $this->baseRepo->update($draft, $input);
154 if (isset($input['template']) && userCan('templates-manage')) {
155 $draft->template = ($input['template'] === 'true');
158 $pageContent = new PageContent($draft);
159 $pageContent->setNewHTML($input['html']);
160 $draft->draft = false;
161 $draft->revision_count = 1;
162 $draft->priority = $this->getNewPriority($draft);
163 $draft->refreshSlug();
166 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
167 $draft->indexForSearch();
168 return $draft->refresh();
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 if (isset($input['template']) && userCan('templates-manage')) {
181 $page->template = ($input['template'] === 'true');
184 $pageContent = new PageContent($page);
185 $pageContent->setNewHTML($input['html']);
186 $this->baseRepo->update($page, $input);
188 // Update with new details
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->getAttributes());
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.
265 public function destroy(Page $page)
267 $trashCan = new TrashCan();
268 $trashCan->softDestroyPage($page);
269 $trashCan->autoClearOld();
273 * Restores a revision's content back into a page.
275 public function restoreRevision(Page $page, int $revisionId): Page
277 $page->revision_count++;
278 $this->savePageRevision($page);
280 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
281 $page->fill($revision->toArray());
282 $content = new PageContent($page);
283 $content->setNewHTML($revision->html);
284 $page->updated_by = user()->id;
285 $page->refreshSlug();
288 $page->indexForSearch();
293 * Move the given page into a new parent book or chapter.
294 * The $parentIdentifier must be a string of the following format:
295 * 'book:<id>' (book:5)
296 * @throws MoveOperationException
297 * @throws PermissionsException
299 public function move(Page $page, string $parentIdentifier): Book
301 $parent = $this->findParentByIdentifier($parentIdentifier);
302 if ($parent === null) {
303 throw new MoveOperationException('Book or chapter to move page into not found');
306 if (!userCan('page-create', $parent)) {
307 throw new PermissionsException('User does not have permission to create a page within the new parent');
310 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
311 $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
312 $page->rebuildPermissions();
314 return ($parent instanceof Book ? $parent : $parent->book);
318 * Copy an existing page in the system.
319 * Optionally providing a new parent via string identifier and a new name.
320 * @throws MoveOperationException
321 * @throws PermissionsException
323 public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
325 $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
326 if ($parent === null) {
327 throw new MoveOperationException('Book or chapter to move page into not found');
330 if (!userCan('page-create', $parent)) {
331 throw new PermissionsException('User does not have permission to create a page within the new parent');
334 $copyPage = $this->getNewDraftPage($parent);
335 $pageData = $page->getAttributes();
338 if (!empty($newName)) {
339 $pageData['name'] = $newName;
342 // Copy tags from previous page if set
344 $pageData['tags'] = [];
345 foreach ($page->tags as $tag) {
346 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
350 return $this->publishDraft($copyPage, $pageData);
354 * Find a page parent entity via a identifier string in the format:
357 * @throws MoveOperationException
359 protected function findParentByIdentifier(string $identifier): ?Entity
361 $stringExploded = explode(':', $identifier);
362 $entityType = $stringExploded[0];
363 $entityId = intval($stringExploded[1]);
365 if ($entityType !== 'book' && $entityType !== 'chapter') {
366 throw new MoveOperationException('Pages can only be in books or chapters');
369 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
370 return $parentClass::visible()->where('id', '=', $entityId)->first();
374 * Update the permissions of a page.
376 public function updatePermissions(Page $page, bool $restricted, Collection $permissions = null)
378 $this->baseRepo->updatePermissions($page, $restricted, $permissions);
382 * Change the page's parent to the given entity.
384 protected function changeParent(Page $page, Entity $parent)
386 $book = ($parent instanceof Book) ? $parent : $parent->book;
387 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
390 if ($page->book->id !== $book->id) {
391 $page->changeBook($book->id);
395 $book->rebuildPermissions();
399 * Get a page revision to update for the given page.
400 * Checks for an existing revisions before providing a fresh one.
402 protected function getPageRevisionToUpdate(Page $page): PageRevision
404 $drafts = $this->getUserDraftQuery($page)->get();
405 if ($drafts->count() > 0) {
406 return $drafts->first();
409 $draft = new PageRevision();
410 $draft->page_id = $page->id;
411 $draft->slug = $page->slug;
412 $draft->book_slug = $page->book->slug;
413 $draft->created_by = user()->id;
414 $draft->type = 'update_draft';
419 * Delete old revisions, for the given page, from the system.
421 protected function deleteOldRevisions(Page $page)
423 $revisionLimit = config('app.revision_limit');
424 if ($revisionLimit === false) {
428 $revisionsToDelete = PageRevision::query()
429 ->where('page_id', '=', $page->id)
430 ->orderBy('created_at', 'desc')
431 ->skip(intval($revisionLimit))
434 if ($revisionsToDelete->count() > 0) {
435 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
440 * Get a new priority for a page
442 protected function getNewPriority(Page $page): int
444 $parent = $page->getParent();
445 if ($parent instanceof Chapter) {
446 $lastPage = $parent->pages('desc')->first();
447 return $lastPage ? $lastPage->priority + 1 : 0;
450 return (new BookContents($page->book))->getLastPriority() + 1;
454 * Get the query to find the user's draft copies of the given page.
456 protected function getUserDraftQuery(Page $page)
458 return PageRevision::query()->where('created_by', '=', user()->id)
459 ->where('type', 'update_draft')
460 ->where('page_id', '=', $page->id)
461 ->orderBy('created_at', 'desc');