1 <?php namespace BookStack\Entities\Repos;
4 use BookStack\Actions\TagRepo;
5 use BookStack\Actions\ViewService;
6 use BookStack\Auth\Permissions\PermissionService;
7 use BookStack\Auth\User;
8 use BookStack\Entities\Book;
9 use BookStack\Entities\BookChild;
10 use BookStack\Entities\Bookshelf;
11 use BookStack\Entities\Chapter;
12 use BookStack\Entities\Entity;
13 use BookStack\Entities\EntityProvider;
14 use BookStack\Entities\Page;
15 use BookStack\Entities\SearchService;
16 use BookStack\Exceptions\NotFoundException;
17 use BookStack\Exceptions\NotifyException;
18 use BookStack\Uploads\AttachmentService;
21 use Illuminate\Contracts\Pagination\LengthAwarePaginator;
22 use Illuminate\Database\Eloquent\Builder;
23 use Illuminate\Database\Query\Builder as QueryBuilder;
24 use Illuminate\Http\Request;
25 use Illuminate\Support\Collection;
34 protected $entityProvider;
37 * @var PermissionService
39 protected $permissionService;
44 protected $viewService;
54 protected $searchService;
57 * EntityRepo constructor.
58 * @param EntityProvider $entityProvider
59 * @param ViewService $viewService
60 * @param PermissionService $permissionService
61 * @param TagRepo $tagRepo
62 * @param SearchService $searchService
64 public function __construct(
65 EntityProvider $entityProvider,
66 ViewService $viewService,
67 PermissionService $permissionService,
69 SearchService $searchService
71 $this->entityProvider = $entityProvider;
72 $this->viewService = $viewService;
73 $this->permissionService = $permissionService;
74 $this->tagRepo = $tagRepo;
75 $this->searchService = $searchService;
79 * Base query for searching entities via permission system
81 * @param bool $allowDrafts
82 * @param string $permission
83 * @return QueryBuilder
85 protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
87 $q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
88 if (strtolower($type) === 'page' && !$allowDrafts) {
89 $q = $q->where('draft', '=', false);
95 * Check if an entity with the given id exists.
100 public function exists($type, $id)
102 return $this->entityQuery($type)->where('id', '=', $id)->exists();
106 * Get an entity by ID
107 * @param string $type
109 * @param bool $allowDrafts
110 * @param bool $ignorePermissions
113 public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
115 $query = $this->entityQuery($type, $allowDrafts);
117 if ($ignorePermissions) {
118 $query = $this->entityProvider->get($type)->newQuery();
121 return $query->find($id);
125 * @param string $type
127 * @param bool $allowDrafts
128 * @param bool $ignorePermissions
129 * @return Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
131 public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
133 $query = $this->entityQuery($type, $allowDrafts);
135 if ($ignorePermissions) {
136 $query = $this->entityProvider->get($type)->newQuery();
139 return $query->whereIn('id', $ids)->get();
143 * Get an entity by its url slug.
144 * @param string $type
145 * @param string $slug
146 * @param string|null $bookSlug
148 * @throws NotFoundException
150 public function getEntityBySlug(string $type, string $slug, string $bookSlug = null): Entity
152 $type = strtolower($type);
153 $query = $this->entityQuery($type)->where('slug', '=', $slug);
155 if ($type === 'chapter' || $type === 'page') {
156 $query = $query->where('book_id', '=', function (QueryBuilder $query) use ($bookSlug) {
158 ->from($this->entityProvider->book->getTable())
159 ->where('slug', '=', $bookSlug)->limit(1);
163 $entity = $query->first();
165 if ($entity === null) {
166 throw new NotFoundException(trans('errors.' . $type . '_not_found'));
174 * Get all entities of a type with the given permission, limited by count unless count is false.
175 * @param string $type
176 * @param integer|bool $count
177 * @param string $permission
180 public function getAll($type, $count = 20, $permission = 'view')
182 $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
183 if ($count !== false) {
184 $q = $q->take($count);
190 * Get all entities in a paginated format
193 * @param string $sort
194 * @param string $order
195 * @param null|callable $queryAddition
196 * @return LengthAwarePaginator
198 public function getAllPaginated($type, int $count = 10, string $sort = 'name', string $order = 'asc', $queryAddition = null)
200 $query = $this->entityQuery($type);
201 $query = $this->addSortToQuery($query, $sort, $order);
202 if ($queryAddition) {
203 $queryAddition($query);
205 return $query->paginate($count);
209 * Add sorting operations to an entity query.
210 * @param Builder $query
211 * @param string $sort
212 * @param string $order
215 protected function addSortToQuery(Builder $query, string $sort = 'name', string $order = 'asc')
217 $order = ($order === 'asc') ? 'asc' : 'desc';
218 $propertySorts = ['name', 'created_at', 'updated_at'];
220 if (in_array($sort, $propertySorts)) {
221 return $query->orderBy($sort, $order);
228 * Get the most recently created entities of the given type.
229 * @param string $type
232 * @param bool|callable $additionalQuery
235 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
237 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
238 ->orderBy('created_at', 'desc');
239 if (strtolower($type) === 'page') {
240 $query = $query->where('draft', '=', false);
242 if ($additionalQuery !== false && is_callable($additionalQuery)) {
243 $additionalQuery($query);
245 return $query->skip($page * $count)->take($count)->get();
249 * Get the most recently updated entities of the given type.
250 * @param string $type
253 * @param bool|callable $additionalQuery
256 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
258 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
259 ->orderBy('updated_at', 'desc');
260 if (strtolower($type) === 'page') {
261 $query = $query->where('draft', '=', false);
263 if ($additionalQuery !== false && is_callable($additionalQuery)) {
264 $additionalQuery($query);
266 return $query->skip($page * $count)->take($count)->get();
270 * Get the most recently viewed entities.
271 * @param string|bool $type
276 public function getRecentlyViewed($type, $count = 10, $page = 0)
278 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
279 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
283 * Get the latest pages added to the system with pagination.
284 * @param string $type
288 public function getRecentlyCreatedPaginated($type, $count = 20)
290 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
294 * Get the latest pages added to the system with pagination.
295 * @param string $type
299 public function getRecentlyUpdatedPaginated($type, $count = 20)
301 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
305 * Get the most popular entities base on all views.
306 * @param string $type
311 public function getPopular(string $type, int $count = 10, int $page = 0)
313 return $this->viewService->getPopular($count, $page, $type);
317 * Get draft pages owned by the current user.
322 public function getUserDraftPages($count = 20, $page = 0)
324 return $this->entityProvider->page->where('draft', '=', true)
325 ->where('created_by', '=', user()->id)
326 ->orderBy('updated_at', 'desc')
327 ->skip($count * $page)->take($count)->get();
331 * Get the number of entities the given user has created.
332 * @param string $type
336 public function getUserTotalCreated(string $type, User $user)
338 return $this->entityProvider->get($type)
339 ->where('created_by', '=', $user->id)->count();
343 * Get the child items for a chapter sorted by priority but
344 * with draft items floated to the top.
345 * @param Bookshelf $bookshelf
346 * @return \Illuminate\Database\Eloquent\Collection|static[]
348 public function getBookshelfChildren(Bookshelf $bookshelf)
350 return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
354 * Get the direct children of a book.
356 * @return \Illuminate\Database\Eloquent\Collection
358 public function getBookDirectChildren(Book $book)
360 $pages = $this->permissionService->enforceEntityRestrictions('page', $book->directPages())->get();
361 $chapters = $this->permissionService->enforceEntityRestrictions('chapters', $book->chapters())->get();
362 return collect()->concat($pages)->concat($chapters)->sortBy('priority')->sortByDesc('draft');
366 * Get all child objects of a book.
367 * Returns a sorted collection of Pages and Chapters.
368 * Loads the book slug onto child elements to prevent access database access for getting the slug.
370 * @param bool $filterDrafts
371 * @param bool $renderPages
374 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
376 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
381 foreach ($q as $index => $rawEntity) {
382 if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
383 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
385 $entities[$index]->html = $rawEntity->html;
386 $entities[$index]->html = $this->renderPage($entities[$index]);
388 } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
389 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
390 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
391 $parents[$key] = $entities[$index];
392 $parents[$key]->setAttribute('pages', collect());
394 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
395 $tree[] = $entities[$index];
397 $entities[$index]->book = $book;
400 foreach ($entities as $entity) {
401 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
404 $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
405 if (!isset($parents[$parentKey])) {
409 $chapter = $parents[$parentKey];
410 $chapter->pages->push($entity);
413 return collect($tree);
418 * Get the bookshelves that a book is contained in.
420 * @return \Illuminate\Database\Eloquent\Collection|static[]
422 public function getBookParentShelves(Book $book)
424 return $this->permissionService->enforceEntityRestrictions('shelf', $book->shelves())->get();
428 * Get the child items for a chapter sorted by priority but
429 * with draft items floated to the top.
430 * @param Chapter $chapter
431 * @return \Illuminate\Database\Eloquent\Collection|static[]
433 public function getChapterChildren(Chapter $chapter)
435 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
436 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
441 * Get the next sequential priority for a new child element in the given book.
445 public function getNewBookPriority(Book $book)
447 $lastElem = $this->getBookChildren($book)->pop();
448 return $lastElem ? $lastElem->priority + 1 : 0;
452 * Get a new priority for a new page to be added to the given chapter.
453 * @param Chapter $chapter
456 public function getNewChapterPriority(Chapter $chapter)
458 $lastPage = $chapter->pages('DESC')->first();
459 return $lastPage !== null ? $lastPage->priority + 1 : 0;
463 * Find a suitable slug for an entity.
464 * @param string $type
465 * @param string $name
466 * @param bool|integer $currentId
467 * @param bool|integer $bookId Only pass if type is not a book
470 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
472 $slug = $this->nameToSlug($name);
473 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
474 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
481 * Updates entity restrictions from a request
482 * @param Request $request
483 * @param Entity $entity
486 public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
488 $entity->restricted = $request->get('restricted', '') === 'true';
489 $entity->permissions()->delete();
491 if ($request->filled('restrictions')) {
492 $entityPermissionData = collect($request->get('restrictions'))->flatMap(function($restrictions, $roleId) {
493 return collect($restrictions)->keys()->map(function($action) use ($roleId) {
495 'role_id' => $roleId,
496 'action' => strtolower($action),
501 $entity->permissions()->createMany($entityPermissionData);
505 $entity->rebuildPermissions();
510 * Create a new entity from request input.
511 * Used for books and chapters.
512 * @param string $type
513 * @param array $input
514 * @param Book|null $book
517 public function createFromInput(string $type, array $input = [], Book $book = null)
519 $entityModel = $this->entityProvider->get($type)->newInstance($input);
520 $entityModel->created_by = user()->id;
521 $entityModel->updated_by = user()->id;
524 $entityModel->book_id = $book->id;
527 $entityModel->refreshSlug();
528 $entityModel->save();
530 if (isset($input['tags'])) {
531 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
534 $entityModel->rebuildPermissions();
535 $this->searchService->indexEntity($entityModel);
540 * Update entity details from request input.
541 * Used for shelves, books and chapters.
543 public function updateFromInput(Entity $entityModel, array $input): Entity
545 $entityModel->fill($input);
546 $entityModel->updated_by = user()->id;
548 if ($entityModel->isDirty('name')) {
549 $entityModel->refreshSlug();
552 $entityModel->save();
554 if (isset($input['tags'])) {
555 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
558 $entityModel->rebuildPermissions();
559 $this->searchService->indexEntity($entityModel);
564 * Sync the books assigned to a shelf from a comma-separated list
566 * @param Bookshelf $shelf
567 * @param string $books
569 public function updateShelfBooks(Bookshelf $shelf, string $books)
571 $ids = explode(',', $books);
573 // Check books exist and match ordering
574 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
576 foreach ($ids as $index => $id) {
577 if ($bookIds->contains($id)) {
578 $syncData[$id] = ['order' => $index];
582 $shelf->books()->sync($syncData);
586 * Change the book that an entity belongs to.
588 public function changeBook(BookChild $bookChild, int $newBookId): Entity
590 $bookChild->book_id = $newBookId;
591 $bookChild->refreshSlug();
594 // Update related activity
595 $bookChild->activity()->update(['book_id' => $newBookId]);
597 // Update all child pages if a chapter
598 if ($bookChild->isA('chapter')) {
599 foreach ($bookChild->pages as $page) {
600 $this->changeBook($page, $newBookId);
608 * Render the page for viewing
610 * @param bool $blankIncludes
613 public function renderPage(Page $page, bool $blankIncludes = false) : string
615 $content = $page->html;
617 if (!config('app.allow_content_scripts')) {
618 $content = $this->escapeScripts($content);
621 if ($blankIncludes) {
622 $content = $this->blankPageIncludes($content);
624 $content = $this->parsePageIncludes($content);
631 * Remove any page include tags within the given HTML.
632 * @param string $html
635 protected function blankPageIncludes(string $html) : string
637 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
641 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
642 * @param string $html
643 * @return mixed|string
645 protected function parsePageIncludes(string $html) : string
648 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
650 $topLevelTags = ['table', 'ul', 'ol'];
651 foreach ($matches[1] as $index => $includeId) {
652 $splitInclude = explode('#', $includeId, 2);
653 $pageId = intval($splitInclude[0]);
654 if (is_nan($pageId)) {
658 $matchedPage = $this->getById('page', $pageId);
659 if ($matchedPage === null) {
660 $html = str_replace($matches[0][$index], '', $html);
664 if (count($splitInclude) === 1) {
665 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
669 $doc = new DOMDocument();
670 libxml_use_internal_errors(true);
671 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
672 $matchingElem = $doc->getElementById($splitInclude[1]);
673 if ($matchingElem === null) {
674 $html = str_replace($matches[0][$index], '', $html);
678 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
680 $innerContent .= $doc->saveHTML($matchingElem);
682 foreach ($matchingElem->childNodes as $childNode) {
683 $innerContent .= $doc->saveHTML($childNode);
686 libxml_clear_errors();
687 $html = str_replace($matches[0][$index], trim($innerContent), $html);
694 * Escape script tags within HTML content.
695 * @param string $html
698 protected function escapeScripts(string $html) : string
704 libxml_use_internal_errors(true);
705 $doc = new DOMDocument();
706 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
707 $xPath = new DOMXPath($doc);
709 // Remove standard script tags
710 $scriptElems = $xPath->query('//script');
711 foreach ($scriptElems as $scriptElem) {
712 $scriptElem->parentNode->removeChild($scriptElem);
715 // Remove data or JavaScript iFrames
716 $badIframes = $xPath->query('//*[contains(@src, \'data:\')] | //*[contains(@src, \'javascript:\')] | //*[@srcdoc]');
717 foreach ($badIframes as $badIframe) {
718 $badIframe->parentNode->removeChild($badIframe);
721 // Remove 'on*' attributes
722 $onAttributes = $xPath->query('//@*[starts-with(name(), \'on\')]');
723 foreach ($onAttributes as $attr) {
724 /** @var \DOMAttr $attr*/
725 $attrName = $attr->nodeName;
726 $attr->parentNode->removeAttribute($attrName);
730 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
731 foreach ($topElems as $child) {
732 $html .= $doc->saveHTML($child);
739 * Search for image usage within page content.
740 * @param $imageString
743 public function searchForImage($imageString)
745 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get(['id', 'name', 'slug', 'book_id']);
746 foreach ($pages as $page) {
747 $page->url = $page->getUrl();
751 return count($pages) > 0 ? $pages : false;
755 * Destroy a bookshelf instance
756 * @param Bookshelf $shelf
759 public function destroyBookshelf(Bookshelf $shelf)
761 $this->destroyEntityCommonRelations($shelf);
766 * Destroy a chapter and its relations.
767 * @param Chapter $chapter
770 public function destroyChapter(Chapter $chapter)
772 if (count($chapter->pages) > 0) {
773 foreach ($chapter->pages as $page) {
774 $page->chapter_id = 0;
778 $this->destroyEntityCommonRelations($chapter);
783 * Destroy a given page along with its dependencies.
785 * @throws NotifyException
788 public function destroyPage(Page $page)
790 // Check if set as custom homepage & remove setting if not used or throw error if active
791 $customHome = setting('app-homepage', '0:');
792 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
793 if (setting('app-homepage-type') === 'page') {
794 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
796 setting()->remove('app-homepage');
799 $this->destroyEntityCommonRelations($page);
801 // Delete Attached Files
802 $attachmentService = app(AttachmentService::class);
803 foreach ($page->attachments as $attachment) {
804 $attachmentService->deleteFile($attachment);
811 * Destroy or handle the common relations connected to an entity.
812 * @param Entity $entity
815 protected function destroyEntityCommonRelations(Entity $entity)
817 Activity::removeEntity($entity);
818 $entity->views()->delete();
819 $entity->permissions()->delete();
820 $entity->tags()->delete();
821 $entity->comments()->delete();
822 $this->permissionService->deleteJointPermissionsForEntity($entity);
823 $this->searchService->deleteEntityTerms($entity);
827 * Copy the permissions of a bookshelf to all child books.
828 * Returns the number of books that had permissions updated.
829 * @param Bookshelf $bookshelf
833 public function copyBookshelfPermissions(Bookshelf $bookshelf)
835 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
836 $shelfBooks = $bookshelf->books()->get();
837 $updatedBookCount = 0;
839 /** @var Book $book */
840 foreach ($shelfBooks as $book) {
841 if (!userCan('restrictions-manage', $book)) {
844 $book->permissions()->delete();
845 $book->restricted = $bookshelf->restricted;
846 $book->permissions()->createMany($shelfPermissions);
848 $book->rebuildPermissions();
852 return $updatedBookCount;