1 <?php namespace BookStack\Repos;
6 use BookStack\Exceptions\NotFoundException;
8 use BookStack\PageRevision;
9 use BookStack\Services\AttachmentService;
10 use BookStack\Services\PermissionService;
11 use BookStack\Services\SearchService;
12 use BookStack\Services\ViewService;
16 use Illuminate\Support\Collection;
39 protected $pageRevision;
42 * Base entity instances keyed by type
48 * @var PermissionService
50 protected $permissionService;
55 protected $viewService;
65 protected $searchService;
68 * EntityRepo constructor.
70 * @param Chapter $chapter
72 * @param PageRevision $pageRevision
73 * @param ViewService $viewService
74 * @param PermissionService $permissionService
75 * @param TagRepo $tagRepo
76 * @param SearchService $searchService
78 public function __construct(
79 Book $book, Chapter $chapter, Page $page, PageRevision $pageRevision,
80 ViewService $viewService, PermissionService $permissionService,
81 TagRepo $tagRepo, SearchService $searchService
85 $this->chapter = $chapter;
87 $this->pageRevision = $pageRevision;
89 'page' => $this->page,
90 'chapter' => $this->chapter,
93 $this->viewService = $viewService;
94 $this->permissionService = $permissionService;
95 $this->tagRepo = $tagRepo;
96 $this->searchService = $searchService;
100 * Get an entity instance via type.
104 protected function getEntity($type)
106 return $this->entities[strtolower($type)];
110 * Base query for searching entities via permission system
111 * @param string $type
112 * @param bool $allowDrafts
113 * @return \Illuminate\Database\Query\Builder
115 protected function entityQuery($type, $allowDrafts = false)
117 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), 'view');
118 if (strtolower($type) === 'page' && !$allowDrafts) {
119 $q = $q->where('draft', '=', false);
125 * Check if an entity with the given id exists.
130 public function exists($type, $id)
132 return $this->entityQuery($type)->where('id', '=', $id)->exists();
136 * Get an entity by ID
137 * @param string $type
139 * @param bool $allowDrafts
142 public function getById($type, $id, $allowDrafts = false)
144 return $this->entityQuery($type, $allowDrafts)->find($id);
148 * Get an entity by its url slug.
149 * @param string $type
150 * @param string $slug
151 * @param string|bool $bookSlug
153 * @throws NotFoundException
155 public function getBySlug($type, $slug, $bookSlug = false)
157 $q = $this->entityQuery($type)->where('slug', '=', $slug);
159 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
160 $q = $q->where('book_id', '=', function($query) use ($bookSlug) {
162 ->from($this->book->getTable())
163 ->where('slug', '=', $bookSlug)->limit(1);
166 $entity = $q->first();
167 if ($entity === null) throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
173 * Search through page revisions and retrieve the last page in the
174 * current book that has a slug equal to the one given.
175 * @param string $pageSlug
176 * @param string $bookSlug
179 public function getPageByOldSlug($pageSlug, $bookSlug)
181 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
182 ->whereHas('page', function ($query) {
183 $this->permissionService->enforceEntityRestrictions('page', $query);
185 ->where('type', '=', 'version')
186 ->where('book_slug', '=', $bookSlug)
187 ->orderBy('created_at', 'desc')
188 ->with('page')->first();
189 return $revision !== null ? $revision->page : null;
193 * Get all entities of a type limited by count unless count if false.
194 * @param string $type
195 * @param integer|bool $count
198 public function getAll($type, $count = 20)
200 $q = $this->entityQuery($type)->orderBy('name', 'asc');
201 if ($count !== false) $q = $q->take($count);
206 * Get all entities in a paginated format
209 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
211 public function getAllPaginated($type, $count = 10)
213 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
217 * Get the most recently created entities of the given type.
218 * @param string $type
221 * @param bool|callable $additionalQuery
224 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
226 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
227 ->orderBy('created_at', 'desc');
228 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
229 if ($additionalQuery !== false && is_callable($additionalQuery)) {
230 $additionalQuery($query);
232 return $query->skip($page * $count)->take($count)->get();
236 * Get the most recently updated entities of the given type.
237 * @param string $type
240 * @param bool|callable $additionalQuery
243 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
245 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
246 ->orderBy('updated_at', 'desc');
247 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
248 if ($additionalQuery !== false && is_callable($additionalQuery)) {
249 $additionalQuery($query);
251 return $query->skip($page * $count)->take($count)->get();
255 * Get the most recently viewed entities.
256 * @param string|bool $type
261 public function getRecentlyViewed($type, $count = 10, $page = 0)
263 $filter = is_bool($type) ? false : $this->getEntity($type);
264 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
268 * Get the latest pages added to the system with pagination.
269 * @param string $type
273 public function getRecentlyCreatedPaginated($type, $count = 20)
275 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
279 * Get the latest pages added to the system with pagination.
280 * @param string $type
284 public function getRecentlyUpdatedPaginated($type, $count = 20)
286 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
290 * Get the most popular entities base on all views.
291 * @param string|bool $type
296 public function getPopular($type, $count = 10, $page = 0)
298 $filter = is_bool($type) ? false : $this->getEntity($type);
299 return $this->viewService->getPopular($count, $page, $filter);
303 * Get draft pages owned by the current user.
307 public function getUserDraftPages($count = 20, $page = 0)
309 return $this->page->where('draft', '=', true)
310 ->where('created_by', '=', user()->id)
311 ->orderBy('updated_at', 'desc')
312 ->skip($count * $page)->take($count)->get();
316 * Get all child objects of a book.
317 * Returns a sorted collection of Pages and Chapters.
318 * Loads the book slug onto child elements to prevent access database access for getting the slug.
320 * @param bool $filterDrafts
321 * @param bool $renderPages
324 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
326 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
331 foreach ($q as $index => $rawEntity) {
332 if ($rawEntity->entity_type === 'BookStack\\Page') {
333 $entities[$index] = $this->page->newFromBuilder($rawEntity);
335 $entities[$index]->html = $rawEntity->html;
336 $entities[$index]->html = $this->renderPage($entities[$index]);
338 } else if ($rawEntity->entity_type === 'BookStack\\Chapter') {
339 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
340 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
341 $parents[$key] = $entities[$index];
342 $parents[$key]->setAttribute('pages', collect());
344 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') $tree[] = $entities[$index];
345 $entities[$index]->book = $book;
348 foreach ($entities as $entity) {
349 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') continue;
350 $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id;
351 $chapter = $parents[$parentKey];
352 $chapter->pages->push($entity);
355 return collect($tree);
359 * Get the child items for a chapter sorted by priority but
360 * with draft items floated to the top.
361 * @param Chapter $chapter
362 * @return \Illuminate\Database\Eloquent\Collection|static[]
364 public function getChapterChildren(Chapter $chapter)
366 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
367 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
372 * Get the next sequential priority for a new child element in the given book.
376 public function getNewBookPriority(Book $book)
378 $lastElem = $this->getBookChildren($book)->pop();
379 return $lastElem ? $lastElem->priority + 1 : 0;
383 * Get a new priority for a new page to be added to the given chapter.
384 * @param Chapter $chapter
387 public function getNewChapterPriority(Chapter $chapter)
389 $lastPage = $chapter->pages('DESC')->first();
390 return $lastPage !== null ? $lastPage->priority + 1 : 0;
394 * Find a suitable slug for an entity.
395 * @param string $type
396 * @param string $name
397 * @param bool|integer $currentId
398 * @param bool|integer $bookId Only pass if type is not a book
401 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
403 $slug = $this->nameToSlug($name);
404 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
405 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
411 * Check if a slug already exists in the database.
412 * @param string $type
413 * @param string $slug
414 * @param bool|integer $currentId
415 * @param bool|integer $bookId
418 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
420 $query = $this->getEntity($type)->where('slug', '=', $slug);
421 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
422 $query = $query->where('book_id', '=', $bookId);
424 if ($currentId) $query = $query->where('id', '!=', $currentId);
425 return $query->count() > 0;
429 * Updates entity restrictions from a request
431 * @param Entity $entity
433 public function updateEntityPermissionsFromRequest($request, Entity $entity)
435 $entity->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
436 $entity->permissions()->delete();
437 if ($request->has('restrictions')) {
438 foreach ($request->get('restrictions') as $roleId => $restrictions) {
439 foreach ($restrictions as $action => $value) {
440 $entity->permissions()->create([
441 'role_id' => $roleId,
442 'action' => strtolower($action)
448 $this->permissionService->buildJointPermissionsForEntity($entity);
454 * Create a new entity from request input.
455 * Used for books and chapters.
456 * @param string $type
457 * @param array $input
458 * @param bool|Book $book
461 public function createFromInput($type, $input = [], $book = false)
463 $isChapter = strtolower($type) === 'chapter';
464 $entity = $this->getEntity($type)->newInstance($input);
465 $entity->slug = $this->findSuitableSlug($type, $entity->name, false, $isChapter ? $book->id : false);
466 $entity->created_by = user()->id;
467 $entity->updated_by = user()->id;
468 $isChapter ? $book->chapters()->save($entity) : $entity->save();
469 $this->permissionService->buildJointPermissionsForEntity($entity);
470 $this->searchService->indexEntity($entity);
475 * Update entity details from request input.
476 * Used for books and chapters
477 * @param string $type
478 * @param Entity $entityModel
479 * @param array $input
482 public function updateFromInput($type, Entity $entityModel, $input = [])
484 if ($entityModel->name !== $input['name']) {
485 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
487 $entityModel->fill($input);
488 $entityModel->updated_by = user()->id;
489 $entityModel->save();
490 $this->permissionService->buildJointPermissionsForEntity($entityModel);
491 $this->searchService->indexEntity($entityModel);
496 * Change the book that an entity belongs to.
497 * @param string $type
498 * @param integer $newBookId
499 * @param Entity $entity
500 * @param bool $rebuildPermissions
503 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
505 $entity->book_id = $newBookId;
506 // Update related activity
507 foreach ($entity->activity as $activity) {
508 $activity->book_id = $newBookId;
511 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
514 // Update all child pages if a chapter
515 if (strtolower($type) === 'chapter') {
516 foreach ($entity->pages as $page) {
517 $this->changeBook('page', $newBookId, $page, false);
521 // Update permissions if applicable
522 if ($rebuildPermissions) {
523 $entity->load('book');
524 $this->permissionService->buildJointPermissionsForEntity($entity->book);
531 * Alias method to update the book jointPermissions in the PermissionService.
532 * @param Collection $collection collection on entities
534 public function buildJointPermissions(Collection $collection)
536 $this->permissionService->buildJointPermissionsForEntities($collection);
540 * Format a name as a url slug.
544 protected function nameToSlug($name)
546 $slug = str_replace(' ', '-', strtolower($name));
547 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', $slug);
548 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
553 * Publish a draft page to make it a normal page.
554 * Sets the slug and updates the content.
555 * @param Page $draftPage
556 * @param array $input
559 public function publishPageDraft(Page $draftPage, array $input)
561 $draftPage->fill($input);
563 // Save page tags if present
564 if (isset($input['tags'])) {
565 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
568 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
569 $draftPage->html = $this->formatHtml($input['html']);
570 $draftPage->text = strip_tags($draftPage->html);
571 $draftPage->draft = false;
572 $draftPage->revision_count = 1;
575 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
576 $this->searchService->indexEntity($draftPage);
581 * Saves a page revision into the system.
583 * @param null|string $summary
584 * @return PageRevision
586 public function savePageRevision(Page $page, $summary = null)
588 $revision = $this->pageRevision->newInstance($page->toArray());
589 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
590 $revision->page_id = $page->id;
591 $revision->slug = $page->slug;
592 $revision->book_slug = $page->book->slug;
593 $revision->created_by = user()->id;
594 $revision->created_at = $page->updated_at;
595 $revision->type = 'version';
596 $revision->summary = $summary;
597 $revision->revision_number = $page->revision_count;
600 // Clear old revisions
601 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
602 $this->pageRevision->where('page_id', '=', $page->id)
603 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
610 * Formats a page's html to be tagged correctly
612 * @param string $htmlText
615 protected function formatHtml($htmlText)
617 if ($htmlText == '') return $htmlText;
618 libxml_use_internal_errors(true);
619 $doc = new DOMDocument();
620 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
622 $container = $doc->documentElement;
623 $body = $container->childNodes->item(0);
624 $childNodes = $body->childNodes;
626 // Ensure no duplicate ids are used
629 foreach ($childNodes as $index => $childNode) {
630 /** @var \DOMElement $childNode */
631 if (get_class($childNode) !== 'DOMElement') continue;
633 // Overwrite id if not a BookStack custom id
634 if ($childNode->hasAttribute('id')) {
635 $id = $childNode->getAttribute('id');
636 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
642 // Create an unique id for the element
643 // Uses the content as a basis to ensure output is the same every time
644 // the same content is passed through.
645 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
646 $newId = urlencode($contentId);
648 while (in_array($newId, $idArray)) {
649 $newId = urlencode($contentId . '-' . $loopIndex);
653 $childNode->setAttribute('id', $newId);
657 // Generate inner html as a string
659 foreach ($childNodes as $childNode) {
660 $html .= $doc->saveHTML($childNode);
668 * Render the page for viewing, Parsing and performing features such as page transclusion.
670 * @return mixed|string
672 public function renderPage(Page $page)
674 $content = $page->html;
676 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
677 if (count($matches[0]) === 0) return $content;
679 foreach ($matches[1] as $index => $includeId) {
680 $splitInclude = explode('#', $includeId, 2);
681 $pageId = intval($splitInclude[0]);
682 if (is_nan($pageId)) continue;
684 $page = $this->getById('page', $pageId);
685 if ($page === null) {
686 $content = str_replace($matches[0][$index], '', $content);
690 if (count($splitInclude) === 1) {
691 $content = str_replace($matches[0][$index], $page->html, $content);
695 $doc = new DOMDocument();
696 $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
697 $matchingElem = $doc->getElementById($splitInclude[1]);
698 if ($matchingElem === null) {
699 $content = str_replace($matches[0][$index], '', $content);
703 foreach ($matchingElem->childNodes as $childNode) {
704 $innerContent .= $doc->saveHTML($childNode);
706 $content = str_replace($matches[0][$index], trim($innerContent), $content);
713 * Get a new draft page instance.
715 * @param Chapter|bool $chapter
718 public function getDraftPage(Book $book, $chapter = false)
720 $page = $this->page->newInstance();
721 $page->name = trans('entities.pages_initial_name');
722 $page->created_by = user()->id;
723 $page->updated_by = user()->id;
726 if ($chapter) $page->chapter_id = $chapter->id;
728 $book->pages()->save($page);
729 $this->permissionService->buildJointPermissionsForEntity($page);
734 * Search for image usage within page content.
735 * @param $imageString
738 public function searchForImage($imageString)
740 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
741 foreach ($pages as $page) {
742 $page->url = $page->getUrl();
746 return count($pages) > 0 ? $pages : false;
750 * Parse the headers on the page to get a navigation menu
751 * @param String $pageContent
754 public function getPageNav($pageContent)
756 if ($pageContent == '') return [];
757 libxml_use_internal_errors(true);
758 $doc = new DOMDocument();
759 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
760 $xPath = new DOMXPath($doc);
761 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
763 if (is_null($headers)) return [];
766 foreach ($headers as $header) {
767 $text = $header->nodeValue;
769 'nodeName' => strtolower($header->nodeName),
770 'level' => intval(str_replace('h', '', $header->nodeName)),
771 'link' => '#' . $header->getAttribute('id'),
772 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
776 // Normalise headers if only smaller headers have been used
777 if (count($tree) > 0) {
778 $minLevel = $tree->pluck('level')->min();
779 $tree = $tree->map(function($header) use ($minLevel) {
780 $header['level'] -= ($minLevel - 2);
784 return $tree->toArray();
788 * Updates a page with any fillable data and saves it into the database.
790 * @param int $book_id
791 * @param array $input
794 public function updatePage(Page $page, $book_id, $input)
796 // Hold the old details to compare later
797 $oldHtml = $page->html;
798 $oldName = $page->name;
800 // Prevent slug being updated if no name change
801 if ($page->name !== $input['name']) {
802 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
805 // Save page tags if present
806 if (isset($input['tags'])) {
807 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
810 // Update with new details
811 $userId = user()->id;
813 $page->html = $this->formatHtml($input['html']);
814 $page->text = strip_tags($page->html);
815 if (setting('app-editor') !== 'markdown') $page->markdown = '';
816 $page->updated_by = $userId;
817 $page->revision_count++;
820 // Remove all update drafts for this user & page.
821 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
823 // Save a revision after updating
824 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
825 $this->savePageRevision($page, $input['summary']);
828 $this->searchService->indexEntity($page);
834 * The base query for getting user update drafts.
839 protected function userUpdatePageDraftsQuery(Page $page, $userId)
841 return $this->pageRevision->where('created_by', '=', $userId)
842 ->where('type', 'update_draft')
843 ->where('page_id', '=', $page->id)
844 ->orderBy('created_at', 'desc');
848 * Checks whether a user has a draft version of a particular page or not.
853 public function hasUserGotPageDraft(Page $page, $userId)
855 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
859 * Get the latest updated draft revision for a particular page and user.
864 public function getUserPageDraft(Page $page, $userId)
866 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
870 * Get the notification message that informs the user that they are editing a draft page.
871 * @param PageRevision $draft
874 public function getUserPageDraftMessage(PageRevision $draft)
876 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
877 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
878 return $message . "\n" . trans('entities.pages_draft_edited_notification');
882 * Check if a page is being actively editing.
883 * Checks for edits since last page updated.
884 * Passing in a minuted range will check for edits
885 * within the last x minutes.
887 * @param null $minRange
890 public function isPageEditingActive(Page $page, $minRange = null)
892 $draftSearch = $this->activePageEditingQuery($page, $minRange);
893 return $draftSearch->count() > 0;
897 * A query to check for active update drafts on a particular page.
899 * @param null $minRange
902 protected function activePageEditingQuery(Page $page, $minRange = null)
904 $query = $this->pageRevision->where('type', '=', 'update_draft')
905 ->where('page_id', '=', $page->id)
906 ->where('updated_at', '>', $page->updated_at)
907 ->where('created_by', '!=', user()->id)
910 if ($minRange !== null) {
911 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
918 * Restores a revision's content back into a page.
921 * @param int $revisionId
924 public function restorePageRevision(Page $page, Book $book, $revisionId)
926 $page->revision_count++;
927 $this->savePageRevision($page);
928 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
929 $page->fill($revision->toArray());
930 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
931 $page->text = strip_tags($page->html);
932 $page->updated_by = user()->id;
934 $this->searchService->indexEntity($page);
940 * Save a page update draft.
943 * @return PageRevision|Page
945 public function updatePageDraft(Page $page, $data = [])
947 // If the page itself is a draft simply update that
950 if (isset($data['html'])) {
951 $page->text = strip_tags($data['html']);
957 // Otherwise save the data to a revision
958 $userId = user()->id;
959 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
961 if ($drafts->count() > 0) {
962 $draft = $drafts->first();
964 $draft = $this->pageRevision->newInstance();
965 $draft->page_id = $page->id;
966 $draft->slug = $page->slug;
967 $draft->book_slug = $page->book->slug;
968 $draft->created_by = $userId;
969 $draft->type = 'update_draft';
973 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
980 * Get a notification message concerning the editing activity on a particular page.
982 * @param null $minRange
985 public function getPageEditingActiveMessage(Page $page, $minRange = null)
987 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
989 $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]);
990 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
991 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
995 * Change the page's parent to the given entity.
997 * @param Entity $parent
999 public function changePageParent(Page $page, Entity $parent)
1001 $book = $parent->isA('book') ? $parent : $parent->book;
1002 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1004 if ($page->book->id !== $book->id) {
1005 $page = $this->changeBook('page', $book->id, $page);
1007 $page->load('book');
1008 $this->permissionService->buildJointPermissionsForEntity($book);
1012 * Destroy the provided book and all its child entities.
1015 public function destroyBook(Book $book)
1017 foreach ($book->pages as $page) {
1018 $this->destroyPage($page);
1020 foreach ($book->chapters as $chapter) {
1021 $this->destroyChapter($chapter);
1023 \Activity::removeEntity($book);
1024 $book->views()->delete();
1025 $book->permissions()->delete();
1026 $this->permissionService->deleteJointPermissionsForEntity($book);
1027 $this->searchService->deleteEntityTerms($book);
1032 * Destroy a chapter and its relations.
1033 * @param Chapter $chapter
1035 public function destroyChapter(Chapter $chapter)
1037 if (count($chapter->pages) > 0) {
1038 foreach ($chapter->pages as $page) {
1039 $page->chapter_id = 0;
1043 \Activity::removeEntity($chapter);
1044 $chapter->views()->delete();
1045 $chapter->permissions()->delete();
1046 $this->permissionService->deleteJointPermissionsForEntity($chapter);
1047 $this->searchService->deleteEntityTerms($chapter);
1052 * Destroy a given page along with its dependencies.
1055 public function destroyPage(Page $page)
1057 \Activity::removeEntity($page);
1058 $page->views()->delete();
1059 $page->tags()->delete();
1060 $page->revisions()->delete();
1061 $page->permissions()->delete();
1062 $this->permissionService->deleteJointPermissionsForEntity($page);
1063 $this->searchService->deleteEntityTerms($page);
1065 // Delete Attached Files
1066 $attachmentService = app(AttachmentService::class);
1067 foreach ($page->attachments as $attachment) {
1068 $attachmentService->deleteFile($attachment);