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 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
187 public function getAllPaginated($type, int $count = 10, string $sort = 'name', string $order = 'asc')
189 $query = $this->entityQuery($type);
190 $query = $this->addSortToQuery($query, $sort, $order);
191 return $query->paginate($count);
194 protected function addSortToQuery(Builder $query, string $sort = 'name', string $order = 'asc')
196 $order = ($order === 'asc') ? 'asc' : 'desc';
197 $propertySorts = ['name', 'created_at', 'updated_at'];
199 if (in_array($sort, $propertySorts)) {
200 return $query->orderBy($sort, $order);
207 * Get the most recently created entities of the given type.
208 * @param string $type
211 * @param bool|callable $additionalQuery
214 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
216 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
217 ->orderBy('created_at', 'desc');
218 if (strtolower($type) === 'page') {
219 $query = $query->where('draft', '=', false);
221 if ($additionalQuery !== false && is_callable($additionalQuery)) {
222 $additionalQuery($query);
224 return $query->skip($page * $count)->take($count)->get();
228 * Get the most recently updated entities of the given type.
229 * @param string $type
232 * @param bool|callable $additionalQuery
235 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
237 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
238 ->orderBy('updated_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 viewed entities.
250 * @param string|bool $type
255 public function getRecentlyViewed($type, $count = 10, $page = 0)
257 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
258 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
262 * Get the latest pages added to the system with pagination.
263 * @param string $type
267 public function getRecentlyCreatedPaginated($type, $count = 20)
269 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
273 * Get the latest pages added to the system with pagination.
274 * @param string $type
278 public function getRecentlyUpdatedPaginated($type, $count = 20)
280 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
284 * Get the most popular entities base on all views.
285 * @param string|bool $type
290 public function getPopular($type, $count = 10, $page = 0)
292 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
293 return $this->viewService->getPopular($count, $page, $filter);
297 * Get draft pages owned by the current user.
302 public function getUserDraftPages($count = 20, $page = 0)
304 return $this->entityProvider->page->where('draft', '=', true)
305 ->where('created_by', '=', user()->id)
306 ->orderBy('updated_at', 'desc')
307 ->skip($count * $page)->take($count)->get();
311 * Get the number of entities the given user has created.
312 * @param string $type
316 public function getUserTotalCreated(string $type, User $user)
318 return $this->entityProvider->get($type)
319 ->where('created_by', '=', $user->id)->count();
323 * Get the child items for a chapter sorted by priority but
324 * with draft items floated to the top.
325 * @param \BookStack\Entities\Bookshelf $bookshelf
326 * @return \Illuminate\Database\Eloquent\Collection|static[]
328 public function getBookshelfChildren(Bookshelf $bookshelf)
330 return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
334 * Get all child objects of a book.
335 * Returns a sorted collection of Pages and Chapters.
336 * Loads the book slug onto child elements to prevent access database access for getting the slug.
337 * @param \BookStack\Entities\Book $book
338 * @param bool $filterDrafts
339 * @param bool $renderPages
342 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
344 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
349 foreach ($q as $index => $rawEntity) {
350 if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
351 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
353 $entities[$index]->html = $rawEntity->html;
354 $entities[$index]->html = $this->renderPage($entities[$index]);
356 } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
357 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
358 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
359 $parents[$key] = $entities[$index];
360 $parents[$key]->setAttribute('pages', collect());
362 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
363 $tree[] = $entities[$index];
365 $entities[$index]->book = $book;
368 foreach ($entities as $entity) {
369 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
372 $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
373 if (!isset($parents[$parentKey])) {
377 $chapter = $parents[$parentKey];
378 $chapter->pages->push($entity);
381 return collect($tree);
385 * Get the child items for a chapter sorted by priority but
386 * with draft items floated to the top.
387 * @param \BookStack\Entities\Chapter $chapter
388 * @return \Illuminate\Database\Eloquent\Collection|static[]
390 public function getChapterChildren(Chapter $chapter)
392 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
393 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
398 * Get the next sequential priority for a new child element in the given book.
399 * @param \BookStack\Entities\Book $book
402 public function getNewBookPriority(Book $book)
404 $lastElem = $this->getBookChildren($book)->pop();
405 return $lastElem ? $lastElem->priority + 1 : 0;
409 * Get a new priority for a new page to be added to the given chapter.
410 * @param \BookStack\Entities\Chapter $chapter
413 public function getNewChapterPriority(Chapter $chapter)
415 $lastPage = $chapter->pages('DESC')->first();
416 return $lastPage !== null ? $lastPage->priority + 1 : 0;
420 * Find a suitable slug for an entity.
421 * @param string $type
422 * @param string $name
423 * @param bool|integer $currentId
424 * @param bool|integer $bookId Only pass if type is not a book
427 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
429 $slug = $this->nameToSlug($name);
430 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
431 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
437 * Check if a slug already exists in the database.
438 * @param string $type
439 * @param string $slug
440 * @param bool|integer $currentId
441 * @param bool|integer $bookId
444 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
446 $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
447 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
448 $query = $query->where('book_id', '=', $bookId);
451 $query = $query->where('id', '!=', $currentId);
453 return $query->count() > 0;
457 * Updates entity restrictions from a request
458 * @param Request $request
459 * @param \BookStack\Entities\Entity $entity
462 public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
464 $entity->restricted = $request->get('restricted', '') === 'true';
465 $entity->permissions()->delete();
467 if ($request->filled('restrictions')) {
468 foreach ($request->get('restrictions') as $roleId => $restrictions) {
469 foreach ($restrictions as $action => $value) {
470 $entity->permissions()->create([
471 'role_id' => $roleId,
472 'action' => strtolower($action)
479 $this->permissionService->buildJointPermissionsForEntity($entity);
485 * Create a new entity from request input.
486 * Used for books and chapters.
487 * @param string $type
488 * @param array $input
489 * @param bool|Book $book
490 * @return \BookStack\Entities\Entity
492 public function createFromInput($type, $input = [], $book = false)
494 $isChapter = strtolower($type) === 'chapter';
495 $entityModel = $this->entityProvider->get($type)->newInstance($input);
496 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
497 $entityModel->created_by = user()->id;
498 $entityModel->updated_by = user()->id;
499 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
501 if (isset($input['tags'])) {
502 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
505 $this->permissionService->buildJointPermissionsForEntity($entityModel);
506 $this->searchService->indexEntity($entityModel);
511 * Update entity details from request input.
512 * Used for books and chapters
513 * @param string $type
514 * @param \BookStack\Entities\Entity $entityModel
515 * @param array $input
516 * @return \BookStack\Entities\Entity
518 public function updateFromInput($type, Entity $entityModel, $input = [])
520 if ($entityModel->name !== $input['name']) {
521 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
523 $entityModel->fill($input);
524 $entityModel->updated_by = user()->id;
525 $entityModel->save();
527 if (isset($input['tags'])) {
528 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
531 $this->permissionService->buildJointPermissionsForEntity($entityModel);
532 $this->searchService->indexEntity($entityModel);
537 * Sync the books assigned to a shelf from a comma-separated list
539 * @param \BookStack\Entities\Bookshelf $shelf
540 * @param string $books
542 public function updateShelfBooks(Bookshelf $shelf, string $books)
544 $ids = explode(',', $books);
546 // Check books exist and match ordering
547 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
549 foreach ($ids as $index => $id) {
550 if ($bookIds->contains($id)) {
551 $syncData[$id] = ['order' => $index];
555 $shelf->books()->sync($syncData);
559 * Change the book that an entity belongs to.
560 * @param string $type
561 * @param integer $newBookId
562 * @param Entity $entity
563 * @param bool $rebuildPermissions
564 * @return \BookStack\Entities\Entity
566 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
568 $entity->book_id = $newBookId;
569 // Update related activity
570 foreach ($entity->activity as $activity) {
571 $activity->book_id = $newBookId;
574 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
577 // Update all child pages if a chapter
578 if (strtolower($type) === 'chapter') {
579 foreach ($entity->pages as $page) {
580 $this->changeBook('page', $newBookId, $page, false);
584 // Update permissions if applicable
585 if ($rebuildPermissions) {
586 $entity->load('book');
587 $this->permissionService->buildJointPermissionsForEntity($entity->book);
594 * Alias method to update the book jointPermissions in the PermissionService.
597 public function buildJointPermissionsForBook(Book $book)
599 $this->permissionService->buildJointPermissionsForEntity($book);
603 * Format a name as a url slug.
607 protected function nameToSlug($name)
609 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
610 $slug = preg_replace('/\s{2,}/', ' ', $slug);
611 $slug = str_replace(' ', '-', $slug);
613 $slug = substr(md5(rand(1, 500)), 0, 5);
619 * Render the page for viewing, Parsing and performing features such as page transclusion.
621 * @param bool $ignorePermissions
622 * @return mixed|string
624 public function renderPage(Page $page, $ignorePermissions = false)
626 $content = $page->html;
627 if (!config('app.allow_content_scripts')) {
628 $content = $this->escapeScripts($content);
632 preg_match_all("/{{@\s?([0-9].*?)}}/", $content, $matches);
633 if (count($matches[0]) === 0) {
637 $topLevelTags = ['table', 'ul', 'ol'];
638 foreach ($matches[1] as $index => $includeId) {
639 $splitInclude = explode('#', $includeId, 2);
640 $pageId = intval($splitInclude[0]);
641 if (is_nan($pageId)) {
645 $matchedPage = $this->getById('page', $pageId, false, $ignorePermissions);
646 if ($matchedPage === null) {
647 $content = str_replace($matches[0][$index], '', $content);
651 if (count($splitInclude) === 1) {
652 $content = str_replace($matches[0][$index], $matchedPage->html, $content);
656 $doc = new DOMDocument();
657 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
658 $matchingElem = $doc->getElementById($splitInclude[1]);
659 if ($matchingElem === null) {
660 $content = str_replace($matches[0][$index], '', $content);
664 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
666 $innerContent .= $doc->saveHTML($matchingElem);
668 foreach ($matchingElem->childNodes as $childNode) {
669 $innerContent .= $doc->saveHTML($childNode);
672 $content = str_replace($matches[0][$index], trim($innerContent), $content);
679 * Escape script tags within HTML content.
680 * @param string $html
683 protected function escapeScripts(string $html)
685 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
687 preg_match_all($scriptSearchRegex, $html, $matches);
688 if (count($matches) === 0) {
692 foreach ($matches[0] as $match) {
693 $html = str_replace($match, htmlentities($match), $html);
699 * Search for image usage within page content.
700 * @param $imageString
703 public function searchForImage($imageString)
705 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
706 foreach ($pages as $page) {
707 $page->url = $page->getUrl();
711 return count($pages) > 0 ? $pages : false;
715 * Destroy a bookshelf instance
716 * @param \BookStack\Entities\Bookshelf $shelf
719 public function destroyBookshelf(Bookshelf $shelf)
721 $this->destroyEntityCommonRelations($shelf);
726 * Destroy the provided book and all its child entities.
727 * @param \BookStack\Entities\Book $book
728 * @throws NotifyException
731 public function destroyBook(Book $book)
733 foreach ($book->pages as $page) {
734 $this->destroyPage($page);
736 foreach ($book->chapters as $chapter) {
737 $this->destroyChapter($chapter);
739 $this->destroyEntityCommonRelations($book);
744 * Destroy a chapter and its relations.
745 * @param \BookStack\Entities\Chapter $chapter
748 public function destroyChapter(Chapter $chapter)
750 if (count($chapter->pages) > 0) {
751 foreach ($chapter->pages as $page) {
752 $page->chapter_id = 0;
756 $this->destroyEntityCommonRelations($chapter);
761 * Destroy a given page along with its dependencies.
763 * @throws NotifyException
766 public function destroyPage(Page $page)
768 // Check if set as custom homepage
769 $customHome = setting('app-homepage', '0:');
770 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
771 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
774 $this->destroyEntityCommonRelations($page);
776 // Delete Attached Files
777 $attachmentService = app(AttachmentService::class);
778 foreach ($page->attachments as $attachment) {
779 $attachmentService->deleteFile($attachment);
786 * Destroy or handle the common relations connected to an entity.
787 * @param \BookStack\Entities\Entity $entity
790 protected function destroyEntityCommonRelations(Entity $entity)
792 \Activity::removeEntity($entity);
793 $entity->views()->delete();
794 $entity->permissions()->delete();
795 $entity->tags()->delete();
796 $entity->comments()->delete();
797 $this->permissionService->deleteJointPermissionsForEntity($entity);
798 $this->searchService->deleteEntityTerms($entity);
802 * Copy the permissions of a bookshelf to all child books.
803 * Returns the number of books that had permissions updated.
804 * @param \BookStack\Entities\Bookshelf $bookshelf
808 public function copyBookshelfPermissions(Bookshelf $bookshelf)
810 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
811 $shelfBooks = $bookshelf->books()->get();
812 $updatedBookCount = 0;
814 foreach ($shelfBooks as $book) {
815 if (!userCan('restrictions-manage', $book)) {
818 $book->permissions()->delete();
819 $book->restricted = $bookshelf->restricted;
820 $book->permissions()->createMany($shelfPermissions);
822 $this->permissionService->buildJointPermissionsForEntity($book);
826 return $updatedBookCount;