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,
91 $this->viewService = $viewService;
92 $this->permissionService = $permissionService;
93 $this->tagRepo = $tagRepo;
97 * Get an entity instance via type.
101 protected function getEntity($type)
103 return $this->entities[strtolower($type)];
107 * Base query for searching entities via permission system
108 * @param string $type
109 * @param bool $allowDrafts
110 * @return \Illuminate\Database\Query\Builder
112 protected function entityQuery($type, $allowDrafts = false)
114 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type), 'view');
115 if (strtolower($type) === 'page' && !$allowDrafts) {
116 $q = $q->where('draft', '=', false);
122 * Check if an entity with the given id exists.
127 public function exists($type, $id)
129 return $this->entityQuery($type)->where('id', '=', $id)->exists();
133 * Get an entity by ID
134 * @param string $type
136 * @param bool $allowDrafts
139 public function getById($type, $id, $allowDrafts = false)
141 return $this->entityQuery($type, $allowDrafts)->find($id);
145 * Get an entity by its url slug.
146 * @param string $type
147 * @param string $slug
148 * @param string|bool $bookSlug
150 * @throws NotFoundException
152 public function getBySlug($type, $slug, $bookSlug = false)
154 $q = $this->entityQuery($type)->where('slug', '=', $slug);
156 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
157 $q = $q->where('book_id', '=', function($query) use ($bookSlug) {
159 ->from($this->book->getTable())
160 ->where('slug', '=', $bookSlug)->limit(1);
163 $entity = $q->first();
164 if ($entity === null) throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
170 * Search through page revisions and retrieve the last page in the
171 * current book that has a slug equal to the one given.
172 * @param string $pageSlug
173 * @param string $bookSlug
176 public function getPageByOldSlug($pageSlug, $bookSlug)
178 $revision = $this->pageRevision->where('slug', '=', $pageSlug)
179 ->whereHas('page', function ($query) {
180 $this->permissionService->enforceEntityRestrictions('page', $query);
182 ->where('type', '=', 'version')
183 ->where('book_slug', '=', $bookSlug)
184 ->orderBy('created_at', 'desc')
185 ->with('page')->first();
186 return $revision !== null ? $revision->page : null;
190 * Get all entities of a type limited by count unless count if false.
191 * @param string $type
192 * @param integer|bool $count
195 public function getAll($type, $count = 20)
197 $q = $this->entityQuery($type)->orderBy('name', 'asc');
198 if ($count !== false) $q = $q->take($count);
203 * Get all entities in a paginated format
206 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
208 public function getAllPaginated($type, $count = 10)
210 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
214 * Get the most recently created entities of the given type.
215 * @param string $type
218 * @param bool|callable $additionalQuery
220 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
222 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
223 ->orderBy('created_at', 'desc');
224 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
225 if ($additionalQuery !== false && is_callable($additionalQuery)) {
226 $additionalQuery($query);
228 return $query->skip($page * $count)->take($count)->get();
232 * Get the most recently updated entities of the given type.
233 * @param string $type
236 * @param bool|callable $additionalQuery
238 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
240 $query = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type))
241 ->orderBy('updated_at', 'desc');
242 if (strtolower($type) === 'page') $query = $query->where('draft', '=', false);
243 if ($additionalQuery !== false && is_callable($additionalQuery)) {
244 $additionalQuery($query);
246 return $query->skip($page * $count)->take($count)->get();
250 * Get the most recently viewed entities.
251 * @param string|bool $type
256 public function getRecentlyViewed($type, $count = 10, $page = 0)
258 $filter = is_bool($type) ? false : $this->getEntity($type);
259 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
263 * Get the latest pages added to the system with pagination.
264 * @param string $type
268 public function getRecentlyCreatedPaginated($type, $count = 20)
270 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
274 * Get the latest pages added to the system with pagination.
275 * @param string $type
279 public function getRecentlyUpdatedPaginated($type, $count = 20)
281 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
285 * Get the most popular entities base on all views.
286 * @param string|bool $type
291 public function getPopular($type, $count = 10, $page = 0)
293 $filter = is_bool($type) ? false : $this->getEntity($type);
294 return $this->viewService->getPopular($count, $page, $filter);
298 * Get draft pages owned by the current user.
302 public function getUserDraftPages($count = 20, $page = 0)
304 return $this->page->where('draft', '=', true)
305 ->where('created_by', '=', user()->id)
306 ->orderBy('updated_at', 'desc')
307 ->skip($count * $page)->take($count)->get();
311 * Get all child objects of a book.
312 * Returns a sorted collection of Pages and Chapters.
313 * Loads the book slug onto child elements to prevent access database access for getting the slug.
315 * @param bool $filterDrafts
318 public function getBookChildren(Book $book, $filterDrafts = false)
320 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts)->get();
325 foreach ($q as $index => $rawEntity) {
326 if ($rawEntity->entity_type === 'BookStack\\Page') {
327 $entities[$index] = $this->page->newFromBuilder($rawEntity);
328 } else if ($rawEntity->entity_type === 'BookStack\\Chapter') {
329 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
330 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
331 $parents[$key] = $entities[$index];
332 $parents[$key]->setAttribute('pages', collect());
334 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') $tree[] = $entities[$index];
335 $entities[$index]->book = $book;
338 foreach ($entities as $entity) {
339 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') continue;
340 $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id;
341 $chapter = $parents[$parentKey];
342 $chapter->pages->push($entity);
345 return collect($tree);
349 * Get the child items for a chapter sorted by priority but
350 * with draft items floated to the top.
351 * @param Chapter $chapter
353 public function getChapterChildren(Chapter $chapter)
355 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
356 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
360 * Search entities of a type via a given query.
361 * @param string $type
362 * @param string $term
363 * @param array $whereTerms
365 * @param array $paginationAppends
368 public function getBySearch($type, $term, $whereTerms = [], $count = 20, $paginationAppends = [])
370 $terms = $this->prepareSearchTerms($term);
371 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type)->fullTextSearchQuery($terms, $whereTerms));
372 $q = $this->addAdvancedSearchQueries($q, $term);
373 $entities = $q->paginate($count)->appends($paginationAppends);
374 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
376 // Highlight page content
377 if ($type === 'page') {
378 //lookahead/behind assertions ensures cut between words
379 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
381 foreach ($entities as $page) {
382 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
383 //delimiter between occurrences
385 foreach ($matches as $line) {
386 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
389 if (count($results) > $matchLimit) $results = array_slice($results, 0, $matchLimit);
390 $result = join('... ', $results);
393 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
394 if (strlen($result) < 5) $result = $page->getExcerpt(80);
396 $page->searchSnippet = $result;
401 // Highlight chapter/book content
402 foreach ($entities as $entity) {
404 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $entity->getExcerpt(100));
405 $entity->searchSnippet = $result;
411 * Get the next sequential priority for a new child element in the given book.
415 public function getNewBookPriority(Book $book)
417 $lastElem = $this->getBookChildren($book)->pop();
418 return $lastElem ? $lastElem->priority + 1 : 0;
422 * Get a new priority for a new page to be added to the given chapter.
423 * @param Chapter $chapter
426 public function getNewChapterPriority(Chapter $chapter)
428 $lastPage = $chapter->pages('DESC')->first();
429 return $lastPage !== null ? $lastPage->priority + 1 : 0;
433 * Find a suitable slug for an entity.
434 * @param string $type
435 * @param string $name
436 * @param bool|integer $currentId
437 * @param bool|integer $bookId Only pass if type is not a book
440 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
442 $slug = $this->nameToSlug($name);
443 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
444 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
450 * Check if a slug already exists in the database.
451 * @param string $type
452 * @param string $slug
453 * @param bool|integer $currentId
454 * @param bool|integer $bookId
457 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
459 $query = $this->getEntity($type)->where('slug', '=', $slug);
460 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
461 $query = $query->where('book_id', '=', $bookId);
463 if ($currentId) $query = $query->where('id', '!=', $currentId);
464 return $query->count() > 0;
468 * Updates entity restrictions from a request
470 * @param Entity $entity
472 public function updateEntityPermissionsFromRequest($request, Entity $entity)
474 $entity->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
475 $entity->permissions()->delete();
476 if ($request->has('restrictions')) {
477 foreach ($request->get('restrictions') as $roleId => $restrictions) {
478 foreach ($restrictions as $action => $value) {
479 $entity->permissions()->create([
480 'role_id' => $roleId,
481 'action' => strtolower($action)
487 $this->permissionService->buildJointPermissionsForEntity($entity);
491 * Prepare a string of search terms by turning
492 * it into an array of terms.
493 * Keeps quoted terms together.
497 public function prepareSearchTerms($termString)
499 $termString = $this->cleanSearchTermString($termString);
500 preg_match_all('/(".*?")/', $termString, $matches);
502 if (count($matches[1]) > 0) {
503 foreach ($matches[1] as $match) {
506 $termString = trim(preg_replace('/"(.*?)"/', '', $termString));
508 if (!empty($termString)) $terms = array_merge($terms, explode(' ', $termString));
513 * Removes any special search notation that should not
514 * be used in a full-text search.
518 protected function cleanSearchTermString($termString)
520 // Strip tag searches
521 $termString = preg_replace('/\[.*?\]/', '', $termString);
522 // Reduced multiple spacing into single spacing
523 $termString = preg_replace("/\s{2,}/", " ", $termString);
528 * Get the available query operators as a regex escaped list.
531 protected function getRegexEscapedOperators()
533 $escapedOperators = [];
534 foreach ($this->queryOperators as $operator) {
535 $escapedOperators[] = preg_quote($operator);
537 return join('|', $escapedOperators);
541 * Parses advanced search notations and adds them to the db query.
546 protected function addAdvancedSearchQueries($query, $termString)
548 $escapedOperators = $this->getRegexEscapedOperators();
549 // Look for tag searches
550 preg_match_all("/\[(.*?)((${escapedOperators})(.*?))?\]/", $termString, $tags);
551 if (count($tags[0]) > 0) {
552 $this->applyTagSearches($query, $tags);
559 * Apply extracted tag search terms onto a entity query.
564 protected function applyTagSearches($query, $tags) {
565 $query->where(function($query) use ($tags) {
566 foreach ($tags[1] as $index => $tagName) {
567 $query->whereHas('tags', function($query) use ($tags, $index, $tagName) {
568 $tagOperator = $tags[3][$index];
569 $tagValue = $tags[4][$index];
570 if (!empty($tagOperator) && !empty($tagValue) && in_array($tagOperator, $this->queryOperators)) {
571 if (is_numeric($tagValue) && $tagOperator !== 'like') {
572 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
573 // search the value as a string which prevents being able to do number-based operations
574 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
575 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
576 $query->where('name', '=', $tagName)->whereRaw("value ${tagOperator} ${tagValue}");
578 $query->where('name', '=', $tagName)->where('value', $tagOperator, $tagValue);
581 $query->where('name', '=', $tagName);
590 * Create a new entity from request input.
591 * Used for books and chapters.
592 * @param string $type
593 * @param array $input
594 * @param bool|Book $book
597 public function createFromInput($type, $input = [], $book = false)
599 $isChapter = strtolower($type) === 'chapter';
600 $entity = $this->getEntity($type)->newInstance($input);
601 $entity->slug = $this->findSuitableSlug($type, $entity->name, false, $isChapter ? $book->id : false);
602 $entity->created_by = user()->id;
603 $entity->updated_by = user()->id;
604 $isChapter ? $book->chapters()->save($entity) : $entity->save();
605 $this->permissionService->buildJointPermissionsForEntity($entity);
610 * Update entity details from request input.
611 * Use for books and chapters
612 * @param string $type
613 * @param Entity $entityModel
614 * @param array $input
617 public function updateFromInput($type, Entity $entityModel, $input = [])
619 if ($entityModel->name !== $input['name']) {
620 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
622 $entityModel->fill($input);
623 $entityModel->updated_by = user()->id;
624 $entityModel->save();
625 $this->permissionService->buildJointPermissionsForEntity($entityModel);
630 * Change the book that an entity belongs to.
631 * @param string $type
632 * @param integer $newBookId
633 * @param Entity $entity
634 * @param bool $rebuildPermissions
637 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
639 $entity->book_id = $newBookId;
640 // Update related activity
641 foreach ($entity->activity as $activity) {
642 $activity->book_id = $newBookId;
645 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
648 // Update all child pages if a chapter
649 if (strtolower($type) === 'chapter') {
650 foreach ($entity->pages as $page) {
651 $this->changeBook('page', $newBookId, $page, false);
655 // Update permissions if applicable
656 if ($rebuildPermissions) {
657 $entity->load('book');
658 $this->permissionService->buildJointPermissionsForEntity($entity->book);
665 * Alias method to update the book jointPermissions in the PermissionService.
666 * @param Collection $collection collection on entities
668 public function buildJointPermissions(Collection $collection)
670 $this->permissionService->buildJointPermissionsForEntities($collection);
674 * Format a name as a url slug.
678 protected function nameToSlug($name)
680 $slug = str_replace(' ', '-', strtolower($name));
681 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', $slug);
682 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
687 * Publish a draft page to make it a normal page.
688 * Sets the slug and updates the content.
689 * @param Page $draftPage
690 * @param array $input
693 public function publishPageDraft(Page $draftPage, array $input)
695 $draftPage->fill($input);
697 // Save page tags if present
698 if (isset($input['tags'])) {
699 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
702 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
703 $draftPage->html = $this->formatHtml($input['html']);
704 $draftPage->text = strip_tags($draftPage->html);
705 $draftPage->draft = false;
708 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
714 * Saves a page revision into the system.
716 * @param null|string $summary
717 * @return PageRevision
719 public function savePageRevision(Page $page, $summary = null)
721 $revision = $this->pageRevision->newInstance($page->toArray());
722 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
723 $revision->page_id = $page->id;
724 $revision->slug = $page->slug;
725 $revision->book_slug = $page->book->slug;
726 $revision->created_by = user()->id;
727 $revision->created_at = $page->updated_at;
728 $revision->type = 'version';
729 $revision->summary = $summary;
732 // Clear old revisions
733 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
734 $this->pageRevision->where('page_id', '=', $page->id)
735 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
742 * Formats a page's html to be tagged correctly
744 * @param string $htmlText
747 protected function formatHtml($htmlText)
749 if ($htmlText == '') return $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') continue;
765 // Overwrite id if not a BookStack custom id
766 if ($childNode->hasAttribute('id')) {
767 $id = $childNode->getAttribute('id');
768 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
774 // Create an unique id for the element
775 // Uses the content as a basis to ensure output is the same every time
776 // the same content is passed through.
777 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
778 $newId = urlencode($contentId);
780 while (in_array($newId, $idArray)) {
781 $newId = urlencode($contentId . '-' . $loopIndex);
785 $childNode->setAttribute('id', $newId);
789 // Generate inner html as a string
791 foreach ($childNodes as $childNode) {
792 $html .= $doc->saveHTML($childNode);
800 * Render the page for viewing, Parsing and performing features such as page transclusion.
802 * @return mixed|string
804 public function renderPage(Page $page)
806 $content = $page->html;
808 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
809 if (count($matches[0]) === 0) return $content;
811 foreach ($matches[1] as $index => $includeId) {
812 $splitInclude = explode('#', $includeId, 2);
813 $pageId = intval($splitInclude[0]);
814 if (is_nan($pageId)) continue;
816 $page = $this->getById('page', $pageId);
817 if ($page === null) {
818 $content = str_replace($matches[0][$index], '', $content);
822 if (count($splitInclude) === 1) {
823 $content = str_replace($matches[0][$index], $page->html, $content);
827 $doc = new DOMDocument();
828 $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
829 $matchingElem = $doc->getElementById($splitInclude[1]);
830 if ($matchingElem === null) {
831 $content = str_replace($matches[0][$index], '', $content);
835 foreach ($matchingElem->childNodes as $childNode) {
836 $innerContent .= $doc->saveHTML($childNode);
838 $content = str_replace($matches[0][$index], trim($innerContent), $content);
845 * Get a new draft page instance.
847 * @param Chapter|bool $chapter
850 public function getDraftPage(Book $book, $chapter = false)
852 $page = $this->page->newInstance();
853 $page->name = trans('entities.pages_initial_name');
854 $page->created_by = user()->id;
855 $page->updated_by = user()->id;
858 if ($chapter) $page->chapter_id = $chapter->id;
860 $book->pages()->save($page);
861 $this->permissionService->buildJointPermissionsForEntity($page);
866 * Search for image usage within page content.
867 * @param $imageString
870 public function searchForImage($imageString)
872 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
873 foreach ($pages as $page) {
874 $page->url = $page->getUrl();
878 return count($pages) > 0 ? $pages : false;
882 * Parse the headers on the page to get a navigation menu
883 * @param String $pageContent
886 public function getPageNav($pageContent)
888 if ($pageContent == '') return [];
889 libxml_use_internal_errors(true);
890 $doc = new DOMDocument();
891 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
892 $xPath = new DOMXPath($doc);
893 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
895 if (is_null($headers)) return [];
898 foreach ($headers as $header) {
899 $text = $header->nodeValue;
901 'nodeName' => strtolower($header->nodeName),
902 'level' => intval(str_replace('h', '', $header->nodeName)),
903 'link' => '#' . $header->getAttribute('id'),
904 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
908 // Normalise headers if only smaller headers have been used
909 if (count($tree) > 0) {
910 $minLevel = $tree->pluck('level')->min();
911 $tree = $tree->map(function($header) use ($minLevel) {
912 $header['level'] -= ($minLevel - 2);
916 return $tree->toArray();
920 * Updates a page with any fillable data and saves it into the database.
922 * @param int $book_id
923 * @param array $input
926 public function updatePage(Page $page, $book_id, $input)
928 // Hold the old details to compare later
929 $oldHtml = $page->html;
930 $oldName = $page->name;
932 // Prevent slug being updated if no name change
933 if ($page->name !== $input['name']) {
934 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
937 // Save page tags if present
938 if (isset($input['tags'])) {
939 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
942 // Update with new details
943 $userId = user()->id;
945 $page->html = $this->formatHtml($input['html']);
946 $page->text = strip_tags($page->html);
947 if (setting('app-editor') !== 'markdown') $page->markdown = '';
948 $page->updated_by = $userId;
951 // Remove all update drafts for this user & page.
952 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
954 // Save a revision after updating
955 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
956 $this->savePageRevision($page, $input['summary']);
963 * The base query for getting user update drafts.
968 protected function userUpdatePageDraftsQuery(Page $page, $userId)
970 return $this->pageRevision->where('created_by', '=', $userId)
971 ->where('type', 'update_draft')
972 ->where('page_id', '=', $page->id)
973 ->orderBy('created_at', 'desc');
977 * Checks whether a user has a draft version of a particular page or not.
982 public function hasUserGotPageDraft(Page $page, $userId)
984 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
988 * Get the latest updated draft revision for a particular page and user.
993 public function getUserPageDraft(Page $page, $userId)
995 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
999 * Get the notification message that informs the user that they are editing a draft page.
1000 * @param PageRevision $draft
1003 public function getUserPageDraftMessage(PageRevision $draft)
1005 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
1006 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
1007 return $message . "\n" . trans('entities.pages_draft_edited_notification');
1011 * Check if a page is being actively editing.
1012 * Checks for edits since last page updated.
1013 * Passing in a minuted range will check for edits
1014 * within the last x minutes.
1016 * @param null $minRange
1019 public function isPageEditingActive(Page $page, $minRange = null)
1021 $draftSearch = $this->activePageEditingQuery($page, $minRange);
1022 return $draftSearch->count() > 0;
1026 * A query to check for active update drafts on a particular page.
1028 * @param null $minRange
1031 protected function activePageEditingQuery(Page $page, $minRange = null)
1033 $query = $this->pageRevision->where('type', '=', 'update_draft')
1034 ->where('page_id', '=', $page->id)
1035 ->where('updated_at', '>', $page->updated_at)
1036 ->where('created_by', '!=', user()->id)
1037 ->with('createdBy');
1039 if ($minRange !== null) {
1040 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1047 * Restores a revision's content back into a page.
1050 * @param int $revisionId
1053 public function restorePageRevision(Page $page, Book $book, $revisionId)
1055 $this->savePageRevision($page);
1056 $revision = $this->getById('page_revision', $revisionId);
1057 $page->fill($revision->toArray());
1058 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1059 $page->text = strip_tags($page->html);
1060 $page->updated_by = user()->id;
1067 * Save a page update draft.
1069 * @param array $data
1070 * @return PageRevision|Page
1072 public function updatePageDraft(Page $page, $data = [])
1074 // If the page itself is a draft simply update that
1077 if (isset($data['html'])) {
1078 $page->text = strip_tags($data['html']);
1084 // Otherwise save the data to a revision
1085 $userId = user()->id;
1086 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1088 if ($drafts->count() > 0) {
1089 $draft = $drafts->first();
1091 $draft = $this->pageRevision->newInstance();
1092 $draft->page_id = $page->id;
1093 $draft->slug = $page->slug;
1094 $draft->book_slug = $page->book->slug;
1095 $draft->created_by = $userId;
1096 $draft->type = 'update_draft';
1099 $draft->fill($data);
1100 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
1107 * Get a notification message concerning the editing activity on a particular page.
1109 * @param null $minRange
1112 public function getPageEditingActiveMessage(Page $page, $minRange = null)
1114 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1116 $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]);
1117 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1118 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1122 * Change the page's parent to the given entity.
1124 * @param Entity $parent
1126 public function changePageParent(Page $page, Entity $parent)
1128 $book = $parent->isA('book') ? $parent : $parent->book;
1129 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1131 if ($page->book->id !== $book->id) {
1132 $page = $this->changeBook('page', $book->id, $page);
1134 $page->load('book');
1135 $this->permissionService->buildJointPermissionsForEntity($book);
1139 * Destroy the provided book and all its child entities.
1142 public function destroyBook(Book $book)
1144 foreach ($book->pages as $page) {
1145 $this->destroyPage($page);
1147 foreach ($book->chapters as $chapter) {
1148 $this->destroyChapter($chapter);
1150 \Activity::removeEntity($book);
1151 $book->views()->delete();
1152 $book->permissions()->delete();
1153 $this->permissionService->deleteJointPermissionsForEntity($book);
1158 * Destroy a chapter and its relations.
1159 * @param Chapter $chapter
1161 public function destroyChapter(Chapter $chapter)
1163 if (count($chapter->pages) > 0) {
1164 foreach ($chapter->pages as $page) {
1165 $page->chapter_id = 0;
1169 \Activity::removeEntity($chapter);
1170 $chapter->views()->delete();
1171 $chapter->permissions()->delete();
1172 $this->permissionService->deleteJointPermissionsForEntity($chapter);
1177 * Destroy a given page along with its dependencies.
1180 public function destroyPage(Page $page)
1182 \Activity::removeEntity($page);
1183 $page->views()->delete();
1184 $page->tags()->delete();
1185 $page->revisions()->delete();
1186 $page->permissions()->delete();
1187 $this->permissionService->deleteJointPermissionsForEntity($page);
1189 // Delete Attached Files
1190 $attachmentService = app(AttachmentService::class);
1191 foreach ($page->attachments as $attachment) {
1192 $attachmentService->deleteFile($attachment);