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
316 * @param bool $renderPages
319 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
321 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
326 foreach ($q as $index => $rawEntity) {
327 if ($rawEntity->entity_type === 'BookStack\\Page') {
328 $entities[$index] = $this->page->newFromBuilder($rawEntity);
330 $entities[$index]->html = $rawEntity->description;
331 $entities[$index]->html = $this->renderPage($entities[$index]);
333 } else if ($rawEntity->entity_type === 'BookStack\\Chapter') {
334 $entities[$index] = $this->chapter->newFromBuilder($rawEntity);
335 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
336 $parents[$key] = $entities[$index];
337 $parents[$key]->setAttribute('pages', collect());
339 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') $tree[] = $entities[$index];
340 $entities[$index]->book = $book;
343 foreach ($entities as $entity) {
344 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') continue;
345 $parentKey = 'BookStack\\Chapter:' . $entity->chapter_id;
346 $chapter = $parents[$parentKey];
347 $chapter->pages->push($entity);
350 return collect($tree);
354 * Get the child items for a chapter sorted by priority but
355 * with draft items floated to the top.
356 * @param Chapter $chapter
358 public function getChapterChildren(Chapter $chapter)
360 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
361 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
365 * Search entities of a type via a given query.
366 * @param string $type
367 * @param string $term
368 * @param array $whereTerms
370 * @param array $paginationAppends
373 public function getBySearch($type, $term, $whereTerms = [], $count = 20, $paginationAppends = [])
375 $terms = $this->prepareSearchTerms($term);
376 $q = $this->permissionService->enforceEntityRestrictions($type, $this->getEntity($type)->fullTextSearchQuery($terms, $whereTerms));
377 $q = $this->addAdvancedSearchQueries($q, $term);
378 $entities = $q->paginate($count)->appends($paginationAppends);
379 $words = join('|', explode(' ', preg_quote(trim($term), '/')));
381 // Highlight page content
382 if ($type === 'page') {
383 //lookahead/behind assertions ensures cut between words
384 $s = '\s\x00-/:-@\[-`{-~'; //character set for start/end of words
386 foreach ($entities as $page) {
387 preg_match_all('#(?<=[' . $s . ']).{1,30}((' . $words . ').{1,30})+(?=[' . $s . '])#uis', $page->text, $matches, PREG_SET_ORDER);
388 //delimiter between occurrences
390 foreach ($matches as $line) {
391 $results[] = htmlspecialchars($line[0], 0, 'UTF-8');
394 if (count($results) > $matchLimit) $results = array_slice($results, 0, $matchLimit);
395 $result = join('... ', $results);
398 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $result);
399 if (strlen($result) < 5) $result = $page->getExcerpt(80);
401 $page->searchSnippet = $result;
406 // Highlight chapter/book content
407 foreach ($entities as $entity) {
409 $result = preg_replace('#' . $words . '#iu', "<span class=\"highlight\">\$0</span>", $entity->getExcerpt(100));
410 $entity->searchSnippet = $result;
416 * Get the next sequential priority for a new child element in the given book.
420 public function getNewBookPriority(Book $book)
422 $lastElem = $this->getBookChildren($book)->pop();
423 return $lastElem ? $lastElem->priority + 1 : 0;
427 * Get a new priority for a new page to be added to the given chapter.
428 * @param Chapter $chapter
431 public function getNewChapterPriority(Chapter $chapter)
433 $lastPage = $chapter->pages('DESC')->first();
434 return $lastPage !== null ? $lastPage->priority + 1 : 0;
438 * Find a suitable slug for an entity.
439 * @param string $type
440 * @param string $name
441 * @param bool|integer $currentId
442 * @param bool|integer $bookId Only pass if type is not a book
445 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
447 $slug = $this->nameToSlug($name);
448 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
449 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
455 * Check if a slug already exists in the database.
456 * @param string $type
457 * @param string $slug
458 * @param bool|integer $currentId
459 * @param bool|integer $bookId
462 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
464 $query = $this->getEntity($type)->where('slug', '=', $slug);
465 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
466 $query = $query->where('book_id', '=', $bookId);
468 if ($currentId) $query = $query->where('id', '!=', $currentId);
469 return $query->count() > 0;
473 * Updates entity restrictions from a request
475 * @param Entity $entity
477 public function updateEntityPermissionsFromRequest($request, Entity $entity)
479 $entity->restricted = $request->has('restricted') && $request->get('restricted') === 'true';
480 $entity->permissions()->delete();
481 if ($request->has('restrictions')) {
482 foreach ($request->get('restrictions') as $roleId => $restrictions) {
483 foreach ($restrictions as $action => $value) {
484 $entity->permissions()->create([
485 'role_id' => $roleId,
486 'action' => strtolower($action)
492 $this->permissionService->buildJointPermissionsForEntity($entity);
496 * Prepare a string of search terms by turning
497 * it into an array of terms.
498 * Keeps quoted terms together.
502 public function prepareSearchTerms($termString)
504 $termString = $this->cleanSearchTermString($termString);
505 preg_match_all('/(".*?")/', $termString, $matches);
507 if (count($matches[1]) > 0) {
508 foreach ($matches[1] as $match) {
511 $termString = trim(preg_replace('/"(.*?)"/', '', $termString));
513 if (!empty($termString)) $terms = array_merge($terms, explode(' ', $termString));
518 * Removes any special search notation that should not
519 * be used in a full-text search.
523 protected function cleanSearchTermString($termString)
525 // Strip tag searches
526 $termString = preg_replace('/\[.*?\]/', '', $termString);
527 // Reduced multiple spacing into single spacing
528 $termString = preg_replace("/\s{2,}/", " ", $termString);
533 * Get the available query operators as a regex escaped list.
536 protected function getRegexEscapedOperators()
538 $escapedOperators = [];
539 foreach ($this->queryOperators as $operator) {
540 $escapedOperators[] = preg_quote($operator);
542 return join('|', $escapedOperators);
546 * Parses advanced search notations and adds them to the db query.
551 protected function addAdvancedSearchQueries($query, $termString)
553 $escapedOperators = $this->getRegexEscapedOperators();
554 // Look for tag searches
555 preg_match_all("/\[(.*?)((${escapedOperators})(.*?))?\]/", $termString, $tags);
556 if (count($tags[0]) > 0) {
557 $this->applyTagSearches($query, $tags);
564 * Apply extracted tag search terms onto a entity query.
569 protected function applyTagSearches($query, $tags) {
570 $query->where(function($query) use ($tags) {
571 foreach ($tags[1] as $index => $tagName) {
572 $query->whereHas('tags', function($query) use ($tags, $index, $tagName) {
573 $tagOperator = $tags[3][$index];
574 $tagValue = $tags[4][$index];
575 if (!empty($tagOperator) && !empty($tagValue) && in_array($tagOperator, $this->queryOperators)) {
576 if (is_numeric($tagValue) && $tagOperator !== 'like') {
577 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
578 // search the value as a string which prevents being able to do number-based operations
579 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
580 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
581 $query->where('name', '=', $tagName)->whereRaw("value ${tagOperator} ${tagValue}");
583 $query->where('name', '=', $tagName)->where('value', $tagOperator, $tagValue);
586 $query->where('name', '=', $tagName);
595 * Create a new entity from request input.
596 * Used for books and chapters.
597 * @param string $type
598 * @param array $input
599 * @param bool|Book $book
602 public function createFromInput($type, $input = [], $book = false)
604 $isChapter = strtolower($type) === 'chapter';
605 $entity = $this->getEntity($type)->newInstance($input);
606 $entity->slug = $this->findSuitableSlug($type, $entity->name, false, $isChapter ? $book->id : false);
607 $entity->created_by = user()->id;
608 $entity->updated_by = user()->id;
609 $isChapter ? $book->chapters()->save($entity) : $entity->save();
610 $this->permissionService->buildJointPermissionsForEntity($entity);
615 * Update entity details from request input.
616 * Use for books and chapters
617 * @param string $type
618 * @param Entity $entityModel
619 * @param array $input
622 public function updateFromInput($type, Entity $entityModel, $input = [])
624 if ($entityModel->name !== $input['name']) {
625 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
627 $entityModel->fill($input);
628 $entityModel->updated_by = user()->id;
629 $entityModel->save();
630 $this->permissionService->buildJointPermissionsForEntity($entityModel);
635 * Change the book that an entity belongs to.
636 * @param string $type
637 * @param integer $newBookId
638 * @param Entity $entity
639 * @param bool $rebuildPermissions
642 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
644 $entity->book_id = $newBookId;
645 // Update related activity
646 foreach ($entity->activity as $activity) {
647 $activity->book_id = $newBookId;
650 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
653 // Update all child pages if a chapter
654 if (strtolower($type) === 'chapter') {
655 foreach ($entity->pages as $page) {
656 $this->changeBook('page', $newBookId, $page, false);
660 // Update permissions if applicable
661 if ($rebuildPermissions) {
662 $entity->load('book');
663 $this->permissionService->buildJointPermissionsForEntity($entity->book);
670 * Alias method to update the book jointPermissions in the PermissionService.
671 * @param Collection $collection collection on entities
673 public function buildJointPermissions(Collection $collection)
675 $this->permissionService->buildJointPermissionsForEntities($collection);
679 * Format a name as a url slug.
683 protected function nameToSlug($name)
685 $slug = str_replace(' ', '-', strtolower($name));
686 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', $slug);
687 if ($slug === "") $slug = substr(md5(rand(1, 500)), 0, 5);
692 * Publish a draft page to make it a normal page.
693 * Sets the slug and updates the content.
694 * @param Page $draftPage
695 * @param array $input
698 public function publishPageDraft(Page $draftPage, array $input)
700 $draftPage->fill($input);
702 // Save page tags if present
703 if (isset($input['tags'])) {
704 $this->tagRepo->saveTagsToEntity($draftPage, $input['tags']);
707 $draftPage->slug = $this->findSuitableSlug('page', $draftPage->name, false, $draftPage->book->id);
708 $draftPage->html = $this->formatHtml($input['html']);
709 $draftPage->text = strip_tags($draftPage->html);
710 $draftPage->draft = false;
713 $this->savePageRevision($draftPage, trans('entities.pages_initial_revision'));
719 * Saves a page revision into the system.
721 * @param null|string $summary
722 * @return PageRevision
724 public function savePageRevision(Page $page, $summary = null)
726 $revision = $this->pageRevision->newInstance($page->toArray());
727 if (setting('app-editor') !== 'markdown') $revision->markdown = '';
728 $revision->page_id = $page->id;
729 $revision->slug = $page->slug;
730 $revision->book_slug = $page->book->slug;
731 $revision->created_by = user()->id;
732 $revision->created_at = $page->updated_at;
733 $revision->type = 'version';
734 $revision->summary = $summary;
737 // Clear old revisions
738 if ($this->pageRevision->where('page_id', '=', $page->id)->count() > 50) {
739 $this->pageRevision->where('page_id', '=', $page->id)
740 ->orderBy('created_at', 'desc')->skip(50)->take(5)->delete();
747 * Formats a page's html to be tagged correctly
749 * @param string $htmlText
752 protected function formatHtml($htmlText)
754 if ($htmlText == '') return $htmlText;
755 libxml_use_internal_errors(true);
756 $doc = new DOMDocument();
757 $doc->loadHTML(mb_convert_encoding($htmlText, 'HTML-ENTITIES', 'UTF-8'));
759 $container = $doc->documentElement;
760 $body = $container->childNodes->item(0);
761 $childNodes = $body->childNodes;
763 // Ensure no duplicate ids are used
766 foreach ($childNodes as $index => $childNode) {
767 /** @var \DOMElement $childNode */
768 if (get_class($childNode) !== 'DOMElement') continue;
770 // Overwrite id if not a BookStack custom id
771 if ($childNode->hasAttribute('id')) {
772 $id = $childNode->getAttribute('id');
773 if (strpos($id, 'bkmrk') === 0 && array_search($id, $idArray) === false) {
779 // Create an unique id for the element
780 // Uses the content as a basis to ensure output is the same every time
781 // the same content is passed through.
782 $contentId = 'bkmrk-' . substr(strtolower(preg_replace('/\s+/', '-', trim($childNode->nodeValue))), 0, 20);
783 $newId = urlencode($contentId);
785 while (in_array($newId, $idArray)) {
786 $newId = urlencode($contentId . '-' . $loopIndex);
790 $childNode->setAttribute('id', $newId);
794 // Generate inner html as a string
796 foreach ($childNodes as $childNode) {
797 $html .= $doc->saveHTML($childNode);
805 * Render the page for viewing, Parsing and performing features such as page transclusion.
807 * @return mixed|string
809 public function renderPage(Page $page)
811 $content = $page->html;
813 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
814 if (count($matches[0]) === 0) return $content;
816 foreach ($matches[1] as $index => $includeId) {
817 $splitInclude = explode('#', $includeId, 2);
818 $pageId = intval($splitInclude[0]);
819 if (is_nan($pageId)) continue;
821 $page = $this->getById('page', $pageId);
822 if ($page === null) {
823 $content = str_replace($matches[0][$index], '', $content);
827 if (count($splitInclude) === 1) {
828 $content = str_replace($matches[0][$index], $page->html, $content);
832 $doc = new DOMDocument();
833 $doc->loadHTML(mb_convert_encoding('<body>'.$page->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
834 $matchingElem = $doc->getElementById($splitInclude[1]);
835 if ($matchingElem === null) {
836 $content = str_replace($matches[0][$index], '', $content);
840 foreach ($matchingElem->childNodes as $childNode) {
841 $innerContent .= $doc->saveHTML($childNode);
843 $content = str_replace($matches[0][$index], trim($innerContent), $content);
850 * Get a new draft page instance.
852 * @param Chapter|bool $chapter
855 public function getDraftPage(Book $book, $chapter = false)
857 $page = $this->page->newInstance();
858 $page->name = trans('entities.pages_initial_name');
859 $page->created_by = user()->id;
860 $page->updated_by = user()->id;
863 if ($chapter) $page->chapter_id = $chapter->id;
865 $book->pages()->save($page);
866 $this->permissionService->buildJointPermissionsForEntity($page);
871 * Search for image usage within page content.
872 * @param $imageString
875 public function searchForImage($imageString)
877 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
878 foreach ($pages as $page) {
879 $page->url = $page->getUrl();
883 return count($pages) > 0 ? $pages : false;
887 * Parse the headers on the page to get a navigation menu
888 * @param String $pageContent
891 public function getPageNav($pageContent)
893 if ($pageContent == '') return [];
894 libxml_use_internal_errors(true);
895 $doc = new DOMDocument();
896 $doc->loadHTML(mb_convert_encoding($pageContent, 'HTML-ENTITIES', 'UTF-8'));
897 $xPath = new DOMXPath($doc);
898 $headers = $xPath->query("//h1|//h2|//h3|//h4|//h5|//h6");
900 if (is_null($headers)) return [];
903 foreach ($headers as $header) {
904 $text = $header->nodeValue;
906 'nodeName' => strtolower($header->nodeName),
907 'level' => intval(str_replace('h', '', $header->nodeName)),
908 'link' => '#' . $header->getAttribute('id'),
909 'text' => strlen($text) > 30 ? substr($text, 0, 27) . '...' : $text
913 // Normalise headers if only smaller headers have been used
914 if (count($tree) > 0) {
915 $minLevel = $tree->pluck('level')->min();
916 $tree = $tree->map(function($header) use ($minLevel) {
917 $header['level'] -= ($minLevel - 2);
921 return $tree->toArray();
925 * Updates a page with any fillable data and saves it into the database.
927 * @param int $book_id
928 * @param array $input
931 public function updatePage(Page $page, $book_id, $input)
933 // Hold the old details to compare later
934 $oldHtml = $page->html;
935 $oldName = $page->name;
937 // Prevent slug being updated if no name change
938 if ($page->name !== $input['name']) {
939 $page->slug = $this->findSuitableSlug('page', $input['name'], $page->id, $book_id);
942 // Save page tags if present
943 if (isset($input['tags'])) {
944 $this->tagRepo->saveTagsToEntity($page, $input['tags']);
947 // Update with new details
948 $userId = user()->id;
950 $page->html = $this->formatHtml($input['html']);
951 $page->text = strip_tags($page->html);
952 if (setting('app-editor') !== 'markdown') $page->markdown = '';
953 $page->updated_by = $userId;
956 // Remove all update drafts for this user & page.
957 $this->userUpdatePageDraftsQuery($page, $userId)->delete();
959 // Save a revision after updating
960 if ($oldHtml !== $input['html'] || $oldName !== $input['name'] || $input['summary'] !== null) {
961 $this->savePageRevision($page, $input['summary']);
968 * The base query for getting user update drafts.
973 protected function userUpdatePageDraftsQuery(Page $page, $userId)
975 return $this->pageRevision->where('created_by', '=', $userId)
976 ->where('type', 'update_draft')
977 ->where('page_id', '=', $page->id)
978 ->orderBy('created_at', 'desc');
982 * Checks whether a user has a draft version of a particular page or not.
987 public function hasUserGotPageDraft(Page $page, $userId)
989 return $this->userUpdatePageDraftsQuery($page, $userId)->count() > 0;
993 * Get the latest updated draft revision for a particular page and user.
998 public function getUserPageDraft(Page $page, $userId)
1000 return $this->userUpdatePageDraftsQuery($page, $userId)->first();
1004 * Get the notification message that informs the user that they are editing a draft page.
1005 * @param PageRevision $draft
1008 public function getUserPageDraftMessage(PageRevision $draft)
1010 $message = trans('entities.pages_editing_draft_notification', ['timeDiff' => $draft->updated_at->diffForHumans()]);
1011 if ($draft->page->updated_at->timestamp <= $draft->updated_at->timestamp) return $message;
1012 return $message . "\n" . trans('entities.pages_draft_edited_notification');
1016 * Check if a page is being actively editing.
1017 * Checks for edits since last page updated.
1018 * Passing in a minuted range will check for edits
1019 * within the last x minutes.
1021 * @param null $minRange
1024 public function isPageEditingActive(Page $page, $minRange = null)
1026 $draftSearch = $this->activePageEditingQuery($page, $minRange);
1027 return $draftSearch->count() > 0;
1031 * A query to check for active update drafts on a particular page.
1033 * @param null $minRange
1036 protected function activePageEditingQuery(Page $page, $minRange = null)
1038 $query = $this->pageRevision->where('type', '=', 'update_draft')
1039 ->where('page_id', '=', $page->id)
1040 ->where('updated_at', '>', $page->updated_at)
1041 ->where('created_by', '!=', user()->id)
1042 ->with('createdBy');
1044 if ($minRange !== null) {
1045 $query = $query->where('updated_at', '>=', Carbon::now()->subMinutes($minRange));
1052 * Restores a revision's content back into a page.
1055 * @param int $revisionId
1058 public function restorePageRevision(Page $page, Book $book, $revisionId)
1060 $this->savePageRevision($page);
1061 $revision = $page->revisions()->where('id', '=', $revisionId)->first();
1062 $page->fill($revision->toArray());
1063 $page->slug = $this->findSuitableSlug('page', $page->name, $page->id, $book->id);
1064 $page->text = strip_tags($page->html);
1065 $page->updated_by = user()->id;
1072 * Save a page update draft.
1074 * @param array $data
1075 * @return PageRevision|Page
1077 public function updatePageDraft(Page $page, $data = [])
1079 // If the page itself is a draft simply update that
1082 if (isset($data['html'])) {
1083 $page->text = strip_tags($data['html']);
1089 // Otherwise save the data to a revision
1090 $userId = user()->id;
1091 $drafts = $this->userUpdatePageDraftsQuery($page, $userId)->get();
1093 if ($drafts->count() > 0) {
1094 $draft = $drafts->first();
1096 $draft = $this->pageRevision->newInstance();
1097 $draft->page_id = $page->id;
1098 $draft->slug = $page->slug;
1099 $draft->book_slug = $page->book->slug;
1100 $draft->created_by = $userId;
1101 $draft->type = 'update_draft';
1104 $draft->fill($data);
1105 if (setting('app-editor') !== 'markdown') $draft->markdown = '';
1112 * Get a notification message concerning the editing activity on a particular page.
1114 * @param null $minRange
1117 public function getPageEditingActiveMessage(Page $page, $minRange = null)
1119 $pageDraftEdits = $this->activePageEditingQuery($page, $minRange)->get();
1121 $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]);
1122 $timeMessage = $minRange === null ? trans('entities.pages_draft_edit_active.time_a') : trans('entities.pages_draft_edit_active.time_b', ['minCount'=>$minRange]);
1123 return trans('entities.pages_draft_edit_active.message', ['start' => $userMessage, 'time' => $timeMessage]);
1127 * Change the page's parent to the given entity.
1129 * @param Entity $parent
1131 public function changePageParent(Page $page, Entity $parent)
1133 $book = $parent->isA('book') ? $parent : $parent->book;
1134 $page->chapter_id = $parent->isA('chapter') ? $parent->id : 0;
1136 if ($page->book->id !== $book->id) {
1137 $page = $this->changeBook('page', $book->id, $page);
1139 $page->load('book');
1140 $this->permissionService->buildJointPermissionsForEntity($book);
1144 * Destroy the provided book and all its child entities.
1147 public function destroyBook(Book $book)
1149 foreach ($book->pages as $page) {
1150 $this->destroyPage($page);
1152 foreach ($book->chapters as $chapter) {
1153 $this->destroyChapter($chapter);
1155 \Activity::removeEntity($book);
1156 $book->views()->delete();
1157 $book->permissions()->delete();
1158 $this->permissionService->deleteJointPermissionsForEntity($book);
1163 * Destroy a chapter and its relations.
1164 * @param Chapter $chapter
1166 public function destroyChapter(Chapter $chapter)
1168 if (count($chapter->pages) > 0) {
1169 foreach ($chapter->pages as $page) {
1170 $page->chapter_id = 0;
1174 \Activity::removeEntity($chapter);
1175 $chapter->views()->delete();
1176 $chapter->permissions()->delete();
1177 $this->permissionService->deleteJointPermissionsForEntity($chapter);
1182 * Destroy a given page along with its dependencies.
1185 public function destroyPage(Page $page)
1187 \Activity::removeEntity($page);
1188 $page->views()->delete();
1189 $page->tags()->delete();
1190 $page->revisions()->delete();
1191 $page->permissions()->delete();
1192 $this->permissionService->deleteJointPermissionsForEntity($page);
1194 // Delete Attached Files
1195 $attachmentService = app(AttachmentService::class);
1196 foreach ($page->attachments as $attachment) {
1197 $attachmentService->deleteFile($attachment);