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|bool $type
301 public function getPopular($type, $count = 10, $page = 0)
303 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
304 return $this->viewService->getPopular($count, $page, $filter);
308 * Get draft pages owned by the current user.
313 public function getUserDraftPages($count = 20, $page = 0)
315 return $this->entityProvider->page->where('draft', '=', true)
316 ->where('created_by', '=', user()->id)
317 ->orderBy('updated_at', 'desc')
318 ->skip($count * $page)->take($count)->get();
322 * Get the number of entities the given user has created.
323 * @param string $type
327 public function getUserTotalCreated(string $type, User $user)
329 return $this->entityProvider->get($type)
330 ->where('created_by', '=', $user->id)->count();
334 * Get the child items for a chapter sorted by priority but
335 * with draft items floated to the top.
336 * @param \BookStack\Entities\Bookshelf $bookshelf
337 * @return \Illuminate\Database\Eloquent\Collection|static[]
339 public function getBookshelfChildren(Bookshelf $bookshelf)
341 return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
345 * Get the direct children of a book.
347 * @return \Illuminate\Database\Eloquent\Collection
349 public function getBookDirectChildren(Book $book)
351 $pages = $this->permissionService->enforceEntityRestrictions('page', $book->directPages())->get();
352 $chapters = $this->permissionService->enforceEntityRestrictions('chapters', $book->chapters())->get();
353 return collect()->concat($pages)->concat($chapters)->sortBy('priority')->sortByDesc('draft');
357 * Get all child objects of a book.
358 * Returns a sorted collection of Pages and Chapters.
359 * Loads the book slug onto child elements to prevent access database access for getting the slug.
360 * @param \BookStack\Entities\Book $book
361 * @param bool $filterDrafts
362 * @param bool $renderPages
365 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
367 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
372 foreach ($q as $index => $rawEntity) {
373 if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
374 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
376 $entities[$index]->html = $rawEntity->html;
377 $entities[$index]->html = $this->renderPage($entities[$index]);
379 } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
380 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
381 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
382 $parents[$key] = $entities[$index];
383 $parents[$key]->setAttribute('pages', collect());
385 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
386 $tree[] = $entities[$index];
388 $entities[$index]->book = $book;
391 foreach ($entities as $entity) {
392 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
395 $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
396 if (!isset($parents[$parentKey])) {
400 $chapter = $parents[$parentKey];
401 $chapter->pages->push($entity);
404 return collect($tree);
408 * Get the child items for a chapter sorted by priority but
409 * with draft items floated to the top.
410 * @param \BookStack\Entities\Chapter $chapter
411 * @return \Illuminate\Database\Eloquent\Collection|static[]
413 public function getChapterChildren(Chapter $chapter)
415 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
416 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
421 * Get the next sequential priority for a new child element in the given book.
422 * @param \BookStack\Entities\Book $book
425 public function getNewBookPriority(Book $book)
427 $lastElem = $this->getBookChildren($book)->pop();
428 return $lastElem ? $lastElem->priority + 1 : 0;
432 * Get a new priority for a new page to be added to the given chapter.
433 * @param \BookStack\Entities\Chapter $chapter
436 public function getNewChapterPriority(Chapter $chapter)
438 $lastPage = $chapter->pages('DESC')->first();
439 return $lastPage !== null ? $lastPage->priority + 1 : 0;
443 * Find a suitable slug for an entity.
444 * @param string $type
445 * @param string $name
446 * @param bool|integer $currentId
447 * @param bool|integer $bookId Only pass if type is not a book
450 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
452 $slug = $this->nameToSlug($name);
453 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
454 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
460 * Check if a slug already exists in the database.
461 * @param string $type
462 * @param string $slug
463 * @param bool|integer $currentId
464 * @param bool|integer $bookId
467 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
469 $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
470 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
471 $query = $query->where('book_id', '=', $bookId);
474 $query = $query->where('id', '!=', $currentId);
476 return $query->count() > 0;
480 * Updates entity restrictions from a request
481 * @param Request $request
482 * @param \BookStack\Entities\Entity $entity
485 public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
487 $entity->restricted = $request->get('restricted', '') === 'true';
488 $entity->permissions()->delete();
490 if ($request->filled('restrictions')) {
491 foreach ($request->get('restrictions') as $roleId => $restrictions) {
492 foreach ($restrictions as $action => $value) {
493 $entity->permissions()->create([
494 'role_id' => $roleId,
495 'action' => strtolower($action)
502 $this->permissionService->buildJointPermissionsForEntity($entity);
508 * Create a new entity from request input.
509 * Used for books and chapters.
510 * @param string $type
511 * @param array $input
512 * @param bool|Book $book
513 * @return \BookStack\Entities\Entity
515 public function createFromInput($type, $input = [], $book = false)
517 $isChapter = strtolower($type) === 'chapter';
518 $entityModel = $this->entityProvider->get($type)->newInstance($input);
519 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
520 $entityModel->created_by = user()->id;
521 $entityModel->updated_by = user()->id;
522 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
524 if (isset($input['tags'])) {
525 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
528 $this->permissionService->buildJointPermissionsForEntity($entityModel);
529 $this->searchService->indexEntity($entityModel);
534 * Update entity details from request input.
535 * Used for books and chapters
536 * @param string $type
537 * @param \BookStack\Entities\Entity $entityModel
538 * @param array $input
539 * @return \BookStack\Entities\Entity
541 public function updateFromInput($type, Entity $entityModel, $input = [])
543 if ($entityModel->name !== $input['name']) {
544 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
546 $entityModel->fill($input);
547 $entityModel->updated_by = user()->id;
548 $entityModel->save();
550 if (isset($input['tags'])) {
551 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
554 $this->permissionService->buildJointPermissionsForEntity($entityModel);
555 $this->searchService->indexEntity($entityModel);
560 * Sync the books assigned to a shelf from a comma-separated list
562 * @param \BookStack\Entities\Bookshelf $shelf
563 * @param string $books
565 public function updateShelfBooks(Bookshelf $shelf, string $books)
567 $ids = explode(',', $books);
569 // Check books exist and match ordering
570 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
572 foreach ($ids as $index => $id) {
573 if ($bookIds->contains($id)) {
574 $syncData[$id] = ['order' => $index];
578 $shelf->books()->sync($syncData);
582 * Change the book that an entity belongs to.
583 * @param string $type
584 * @param integer $newBookId
585 * @param Entity $entity
586 * @param bool $rebuildPermissions
587 * @return \BookStack\Entities\Entity
589 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
591 $entity->book_id = $newBookId;
592 // Update related activity
593 foreach ($entity->activity as $activity) {
594 $activity->book_id = $newBookId;
597 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
600 // Update all child pages if a chapter
601 if (strtolower($type) === 'chapter') {
602 foreach ($entity->pages as $page) {
603 $this->changeBook('page', $newBookId, $page, false);
607 // Update permissions if applicable
608 if ($rebuildPermissions) {
609 $entity->load('book');
610 $this->permissionService->buildJointPermissionsForEntity($entity->book);
617 * Alias method to update the book jointPermissions in the PermissionService.
620 public function buildJointPermissionsForBook(Book $book)
622 $this->permissionService->buildJointPermissionsForEntity($book);
626 * Format a name as a url slug.
630 protected function nameToSlug($name)
632 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
633 $slug = preg_replace('/\s{2,}/', ' ', $slug);
634 $slug = str_replace(' ', '-', $slug);
636 $slug = substr(md5(rand(1, 500)), 0, 5);
642 * Render the page for viewing
644 * @param bool $blankIncludes
647 public function renderPage(Page $page, bool $blankIncludes = false) : string
649 $content = $page->html;
651 if (!config('app.allow_content_scripts')) {
652 $content = $this->escapeScripts($content);
655 if ($blankIncludes) {
656 $content = $this->blankPageIncludes($content);
658 $content = $this->parsePageIncludes($content);
665 * Remove any page include tags within the given HTML.
666 * @param string $html
669 protected function blankPageIncludes(string $html) : string
671 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
675 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
676 * @param string $html
677 * @return mixed|string
679 protected function parsePageIncludes(string $html) : string
682 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
684 $topLevelTags = ['table', 'ul', 'ol'];
685 foreach ($matches[1] as $index => $includeId) {
686 $splitInclude = explode('#', $includeId, 2);
687 $pageId = intval($splitInclude[0]);
688 if (is_nan($pageId)) {
692 $matchedPage = $this->getById('page', $pageId);
693 if ($matchedPage === null) {
694 $html = str_replace($matches[0][$index], '', $html);
698 if (count($splitInclude) === 1) {
699 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
703 $doc = new DOMDocument();
704 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
705 $matchingElem = $doc->getElementById($splitInclude[1]);
706 if ($matchingElem === null) {
707 $html = str_replace($matches[0][$index], '', $html);
711 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
713 $innerContent .= $doc->saveHTML($matchingElem);
715 foreach ($matchingElem->childNodes as $childNode) {
716 $innerContent .= $doc->saveHTML($childNode);
719 $html = str_replace($matches[0][$index], trim($innerContent), $html);
726 * Escape script tags within HTML content.
727 * @param string $html
730 protected function escapeScripts(string $html) : string
732 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
734 preg_match_all($scriptSearchRegex, $html, $matches);
736 foreach ($matches[0] as $match) {
737 $html = str_replace($match, htmlentities($match), $html);
743 * Search for image usage within page content.
744 * @param $imageString
747 public function searchForImage($imageString)
749 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
750 foreach ($pages as $page) {
751 $page->url = $page->getUrl();
755 return count($pages) > 0 ? $pages : false;
759 * Destroy a bookshelf instance
760 * @param \BookStack\Entities\Bookshelf $shelf
763 public function destroyBookshelf(Bookshelf $shelf)
765 $this->destroyEntityCommonRelations($shelf);
770 * Destroy the provided book and all its child entities.
771 * @param \BookStack\Entities\Book $book
772 * @throws NotifyException
775 public function destroyBook(Book $book)
777 foreach ($book->pages as $page) {
778 $this->destroyPage($page);
780 foreach ($book->chapters as $chapter) {
781 $this->destroyChapter($chapter);
783 $this->destroyEntityCommonRelations($book);
788 * Destroy a chapter and its relations.
789 * @param \BookStack\Entities\Chapter $chapter
792 public function destroyChapter(Chapter $chapter)
794 if (count($chapter->pages) > 0) {
795 foreach ($chapter->pages as $page) {
796 $page->chapter_id = 0;
800 $this->destroyEntityCommonRelations($chapter);
805 * Destroy a given page along with its dependencies.
807 * @throws NotifyException
810 public function destroyPage(Page $page)
812 // Check if set as custom homepage
813 $customHome = setting('app-homepage', '0:');
814 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
815 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
818 $this->destroyEntityCommonRelations($page);
820 // Delete Attached Files
821 $attachmentService = app(AttachmentService::class);
822 foreach ($page->attachments as $attachment) {
823 $attachmentService->deleteFile($attachment);
830 * Destroy or handle the common relations connected to an entity.
831 * @param \BookStack\Entities\Entity $entity
834 protected function destroyEntityCommonRelations(Entity $entity)
836 \Activity::removeEntity($entity);
837 $entity->views()->delete();
838 $entity->permissions()->delete();
839 $entity->tags()->delete();
840 $entity->comments()->delete();
841 $this->permissionService->deleteJointPermissionsForEntity($entity);
842 $this->searchService->deleteEntityTerms($entity);
846 * Copy the permissions of a bookshelf to all child books.
847 * Returns the number of books that had permissions updated.
848 * @param \BookStack\Entities\Bookshelf $bookshelf
852 public function copyBookshelfPermissions(Bookshelf $bookshelf)
854 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
855 $shelfBooks = $bookshelf->books()->get();
856 $updatedBookCount = 0;
858 foreach ($shelfBooks as $book) {
859 if (!userCan('restrictions-manage', $book)) {
862 $book->permissions()->delete();
863 $book->restricted = $bookshelf->restricted;
864 $book->permissions()->createMany($shelfPermissions);
866 $this->permissionService->buildJointPermissionsForEntity($book);
870 return $updatedBookCount;