1 <?php namespace BookStack\Entities\Repos;
3 use BookStack\Actions\TagRepo;
4 use BookStack\Actions\ViewService;
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Book;
8 use BookStack\Entities\Bookshelf;
9 use BookStack\Entities\Chapter;
10 use BookStack\Entities\Entity;
11 use BookStack\Entities\EntityProvider;
12 use BookStack\Entities\Page;
13 use BookStack\Entities\SearchService;
14 use BookStack\Exceptions\NotFoundException;
15 use BookStack\Exceptions\NotifyException;
16 use BookStack\Uploads\AttachmentService;
18 use Illuminate\Database\Eloquent\Builder;
19 use Illuminate\Http\Request;
20 use Illuminate\Support\Collection;
28 protected $entityProvider;
31 * @var PermissionService
33 protected $permissionService;
38 protected $viewService;
48 protected $searchService;
51 * EntityRepo constructor.
52 * @param EntityProvider $entityProvider
53 * @param ViewService $viewService
54 * @param PermissionService $permissionService
55 * @param TagRepo $tagRepo
56 * @param SearchService $searchService
58 public function __construct(
59 EntityProvider $entityProvider,
60 ViewService $viewService,
61 PermissionService $permissionService,
63 SearchService $searchService
65 $this->entityProvider = $entityProvider;
66 $this->viewService = $viewService;
67 $this->permissionService = $permissionService;
68 $this->tagRepo = $tagRepo;
69 $this->searchService = $searchService;
73 * Base query for searching entities via permission system
75 * @param bool $allowDrafts
76 * @param string $permission
77 * @return \Illuminate\Database\Query\Builder
79 protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
81 $q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
82 if (strtolower($type) === 'page' && !$allowDrafts) {
83 $q = $q->where('draft', '=', false);
89 * Check if an entity with the given id exists.
94 public function exists($type, $id)
96 return $this->entityQuery($type)->where('id', '=', $id)->exists();
100 * Get an entity by ID
101 * @param string $type
103 * @param bool $allowDrafts
104 * @param bool $ignorePermissions
105 * @return \BookStack\Entities\Entity
107 public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
109 $query = $this->entityQuery($type, $allowDrafts);
111 if ($ignorePermissions) {
112 $query = $this->entityProvider->get($type)->newQuery();
115 return $query->find($id);
119 * @param string $type
121 * @param bool $allowDrafts
122 * @param bool $ignorePermissions
123 * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
125 public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
127 $query = $this->entityQuery($type, $allowDrafts);
129 if ($ignorePermissions) {
130 $query = $this->entityProvider->get($type)->newQuery();
133 return $query->whereIn('id', $ids)->get();
137 * Get an entity by its url slug.
138 * @param string $type
139 * @param string $slug
140 * @param string|bool $bookSlug
141 * @return \BookStack\Entities\Entity
142 * @throws NotFoundException
144 public function getBySlug($type, $slug, $bookSlug = false)
146 $q = $this->entityQuery($type)->where('slug', '=', $slug);
148 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
149 $q = $q->where('book_id', '=', function ($query) use ($bookSlug) {
151 ->from($this->entityProvider->book->getTable())
152 ->where('slug', '=', $bookSlug)->limit(1);
155 $entity = $q->first();
156 if ($entity === null) {
157 throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
164 * Get all entities of a type with the given permission, limited by count unless count is false.
165 * @param string $type
166 * @param integer|bool $count
167 * @param string $permission
170 public function getAll($type, $count = 20, $permission = 'view')
172 $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
173 if ($count !== false) {
174 $q = $q->take($count);
180 * Get all entities in a paginated format
183 * @param string $sort
184 * @param string $order
185 * @param null|callable $queryAddition
186 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
188 public function getAllPaginated($type, int $count = 10, string $sort = 'name', string $order = 'asc', $queryAddition = null)
190 $query = $this->entityQuery($type);
191 $query = $this->addSortToQuery($query, $sort, $order);
192 if ($queryAddition) {
193 $queryAddition($query);
195 return $query->paginate($count);
199 * Add sorting operations to an entity query.
200 * @param Builder $query
201 * @param string $sort
202 * @param string $order
205 protected function addSortToQuery(Builder $query, string $sort = 'name', string $order = 'asc')
207 $order = ($order === 'asc') ? 'asc' : 'desc';
208 $propertySorts = ['name', 'created_at', 'updated_at'];
210 if (in_array($sort, $propertySorts)) {
211 return $query->orderBy($sort, $order);
218 * Get the most recently created entities of the given type.
219 * @param string $type
222 * @param bool|callable $additionalQuery
225 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
227 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
228 ->orderBy('created_at', 'desc');
229 if (strtolower($type) === 'page') {
230 $query = $query->where('draft', '=', false);
232 if ($additionalQuery !== false && is_callable($additionalQuery)) {
233 $additionalQuery($query);
235 return $query->skip($page * $count)->take($count)->get();
239 * Get the most recently updated entities of the given type.
240 * @param string $type
243 * @param bool|callable $additionalQuery
246 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
248 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
249 ->orderBy('updated_at', 'desc');
250 if (strtolower($type) === 'page') {
251 $query = $query->where('draft', '=', false);
253 if ($additionalQuery !== false && is_callable($additionalQuery)) {
254 $additionalQuery($query);
256 return $query->skip($page * $count)->take($count)->get();
260 * Get the most recently viewed entities.
261 * @param string|bool $type
266 public function getRecentlyViewed($type, $count = 10, $page = 0)
268 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
269 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
273 * Get the latest pages added to the system with pagination.
274 * @param string $type
278 public function getRecentlyCreatedPaginated($type, $count = 20)
280 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
284 * Get the latest pages added to the system with pagination.
285 * @param string $type
289 public function getRecentlyUpdatedPaginated($type, $count = 20)
291 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
295 * Get the most popular entities base on all views.
296 * @param string $type
301 public function getPopular(string $type, int $count = 10, int $page = 0)
303 return $this->viewService->getPopular($count, $page, $type);
307 * Get draft pages owned by the current user.
312 public function getUserDraftPages($count = 20, $page = 0)
314 return $this->entityProvider->page->where('draft', '=', true)
315 ->where('created_by', '=', user()->id)
316 ->orderBy('updated_at', 'desc')
317 ->skip($count * $page)->take($count)->get();
321 * Get the number of entities the given user has created.
322 * @param string $type
326 public function getUserTotalCreated(string $type, User $user)
328 return $this->entityProvider->get($type)
329 ->where('created_by', '=', $user->id)->count();
333 * Get the child items for a chapter sorted by priority but
334 * with draft items floated to the top.
335 * @param \BookStack\Entities\Bookshelf $bookshelf
336 * @return \Illuminate\Database\Eloquent\Collection|static[]
338 public function getBookshelfChildren(Bookshelf $bookshelf)
340 return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
344 * Get the direct children of a book.
346 * @return \Illuminate\Database\Eloquent\Collection
348 public function getBookDirectChildren(Book $book)
350 $pages = $this->permissionService->enforceEntityRestrictions('page', $book->directPages())->get();
351 $chapters = $this->permissionService->enforceEntityRestrictions('chapters', $book->chapters())->get();
352 return collect()->concat($pages)->concat($chapters)->sortBy('priority')->sortByDesc('draft');
356 * Get all child objects of a book.
357 * Returns a sorted collection of Pages and Chapters.
358 * Loads the book slug onto child elements to prevent access database access for getting the slug.
359 * @param \BookStack\Entities\Book $book
360 * @param bool $filterDrafts
361 * @param bool $renderPages
364 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
366 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
371 foreach ($q as $index => $rawEntity) {
372 if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
373 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
375 $entities[$index]->html = $rawEntity->html;
376 $entities[$index]->html = $this->renderPage($entities[$index]);
378 } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
379 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
380 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
381 $parents[$key] = $entities[$index];
382 $parents[$key]->setAttribute('pages', collect());
384 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
385 $tree[] = $entities[$index];
387 $entities[$index]->book = $book;
390 foreach ($entities as $entity) {
391 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
394 $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
395 if (!isset($parents[$parentKey])) {
399 $chapter = $parents[$parentKey];
400 $chapter->pages->push($entity);
403 return collect($tree);
407 * Get the child items for a chapter sorted by priority but
408 * with draft items floated to the top.
409 * @param \BookStack\Entities\Chapter $chapter
410 * @return \Illuminate\Database\Eloquent\Collection|static[]
412 public function getChapterChildren(Chapter $chapter)
414 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
415 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
420 * Get the next sequential priority for a new child element in the given book.
421 * @param \BookStack\Entities\Book $book
424 public function getNewBookPriority(Book $book)
426 $lastElem = $this->getBookChildren($book)->pop();
427 return $lastElem ? $lastElem->priority + 1 : 0;
431 * Get a new priority for a new page to be added to the given chapter.
432 * @param \BookStack\Entities\Chapter $chapter
435 public function getNewChapterPriority(Chapter $chapter)
437 $lastPage = $chapter->pages('DESC')->first();
438 return $lastPage !== null ? $lastPage->priority + 1 : 0;
442 * Find a suitable slug for an entity.
443 * @param string $type
444 * @param string $name
445 * @param bool|integer $currentId
446 * @param bool|integer $bookId Only pass if type is not a book
449 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
451 $slug = $this->nameToSlug($name);
452 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
453 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
459 * Check if a slug already exists in the database.
460 * @param string $type
461 * @param string $slug
462 * @param bool|integer $currentId
463 * @param bool|integer $bookId
466 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
468 $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
469 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
470 $query = $query->where('book_id', '=', $bookId);
473 $query = $query->where('id', '!=', $currentId);
475 return $query->count() > 0;
479 * Updates entity restrictions from a request
480 * @param Request $request
481 * @param \BookStack\Entities\Entity $entity
484 public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
486 $entity->restricted = $request->get('restricted', '') === 'true';
487 $entity->permissions()->delete();
489 if ($request->filled('restrictions')) {
490 foreach ($request->get('restrictions') as $roleId => $restrictions) {
491 foreach ($restrictions as $action => $value) {
492 $entity->permissions()->create([
493 'role_id' => $roleId,
494 'action' => strtolower($action)
501 $this->permissionService->buildJointPermissionsForEntity($entity);
507 * Create a new entity from request input.
508 * Used for books and chapters.
509 * @param string $type
510 * @param array $input
511 * @param bool|Book $book
512 * @return \BookStack\Entities\Entity
514 public function createFromInput($type, $input = [], $book = false)
516 $isChapter = strtolower($type) === 'chapter';
517 $entityModel = $this->entityProvider->get($type)->newInstance($input);
518 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
519 $entityModel->created_by = user()->id;
520 $entityModel->updated_by = user()->id;
521 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
523 if (isset($input['tags'])) {
524 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
527 $this->permissionService->buildJointPermissionsForEntity($entityModel);
528 $this->searchService->indexEntity($entityModel);
533 * Update entity details from request input.
534 * Used for books and chapters
535 * @param string $type
536 * @param \BookStack\Entities\Entity $entityModel
537 * @param array $input
538 * @return \BookStack\Entities\Entity
540 public function updateFromInput($type, Entity $entityModel, $input = [])
542 if ($entityModel->name !== $input['name']) {
543 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
545 $entityModel->fill($input);
546 $entityModel->updated_by = user()->id;
547 $entityModel->save();
549 if (isset($input['tags'])) {
550 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
553 $this->permissionService->buildJointPermissionsForEntity($entityModel);
554 $this->searchService->indexEntity($entityModel);
559 * Sync the books assigned to a shelf from a comma-separated list
561 * @param \BookStack\Entities\Bookshelf $shelf
562 * @param string $books
564 public function updateShelfBooks(Bookshelf $shelf, string $books)
566 $ids = explode(',', $books);
568 // Check books exist and match ordering
569 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
571 foreach ($ids as $index => $id) {
572 if ($bookIds->contains($id)) {
573 $syncData[$id] = ['order' => $index];
577 $shelf->books()->sync($syncData);
581 * Append a Book to a BookShelf.
582 * @param Bookshelf $shelf
585 public function appendBookToShelf(Bookshelf $shelf, Book $book)
587 if ($shelf->contains($book)) {
591 $maxOrder = $shelf->books()->max('order');
592 $shelf->books()->attach($book->id, ['order' => $maxOrder + 1]);
596 * Change the book that an entity belongs to.
597 * @param string $type
598 * @param integer $newBookId
599 * @param Entity $entity
600 * @param bool $rebuildPermissions
601 * @return \BookStack\Entities\Entity
603 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
605 $entity->book_id = $newBookId;
606 // Update related activity
607 foreach ($entity->activity as $activity) {
608 $activity->book_id = $newBookId;
611 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
614 // Update all child pages if a chapter
615 if (strtolower($type) === 'chapter') {
616 foreach ($entity->pages as $page) {
617 $this->changeBook('page', $newBookId, $page, false);
621 // Update permissions if applicable
622 if ($rebuildPermissions) {
623 $entity->load('book');
624 $this->permissionService->buildJointPermissionsForEntity($entity->book);
631 * Alias method to update the book jointPermissions in the PermissionService.
634 public function buildJointPermissionsForBook(Book $book)
636 $this->permissionService->buildJointPermissionsForEntity($book);
640 * Format a name as a url slug.
644 protected function nameToSlug($name)
646 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
647 $slug = preg_replace('/\s{2,}/', ' ', $slug);
648 $slug = str_replace(' ', '-', $slug);
650 $slug = substr(md5(rand(1, 500)), 0, 5);
656 * Render the page for viewing
658 * @param bool $blankIncludes
661 public function renderPage(Page $page, bool $blankIncludes = false) : string
663 $content = $page->html;
665 if (!config('app.allow_content_scripts')) {
666 $content = $this->escapeScripts($content);
669 if ($blankIncludes) {
670 $content = $this->blankPageIncludes($content);
672 $content = $this->parsePageIncludes($content);
679 * Remove any page include tags within the given HTML.
680 * @param string $html
683 protected function blankPageIncludes(string $html) : string
685 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
689 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
690 * @param string $html
691 * @return mixed|string
693 protected function parsePageIncludes(string $html) : string
696 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
698 $topLevelTags = ['table', 'ul', 'ol'];
699 foreach ($matches[1] as $index => $includeId) {
700 $splitInclude = explode('#', $includeId, 2);
701 $pageId = intval($splitInclude[0]);
702 if (is_nan($pageId)) {
706 $matchedPage = $this->getById('page', $pageId);
707 if ($matchedPage === null) {
708 $html = str_replace($matches[0][$index], '', $html);
712 if (count($splitInclude) === 1) {
713 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
717 $doc = new DOMDocument();
718 libxml_use_internal_errors(true);
719 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
720 $matchingElem = $doc->getElementById($splitInclude[1]);
721 if ($matchingElem === null) {
722 $html = str_replace($matches[0][$index], '', $html);
726 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
728 $innerContent .= $doc->saveHTML($matchingElem);
730 foreach ($matchingElem->childNodes as $childNode) {
731 $innerContent .= $doc->saveHTML($childNode);
734 libxml_clear_errors();
735 $html = str_replace($matches[0][$index], trim($innerContent), $html);
742 * Escape script tags within HTML content.
743 * @param string $html
746 protected function escapeScripts(string $html) : string
748 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
750 preg_match_all($scriptSearchRegex, $html, $matches);
752 foreach ($matches[0] as $match) {
753 $html = str_replace($match, htmlentities($match), $html);
759 * Search for image usage within page content.
760 * @param $imageString
763 public function searchForImage($imageString)
765 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get(['id', 'name', 'slug', 'book_id']);
766 foreach ($pages as $page) {
767 $page->url = $page->getUrl();
771 return count($pages) > 0 ? $pages : false;
775 * Destroy a bookshelf instance
776 * @param \BookStack\Entities\Bookshelf $shelf
779 public function destroyBookshelf(Bookshelf $shelf)
781 $this->destroyEntityCommonRelations($shelf);
786 * Destroy the provided book and all its child entities.
787 * @param \BookStack\Entities\Book $book
788 * @throws NotifyException
791 public function destroyBook(Book $book)
793 foreach ($book->pages as $page) {
794 $this->destroyPage($page);
796 foreach ($book->chapters as $chapter) {
797 $this->destroyChapter($chapter);
799 $this->destroyEntityCommonRelations($book);
804 * Destroy a chapter and its relations.
805 * @param \BookStack\Entities\Chapter $chapter
808 public function destroyChapter(Chapter $chapter)
810 if (count($chapter->pages) > 0) {
811 foreach ($chapter->pages as $page) {
812 $page->chapter_id = 0;
816 $this->destroyEntityCommonRelations($chapter);
821 * Destroy a given page along with its dependencies.
823 * @throws NotifyException
826 public function destroyPage(Page $page)
828 // Check if set as custom homepage
829 $customHome = setting('app-homepage', '0:');
830 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
831 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
834 $this->destroyEntityCommonRelations($page);
836 // Delete Attached Files
837 $attachmentService = app(AttachmentService::class);
838 foreach ($page->attachments as $attachment) {
839 $attachmentService->deleteFile($attachment);
846 * Destroy or handle the common relations connected to an entity.
847 * @param \BookStack\Entities\Entity $entity
850 protected function destroyEntityCommonRelations(Entity $entity)
852 \Activity::removeEntity($entity);
853 $entity->views()->delete();
854 $entity->permissions()->delete();
855 $entity->tags()->delete();
856 $entity->comments()->delete();
857 $this->permissionService->deleteJointPermissionsForEntity($entity);
858 $this->searchService->deleteEntityTerms($entity);
862 * Copy the permissions of a bookshelf to all child books.
863 * Returns the number of books that had permissions updated.
864 * @param \BookStack\Entities\Bookshelf $bookshelf
868 public function copyBookshelfPermissions(Bookshelf $bookshelf)
870 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
871 $shelfBooks = $bookshelf->books()->get();
872 $updatedBookCount = 0;
874 foreach ($shelfBooks as $book) {
875 if (!userCan('restrictions-manage', $book)) {
878 $book->permissions()->delete();
879 $book->restricted = $bookshelf->restricted;
880 $book->permissions()->createMany($shelfPermissions);
882 $this->permissionService->buildJointPermissionsForEntity($book);
886 return $updatedBookCount;