1 <?php namespace BookStack\Services;
4 use BookStack\Bookshelf;
7 use BookStack\EntityPermission;
8 use BookStack\JointPermission;
13 use Illuminate\Database\Connection;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Query\Builder as QueryBuilder;
16 use Illuminate\Support\Collection;
18 class PermissionService
21 protected $currentAction;
22 protected $isAdminUser;
23 protected $userRoles = false;
24 protected $currentUserModel = false;
33 protected $jointPermission;
35 protected $entityPermission;
37 protected $entityCache;
40 * PermissionService constructor.
41 * @param JointPermission $jointPermission
42 * @param EntityPermission $entityPermission
44 * @param Connection $db
45 * @param Bookshelf $bookshelf
47 * @param Chapter $chapter
50 public function __construct(
51 JointPermission $jointPermission,
52 EntityPermission $entityPermission,
61 $this->jointPermission = $jointPermission;
62 $this->entityPermission = $entityPermission;
64 $this->bookshelf = $bookshelf;
66 $this->chapter = $chapter;
71 * Set the database connection
72 * @param Connection $connection
74 public function setConnection(Connection $connection)
76 $this->db = $connection;
80 * Prepare the local entity cache and ensure it's empty
81 * @param Entity[] $entities
83 protected function readyEntityCache($entities = [])
85 $this->entityCache = [];
87 foreach ($entities as $entity) {
88 $type = $entity->getType();
89 if (!isset($this->entityCache[$type])) {
90 $this->entityCache[$type] = collect();
92 $this->entityCache[$type]->put($entity->id, $entity);
97 * Get a book via ID, Checks local cache
101 protected function getBook($bookId)
103 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
104 return $this->entityCache['book']->get($bookId);
107 $book = $this->book->find($bookId);
108 if ($book === null) {
116 * Get a chapter via ID, Checks local cache
120 protected function getChapter($chapterId)
122 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
123 return $this->entityCache['chapter']->get($chapterId);
126 $chapter = $this->chapter->find($chapterId);
127 if ($chapter === null) {
135 * Get the roles for the current user;
138 protected function getRoles()
140 if ($this->userRoles !== false) {
141 return $this->userRoles;
146 if (auth()->guest()) {
147 $roles[] = $this->role->getSystemRole('public')->id;
152 foreach ($this->currentUser()->roles as $role) {
153 $roles[] = $role->id;
159 * Re-generate all entity permission from scratch.
161 public function buildJointPermissions()
163 $this->jointPermission->truncate();
164 $this->readyEntityCache();
166 // Get all roles (Should be the most limited dimension)
167 $roles = $this->role->with('permissions')->get()->all();
169 // Chunk through all books
170 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
171 $this->buildJointPermissionsForBooks($books, $roles);
174 // Chunk through all bookshelves
175 $this->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
176 ->chunk(50, function ($shelves) use ($roles) {
177 $this->buildJointPermissionsForShelves($shelves, $roles);
182 * Get a query for fetching a book with it's children.
183 * @return QueryBuilder
185 protected function bookFetchQuery()
187 return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
188 $query->select(['id', 'restricted', 'created_by', 'book_id']);
189 }, 'pages' => function ($query) {
190 $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
195 * @param Collection $shelves
196 * @param array $roles
197 * @param bool $deleteOld
200 protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
203 $this->deleteManyJointPermissionsForEntities($shelves->all());
205 $this->createManyJointPermissions($shelves, $roles);
209 * Build joint permissions for an array of books
210 * @param Collection $books
211 * @param array $roles
212 * @param bool $deleteOld
215 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
217 $entities = clone $books;
219 /** @var Book $book */
220 foreach ($books->all() as $book) {
221 foreach ($book->getRelation('chapters') as $chapter) {
222 $entities->push($chapter);
224 foreach ($book->getRelation('pages') as $page) {
225 $entities->push($page);
230 $this->deleteManyJointPermissionsForEntities($entities->all());
232 $this->createManyJointPermissions($entities, $roles);
236 * Rebuild the entity jointPermissions for a particular entity.
237 * @param Entity $entity
240 public function buildJointPermissionsForEntity(Entity $entity)
242 $entities = [$entity];
243 if ($entity->isA('book')) {
244 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
245 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
250 $entities[] = $entity->book;
253 if ($entity->isA('page') && $entity->chapter_id) {
254 $entities[] = $entity->chapter;
257 if ($entity->isA('chapter')) {
258 foreach ($entity->pages as $page) {
263 $this->buildJointPermissionsForEntities(collect($entities));
267 * Rebuild the entity jointPermissions for a collection of entities.
268 * @param Collection $entities
271 public function buildJointPermissionsForEntities(Collection $entities)
273 $roles = $this->role->newQuery()->get();
274 $this->deleteManyJointPermissionsForEntities($entities->all());
275 $this->createManyJointPermissions($entities, $roles);
279 * Build the entity jointPermissions for a particular role.
282 public function buildJointPermissionForRole(Role $role)
285 $this->deleteManyJointPermissionsForRoles($roles);
287 // Chunk through all books
288 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
289 $this->buildJointPermissionsForBooks($books, $roles);
292 // Chunk through all bookshelves
293 $this->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
294 ->chunk(50, function ($shelves) use ($roles) {
295 $this->buildJointPermissionsForShelves($shelves, $roles);
300 * Delete the entity jointPermissions attached to a particular role.
303 public function deleteJointPermissionsForRole(Role $role)
305 $this->deleteManyJointPermissionsForRoles([$role]);
309 * Delete all of the entity jointPermissions for a list of entities.
310 * @param Role[] $roles
312 protected function deleteManyJointPermissionsForRoles($roles)
314 $roleIds = array_map(function ($role) {
317 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
321 * Delete the entity jointPermissions for a particular entity.
322 * @param Entity $entity
325 public function deleteJointPermissionsForEntity(Entity $entity)
327 $this->deleteManyJointPermissionsForEntities([$entity]);
331 * Delete all of the entity jointPermissions for a list of entities.
332 * @param Entity[] $entities
335 protected function deleteManyJointPermissionsForEntities($entities)
337 if (count($entities) === 0) {
341 $this->db->transaction(function () use ($entities) {
343 foreach (array_chunk($entities, 1000) as $entityChunk) {
344 $query = $this->db->table('joint_permissions');
345 foreach ($entityChunk as $entity) {
346 $query->orWhere(function (QueryBuilder $query) use ($entity) {
347 $query->where('entity_id', '=', $entity->id)
348 ->where('entity_type', '=', $entity->getMorphClass());
357 * Create & Save entity jointPermissions for many entities and jointPermissions.
358 * @param Collection $entities
359 * @param array $roles
362 protected function createManyJointPermissions($entities, $roles)
364 $this->readyEntityCache($entities);
365 $jointPermissions = [];
367 // Fetch Entity Permissions and create a mapping of entity restricted statuses
368 $entityRestrictedMap = [];
369 $permissionFetch = $this->entityPermission->newQuery();
370 foreach ($entities as $entity) {
371 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
372 $permissionFetch->orWhere(function ($query) use ($entity) {
373 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
376 $permissions = $permissionFetch->get();
378 // Create a mapping of explicit entity permissions
380 foreach ($permissions as $permission) {
381 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
382 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
383 $permissionMap[$key] = $isRestricted;
386 // Create a mapping of role permissions
387 $rolePermissionMap = [];
388 foreach ($roles as $role) {
389 foreach ($role->permissions as $permission) {
390 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
394 // Create Joint Permission Data
395 foreach ($entities as $entity) {
396 foreach ($roles as $role) {
397 foreach ($this->getActions($entity) as $action) {
398 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
403 $this->db->transaction(function () use ($jointPermissions) {
404 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
405 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
412 * Get the actions related to an entity.
413 * @param Entity $entity
416 protected function getActions(Entity $entity)
418 $baseActions = ['view', 'update', 'delete'];
419 if ($entity->isA('chapter') || $entity->isA('book')) {
420 $baseActions[] = 'page-create';
422 if ($entity->isA('book')) {
423 $baseActions[] = 'chapter-create';
429 * Create entity permission data for an entity and role
430 * for a particular action.
431 * @param Entity $entity
433 * @param string $action
434 * @param array $permissionMap
435 * @param array $rolePermissionMap
438 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
440 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
441 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
442 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
443 $explodedAction = explode('-', $action);
444 $restrictionAction = end($explodedAction);
446 if ($role->system_name === 'admin') {
447 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
450 if ($entity->restricted) {
451 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
452 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
455 if ($entity->isA('book') || $entity->isA('bookshelf')) {
456 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
459 // For chapters and pages, Check if explicit permissions are set on the Book.
460 $book = $this->getBook($entity->book_id);
461 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
462 $hasPermissiveAccessToParents = !$book->restricted;
464 // For pages with a chapter, Check if explicit permissions are set on the Chapter
465 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
466 $chapter = $this->getChapter($entity->chapter_id);
467 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
468 if ($chapter->restricted) {
469 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
473 return $this->createJointPermissionDataArray(
477 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
478 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
483 * Check for an active restriction in an entity map.
485 * @param Entity $entity
490 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
492 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
493 return isset($entityMap[$key]) ? $entityMap[$key] : false;
497 * Create an array of data with the information of an entity jointPermissions.
498 * Used to build data for bulk insertion.
499 * @param Entity $entity
502 * @param $permissionAll
503 * @param $permissionOwn
506 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
509 'role_id' => $role->getRawAttribute('id'),
510 'entity_id' => $entity->getRawAttribute('id'),
511 'entity_type' => $entity->getMorphClass(),
513 'has_permission' => $permissionAll,
514 'has_permission_own' => $permissionOwn,
515 'created_by' => $entity->getRawAttribute('created_by')
520 * Checks if an entity has a restriction set upon it.
521 * @param Ownable $ownable
525 public function checkOwnableUserAccess(Ownable $ownable, $permission)
527 $explodedPermission = explode('-', $permission);
529 $baseQuery = $ownable->where('id', '=', $ownable->id);
530 $action = end($explodedPermission);
531 $this->currentAction = $action;
533 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
535 // Handle non entity specific jointPermissions
536 if (in_array($explodedPermission[0], $nonJointPermissions)) {
537 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
538 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
539 $this->currentAction = 'view';
540 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
541 return ($allPermission || ($isOwner && $ownPermission));
544 // Handle abnormal create jointPermissions
545 if ($action === 'create') {
546 $this->currentAction = $permission;
549 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
555 * Check if an entity has restrictions set on itself or its
557 * @param Entity $entity
561 public function checkIfRestrictionsSet(Entity $entity, $action)
563 $this->currentAction = $action;
564 if ($entity->isA('page')) {
565 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
566 } elseif ($entity->isA('chapter')) {
567 return $entity->restricted || $entity->book->restricted;
568 } elseif ($entity->isA('book')) {
569 return $entity->restricted;
574 * The general query filter to remove all entities
575 * that the current user does not have access to.
579 protected function entityRestrictionQuery($query)
581 $q = $query->where(function ($parentQuery) {
582 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
583 $permissionQuery->whereIn('role_id', $this->getRoles())
584 ->where('action', '=', $this->currentAction)
585 ->where(function ($query) {
586 $query->where('has_permission', '=', true)
587 ->orWhere(function ($query) {
588 $query->where('has_permission_own', '=', true)
589 ->where('created_by', '=', $this->currentUser()->id);
599 * Get the children of a book in an efficient single query, Filtered by the permission system.
600 * @param integer $book_id
601 * @param bool $filterDrafts
602 * @param bool $fetchPageContent
603 * @return QueryBuilder
605 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
607 $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
608 $query->where('draft', '=', 0);
609 if (!$filterDrafts) {
610 $query->orWhere(function ($query) {
611 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
615 $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
616 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
617 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
619 // Add joint permission filter
620 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
621 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
622 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
623 ->where(function ($query) {
624 $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
625 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
628 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
630 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
636 * Add restrictions for a generic entity
637 * @param string $entityType
638 * @param Builder|Entity $query
639 * @param string $action
642 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
644 if (strtolower($entityType) === 'page') {
645 // Prevent drafts being visible to others.
646 $query = $query->where(function ($query) {
647 $query->where('draft', '=', false);
648 if ($this->currentUser()) {
649 $query->orWhere(function ($query) {
650 $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
656 $this->currentAction = $action;
657 return $this->entityRestrictionQuery($query);
661 * Filter items that have entities set as a polymorphic relation.
663 * @param string $tableName
664 * @param string $entityIdColumn
665 * @param string $entityTypeColumn
666 * @param string $action
669 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
672 $this->currentAction = $action;
673 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
675 $q = $query->where(function ($query) use ($tableDetails) {
676 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
677 $permissionQuery->select('id')->from('joint_permissions')
678 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
679 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
680 ->where('action', '=', $this->currentAction)
681 ->whereIn('role_id', $this->getRoles())
682 ->where(function ($query) {
683 $query->where('has_permission', '=', true)->orWhere(function ($query) {
684 $query->where('has_permission_own', '=', true)
685 ->where('created_by', '=', $this->currentUser()->id);
695 * Filters pages that are a direct relation to another item.
698 * @param $entityIdColumn
701 public function filterRelatedPages($query, $tableName, $entityIdColumn)
703 $this->currentAction = 'view';
704 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
706 $q = $query->where(function ($query) use ($tableDetails) {
707 $query->where(function ($query) use (&$tableDetails) {
708 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
709 $permissionQuery->select('id')->from('joint_permissions')
710 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
711 ->where('entity_type', '=', 'Bookstack\\Page')
712 ->where('action', '=', $this->currentAction)
713 ->whereIn('role_id', $this->getRoles())
714 ->where(function ($query) {
715 $query->where('has_permission', '=', true)->orWhere(function ($query) {
716 $query->where('has_permission_own', '=', true)
717 ->where('created_by', '=', $this->currentUser()->id);
721 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
728 * Get the current user
731 private function currentUser()
733 if ($this->currentUserModel === false) {
734 $this->currentUserModel = user();
737 return $this->currentUserModel;
741 * Clean the cached user elements.
743 private function clean()
745 $this->currentUserModel = false;
746 $this->userRoles = false;
747 $this->isAdminUser = null;