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\Http\Request;
19 use Illuminate\Support\Collection;
27 protected $entityProvider;
30 * @var PermissionService
32 protected $permissionService;
37 protected $viewService;
47 protected $searchService;
50 * EntityRepo constructor.
51 * @param EntityProvider $entityProvider
52 * @param ViewService $viewService
53 * @param PermissionService $permissionService
54 * @param TagRepo $tagRepo
55 * @param SearchService $searchService
57 public function __construct(
58 EntityProvider $entityProvider,
59 ViewService $viewService,
60 PermissionService $permissionService,
62 SearchService $searchService
64 $this->entityProvider = $entityProvider;
65 $this->viewService = $viewService;
66 $this->permissionService = $permissionService;
67 $this->tagRepo = $tagRepo;
68 $this->searchService = $searchService;
72 * Base query for searching entities via permission system
74 * @param bool $allowDrafts
75 * @param string $permission
76 * @return \Illuminate\Database\Query\Builder
78 protected function entityQuery($type, $allowDrafts = false, $permission = 'view')
80 $q = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type), $permission);
81 if (strtolower($type) === 'page' && !$allowDrafts) {
82 $q = $q->where('draft', '=', false);
88 * Check if an entity with the given id exists.
93 public function exists($type, $id)
95 return $this->entityQuery($type)->where('id', '=', $id)->exists();
100 * @param string $type
102 * @param bool $allowDrafts
103 * @param bool $ignorePermissions
104 * @return \BookStack\Entities\Entity
106 public function getById($type, $id, $allowDrafts = false, $ignorePermissions = false)
108 $query = $this->entityQuery($type, $allowDrafts);
110 if ($ignorePermissions) {
111 $query = $this->entityProvider->get($type)->newQuery();
114 return $query->find($id);
118 * @param string $type
120 * @param bool $allowDrafts
121 * @param bool $ignorePermissions
122 * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Collection
124 public function getManyById($type, $ids, $allowDrafts = false, $ignorePermissions = false)
126 $query = $this->entityQuery($type, $allowDrafts);
128 if ($ignorePermissions) {
129 $query = $this->entityProvider->get($type)->newQuery();
132 return $query->whereIn('id', $ids)->get();
136 * Get an entity by its url slug.
137 * @param string $type
138 * @param string $slug
139 * @param string|bool $bookSlug
140 * @return \BookStack\Entities\Entity
141 * @throws NotFoundException
143 public function getBySlug($type, $slug, $bookSlug = false)
145 $q = $this->entityQuery($type)->where('slug', '=', $slug);
147 if (strtolower($type) === 'chapter' || strtolower($type) === 'page') {
148 $q = $q->where('book_id', '=', function ($query) use ($bookSlug) {
150 ->from($this->entityProvider->book->getTable())
151 ->where('slug', '=', $bookSlug)->limit(1);
154 $entity = $q->first();
155 if ($entity === null) {
156 throw new NotFoundException(trans('errors.' . strtolower($type) . '_not_found'));
163 * Get all entities of a type with the given permission, limited by count unless count is false.
164 * @param string $type
165 * @param integer|bool $count
166 * @param string $permission
169 public function getAll($type, $count = 20, $permission = 'view')
171 $q = $this->entityQuery($type, false, $permission)->orderBy('name', 'asc');
172 if ($count !== false) {
173 $q = $q->take($count);
179 * Get all entities in a paginated format
182 * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
184 public function getAllPaginated($type, $count = 10)
186 return $this->entityQuery($type)->orderBy('name', 'asc')->paginate($count);
190 * Get the most recently created entities of the given type.
191 * @param string $type
194 * @param bool|callable $additionalQuery
197 public function getRecentlyCreated($type, $count = 20, $page = 0, $additionalQuery = false)
199 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
200 ->orderBy('created_at', 'desc');
201 if (strtolower($type) === 'page') {
202 $query = $query->where('draft', '=', false);
204 if ($additionalQuery !== false && is_callable($additionalQuery)) {
205 $additionalQuery($query);
207 return $query->skip($page * $count)->take($count)->get();
211 * Get the most recently updated entities of the given type.
212 * @param string $type
215 * @param bool|callable $additionalQuery
218 public function getRecentlyUpdated($type, $count = 20, $page = 0, $additionalQuery = false)
220 $query = $this->permissionService->enforceEntityRestrictions($type, $this->entityProvider->get($type))
221 ->orderBy('updated_at', 'desc');
222 if (strtolower($type) === 'page') {
223 $query = $query->where('draft', '=', false);
225 if ($additionalQuery !== false && is_callable($additionalQuery)) {
226 $additionalQuery($query);
228 return $query->skip($page * $count)->take($count)->get();
232 * Get the most recently viewed entities.
233 * @param string|bool $type
238 public function getRecentlyViewed($type, $count = 10, $page = 0)
240 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
241 return $this->viewService->getUserRecentlyViewed($count, $page, $filter);
245 * Get the latest pages added to the system with pagination.
246 * @param string $type
250 public function getRecentlyCreatedPaginated($type, $count = 20)
252 return $this->entityQuery($type)->orderBy('created_at', 'desc')->paginate($count);
256 * Get the latest pages added to the system with pagination.
257 * @param string $type
261 public function getRecentlyUpdatedPaginated($type, $count = 20)
263 return $this->entityQuery($type)->orderBy('updated_at', 'desc')->paginate($count);
267 * Get the most popular entities base on all views.
268 * @param string|bool $type
273 public function getPopular($type, $count = 10, $page = 0)
275 $filter = is_bool($type) ? false : $this->entityProvider->get($type);
276 return $this->viewService->getPopular($count, $page, $filter);
280 * Get draft pages owned by the current user.
285 public function getUserDraftPages($count = 20, $page = 0)
287 return $this->entityProvider->page->where('draft', '=', true)
288 ->where('created_by', '=', user()->id)
289 ->orderBy('updated_at', 'desc')
290 ->skip($count * $page)->take($count)->get();
294 * Get the number of entities the given user has created.
295 * @param string $type
299 public function getUserTotalCreated(string $type, User $user)
301 return $this->entityProvider->get($type)
302 ->where('created_by', '=', $user->id)->count();
306 * Get the child items for a chapter sorted by priority but
307 * with draft items floated to the top.
308 * @param \BookStack\Entities\Bookshelf $bookshelf
309 * @return \Illuminate\Database\Eloquent\Collection|static[]
311 public function getBookshelfChildren(Bookshelf $bookshelf)
313 return $this->permissionService->enforceEntityRestrictions('book', $bookshelf->books())->get();
317 * Get all child objects of a book.
318 * Returns a sorted collection of Pages and Chapters.
319 * Loads the book slug onto child elements to prevent access database access for getting the slug.
320 * @param \BookStack\Entities\Book $book
321 * @param bool $filterDrafts
322 * @param bool $renderPages
325 public function getBookChildren(Book $book, $filterDrafts = false, $renderPages = false)
327 $q = $this->permissionService->bookChildrenQuery($book->id, $filterDrafts, $renderPages)->get();
332 foreach ($q as $index => $rawEntity) {
333 if ($rawEntity->entity_type === $this->entityProvider->page->getMorphClass()) {
334 $entities[$index] = $this->entityProvider->page->newFromBuilder($rawEntity);
336 $entities[$index]->html = $rawEntity->html;
337 $entities[$index]->html = $this->renderPage($entities[$index]);
339 } else if ($rawEntity->entity_type === $this->entityProvider->chapter->getMorphClass()) {
340 $entities[$index] = $this->entityProvider->chapter->newFromBuilder($rawEntity);
341 $key = $entities[$index]->entity_type . ':' . $entities[$index]->id;
342 $parents[$key] = $entities[$index];
343 $parents[$key]->setAttribute('pages', collect());
345 if ($entities[$index]->chapter_id === 0 || $entities[$index]->chapter_id === '0') {
346 $tree[] = $entities[$index];
348 $entities[$index]->book = $book;
351 foreach ($entities as $entity) {
352 if ($entity->chapter_id === 0 || $entity->chapter_id === '0') {
355 $parentKey = $this->entityProvider->chapter->getMorphClass() . ':' . $entity->chapter_id;
356 if (!isset($parents[$parentKey])) {
360 $chapter = $parents[$parentKey];
361 $chapter->pages->push($entity);
364 return collect($tree);
368 * Get the child items for a chapter sorted by priority but
369 * with draft items floated to the top.
370 * @param \BookStack\Entities\Chapter $chapter
371 * @return \Illuminate\Database\Eloquent\Collection|static[]
373 public function getChapterChildren(Chapter $chapter)
375 return $this->permissionService->enforceEntityRestrictions('page', $chapter->pages())
376 ->orderBy('draft', 'DESC')->orderBy('priority', 'ASC')->get();
381 * Get the next sequential priority for a new child element in the given book.
382 * @param \BookStack\Entities\Book $book
385 public function getNewBookPriority(Book $book)
387 $lastElem = $this->getBookChildren($book)->pop();
388 return $lastElem ? $lastElem->priority + 1 : 0;
392 * Get a new priority for a new page to be added to the given chapter.
393 * @param \BookStack\Entities\Chapter $chapter
396 public function getNewChapterPriority(Chapter $chapter)
398 $lastPage = $chapter->pages('DESC')->first();
399 return $lastPage !== null ? $lastPage->priority + 1 : 0;
403 * Find a suitable slug for an entity.
404 * @param string $type
405 * @param string $name
406 * @param bool|integer $currentId
407 * @param bool|integer $bookId Only pass if type is not a book
410 public function findSuitableSlug($type, $name, $currentId = false, $bookId = false)
412 $slug = $this->nameToSlug($name);
413 while ($this->slugExists($type, $slug, $currentId, $bookId)) {
414 $slug .= '-' . substr(md5(rand(1, 500)), 0, 3);
420 * Check if a slug already exists in the database.
421 * @param string $type
422 * @param string $slug
423 * @param bool|integer $currentId
424 * @param bool|integer $bookId
427 protected function slugExists($type, $slug, $currentId = false, $bookId = false)
429 $query = $this->entityProvider->get($type)->where('slug', '=', $slug);
430 if (strtolower($type) === 'page' || strtolower($type) === 'chapter') {
431 $query = $query->where('book_id', '=', $bookId);
434 $query = $query->where('id', '!=', $currentId);
436 return $query->count() > 0;
440 * Updates entity restrictions from a request
441 * @param Request $request
442 * @param \BookStack\Entities\Entity $entity
445 public function updateEntityPermissionsFromRequest(Request $request, Entity $entity)
447 $entity->restricted = $request->get('restricted', '') === 'true';
448 $entity->permissions()->delete();
450 if ($request->filled('restrictions')) {
451 foreach ($request->get('restrictions') as $roleId => $restrictions) {
452 foreach ($restrictions as $action => $value) {
453 $entity->permissions()->create([
454 'role_id' => $roleId,
455 'action' => strtolower($action)
462 $this->permissionService->buildJointPermissionsForEntity($entity);
468 * Create a new entity from request input.
469 * Used for books and chapters.
470 * @param string $type
471 * @param array $input
472 * @param bool|Book $book
473 * @return \BookStack\Entities\Entity
475 public function createFromInput($type, $input = [], $book = false)
477 $isChapter = strtolower($type) === 'chapter';
478 $entityModel = $this->entityProvider->get($type)->newInstance($input);
479 $entityModel->slug = $this->findSuitableSlug($type, $entityModel->name, false, $isChapter ? $book->id : false);
480 $entityModel->created_by = user()->id;
481 $entityModel->updated_by = user()->id;
482 $isChapter ? $book->chapters()->save($entityModel) : $entityModel->save();
484 if (isset($input['tags'])) {
485 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
488 $this->permissionService->buildJointPermissionsForEntity($entityModel);
489 $this->searchService->indexEntity($entityModel);
494 * Update entity details from request input.
495 * Used for books and chapters
496 * @param string $type
497 * @param \BookStack\Entities\Entity $entityModel
498 * @param array $input
499 * @return \BookStack\Entities\Entity
501 public function updateFromInput($type, Entity $entityModel, $input = [])
503 if ($entityModel->name !== $input['name']) {
504 $entityModel->slug = $this->findSuitableSlug($type, $input['name'], $entityModel->id);
506 $entityModel->fill($input);
507 $entityModel->updated_by = user()->id;
508 $entityModel->save();
510 if (isset($input['tags'])) {
511 $this->tagRepo->saveTagsToEntity($entityModel, $input['tags']);
514 $this->permissionService->buildJointPermissionsForEntity($entityModel);
515 $this->searchService->indexEntity($entityModel);
520 * Sync the books assigned to a shelf from a comma-separated list
522 * @param \BookStack\Entities\Bookshelf $shelf
523 * @param string $books
525 public function updateShelfBooks(Bookshelf $shelf, string $books)
527 $ids = explode(',', $books);
529 // Check books exist and match ordering
530 $bookIds = $this->entityQuery('book')->whereIn('id', $ids)->get(['id'])->pluck('id');
532 foreach ($ids as $index => $id) {
533 if ($bookIds->contains($id)) {
534 $syncData[$id] = ['order' => $index];
538 $shelf->books()->sync($syncData);
542 * Change the book that an entity belongs to.
543 * @param string $type
544 * @param integer $newBookId
545 * @param Entity $entity
546 * @param bool $rebuildPermissions
547 * @return \BookStack\Entities\Entity
549 public function changeBook($type, $newBookId, Entity $entity, $rebuildPermissions = false)
551 $entity->book_id = $newBookId;
552 // Update related activity
553 foreach ($entity->activity as $activity) {
554 $activity->book_id = $newBookId;
557 $entity->slug = $this->findSuitableSlug($type, $entity->name, $entity->id, $newBookId);
560 // Update all child pages if a chapter
561 if (strtolower($type) === 'chapter') {
562 foreach ($entity->pages as $page) {
563 $this->changeBook('page', $newBookId, $page, false);
567 // Update permissions if applicable
568 if ($rebuildPermissions) {
569 $entity->load('book');
570 $this->permissionService->buildJointPermissionsForEntity($entity->book);
577 * Alias method to update the book jointPermissions in the PermissionService.
580 public function buildJointPermissionsForBook(Book $book)
582 $this->permissionService->buildJointPermissionsForEntity($book);
586 * Format a name as a url slug.
590 protected function nameToSlug($name)
592 $slug = preg_replace('/[\+\/\\\?\@\}\{\.\,\=\[\]\#\&\!\*\'\;\:\$\%]/', '', mb_strtolower($name));
593 $slug = preg_replace('/\s{2,}/', ' ', $slug);
594 $slug = str_replace(' ', '-', $slug);
596 $slug = substr(md5(rand(1, 500)), 0, 5);
602 * Render the page for viewing
604 * @param bool $blankIncludes
607 public function renderPage(Page $page, bool $blankIncludes = false) : string
609 $content = $page->html;
611 if (!config('app.allow_content_scripts')) {
612 $content = $this->escapeScripts($content);
615 if ($blankIncludes) {
616 $content = $this->blankPageIncludes($content);
618 $content = $this->parsePageIncludes($content);
625 * Remove any page include tags within the given HTML.
626 * @param string $html
629 protected function blankPageIncludes(string $html) : string
631 return preg_replace("/{{@\s?([0-9].*?)}}/", '', $html);
635 * Parse any include tags "{{@<page_id>#section}}" to be part of the page.
636 * @param string $html
637 * @return mixed|string
639 protected function parsePageIncludes(string $html) : string
642 preg_match_all("/{{@\s?([0-9].*?)}}/", $html, $matches);
644 $topLevelTags = ['table', 'ul', 'ol'];
645 foreach ($matches[1] as $index => $includeId) {
646 $splitInclude = explode('#', $includeId, 2);
647 $pageId = intval($splitInclude[0]);
648 if (is_nan($pageId)) {
652 $matchedPage = $this->getById('page', $pageId);
653 if ($matchedPage === null) {
654 $html = str_replace($matches[0][$index], '', $html);
658 if (count($splitInclude) === 1) {
659 $html = str_replace($matches[0][$index], $matchedPage->html, $html);
663 $doc = new DOMDocument();
664 $doc->loadHTML(mb_convert_encoding('<body>'.$matchedPage->html.'</body>', 'HTML-ENTITIES', 'UTF-8'));
665 $matchingElem = $doc->getElementById($splitInclude[1]);
666 if ($matchingElem === null) {
667 $html = str_replace($matches[0][$index], '', $html);
671 $isTopLevel = in_array(strtolower($matchingElem->nodeName), $topLevelTags);
673 $innerContent .= $doc->saveHTML($matchingElem);
675 foreach ($matchingElem->childNodes as $childNode) {
676 $innerContent .= $doc->saveHTML($childNode);
679 $html = str_replace($matches[0][$index], trim($innerContent), $html);
686 * Escape script tags within HTML content.
687 * @param string $html
690 protected function escapeScripts(string $html) : string
692 $scriptSearchRegex = '/<script.*?>.*?<\/script>/ms';
694 preg_match_all($scriptSearchRegex, $html, $matches);
696 foreach ($matches[0] as $match) {
697 $html = str_replace($match, htmlentities($match), $html);
703 * Search for image usage within page content.
704 * @param $imageString
707 public function searchForImage($imageString)
709 $pages = $this->entityQuery('page')->where('html', 'like', '%' . $imageString . '%')->get();
710 foreach ($pages as $page) {
711 $page->url = $page->getUrl();
715 return count($pages) > 0 ? $pages : false;
719 * Destroy a bookshelf instance
720 * @param \BookStack\Entities\Bookshelf $shelf
723 public function destroyBookshelf(Bookshelf $shelf)
725 $this->destroyEntityCommonRelations($shelf);
730 * Destroy the provided book and all its child entities.
731 * @param \BookStack\Entities\Book $book
732 * @throws NotifyException
735 public function destroyBook(Book $book)
737 foreach ($book->pages as $page) {
738 $this->destroyPage($page);
740 foreach ($book->chapters as $chapter) {
741 $this->destroyChapter($chapter);
743 $this->destroyEntityCommonRelations($book);
748 * Destroy a chapter and its relations.
749 * @param \BookStack\Entities\Chapter $chapter
752 public function destroyChapter(Chapter $chapter)
754 if (count($chapter->pages) > 0) {
755 foreach ($chapter->pages as $page) {
756 $page->chapter_id = 0;
760 $this->destroyEntityCommonRelations($chapter);
765 * Destroy a given page along with its dependencies.
767 * @throws NotifyException
770 public function destroyPage(Page $page)
772 // Check if set as custom homepage
773 $customHome = setting('app-homepage', '0:');
774 if (intval($page->id) === intval(explode(':', $customHome)[0])) {
775 throw new NotifyException(trans('errors.page_custom_home_deletion'), $page->getUrl());
778 $this->destroyEntityCommonRelations($page);
780 // Delete Attached Files
781 $attachmentService = app(AttachmentService::class);
782 foreach ($page->attachments as $attachment) {
783 $attachmentService->deleteFile($attachment);
790 * Destroy or handle the common relations connected to an entity.
791 * @param \BookStack\Entities\Entity $entity
794 protected function destroyEntityCommonRelations(Entity $entity)
796 \Activity::removeEntity($entity);
797 $entity->views()->delete();
798 $entity->permissions()->delete();
799 $entity->tags()->delete();
800 $entity->comments()->delete();
801 $this->permissionService->deleteJointPermissionsForEntity($entity);
802 $this->searchService->deleteEntityTerms($entity);
806 * Copy the permissions of a bookshelf to all child books.
807 * Returns the number of books that had permissions updated.
808 * @param \BookStack\Entities\Bookshelf $bookshelf
812 public function copyBookshelfPermissions(Bookshelf $bookshelf)
814 $shelfPermissions = $bookshelf->permissions()->get(['role_id', 'action'])->toArray();
815 $shelfBooks = $bookshelf->books()->get();
816 $updatedBookCount = 0;
818 foreach ($shelfBooks as $book) {
819 if (!userCan('restrictions-manage', $book)) {
822 $book->permissions()->delete();
823 $book->restricted = $bookshelf->restricted;
824 $book->permissions()->createMany($shelfPermissions);
826 $this->permissionService->buildJointPermissionsForEntity($book);
830 return $updatedBookCount;