1 <?php namespace BookStack\Entities;
3 use BookStack\Actions\TagRepo;
4 use BookStack\Actions\ViewService;
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\NotFoundException;
8 use BookStack\Exceptions\NotifyException;
9 use BookStack\Uploads\AttachmentService;
13 use Illuminate\Http\Request;
14 use Illuminate\Support\Collection;
22 protected $entityProvider;
25 * @var PermissionService
27 protected $permissionService;
32 protected $viewService;
42 protected $searchService;
45 * EntityRepo constructor.
46 * @param EntityProvider $entityProvider
47 * @param ViewService $viewService
48 * @param PermissionService $permissionService
49 * @param TagRepo $tagRepo
50 * @param SearchService $searchService
52 public function __construct(
53 EntityProvider $entityProvider,
54 ViewService $viewService,
55 PermissionService $permissionService,
57 SearchService $searchService
59 $this->entityProvider = $entityProvider;
60 $this->viewService = $viewService;
61 $this->permissionService = $permissionService;
62 $this->tagRepo = $tagRepo;
63 $this->searchService = $searchService;
67 * Base query for searching entities via permission system
69 * @param bool $allowDrafts
70 * @param string $permission
71 * @return \Illuminate\Database\Query\Builder
73 protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
75 $q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
76 if (strtolower($type) === 'page' && !$allowDrafts) {
77 $q = $q->where('draft', '=', false);
83 * Check if an entity with the given id exists.
88 public function exists($type, $id)
90 return $this->entityQuery($type)->where('id', '=', $id)->exists();
97 * @param bool $allowDrafts
98 * @param bool $ignorePermissions
99 * @return \BookStack\Entities\Entity
101 public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
103 $query = $this->entityQuery($type, $allowDrafts);
105 if ($ignorePermissions) {
106 $query = $this->entityProvider->get($type)->newQuery();
109 return $query->find($id);
113 * @param string $type
115 * @param bool $allowDrafts
116 * @param bool $ignorePermissions
117 * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
119 public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
121 $query = $this->entityQuery($type, $allowDrafts);
123 if ($ignorePermissions) {
124 $query = $this->entityProvider->get($type)->newQuery();
127 return $query->whereIn('id', $ids)->get();
131 * Get an entity by its url slug.
132 * @param string $type
133 * @param string $slug
134 * @param string|bool $bookSlug
135 * @return \BookStack\Entities\Entity
136 * @throws NotFoundException
138 public function getBySlug($type, $slug, $bookSlug = false)
140 $q = $this->entityQuery($type)->where('slug', '=', $slug);
142 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
143 $q = $q->where('book_id', '=', function ($query) use ($bookSlug) {
145 ->from($this->entityProvider->book->getTable())
146 ->where('slug', '=', $bookSlug)->limit(1);
149 $entity = $q->first();
150 if ($entity === null) {
151 throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
158 * Search through page revisions and retrieve the last page in the
159 * current book that has a slug equal to the one given.
160 * @param string $pageSlug
161 * @param string $bookSlug
164 public function getPageByOldSlug($pageSlug, $bookSlug)
166 $revision = $this->entityProvider->pageRevision->where('slug', '=', $pageSlug)
167 ->whereHas('page', function ($query) {
168 $this->permissionService->enforceEntityRestrictions('page', $query);
170 ->where('type', '=', 'version')
171 ->where('book_slug', '=', $bookSlug)
172 ->orderBy('created_at', 'desc')
173 ->with('page')->first();
174 return $revision !== null ? $revision->page : null;
178 * Get all entities of a type with the given permission, limited by count unless count is false.
179 * @param string $type
180 * @param integer|bool $count
181 * @param string $permission
184 public function getAll($type, $count = 20, $permission = 'view')
186 $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
187 if ($count !== false) {
188 $q = $q->take($count);
194 * Get all entities in a paginated format
197 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
199 public function getAllPaginated($type, $count = 10)
201 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
205 * Get the most recently created entities of the given type.
206 * @param string $type
209 * @param bool|callable $additionalQuery
212 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
214 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
215 ->orderBy('created_at', 'desc');
216 if (strtolower($type) === 'page') {
217 $query = $query->where('draft', '=', false);
219 if ($additionalQuery !== false && is_callable($additionalQuery)) {
220 $additionalQuery($query);
222 return $query->skip($page * $count)->take($count)->get();
226 * Get the most recently updated entities of the given type.
227 * @param string $type
230 * @param bool|callable $additionalQuery
233 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
235 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
236 ->orderBy('updated_at', 'desc');
237 if (strtolower($type) === 'page') {
238 $query = $query->where('draft', '=', false);
240 if ($additionalQuery !== false && is_callable($additionalQuery)) {
241 $additionalQuery($query);
243 return $query->skip($page * $count)->take($count)->get();
247 * Get the most recently viewed entities.
248 * @param string|bool $type
253 public function getRecentlyViewed($type, $count = 10, $page = 0)
255 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
256 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
260 * Get the latest pages added to the system with pagination.
261 * @param string $type
265 public function getRecentlyCreatedPaginated($type, $count = 20)
267 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
271 * Get the latest pages added to the system with pagination.
272 * @param string $type
276 public function getRecentlyUpdatedPaginated($type, $count = 20)
278 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
282 * Get the most popular entities base on all views.
283 * @param string|bool $type
288 public function getPopular($type, $count = 10, $page = 0)
290 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
291 return $this->viewService->getPopular($count, $page, $filter);
295 * Get draft pages owned by the current user.
300 public function getUserDraftPages($count = 20, $page = 0)
302 return $this->entityProvider->page->where('draft', '=', true)
303 ->where('created_by', '=', user()->id)
304 ->orderBy('updated_at', 'desc')
305 ->skip($count * $page)->take($count)->get();
309 * Get the number of entities the given user has created.
310 * @param string $type
314 public function getUserTotalCreated(string $type, User $user)
316 return $this->entityProvider->get($type)
317 ->where('created_by', '=', $user->id)->count();
321 * Get the child items for a chapter sorted by priority but
322 * with draft items floated to the top.
323 * @param \BookStack\Entities\Bookshelf $bookshelf
324 * @return \Illuminate\Database\Eloquent\Collection|static[]
326 public function getBookshelfChildren(Bookshelf $bookshelf)
328 return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
332 * Get all child objects of a book.
333 * Returns a sorted collection of Pages and Chapters.
334 * Loads the book slug onto child elements to prevent access database access for getting the slug.
335 * @param \BookStack\Entities\Book $book
336 * @param bool $filterDrafts
337 * @param bool $renderPages
340 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
342 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
347 foreach ($q as $index => $rawEntity) {
348 if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
349 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
351 $entities[$index]->html = $rawEntity->html;
352 $entities[$index]->html = $this->renderPage($entities[$index]);
354 } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
355 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
356 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
357 $parents[$key] = $entities[$index];
358 $parents[$key]->setAttribute('pages', collect());
360 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
361 $tree[] = $entities[$index];
363 $entities[$index]->book = $book;
366 foreach ($entities as $entity) {
367 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
370 $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
371 if (!isset($parents[$parentKey])) {
375 $chapter = $parents[$parentKey];
376 $chapter->pages->push($entity);
379 return collect($tree);
383 * Get the child items for a chapter sorted by priority but
384 * with draft items floated to the top.
385 * @param \BookStack\Entities\Chapter $chapter
386 * @return \Illuminate\Database\Eloquent\Collection|static[]
388 public function getChapterChildren(Chapter $chapter)
390 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
391 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
396 * Get the next sequential priority for a new child element in the given book.
397 * @param \BookStack\Entities\Book $book
400 public function getNewBookPriority(Book $book)
402 $lastElem = $this->getBookChildren($book)->pop();
403 return $lastElem ? $lastElem->priority + 1 : 0;
407 * Get a new priority for a new page to be added to the given chapter.
408 * @param \BookStack\Entities\Chapter $chapter
411 public function getNewChapterPriority(Chapter $chapter)
413 $lastPage = $chapter->pages('DESC')->first();
414 return $lastPage !== null ? $lastPage->priority + 1 : 0;
418 * Find a suitable slug for an entity.
419 * @param string $type
420 * @param string $name
421 * @param bool|integer $currentId
422 * @param bool|integer $bookId Only pass if type is not a book
425 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
427 $slug = $this->nameToSlug($name);
428 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
429 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
435 * Check if a slug already exists in the database.
436 * @param string $type
437 * @param string $slug
438 * @param bool|integer $currentId
439 * @param bool|integer $bookId
442 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
444 $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
445 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
446 $query = $query->where('book_id', '=', $bookId);
449 $query = $query->where('id', '!=', $currentId);
451 return $query->count() > 0;
455 * Updates entity restrictions from a request
456 * @param Request $request
457 * @param \BookStack\Entities\Entity $entity
460 public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
462 $entity->restricted = $request->get('restricted', '') === 'true';
463 $entity->permissions()->delete();
465 if ($request->filled('restrictions')) {
466 foreach ($request->get('restrictions') as $roleId => $restrictions) {
467 foreach ($restrictions as $action => $value) {
468 $entity->permissions()->create([
469 'role_id' => $roleId,
470 'action' => strtolower($action)
477 $this->permissionService->buildJointPermissionsForEntity($entity);
483 * Create a new entity from request input.
484 * Used for books and chapters.
485 * @param string $type
486 * @param array $input
487 * @param bool|Book $book
488 * @return \BookStack\Entities\Entity
490 public function createFromInput($type, $input = [], $book = false)
492 $isChapter = strtolower($type) === 'chapter';
493 $entityModel = $this->entityProvider->get($type)->newInstance($input);
494 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
495 $entityModel->created_by = user()->id;
496 $entityModel->updated_by = user()->id;
497 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
499 if (isset($input['tags'])) {
500 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
503 $this->permissionService->buildJointPermissionsForEntity($entityModel);
504 $this->searchService->indexEntity($entityModel);
509 * Update entity details from request input.
510 * Used for books and chapters
511 * @param string $type
512 * @param \BookStack\Entities\Entity $entityModel
513 * @param array $input
514 * @return \BookStack\Entities\Entity
516 public function updateFromInput($type, Entity $entityModel, $input = [])
518 if ($entityModel->name !== $input['name']) {
519 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
521 $entityModel->fill($input);
522 $entityModel->updated_by = user()->id;
523 $entityModel->save();
525 if (isset($input['tags'])) {
526 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
529 $this->permissionService->buildJointPermissionsForEntity($entityModel);
530 $this->searchService->indexEntity($entityModel);
535 * Sync the books assigned to a shelf from a comma-separated list
537 * @param \BookStack\Entities\Bookshelf $shelf
538 * @param string $books
540 public function updateShelfBooks(Bookshelf $shelf, string $books)
542 $ids = explode(',', $books);
544 // Check books exist and match ordering
545 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
547 foreach ($ids as $index => $id) {
548 if ($bookIds->contains($id)) {
549 $syncData[$id] = ['order' => $index];
553 $shelf->books()->sync($syncData);
557 * Change the book that an entity belongs to.
558 * @param string $type
559 * @param integer $newBookId
560 * @param Entity $entity
561 * @param bool $rebuildPermissions
562 * @return \BookStack\Entities\Entity
564 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
566 $entity->book_id = $newBookId;
567 // Update related activity
568 foreach ($entity->activity as $activity) {
569 $activity->book_id = $newBookId;
572 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
575 // Update all child pages if a chapter
576 if (strtolower($type) === 'chapter') {
577 foreach ($entity->pages as $page) {
578 $this->changeBook('page', $newBookId, $page, false);
582 // Update permissions if applicable
583 if ($rebuildPermissions) {
584 $entity->load('book');
585 $this->permissionService->buildJointPermissionsForEntity($entity->book);
592 * Alias method to update the book jointPermissions in the PermissionService.
595 public function buildJointPermissionsForBook(Book $book)
597 $this->permissionService->buildJointPermissionsForEntity($book);
601 * Format a name as a url slug.
605 protected function nameToSlug($name)
607 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
608 $slug = preg_replace('/\s{2,}/', ' ', $slug);
609 $slug = str_replace(' ', '-', $slug);
611 $slug = substr(md5(rand(1, 500)), 0, 5);
617 * Get a new draft page instance.
619 * @param Chapter|bool $chapter
620 * @return \BookStack\Entities\Page
622 public function getDraftPage(Book $book, $chapter = false)
624 $page = $this->entityProvider->page->newInstance();
625 $page->name = trans('entities.pages_initial_name');
626 $page->created_by = user()->id;
627 $page->updated_by = user()->id;
631 $page->chapter_id = $chapter->id;
634 $book->pages()->save($page);
635 $page = $this->entityProvider->page->find($page->id);
636 $this->permissionService->buildJointPermissionsForEntity($page);
641 * Publish a draft page to make it a normal page.
642 * Sets the slug and updates the content.
643 * @param Page $draftPage
644 * @param array $input
647 public function publishPageDraft(Page $draftPage, array $input)
649 $draftPage->fill($input);
651 // Save page tags if present
652 if (isset($input['tags'])) {
653 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
656 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
657 $draftPage->html = $this->formatHtml($input['html']);
658 $draftPage->text = $this->pageToPlainText($draftPage);
659 $draftPage->draft = false;
660 $draftPage->revision_count = 1;
663 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
664 $this->searchService->indexEntity($draftPage);
669 * Create a copy of a page in a new location with a new name.
670 * @param \BookStack\Entities\Page $page
671 * @param \BookStack\Entities\Entity $newParent
672 * @param string $newName
673 * @return \BookStack\Entities\Page
675 public function copyPage(Page $page, Entity $newParent, $newName = '')
677 $newBook = $newParent->isA('book') ? $newParent : $newParent->book;
678 $newChapter = $newParent->isA('chapter') ? $newParent : null;
679 $copyPage = $this->getDraftPage($newBook, $newChapter);
680 $pageData = $page->getAttributes();
683 if (!empty($newName)) {
684 $pageData['name'] = $newName;
687 // Copy tags from previous page if set
689 $pageData['tags'] = [];
690 foreach ($page->tags as $tag) {
691 $pageData['tags'][] = ['name' => $tag->name, 'value' => $tag->value];
696 if ($newParent->isA('chapter')) {
697 $pageData['priority'] = $this->getNewChapterPriority($newParent);
699 $pageData['priority'] = $this->getNewBookPriority($newParent);
702 return $this->publishPageDraft($copyPage, $pageData);
706 * Saves a page revision into the system.
708 * @param null|string $summary
709 * @return \BookStack\Entities\PageRevision
711 public function savePageRevision(Page $page, $summary = null)
713 $revision = $this->entityProvider->pageRevision->newInstance($page->toArray());
714 if (setting('app-editor') !== 'markdown') {
715 $revision->markdown = '';
717 $revision->page_id = $page->id;
718 $revision->slug = $page->slug;
719 $revision->book_slug = $page->book->slug;
720 $revision->created_by = user()->id;
721 $revision->created_at = $page->updated_at;
722 $revision->type = 'version';
723 $revision->summary = $summary;
724 $revision->revision_number = $page->revision_count;
727 $revisionLimit = config('app.revision_limit');
728 if ($revisionLimit !== false) {
729 $revisionsToDelete = $this->entityProvider->pageRevision->where('page_id', '=', $page->id)
730 ->orderBy('created_at', 'desc')->skip(intval($revisionLimit))->take(10)->get(['id']);
731 if ($revisionsToDelete->count() > 0) {
732 $this->entityProvider->pageRevision->whereIn('id', $revisionsToDelete->pluck('id'))->delete();
740 * Formats a page's html to be tagged correctly
742 * @param string $htmlText
745 protected function formatHtml($htmlText)
747 if ($htmlText == '') {
750 libxml_use_internal_errors(true);
751 $doc = new DOMDocument();
752 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
754 $container = $doc->documentElement;
755 $body = $container->childNodes->item(0);
756 $childNodes = $body->childNodes;
758 // Ensure no duplicate ids are used
761 foreach ($childNodes as $index => $childNode) {
762 /** @var \DOMElement $childNode */
763 if (get_class($childNode) !== 'DOMElement') {
767 // Overwrite id if not a BookStack custom id
768 if ($childNode->hasAttribute('id')) {
769 $id = $childNode->getAttribute('id');
770 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
776 // Create an unique id for the element
777 // Uses the content as a basis to ensure output is the same every time
778 // the same content is passed through.
779 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
780 $newId = urlencode($contentId);
782 while (in_array($newId, $idArray)) {
783 $newId = urlencode($contentId . '-' . $loopIndex);
787 $childNode->setAttribute('id', $newId);
791 // Generate inner html as a string
793 foreach ($childNodes as $childNode) {
794 $html .= $doc->saveHTML($childNode);
802 * Render the page for viewing, Parsing and performing features such as page transclusion.
804 * @param bool $ignorePermissions
805 * @return mixed|string
807 public function renderPage(Page $page, $ignorePermissions = false)
809 $content = $page->html;
810 if (!config('app.allow_content_scripts')) {
811 $content = $this->escapeScripts($content);
815 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
816 if (count($matches[0]) === 0) {
820 $topLevelTags = ['table', 'ul', 'ol'];
821 foreach ($matches[1] as $index => $includeId) {
822 $splitInclude = explode('#', $includeId, 2);
823 $pageId = intval($splitInclude[0]);
824 if (is_nan($pageId)) {
828 $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
829 if ($matchedPage === null) {
830 $content = str_replace($matches[0][$index], '', $content);
834 if (count($splitInclude) === 1) {
835 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
839 $doc = new DOMDocument();
840 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
841 $matchingElem = $doc->getElementById($splitInclude[1]);
842 if ($matchingElem === null) {
843 $content = str_replace($matches[0][$index], '', $content);
847 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
849 $innerContent .= $doc->saveHTML($matchingElem);
851 foreach ($matchingElem->childNodes as $childNode) {
852 $innerContent .= $doc->saveHTML($childNode);
855 $content = str_replace($matches[0][$index], trim($innerContent), $content);
862 * Escape script tags within HTML content.
863 * @param string $html
866 protected function escapeScripts(string $html)
868 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
870 preg_match_all($scriptSearchRegex, $html, $matches);
871 if (count($matches) === 0) {
875 foreach ($matches[0] as $match) {
876 $html = str_replace($match, htmlentities($match), $html);
882 * Get the plain text version of a page's content.
883 * @param \BookStack\Entities\Page $page
886 public function pageToPlainText(Page $page)
888 $html = $this->renderPage($page);
889 return strip_tags($html);
893 * Search for image usage within page content.
894 * @param $imageString
897 public function searchForImage($imageString)
899 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
900 foreach ($pages as $page) {
901 $page->url = $page->getUrl();
905 return count($pages) > 0 ? $pages : false;
909 * Parse the headers on the page to get a navigation menu
910 * @param String $pageContent
913 public function getPageNav($pageContent)
915 if ($pageContent == '') {
918 libxml_use_internal_errors(true);
919 $doc = new DOMDocument();
920 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
921 $xPath = new DOMXPath($doc);
922 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
924 if (is_null($headers)) {
929 foreach ($headers as $header) {
930 $text = $header->nodeValue;
932 'nodeName' => strtolower($header->nodeName),
933 'level' => intval(str_replace('h', '', $header->nodeName)),
934 'link' => '#' . $header->getAttribute('id'),
935 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
939 // Normalise headers if only smaller headers have been used
940 if (count($tree) > 0) {
941 $minLevel = $tree->pluck('level')->min();
942 $tree = $tree->map(function ($header) use ($minLevel) {
943 $header['level'] -= ($minLevel - 2);
947 return $tree->toArray();
951 * Updates a page with any fillable data and saves it into the database.
952 * @param \BookStack\Entities\Page $page
953 * @param int $book_id
954 * @param array $input
955 * @return \BookStack\Entities\Page
957 public function updatePage(Page $page, $book_id, $input)
959 // Hold the old details to compare later
960 $oldHtml = $page->html;
961 $oldName = $page->name;
963 // Prevent slug being updated if no name change
964 if ($page->name !== $input['name']) {
965 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
968 // Save page tags if present
969 if (isset($input['tags'])) {
970 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
973 // Update with new details
974 $userId = user()->id;
976 $page->html = $this->formatHtml($input['html']);
977 $page->text = $this->pageToPlainText($page);
978 if (setting('app-editor') !== 'markdown') {
979 $page->markdown = '';
981 $page->updated_by = $userId;
982 $page->revision_count++;
985 // Remove all update drafts for this user & page.
986 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
988 // Save a revision after updating
989 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
990 $this->savePageRevision($page, $input['summary']);
993 $this->searchService->indexEntity($page);
999 * The base query for getting user update drafts.
1000 * @param \BookStack\Entities\Page $page
1004 protected function userUpdatePageDraftsQuery(Page $page, $userId)
1006 return $this->entityProvider->pageRevision->where('created_by', '=', $userId)
1007 ->where('type', 'update_draft')
1008 ->where('page_id', '=', $page->id)
1009 ->orderBy('created_at', 'desc');
1013 * Checks whether a user has a draft version of a particular page or not.
1014 * @param \BookStack\Entities\Page $page
1018 public function hasUserGotPageDraft(Page $page, $userId)
1020 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
1024 * Get the latest updated draft revision for a particular page and user.
1029 public function getUserPageDraft(Page $page, $userId)
1031 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
1035 * Get the notification message that informs the user that they are editing a draft page.
1036 * @param PageRevision $draft
1039 public function getUserPageDraftMessage(PageRevision $draft)
1041 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
1042 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) {
1045 return $message . "\n" . trans('entities.pages_draft_edited_notification');
1049 * Check if a page is being actively editing.
1050 * Checks for edits since last page updated.
1051 * Passing in a minuted range will check for edits
1052 * within the last x minutes.
1053 * @param \BookStack\Entities\Page $page
1054 * @param null $minRange
1057 public function isPageEditingActive(Page $page, $minRange = null)
1059 $draftSearch = $this->activePageEditingQuery($page, $minRange);
1060 return $draftSearch->count() > 0;
1064 * A query to check for active update drafts on a particular page.
1066 * @param null $minRange
1069 protected function activePageEditingQuery(Page $page, $minRange = null)
1071 $query = $this->entityProvider->pageRevision->where('type', '=', 'update_draft')
1072 ->where('page_id', '=', $page->id)
1073 ->where('updated_at', '>', $page->updated_at)
1074 ->where('created_by', '!=', user()->id)
1075 ->with('createdBy');
1077 if ($minRange !== null) {
1078 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1085 * Restores a revision's content back into a page.
1088 * @param int $revisionId
1089 * @return \BookStack\Entities\Page
1091 public function restorePageRevision(Page $page, Book $book, $revisionId)
1093 $page->revision_count++;
1094 $this->savePageRevision($page);
1095 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
1096 $page->fill($revision->toArray());
1097 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1098 $page->text = $this->pageToPlainText($page);
1099 $page->updated_by = user()->id;
1101 $this->searchService->indexEntity($page);
1107 * Save a page update draft.
1109 * @param array $data
1110 * @return PageRevision|Page
1112 public function updatePageDraft(Page $page, $data = [])
1114 // If the page itself is a draft simply update that
1117 if (isset($data['html'])) {
1118 $page->text = $this->pageToPlainText($page);
1124 // Otherwise save the data to a revision
1125 $userId = user()->id;
1126 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1128 if ($drafts->count() > 0) {
1129 $draft = $drafts->first();
1131 $draft = $this->entityProvider->pageRevision->newInstance();
1132 $draft->page_id = $page->id;
1133 $draft->slug = $page->slug;
1134 $draft->book_slug = $page->book->slug;
1135 $draft->created_by = $userId;
1136 $draft->type = 'update_draft';
1139 $draft->fill($data);
1140 if (setting('app-editor') !== 'markdown') {
1141 $draft->markdown = '';
1149 * Get a notification message concerning the editing activity on a particular page.
1151 * @param null $minRange
1154 public function getPageEditingActiveMessage(Page $page, $minRange = null)
1156 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1158 $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]);
1159 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1160 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1164 * Change the page's parent to the given entity.
1165 * @param \BookStack\Entities\Page $page
1166 * @param \BookStack\Entities\Entity $parent
1168 public function changePageParent(Page $page, Entity $parent)
1170 $book = $parent->isA('book') ? $parent : $parent->book;
1171 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1173 if ($page->book->id !== $book->id) {
1174 $page = $this->changeBook('page', $book->id, $page);
1176 $page->load('book');
1177 $this->permissionService->buildJointPermissionsForEntity($book);
1181 * Destroy a bookshelf instance
1182 * @param \BookStack\Entities\Bookshelf $shelf
1183 * @throws \Throwable
1185 public function destroyBookshelf(Bookshelf $shelf)
1187 $this->destroyEntityCommonRelations($shelf);
1192 * Destroy the provided book and all its child entities.
1193 * @param \BookStack\Entities\Book $book
1194 * @throws NotifyException
1195 * @throws \Throwable
1197 public function destroyBook(Book $book)
1199 foreach ($book->pages as $page) {
1200 $this->destroyPage($page);
1202 foreach ($book->chapters as $chapter) {
1203 $this->destroyChapter($chapter);
1205 $this->destroyEntityCommonRelations($book);
1210 * Destroy a chapter and its relations.
1211 * @param \BookStack\Entities\Chapter $chapter
1212 * @throws \Throwable
1214 public function destroyChapter(Chapter $chapter)
1216 if (count($chapter->pages) > 0) {
1217 foreach ($chapter->pages as $page) {
1218 $page->chapter_id = 0;
1222 $this->destroyEntityCommonRelations($chapter);
1227 * Destroy a given page along with its dependencies.
1229 * @throws NotifyException
1230 * @throws \Throwable
1232 public function destroyPage(Page $page)
1234 // Check if set as custom homepage
1235 $customHome = setting('app-homepage', '0:');
1236 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
1237 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
1240 $this->destroyEntityCommonRelations($page);
1242 // Delete Attached Files
1243 $attachmentService = app(AttachmentService::class);
1244 foreach ($page->attachments as $attachment) {
1245 $attachmentService->deleteFile($attachment);
1252 * Destroy or handle the common relations connected to an entity.
1253 * @param \BookStack\Entities\Entity $entity
1254 * @throws \Throwable
1256 protected function destroyEntityCommonRelations(Entity $entity)
1258 \Activity::removeEntity($entity);
1259 $entity->views()->delete();
1260 $entity->permissions()->delete();
1261 $entity->tags()->delete();
1262 $entity->comments()->delete();
1263 $this->permissionService->deleteJointPermissionsForEntity($entity);
1264 $this->searchService->deleteEntityTerms($entity);
1268 * Copy the permissions of a bookshelf to all child books.
1269 * Returns the number of books that had permissions updated.
1270 * @param \BookStack\Entities\Bookshelf $bookshelf
1272 * @throws \Throwable
1274 public function copyBookshelfPermissions(Bookshelf $bookshelf)
1276 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
1277 $shelfBooks = $bookshelf->books()->get();
1278 $updatedBookCount = 0;
1280 foreach ($shelfBooks as $book) {
1281 if (!userCan('restrictions-manage', $book)) {
1284 $book->permissions()->delete();
1285 $book->restricted = $bookshelf->restricted;
1286 $book->permissions()->createMany($shelfPermissions);
1288 $this->permissionService->buildJointPermissionsForEntity($book);
1289 $updatedBookCount++;
1292 return $updatedBookCount;