1 <?php namespace BookStack\Repos;
6 use BookStack\Exceptions\NotFoundException;
7 use BookStack\Exceptions\NotifyException;
9 use BookStack\PageRevision;
10 use BookStack\Services\AttachmentService;
11 use BookStack\Services\PermissionService;
12 use BookStack\Services\SearchService;
13 use BookStack\Services\ViewService;
17 use Illuminate\Support\Collection;
40 protected $pageRevision;
43 * Base entity instances keyed by type
49 * @var PermissionService
51 protected $permissionService;
56 protected $viewService;
66 protected $searchService;
69 * EntityRepo constructor.
71 * @param Chapter $chapter
73 * @param PageRevision $pageRevision
74 * @param ViewService $viewService
75 * @param PermissionService $permissionService
76 * @param TagRepo $tagRepo
77 * @param SearchService $searchService
79 public function __construct(
83 PageRevision $pageRevision,
84 ViewService $viewService,
85 PermissionService $permissionService,
87 SearchService $searchService
90 $this->chapter = $chapter;
92 $this->pageRevision = $pageRevision;
94 'page' => $this->page,
95 'chapter' => $this->chapter,
98 $this->viewService = $viewService;
99 $this->permissionService = $permissionService;
100 $this->tagRepo = $tagRepo;
101 $this->searchService = $searchService;
105 * Get an entity instance via type.
109 protected function getEntity($type)
111 return $this->entities[strtolower($type)];
115 * Base query for searching entities via permission system
116 * @param string $type
117 * @param bool $allowDrafts
118 * @return \Illuminate\Database\Query\Builder
120 protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
122 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), $permission);
123 if (strtolower($type) === 'page' && !$allowDrafts) {
124 $q = $q->where('draft', '=', false);
130 * Check if an entity with the given id exists.
135 public function exists($type, $id)
137 return $this->entityQuery($type)->where('id', '=', $id)->exists();
141 * Get an entity by ID
142 * @param string $type
144 * @param bool $allowDrafts
145 * @param bool $ignorePermissions
148 public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
150 if ($ignorePermissions) {
151 $entity = $this->getEntity($type);
152 return $entity->newQuery()->find($id);
154 return $this->entityQuery($type, $allowDrafts)->find($id);
158 * Get an entity by its url slug.
159 * @param string $type
160 * @param string $slug
161 * @param string|bool $bookSlug
163 * @throws NotFoundException
165 public function getBySlug($type, $slug, $bookSlug = false)
167 $q = $this->entityQuery($type)->where('slug', '=', $slug);
169 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
170 $q = $q->where('book_id', '=', function ($query) use ($bookSlug) {
172 ->from($this->book->getTable())
173 ->where('slug', '=', $bookSlug)->limit(1);
176 $entity = $q->first();
177 if ($entity === null) {
178 throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
185 * Search through page revisions and retrieve the last page in the
186 * current book that has a slug equal to the one given.
187 * @param string $pageSlug
188 * @param string $bookSlug
191 public function getPageByOldSlug($pageSlug, $bookSlug)
193 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
194 ->whereHas('page', function ($query) {
195 $this->permissionService->enforceEntityRestrictions('page', $query);
197 ->where('type', '=', 'version')
198 ->where('book_slug', '=', $bookSlug)
199 ->orderBy('created_at', 'desc')
200 ->with('page')->first();
201 return $revision !== null ? $revision->page : null;
205 * Get all entities of a type with the given permission, limited by count unless count is false.
206 * @param string $type
207 * @param integer|bool $count
208 * @param string $permission
211 public function getAll($type, $count = 20, $permission = 'view')
213 $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
214 if ($count !== false) {
215 $q = $q->take($count);
221 * Get all entities in a paginated format
224 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
226 public function getAllPaginated($type, $count = 10)
228 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
232 * Get the most recently created entities of the given type.
233 * @param string $type
236 * @param bool|callable $additionalQuery
239 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
241 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
242 ->orderBy('created_at', 'desc');
243 if (strtolower($type) === 'page') {
244 $query = $query->where('draft', '=', false);
246 if ($additionalQuery !== false && is_callable($additionalQuery)) {
247 $additionalQuery($query);
249 return $query->skip($page * $count)->take($count)->get();
253 * Get the most recently updated entities of the given type.
254 * @param string $type
257 * @param bool|callable $additionalQuery
260 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
262 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
263 ->orderBy('updated_at', 'desc');
264 if (strtolower($type) === 'page') {
265 $query = $query->where('draft', '=', false);
267 if ($additionalQuery !== false && is_callable($additionalQuery)) {
268 $additionalQuery($query);
270 return $query->skip($page * $count)->take($count)->get();
274 * Get the most recently viewed entities.
275 * @param string|bool $type
280 public function getRecentlyViewed($type, $count = 10, $page = 0)
282 $filter = is_bool($type) ? false : $this->getEntity($type);
283 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
287 * Get the latest pages added to the system with pagination.
288 * @param string $type
292 public function getRecentlyCreatedPaginated($type, $count = 20)
294 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
298 * Get the latest pages added to the system with pagination.
299 * @param string $type
303 public function getRecentlyUpdatedPaginated($type, $count = 20)
305 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
309 * Get the most popular entities base on all views.
310 * @param string|bool $type
315 public function getPopular($type, $count = 10, $page = 0)
317 $filter = is_bool($type) ? false : $this->getEntity($type);
318 return $this->viewService->getPopular($count, $page, $filter);
322 * Get draft pages owned by the current user.
326 public function getUserDraftPages($count = 20, $page = 0)
328 return $this->page->where('draft', '=', true)
329 ->where('created_by', '=', user()->id)
330 ->orderBy('updated_at', 'desc')
331 ->skip($count * $page)->take($count)->get();
335 * Get all child objects of a book.
336 * Returns a sorted collection of Pages and Chapters.
337 * Loads the book slug onto child elements to prevent access database access for getting the slug.
339 * @param bool $filterDrafts
340 * @param bool $renderPages
343 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
345 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
350 foreach ($q as $index => $rawEntity) {
351 if ($rawEntity->entity_type === 'BookStack\\Page') {
352 $entities[$index] = $this->page->newFromBuilder($rawEntity);
354 $entities[$index]->html = $rawEntity->html;
355 $entities[$index]->html = $this->renderPage($entities[$index]);
357 } else if ($rawEntity->entity_type === 'BookStack\\Chapter') {
358 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
359 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
360 $parents[$key] = $entities[$index];
361 $parents[$key]->setAttribute('pages', collect());
363 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
364 $tree[] = $entities[$index];
366 $entities[$index]->book = $book;
369 foreach ($entities as $entity) {
370 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
373 $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id;
374 if (!isset($parents[$parentKey])) {
378 $chapter = $parents[$parentKey];
379 $chapter->pages->push($entity);
382 return collect($tree);
386 * Get the child items for a chapter sorted by priority but
387 * with draft items floated to the top.
388 * @param Chapter $chapter
389 * @return \Illuminate\Database\Eloquent\Collection|static[]
391 public function getChapterChildren(Chapter $chapter)
393 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
394 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
399 * Get the next sequential priority for a new child element in the given book.
403 public function getNewBookPriority(Book $book)
405 $lastElem = $this->getBookChildren($book)->pop();
406 return $lastElem ? $lastElem->priority + 1 : 0;
410 * Get a new priority for a new page to be added to the given chapter.
411 * @param Chapter $chapter
414 public function getNewChapterPriority(Chapter $chapter)
416 $lastPage = $chapter->pages('DESC')->first();
417 return $lastPage !== null ? $lastPage->priority + 1 : 0;
421 * Find a suitable slug for an entity.
422 * @param string $type
423 * @param string $name
424 * @param bool|integer $currentId
425 * @param bool|integer $bookId Only pass if type is not a book
428 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
430 $slug = $this->nameToSlug($name);
431 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
432 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
438 * Check if a slug already exists in the database.
439 * @param string $type
440 * @param string $slug
441 * @param bool|integer $currentId
442 * @param bool|integer $bookId
445 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
447 $query = $this->getEntity($type)->where('slug', '=', $slug);
448 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
449 $query = $query->where('book_id', '=', $bookId);
452 $query = $query->where('id', '!=', $currentId);
454 return $query->count() > 0;
458 * Updates entity restrictions from a request
460 * @param Entity $entity
462 public function updateEntityPermissionsFromRequest($request, Entity $entity)
464 $entity->restricted = $request->get('restricted', '') === 'true';
465 $entity->permissions()->delete();
467 if ($request->filled('restrictions')) {
468 foreach ($request->get('restrictions') as $roleId => $restrictions) {
469 foreach ($restrictions as $action => $value) {
470 $entity->permissions()->create([
471 'role_id' => $roleId,
472 'action' => strtolower($action)
479 $this->permissionService->buildJointPermissionsForEntity($entity);
485 * Create a new entity from request input.
486 * Used for books and chapters.
487 * @param string $type
488 * @param array $input
489 * @param bool|Book $book
492 public function createFromInput($type, $input = [], $book = false)
494 $isChapter = strtolower($type) === 'chapter';
495 $entityModel = $this->getEntity($type)->newInstance($input);
496 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
497 $entityModel->created_by = user()->id;
498 $entityModel->updated_by = user()->id;
499 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
501 if (isset($input['tags'])) {
502 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
505 $this->permissionService->buildJointPermissionsForEntity($entityModel);
506 $this->searchService->indexEntity($entityModel);
511 * Update entity details from request input.
512 * Used for books and chapters
513 * @param string $type
514 * @param Entity $entityModel
515 * @param array $input
518 public function updateFromInput($type, Entity $entityModel, $input = [])
520 if ($entityModel->name !== $input['name']) {
521 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
523 $entityModel->fill($input);
524 $entityModel->updated_by = user()->id;
525 $entityModel->save();
527 if (isset($input['tags'])) {
528 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
531 $this->permissionService->buildJointPermissionsForEntity($entityModel);
532 $this->searchService->indexEntity($entityModel);
537 * Change the book that an entity belongs to.
538 * @param string $type
539 * @param integer $newBookId
540 * @param Entity $entity
541 * @param bool $rebuildPermissions
544 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
546 $entity->book_id = $newBookId;
547 // Update related activity
548 foreach ($entity->activity as $activity) {
549 $activity->book_id = $newBookId;
552 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
555 // Update all child pages if a chapter
556 if (strtolower($type) === 'chapter') {
557 foreach ($entity->pages as $page) {
558 $this->changeBook('page', $newBookId, $page, false);
562 // Update permissions if applicable
563 if ($rebuildPermissions) {
564 $entity->load('book');
565 $this->permissionService->buildJointPermissionsForEntity($entity->book);
572 * Alias method to update the book jointPermissions in the PermissionService.
575 public function buildJointPermissionsForBook(Book $book)
577 $this->permissionService->buildJointPermissionsForEntity($book);
581 * Format a name as a url slug.
585 protected function nameToSlug($name)
587 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
588 $slug = preg_replace('/\s{2,}/', ' ', $slug);
589 $slug = str_replace(' ', '-', $slug);
591 $slug = substr(md5(rand(1, 500)), 0, 5);
597 * Publish a draft page to make it a normal page.
598 * Sets the slug and updates the content.
599 * @param Page $draftPage
600 * @param array $input
603 public function publishPageDraft(Page $draftPage, array $input)
605 $draftPage->fill($input);
607 // Save page tags if present
608 if (isset($input['tags'])) {
609 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
612 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
613 $draftPage->html = $this->formatHtml($input['html']);
614 $draftPage->text = $this->pageToPlainText($draftPage);
615 $draftPage->draft = false;
616 $draftPage->revision_count = 1;
619 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
620 $this->searchService->indexEntity($draftPage);
625 * Saves a page revision into the system.
627 * @param null|string $summary
628 * @return PageRevision
630 public function savePageRevision(Page $page, $summary = null)
632 $revision = $this->pageRevision->newInstance($page->toArray());
633 if (setting('app-editor') !== 'markdown') {
634 $revision->markdown = '';
636 $revision->page_id = $page->id;
637 $revision->slug = $page->slug;
638 $revision->book_slug = $page->book->slug;
639 $revision->created_by = user()->id;
640 $revision->created_at = $page->updated_at;
641 $revision->type = 'version';
642 $revision->summary = $summary;
643 $revision->revision_number = $page->revision_count;
646 // Clear old revisions
647 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
648 $this->pageRevision->where('page_id', '=', $page->id)
649 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
656 * Formats a page's html to be tagged correctly
658 * @param string $htmlText
661 protected function formatHtml($htmlText)
663 if ($htmlText == '') {
666 libxml_use_internal_errors(true);
667 $doc = new DOMDocument();
668 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
670 $container = $doc->documentElement;
671 $body = $container->childNodes->item(0);
672 $childNodes = $body->childNodes;
674 // Ensure no duplicate ids are used
677 foreach ($childNodes as $index => $childNode) {
678 /** @var \DOMElement $childNode */
679 if (get_class($childNode) !== 'DOMElement') {
683 // Overwrite id if not a BookStack custom id
684 if ($childNode->hasAttribute('id')) {
685 $id = $childNode->getAttribute('id');
686 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
692 // Create an unique id for the element
693 // Uses the content as a basis to ensure output is the same every time
694 // the same content is passed through.
695 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
696 $newId = urlencode($contentId);
698 while (in_array($newId, $idArray)) {
699 $newId = urlencode($contentId . '-' . $loopIndex);
703 $childNode->setAttribute('id', $newId);
707 // Generate inner html as a string
709 foreach ($childNodes as $childNode) {
710 $html .= $doc->saveHTML($childNode);
718 * Render the page for viewing, Parsing and performing features such as page transclusion.
720 * @param bool $ignorePermissions
721 * @return mixed|string
723 public function renderPage(Page $page, $ignorePermissions = false)
725 $content = $page->html;
726 if (!config('app.allow_content_scripts')) {
727 $content = $this->escapeScripts($content);
731 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
732 if (count($matches[0]) === 0) {
736 $topLevelTags = ['table', 'ul', 'ol'];
737 foreach ($matches[1] as $index => $includeId) {
738 $splitInclude = explode('#', $includeId, 2);
739 $pageId = intval($splitInclude[0]);
740 if (is_nan($pageId)) {
744 $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
745 if ($matchedPage === null) {
746 $content = str_replace($matches[0][$index], '', $content);
750 if (count($splitInclude) === 1) {
751 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
755 $doc = new DOMDocument();
756 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
757 $matchingElem = $doc->getElementById($splitInclude[1]);
758 if ($matchingElem === null) {
759 $content = str_replace($matches[0][$index], '', $content);
763 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
765 $innerContent .= $doc->saveHTML($matchingElem);
767 foreach ($matchingElem->childNodes as $childNode) {
768 $innerContent .= $doc->saveHTML($childNode);
771 $content = str_replace($matches[0][$index], trim($innerContent), $content);
778 * Escape script tags within HTML content.
779 * @param string $html
782 protected function escapeScripts(string $html)
784 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
786 preg_match_all($scriptSearchRegex, $html, $matches);
787 if (count($matches) === 0) {
791 foreach ($matches[0] as $match) {
792 $html = str_replace($match, htmlentities($match), $html);
798 * Get the plain text version of a page's content.
802 public function pageToPlainText(Page $page)
804 $html = $this->renderPage($page);
805 return strip_tags($html);
809 * Get a new draft page instance.
811 * @param Chapter|bool $chapter
814 public function getDraftPage(Book $book, $chapter = false)
816 $page = $this->page->newInstance();
817 $page->name = trans('entities.pages_initial_name');
818 $page->created_by = user()->id;
819 $page->updated_by = user()->id;
823 $page->chapter_id = $chapter->id;
826 $book->pages()->save($page);
827 $page = $this->page->find($page->id);
828 $this->permissionService->buildJointPermissionsForEntity($page);
833 * Search for image usage within page content.
834 * @param $imageString
837 public function searchForImage($imageString)
839 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
840 foreach ($pages as $page) {
841 $page->url = $page->getUrl();
845 return count($pages) > 0 ? $pages : false;
849 * Parse the headers on the page to get a navigation menu
850 * @param String $pageContent
853 public function getPageNav($pageContent)
855 if ($pageContent == '') {
858 libxml_use_internal_errors(true);
859 $doc = new DOMDocument();
860 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
861 $xPath = new DOMXPath($doc);
862 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
864 if (is_null($headers)) {
869 foreach ($headers as $header) {
870 $text = $header->nodeValue;
872 'nodeName' => strtolower($header->nodeName),
873 'level' => intval(str_replace('h', '', $header->nodeName)),
874 'link' => '#' . $header->getAttribute('id'),
875 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
879 // Normalise headers if only smaller headers have been used
880 if (count($tree) > 0) {
881 $minLevel = $tree->pluck('level')->min();
882 $tree = $tree->map(function ($header) use ($minLevel) {
883 $header['level'] -= ($minLevel - 2);
887 return $tree->toArray();
891 * Updates a page with any fillable data and saves it into the database.
893 * @param int $book_id
894 * @param array $input
897 public function updatePage(Page $page, $book_id, $input)
899 // Hold the old details to compare later
900 $oldHtml = $page->html;
901 $oldName = $page->name;
903 // Prevent slug being updated if no name change
904 if ($page->name !== $input['name']) {
905 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
908 // Save page tags if present
909 if (isset($input['tags'])) {
910 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
913 // Update with new details
914 $userId = user()->id;
916 $page->html = $this->formatHtml($input['html']);
917 $page->text = $this->pageToPlainText($page);
918 if (setting('app-editor') !== 'markdown') {
919 $page->markdown = '';
921 $page->updated_by = $userId;
922 $page->revision_count++;
925 // Remove all update drafts for this user & page.
926 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
928 // Save a revision after updating
929 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
930 $this->savePageRevision($page, $input['summary']);
933 $this->searchService->indexEntity($page);
939 * The base query for getting user update drafts.
944 protected function userUpdatePageDraftsQuery(Page $page, $userId)
946 return $this->pageRevision->where('created_by', '=', $userId)
947 ->where('type', 'update_draft')
948 ->where('page_id', '=', $page->id)
949 ->orderBy('created_at', 'desc');
953 * Checks whether a user has a draft version of a particular page or not.
958 public function hasUserGotPageDraft(Page $page, $userId)
960 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
964 * Get the latest updated draft revision for a particular page and user.
969 public function getUserPageDraft(Page $page, $userId)
971 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
975 * Get the notification message that informs the user that they are editing a draft page.
976 * @param PageRevision $draft
979 public function getUserPageDraftMessage(PageRevision $draft)
981 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
982 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
985 return $message . "\n" . trans('entities.pages_draft_edited_notification');
989 * Check if a page is being actively editing.
990 * Checks for edits since last page updated.
991 * Passing in a minuted range will check for edits
992 * within the last x minutes.
994 * @param null $minRange
997 public function isPageEditingActive(Page $page, $minRange = null)
999 $draftSearch = $this->activePageEditingQuery($page, $minRange);
1000 return $draftSearch->count() > 0;
1004 * A query to check for active update drafts on a particular page.
1006 * @param null $minRange
1009 protected function activePageEditingQuery(Page $page, $minRange = null)
1011 $query = $this->pageRevision->where('type', '=', 'update_draft')
1012 ->where('page_id', '=', $page->id)
1013 ->where('updated_at', '>', $page->updated_at)
1014 ->where('created_by', '!=', user()->id)
1015 ->with('createdBy');
1017 if ($minRange !== null) {
1018 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1025 * Restores a revision's content back into a page.
1028 * @param int $revisionId
1031 public function restorePageRevision(Page $page, Book $book, $revisionId)
1033 $page->revision_count++;
1034 $this->savePageRevision($page);
1035 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
1036 $page->fill($revision->toArray());
1037 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1038 $page->text = $this->pageToPlainText($page);
1039 $page->updated_by = user()->id;
1041 $this->searchService->indexEntity($page);
1047 * Save a page update draft.
1049 * @param array $data
1050 * @return PageRevision|Page
1052 public function updatePageDraft(Page $page, $data = [])
1054 // If the page itself is a draft simply update that
1057 if (isset($data['html'])) {
1058 $page->text = $this->pageToPlainText($page);
1064 // Otherwise save the data to a revision
1065 $userId = user()->id;
1066 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1068 if ($drafts->count() > 0) {
1069 $draft = $drafts->first();
1071 $draft = $this->pageRevision->newInstance();
1072 $draft->page_id = $page->id;
1073 $draft->slug = $page->slug;
1074 $draft->book_slug = $page->book->slug;
1075 $draft->created_by = $userId;
1076 $draft->type = 'update_draft';
1079 $draft->fill($data);
1080 if (setting('app-editor') !== 'markdown') {
1081 $draft->markdown = '';
1089 * Get a notification message concerning the editing activity on a particular page.
1091 * @param null $minRange
1094 public function getPageEditingActiveMessage(Page $page, $minRange = null)
1096 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1098 $userMessage = $pageDraftEdits->count() > 1 ? trans('entities.pages_draft_edit_active.start_a', ['count' => $pageDraftEdits->count()]): trans('entities.pages_draft_edit_active.start_b', ['userName' => $pageDraftEdits->first()->createdBy->name]);
1099 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1100 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1104 * Change the page's parent to the given entity.
1106 * @param Entity $parent
1108 public function changePageParent(Page $page, Entity $parent)
1110 $book = $parent->isA('book') ? $parent : $parent->book;
1111 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1113 if ($page->book->id !== $book->id) {
1114 $page = $this->changeBook('page', $book->id, $page);
1116 $page->load('book');
1117 $this->permissionService->buildJointPermissionsForEntity($book);
1121 * Destroy the provided book and all its child entities.
1124 public function destroyBook(Book $book)
1126 foreach ($book->pages as $page) {
1127 $this->destroyPage($page);
1129 foreach ($book->chapters as $chapter) {
1130 $this->destroyChapter($chapter);
1132 \Activity::removeEntity($book);
1133 $book->views()->delete();
1134 $book->permissions()->delete();
1135 $this->permissionService->deleteJointPermissionsForEntity($book);
1136 $this->searchService->deleteEntityTerms($book);
1141 * Destroy a chapter and its relations.
1142 * @param Chapter $chapter
1144 public function destroyChapter(Chapter $chapter)
1146 if (count($chapter->pages) > 0) {
1147 foreach ($chapter->pages as $page) {
1148 $page->chapter_id = 0;
1152 \Activity::removeEntity($chapter);
1153 $chapter->views()->delete();
1154 $chapter->permissions()->delete();
1155 $this->permissionService->deleteJointPermissionsForEntity($chapter);
1156 $this->searchService->deleteEntityTerms($chapter);
1161 * Destroy a given page along with its dependencies.
1163 * @throws NotifyException
1165 public function destroyPage(Page $page)
1167 \Activity::removeEntity($page);
1168 $page->views()->delete();
1169 $page->tags()->delete();
1170 $page->revisions()->delete();
1171 $page->permissions()->delete();
1172 $this->permissionService->deleteJointPermissionsForEntity($page);
1173 $this->searchService->deleteEntityTerms($page);
1175 // Check if set as custom homepage
1176 $customHome = setting('app-homepage', '0:');
1177 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
1178 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
1181 // Delete Attached Files
1182 $attachmentService = app(AttachmentService::class);
1183 foreach ($page->attachments as $attachment) {
1184 $attachmentService->deleteFile($attachment);