1 <?php namespace BookStack\Repos;
4 use BookStack\Bookshelf;
7 use BookStack\Exceptions\NotFoundException;
8 use BookStack\Exceptions\NotifyException;
10 use BookStack\PageRevision;
11 use BookStack\Services\AttachmentService;
12 use BookStack\Services\PermissionService;
13 use BookStack\Services\SearchService;
14 use BookStack\Services\ViewService;
18 use Illuminate\Support\Collection;
45 protected $pageRevision;
48 * Base entity instances keyed by type
54 * @var PermissionService
56 protected $permissionService;
61 protected $viewService;
71 protected $searchService;
74 * EntityRepo constructor.
75 * @param Bookshelf $bookshelf
77 * @param Chapter $chapter
79 * @param PageRevision $pageRevision
80 * @param ViewService $viewService
81 * @param PermissionService $permissionService
82 * @param TagRepo $tagRepo
83 * @param SearchService $searchService
85 public function __construct(
90 PageRevision $pageRevision,
91 ViewService $viewService,
92 PermissionService $permissionService,
94 SearchService $searchService
96 $this->bookshelf = $bookshelf;
98 $this->chapter = $chapter;
100 $this->pageRevision = $pageRevision;
102 'bookshelf' => $this->bookshelf,
103 'page' => $this->page,
104 'chapter' => $this->chapter,
105 'book' => $this->book
107 $this->viewService = $viewService;
108 $this->permissionService = $permissionService;
109 $this->tagRepo = $tagRepo;
110 $this->searchService = $searchService;
114 * Get an entity instance via type.
118 protected function getEntity($type)
120 return $this->entities[strtolower($type)];
124 * Base query for searching entities via permission system
125 * @param string $type
126 * @param bool $allowDrafts
127 * @return \Illuminate\Database\Query\Builder
129 protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
131 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), $permission);
132 if (strtolower($type) === 'page' && !$allowDrafts) {
133 $q = $q->where('draft', '=', false);
139 * Check if an entity with the given id exists.
144 public function exists($type, $id)
146 return $this->entityQuery($type)->where('id', '=', $id)->exists();
150 * Get an entity by ID
151 * @param string $type
153 * @param bool $allowDrafts
154 * @param bool $ignorePermissions
157 public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
159 if ($ignorePermissions) {
160 $entity = $this->getEntity($type);
161 return $entity->newQuery()->find($id);
163 return $this->entityQuery($type, $allowDrafts)->find($id);
167 * Get an entity by its url slug.
168 * @param string $type
169 * @param string $slug
170 * @param string|bool $bookSlug
172 * @throws NotFoundException
174 public function getBySlug($type, $slug, $bookSlug = false)
176 $q = $this->entityQuery($type)->where('slug', '=', $slug);
178 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
179 $q = $q->where('book_id', '=', function ($query) use ($bookSlug) {
181 ->from($this->book->getTable())
182 ->where('slug', '=', $bookSlug)->limit(1);
185 $entity = $q->first();
186 if ($entity === null) {
187 throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
194 * Search through page revisions and retrieve the last page in the
195 * current book that has a slug equal to the one given.
196 * @param string $pageSlug
197 * @param string $bookSlug
200 public function getPageByOldSlug($pageSlug, $bookSlug)
202 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
203 ->whereHas('page', function ($query) {
204 $this->permissionService->enforceEntityRestrictions('page', $query);
206 ->where('type', '=', 'version')
207 ->where('book_slug', '=', $bookSlug)
208 ->orderBy('created_at', 'desc')
209 ->with('page')->first();
210 return $revision !== null ? $revision->page : null;
214 * Get all entities of a type with the given permission, limited by count unless count is false.
215 * @param string $type
216 * @param integer|bool $count
217 * @param string $permission
220 public function getAll($type, $count = 20, $permission = 'view')
222 $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
223 if ($count !== false) {
224 $q = $q->take($count);
230 * Get all entities in a paginated format
233 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
235 public function getAllPaginated($type, $count = 10)
237 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
241 * Get the most recently created entities of the given type.
242 * @param string $type
245 * @param bool|callable $additionalQuery
248 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
250 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
251 ->orderBy('created_at', 'desc');
252 if (strtolower($type) === 'page') {
253 $query = $query->where('draft', '=', false);
255 if ($additionalQuery !== false && is_callable($additionalQuery)) {
256 $additionalQuery($query);
258 return $query->skip($page * $count)->take($count)->get();
262 * Get the most recently updated entities of the given type.
263 * @param string $type
266 * @param bool|callable $additionalQuery
269 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
271 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
272 ->orderBy('updated_at', 'desc');
273 if (strtolower($type) === 'page') {
274 $query = $query->where('draft', '=', false);
276 if ($additionalQuery !== false && is_callable($additionalQuery)) {
277 $additionalQuery($query);
279 return $query->skip($page * $count)->take($count)->get();
283 * Get the most recently viewed entities.
284 * @param string|bool $type
289 public function getRecentlyViewed($type, $count = 10, $page = 0)
291 $filter = is_bool($type) ? false : $this->getEntity($type);
292 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
296 * Get the latest pages added to the system with pagination.
297 * @param string $type
301 public function getRecentlyCreatedPaginated($type, $count = 20)
303 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
307 * Get the latest pages added to the system with pagination.
308 * @param string $type
312 public function getRecentlyUpdatedPaginated($type, $count = 20)
314 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
318 * Get the most popular entities base on all views.
319 * @param string|bool $type
324 public function getPopular($type, $count = 10, $page = 0)
326 $filter = is_bool($type) ? false : $this->getEntity($type);
327 return $this->viewService->getPopular($count, $page, $filter);
331 * Get draft pages owned by the current user.
335 public function getUserDraftPages($count = 20, $page = 0)
337 return $this->page->where('draft', '=', true)
338 ->where('created_by', '=', user()->id)
339 ->orderBy('updated_at', 'desc')
340 ->skip($count * $page)->take($count)->get();
344 * Get the child items for a chapter sorted by priority but
345 * with draft items floated to the top.
346 * @param Bookshelf $bookshelf
347 * @return \Illuminate\Database\Eloquent\Collection|static[]
349 public function getBookshelfChildren(Bookshelf $bookshelf)
351 return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
355 * Get all child objects of a book.
356 * Returns a sorted collection of Pages and Chapters.
357 * Loads the book slug onto child elements to prevent access database access for getting the slug.
359 * @param bool $filterDrafts
360 * @param bool $renderPages
363 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
365 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
370 foreach ($q as $index => $rawEntity) {
371 if ($rawEntity->entity_type === 'BookStack\\Page') {
372 $entities[$index] = $this->page->newFromBuilder($rawEntity);
374 $entities[$index]->html = $rawEntity->html;
375 $entities[$index]->html = $this->renderPage($entities[$index]);
377 } else if ($rawEntity->entity_type === 'BookStack\\Chapter') {
378 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
379 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
380 $parents[$key] = $entities[$index];
381 $parents[$key]->setAttribute('pages', collect());
383 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
384 $tree[] = $entities[$index];
386 $entities[$index]->book = $book;
389 foreach ($entities as $entity) {
390 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
393 $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id;
394 if (!isset($parents[$parentKey])) {
398 $chapter = $parents[$parentKey];
399 $chapter->pages->push($entity);
402 return collect($tree);
406 * Get the child items for a chapter sorted by priority but
407 * with draft items floated to the top.
408 * @param Chapter $chapter
409 * @return \Illuminate\Database\Eloquent\Collection|static[]
411 public function getChapterChildren(Chapter $chapter)
413 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
414 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
419 * Get the next sequential priority for a new child element in the given book.
423 public function getNewBookPriority(Book $book)
425 $lastElem = $this->getBookChildren($book)->pop();
426 return $lastElem ? $lastElem->priority + 1 : 0;
430 * Get a new priority for a new page to be added to the given chapter.
431 * @param Chapter $chapter
434 public function getNewChapterPriority(Chapter $chapter)
436 $lastPage = $chapter->pages('DESC')->first();
437 return $lastPage !== null ? $lastPage->priority + 1 : 0;
441 * Find a suitable slug for an entity.
442 * @param string $type
443 * @param string $name
444 * @param bool|integer $currentId
445 * @param bool|integer $bookId Only pass if type is not a book
448 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
450 $slug = $this->nameToSlug($name);
451 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
452 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
458 * Check if a slug already exists in the database.
459 * @param string $type
460 * @param string $slug
461 * @param bool|integer $currentId
462 * @param bool|integer $bookId
465 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
467 $query = $this->getEntity($type)->where('slug', '=', $slug);
468 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
469 $query = $query->where('book_id', '=', $bookId);
472 $query = $query->where('id', '!=', $currentId);
474 return $query->count() > 0;
478 * Updates entity restrictions from a request
480 * @param Entity $entity
482 public function updateEntityPermissionsFromRequest($request, Entity $entity)
484 $entity->restricted = $request->get('restricted', '') === 'true';
485 $entity->permissions()->delete();
487 if ($request->filled('restrictions')) {
488 foreach ($request->get('restrictions') as $roleId => $restrictions) {
489 foreach ($restrictions as $action => $value) {
490 $entity->permissions()->create([
491 'role_id' => $roleId,
492 'action' => strtolower($action)
499 $this->permissionService->buildJointPermissionsForEntity($entity);
505 * Create a new entity from request input.
506 * Used for books and chapters.
507 * @param string $type
508 * @param array $input
509 * @param bool|Book $book
512 public function createFromInput($type, $input = [], $book = false)
514 $isChapter = strtolower($type) === 'chapter';
515 $entityModel = $this->getEntity($type)->newInstance($input);
516 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
517 $entityModel->created_by = user()->id;
518 $entityModel->updated_by = user()->id;
519 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
521 if (isset($input['tags'])) {
522 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
525 $this->permissionService->buildJointPermissionsForEntity($entityModel);
526 $this->searchService->indexEntity($entityModel);
531 * Update entity details from request input.
532 * Used for books and chapters
533 * @param string $type
534 * @param Entity $entityModel
535 * @param array $input
538 public function updateFromInput($type, Entity $entityModel, $input = [])
540 if ($entityModel->name !== $input['name']) {
541 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
543 $entityModel->fill($input);
544 $entityModel->updated_by = user()->id;
545 $entityModel->save();
547 if (isset($input['tags'])) {
548 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
551 $this->permissionService->buildJointPermissionsForEntity($entityModel);
552 $this->searchService->indexEntity($entityModel);
557 * Sync the books assigned to a shelf from a comma-separated list
559 * @param Bookshelf $shelf
560 * @param string $books
562 public function updateShelfBooks(Bookshelf $shelf, string $books)
564 $ids = explode(',', $books);
566 // Check books exist and match ordering
567 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
569 foreach ($ids as $index => $id) {
570 if ($bookIds->contains($id)) {
571 $syncData[$id] = ['order' => $index];
575 $shelf->books()->sync($syncData);
579 * Change the book that an entity belongs to.
580 * @param string $type
581 * @param integer $newBookId
582 * @param Entity $entity
583 * @param bool $rebuildPermissions
586 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
588 $entity->book_id = $newBookId;
589 // Update related activity
590 foreach ($entity->activity as $activity) {
591 $activity->book_id = $newBookId;
594 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
597 // Update all child pages if a chapter
598 if (strtolower($type) === 'chapter') {
599 foreach ($entity->pages as $page) {
600 $this->changeBook('page', $newBookId, $page, false);
604 // Update permissions if applicable
605 if ($rebuildPermissions) {
606 $entity->load('book');
607 $this->permissionService->buildJointPermissionsForEntity($entity->book);
614 * Alias method to update the book jointPermissions in the PermissionService.
617 public function buildJointPermissionsForBook(Book $book)
619 $this->permissionService->buildJointPermissionsForEntity($book);
623 * Format a name as a url slug.
627 protected function nameToSlug($name)
629 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
630 $slug = preg_replace('/\s{2,}/', ' ', $slug);
631 $slug = str_replace(' ', '-', $slug);
633 $slug = substr(md5(rand(1, 500)), 0, 5);
639 * Get a new draft page instance.
641 * @param Chapter|bool $chapter
644 public function getDraftPage(Book $book, $chapter = false)
646 $page = $this->page->newInstance();
647 $page->name = trans('entities.pages_initial_name');
648 $page->created_by = user()->id;
649 $page->updated_by = user()->id;
653 $page->chapter_id = $chapter->id;
656 $book->pages()->save($page);
657 $page = $this->page->find($page->id);
658 $this->permissionService->buildJointPermissionsForEntity($page);
663 * Publish a draft page to make it a normal page.
664 * Sets the slug and updates the content.
665 * @param Page $draftPage
666 * @param array $input
669 public function publishPageDraft(Page $draftPage, array $input)
671 $draftPage->fill($input);
673 // Save page tags if present
674 if (isset($input['tags'])) {
675 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
678 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
679 $draftPage->html = $this->formatHtml($input['html']);
680 $draftPage->text = $this->pageToPlainText($draftPage);
681 $draftPage->draft = false;
682 $draftPage->revision_count = 1;
685 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
686 $this->searchService->indexEntity($draftPage);
691 * Create a copy of a page in a new location with a new name.
693 * @param Entity $newParent
694 * @param string $newName
697 public function copyPage(Page $page, Entity $newParent, $newName = '')
699 $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
700 $newChapter = $newParent->isA('chapter') ? $newParent : null;
701 $copyPage = $this->getDraftPage($newBook, $newChapter);
702 $pageData = $page->getAttributes();
705 if (!empty($newName)) {
706 $pageData['name'] = $newName;
709 // Copy tags from previous page if set
711 $pageData['tags'] = [];
712 foreach ($page->tags as $tag) {
713 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
718 if ($newParent->isA('chapter')) {
719 $pageData['priority'] = $this->getNewChapterPriority($newParent);
721 $pageData['priority'] = $this->getNewBookPriority($newParent);
724 return $this->publishPageDraft($copyPage, $pageData);
728 * Saves a page revision into the system.
730 * @param null|string $summary
731 * @return PageRevision
733 public function savePageRevision(Page $page, $summary = null)
735 $revision = $this->pageRevision->newInstance($page->toArray());
736 if (setting('app-editor') !== 'markdown') {
737 $revision->markdown = '';
739 $revision->page_id = $page->id;
740 $revision->slug = $page->slug;
741 $revision->book_slug = $page->book->slug;
742 $revision->created_by = user()->id;
743 $revision->created_at = $page->updated_at;
744 $revision->type = 'version';
745 $revision->summary = $summary;
746 $revision->revision_number = $page->revision_count;
749 $revisionLimit = config('app.revision_limit');
750 if ($revisionLimit !== false) {
751 $revisionsToDelete = $this->pageRevision->where('page_id', '=', $page->id)
752 ->orderBy('created_at', 'desc')->skip(intval($revisionLimit))->take(10)->get(['id']);
753 if ($revisionsToDelete->count() > 0) {
754 $this->pageRevision->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
762 * Formats a page's html to be tagged correctly
764 * @param string $htmlText
767 protected function formatHtml($htmlText)
769 if ($htmlText == '') {
772 libxml_use_internal_errors(true);
773 $doc = new DOMDocument();
774 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
776 $container = $doc->documentElement;
777 $body = $container->childNodes->item(0);
778 $childNodes = $body->childNodes;
780 // Ensure no duplicate ids are used
783 foreach ($childNodes as $index => $childNode) {
784 /** @var \DOMElement $childNode */
785 if (get_class($childNode) !== 'DOMElement') {
789 // Overwrite id if not a BookStack custom id
790 if ($childNode->hasAttribute('id')) {
791 $id = $childNode->getAttribute('id');
792 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
798 // Create an unique id for the element
799 // Uses the content as a basis to ensure output is the same every time
800 // the same content is passed through.
801 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
802 $newId = urlencode($contentId);
804 while (in_array($newId, $idArray)) {
805 $newId = urlencode($contentId . '-' . $loopIndex);
809 $childNode->setAttribute('id', $newId);
813 // Generate inner html as a string
815 foreach ($childNodes as $childNode) {
816 $html .= $doc->saveHTML($childNode);
824 * Render the page for viewing, Parsing and performing features such as page transclusion.
826 * @param bool $ignorePermissions
827 * @return mixed|string
829 public function renderPage(Page $page, $ignorePermissions = false)
831 $content = $page->html;
832 if (!config('app.allow_content_scripts')) {
833 $content = $this->escapeScripts($content);
837 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
838 if (count($matches[0]) === 0) {
842 $topLevelTags = ['table', 'ul', 'ol'];
843 foreach ($matches[1] as $index => $includeId) {
844 $splitInclude = explode('#', $includeId, 2);
845 $pageId = intval($splitInclude[0]);
846 if (is_nan($pageId)) {
850 $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
851 if ($matchedPage === null) {
852 $content = str_replace($matches[0][$index], '', $content);
856 if (count($splitInclude) === 1) {
857 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
861 $doc = new DOMDocument();
862 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
863 $matchingElem = $doc->getElementById($splitInclude[1]);
864 if ($matchingElem === null) {
865 $content = str_replace($matches[0][$index], '', $content);
869 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
871 $innerContent .= $doc->saveHTML($matchingElem);
873 foreach ($matchingElem->childNodes as $childNode) {
874 $innerContent .= $doc->saveHTML($childNode);
877 $content = str_replace($matches[0][$index], trim($innerContent), $content);
884 * Escape script tags within HTML content.
885 * @param string $html
888 protected function escapeScripts(string $html)
890 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
892 preg_match_all($scriptSearchRegex, $html, $matches);
893 if (count($matches) === 0) {
897 foreach ($matches[0] as $match) {
898 $html = str_replace($match, htmlentities($match), $html);
904 * Get the plain text version of a page's content.
908 public function pageToPlainText(Page $page)
910 $html = $this->renderPage($page);
911 return strip_tags($html);
915 * Search for image usage within page content.
916 * @param $imageString
919 public function searchForImage($imageString)
921 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
922 foreach ($pages as $page) {
923 $page->url = $page->getUrl();
927 return count($pages) > 0 ? $pages : false;
931 * Parse the headers on the page to get a navigation menu
932 * @param String $pageContent
935 public function getPageNav($pageContent)
937 if ($pageContent == '') {
940 libxml_use_internal_errors(true);
941 $doc = new DOMDocument();
942 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
943 $xPath = new DOMXPath($doc);
944 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
946 if (is_null($headers)) {
951 foreach ($headers as $header) {
952 $text = $header->nodeValue;
954 'nodeName' => strtolower($header->nodeName),
955 'level' => intval(str_replace('h', '', $header->nodeName)),
956 'link' => '#' . $header->getAttribute('id'),
957 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
961 // Normalise headers if only smaller headers have been used
962 if (count($tree) > 0) {
963 $minLevel = $tree->pluck('level')->min();
964 $tree = $tree->map(function ($header) use ($minLevel) {
965 $header['level'] -= ($minLevel - 2);
969 return $tree->toArray();
973 * Updates a page with any fillable data and saves it into the database.
975 * @param int $book_id
976 * @param array $input
979 public function updatePage(Page $page, $book_id, $input)
981 // Hold the old details to compare later
982 $oldHtml = $page->html;
983 $oldName = $page->name;
985 // Prevent slug being updated if no name change
986 if ($page->name !== $input['name']) {
987 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
990 // Save page tags if present
991 if (isset($input['tags'])) {
992 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
995 // Update with new details
996 $userId = user()->id;
998 $page->html = $this->formatHtml($input['html']);
999 $page->text = $this->pageToPlainText($page);
1000 if (setting('app-editor') !== 'markdown') {
1001 $page->markdown = '';
1003 $page->updated_by = $userId;
1004 $page->revision_count++;
1007 // Remove all update drafts for this user & page.
1008 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
1010 // Save a revision after updating
1011 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
1012 $this->savePageRevision($page, $input['summary']);
1015 $this->searchService->indexEntity($page);
1021 * The base query for getting user update drafts.
1026 protected function userUpdatePageDraftsQuery(Page $page, $userId)
1028 return $this->pageRevision->where('created_by', '=', $userId)
1029 ->where('type', 'update_draft')
1030 ->where('page_id', '=', $page->id)
1031 ->orderBy('created_at', 'desc');
1035 * Checks whether a user has a draft version of a particular page or not.
1040 public function hasUserGotPageDraft(Page $page, $userId)
1042 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
1046 * Get the latest updated draft revision for a particular page and user.
1051 public function getUserPageDraft(Page $page, $userId)
1053 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
1057 * Get the notification message that informs the user that they are editing a draft page.
1058 * @param PageRevision $draft
1061 public function getUserPageDraftMessage(PageRevision $draft)
1063 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
1064 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
1067 return $message . "\n" . trans('entities.pages_draft_edited_notification');
1071 * Check if a page is being actively editing.
1072 * Checks for edits since last page updated.
1073 * Passing in a minuted range will check for edits
1074 * within the last x minutes.
1076 * @param null $minRange
1079 public function isPageEditingActive(Page $page, $minRange = null)
1081 $draftSearch = $this->activePageEditingQuery($page, $minRange);
1082 return $draftSearch->count() > 0;
1086 * A query to check for active update drafts on a particular page.
1088 * @param null $minRange
1091 protected function activePageEditingQuery(Page $page, $minRange = null)
1093 $query = $this->pageRevision->where('type', '=', 'update_draft')
1094 ->where('page_id', '=', $page->id)
1095 ->where('updated_at', '>', $page->updated_at)
1096 ->where('created_by', '!=', user()->id)
1097 ->with('createdBy');
1099 if ($minRange !== null) {
1100 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1107 * Restores a revision's content back into a page.
1110 * @param int $revisionId
1113 public function restorePageRevision(Page $page, Book $book, $revisionId)
1115 $page->revision_count++;
1116 $this->savePageRevision($page);
1117 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
1118 $page->fill($revision->toArray());
1119 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1120 $page->text = $this->pageToPlainText($page);
1121 $page->updated_by = user()->id;
1123 $this->searchService->indexEntity($page);
1129 * Save a page update draft.
1131 * @param array $data
1132 * @return PageRevision|Page
1134 public function updatePageDraft(Page $page, $data = [])
1136 // If the page itself is a draft simply update that
1139 if (isset($data['html'])) {
1140 $page->text = $this->pageToPlainText($page);
1146 // Otherwise save the data to a revision
1147 $userId = user()->id;
1148 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1150 if ($drafts->count() > 0) {
1151 $draft = $drafts->first();
1153 $draft = $this->pageRevision->newInstance();
1154 $draft->page_id = $page->id;
1155 $draft->slug = $page->slug;
1156 $draft->book_slug = $page->book->slug;
1157 $draft->created_by = $userId;
1158 $draft->type = 'update_draft';
1161 $draft->fill($data);
1162 if (setting('app-editor') !== 'markdown') {
1163 $draft->markdown = '';
1171 * Get a notification message concerning the editing activity on a particular page.
1173 * @param null $minRange
1176 public function getPageEditingActiveMessage(Page $page, $minRange = null)
1178 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1180 $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]);
1181 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1182 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1186 * Change the page's parent to the given entity.
1188 * @param Entity $parent
1190 public function changePageParent(Page $page, Entity $parent)
1192 $book = $parent->isA('book') ? $parent : $parent->book;
1193 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1195 if ($page->book->id !== $book->id) {
1196 $page = $this->changeBook('page', $book->id, $page);
1198 $page->load('book');
1199 $this->permissionService->buildJointPermissionsForEntity($book);
1203 * Destroy a bookshelf instance
1204 * @param Bookshelf $shelf
1205 * @throws \Throwable
1207 public function destroyBookshelf(Bookshelf $shelf)
1209 $this->destroyEntityCommonRelations($shelf);
1214 * Destroy the provided book and all its child entities.
1216 * @throws NotifyException
1217 * @throws \Throwable
1219 public function destroyBook(Book $book)
1221 foreach ($book->pages as $page) {
1222 $this->destroyPage($page);
1224 foreach ($book->chapters as $chapter) {
1225 $this->destroyChapter($chapter);
1227 $this->destroyEntityCommonRelations($book);
1232 * Destroy a chapter and its relations.
1233 * @param Chapter $chapter
1234 * @throws \Throwable
1236 public function destroyChapter(Chapter $chapter)
1238 if (count($chapter->pages) > 0) {
1239 foreach ($chapter->pages as $page) {
1240 $page->chapter_id = 0;
1244 $this->destroyEntityCommonRelations($chapter);
1249 * Destroy a given page along with its dependencies.
1251 * @throws NotifyException
1252 * @throws \Throwable
1254 public function destroyPage(Page $page)
1256 // Check if set as custom homepage
1257 $customHome = setting('app-homepage', '0:');
1258 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
1259 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
1262 $this->destroyEntityCommonRelations($page);
1264 // Delete Attached Files
1265 $attachmentService = app(AttachmentService::class);
1266 foreach ($page->attachments as $attachment) {
1267 $attachmentService->deleteFile($attachment);
1274 * Destroy or handle the common relations connected to an entity.
1275 * @param Entity $entity
1276 * @throws \Throwable
1278 protected function destroyEntityCommonRelations(Entity $entity)
1280 \Activity::removeEntity($entity);
1281 $entity->views()->delete();
1282 $entity->permissions()->delete();
1283 $entity->tags()->delete();
1284 $entity->comments()->delete();
1285 $this->permissionService->deleteJointPermissionsForEntity($entity);
1286 $this->searchService->deleteEntityTerms($entity);
1290 * Copy the permissions of a bookshelf to all child books.
1291 * Returns the number of books that had permissions updated.
1292 * @param Bookshelf $bookshelf
1294 * @throws \Throwable
1296 public function copyBookshelfPermissions(Bookshelf $bookshelf)
1298 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
1299 $shelfBooks = $bookshelf->books()->get();
1300 $updatedBookCount = 0;
1302 foreach ($shelfBooks as $book) {
1303 if (!userCan('restrictions-manage', $book)) {
1306 $book->permissions()->delete();
1307 $book->restricted = $bookshelf->restricted;
1308 $book->permissions()->createMany($shelfPermissions);
1310 $this->permissionService->buildJointPermissionsForEntity($book);
1311 $updatedBookCount++;
1314 return $updatedBookCount;