1 <?php namespace BookStack\Services;
6 use BookStack\EntityPermission;
7 use BookStack\JointPermission;
12 use Illuminate\Database\Connection;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Query\Builder as QueryBuilder;
15 use Illuminate\Support\Collection;
17 class PermissionService
20 protected $currentAction;
21 protected $isAdminUser;
22 protected $userRoles = false;
23 protected $currentUserModel = false;
31 protected $jointPermission;
33 protected $entityPermission;
35 protected $entityCache;
38 * PermissionService constructor.
39 * @param JointPermission $jointPermission
40 * @param EntityPermission $entityPermission
41 * @param Connection $db
43 * @param Chapter $chapter
47 public function __construct(JointPermission $jointPermission, EntityPermission $entityPermission, Connection $db, Book $book, Chapter $chapter, Page $page, Role $role)
50 $this->jointPermission = $jointPermission;
51 $this->entityPermission = $entityPermission;
54 $this->chapter = $chapter;
56 // TODO - Update so admin still goes through filters
60 * Set the database connection
61 * @param Connection $connection
63 public function setConnection(Connection $connection)
65 $this->db = $connection;
69 * Prepare the local entity cache and ensure it's empty
71 protected function readyEntityCache()
73 $this->entityCache = [
75 'chapters' => collect()
80 * Get a book via ID, Checks local cache
84 protected function getBook($bookId)
86 if (isset($this->entityCache['books']) && $this->entityCache['books']->has($bookId)) {
87 return $this->entityCache['books']->get($bookId);
90 $book = $this->book->find($bookId);
94 if (isset($this->entityCache['books'])) {
95 $this->entityCache['books']->put($bookId, $book);
102 * Get a chapter via ID, Checks local cache
106 protected function getChapter($chapterId)
108 if (isset($this->entityCache['chapters']) && $this->entityCache['chapters']->has($chapterId)) {
109 return $this->entityCache['chapters']->get($chapterId);
112 $chapter = $this->chapter->find($chapterId);
113 if ($chapter === null) {
116 if (isset($this->entityCache['chapters'])) {
117 $this->entityCache['chapters']->put($chapterId, $chapter);
124 * Get the roles for the current user;
127 protected function getRoles()
129 if ($this->userRoles !== false) {
130 return $this->userRoles;
135 if (auth()->guest()) {
136 $roles[] = $this->role->getSystemRole('public')->id;
141 foreach ($this->currentUser()->roles as $role) {
142 $roles[] = $role->id;
148 * Re-generate all entity permission from scratch.
150 public function buildJointPermissions()
152 $this->jointPermission->truncate();
153 $this->readyEntityCache();
155 // Get all roles (Should be the most limited dimension)
156 $roles = $this->role->with('permissions')->get()->all();
158 // Chunk through all books
159 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
160 $this->buildJointPermissionsForBooks($books, $roles);
165 * Get a query for fetching a book with it's children.
166 * @return QueryBuilder
168 protected function bookFetchQuery()
170 return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
171 $query->select(['id', 'restricted', 'created_by', 'book_id']);
172 }, 'pages' => function ($query) {
173 $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
178 * Build joint permissions for an array of books
179 * @param Collection $books
180 * @param array $roles
181 * @param bool $deleteOld
183 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
185 $entities = clone $books;
187 /** @var Book $book */
188 foreach ($books->all() as $book) {
189 foreach ($book->getRelation('chapters') as $chapter) {
190 $entities->push($chapter);
192 foreach ($book->getRelation('pages') as $page) {
193 $entities->push($page);
198 $this->deleteManyJointPermissionsForEntities($entities->all());
200 $this->createManyJointPermissions($entities, $roles);
204 * Rebuild the entity jointPermissions for a particular entity.
205 * @param Entity $entity
207 public function buildJointPermissionsForEntity(Entity $entity)
209 $entities = [$entity];
210 if ($entity->isA('book')) {
211 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
212 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
216 $entities[] = $entity->book;
218 if ($entity->isA('page') && $entity->chapter_id) {
219 $entities[] = $entity->chapter;
222 if ($entity->isA('chapter')) {
223 foreach ($entity->pages as $page) {
228 $this->deleteManyJointPermissionsForEntities($entities);
229 $this->buildJointPermissionsForEntities(collect($entities));
233 * Rebuild the entity jointPermissions for a collection of entities.
234 * @param Collection $entities
236 public function buildJointPermissionsForEntities(Collection $entities)
238 $roles = $this->role->newQuery()->get();
239 $this->deleteManyJointPermissionsForEntities($entities->all());
240 $this->createManyJointPermissions($entities, $roles);
244 * Build the entity jointPermissions for a particular role.
247 public function buildJointPermissionForRole(Role $role)
250 $this->deleteManyJointPermissionsForRoles($roles);
252 // Chunk through all books
253 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
254 $this->buildJointPermissionsForBooks($books, $roles);
259 * Delete the entity jointPermissions attached to a particular role.
262 public function deleteJointPermissionsForRole(Role $role)
264 $this->deleteManyJointPermissionsForRoles([$role]);
268 * Delete all of the entity jointPermissions for a list of entities.
269 * @param Role[] $roles
271 protected function deleteManyJointPermissionsForRoles($roles)
273 $roleIds = array_map(function ($role) {
276 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
280 * Delete the entity jointPermissions for a particular entity.
281 * @param Entity $entity
283 public function deleteJointPermissionsForEntity(Entity $entity)
285 $this->deleteManyJointPermissionsForEntities([$entity]);
289 * Delete all of the entity jointPermissions for a list of entities.
290 * @param Entity[] $entities
292 protected function deleteManyJointPermissionsForEntities($entities)
294 if (count($entities) === 0) {
298 $this->db->transaction(function () use ($entities) {
300 foreach (array_chunk($entities, 1000) as $entityChunk) {
301 $query = $this->db->table('joint_permissions');
302 foreach ($entityChunk as $entity) {
303 $query->orWhere(function (QueryBuilder $query) use ($entity) {
304 $query->where('entity_id', '=', $entity->id)
305 ->where('entity_type', '=', $entity->getMorphClass());
314 * Create & Save entity jointPermissions for many entities and jointPermissions.
315 * @param Collection $entities
316 * @param array $roles
318 protected function createManyJointPermissions($entities, $roles)
320 $this->readyEntityCache();
321 $jointPermissions = [];
323 // Fetch Entity Permissions and create a mapping of entity restricted statuses
324 $entityRestrictedMap = [];
325 $permissionFetch = $this->entityPermission->newQuery();
326 foreach ($entities as $entity) {
327 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
328 $permissionFetch->orWhere(function ($query) use ($entity) {
329 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
332 $permissions = $permissionFetch->get();
334 // Create a mapping of explicit entity permissions
336 foreach ($permissions as $permission) {
337 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
338 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
339 $permissionMap[$key] = $isRestricted;
342 // Create a mapping of role permissions
343 $rolePermissionMap = [];
344 foreach ($roles as $role) {
345 foreach ($role->getRelationValue('permissions') as $permission) {
346 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
350 // Create Joint Permission Data
351 foreach ($entities as $entity) {
352 foreach ($roles as $role) {
353 foreach ($this->getActions($entity) as $action) {
354 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
359 $this->db->transaction(function () use ($jointPermissions) {
360 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
361 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
368 * Get the actions related to an entity.
369 * @param Entity $entity
372 protected function getActions(Entity $entity)
374 $baseActions = ['view', 'update', 'delete'];
375 if ($entity->isA('chapter') || $entity->isA('book')) {
376 $baseActions[] = 'page-create';
378 if ($entity->isA('book')) {
379 $baseActions[] = 'chapter-create';
385 * Create entity permission data for an entity and role
386 * for a particular action.
387 * @param Entity $entity
389 * @param string $action
390 * @param array $permissionMap
391 * @param array $rolePermissionMap
394 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
396 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
397 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
398 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
399 $explodedAction = explode('-', $action);
400 $restrictionAction = end($explodedAction);
402 if ($role->system_name === 'admin') {
403 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
406 if ($entity->restricted) {
407 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
408 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
411 if ($entity->isA('book')) {
412 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
415 // For chapters and pages, Check if explicit permissions are set on the Book.
416 $book = $this->getBook($entity->book_id);
417 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
418 $hasPermissiveAccessToParents = !$book->restricted;
420 // For pages with a chapter, Check if explicit permissions are set on the Chapter
421 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
422 $chapter = $this->getChapter($entity->chapter_id);
423 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
424 if ($chapter->restricted) {
425 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
429 return $this->createJointPermissionDataArray(
433 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
434 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
439 * Check for an active restriction in an entity map.
441 * @param Entity $entity
446 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
448 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
449 return isset($entityMap[$key]) ? $entityMap[$key] : false;
453 * Create an array of data with the information of an entity jointPermissions.
454 * Used to build data for bulk insertion.
455 * @param Entity $entity
458 * @param $permissionAll
459 * @param $permissionOwn
462 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
465 'role_id' => $role->getRawAttribute('id'),
466 'entity_id' => $entity->getRawAttribute('id'),
467 'entity_type' => $entity->getMorphClass(),
469 'has_permission' => $permissionAll,
470 'has_permission_own' => $permissionOwn,
471 'created_by' => $entity->getRawAttribute('created_by')
476 * Checks if an entity has a restriction set upon it.
477 * @param Ownable $ownable
481 public function checkOwnableUserAccess(Ownable $ownable, $permission)
483 if ($this->isAdmin()) {
488 $explodedPermission = explode('-', $permission);
490 $baseQuery = $ownable->where('id', '=', $ownable->id);
491 $action = end($explodedPermission);
492 $this->currentAction = $action;
494 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
496 // Handle non entity specific jointPermissions
497 if (in_array($explodedPermission[0], $nonJointPermissions)) {
498 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
499 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
500 $this->currentAction = 'view';
501 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
502 return ($allPermission || ($isOwner && $ownPermission));
505 // Handle abnormal create jointPermissions
506 if ($action === 'create') {
507 $this->currentAction = $permission;
510 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
516 * Check if an entity has restrictions set on itself or its
518 * @param Entity $entity
522 public function checkIfRestrictionsSet(Entity $entity, $action)
524 $this->currentAction = $action;
525 if ($entity->isA('page')) {
526 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
527 } elseif ($entity->isA('chapter')) {
528 return $entity->restricted || $entity->book->restricted;
529 } elseif ($entity->isA('book')) {
530 return $entity->restricted;
535 * The general query filter to remove all entities
536 * that the current user does not have access to.
540 protected function entityRestrictionQuery($query)
542 $q = $query->where(function ($parentQuery) {
543 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
544 $permissionQuery->whereIn('role_id', $this->getRoles())
545 ->where('action', '=', $this->currentAction)
546 ->where(function ($query) {
547 $query->where('has_permission', '=', true)
548 ->orWhere(function ($query) {
549 $query->where('has_permission_own', '=', true)
550 ->where('created_by', '=', $this->currentUser()->id);
560 * Get the children of a book in an efficient single query, Filtered by the permission system.
561 * @param integer $book_id
562 * @param bool $filterDrafts
563 * @param bool $fetchPageContent
564 * @return QueryBuilder
566 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
568 $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
569 $query->where('draft', '=', 0);
570 if (!$filterDrafts) {
571 $query->orWhere(function ($query) {
572 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
576 $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
577 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
578 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
580 if (!$this->isAdmin()) {
581 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
582 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
583 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
584 ->where(function ($query) {
585 $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
586 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
589 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
592 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
598 * Add restrictions for a generic entity
599 * @param string $entityType
600 * @param Builder|Entity $query
601 * @param string $action
604 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
606 if (strtolower($entityType) === 'page') {
607 // Prevent drafts being visible to others.
608 $query = $query->where(function ($query) {
609 $query->where('draft', '=', false);
610 if ($this->currentUser()) {
611 $query->orWhere(function ($query) {
612 $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
618 if ($this->isAdmin()) {
623 $this->currentAction = $action;
624 return $this->entityRestrictionQuery($query);
628 * Filter items that have entities set as a polymorphic relation.
630 * @param string $tableName
631 * @param string $entityIdColumn
632 * @param string $entityTypeColumn
635 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn)
637 if ($this->isAdmin()) {
642 $this->currentAction = 'view';
643 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
645 $q = $query->where(function ($query) use ($tableDetails) {
646 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
647 $permissionQuery->select('id')->from('joint_permissions')
648 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
649 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
650 ->where('action', '=', $this->currentAction)
651 ->whereIn('role_id', $this->getRoles())
652 ->where(function ($query) {
653 $query->where('has_permission', '=', true)->orWhere(function ($query) {
654 $query->where('has_permission_own', '=', true)
655 ->where('created_by', '=', $this->currentUser()->id);
665 * Filters pages that are a direct relation to another item.
668 * @param $entityIdColumn
671 public function filterRelatedPages($query, $tableName, $entityIdColumn)
673 if ($this->isAdmin()) {
678 $this->currentAction = 'view';
679 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
681 $q = $query->where(function ($query) use ($tableDetails) {
682 $query->where(function ($query) use (&$tableDetails) {
683 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
684 $permissionQuery->select('id')->from('joint_permissions')
685 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
686 ->where('entity_type', '=', 'Bookstack\\Page')
687 ->where('action', '=', $this->currentAction)
688 ->whereIn('role_id', $this->getRoles())
689 ->where(function ($query) {
690 $query->where('has_permission', '=', true)->orWhere(function ($query) {
691 $query->where('has_permission_own', '=', true)
692 ->where('created_by', '=', $this->currentUser()->id);
696 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
703 * Check if the current user is an admin.
706 private function isAdmin()
708 if ($this->isAdminUser === null) {
709 $this->isAdminUser = ($this->currentUser()->id !== null) ? $this->currentUser()->hasSystemRole('admin') : false;
712 return $this->isAdminUser;
716 * Get the current user
719 private function currentUser()
721 if ($this->currentUserModel === false) {
722 $this->currentUserModel = user();
725 return $this->currentUserModel;
729 * Clean the cached user elements.
731 private function clean()
733 $this->currentUserModel = false;
734 $this->userRoles = false;
735 $this->isAdminUser = null;