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;
180 $oldMarkdown = $page->markdown;
182 $this->updateTemplateStatusAndContentFromInput($page, $input);
183 $this->baseRepo->update($page, $input);
185 // Update with new details
186 $page->revision_count++;
189 // Remove all update drafts for this user & page.
190 $this->getUserDraftQuery($page)->delete();
192 // Save a revision after updating
193 $summary = trim($input['summary'] ?? "");
194 $htmlChanged = isset($input['html']) && $input['html'] !== $oldHtml;
195 $nameChanged = isset($input['name']) && $input['name'] !== $oldName;
196 $markdownChanged = isset($input['markdown']) && $input['markdown'] !== $oldMarkdown;
197 if ($htmlChanged || $nameChanged || $markdownChanged || $summary) {
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 (!empty($input['markdown'] ?? '')) {
213 $pageContent->setNewMarkdown($input['markdown']);
215 $pageContent->setNewHTML($input['html'] ?? '');
220 * Saves a page revision into the system.
222 protected function savePageRevision(Page $page, string $summary = null): PageRevision
224 $revision = new PageRevision($page->getAttributes());
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
247 if (isset($input['html'])) {
248 (new PageContent($page))->setNewHTML($input['html']);
255 // Otherwise save the data to a revision
256 $draft = $this->getPageRevisionToUpdate($page);
257 $draft->fill($input);
258 if (setting('app-editor') !== 'markdown') {
259 $draft->markdown = '';
267 * Destroy a page from the system.
270 public function destroy(Page $page)
272 $trashCan = new TrashCan();
273 $trashCan->softDestroyPage($page);
274 Activity::addForEntity($page, ActivityType::PAGE_DELETE);
275 $trashCan->autoClearOld();
279 * Restores a revision's content back into a page.
281 public function restoreRevision(Page $page, int $revisionId): Page
283 $page->revision_count++;
284 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
286 $page->fill($revision->toArray());
287 $content = new PageContent($page);
289 if (!empty($revision->markdown)) {
290 $content->setNewMarkdown($revision->markdown);
292 $content->setNewHTML($revision->html);
295 $page->updated_by = user()->id;
296 $page->refreshSlug();
298 $page->indexForSearch();
300 $summary = trans('entities.pages_revision_restored_from', ['id' => strval($revisionId), 'summary' => $revision->summary]);
301 $this->savePageRevision($page, $summary);
303 Activity::addForEntity($page, ActivityType::PAGE_RESTORE);
308 * Move the given page into a new parent book or chapter.
309 * The $parentIdentifier must be a string of the following format:
310 * 'book:<id>' (book:5)
311 * @throws MoveOperationException
312 * @throws PermissionsException
314 public function move(Page $page, string $parentIdentifier): Entity
316 $parent = $this->findParentByIdentifier($parentIdentifier);
317 if ($parent === null) {
318 throw new MoveOperationException('Book or chapter to move page into not found');
321 if (!userCan('page-create', $parent)) {
322 throw new PermissionsException('User does not have permission to create a page within the new parent');
325 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : null;
326 $page->changeBook($parent instanceof Book ? $parent->id : $parent->book->id);
327 $page->rebuildPermissions();
329 Activity::addForEntity($page, ActivityType::PAGE_MOVE);
334 * Copy an existing page in the system.
335 * Optionally providing a new parent via string identifier and a new name.
336 * @throws MoveOperationException
337 * @throws PermissionsException
339 public function copy(Page $page, string $parentIdentifier = null, string $newName = null): Page
341 $parent = $parentIdentifier ? $this->findParentByIdentifier($parentIdentifier) : $page->getParent();
342 if ($parent === null) {
343 throw new MoveOperationException('Book or chapter to move page into not found');
346 if (!userCan('page-create', $parent)) {
347 throw new PermissionsException('User does not have permission to create a page within the new parent');
350 $copyPage = $this->getNewDraftPage($parent);
351 $pageData = $page->getAttributes();
354 if (!empty($newName)) {
355 $pageData['name'] = $newName;
358 // Copy tags from previous page if set
360 $pageData['tags'] = [];
361 foreach ($page->tags as $tag) {
362 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
366 return $this->publishDraft($copyPage, $pageData);
370 * Find a page parent entity via a identifier string in the format:
373 * @throws MoveOperationException
375 protected function findParentByIdentifier(string $identifier): ?Entity
377 $stringExploded = explode(':', $identifier);
378 $entityType = $stringExploded[0];
379 $entityId = intval($stringExploded[1]);
381 if ($entityType !== 'book' && $entityType !== 'chapter') {
382 throw new MoveOperationException('Pages can only be in books or chapters');
385 $parentClass = $entityType === 'book' ? Book::class : Chapter::class;
386 return $parentClass::visible()->where('id', '=', $entityId)->first();
390 * Change the page's parent to the given entity.
392 protected function changeParent(Page $page, Entity $parent)
394 $book = ($parent instanceof Book) ? $parent : $parent->book;
395 $page->chapter_id = ($parent instanceof Chapter) ? $parent->id : 0;
398 if ($page->book->id !== $book->id) {
399 $page->changeBook($book->id);
403 $book->rebuildPermissions();
407 * Get a page revision to update for the given page.
408 * Checks for an existing revisions before providing a fresh one.
410 protected function getPageRevisionToUpdate(Page $page): PageRevision
412 $drafts = $this->getUserDraftQuery($page)->get();
413 if ($drafts->count() > 0) {
414 return $drafts->first();
417 $draft = new PageRevision();
418 $draft->page_id = $page->id;
419 $draft->slug = $page->slug;
420 $draft->book_slug = $page->book->slug;
421 $draft->created_by = user()->id;
422 $draft->type = 'update_draft';
427 * Delete old revisions, for the given page, from the system.
429 protected function deleteOldRevisions(Page $page)
431 $revisionLimit = config('app.revision_limit');
432 if ($revisionLimit === false) {
436 $revisionsToDelete = PageRevision::query()
437 ->where('page_id', '=', $page->id)
438 ->orderBy('created_at', 'desc')
439 ->skip(intval($revisionLimit))
442 if ($revisionsToDelete->count() > 0) {
443 PageRevision::query()->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
448 * Get a new priority for a page
450 protected function getNewPriority(Page $page): int
452 $parent = $page->getParent();
453 if ($parent instanceof Chapter) {
454 $lastPage = $parent->pages('desc')->first();
455 return $lastPage ? $lastPage->priority + 1 : 0;
458 return (new BookContents($page->book))->getLastPriority() + 1;
462 * Get the query to find the user's draft copies of the given page.
464 protected function getUserDraftQuery(Page $page)
466 return PageRevision::query()->where('created_by', '=', user()->id)
467 ->where('type', 'update_draft')
468 ->where('page_id', '=', $page->id)
469 ->orderBy('created_at', 'desc');