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);
91 if ($book === null) $book = false;
92 if (isset($this->entityCache['books'])) {
93 $this->entityCache['books']->put($bookId, $book);
100 * Get a chapter via ID, Checks local cache
104 protected function getChapter($chapterId)
106 if (isset($this->entityCache['chapters']) && $this->entityCache['chapters']->has($chapterId)) {
107 return $this->entityCache['chapters']->get($chapterId);
110 $chapter = $this->chapter->find($chapterId);
111 if ($chapter === null) $chapter = false;
112 if (isset($this->entityCache['chapters'])) {
113 $this->entityCache['chapters']->put($chapterId, $chapter);
120 * Get the roles for the current user;
123 protected function getRoles()
125 if ($this->userRoles !== false) return $this->userRoles;
129 if (auth()->guest()) {
130 $roles[] = $this->role->getSystemRole('public')->id;
135 foreach ($this->currentUser()->roles as $role) {
136 $roles[] = $role->id;
142 * Re-generate all entity permission from scratch.
144 public function buildJointPermissions()
146 $this->jointPermission->truncate();
147 $this->readyEntityCache();
149 // Get all roles (Should be the most limited dimension)
150 $roles = $this->role->with('permissions')->get()->all();
152 // Chunk through all books
153 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
154 $this->buildJointPermissionsForBooks($books, $roles);
159 * Get a query for fetching a book with it's children.
160 * @return QueryBuilder
162 protected function bookFetchQuery()
164 return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function($query) {
165 $query->select(['id', 'restricted', 'created_by', 'book_id']);
166 }, 'pages' => function($query) {
167 $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
172 * Build joint permissions for an array of books
173 * @param Collection $books
174 * @param array $roles
175 * @param bool $deleteOld
177 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false) {
178 $entities = clone $books;
180 /** @var Book $book */
181 foreach ($books->all() as $book) {
182 foreach ($book->getRelation('chapters') as $chapter) {
183 $entities->push($chapter);
185 foreach ($book->getRelation('pages') as $page) {
186 $entities->push($page);
190 if ($deleteOld) $this->deleteManyJointPermissionsForEntities($entities->all());
191 $this->createManyJointPermissions($entities, $roles);
195 * Rebuild the entity jointPermissions for a particular entity.
196 * @param Entity $entity
198 public function buildJointPermissionsForEntity(Entity $entity)
200 $entities = [$entity];
201 if ($entity->isA('book')) {
202 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
203 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
207 $entities[] = $entity->book;
209 if ($entity->isA('page') && $entity->chapter_id) {
210 $entities[] = $entity->chapter;
213 if ($entity->isA('chapter')) {
214 foreach ($entity->pages as $page) {
219 $this->deleteManyJointPermissionsForEntities($entities);
220 $this->buildJointPermissionsForEntities(collect($entities));
224 * Rebuild the entity jointPermissions for a collection of entities.
225 * @param Collection $entities
227 public function buildJointPermissionsForEntities(Collection $entities)
229 $roles = $this->role->newQuery()->get();
230 $this->deleteManyJointPermissionsForEntities($entities->all());
231 $this->createManyJointPermissions($entities, $roles);
235 * Build the entity jointPermissions for a particular role.
238 public function buildJointPermissionForRole(Role $role)
241 $this->deleteManyJointPermissionsForRoles($roles);
243 // Chunk through all books
244 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
245 $this->buildJointPermissionsForBooks($books, $roles);
250 * Delete the entity jointPermissions attached to a particular role.
253 public function deleteJointPermissionsForRole(Role $role)
255 $this->deleteManyJointPermissionsForRoles([$role]);
259 * Delete all of the entity jointPermissions for a list of entities.
260 * @param Role[] $roles
262 protected function deleteManyJointPermissionsForRoles($roles)
264 $roleIds = array_map(function($role) {
267 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
271 * Delete the entity jointPermissions for a particular entity.
272 * @param Entity $entity
274 public function deleteJointPermissionsForEntity(Entity $entity)
276 $this->deleteManyJointPermissionsForEntities([$entity]);
280 * Delete all of the entity jointPermissions for a list of entities.
281 * @param Entity[] $entities
283 protected function deleteManyJointPermissionsForEntities($entities)
285 if (count($entities) === 0) return;
287 $this->db->transaction(function() use ($entities) {
289 foreach (array_chunk($entities, 1000) as $entityChunk) {
290 $query = $this->db->table('joint_permissions');
291 foreach ($entityChunk as $entity) {
292 $query->orWhere(function(QueryBuilder $query) use ($entity) {
293 $query->where('entity_id', '=', $entity->id)
294 ->where('entity_type', '=', $entity->getMorphClass());
304 * Create & Save entity jointPermissions for many entities and jointPermissions.
305 * @param Collection $entities
306 * @param array $roles
308 protected function createManyJointPermissions($entities, $roles)
310 $this->readyEntityCache();
311 $jointPermissions = [];
313 // Fetch Entity Permissions and create a mapping of entity restricted statuses
314 $entityRestrictedMap = [];
315 $permissionFetch = $this->entityPermission->newQuery();
316 foreach ($entities as $entity) {
317 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
318 $permissionFetch->orWhere(function($query) use ($entity) {
319 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
322 $permissions = $permissionFetch->get();
324 // Create a mapping of explicit entity permissions
326 foreach ($permissions as $permission) {
327 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
328 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
329 $permissionMap[$key] = $isRestricted;
332 // Create a mapping of role permissions
333 $rolePermissionMap = [];
334 foreach ($roles as $role) {
335 foreach ($role->getRelationValue('permissions') as $permission) {
336 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
340 // Create Joint Permission Data
341 foreach ($entities as $entity) {
342 foreach ($roles as $role) {
343 foreach ($this->getActions($entity) as $action) {
344 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
349 $this->db->transaction(function() use ($jointPermissions) {
350 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
351 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
358 * Get the actions related to an entity.
359 * @param Entity $entity
362 protected function getActions(Entity $entity)
364 $baseActions = ['view', 'update', 'delete'];
365 if ($entity->isA('chapter') || $entity->isA('book')) $baseActions[] = 'page-create';
366 if ($entity->isA('book')) $baseActions[] = 'chapter-create';
371 * Create entity permission data for an entity and role
372 * for a particular action.
373 * @param Entity $entity
375 * @param string $action
376 * @param array $permissionMap
377 * @param array $rolePermissionMap
380 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
382 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
383 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
384 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
385 $explodedAction = explode('-', $action);
386 $restrictionAction = end($explodedAction);
388 if ($role->system_name === 'admin') {
389 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
392 if ($entity->restricted) {
393 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
394 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
397 if ($entity->isA('book')) {
398 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
401 // For chapters and pages, Check if explicit permissions are set on the Book.
402 $book = $this->getBook($entity->book_id);
403 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
404 $hasPermissiveAccessToParents = !$book->restricted;
406 // For pages with a chapter, Check if explicit permissions are set on the Chapter
407 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
408 $chapter = $this->getChapter($entity->chapter_id);
409 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
410 if ($chapter->restricted) {
411 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
415 return $this->createJointPermissionDataArray($entity, $role, $action,
416 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
417 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
422 * Check for an active restriction in an entity map.
424 * @param Entity $entity
429 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action) {
430 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
431 return isset($entityMap[$key]) ? $entityMap[$key] : false;
435 * Create an array of data with the information of an entity jointPermissions.
436 * Used to build data for bulk insertion.
437 * @param Entity $entity
440 * @param $permissionAll
441 * @param $permissionOwn
444 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
447 'role_id' => $role->getRawAttribute('id'),
448 'entity_id' => $entity->getRawAttribute('id'),
449 'entity_type' => $entity->getMorphClass(),
451 'has_permission' => $permissionAll,
452 'has_permission_own' => $permissionOwn,
453 'created_by' => $entity->getRawAttribute('created_by')
458 * Checks if an entity has a restriction set upon it.
459 * @param Ownable $ownable
463 public function checkOwnableUserAccess(Ownable $ownable, $permission)
465 if ($this->isAdmin()) {
470 $explodedPermission = explode('-', $permission);
472 $baseQuery = $ownable->where('id', '=', $ownable->id);
473 $action = end($explodedPermission);
474 $this->currentAction = $action;
476 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
478 // Handle non entity specific jointPermissions
479 if (in_array($explodedPermission[0], $nonJointPermissions)) {
480 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
481 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
482 $this->currentAction = 'view';
483 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
484 return ($allPermission || ($isOwner && $ownPermission));
487 // Handle abnormal create jointPermissions
488 if ($action === 'create') {
489 $this->currentAction = $permission;
492 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
498 * Check if an entity has restrictions set on itself or its
500 * @param Entity $entity
504 public function checkIfRestrictionsSet(Entity $entity, $action)
506 $this->currentAction = $action;
507 if ($entity->isA('page')) {
508 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
509 } elseif ($entity->isA('chapter')) {
510 return $entity->restricted || $entity->book->restricted;
511 } elseif ($entity->isA('book')) {
512 return $entity->restricted;
517 * The general query filter to remove all entities
518 * that the current user does not have access to.
522 protected function entityRestrictionQuery($query)
524 $q = $query->where(function ($parentQuery) {
525 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
526 $permissionQuery->whereIn('role_id', $this->getRoles())
527 ->where('action', '=', $this->currentAction)
528 ->where(function ($query) {
529 $query->where('has_permission', '=', true)
530 ->orWhere(function ($query) {
531 $query->where('has_permission_own', '=', true)
532 ->where('created_by', '=', $this->currentUser()->id);
542 * Get the children of a book in an efficient single query, Filtered by the permission system.
543 * @param integer $book_id
544 * @param bool $filterDrafts
545 * @param bool $fetchPageContent
546 * @return QueryBuilder
548 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false) {
549 $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function($query) use ($filterDrafts) {
550 $query->where('draft', '=', 0);
551 if (!$filterDrafts) {
552 $query->orWhere(function($query) {
553 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
557 $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
558 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
559 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
561 if (!$this->isAdmin()) {
562 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
563 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
564 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
565 ->where(function($query) {
566 $query->where('jp.has_permission', '=', 1)->orWhere(function($query) {
567 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
570 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
573 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
579 * Add restrictions for a generic entity
580 * @param string $entityType
581 * @param Builder|Entity $query
582 * @param string $action
585 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
587 if (strtolower($entityType) === 'page') {
588 // Prevent drafts being visible to others.
589 $query = $query->where(function ($query) {
590 $query->where('draft', '=', false);
591 if ($this->currentUser()) {
592 $query->orWhere(function ($query) {
593 $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
599 if ($this->isAdmin()) {
604 $this->currentAction = $action;
605 return $this->entityRestrictionQuery($query);
609 * Filter items that have entities set as a polymorphic relation.
611 * @param string $tableName
612 * @param string $entityIdColumn
613 * @param string $entityTypeColumn
616 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn)
618 if ($this->isAdmin()) {
623 $this->currentAction = 'view';
624 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
626 $q = $query->where(function ($query) use ($tableDetails) {
627 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
628 $permissionQuery->select('id')->from('joint_permissions')
629 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
630 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
631 ->where('action', '=', $this->currentAction)
632 ->whereIn('role_id', $this->getRoles())
633 ->where(function ($query) {
634 $query->where('has_permission', '=', true)->orWhere(function ($query) {
635 $query->where('has_permission_own', '=', true)
636 ->where('created_by', '=', $this->currentUser()->id);
646 * Filters pages that are a direct relation to another item.
649 * @param $entityIdColumn
652 public function filterRelatedPages($query, $tableName, $entityIdColumn)
654 if ($this->isAdmin()) {
659 $this->currentAction = 'view';
660 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
662 $q = $query->where(function ($query) use ($tableDetails) {
663 $query->where(function ($query) use (&$tableDetails) {
664 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
665 $permissionQuery->select('id')->from('joint_permissions')
666 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
667 ->where('entity_type', '=', 'Bookstack\\Page')
668 ->where('action', '=', $this->currentAction)
669 ->whereIn('role_id', $this->getRoles())
670 ->where(function ($query) {
671 $query->where('has_permission', '=', true)->orWhere(function ($query) {
672 $query->where('has_permission_own', '=', true)
673 ->where('created_by', '=', $this->currentUser()->id);
677 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
684 * Check if the current user is an admin.
687 private function isAdmin()
689 if ($this->isAdminUser === null) {
690 $this->isAdminUser = ($this->currentUser()->id !== null) ? $this->currentUser()->hasSystemRole('admin') : false;
693 return $this->isAdminUser;
697 * Get the current user
700 private function currentUser()
702 if ($this->currentUserModel === false) {
703 $this->currentUserModel = user();
706 return $this->currentUserModel;
710 * Clean the cached user elements.
712 private function clean()
714 $this->currentUserModel = false;
715 $this->userRoles = false;
716 $this->isAdminUser = null;