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 all child objects of a book.
346 * Returns a sorted collection of Pages and Chapters.
347 * Loads the book slug onto child elements to prevent access database access for getting the slug.
348 * @param \BookStack\Entities\Book $book
349 * @param bool $filterDrafts
350 * @param bool $renderPages
353 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
355 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
360 foreach ($q as $index => $rawEntity) {
361 if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
362 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
364 $entities[$index]->html = $rawEntity->html;
365 $entities[$index]->html = $this->renderPage($entities[$index]);
367 } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
368 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
369 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
370 $parents[$key] = $entities[$index];
371 $parents[$key]->setAttribute('pages', collect());
373 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
374 $tree[] = $entities[$index];
376 $entities[$index]->book = $book;
379 foreach ($entities as $entity) {
380 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
383 $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
384 if (!isset($parents[$parentKey])) {
388 $chapter = $parents[$parentKey];
389 $chapter->pages->push($entity);
392 return collect($tree);
396 * Get the child items for a chapter sorted by priority but
397 * with draft items floated to the top.
398 * @param \BookStack\Entities\Chapter $chapter
399 * @return \Illuminate\Database\Eloquent\Collection|static[]
401 public function getChapterChildren(Chapter $chapter)
403 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
404 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
409 * Get the next sequential priority for a new child element in the given book.
410 * @param \BookStack\Entities\Book $book
413 public function getNewBookPriority(Book $book)
415 $lastElem = $this->getBookChildren($book)->pop();
416 return $lastElem ? $lastElem->priority + 1 : 0;
420 * Get a new priority for a new page to be added to the given chapter.
421 * @param \BookStack\Entities\Chapter $chapter
424 public function getNewChapterPriority(Chapter $chapter)
426 $lastPage = $chapter->pages('DESC')->first();
427 return $lastPage !== null ? $lastPage->priority + 1 : 0;
431 * Find a suitable slug for an entity.
432 * @param string $type
433 * @param string $name
434 * @param bool|integer $currentId
435 * @param bool|integer $bookId Only pass if type is not a book
438 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
440 $slug = $this->nameToSlug($name);
441 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
442 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
448 * Check if a slug already exists in the database.
449 * @param string $type
450 * @param string $slug
451 * @param bool|integer $currentId
452 * @param bool|integer $bookId
455 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
457 $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
458 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
459 $query = $query->where('book_id', '=', $bookId);
462 $query = $query->where('id', '!=', $currentId);
464 return $query->count() > 0;
468 * Updates entity restrictions from a request
469 * @param Request $request
470 * @param \BookStack\Entities\Entity $entity
473 public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
475 $entity->restricted = $request->get('restricted', '') === 'true';
476 $entity->permissions()->delete();
478 if ($request->filled('restrictions')) {
479 foreach ($request->get('restrictions') as $roleId => $restrictions) {
480 foreach ($restrictions as $action => $value) {
481 $entity->permissions()->create([
482 'role_id' => $roleId,
483 'action' => strtolower($action)
490 $this->permissionService->buildJointPermissionsForEntity($entity);
496 * Create a new entity from request input.
497 * Used for books and chapters.
498 * @param string $type
499 * @param array $input
500 * @param bool|Book $book
501 * @return \BookStack\Entities\Entity
503 public function createFromInput($type, $input = [], $book = false)
505 $isChapter = strtolower($type) === 'chapter';
506 $entityModel = $this->entityProvider->get($type)->newInstance($input);
507 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
508 $entityModel->created_by = user()->id;
509 $entityModel->updated_by = user()->id;
510 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
512 if (isset($input['tags'])) {
513 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
516 $this->permissionService->buildJointPermissionsForEntity($entityModel);
517 $this->searchService->indexEntity($entityModel);
522 * Update entity details from request input.
523 * Used for books and chapters
524 * @param string $type
525 * @param \BookStack\Entities\Entity $entityModel
526 * @param array $input
527 * @return \BookStack\Entities\Entity
529 public function updateFromInput($type, Entity $entityModel, $input = [])
531 if ($entityModel->name !== $input['name']) {
532 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
534 $entityModel->fill($input);
535 $entityModel->updated_by = user()->id;
536 $entityModel->save();
538 if (isset($input['tags'])) {
539 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
542 $this->permissionService->buildJointPermissionsForEntity($entityModel);
543 $this->searchService->indexEntity($entityModel);
548 * Sync the books assigned to a shelf from a comma-separated list
550 * @param \BookStack\Entities\Bookshelf $shelf
551 * @param string $books
553 public function updateShelfBooks(Bookshelf $shelf, string $books)
555 $ids = explode(',', $books);
557 // Check books exist and match ordering
558 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
560 foreach ($ids as $index => $id) {
561 if ($bookIds->contains($id)) {
562 $syncData[$id] = ['order' => $index];
566 $shelf->books()->sync($syncData);
570 * Change the book that an entity belongs to.
571 * @param string $type
572 * @param integer $newBookId
573 * @param Entity $entity
574 * @param bool $rebuildPermissions
575 * @return \BookStack\Entities\Entity
577 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
579 $entity->book_id = $newBookId;
580 // Update related activity
581 foreach ($entity->activity as $activity) {
582 $activity->book_id = $newBookId;
585 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
588 // Update all child pages if a chapter
589 if (strtolower($type) === 'chapter') {
590 foreach ($entity->pages as $page) {
591 $this->changeBook('page', $newBookId, $page, false);
595 // Update permissions if applicable
596 if ($rebuildPermissions) {
597 $entity->load('book');
598 $this->permissionService->buildJointPermissionsForEntity($entity->book);
605 * Alias method to update the book jointPermissions in the PermissionService.
608 public function buildJointPermissionsForBook(Book $book)
610 $this->permissionService->buildJointPermissionsForEntity($book);
614 * Format a name as a url slug.
618 protected function nameToSlug($name)
620 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
621 $slug = preg_replace('/\s{2,}/', ' ', $slug);
622 $slug = str_replace(' ', '-', $slug);
624 $slug = substr(md5(rand(1, 500)), 0, 5);
630 * Render the page for viewing
632 * @param bool $blankIncludes
635 public function renderPage(Page $page, bool $blankIncludes = false) : string
637 $content = $page->html;
639 if (!config('app.allow_content_scripts')) {
640 $content = $this->escapeScripts($content);
643 if ($blankIncludes) {
644 $content = $this->blankPageIncludes($content);
646 $content = $this->parsePageIncludes($content);
653 * Remove any page include tags within the given HTML.
654 * @param string $html
657 protected function blankPageIncludes(string $html) : string
659 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
663 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
664 * @param string $html
665 * @return mixed|string
667 protected function parsePageIncludes(string $html) : string
670 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
672 $topLevelTags = ['table', 'ul', 'ol'];
673 foreach ($matches[1] as $index => $includeId) {
674 $splitInclude = explode('#', $includeId, 2);
675 $pageId = intval($splitInclude[0]);
676 if (is_nan($pageId)) {
680 $matchedPage = $this->getById('page', $pageId);
681 if ($matchedPage === null) {
682 $html = str_replace($matches[0][$index], '', $html);
686 if (count($splitInclude) === 1) {
687 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
691 $doc = new DOMDocument();
692 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
693 $matchingElem = $doc->getElementById($splitInclude[1]);
694 if ($matchingElem === null) {
695 $html = str_replace($matches[0][$index], '', $html);
699 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
701 $innerContent .= $doc->saveHTML($matchingElem);
703 foreach ($matchingElem->childNodes as $childNode) {
704 $innerContent .= $doc->saveHTML($childNode);
707 $html = str_replace($matches[0][$index], trim($innerContent), $html);
714 * Escape script tags within HTML content.
715 * @param string $html
718 protected function escapeScripts(string $html) : string
720 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
722 preg_match_all($scriptSearchRegex, $html, $matches);
724 foreach ($matches[0] as $match) {
725 $html = str_replace($match, htmlentities($match), $html);
731 * Search for image usage within page content.
732 * @param $imageString
735 public function searchForImage($imageString)
737 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
738 foreach ($pages as $page) {
739 $page->url = $page->getUrl();
743 return count($pages) > 0 ? $pages : false;
747 * Destroy a bookshelf instance
748 * @param \BookStack\Entities\Bookshelf $shelf
751 public function destroyBookshelf(Bookshelf $shelf)
753 $this->destroyEntityCommonRelations($shelf);
758 * Destroy the provided book and all its child entities.
759 * @param \BookStack\Entities\Book $book
760 * @throws NotifyException
763 public function destroyBook(Book $book)
765 foreach ($book->pages as $page) {
766 $this->destroyPage($page);
768 foreach ($book->chapters as $chapter) {
769 $this->destroyChapter($chapter);
771 $this->destroyEntityCommonRelations($book);
776 * Destroy a chapter and its relations.
777 * @param \BookStack\Entities\Chapter $chapter
780 public function destroyChapter(Chapter $chapter)
782 if (count($chapter->pages) > 0) {
783 foreach ($chapter->pages as $page) {
784 $page->chapter_id = 0;
788 $this->destroyEntityCommonRelations($chapter);
793 * Destroy a given page along with its dependencies.
795 * @throws NotifyException
798 public function destroyPage(Page $page)
800 // Check if set as custom homepage
801 $customHome = setting('app-homepage', '0:');
802 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
803 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
806 $this->destroyEntityCommonRelations($page);
808 // Delete Attached Files
809 $attachmentService = app(AttachmentService::class);
810 foreach ($page->attachments as $attachment) {
811 $attachmentService->deleteFile($attachment);
818 * Destroy or handle the common relations connected to an entity.
819 * @param \BookStack\Entities\Entity $entity
822 protected function destroyEntityCommonRelations(Entity $entity)
824 \Activity::removeEntity($entity);
825 $entity->views()->delete();
826 $entity->permissions()->delete();
827 $entity->tags()->delete();
828 $entity->comments()->delete();
829 $this->permissionService->deleteJointPermissionsForEntity($entity);
830 $this->searchService->deleteEntityTerms($entity);
834 * Copy the permissions of a bookshelf to all child books.
835 * Returns the number of books that had permissions updated.
836 * @param \BookStack\Entities\Bookshelf $bookshelf
840 public function copyBookshelfPermissions(Bookshelf $bookshelf)
842 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
843 $shelfBooks = $bookshelf->books()->get();
844 $updatedBookCount = 0;
846 foreach ($shelfBooks as $book) {
847 if (!userCan('restrictions-manage', $book)) {
850 $book->permissions()->delete();
851 $book->restricted = $bookshelf->restricted;
852 $book->permissions()->createMany($shelfPermissions);
854 $this->permissionService->buildJointPermissionsForEntity($book);
858 return $updatedBookCount;