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;
208 if ($entity->isA('page') && $entity->chapter_id) $entities[] = $entity->chapter;
209 if ($entity->isA('chapter')) {
210 foreach ($entity->pages as $page) {
214 $this->deleteManyJointPermissionsForEntities($entities);
215 $this->buildJointPermissionsForEntities(collect($entities));
219 * Rebuild the entity jointPermissions for a collection of entities.
220 * @param Collection $entities
222 public function buildJointPermissionsForEntities(Collection $entities)
224 $roles = $this->role->newQuery()->get();
225 $this->deleteManyJointPermissionsForEntities($entities->all());
226 $this->createManyJointPermissions($entities, $roles);
230 * Build the entity jointPermissions for a particular role.
233 public function buildJointPermissionForRole(Role $role)
236 $this->deleteManyJointPermissionsForRoles($roles);
238 // Chunk through all books
239 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
240 $this->buildJointPermissionsForBooks($books, $roles);
245 * Delete the entity jointPermissions attached to a particular role.
248 public function deleteJointPermissionsForRole(Role $role)
250 $this->deleteManyJointPermissionsForRoles([$role]);
254 * Delete all of the entity jointPermissions for a list of entities.
255 * @param Role[] $roles
257 protected function deleteManyJointPermissionsForRoles($roles)
259 $roleIds = array_map(function($role) {
262 $this->jointPermission->newQuery()->whereIn('id', $roleIds)->delete();
266 * Delete the entity jointPermissions for a particular entity.
267 * @param Entity $entity
269 public function deleteJointPermissionsForEntity(Entity $entity)
271 $this->deleteManyJointPermissionsForEntities([$entity]);
275 * Delete all of the entity jointPermissions for a list of entities.
276 * @param Entity[] $entities
278 protected function deleteManyJointPermissionsForEntities($entities)
280 if (count($entities) === 0) return;
282 $this->db->transaction(function() use ($entities) {
284 foreach (array_chunk($entities, 1000) as $entityChunk) {
285 $query = $this->db->table('joint_permissions');
286 foreach ($entityChunk as $entity) {
287 $query->orWhere(function(QueryBuilder $query) use ($entity) {
288 $query->where('entity_id', '=', $entity->id)
289 ->where('entity_type', '=', $entity->getMorphClass());
299 * Create & Save entity jointPermissions for many entities and jointPermissions.
300 * @param Collection $entities
301 * @param array $roles
303 protected function createManyJointPermissions($entities, $roles)
305 $this->readyEntityCache();
306 $jointPermissions = [];
308 // Fetch Entity Permissions and create a mapping of entity restricted statuses
309 $entityRestrictedMap = [];
310 $permissionFetch = $this->entityPermission->newQuery();
311 foreach ($entities as $entity) {
312 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
313 $permissionFetch->orWhere(function($query) use ($entity) {
314 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
317 $permissions = $permissionFetch->get();
319 // Create a mapping of explicit entity permissions
321 foreach ($permissions as $permission) {
322 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
323 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
324 $permissionMap[$key] = $isRestricted;
327 // Create a mapping of role permissions
328 $rolePermissionMap = [];
329 foreach ($roles as $role) {
330 foreach ($role->getRelationValue('permissions') as $permission) {
331 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
335 // Create Joint Permission Data
336 foreach ($entities as $entity) {
337 foreach ($roles as $role) {
338 foreach ($this->getActions($entity) as $action) {
339 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
344 $this->db->transaction(function() use ($jointPermissions) {
345 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
346 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
353 * Get the actions related to an entity.
354 * @param Entity $entity
357 protected function getActions(Entity $entity)
359 $baseActions = ['view', 'update', 'delete'];
360 if ($entity->isA('chapter') || $entity->isA('book')) $baseActions[] = 'page-create';
361 if ($entity->isA('book')) $baseActions[] = 'chapter-create';
366 * Create entity permission data for an entity and role
367 * for a particular action.
368 * @param Entity $entity
370 * @param string $action
371 * @param array $permissionMap
372 * @param array $rolePermissionMap
375 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
377 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
378 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
379 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
380 $explodedAction = explode('-', $action);
381 $restrictionAction = end($explodedAction);
383 if ($role->system_name === 'admin') {
384 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
387 if ($entity->restricted) {
388 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
389 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
392 if ($entity->isA('book')) {
393 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
396 // For chapters and pages, Check if explicit permissions are set on the Book.
397 $book = $this->getBook($entity->book_id);
398 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
399 $hasPermissiveAccessToParents = !$book->restricted;
401 // For pages with a chapter, Check if explicit permissions are set on the Chapter
402 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
403 $chapter = $this->getChapter($entity->chapter_id);
404 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
405 if ($chapter->restricted) {
406 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
410 return $this->createJointPermissionDataArray($entity, $role, $action,
411 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
412 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
417 * Check for an active restriction in an entity map.
419 * @param Entity $entity
424 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action) {
425 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
426 return isset($entityMap[$key]) ? $entityMap[$key] : false;
430 * Create an array of data with the information of an entity jointPermissions.
431 * Used to build data for bulk insertion.
432 * @param Entity $entity
435 * @param $permissionAll
436 * @param $permissionOwn
439 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
442 'role_id' => $role->getRawAttribute('id'),
443 'entity_id' => $entity->getRawAttribute('id'),
444 'entity_type' => $entity->getMorphClass(),
446 'has_permission' => $permissionAll,
447 'has_permission_own' => $permissionOwn,
448 'created_by' => $entity->getRawAttribute('created_by')
453 * Checks if an entity has a restriction set upon it.
454 * @param Ownable $ownable
458 public function checkOwnableUserAccess(Ownable $ownable, $permission)
460 if ($this->isAdmin()) {
465 $explodedPermission = explode('-', $permission);
467 $baseQuery = $ownable->where('id', '=', $ownable->id);
468 $action = end($explodedPermission);
469 $this->currentAction = $action;
471 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
473 // Handle non entity specific jointPermissions
474 if (in_array($explodedPermission[0], $nonJointPermissions)) {
475 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
476 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
477 $this->currentAction = 'view';
478 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
479 return ($allPermission || ($isOwner && $ownPermission));
482 // Handle abnormal create jointPermissions
483 if ($action === 'create') {
484 $this->currentAction = $permission;
487 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
493 * Check if an entity has restrictions set on itself or its
495 * @param Entity $entity
499 public function checkIfRestrictionsSet(Entity $entity, $action)
501 $this->currentAction = $action;
502 if ($entity->isA('page')) {
503 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
504 } elseif ($entity->isA('chapter')) {
505 return $entity->restricted || $entity->book->restricted;
506 } elseif ($entity->isA('book')) {
507 return $entity->restricted;
512 * The general query filter to remove all entities
513 * that the current user does not have access to.
517 protected function entityRestrictionQuery($query)
519 $q = $query->where(function ($parentQuery) {
520 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
521 $permissionQuery->whereIn('role_id', $this->getRoles())
522 ->where('action', '=', $this->currentAction)
523 ->where(function ($query) {
524 $query->where('has_permission', '=', true)
525 ->orWhere(function ($query) {
526 $query->where('has_permission_own', '=', true)
527 ->where('created_by', '=', $this->currentUser()->id);
537 * Get the children of a book in an efficient single query, Filtered by the permission system.
538 * @param integer $book_id
539 * @param bool $filterDrafts
540 * @param bool $fetchPageContent
541 * @return QueryBuilder
543 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false) {
544 $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function($query) use ($filterDrafts) {
545 $query->where('draft', '=', 0);
546 if (!$filterDrafts) {
547 $query->orWhere(function($query) {
548 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
552 $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
553 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
554 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
556 if (!$this->isAdmin()) {
557 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
558 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
559 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
560 ->where(function($query) {
561 $query->where('jp.has_permission', '=', 1)->orWhere(function($query) {
562 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
565 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
568 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
574 * Add restrictions for a generic entity
575 * @param string $entityType
576 * @param Builder|Entity $query
577 * @param string $action
580 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
582 if (strtolower($entityType) === 'page') {
583 // Prevent drafts being visible to others.
584 $query = $query->where(function ($query) {
585 $query->where('draft', '=', false);
586 if ($this->currentUser()) {
587 $query->orWhere(function ($query) {
588 $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
594 if ($this->isAdmin()) {
599 $this->currentAction = $action;
600 return $this->entityRestrictionQuery($query);
604 * Filter items that have entities set as a polymorphic relation.
606 * @param string $tableName
607 * @param string $entityIdColumn
608 * @param string $entityTypeColumn
611 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn)
613 if ($this->isAdmin()) {
618 $this->currentAction = 'view';
619 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
621 $q = $query->where(function ($query) use ($tableDetails) {
622 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
623 $permissionQuery->select('id')->from('joint_permissions')
624 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
625 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
626 ->where('action', '=', $this->currentAction)
627 ->whereIn('role_id', $this->getRoles())
628 ->where(function ($query) {
629 $query->where('has_permission', '=', true)->orWhere(function ($query) {
630 $query->where('has_permission_own', '=', true)
631 ->where('created_by', '=', $this->currentUser()->id);
641 * Filters pages that are a direct relation to another item.
644 * @param $entityIdColumn
647 public function filterRelatedPages($query, $tableName, $entityIdColumn)
649 if ($this->isAdmin()) {
654 $this->currentAction = 'view';
655 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
657 $q = $query->where(function ($query) use ($tableDetails) {
658 $query->where(function ($query) use (&$tableDetails) {
659 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
660 $permissionQuery->select('id')->from('joint_permissions')
661 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
662 ->where('entity_type', '=', 'Bookstack\\Page')
663 ->where('action', '=', $this->currentAction)
664 ->whereIn('role_id', $this->getRoles())
665 ->where(function ($query) {
666 $query->where('has_permission', '=', true)->orWhere(function ($query) {
667 $query->where('has_permission_own', '=', true)
668 ->where('created_by', '=', $this->currentUser()->id);
672 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
679 * Check if the current user is an admin.
682 private function isAdmin()
684 if ($this->isAdminUser === null) {
685 $this->isAdminUser = ($this->currentUser()->id !== null) ? $this->currentUser()->hasSystemRole('admin') : false;
688 return $this->isAdminUser;
692 * Get the current user
695 private function currentUser()
697 if ($this->currentUserModel === false) {
698 $this->currentUserModel = user();
701 return $this->currentUserModel;
705 * Clean the cached user elements.
707 private function clean()
709 $this->currentUserModel = false;
710 $this->userRoles = false;
711 $this->isAdminUser = null;