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\ViewService;
15 use Illuminate\Support\Collection;
38 protected $pageRevision;
41 * Base entity instances keyed by type
47 * @var PermissionService
49 protected $permissionService;
54 protected $viewService;
62 * Acceptable operators to be used in a query
65 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
68 * EntityService constructor.
70 * @param Chapter $chapter
72 * @param PageRevision $pageRevision
73 * @param ViewService $viewService
74 * @param PermissionService $permissionService
75 * @param TagRepo $tagRepo
77 public function __construct(
78 Book $book, Chapter $chapter, Page $page, PageRevision $pageRevision,
79 ViewService $viewService, PermissionService $permissionService, TagRepo $tagRepo
83 $this->chapter = $chapter;
85 $this->pageRevision = $pageRevision;
87 'page' => $this->page,
88 'chapter' => $this->chapter,
89 'book' => $this->book,
90 'page_revision' => $this->pageRevision
92 $this->viewService = $viewService;
93 $this->permissionService = $permissionService;
94 $this->tagRepo = $tagRepo;
98 * Get an entity instance via type.
102 protected function getEntity($type)
104 return $this->entities[strtolower($type)];
108 * Base query for searching entities via permission system
109 * @param string $type
110 * @param bool $allowDrafts
111 * @return \Illuminate\Database\Query\Builder
113 protected function entityQuery($type, $allowDrafts = false)
115 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), 'view');
116 if (strtolower($type) === 'page' && !$allowDrafts) {
117 $q = $q->where('draft', '=', false);
123 * Check if an entity with the given id exists.
128 public function exists($type, $id)
130 return $this->entityQuery($type)->where('id', '=', $id)->exists();
134 * Get an entity by ID
135 * @param string $type
137 * @param bool $allowDrafts
140 public function getById($type, $id, $allowDrafts = false)
142 return $this->entityQuery($type, $allowDrafts)->findOrFail($id);
146 * Get an entity by its url slug.
147 * @param string $type
148 * @param string $slug
149 * @param string|bool $bookSlug
151 * @throws NotFoundException
153 public function getBySlug($type, $slug, $bookSlug = false)
155 $q = $this->entityQuery($type)->where('slug', '=', $slug);
157 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
158 $q = $q->where('book_id', '=', function($query) use ($bookSlug) {
160 ->from($this->book->getTable())
161 ->where('slug', '=', $bookSlug)->limit(1);
164 $entity = $q->first();
165 if ($entity === null) throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
171 * Search through page revisions and retrieve the last page in the
172 * current book that has a slug equal to the one given.
173 * @param string $pageSlug
174 * @param string $bookSlug
177 public function getPageByOldSlug($pageSlug, $bookSlug)
179 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
180 ->whereHas('page', function ($query) {
181 $this->permissionService->enforceEntityRestrictions('page', $query);
183 ->where('type', '=', 'version')
184 ->where('book_slug', '=', $bookSlug)
185 ->orderBy('created_at', 'desc')
186 ->with('page')->first();
187 return $revision !== null ? $revision->page : null;
191 * Get all entities of a type limited by count unless count if false.
192 * @param string $type
193 * @param integer|bool $count
196 public function getAll($type, $count = 20)
198 $q = $this->entityQuery($type)->orderBy('name', 'asc');
199 if ($count !== false) $q = $q->take($count);
204 * Get all entities in a paginated format
207 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
209 public function getAllPaginated($type, $count = 10)
211 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
215 * Get the most recently created entities of the given type.
216 * @param string $type
219 * @param bool|callable $additionalQuery
221 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
223 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
224 ->orderBy('created_at', 'desc');
225 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
226 if ($additionalQuery !== false && is_callable($additionalQuery)) {
227 $additionalQuery($query);
229 return $query->skip($page * $count)->take($count)->get();
233 * Get the most recently updated entities of the given type.
234 * @param string $type
237 * @param bool|callable $additionalQuery
239 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
241 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
242 ->orderBy('updated_at', 'desc');
243 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
244 if ($additionalQuery !== false && is_callable($additionalQuery)) {
245 $additionalQuery($query);
247 return $query->skip($page * $count)->take($count)->get();
251 * Get the most recently viewed entities.
252 * @param string|bool $type
257 public function getRecentlyViewed($type, $count = 10, $page = 0)
259 $filter = is_bool($type) ? false : $this->getEntity($type);
260 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
264 * Get the latest pages added to the system with pagination.
265 * @param string $type
269 public function getRecentlyCreatedPaginated($type, $count = 20)
271 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
275 * Get the latest pages added to the system with pagination.
276 * @param string $type
280 public function getRecentlyUpdatedPaginated($type, $count = 20)
282 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
286 * Get the most popular entities base on all views.
287 * @param string|bool $type
292 public function getPopular($type, $count = 10, $page = 0)
294 $filter = is_bool($type) ? false : $this->getEntity($type);
295 return $this->viewService->getPopular($count, $page, $filter);
299 * Get draft pages owned by the current user.
303 public function getUserDraftPages($count = 20, $page = 0)
305 return $this->page->where('draft', '=', true)
306 ->where('created_by', '=', user()->id)
307 ->orderBy('updated_at', 'desc')
308 ->skip($count * $page)->take($count)->get();
312 * Get all child objects of a book.
313 * Returns a sorted collection of Pages and Chapters.
314 * Loads the book slug onto child elements to prevent access database access for getting the slug.
316 * @param bool $filterDrafts
319 public function getBookChildren(Book $book, $filterDrafts = false)
321 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts)->get();
326 foreach ($q as $index => $rawEntity) {
327 if ($rawEntity->entity_type === 'BookStack\\Page') {
328 $entities[$index] = $this->page->newFromBuilder($rawEntity);
329 } else if ($rawEntity->entity_type === 'BookStack\\Chapter') {
330 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
331 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
332 $parents[$key] = $entities[$index];
333 $parents[$key]->setAttribute('pages', collect());
335 if ($entities[$index]->chapter_id === 0) $tree[] = $entities[$index];
336 $entities[$index]->book = $book;
339 foreach ($entities as $entity) {
340 if ($entity->chapter_id === 0) continue;
341 $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id;
342 $chapter = $parents[$parentKey];
343 $chapter->pages->push($entity);
346 return collect($tree);
350 * Get the child items for a chapter sorted by priority but
351 * with draft items floated to the top.
352 * @param Chapter $chapter
354 public function getChapterChildren(Chapter $chapter)
356 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
357 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
361 * Search entities of a type via a given query.
362 * @param string $type
363 * @param string $term
364 * @param array $whereTerms
366 * @param array $paginationAppends
369 public function getBySearch($type, $term, $whereTerms = [], $count = 20, $paginationAppends = [])
371 $terms = $this->prepareSearchTerms($term);
372 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type)->fullTextSearchQuery($terms, $whereTerms));
373 $q = $this->addAdvancedSearchQueries($q, $term);
374 $entities = $q->paginate($count)->appends($paginationAppends);
375 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
377 // Highlight page content
378 if ($type === 'page') {
379 //lookahead/behind assertions ensures cut between words
380 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
382 foreach ($entities as $page) {
383 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
384 //delimiter between occurrences
386 foreach ($matches as $line) {
387 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
390 if (count($results) > $matchLimit) $results = array_slice($results, 0, $matchLimit);
391 $result = join('... ', $results);
394 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
395 if (strlen($result) < 5) $result = $page->getExcerpt(80);
397 $page->searchSnippet = $result;
402 // Highlight chapter/book content
403 foreach ($entities as $entity) {
405 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $entity->getExcerpt(100));
406 $entity->searchSnippet = $result;
412 * Get the next sequential priority for a new child element in the given book.
416 public function getNewBookPriority(Book $book)
418 $lastElem = $this->getBookChildren($book)->pop();
419 return $lastElem ? $lastElem->priority + 1 : 0;
423 * Get a new priority for a new page to be added to the given chapter.
424 * @param Chapter $chapter
427 public function getNewChapterPriority(Chapter $chapter)
429 $lastPage = $chapter->pages('DESC')->first();
430 return $lastPage !== null ? $lastPage->priority + 1 : 0;
434 * Find a suitable slug for an entity.
435 * @param string $type
436 * @param string $name
437 * @param bool|integer $currentId
438 * @param bool|integer $bookId Only pass if type is not a book
441 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
443 $slug = $this->nameToSlug($name);
444 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
445 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
451 * Check if a slug already exists in the database.
452 * @param string $type
453 * @param string $slug
454 * @param bool|integer $currentId
455 * @param bool|integer $bookId
458 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
460 $query = $this->getEntity($type)->where('slug', '=', $slug);
461 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
462 $query = $query->where('book_id', '=', $bookId);
464 if ($currentId) $query = $query->where('id', '!=', $currentId);
465 return $query->count() > 0;
469 * Updates entity restrictions from a request
471 * @param Entity $entity
473 public function updateEntityPermissionsFromRequest($request, Entity $entity)
475 $entity->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
476 $entity->permissions()->delete();
477 if ($request->has('restrictions')) {
478 foreach ($request->get('restrictions') as $roleId => $restrictions) {
479 foreach ($restrictions as $action => $value) {
480 $entity->permissions()->create([
481 'role_id' => $roleId,
482 'action' => strtolower($action)
488 $this->permissionService->buildJointPermissionsForEntity($entity);
492 * Prepare a string of search terms by turning
493 * it into an array of terms.
494 * Keeps quoted terms together.
498 public function prepareSearchTerms($termString)
500 $termString = $this->cleanSearchTermString($termString);
501 preg_match_all('/(".*?")/', $termString, $matches);
503 if (count($matches[1]) > 0) {
504 foreach ($matches[1] as $match) {
507 $termString = trim(preg_replace('/"(.*?)"/', '', $termString));
509 if (!empty($termString)) $terms = array_merge($terms, explode(' ', $termString));
514 * Removes any special search notation that should not
515 * be used in a full-text search.
519 protected function cleanSearchTermString($termString)
521 // Strip tag searches
522 $termString = preg_replace('/\[.*?\]/', '', $termString);
523 // Reduced multiple spacing into single spacing
524 $termString = preg_replace("/\s{2,}/", " ", $termString);
529 * Get the available query operators as a regex escaped list.
532 protected function getRegexEscapedOperators()
534 $escapedOperators = [];
535 foreach ($this->queryOperators as $operator) {
536 $escapedOperators[] = preg_quote($operator);
538 return join('|', $escapedOperators);
542 * Parses advanced search notations and adds them to the db query.
547 protected function addAdvancedSearchQueries($query, $termString)
549 $escapedOperators = $this->getRegexEscapedOperators();
550 // Look for tag searches
551 preg_match_all("/\[(.*?)((${escapedOperators})(.*?))?\]/", $termString, $tags);
552 if (count($tags[0]) > 0) {
553 $this->applyTagSearches($query, $tags);
560 * Apply extracted tag search terms onto a entity query.
565 protected function applyTagSearches($query, $tags) {
566 $query->where(function($query) use ($tags) {
567 foreach ($tags[1] as $index => $tagName) {
568 $query->whereHas('tags', function($query) use ($tags, $index, $tagName) {
569 $tagOperator = $tags[3][$index];
570 $tagValue = $tags[4][$index];
571 if (!empty($tagOperator) && !empty($tagValue) && in_array($tagOperator, $this->queryOperators)) {
572 if (is_numeric($tagValue) && $tagOperator !== 'like') {
573 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
574 // search the value as a string which prevents being able to do number-based operations
575 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
576 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
577 $query->where('name', '=', $tagName)->whereRaw("value ${tagOperator} ${tagValue}");
579 $query->where('name', '=', $tagName)->where('value', $tagOperator, $tagValue);
582 $query->where('name', '=', $tagName);
591 * Create a new entity from request input.
592 * Used for books and chapters.
593 * @param string $type
594 * @param array $input
595 * @param bool|Book $book
598 public function createFromInput($type, $input = [], $book = false)
600 $isChapter = strtolower($type) === 'chapter';
601 $entity = $this->getEntity($type)->newInstance($input);
602 $entity->slug = $this->findSuitableSlug($type, $entity->name, false, $isChapter ? $book->id : false);
603 $entity->created_by = user()->id;
604 $entity->updated_by = user()->id;
605 $isChapter ? $book->chapters()->save($entity) : $entity->save();
606 $this->permissionService->buildJointPermissionsForEntity($entity);
611 * Update entity details from request input.
612 * Use for books and chapters
613 * @param string $type
614 * @param Entity $entityModel
615 * @param array $input
618 public function updateFromInput($type, Entity $entityModel, $input = [])
620 if ($entityModel->name !== $input['name']) {
621 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
623 $entityModel->fill($input);
624 $entityModel->updated_by = user()->id;
625 $entityModel->save();
626 $this->permissionService->buildJointPermissionsForEntity($entityModel);
631 * Change the book that an entity belongs to.
632 * @param string $type
633 * @param integer $newBookId
634 * @param Entity $entity
635 * @param bool $rebuildPermissions
638 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
640 $entity->book_id = $newBookId;
641 // Update related activity
642 foreach ($entity->activity as $activity) {
643 $activity->book_id = $newBookId;
646 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
649 // Update all child pages if a chapter
650 if (strtolower($type) === 'chapter') {
651 foreach ($entity->pages as $page) {
652 $this->changeBook('page', $newBookId, $page, false);
656 // Update permissions if applicable
657 if ($rebuildPermissions) {
658 $entity->load('book');
659 $this->permissionService->buildJointPermissionsForEntity($entity->book);
666 * Alias method to update the book jointPermissions in the PermissionService.
667 * @param Collection $collection collection on entities
669 public function buildJointPermissions(Collection $collection)
671 $this->permissionService->buildJointPermissionsForEntities($collection);
675 * Format a name as a url slug.
679 protected function nameToSlug($name)
681 $slug = str_replace(' ', '-', strtolower($name));
682 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', $slug);
683 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
688 * Publish a draft page to make it a normal page.
689 * Sets the slug and updates the content.
690 * @param Page $draftPage
691 * @param array $input
694 public function publishPageDraft(Page $draftPage, array $input)
696 $draftPage->fill($input);
698 // Save page tags if present
699 if (isset($input['tags'])) {
700 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
703 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
704 $draftPage->html = $this->formatHtml($input['html']);
705 $draftPage->text = strip_tags($draftPage->html);
706 $draftPage->draft = false;
709 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
715 * Saves a page revision into the system.
717 * @param null|string $summary
718 * @return PageRevision
720 public function savePageRevision(Page $page, $summary = null)
722 $revision = $this->pageRevision->newInstance($page->toArray());
723 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
724 $revision->page_id = $page->id;
725 $revision->slug = $page->slug;
726 $revision->book_slug = $page->book->slug;
727 $revision->created_by = user()->id;
728 $revision->created_at = $page->updated_at;
729 $revision->type = 'version';
730 $revision->summary = $summary;
733 // Clear old revisions
734 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
735 $this->pageRevision->where('page_id', '=', $page->id)
736 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
743 * Formats a page's html to be tagged correctly
745 * @param string $htmlText
748 protected function formatHtml($htmlText)
750 if ($htmlText == '') return $htmlText;
751 libxml_use_internal_errors(true);
752 $doc = new DOMDocument();
753 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
755 $container = $doc->documentElement;
756 $body = $container->childNodes->item(0);
757 $childNodes = $body->childNodes;
759 // Ensure no duplicate ids are used
762 foreach ($childNodes as $index => $childNode) {
763 /** @var \DOMElement $childNode */
764 if (get_class($childNode) !== 'DOMElement') continue;
766 // Overwrite id if not a BookStack custom id
767 if ($childNode->hasAttribute('id')) {
768 $id = $childNode->getAttribute('id');
769 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
775 // Create an unique id for the element
776 // Uses the content as a basis to ensure output is the same every time
777 // the same content is passed through.
778 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
779 $newId = urlencode($contentId);
781 while (in_array($newId, $idArray)) {
782 $newId = urlencode($contentId . '-' . $loopIndex);
786 $childNode->setAttribute('id', $newId);
790 // Generate inner html as a string
792 foreach ($childNodes as $childNode) {
793 $html .= $doc->saveHTML($childNode);
800 * Get a new draft page instance.
802 * @param Chapter|bool $chapter
805 public function getDraftPage(Book $book, $chapter = false)
807 $page = $this->page->newInstance();
808 $page->name = trans('entities.pages_initial_name');
809 $page->created_by = user()->id;
810 $page->updated_by = user()->id;
813 if ($chapter) $page->chapter_id = $chapter->id;
815 $book->pages()->save($page);
816 $this->permissionService->buildJointPermissionsForEntity($page);
821 * Search for image usage within page content.
822 * @param $imageString
825 public function searchForImage($imageString)
827 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
828 foreach ($pages as $page) {
829 $page->url = $page->getUrl();
833 return count($pages) > 0 ? $pages : false;
837 * Parse the headers on the page to get a navigation menu
841 public function getPageNav(Page $page)
843 if ($page->html == '') return [];
844 libxml_use_internal_errors(true);
845 $doc = new DOMDocument();
846 $doc->loadHTML(mb_convert_encoding($page->html, 'HTML-ENTITIES', 'UTF-8'));
847 $xPath = new DOMXPath($doc);
848 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
850 if (is_null($headers)) return [];
853 foreach ($headers as $header) {
854 $text = $header->nodeValue;
856 'nodeName' => strtolower($header->nodeName),
857 'level' => intval(str_replace('h', '', $header->nodeName)),
858 'link' => '#' . $header->getAttribute('id'),
859 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
863 // Normalise headers if only smaller headers have been used
864 if (count($tree) > 0) {
865 $minLevel = $tree->pluck('level')->min();
866 $tree = $tree->map(function($header) use ($minLevel) {
867 $header['level'] -= ($minLevel - 2);
871 return $tree->toArray();
875 * Updates a page with any fillable data and saves it into the database.
877 * @param int $book_id
878 * @param array $input
881 public function updatePage(Page $page, $book_id, $input)
883 // Hold the old details to compare later
884 $oldHtml = $page->html;
885 $oldName = $page->name;
887 // Prevent slug being updated if no name change
888 if ($page->name !== $input['name']) {
889 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
892 // Save page tags if present
893 if (isset($input['tags'])) {
894 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
897 // Update with new details
898 $userId = user()->id;
900 $page->html = $this->formatHtml($input['html']);
901 $page->text = strip_tags($page->html);
902 if (setting('app-editor') !== 'markdown') $page->markdown = '';
903 $page->updated_by = $userId;
906 // Remove all update drafts for this user & page.
907 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
909 // Save a revision after updating
910 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
911 $this->savePageRevision($page, $input['summary']);
918 * The base query for getting user update drafts.
923 protected function userUpdatePageDraftsQuery(Page $page, $userId)
925 return $this->pageRevision->where('created_by', '=', $userId)
926 ->where('type', 'update_draft')
927 ->where('page_id', '=', $page->id)
928 ->orderBy('created_at', 'desc');
932 * Checks whether a user has a draft version of a particular page or not.
937 public function hasUserGotPageDraft(Page $page, $userId)
939 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
943 * Get the latest updated draft revision for a particular page and user.
948 public function getUserPageDraft(Page $page, $userId)
950 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
954 * Get the notification message that informs the user that they are editing a draft page.
955 * @param PageRevision $draft
958 public function getUserPageDraftMessage(PageRevision $draft)
960 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
961 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
962 return $message . "\n" . trans('entities.pages_draft_edited_notification');
966 * Check if a page is being actively editing.
967 * Checks for edits since last page updated.
968 * Passing in a minuted range will check for edits
969 * within the last x minutes.
971 * @param null $minRange
974 public function isPageEditingActive(Page $page, $minRange = null)
976 $draftSearch = $this->activePageEditingQuery($page, $minRange);
977 return $draftSearch->count() > 0;
981 * A query to check for active update drafts on a particular page.
983 * @param null $minRange
986 protected function activePageEditingQuery(Page $page, $minRange = null)
988 $query = $this->pageRevision->where('type', '=', 'update_draft')
989 ->where('page_id', '=', $page->id)
990 ->where('updated_at', '>', $page->updated_at)
991 ->where('created_by', '!=', user()->id)
994 if ($minRange !== null) {
995 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1002 * Restores a revision's content back into a page.
1005 * @param int $revisionId
1008 public function restorePageRevision(Page $page, Book $book, $revisionId)
1010 $this->savePageRevision($page);
1011 $revision = $this->getById('page_revision', $revisionId);
1012 $page->fill($revision->toArray());
1013 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1014 $page->text = strip_tags($page->html);
1015 $page->updated_by = user()->id;
1022 * Save a page update draft.
1024 * @param array $data
1025 * @return PageRevision|Page
1027 public function updatePageDraft(Page $page, $data = [])
1029 // If the page itself is a draft simply update that
1032 if (isset($data['html'])) {
1033 $page->text = strip_tags($data['html']);
1039 // Otherwise save the data to a revision
1040 $userId = user()->id;
1041 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1043 if ($drafts->count() > 0) {
1044 $draft = $drafts->first();
1046 $draft = $this->pageRevision->newInstance();
1047 $draft->page_id = $page->id;
1048 $draft->slug = $page->slug;
1049 $draft->book_slug = $page->book->slug;
1050 $draft->created_by = $userId;
1051 $draft->type = 'update_draft';
1054 $draft->fill($data);
1055 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
1062 * Get a notification message concerning the editing activity on a particular page.
1064 * @param null $minRange
1067 public function getPageEditingActiveMessage(Page $page, $minRange = null)
1069 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1071 $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]);
1072 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1073 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1077 * Change the page's parent to the given entity.
1079 * @param Entity $parent
1081 public function changePageParent(Page $page, Entity $parent)
1083 $book = $parent->isA('book') ? $parent : $parent->book;
1084 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1086 if ($page->book->id !== $book->id) {
1087 $page = $this->changeBook('page', $book->id, $page);
1089 $page->load('book');
1090 $this->permissionService->buildJointPermissionsForEntity($book);
1094 * Destroy the provided book and all its child entities.
1097 public function destroyBook(Book $book)
1099 foreach ($book->pages as $page) {
1100 $this->destroyPage($page);
1102 foreach ($book->chapters as $chapter) {
1103 $this->destroyChapter($chapter);
1105 \Activity::removeEntity($book);
1106 $book->views()->delete();
1107 $book->permissions()->delete();
1108 $this->permissionService->deleteJointPermissionsForEntity($book);
1113 * Destroy a chapter and its relations.
1114 * @param Chapter $chapter
1116 public function destroyChapter(Chapter $chapter)
1118 if (count($chapter->pages) > 0) {
1119 foreach ($chapter->pages as $page) {
1120 $page->chapter_id = 0;
1124 \Activity::removeEntity($chapter);
1125 $chapter->views()->delete();
1126 $chapter->permissions()->delete();
1127 $this->permissionService->deleteJointPermissionsForEntity($chapter);
1132 * Destroy a given page along with its dependencies.
1135 public function destroyPage(Page $page)
1137 \Activity::removeEntity($page);
1138 $page->views()->delete();
1139 $page->tags()->delete();
1140 $page->revisions()->delete();
1141 $page->permissions()->delete();
1142 $this->permissionService->deleteJointPermissionsForEntity($page);
1144 // Delete Attached Files
1145 $attachmentService = app(AttachmentService::class);
1146 foreach ($page->attachments as $attachment) {
1147 $attachmentService->deleteFile($attachment);