1 <?php namespace BookStack\Entities\Repos;
3 use BookStack\Actions\ActivityType;
4 use BookStack\Entities\Book;
5 use BookStack\Entities\Chapter;
6 use BookStack\Entities\Entity;
7 use BookStack\Entities\Managers\BookContents;
8 use BookStack\Entities\Managers\PageContent;
9 use BookStack\Entities\Managers\TrashCan;
10 use BookStack\Entities\Page;
11 use BookStack\Entities\PageRevision;
12 use BookStack\Exceptions\MoveOperationException;
13 use BookStack\Exceptions\NotFoundException;
14 use BookStack\Exceptions\NotifyException;
15 use BookStack\Exceptions\PermissionsException;
16 use BookStack\Facades\Activity;
18 use Illuminate\Database\Eloquent\Builder;
19 use Illuminate\Pagination\LengthAwarePaginator;
20 use Illuminate\Support\Collection;
28 * PageRepo constructor.
30 public function __construct(BaseRepo $baseRepo)
32 $this->baseRepo = $baseRepo;
37 * @throws NotFoundException
39 public function getById(int $id): Page
41 $page = Page::visible()->with(['book'])->find($id);
44 throw new NotFoundException(trans('errors.page_not_found'));
51 * Get a page its book and own slug.
52 * @throws NotFoundException
54 public function getBySlug(string $bookSlug, string $pageSlug): Page
56 $page = Page::visible()->whereSlugs($bookSlug, $pageSlug)->first();
59 throw new NotFoundException(trans('errors.page_not_found'));
66 * Get a page by its old slug but checking the revisions table
67 * for the last revision that matched the given page and book slug.
69 public function getByOldSlug(string $bookSlug, string $pageSlug): ?Page
71 $revision = PageRevision::query()
72 ->whereHas('page', function (Builder $query) {
75 ->where('slug', '=', $pageSlug)
76 ->where('type', '=', 'version')
77 ->where('book_slug', '=', $bookSlug)
78 ->orderBy('created_at', 'desc')
81 return $revision ? $revision->page : null;
85 * Get pages that have been marked as a template.
87 public function getTemplates(int $count = 10, int $page = 1, string $search = ''): LengthAwarePaginator
89 $query = Page::visible()
90 ->where('template', '=', true)
91 ->orderBy('name', 'asc')
92 ->skip(($page - 1) * $count)
96 $query->where('name', 'like', '%' . $search . '%');
99 $paginator = $query->paginate($count, ['*'], 'page', $page);
100 $paginator->withPath('/templates');
106 * Get a parent item via slugs.
108 public function getParentFromSlugs(string $bookSlug, string $chapterSlug = null): Entity
110 if ($chapterSlug !== null) {
111 return $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->firstOrFail();
114 return Book::visible()->where('slug', '=', $bookSlug)->firstOrFail();
118 * Get the draft copy of the given page for the current user.
120 public function getUserDraft(Page $page): ?PageRevision
122 $revision = $this->getUserDraftQuery($page)->first();
127 * Get a new draft page belonging to the given parent entity.
129 public function getNewDraftPage(Entity $parent)
131 $page = (new Page())->forceFill([
132 'name' => trans('entities.pages_initial_name'),
133 'created_by' => user()->id,
134 'updated_by' => user()->id,
138 if ($parent instanceof Chapter) {
139 $page->chapter_id = $parent->id;
140 $page->book_id = $parent->book_id;
142 $page->book_id = $parent->id;
146 $page->refresh()->rebuildPermissions();
151 * Publish a draft page to make it a live, non-draft page.
153 public function publishDraft(Page $draft, array $input): Page
155 $this->baseRepo->update($draft, $input);
156 if (isset($input['template']) && userCan('templates-manage')) {
157 $draft->template = ($input['template'] === 'true');
160 $pageContent = new PageContent($draft);
161 $pageContent->setNewHTML($input['html']);
162 $draft->draft = false;
163 $draft->revision_count = 1;
164 $draft->priority = $this->getNewPriority($draft);
165 $draft->refreshSlug();
168 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
169 $draft->indexForSearch();
172 Activity::addForEntity($draft, ActivityType::PAGE_CREATE);
177 * Update a page in the system.
179 public function update(Page $page, array $input): Page
181 // Hold the old details to compare later
182 $oldHtml = $page->html;
183 $oldName = $page->name;
185 if (isset($input['template']) && userCan('templates-manage')) {
186 $page->template = ($input['template'] === 'true');
189 $pageContent = new PageContent($page);
190 $pageContent->setNewHTML($input['html']);
191 $this->baseRepo->update($page, $input);
193 // Update with new details
194 $page->revision_count++;
196 if (setting('app-editor') !== 'markdown') {
197 $page->markdown = '';
202 // Remove all update drafts for this user & page.
203 $this->getUserDraftQuery($page)->delete();
205 // Save a revision after updating
206 $summary = $input['summary'] ?? null;
207 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
208 $this->savePageRevision($page, $summary);
211 Activity::addForEntity($page, ActivityType::PAGE_UPDATE);
216 * Saves a page revision into the system.
218 protected function savePageRevision(Page $page, string $summary = null)
220 $revision = new PageRevision($page->getAttributes());
222 if (setting('app-editor') !== 'markdown') {
223 $revision->markdown = '';
226 $revision->page_id = $page->id;
227 $revision->slug = $page->slug;
228 $revision->book_slug = $page->book->slug;
229 $revision->created_by = user()->id;
230 $revision->created_at = $page->updated_at;
231 $revision->type = 'version';
232 $revision->summary = $summary;
233 $revision->revision_number = $page->revision_count;
236 $this->deleteOldRevisions($page);
241 * Save a page update draft.
243 public function updatePageDraft(Page $page, array $input)
245 // If the page itself is a draft simply update that
248 if (isset($input['html'])) {
249 $content = new PageContent($page);
250 $content->setNewHTML($input['html']);
256 // Otherwise save the data to a revision
257 $draft = $this->getPageRevisionToUpdate($page);
258 $draft->fill($input);
259 if (setting('app-editor') !== 'markdown') {
260 $draft->markdown = '';
268 * Destroy a page from the system.
271 public function destroy(Page $page)
273 $trashCan = new TrashCan();
274 $trashCan->softDestroyPage($page);
275 Activity::addForEntity($page, ActivityType::PAGE_DELETE);
276 $trashCan->autoClearOld();
280 * Restores a revision's content back into a page.
282 public function restoreRevision(Page $page, int $revisionId): Page
284 $page->revision_count++;
285 $this->savePageRevision($page);
287 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
288 $page->fill($revision->toArray());
289 $content = new PageContent($page);
290 $content->setNewHTML($revision->html);
291 $page->updated_by = user()->id;
292 $page->refreshSlug();
295 $page->indexForSearch();
296 Activity::addForEntity($page, ActivityType::PAGE_RESTORE);
301 * Move the given page into a new parent book or chapter.
302 * The $parentIdentifier must be a string of the following format:
303 * 'book:<id>' (book:5)
304 * @throws MoveOperationException
305 * @throws PermissionsException
307 public function move(Page $page, string $parentIdentifier): Entity
309 $parent = $this->findParentByIdentifier($parentIdentifier);
310 if ($parent === null) {
311 throw new MoveOperationException('Book or chapter to move page into not found');
314 if (!userCan('page-create', $parent)) {
315 throw new PermissionsException('User does not have permission to create a page within the new parent');
318 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
319 $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
320 $page->rebuildPermissions();
322 Activity::addForEntity($page, ActivityType::PAGE_MOVE);
327 * Copy an existing page in the system.
328 * Optionally providing a new parent via string identifier and a new name.
329 * @throws MoveOperationException
330 * @throws PermissionsException
332 public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
334 $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
335 if ($parent === null) {
336 throw new MoveOperationException('Book or chapter to move page into not found');
339 if (!userCan('page-create', $parent)) {
340 throw new PermissionsException('User does not have permission to create a page within the new parent');
343 $copyPage = $this->getNewDraftPage($parent);
344 $pageData = $page->getAttributes();
347 if (!empty($newName)) {
348 $pageData['name'] = $newName;
351 // Copy tags from previous page if set
353 $pageData['tags'] = [];
354 foreach ($page->tags as $tag) {
355 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
359 return $this->publishDraft($copyPage, $pageData);
363 * Find a page parent entity via a identifier string in the format:
366 * @throws MoveOperationException
368 protected function findParentByIdentifier(string $identifier): ?Entity
370 $stringExploded = explode(':', $identifier);
371 $entityType = $stringExploded[0];
372 $entityId = intval($stringExploded[1]);
374 if ($entityType !== 'book' && $entityType !== 'chapter') {
375 throw new MoveOperationException('Pages can only be in books or chapters');
378 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
379 return $parentClass::visible()->where('id', '=', $entityId)->first();
383 * Update the permissions of a page.
385 public function updatePermissions(Page $page, bool $restricted, Collection $permissions = null)
387 $this->baseRepo->updatePermissions($page, $restricted, $permissions);
391 * Change the page's parent to the given entity.
393 protected function changeParent(Page $page, Entity $parent)
395 $book = ($parent instanceof Book) ? $parent : $parent->book;
396 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
399 if ($page->book->id !== $book->id) {
400 $page->changeBook($book->id);
404 $book->rebuildPermissions();
408 * Get a page revision to update for the given page.
409 * Checks for an existing revisions before providing a fresh one.
411 protected function getPageRevisionToUpdate(Page $page): PageRevision
413 $drafts = $this->getUserDraftQuery($page)->get();
414 if ($drafts->count() > 0) {
415 return $drafts->first();
418 $draft = new PageRevision();
419 $draft->page_id = $page->id;
420 $draft->slug = $page->slug;
421 $draft->book_slug = $page->book->slug;
422 $draft->created_by = user()->id;
423 $draft->type = 'update_draft';
428 * Delete old revisions, for the given page, from the system.
430 protected function deleteOldRevisions(Page $page)
432 $revisionLimit = config('app.revision_limit');
433 if ($revisionLimit === false) {
437 $revisionsToDelete = PageRevision::query()
438 ->where('page_id', '=', $page->id)
439 ->orderBy('created_at', 'desc')
440 ->skip(intval($revisionLimit))
443 if ($revisionsToDelete->count() > 0) {
444 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
449 * Get a new priority for a page
451 protected function getNewPriority(Page $page): int
453 $parent = $page->getParent();
454 if ($parent instanceof Chapter) {
455 $lastPage = $parent->pages('desc')->first();
456 return $lastPage ? $lastPage->priority + 1 : 0;
459 return (new BookContents($page->book))->getLastPriority() + 1;
463 * Get the query to find the user's draft copies of the given page.
465 protected function getUserDraftQuery(Page $page)
467 return PageRevision::query()->where('created_by', '=', user()->id)
468 ->where('type', 'update_draft')
469 ->where('page_id', '=', $page->id)
470 ->orderBy('created_at', 'desc');