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, EntityPermission $entityPermission, Role $role, Connection $db,
52 Bookshelf $bookshelf, Book $book, Chapter $chapter, Page $page
56 $this->jointPermission = $jointPermission;
57 $this->entityPermission = $entityPermission;
59 $this->bookshelf = $bookshelf;
61 $this->chapter = $chapter;
66 * Set the database connection
67 * @param Connection $connection
69 public function setConnection(Connection $connection)
71 $this->db = $connection;
75 * Prepare the local entity cache and ensure it's empty
76 * @param Entity[] $entities
78 protected function readyEntityCache($entities = [])
80 $this->entityCache = [];
82 foreach ($entities as $entity) {
83 $type = $entity->getType();
84 if (!isset($this->entityCache[$type])) {
85 $this->entityCache[$type] = collect();
87 $this->entityCache[$type]->put($entity->id, $entity);
92 * Get a book via ID, Checks local cache
96 protected function getBook($bookId)
98 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
99 return $this->entityCache['book']->get($bookId);
102 $book = $this->book->find($bookId);
103 if ($book === null) {
111 * Get a chapter via ID, Checks local cache
115 protected function getChapter($chapterId)
117 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
118 return $this->entityCache['chapter']->get($chapterId);
121 $chapter = $this->chapter->find($chapterId);
122 if ($chapter === null) {
130 * Get the roles for the current user;
133 protected function getRoles()
135 if ($this->userRoles !== false) {
136 return $this->userRoles;
141 if (auth()->guest()) {
142 $roles[] = $this->role->getSystemRole('public')->id;
147 foreach ($this->currentUser()->roles as $role) {
148 $roles[] = $role->id;
154 * Re-generate all entity permission from scratch.
156 public function buildJointPermissions()
158 $this->jointPermission->truncate();
159 $this->readyEntityCache();
161 // Get all roles (Should be the most limited dimension)
162 $roles = $this->role->with('permissions')->get()->all();
164 // Chunk through all books
165 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
166 $this->buildJointPermissionsForBooks($books, $roles);
169 // Chunk through all bookshelves
170 $this->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
171 ->chunk(50, function ($shelves) use ($roles) {
172 $this->buildJointPermissionsForShelves($shelves, $roles);
177 * Get a query for fetching a book with it's children.
178 * @return QueryBuilder
180 protected function bookFetchQuery()
182 return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
183 $query->select(['id', 'restricted', 'created_by', 'book_id']);
184 }, 'pages' => function ($query) {
185 $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
190 * @param Collection $shelves
191 * @param array $roles
192 * @param bool $deleteOld
195 protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
198 $this->deleteManyJointPermissionsForEntities($shelves->all());
200 $this->createManyJointPermissions($shelves, $roles);
204 * Build joint permissions for an array of books
205 * @param Collection $books
206 * @param array $roles
207 * @param bool $deleteOld
210 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
212 $entities = clone $books;
214 /** @var Book $book */
215 foreach ($books->all() as $book) {
216 foreach ($book->getRelation('chapters') as $chapter) {
217 $entities->push($chapter);
219 foreach ($book->getRelation('pages') as $page) {
220 $entities->push($page);
225 $this->deleteManyJointPermissionsForEntities($entities->all());
227 $this->createManyJointPermissions($entities, $roles);
231 * Rebuild the entity jointPermissions for a particular entity.
232 * @param Entity $entity
235 public function buildJointPermissionsForEntity(Entity $entity)
237 $entities = [$entity];
238 if ($entity->isA('book')) {
239 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
240 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
245 $entities[] = $entity->book;
248 if ($entity->isA('page') && $entity->chapter_id) {
249 $entities[] = $entity->chapter;
252 if ($entity->isA('chapter')) {
253 foreach ($entity->pages as $page) {
258 $this->buildJointPermissionsForEntities(collect($entities));
262 * Rebuild the entity jointPermissions for a collection of entities.
263 * @param Collection $entities
266 public function buildJointPermissionsForEntities(Collection $entities)
268 $roles = $this->role->newQuery()->get();
269 $this->deleteManyJointPermissionsForEntities($entities->all());
270 $this->createManyJointPermissions($entities, $roles);
274 * Build the entity jointPermissions for a particular role.
277 public function buildJointPermissionForRole(Role $role)
280 $this->deleteManyJointPermissionsForRoles($roles);
282 // Chunk through all books
283 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
284 $this->buildJointPermissionsForBooks($books, $roles);
287 // Chunk through all bookshelves
288 $this->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
289 ->chunk(50, function ($shelves) use ($roles) {
290 $this->buildJointPermissionsForShelves($shelves, $roles);
295 * Delete the entity jointPermissions attached to a particular role.
298 public function deleteJointPermissionsForRole(Role $role)
300 $this->deleteManyJointPermissionsForRoles([$role]);
304 * Delete all of the entity jointPermissions for a list of entities.
305 * @param Role[] $roles
307 protected function deleteManyJointPermissionsForRoles($roles)
309 $roleIds = array_map(function ($role) {
312 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
316 * Delete the entity jointPermissions for a particular entity.
317 * @param Entity $entity
320 public function deleteJointPermissionsForEntity(Entity $entity)
322 $this->deleteManyJointPermissionsForEntities([$entity]);
326 * Delete all of the entity jointPermissions for a list of entities.
327 * @param Entity[] $entities
330 protected function deleteManyJointPermissionsForEntities($entities)
332 if (count($entities) === 0) {
336 $this->db->transaction(function () use ($entities) {
338 foreach (array_chunk($entities, 1000) as $entityChunk) {
339 $query = $this->db->table('joint_permissions');
340 foreach ($entityChunk as $entity) {
341 $query->orWhere(function (QueryBuilder $query) use ($entity) {
342 $query->where('entity_id', '=', $entity->id)
343 ->where('entity_type', '=', $entity->getMorphClass());
352 * Create & Save entity jointPermissions for many entities and jointPermissions.
353 * @param Collection $entities
354 * @param array $roles
357 protected function createManyJointPermissions($entities, $roles)
359 $this->readyEntityCache($entities);
360 $jointPermissions = [];
362 // Fetch Entity Permissions and create a mapping of entity restricted statuses
363 $entityRestrictedMap = [];
364 $permissionFetch = $this->entityPermission->newQuery();
365 foreach ($entities as $entity) {
366 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
367 $permissionFetch->orWhere(function ($query) use ($entity) {
368 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
371 $permissions = $permissionFetch->get();
373 // Create a mapping of explicit entity permissions
375 foreach ($permissions as $permission) {
376 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
377 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
378 $permissionMap[$key] = $isRestricted;
381 // Create a mapping of role permissions
382 $rolePermissionMap = [];
383 foreach ($roles as $role) {
384 foreach ($role->permissions as $permission) {
385 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
389 // Create Joint Permission Data
390 foreach ($entities as $entity) {
391 foreach ($roles as $role) {
392 foreach ($this->getActions($entity) as $action) {
393 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
398 $this->db->transaction(function () use ($jointPermissions) {
399 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
400 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
407 * Get the actions related to an entity.
408 * @param Entity $entity
411 protected function getActions(Entity $entity)
413 $baseActions = ['view', 'update', 'delete'];
414 if ($entity->isA('chapter') || $entity->isA('book')) {
415 $baseActions[] = 'page-create';
417 if ($entity->isA('book')) {
418 $baseActions[] = 'chapter-create';
424 * Create entity permission data for an entity and role
425 * for a particular action.
426 * @param Entity $entity
428 * @param string $action
429 * @param array $permissionMap
430 * @param array $rolePermissionMap
433 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
435 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
436 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
437 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
438 $explodedAction = explode('-', $action);
439 $restrictionAction = end($explodedAction);
441 if ($role->system_name === 'admin') {
442 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
445 if ($entity->restricted) {
446 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
447 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
450 if ($entity->isA('book') || $entity->isA('bookshelf')) {
451 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
454 // For chapters and pages, Check if explicit permissions are set on the Book.
455 $book = $this->getBook($entity->book_id);
456 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
457 $hasPermissiveAccessToParents = !$book->restricted;
459 // For pages with a chapter, Check if explicit permissions are set on the Chapter
460 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
461 $chapter = $this->getChapter($entity->chapter_id);
462 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
463 if ($chapter->restricted) {
464 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
468 return $this->createJointPermissionDataArray(
472 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
473 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
478 * Check for an active restriction in an entity map.
480 * @param Entity $entity
485 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
487 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
488 return isset($entityMap[$key]) ? $entityMap[$key] : false;
492 * Create an array of data with the information of an entity jointPermissions.
493 * Used to build data for bulk insertion.
494 * @param Entity $entity
497 * @param $permissionAll
498 * @param $permissionOwn
501 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
504 'role_id' => $role->getRawAttribute('id'),
505 'entity_id' => $entity->getRawAttribute('id'),
506 'entity_type' => $entity->getMorphClass(),
508 'has_permission' => $permissionAll,
509 'has_permission_own' => $permissionOwn,
510 'created_by' => $entity->getRawAttribute('created_by')
515 * Checks if an entity has a restriction set upon it.
516 * @param Ownable $ownable
520 public function checkOwnableUserAccess(Ownable $ownable, $permission)
522 $explodedPermission = explode('-', $permission);
524 $baseQuery = $ownable->where('id', '=', $ownable->id);
525 $action = end($explodedPermission);
526 $this->currentAction = $action;
528 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
530 // Handle non entity specific jointPermissions
531 if (in_array($explodedPermission[0], $nonJointPermissions)) {
532 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
533 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
534 $this->currentAction = 'view';
535 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
536 return ($allPermission || ($isOwner && $ownPermission));
539 // Handle abnormal create jointPermissions
540 if ($action === 'create') {
541 $this->currentAction = $permission;
544 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
550 * Check if an entity has restrictions set on itself or its
552 * @param Entity $entity
556 public function checkIfRestrictionsSet(Entity $entity, $action)
558 $this->currentAction = $action;
559 if ($entity->isA('page')) {
560 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
561 } elseif ($entity->isA('chapter')) {
562 return $entity->restricted || $entity->book->restricted;
563 } elseif ($entity->isA('book')) {
564 return $entity->restricted;
569 * The general query filter to remove all entities
570 * that the current user does not have access to.
574 protected function entityRestrictionQuery($query)
576 $q = $query->where(function ($parentQuery) {
577 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
578 $permissionQuery->whereIn('role_id', $this->getRoles())
579 ->where('action', '=', $this->currentAction)
580 ->where(function ($query) {
581 $query->where('has_permission', '=', true)
582 ->orWhere(function ($query) {
583 $query->where('has_permission_own', '=', true)
584 ->where('created_by', '=', $this->currentUser()->id);
594 * Get the children of a book in an efficient single query, Filtered by the permission system.
595 * @param integer $book_id
596 * @param bool $filterDrafts
597 * @param bool $fetchPageContent
598 * @return QueryBuilder
600 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
602 $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
603 $query->where('draft', '=', 0);
604 if (!$filterDrafts) {
605 $query->orWhere(function ($query) {
606 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
610 $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
611 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
612 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
614 // Add joint permission filter
615 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
616 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
617 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
618 ->where(function ($query) {
619 $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
620 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
623 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
625 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
631 * Add restrictions for a generic entity
632 * @param string $entityType
633 * @param Builder|Entity $query
634 * @param string $action
637 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
639 if (strtolower($entityType) === 'page') {
640 // Prevent drafts being visible to others.
641 $query = $query->where(function ($query) {
642 $query->where('draft', '=', false);
643 if ($this->currentUser()) {
644 $query->orWhere(function ($query) {
645 $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
651 $this->currentAction = $action;
652 return $this->entityRestrictionQuery($query);
656 * Filter items that have entities set as a polymorphic relation.
658 * @param string $tableName
659 * @param string $entityIdColumn
660 * @param string $entityTypeColumn
661 * @param string $action
664 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
667 $this->currentAction = $action;
668 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
670 $q = $query->where(function ($query) use ($tableDetails) {
671 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
672 $permissionQuery->select('id')->from('joint_permissions')
673 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
674 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
675 ->where('action', '=', $this->currentAction)
676 ->whereIn('role_id', $this->getRoles())
677 ->where(function ($query) {
678 $query->where('has_permission', '=', true)->orWhere(function ($query) {
679 $query->where('has_permission_own', '=', true)
680 ->where('created_by', '=', $this->currentUser()->id);
690 * Filters pages that are a direct relation to another item.
693 * @param $entityIdColumn
696 public function filterRelatedPages($query, $tableName, $entityIdColumn)
698 $this->currentAction = 'view';
699 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
701 $q = $query->where(function ($query) use ($tableDetails) {
702 $query->where(function ($query) use (&$tableDetails) {
703 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
704 $permissionQuery->select('id')->from('joint_permissions')
705 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
706 ->where('entity_type', '=', 'Bookstack\\Page')
707 ->where('action', '=', $this->currentAction)
708 ->whereIn('role_id', $this->getRoles())
709 ->where(function ($query) {
710 $query->where('has_permission', '=', true)->orWhere(function ($query) {
711 $query->where('has_permission_own', '=', true)
712 ->where('created_by', '=', $this->currentUser()->id);
716 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
723 * Get the current user
726 private function currentUser()
728 if ($this->currentUserModel === false) {
729 $this->currentUserModel = user();
732 return $this->currentUserModel;
736 * Clean the cached user elements.
738 private function clean()
740 $this->currentUserModel = false;
741 $this->userRoles = false;
742 $this->isAdminUser = null;