]> BookStack Code Mirror - bookstack/blobdiff - app/Auth/Permissions/PermissionService.php
Updated minimum php version from 7.3 to 7.4
[bookstack] / app / Auth / Permissions / PermissionService.php
index a5ab4ea9a8e51109c7225bc82ccca1799470205d..59ff37dc9bcb7ebb9c3b856cc40868e5ccbcae9c 100644 (file)
@@ -1,79 +1,56 @@
-<?php namespace BookStack\Auth\Permissions;
+<?php
+
+namespace BookStack\Auth\Permissions;
 
-use BookStack\Auth\Permissions;
 use BookStack\Auth\Role;
-use BookStack\Entities\Book;
-use BookStack\Entities\Bookshelf;
-use BookStack\Entities\Chapter;
-use BookStack\Entities\Entity;
-use BookStack\Entities\EntityProvider;
-use BookStack\Entities\Page;
-use BookStack\Ownable;
+use BookStack\Auth\User;
+use BookStack\Entities\Models\Book;
+use BookStack\Entities\Models\BookChild;
+use BookStack\Entities\Models\Bookshelf;
+use BookStack\Entities\Models\Chapter;
+use BookStack\Entities\Models\Entity;
+use BookStack\Entities\Models\Page;
+use BookStack\Model;
+use BookStack\Traits\HasCreatorAndUpdater;
+use BookStack\Traits\HasOwner;
 use Illuminate\Database\Connection;
 use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Collection as EloquentCollection;
 use Illuminate\Database\Query\Builder as QueryBuilder;
-use Illuminate\Support\Collection;
+use Throwable;
 
 class PermissionService
 {
-
-    protected $currentAction;
-    protected $isAdminUser;
-    protected $userRoles = false;
-    protected $currentUserModel = false;
-
     /**
-     * @var Connection
+     * @var ?array
      */
-    protected $db;
+    protected $userRoles = null;
 
     /**
-     * @var JointPermission
+     * @var ?User
      */
-    protected $jointPermission;
+    protected $currentUserModel = null;
 
     /**
-     * @var Role
-     */
-    protected $role;
-
-    /**
-     * @var EntityPermission
+     * @var Connection
      */
-    protected $entityPermission;
+    protected $db;
 
     /**
-     * @var EntityProvider
+     * @var array
      */
-    protected $entityProvider;
-
     protected $entityCache;
 
     /**
      * PermissionService constructor.
-     * @param JointPermission $jointPermission
-     * @param EntityPermission $entityPermission
-     * @param Role $role
-     * @param Connection $db
-     * @param EntityProvider $entityProvider
-     */
-    public function __construct(
-        JointPermission $jointPermission,
-        Permissions\EntityPermission $entityPermission,
-        Role $role,
-        Connection $db,
-        EntityProvider $entityProvider
-    ) {
+     */
+    public function __construct(Connection $db)
+    {
         $this->db = $db;
-        $this->jointPermission = $jointPermission;
-        $this->entityPermission = $entityPermission;
-        $this->role = $role;
-        $this->entityProvider = $entityProvider;
     }
 
     /**
-     * Set the database connection
-     * @param Connection $connection
+     * Set the database connection.
      */
     public function setConnection(Connection $connection)
     {
@@ -81,82 +58,65 @@ class PermissionService
     }
 
     /**
-     * Prepare the local entity cache and ensure it's empty
-     * @param \BookStack\Entities\Entity[] $entities
+     * Prepare the local entity cache and ensure it's empty.
+     *
+     * @param Entity[] $entities
      */
-    protected function readyEntityCache($entities = [])
+    protected function readyEntityCache(array $entities = [])
     {
         $this->entityCache = [];
 
         foreach ($entities as $entity) {
-            $type = $entity->getType();
-            if (!isset($this->entityCache[$type])) {
-                $this->entityCache[$type] = collect();
+            $class = get_class($entity);
+            if (!isset($this->entityCache[$class])) {
+                $this->entityCache[$class] = collect();
             }
-            $this->entityCache[$type]->put($entity->id, $entity);
+            $this->entityCache[$class]->put($entity->id, $entity);
         }
     }
 
     /**
-     * Get a book via ID, Checks local cache
-     * @param $bookId
-     * @return Book
+     * Get a book via ID, Checks local cache.
      */
-    protected function getBook($bookId)
+    protected function getBook(int $bookId): ?Book
     {
-        if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
-            return $this->entityCache['book']->get($bookId);
+        if (isset($this->entityCache[Book::class]) && $this->entityCache[Book::class]->has($bookId)) {
+            return $this->entityCache[Book::class]->get($bookId);
         }
 
-        $book = $this->entityProvider->book->find($bookId);
-        if ($book === null) {
-            $book = false;
-        }
-
-        return $book;
+        return Book::query()->withTrashed()->find($bookId);
     }
 
     /**
-     * Get a chapter via ID, Checks local cache
-     * @param $chapterId
-     * @return \BookStack\Entities\Book
+     * Get a chapter via ID, Checks local cache.
      */
-    protected function getChapter($chapterId)
+    protected function getChapter(int $chapterId): ?Chapter
     {
-        if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
-            return $this->entityCache['chapter']->get($chapterId);
-        }
-
-        $chapter = $this->entityProvider->chapter->find($chapterId);
-        if ($chapter === null) {
-            $chapter = false;
+        if (isset($this->entityCache[Chapter::class]) && $this->entityCache[Chapter::class]->has($chapterId)) {
+            return $this->entityCache[Chapter::class]->get($chapterId);
         }
 
-        return $chapter;
+        return Chapter::query()
+            ->withTrashed()
+            ->find($chapterId);
     }
 
     /**
-     * Get the roles for the current user;
-     * @return array|bool
+     * Get the roles for the current logged in user.
      */
-    protected function getRoles()
+    protected function getCurrentUserRoles(): array
     {
-        if ($this->userRoles !== false) {
+        if (!is_null($this->userRoles)) {
             return $this->userRoles;
         }
 
-        $roles = [];
-
         if (auth()->guest()) {
-            $roles[] = $this->role->getSystemRole('public')->id;
-            return $roles;
+            $this->userRoles = [Role::getSystemRole('public')->id];
+        } else {
+            $this->userRoles = $this->currentUser()->roles->pluck('id')->values()->all();
         }
 
-
-        foreach ($this->currentUser()->roles as $role) {
-            $roles[] = $role->id;
-        }
-        return $roles;
+        return $this->userRoles;
     }
 
     /**
@@ -164,60 +124,59 @@ class PermissionService
      */
     public function buildJointPermissions()
     {
-        $this->jointPermission->truncate();
+        JointPermission::query()->truncate();
         $this->readyEntityCache();
 
         // Get all roles (Should be the most limited dimension)
-        $roles = $this->role->with('permissions')->get()->all();
+        $roles = Role::query()->with('permissions')->get()->all();
 
         // Chunk through all books
-        $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
+        $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
             $this->buildJointPermissionsForBooks($books, $roles);
         });
 
         // Chunk through all bookshelves
-        $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
-            ->chunk(50, function ($shelves) use ($roles) {
+        Bookshelf::query()->withTrashed()->select(['id', 'restricted', 'owned_by'])
+            ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
                 $this->buildJointPermissionsForShelves($shelves, $roles);
             });
     }
 
     /**
      * Get a query for fetching a book with it's children.
-     * @return QueryBuilder
      */
-    protected function bookFetchQuery()
+    protected function bookFetchQuery(): Builder
     {
-        return $this->entityProvider->book->newQuery()
-            ->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
-                $query->select(['id', 'restricted', 'created_by', 'book_id']);
-            }, 'pages'  => function ($query) {
-                $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
-            }]);
+        return Book::query()->withTrashed()
+            ->select(['id', 'restricted', 'owned_by'])->with([
+                'chapters' => function ($query) {
+                    $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
+                },
+                'pages' => function ($query) {
+                    $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
+                },
+            ]);
     }
 
     /**
-     * @param Collection $shelves
-     * @param array $roles
-     * @param bool $deleteOld
-     * @throws \Throwable
+     * Build joint permissions for the given shelf and role combinations.
+     *
+     * @throws Throwable
      */
-    protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
+    protected function buildJointPermissionsForShelves(EloquentCollection $shelves, array $roles, bool $deleteOld = false)
     {
         if ($deleteOld) {
             $this->deleteManyJointPermissionsForEntities($shelves->all());
         }
-        $this->createManyJointPermissions($shelves, $roles);
+        $this->createManyJointPermissions($shelves->all(), $roles);
     }
 
     /**
-     * Build joint permissions for an array of books
-     * @param Collection $books
-     * @param array $roles
-     * @param bool $deleteOld
-     * @throws \Throwable
+     * Build joint permissions for the given book and role combinations.
+     *
+     * @throws Throwable
      */
-    protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
+    protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
     {
         $entities = clone $books;
 
@@ -234,55 +193,56 @@ class PermissionService
         if ($deleteOld) {
             $this->deleteManyJointPermissionsForEntities($entities->all());
         }
-        $this->createManyJointPermissions($entities, $roles);
+        $this->createManyJointPermissions($entities->all(), $roles);
     }
 
     /**
      * Rebuild the entity jointPermissions for a particular entity.
-     * @param \BookStack\Entities\Entity $entity
-     * @throws \Throwable
+     *
+     * @throws Throwable
      */
     public function buildJointPermissionsForEntity(Entity $entity)
     {
         $entities = [$entity];
-        if ($entity->isA('book')) {
+        if ($entity instanceof Book) {
             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
-            $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
+            $this->buildJointPermissionsForBooks($books, Role::query()->get()->all(), true);
+
             return;
         }
 
+        /** @var BookChild $entity */
         if ($entity->book) {
             $entities[] = $entity->book;
         }
 
-        if ($entity->isA('page') && $entity->chapter_id) {
+        if ($entity instanceof Page && $entity->chapter_id) {
             $entities[] = $entity->chapter;
         }
 
-        if ($entity->isA('chapter')) {
+        if ($entity instanceof Chapter) {
             foreach ($entity->pages as $page) {
                 $entities[] = $page;
             }
         }
 
-        $this->buildJointPermissionsForEntities(collect($entities));
+        $this->buildJointPermissionsForEntities($entities);
     }
 
     /**
      * Rebuild the entity jointPermissions for a collection of entities.
-     * @param Collection $entities
-     * @throws \Throwable
+     *
+     * @throws Throwable
      */
-    public function buildJointPermissionsForEntities(Collection $entities)
+    public function buildJointPermissionsForEntities(array $entities)
     {
-        $roles = $this->role->newQuery()->get();
-        $this->deleteManyJointPermissionsForEntities($entities->all());
+        $roles = Role::query()->get()->values()->all();
+        $this->deleteManyJointPermissionsForEntities($entities);
         $this->createManyJointPermissions($entities, $roles);
     }
 
     /**
      * Build the entity jointPermissions for a particular role.
-     * @param Role $role
      */
     public function buildJointPermissionForRole(Role $role)
     {
@@ -295,7 +255,7 @@ class PermissionService
         });
 
         // Chunk through all bookshelves
-        $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
+        Bookshelf::query()->select(['id', 'restricted', 'owned_by'])
             ->chunk(50, function ($shelves) use ($roles) {
                 $this->buildJointPermissionsForShelves($shelves, $roles);
             });
@@ -303,7 +263,6 @@ class PermissionService
 
     /**
      * Delete the entity jointPermissions attached to a particular role.
-     * @param Role $role
      */
     public function deleteJointPermissionsForRole(Role $role)
     {
@@ -312,6 +271,7 @@ class PermissionService
 
     /**
      * Delete all of the entity jointPermissions for a list of entities.
+     *
      * @param Role[] $roles
      */
     protected function deleteManyJointPermissionsForRoles($roles)
@@ -319,13 +279,15 @@ class PermissionService
         $roleIds = array_map(function ($role) {
             return $role->id;
         }, $roles);
-        $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
+        JointPermission::query()->whereIn('role_id', $roleIds)->delete();
     }
 
     /**
      * Delete the entity jointPermissions for a particular entity.
+     *
      * @param Entity $entity
-     * @throws \Throwable
+     *
+     * @throws Throwable
      */
     public function deleteJointPermissionsForEntity(Entity $entity)
     {
@@ -334,17 +296,18 @@ class PermissionService
 
     /**
      * Delete all of the entity jointPermissions for a list of entities.
-     * @param \BookStack\Entities\Entity[] $entities
-     * @throws \Throwable
+     *
+     * @param Entity[] $entities
+     *
+     * @throws Throwable
      */
-    protected function deleteManyJointPermissionsForEntities($entities)
+    protected function deleteManyJointPermissionsForEntities(array $entities)
     {
         if (count($entities) === 0) {
             return;
         }
 
         $this->db->transaction(function () use ($entities) {
-
             foreach (array_chunk($entities, 1000) as $entityChunk) {
                 $query = $this->db->table('joint_permissions');
                 foreach ($entityChunk as $entity) {
@@ -359,19 +322,21 @@ class PermissionService
     }
 
     /**
-     * Create & Save entity jointPermissions for many entities and jointPermissions.
-     * @param Collection $entities
-     * @param array $roles
-     * @throws \Throwable
+     * Create & Save entity jointPermissions for many entities and roles.
+     *
+     * @param Entity[] $entities
+     * @param Role[]   $roles
+     *
+     * @throws Throwable
      */
-    protected function createManyJointPermissions($entities, $roles)
+    protected function createManyJointPermissions(array $entities, array $roles)
     {
         $this->readyEntityCache($entities);
         $jointPermissions = [];
 
         // Fetch Entity Permissions and create a mapping of entity restricted statuses
         $entityRestrictedMap = [];
-        $permissionFetch = $this->entityPermission->newQuery();
+        $permissionFetch = EntityPermission::query();
         foreach ($entities as $entity) {
             $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
             $permissionFetch->orWhere(function ($query) use ($entity) {
@@ -412,35 +377,27 @@ class PermissionService
         });
     }
 
-
     /**
      * Get the actions related to an entity.
-     * @param \BookStack\Entities\Entity $entity
-     * @return array
      */
-    protected function getActions(Entity $entity)
+    protected function getActions(Entity $entity): array
     {
         $baseActions = ['view', 'update', 'delete'];
-        if ($entity->isA('chapter') || $entity->isA('book')) {
+        if ($entity instanceof Chapter || $entity instanceof Book) {
             $baseActions[] = 'page-create';
         }
-        if ($entity->isA('book')) {
+        if ($entity instanceof Book) {
             $baseActions[] = 'chapter-create';
         }
+
         return $baseActions;
     }
 
     /**
      * Create entity permission data for an entity and role
      * for a particular action.
-     * @param Entity $entity
-     * @param Role $role
-     * @param string $action
-     * @param array $permissionMap
-     * @param array $rolePermissionMap
-     * @return array
      */
-    protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
+    protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array
     {
         $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
         $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
@@ -454,10 +411,11 @@ class PermissionService
 
         if ($entity->restricted) {
             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
+
             return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
         }
 
-        if ($entity->isA('book') || $entity->isA('bookshelf')) {
+        if ($entity instanceof Book || $entity instanceof Bookshelf) {
             return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
         }
 
@@ -467,7 +425,7 @@ class PermissionService
         $hasPermissiveAccessToParents = !$book->restricted;
 
         // For pages with a chapter, Check if explicit permissions are set on the Chapter
-        if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
+        if ($entity instanceof Page && intval($entity->chapter_id) !== 0) {
             $chapter = $this->getChapter($entity->chapter_id);
             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
             if ($chapter->restricted) {
@@ -486,29 +444,19 @@ class PermissionService
 
     /**
      * Check for an active restriction in an entity map.
-     * @param $entityMap
-     * @param Entity $entity
-     * @param Role $role
-     * @param $action
-     * @return bool
      */
-    protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
+    protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool
     {
         $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
-        return isset($entityMap[$key]) ? $entityMap[$key] : false;
+
+        return $entityMap[$key] ?? false;
     }
 
     /**
      * Create an array of data with the information of an entity jointPermissions.
      * Used to build data for bulk insertion.
-     * @param \BookStack\Entities\Entity $entity
-     * @param Role $role
-     * @param $action
-     * @param $permissionAll
-     * @param $permissionOwn
-     * @return array
      */
-    protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
+    protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array
     {
         return [
             'role_id'            => $role->getRawAttribute('id'),
@@ -517,266 +465,243 @@ class PermissionService
             'action'             => $action,
             'has_permission'     => $permissionAll,
             'has_permission_own' => $permissionOwn,
-            'created_by'         => $entity->getRawAttribute('created_by')
+            'owned_by'           => $entity->getRawAttribute('owned_by'),
         ];
     }
 
     /**
      * Checks if an entity has a restriction set upon it.
-     * @param Ownable $ownable
-     * @param $permission
-     * @return bool
+     *
+     * @param HasCreatorAndUpdater|HasOwner $ownable
      */
-    public function checkOwnableUserAccess(Ownable $ownable, $permission)
+    public function checkOwnableUserAccess(Model $ownable, string $permission): bool
     {
         $explodedPermission = explode('-', $permission);
 
-        $baseQuery = $ownable->where('id', '=', $ownable->id);
+        $baseQuery = $ownable->newQuery()->where('id', '=', $ownable->id);
         $action = end($explodedPermission);
-        $this->currentAction = $action;
+        $user = $this->currentUser();
 
         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
 
         // Handle non entity specific jointPermissions
         if (in_array($explodedPermission[0], $nonJointPermissions)) {
-            $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
-            $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
-            $this->currentAction = 'view';
-            $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
-            return ($allPermission || ($isOwner && $ownPermission));
+            $allPermission = $user && $user->can($permission . '-all');
+            $ownPermission = $user && $user->can($permission . '-own');
+            $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
+            $isOwner = $user && $user->id === $ownable->$ownerField;
+
+            return $allPermission || ($isOwner && $ownPermission);
         }
 
         // Handle abnormal create jointPermissions
         if ($action === 'create') {
-            $this->currentAction = $permission;
+            $action = $permission;
         }
 
-        $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
+        $hasAccess = $this->entityRestrictionQuery($baseQuery, $action)->count() > 0;
         $this->clean();
-        return $q;
+
+        return $hasAccess;
     }
 
     /**
      * Checks if a user has the given permission for any items in the system.
      * Can be passed an entity instance to filter on a specific type.
-     * @param string $permission
-     * @param string $entityClass
-     * @return bool
      */
-    public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null)
+    public function checkUserHasPermissionOnAnything(string $permission, ?string $entityClass = null): bool
     {
         $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
         $userId = $this->currentUser()->id;
 
-        $permissionQuery = $this->db->table('joint_permissions')
+        $permissionQuery = JointPermission::query()
             ->where('action', '=', $permission)
             ->whereIn('role_id', $userRoleIds)
-            ->where(function ($query) use ($userId) {
-                $query->where('has_permission', '=', 1)
-                    ->orWhere(function ($query2) use ($userId) {
-                        $query2->where('has_permission_own', '=', 1)
-                            ->where('created_by', '=', $userId);
-                    });
+            ->where(function (Builder $query) use ($userId) {
+                $this->addJointHasPermissionCheck($query, $userId);
             });
 
         if (!is_null($entityClass)) {
-            $entityInstance = app()->make($entityClass);
+            $entityInstance = app($entityClass);
             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
         }
 
         $hasPermission = $permissionQuery->count() > 0;
         $this->clean();
-        return $hasPermission;
-    }
 
-    /**
-     * Check if an entity has restrictions set on itself or its
-     * parent tree.
-     * @param \BookStack\Entities\Entity $entity
-     * @param $action
-     * @return bool|mixed
-     */
-    public function checkIfRestrictionsSet(Entity $entity, $action)
-    {
-        $this->currentAction = $action;
-        if ($entity->isA('page')) {
-            return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
-        } elseif ($entity->isA('chapter')) {
-            return $entity->restricted || $entity->book->restricted;
-        } elseif ($entity->isA('book')) {
-            return $entity->restricted;
-        }
+        return $hasPermission;
     }
 
     /**
      * The general query filter to remove all entities
      * that the current user does not have access to.
-     * @param $query
-     * @return mixed
-     */
-    protected function entityRestrictionQuery($query)
-    {
-        $q = $query->where(function ($parentQuery) {
-            $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
-                $permissionQuery->whereIn('role_id', $this->getRoles())
-                    ->where('action', '=', $this->currentAction)
-                    ->where(function ($query) {
-                        $query->where('has_permission', '=', true)
-                            ->orWhere(function ($query) {
-                                $query->where('has_permission_own', '=', true)
-                                    ->where('created_by', '=', $this->currentUser()->id);
-                            });
+     */
+    protected function entityRestrictionQuery(Builder $query, string $action): Builder
+    {
+        $q = $query->where(function ($parentQuery) use ($action) {
+            $parentQuery->whereHas('jointPermissions', function ($permissionQuery) use ($action) {
+                $permissionQuery->whereIn('role_id', $this->getCurrentUserRoles())
+                    ->where('action', '=', $action)
+                    ->where(function (Builder $query) {
+                        $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                     });
             });
         });
+
         $this->clean();
+
         return $q;
     }
 
     /**
-     * Get the children of a book in an efficient single query, Filtered by the permission system.
-     * @param integer $book_id
-     * @param bool $filterDrafts
-     * @param bool $fetchPageContent
-     * @return QueryBuilder
+     * Limited the given entity query so that the query will only
+     * return items that the user has permission for the given ability.
      */
-    public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
+    public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
     {
-        $entities = $this->entityProvider;
-        $pageSelect = $this->db->table('pages')->selectRaw($entities->page->entityRawQuery($fetchPageContent))
-            ->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
-                $query->where('draft', '=', 0);
-                if (!$filterDrafts) {
-                    $query->orWhere(function ($query) {
-                        $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
+        $this->clean();
+
+        return $query->where(function (Builder $parentQuery) use ($ability) {
+            $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) {
+                $permissionQuery->whereIn('role_id', $this->getCurrentUserRoles())
+                    ->where('action', '=', $ability)
+                    ->where(function (Builder $query) {
+                        $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                     });
-                }
-            });
-        $chapterSelect = $this->db->table('chapters')->selectRaw($entities->chapter->entityRawQuery())->where('book_id', '=', $book_id);
-        $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
-            ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
-
-        // Add joint permission filter
-        $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
-            ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
-            ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
-            ->where(function ($query) {
-                $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
-                    $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
-                });
             });
-        $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
+        });
+    }
 
-        $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
-        $this->clean();
-        return  $query;
+    /**
+     * Extend the given page query to ensure draft items are not visible
+     * unless created by the given user.
+     */
+    public function enforceDraftVisibilityOnQuery(Builder $query): Builder
+    {
+        return $query->where(function (Builder $query) {
+            $query->where('draft', '=', false)
+                ->orWhere(function (Builder $query) {
+                    $query->where('draft', '=', true)
+                        ->where('owned_by', '=', $this->currentUser()->id);
+                });
+        });
     }
 
     /**
-     * Add restrictions for a generic entity
-     * @param string $entityType
-     * @param Builder|\BookStack\Entities\Entity $query
-     * @param string $action
-     * @return Builder
+     * Add restrictions for a generic entity.
      */
-    public function enforceEntityRestrictions($entityType, $query, $action = 'view')
+    public function enforceEntityRestrictions(Entity $entity, Builder $query, string $action = 'view'): Builder
     {
-        if (strtolower($entityType) === 'page') {
+        if ($entity instanceof Page) {
             // Prevent drafts being visible to others.
-            $query = $query->where(function ($query) {
-                $query->where('draft', '=', false);
-                if ($this->currentUser()) {
-                    $query->orWhere(function ($query) {
-                        $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
-                    });
-                }
-            });
+            $this->enforceDraftVisibilityOnQuery($query);
         }
 
-        $this->currentAction = $action;
-        return $this->entityRestrictionQuery($query);
+        return $this->entityRestrictionQuery($query, $action);
     }
 
     /**
      * Filter items that have entities set as a polymorphic relation.
-     * @param $query
-     * @param string $tableName
-     * @param string $entityIdColumn
-     * @param string $entityTypeColumn
-     * @param string $action
-     * @return QueryBuilder
+     * For simplicity, this will not return results attached to draft pages.
+     * Draft pages should never really have related items though.
+     *
+     * @param Builder|QueryBuilder $query
      */
-    public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
+    public function filterRestrictedEntityRelations($query, string $tableName, string $entityIdColumn, string $entityTypeColumn, string $action = 'view')
     {
-
-        $this->currentAction = $action;
         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
-
-        $q = $query->where(function ($query) use ($tableDetails) {
-            $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
-                $permissionQuery->select('id')->from('joint_permissions')
-                    ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
-                    ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
-                    ->where('action', '=', $this->currentAction)
-                    ->whereIn('role_id', $this->getRoles())
-                    ->where(function ($query) {
-                        $query->where('has_permission', '=', true)->orWhere(function ($query) {
-                            $query->where('has_permission_own', '=', true)
-                                ->where('created_by', '=', $this->currentUser()->id);
-                        });
-                    });
-            });
+        $pageMorphClass = (new Page())->getMorphClass();
+
+        $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {
+            /** @var Builder $permissionQuery */
+            $permissionQuery->select(['role_id'])->from('joint_permissions')
+                ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
+                ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
+                ->where('joint_permissions.action', '=', $action)
+                ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoles())
+                ->where(function (QueryBuilder $query) {
+                    $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
+                });
+        })->where(function ($query) use ($tableDetails, $pageMorphClass) {
+            /** @var Builder $query */
+            $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass)
+                ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) {
+                    $query->select('id')->from('pages')
+                        ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
+                        ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass)
+                        ->where('pages.draft', '=', false);
+                });
         });
+
         $this->clean();
+
         return $q;
     }
 
     /**
      * Add conditions to a query to filter the selection to related entities
-     * where permissions are granted.
-     * @param $entityType
-     * @param $query
-     * @param $tableName
-     * @param $entityIdColumn
-     * @return mixed
-     */
-    public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn)
-    {
-        $this->currentAction = 'view';
-        $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
-
-        $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass();
-
-        $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) {
-            $query->where(function ($query) use (&$tableDetails, $pageMorphClass) {
-                $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) {
-                    $permissionQuery->select('id')->from('joint_permissions')
-                        ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
-                        ->where('entity_type', '=', $pageMorphClass)
-                        ->where('action', '=', $this->currentAction)
-                        ->whereIn('role_id', $this->getRoles())
-                        ->where(function ($query) {
-                            $query->where('has_permission', '=', true)->orWhere(function ($query) {
-                                $query->where('has_permission_own', '=', true)
-                                    ->where('created_by', '=', $this->currentUser()->id);
-                            });
-                        });
+     * where view permissions are granted.
+     */
+    public function filterRelatedEntity(string $entityClass, Builder $query, string $tableName, string $entityIdColumn): Builder
+    {
+        $fullEntityIdColumn = $tableName . '.' . $entityIdColumn;
+        $instance = new $entityClass();
+        $morphClass = $instance->getMorphClass();
+
+        $existsQuery = function ($permissionQuery) use ($fullEntityIdColumn, $morphClass) {
+            /** @var Builder $permissionQuery */
+            $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
+                ->whereColumn('joint_permissions.entity_id', '=', $fullEntityIdColumn)
+                ->where('joint_permissions.entity_type', '=', $morphClass)
+                ->where('joint_permissions.action', '=', 'view')
+                ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoles())
+                ->where(function (QueryBuilder $query) {
+                    $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                 });
-            })->orWhere($tableDetails['entityIdColumn'], '=', 0);
+        };
+
+        $q = $query->where(function ($query) use ($existsQuery, $fullEntityIdColumn) {
+            $query->whereExists($existsQuery)
+                ->orWhere($fullEntityIdColumn, '=', 0);
         });
 
+        if ($instance instanceof Page) {
+            // Prevent visibility of non-owned draft pages
+            $q->whereExists(function (QueryBuilder $query) use ($fullEntityIdColumn) {
+                $query->select('id')->from('pages')
+                    ->whereColumn('pages.id', '=', $fullEntityIdColumn)
+                    ->where(function (QueryBuilder $query) {
+                        $query->where('pages.draft', '=', false)
+                            ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
+                    });
+            });
+        }
+
         $this->clean();
 
         return $q;
     }
 
     /**
-     * Get the current user
-     * @return \BookStack\Auth\User
+     * Add the query for checking the given user id has permission
+     * within the join_permissions table.
+     *
+     * @param QueryBuilder|Builder $query
+     */
+    protected function addJointHasPermissionCheck($query, int $userIdToCheck)
+    {
+        $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
+            $query->where('joint_permissions.has_permission_own', '=', true)
+                ->where('joint_permissions.owned_by', '=', $userIdToCheck);
+        });
+    }
+
+    /**
+     * Get the current user.
      */
-    private function currentUser()
+    private function currentUser(): User
     {
-        if ($this->currentUserModel === false) {
+        if (is_null($this->currentUserModel)) {
             $this->currentUserModel = user();
         }
 
@@ -786,10 +711,9 @@ class PermissionService
     /**
      * Clean the cached user elements.
      */
-    private function clean()
+    private function clean(): void
     {
-        $this->currentUserModel = false;
-        $this->userRoles = false;
-        $this->isAdminUser = null;
+        $this->currentUserModel = null;
+        $this->userRoles = null;
     }
 }