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 'owned_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 $this->updateTemplateStatusAndContentFromInput($draft, $input);
158 $draft->draft = false;
159 $draft->revision_count = 1;
160 $draft->priority = $this->getNewPriority($draft);
161 $draft->refreshSlug();
164 $this->savePageRevision($draft, trans('entities.pages_initial_revision'));
165 $draft->indexForSearch();
168 Activity::addForEntity($draft, ActivityType::PAGE_CREATE);
173 * Update a page in the system.
175 public function update(Page $page, array $input): Page
177 // Hold the old details to compare later
178 $oldHtml = $page->html;
179 $oldName = $page->name;
181 $this->updateTemplateStatusAndContentFromInput($page, $input);
182 $this->baseRepo->update($page, $input);
184 // Update with new details
185 $page->revision_count++;
187 if (setting('app-editor') !== 'markdown') {
188 $page->markdown = '';
193 // Remove all update drafts for this user & page.
194 $this->getUserDraftQuery($page)->delete();
196 // Save a revision after updating
197 $summary = $input['summary'] ?? null;
198 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $summary !== null) {
199 $this->savePageRevision($page, $summary);
202 Activity::addForEntity($page, ActivityType::PAGE_UPDATE);
206 protected function updateTemplateStatusAndContentFromInput(Page $page, array $input)
208 if (isset($input['template']) && userCan('templates-manage')) {
209 $page->template = ($input['template'] === 'true');
212 $pageContent = new PageContent($page);
213 if (!empty($input['markdown'] ?? '')) {
214 $pageContent->setNewMarkdown($input['markdown']);
216 $pageContent->setNewHTML($input['html']);
221 * Saves a page revision into the system.
223 protected function savePageRevision(Page $page, string $summary = null): PageRevision
225 $revision = new PageRevision($page->getAttributes());
227 if (setting('app-editor') !== 'markdown') {
228 $revision->markdown = '';
231 $revision->page_id = $page->id;
232 $revision->slug = $page->slug;
233 $revision->book_slug = $page->book->slug;
234 $revision->created_by = user()->id;
235 $revision->created_at = $page->updated_at;
236 $revision->type = 'version';
237 $revision->summary = $summary;
238 $revision->revision_number = $page->revision_count;
241 $this->deleteOldRevisions($page);
246 * Save a page update draft.
248 public function updatePageDraft(Page $page, array $input)
250 // If the page itself is a draft simply update that
252 if (isset($input['html'])) {
253 (new PageContent($page))->setNewHTML($input['html']);
260 // Otherwise save the data to a revision
261 $draft = $this->getPageRevisionToUpdate($page);
262 $draft->fill($input);
263 if (setting('app-editor') !== 'markdown') {
264 $draft->markdown = '';
272 * Destroy a page from the system.
275 public function destroy(Page $page)
277 $trashCan = new TrashCan();
278 $trashCan->softDestroyPage($page);
279 Activity::addForEntity($page, ActivityType::PAGE_DELETE);
280 $trashCan->autoClearOld();
284 * Restores a revision's content back into a page.
286 public function restoreRevision(Page $page, int $revisionId): Page
288 $page->revision_count++;
289 $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();
297 $page->indexForSearch();
299 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
300 $this->savePageRevision($page, $summary);
302 Activity::addForEntity($page, ActivityType::PAGE_RESTORE);
307 * Move the given page into a new parent book or chapter.
308 * The $parentIdentifier must be a string of the following format:
309 * 'book:<id>' (book:5)
310 * @throws MoveOperationException
311 * @throws PermissionsException
313 public function move(Page $page, string $parentIdentifier): Entity
315 $parent = $this->findParentByIdentifier($parentIdentifier);
316 if ($parent === null) {
317 throw new MoveOperationException('Book or chapter to move page into not found');
320 if (!userCan('page-create', $parent)) {
321 throw new PermissionsException('User does not have permission to create a page within the new parent');
324 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
325 $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
326 $page->rebuildPermissions();
328 Activity::addForEntity($page, ActivityType::PAGE_MOVE);
333 * Copy an existing page in the system.
334 * Optionally providing a new parent via string identifier and a new name.
335 * @throws MoveOperationException
336 * @throws PermissionsException
338 public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
340 $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
341 if ($parent === null) {
342 throw new MoveOperationException('Book or chapter to move page into not found');
345 if (!userCan('page-create', $parent)) {
346 throw new PermissionsException('User does not have permission to create a page within the new parent');
349 $copyPage = $this->getNewDraftPage($parent);
350 $pageData = $page->getAttributes();
353 if (!empty($newName)) {
354 $pageData['name'] = $newName;
357 // Copy tags from previous page if set
359 $pageData['tags'] = [];
360 foreach ($page->tags as $tag) {
361 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
365 return $this->publishDraft($copyPage, $pageData);
369 * Find a page parent entity via a identifier string in the format:
372 * @throws MoveOperationException
374 protected function findParentByIdentifier(string $identifier): ?Entity
376 $stringExploded = explode(':', $identifier);
377 $entityType = $stringExploded[0];
378 $entityId = intval($stringExploded[1]);
380 if ($entityType !== 'book' && $entityType !== 'chapter') {
381 throw new MoveOperationException('Pages can only be in books or chapters');
384 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
385 return $parentClass::visible()->where('id', '=', $entityId)->first();
389 * Change the page's parent to the given entity.
391 protected function changeParent(Page $page, Entity $parent)
393 $book = ($parent instanceof Book) ? $parent : $parent->book;
394 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
397 if ($page->book->id !== $book->id) {
398 $page->changeBook($book->id);
402 $book->rebuildPermissions();
406 * Get a page revision to update for the given page.
407 * Checks for an existing revisions before providing a fresh one.
409 protected function getPageRevisionToUpdate(Page $page): PageRevision
411 $drafts = $this->getUserDraftQuery($page)->get();
412 if ($drafts->count() > 0) {
413 return $drafts->first();
416 $draft = new PageRevision();
417 $draft->page_id = $page->id;
418 $draft->slug = $page->slug;
419 $draft->book_slug = $page->book->slug;
420 $draft->created_by = user()->id;
421 $draft->type = 'update_draft';
426 * Delete old revisions, for the given page, from the system.
428 protected function deleteOldRevisions(Page $page)
430 $revisionLimit = config('app.revision_limit');
431 if ($revisionLimit === false) {
435 $revisionsToDelete = PageRevision::query()
436 ->where('page_id', '=', $page->id)
437 ->orderBy('created_at', 'desc')
438 ->skip(intval($revisionLimit))
441 if ($revisionsToDelete->count() > 0) {
442 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
447 * Get a new priority for a page
449 protected function getNewPriority(Page $page): int
451 $parent = $page->getParent();
452 if ($parent instanceof Chapter) {
453 $lastPage = $parent->pages('desc')->first();
454 return $lastPage ? $lastPage->priority + 1 : 0;
457 return (new BookContents($page->book))->getLastPriority() + 1;
461 * Get the query to find the user's draft copies of the given page.
463 protected function getUserDraftQuery(Page $page)
465 return PageRevision::query()->where('created_by', '=', user()->id)
466 ->where('type', 'update_draft')
467 ->where('page_id', '=', $page->id)
468 ->orderBy('created_at', 'desc');