1 <?php namespace BookStack\Repos;
6 use BookStack\Exceptions\NotFoundException;
7 use BookStack\Exceptions\NotifyException;
9 use BookStack\PageRevision;
10 use BookStack\Services\AttachmentService;
11 use BookStack\Services\PermissionService;
12 use BookStack\Services\SearchService;
13 use BookStack\Services\ViewService;
17 use Illuminate\Support\Collection;
40 protected $pageRevision;
43 * Base entity instances keyed by type
49 * @var PermissionService
51 protected $permissionService;
56 protected $viewService;
66 protected $searchService;
69 * EntityRepo constructor.
71 * @param Chapter $chapter
73 * @param PageRevision $pageRevision
74 * @param ViewService $viewService
75 * @param PermissionService $permissionService
76 * @param TagRepo $tagRepo
77 * @param SearchService $searchService
79 public function __construct(
80 Book $book, Chapter $chapter, Page $page, PageRevision $pageRevision,
81 ViewService $viewService, PermissionService $permissionService,
82 TagRepo $tagRepo, SearchService $searchService
86 $this->chapter = $chapter;
88 $this->pageRevision = $pageRevision;
90 'page' => $this->page,
91 'chapter' => $this->chapter,
94 $this->viewService = $viewService;
95 $this->permissionService = $permissionService;
96 $this->tagRepo = $tagRepo;
97 $this->searchService = $searchService;
101 * Get an entity instance via type.
105 protected function getEntity($type)
107 return $this->entities[strtolower($type)];
111 * Base query for searching entities via permission system
112 * @param string $type
113 * @param bool $allowDrafts
114 * @return \Illuminate\Database\Query\Builder
116 protected function entityQuery($type, $allowDrafts = false)
118 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), 'view');
119 if (strtolower($type) === 'page' && !$allowDrafts) {
120 $q = $q->where('draft', '=', false);
126 * Check if an entity with the given id exists.
131 public function exists($type, $id)
133 return $this->entityQuery($type)->where('id', '=', $id)->exists();
137 * Get an entity by ID
138 * @param string $type
140 * @param bool $allowDrafts
141 * @param bool $ignorePermissions
144 public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
146 if ($ignorePermissions) {
147 $entity = $this->getEntity($type);
148 return $entity->newQuery()->find($id);
150 return $this->entityQuery($type, $allowDrafts)->find($id);
154 * Get an entity by its url slug.
155 * @param string $type
156 * @param string $slug
157 * @param string|bool $bookSlug
159 * @throws NotFoundException
161 public function getBySlug($type, $slug, $bookSlug = false)
163 $q = $this->entityQuery($type)->where('slug', '=', $slug);
165 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
166 $q = $q->where('book_id', '=', function($query) use ($bookSlug) {
168 ->from($this->book->getTable())
169 ->where('slug', '=', $bookSlug)->limit(1);
172 $entity = $q->first();
173 if ($entity === null) throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
179 * Search through page revisions and retrieve the last page in the
180 * current book that has a slug equal to the one given.
181 * @param string $pageSlug
182 * @param string $bookSlug
185 public function getPageByOldSlug($pageSlug, $bookSlug)
187 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
188 ->whereHas('page', function ($query) {
189 $this->permissionService->enforceEntityRestrictions('page', $query);
191 ->where('type', '=', 'version')
192 ->where('book_slug', '=', $bookSlug)
193 ->orderBy('created_at', 'desc')
194 ->with('page')->first();
195 return $revision !== null ? $revision->page : null;
199 * Get all entities of a type limited by count unless count if false.
200 * @param string $type
201 * @param integer|bool $count
204 public function getAll($type, $count = 20)
206 $q = $this->entityQuery($type)->orderBy('name', 'asc');
207 if ($count !== false) $q = $q->take($count);
212 * Get all entities in a paginated format
215 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
217 public function getAllPaginated($type, $count = 10)
219 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
223 * Get the most recently created entities of the given type.
224 * @param string $type
227 * @param bool|callable $additionalQuery
230 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
232 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
233 ->orderBy('created_at', 'desc');
234 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
235 if ($additionalQuery !== false && is_callable($additionalQuery)) {
236 $additionalQuery($query);
238 return $query->skip($page * $count)->take($count)->get();
242 * Get the most recently updated entities of the given type.
243 * @param string $type
246 * @param bool|callable $additionalQuery
249 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
251 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
252 ->orderBy('updated_at', 'desc');
253 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
254 if ($additionalQuery !== false && is_callable($additionalQuery)) {
255 $additionalQuery($query);
257 return $query->skip($page * $count)->take($count)->get();
261 * Get the most recently viewed entities.
262 * @param string|bool $type
267 public function getRecentlyViewed($type, $count = 10, $page = 0)
269 $filter = is_bool($type) ? false : $this->getEntity($type);
270 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
274 * Get the latest pages added to the system with pagination.
275 * @param string $type
279 public function getRecentlyCreatedPaginated($type, $count = 20)
281 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
285 * Get the latest pages added to the system with pagination.
286 * @param string $type
290 public function getRecentlyUpdatedPaginated($type, $count = 20)
292 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
296 * Get the most popular entities base on all views.
297 * @param string|bool $type
302 public function getPopular($type, $count = 10, $page = 0)
304 $filter = is_bool($type) ? false : $this->getEntity($type);
305 return $this->viewService->getPopular($count, $page, $filter);
309 * Get draft pages owned by the current user.
313 public function getUserDraftPages($count = 20, $page = 0)
315 return $this->page->where('draft', '=', true)
316 ->where('created_by', '=', user()->id)
317 ->orderBy('updated_at', 'desc')
318 ->skip($count * $page)->take($count)->get();
322 * Get all child objects of a book.
323 * Returns a sorted collection of Pages and Chapters.
324 * Loads the book slug onto child elements to prevent access database access for getting the slug.
326 * @param bool $filterDrafts
327 * @param bool $renderPages
330 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
332 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
337 foreach ($q as $index => $rawEntity) {
338 if ($rawEntity->entity_type === 'BookStack\\Page') {
339 $entities[$index] = $this->page->newFromBuilder($rawEntity);
341 $entities[$index]->html = $rawEntity->html;
342 $entities[$index]->html = $this->renderPage($entities[$index]);
344 } else if ($rawEntity->entity_type === 'BookStack\\Chapter') {
345 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
346 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
347 $parents[$key] = $entities[$index];
348 $parents[$key]->setAttribute('pages', collect());
350 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') $tree[] = $entities[$index];
351 $entities[$index]->book = $book;
354 foreach ($entities as $entity) {
355 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') continue;
356 $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id;
357 if (!isset($parents[$parentKey])) {
361 $chapter = $parents[$parentKey];
362 $chapter->pages->push($entity);
365 return collect($tree);
369 * Get the child items for a chapter sorted by priority but
370 * with draft items floated to the top.
371 * @param Chapter $chapter
372 * @return \Illuminate\Database\Eloquent\Collection|static[]
374 public function getChapterChildren(Chapter $chapter)
376 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
377 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
382 * Get the next sequential priority for a new child element in the given book.
386 public function getNewBookPriority(Book $book)
388 $lastElem = $this->getBookChildren($book)->pop();
389 return $lastElem ? $lastElem->priority + 1 : 0;
393 * Get a new priority for a new page to be added to the given chapter.
394 * @param Chapter $chapter
397 public function getNewChapterPriority(Chapter $chapter)
399 $lastPage = $chapter->pages('DESC')->first();
400 return $lastPage !== null ? $lastPage->priority + 1 : 0;
404 * Find a suitable slug for an entity.
405 * @param string $type
406 * @param string $name
407 * @param bool|integer $currentId
408 * @param bool|integer $bookId Only pass if type is not a book
411 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
413 $slug = $this->nameToSlug($name);
414 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
415 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
421 * Check if a slug already exists in the database.
422 * @param string $type
423 * @param string $slug
424 * @param bool|integer $currentId
425 * @param bool|integer $bookId
428 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
430 $query = $this->getEntity($type)->where('slug', '=', $slug);
431 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
432 $query = $query->where('book_id', '=', $bookId);
434 if ($currentId) $query = $query->where('id', '!=', $currentId);
435 return $query->count() > 0;
439 * Updates entity restrictions from a request
441 * @param Entity $entity
443 public function updateEntityPermissionsFromRequest($request, Entity $entity)
445 $entity->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
446 $entity->permissions()->delete();
447 if ($request->has('restrictions')) {
448 foreach ($request->get('restrictions') as $roleId => $restrictions) {
449 foreach ($restrictions as $action => $value) {
450 $entity->permissions()->create([
451 'role_id' => $roleId,
452 'action' => strtolower($action)
458 $this->permissionService->buildJointPermissionsForEntity($entity);
464 * Create a new entity from request input.
465 * Used for books and chapters.
466 * @param string $type
467 * @param array $input
468 * @param bool|Book $book
471 public function createFromInput($type, $input = [], $book = false)
473 $isChapter = strtolower($type) === 'chapter';
474 $entity = $this->getEntity($type)->newInstance($input);
475 $entity->slug = $this->findSuitableSlug($type, $entity->name, false, $isChapter ? $book->id : false);
476 $entity->created_by = user()->id;
477 $entity->updated_by = user()->id;
478 $isChapter ? $book->chapters()->save($entity) : $entity->save();
479 $this->permissionService->buildJointPermissionsForEntity($entity);
480 $this->searchService->indexEntity($entity);
485 * Update entity details from request input.
486 * Used for books and chapters
487 * @param string $type
488 * @param Entity $entityModel
489 * @param array $input
492 public function updateFromInput($type, Entity $entityModel, $input = [])
494 if ($entityModel->name !== $input['name']) {
495 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
497 $entityModel->fill($input);
498 $entityModel->updated_by = user()->id;
499 $entityModel->save();
500 $this->permissionService->buildJointPermissionsForEntity($entityModel);
501 $this->searchService->indexEntity($entityModel);
506 * Change the book that an entity belongs to.
507 * @param string $type
508 * @param integer $newBookId
509 * @param Entity $entity
510 * @param bool $rebuildPermissions
513 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
515 $entity->book_id = $newBookId;
516 // Update related activity
517 foreach ($entity->activity as $activity) {
518 $activity->book_id = $newBookId;
521 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
524 // Update all child pages if a chapter
525 if (strtolower($type) === 'chapter') {
526 foreach ($entity->pages as $page) {
527 $this->changeBook('page', $newBookId, $page, false);
531 // Update permissions if applicable
532 if ($rebuildPermissions) {
533 $entity->load('book');
534 $this->permissionService->buildJointPermissionsForEntity($entity->book);
541 * Alias method to update the book jointPermissions in the PermissionService.
544 public function buildJointPermissionsForBook(Book $book)
546 $this->permissionService->buildJointPermissionsForEntity($book);
550 * Format a name as a url slug.
554 protected function nameToSlug($name)
556 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
557 $slug = preg_replace('/\s{2,}/', ' ', $slug);
558 $slug = str_replace(' ', '-', $slug);
559 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
564 * Publish a draft page to make it a normal page.
565 * Sets the slug and updates the content.
566 * @param Page $draftPage
567 * @param array $input
570 public function publishPageDraft(Page $draftPage, array $input)
572 $draftPage->fill($input);
574 // Save page tags if present
575 if (isset($input['tags'])) {
576 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
579 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
580 $draftPage->html = $this->formatHtml($input['html']);
581 $draftPage->text = $this->pageToPlainText($draftPage);
582 $draftPage->draft = false;
583 $draftPage->revision_count = 1;
586 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
587 $this->searchService->indexEntity($draftPage);
592 * Saves a page revision into the system.
594 * @param null|string $summary
595 * @return PageRevision
597 public function savePageRevision(Page $page, $summary = null)
599 $revision = $this->pageRevision->newInstance($page->toArray());
600 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
601 $revision->page_id = $page->id;
602 $revision->slug = $page->slug;
603 $revision->book_slug = $page->book->slug;
604 $revision->created_by = user()->id;
605 $revision->created_at = $page->updated_at;
606 $revision->type = 'version';
607 $revision->summary = $summary;
608 $revision->revision_number = $page->revision_count;
611 // Clear old revisions
612 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
613 $this->pageRevision->where('page_id', '=', $page->id)
614 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
621 * Formats a page's html to be tagged correctly
623 * @param string $htmlText
626 protected function formatHtml($htmlText)
628 if ($htmlText == '') return $htmlText;
629 libxml_use_internal_errors(true);
630 $doc = new DOMDocument();
631 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
633 $container = $doc->documentElement;
634 $body = $container->childNodes->item(0);
635 $childNodes = $body->childNodes;
637 // Ensure no duplicate ids are used
640 foreach ($childNodes as $index => $childNode) {
641 /** @var \DOMElement $childNode */
642 if (get_class($childNode) !== 'DOMElement') continue;
644 // Overwrite id if not a BookStack custom id
645 if ($childNode->hasAttribute('id')) {
646 $id = $childNode->getAttribute('id');
647 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
653 // Create an unique id for the element
654 // Uses the content as a basis to ensure output is the same every time
655 // the same content is passed through.
656 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
657 $newId = urlencode($contentId);
659 while (in_array($newId, $idArray)) {
660 $newId = urlencode($contentId . '-' . $loopIndex);
664 $childNode->setAttribute('id', $newId);
668 // Generate inner html as a string
670 foreach ($childNodes as $childNode) {
671 $html .= $doc->saveHTML($childNode);
679 * Render the page for viewing, Parsing and performing features such as page transclusion.
681 * @param bool $ignorePermissions
682 * @return mixed|string
684 public function renderPage(Page $page, $ignorePermissions = false)
686 $content = $page->html;
688 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
689 if (count($matches[0]) === 0) return $content;
691 foreach ($matches[1] as $index => $includeId) {
692 $splitInclude = explode('#', $includeId, 2);
693 $pageId = intval($splitInclude[0]);
694 if (is_nan($pageId)) continue;
696 $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
697 if ($matchedPage === null) {
698 $content = str_replace($matches[0][$index], '', $content);
702 if (count($splitInclude) === 1) {
703 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
707 $doc = new DOMDocument();
708 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
709 $matchingElem = $doc->getElementById($splitInclude[1]);
710 if ($matchingElem === null) {
711 $content = str_replace($matches[0][$index], '', $content);
715 foreach ($matchingElem->childNodes as $childNode) {
716 $innerContent .= $doc->saveHTML($childNode);
718 $content = str_replace($matches[0][$index], trim($innerContent), $content);
725 * Get the plain text version of a page's content.
729 public function pageToPlainText(Page $page)
731 $html = $this->renderPage($page);
732 return strip_tags($html);
736 * Get a new draft page instance.
738 * @param Chapter|bool $chapter
741 public function getDraftPage(Book $book, $chapter = false)
743 $page = $this->page->newInstance();
744 $page->name = trans('entities.pages_initial_name');
745 $page->created_by = user()->id;
746 $page->updated_by = user()->id;
749 if ($chapter) $page->chapter_id = $chapter->id;
751 $book->pages()->save($page);
752 $page = $this->page->find($page->id);
753 $this->permissionService->buildJointPermissionsForEntity($page);
758 * Search for image usage within page content.
759 * @param $imageString
762 public function searchForImage($imageString)
764 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
765 foreach ($pages as $page) {
766 $page->url = $page->getUrl();
770 return count($pages) > 0 ? $pages : false;
774 * Parse the headers on the page to get a navigation menu
775 * @param String $pageContent
778 public function getPageNav($pageContent)
780 if ($pageContent == '') return [];
781 libxml_use_internal_errors(true);
782 $doc = new DOMDocument();
783 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
784 $xPath = new DOMXPath($doc);
785 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
787 if (is_null($headers)) return [];
790 foreach ($headers as $header) {
791 $text = $header->nodeValue;
793 'nodeName' => strtolower($header->nodeName),
794 'level' => intval(str_replace('h', '', $header->nodeName)),
795 'link' => '#' . $header->getAttribute('id'),
796 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
800 // Normalise headers if only smaller headers have been used
801 if (count($tree) > 0) {
802 $minLevel = $tree->pluck('level')->min();
803 $tree = $tree->map(function($header) use ($minLevel) {
804 $header['level'] -= ($minLevel - 2);
808 return $tree->toArray();
812 * Updates a page with any fillable data and saves it into the database.
814 * @param int $book_id
815 * @param array $input
818 public function updatePage(Page $page, $book_id, $input)
820 // Hold the old details to compare later
821 $oldHtml = $page->html;
822 $oldName = $page->name;
824 // Prevent slug being updated if no name change
825 if ($page->name !== $input['name']) {
826 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
829 // Save page tags if present
830 if (isset($input['tags'])) {
831 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
834 // Update with new details
835 $userId = user()->id;
837 $page->html = $this->formatHtml($input['html']);
838 $page->text = $this->pageToPlainText($page);
839 if (setting('app-editor') !== 'markdown') $page->markdown = '';
840 $page->updated_by = $userId;
841 $page->revision_count++;
844 // Remove all update drafts for this user & page.
845 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
847 // Save a revision after updating
848 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
849 $this->savePageRevision($page, $input['summary']);
852 $this->searchService->indexEntity($page);
858 * The base query for getting user update drafts.
863 protected function userUpdatePageDraftsQuery(Page $page, $userId)
865 return $this->pageRevision->where('created_by', '=', $userId)
866 ->where('type', 'update_draft')
867 ->where('page_id', '=', $page->id)
868 ->orderBy('created_at', 'desc');
872 * Checks whether a user has a draft version of a particular page or not.
877 public function hasUserGotPageDraft(Page $page, $userId)
879 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
883 * Get the latest updated draft revision for a particular page and user.
888 public function getUserPageDraft(Page $page, $userId)
890 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
894 * Get the notification message that informs the user that they are editing a draft page.
895 * @param PageRevision $draft
898 public function getUserPageDraftMessage(PageRevision $draft)
900 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
901 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
902 return $message . "\n" . trans('entities.pages_draft_edited_notification');
906 * Check if a page is being actively editing.
907 * Checks for edits since last page updated.
908 * Passing in a minuted range will check for edits
909 * within the last x minutes.
911 * @param null $minRange
914 public function isPageEditingActive(Page $page, $minRange = null)
916 $draftSearch = $this->activePageEditingQuery($page, $minRange);
917 return $draftSearch->count() > 0;
921 * A query to check for active update drafts on a particular page.
923 * @param null $minRange
926 protected function activePageEditingQuery(Page $page, $minRange = null)
928 $query = $this->pageRevision->where('type', '=', 'update_draft')
929 ->where('page_id', '=', $page->id)
930 ->where('updated_at', '>', $page->updated_at)
931 ->where('created_by', '!=', user()->id)
934 if ($minRange !== null) {
935 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
942 * Restores a revision's content back into a page.
945 * @param int $revisionId
948 public function restorePageRevision(Page $page, Book $book, $revisionId)
950 $page->revision_count++;
951 $this->savePageRevision($page);
952 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
953 $page->fill($revision->toArray());
954 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
955 $page->text = $this->pageToPlainText($page);
956 $page->updated_by = user()->id;
958 $this->searchService->indexEntity($page);
964 * Save a page update draft.
967 * @return PageRevision|Page
969 public function updatePageDraft(Page $page, $data = [])
971 // If the page itself is a draft simply update that
974 if (isset($data['html'])) {
975 $page->text = $this->pageToPlainText($page);
981 // Otherwise save the data to a revision
982 $userId = user()->id;
983 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
985 if ($drafts->count() > 0) {
986 $draft = $drafts->first();
988 $draft = $this->pageRevision->newInstance();
989 $draft->page_id = $page->id;
990 $draft->slug = $page->slug;
991 $draft->book_slug = $page->book->slug;
992 $draft->created_by = $userId;
993 $draft->type = 'update_draft';
997 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
1004 * Get a notification message concerning the editing activity on a particular page.
1006 * @param null $minRange
1009 public function getPageEditingActiveMessage(Page $page, $minRange = null)
1011 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1013 $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]);
1014 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1015 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1019 * Change the page's parent to the given entity.
1021 * @param Entity $parent
1023 public function changePageParent(Page $page, Entity $parent)
1025 $book = $parent->isA('book') ? $parent : $parent->book;
1026 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1028 if ($page->book->id !== $book->id) {
1029 $page = $this->changeBook('page', $book->id, $page);
1031 $page->load('book');
1032 $this->permissionService->buildJointPermissionsForEntity($book);
1036 * Destroy the provided book and all its child entities.
1039 public function destroyBook(Book $book)
1041 foreach ($book->pages as $page) {
1042 $this->destroyPage($page);
1044 foreach ($book->chapters as $chapter) {
1045 $this->destroyChapter($chapter);
1047 \Activity::removeEntity($book);
1048 $book->views()->delete();
1049 $book->permissions()->delete();
1050 $this->permissionService->deleteJointPermissionsForEntity($book);
1051 $this->searchService->deleteEntityTerms($book);
1056 * Destroy a chapter and its relations.
1057 * @param Chapter $chapter
1059 public function destroyChapter(Chapter $chapter)
1061 if (count($chapter->pages) > 0) {
1062 foreach ($chapter->pages as $page) {
1063 $page->chapter_id = 0;
1067 \Activity::removeEntity($chapter);
1068 $chapter->views()->delete();
1069 $chapter->permissions()->delete();
1070 $this->permissionService->deleteJointPermissionsForEntity($chapter);
1071 $this->searchService->deleteEntityTerms($chapter);
1076 * Destroy a given page along with its dependencies.
1078 * @throws NotifyException
1080 public function destroyPage(Page $page)
1082 \Activity::removeEntity($page);
1083 $page->views()->delete();
1084 $page->tags()->delete();
1085 $page->revisions()->delete();
1086 $page->permissions()->delete();
1087 $this->permissionService->deleteJointPermissionsForEntity($page);
1088 $this->searchService->deleteEntityTerms($page);
1090 // Check if set as custom homepage
1091 $customHome = setting('app-homepage', '0:');
1092 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
1093 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
1096 // Delete Attached Files
1097 $attachmentService = app(AttachmentService::class);
1098 foreach ($page->attachments as $attachment) {
1099 $attachmentService->deleteFile($attachment);