]> BookStack Code Mirror - bookstack/blobdiff - app/Services/PermissionService.php
Updated 'Spanish Argentina' translation.
[bookstack] / app / Services / PermissionService.php
index 4f8b4e0f9d0fe2b1003b89fa4e7483730b4b9b88..0dd316b34a06e2c2fba24b36fd09befbb74a0bd2 100644 (file)
@@ -67,13 +67,19 @@ class PermissionService
 
     /**
      * Prepare the local entity cache and ensure it's empty
+     * @param Entity[] $entities
      */
-    protected function readyEntityCache()
+    protected function readyEntityCache($entities = [])
     {
-        $this->entityCache = [
-            'books' => collect(),
-            'chapters' => collect()
-        ];
+        $this->entityCache = [];
+
+        foreach ($entities as $entity) {
+            $type = $entity->getType();
+            if (!isset($this->entityCache[$type])) {
+                $this->entityCache[$type] = collect();
+            }
+            $this->entityCache[$type]->put($entity->id, $entity);
+        }
     }
 
     /**
@@ -83,14 +89,13 @@ class PermissionService
      */
     protected function getBook($bookId)
     {
-        if (isset($this->entityCache['books']) && $this->entityCache['books']->has($bookId)) {
-            return $this->entityCache['books']->get($bookId);
+        if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
+            return $this->entityCache['book']->get($bookId);
         }
 
         $book = $this->book->find($bookId);
-        if ($book === null) $book = false;
-        if (isset($this->entityCache['books'])) {
-            $this->entityCache['books']->put($bookId, $book);
+        if ($book === null) {
+            $book = false;
         }
 
         return $book;
@@ -103,14 +108,13 @@ class PermissionService
      */
     protected function getChapter($chapterId)
     {
-        if (isset($this->entityCache['chapters']) && $this->entityCache['chapters']->has($chapterId)) {
-            return $this->entityCache['chapters']->get($chapterId);
+        if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
+            return $this->entityCache['chapter']->get($chapterId);
         }
 
         $chapter = $this->chapter->find($chapterId);
-        if ($chapter === null) $chapter = false;
-        if (isset($this->entityCache['chapters'])) {
-            $this->entityCache['chapters']->put($chapterId, $chapter);
+        if ($chapter === null) {
+            $chapter = false;
         }
 
         return $chapter;
@@ -122,7 +126,9 @@ class PermissionService
      */
     protected function getRoles()
     {
-        if ($this->userRoles !== false) return $this->userRoles;
+        if ($this->userRoles !== false) {
+            return $this->userRoles;
+        }
 
         $roles = [];
 
@@ -161,9 +167,9 @@ class PermissionService
      */
     protected function bookFetchQuery()
     {
-        return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function($query) {
+        return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
             $query->select(['id', 'restricted', 'created_by', 'book_id']);
-        }, 'pages'  => function($query) {
+        }, 'pages'  => function ($query) {
             $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
         }]);
     }
@@ -173,8 +179,10 @@ class PermissionService
      * @param Collection $books
      * @param array $roles
      * @param bool $deleteOld
+     * @throws \Throwable
      */
-    protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false) {
+    protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
+    {
         $entities = clone $books;
 
         /** @var Book $book */
@@ -187,7 +195,9 @@ class PermissionService
             }
         }
 
-        if ($deleteOld) $this->deleteManyJointPermissionsForEntities($entities->all());
+        if ($deleteOld) {
+            $this->deleteManyJointPermissionsForEntities($entities->all());
+        }
         $this->createManyJointPermissions($entities, $roles);
     }
 
@@ -241,7 +251,7 @@ class PermissionService
         $this->deleteManyJointPermissionsForRoles($roles);
 
         // Chunk through all books
-        $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
+        $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
             $this->buildJointPermissionsForBooks($books, $roles);
         });
     }
@@ -261,7 +271,7 @@ class PermissionService
      */
     protected function deleteManyJointPermissionsForRoles($roles)
     {
-        $roleIds = array_map(function($role) {
+        $roleIds = array_map(function ($role) {
             return $role->id;
         }, $roles);
         $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
@@ -270,6 +280,7 @@ class PermissionService
     /**
      * Delete the entity jointPermissions for a particular entity.
      * @param Entity $entity
+     * @throws \Throwable
      */
     public function deleteJointPermissionsForEntity(Entity $entity)
     {
@@ -279,24 +290,26 @@ class PermissionService
     /**
      * Delete all of the entity jointPermissions for a list of entities.
      * @param Entity[] $entities
+     * @throws \Throwable
      */
     protected function deleteManyJointPermissionsForEntities($entities)
     {
-        if (count($entities) === 0) return;
+        if (count($entities) === 0) {
+            return;
+        }
 
-        $this->db->transaction(function() use ($entities) {
+        $this->db->transaction(function () use ($entities) {
 
             foreach (array_chunk($entities, 1000) as $entityChunk) {
                 $query = $this->db->table('joint_permissions');
                 foreach ($entityChunk as $entity) {
-                    $query->orWhere(function(QueryBuilder $query) use ($entity) {
+                    $query->orWhere(function (QueryBuilder $query) use ($entity) {
                         $query->where('entity_id', '=', $entity->id)
                             ->where('entity_type', '=', $entity->getMorphClass());
                     });
                 }
                 $query->delete();
             }
-
         });
     }
 
@@ -304,10 +317,11 @@ class PermissionService
      * Create & Save entity jointPermissions for many entities and jointPermissions.
      * @param Collection $entities
      * @param array $roles
+     * @throws \Throwable
      */
     protected function createManyJointPermissions($entities, $roles)
     {
-        $this->readyEntityCache();
+        $this->readyEntityCache($entities);
         $jointPermissions = [];
 
         // Fetch Entity Permissions and create a mapping of entity restricted statuses
@@ -315,7 +329,7 @@ class PermissionService
         $permissionFetch = $this->entityPermission->newQuery();
         foreach ($entities as $entity) {
             $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
-            $permissionFetch->orWhere(function($query) use ($entity) {
+            $permissionFetch->orWhere(function ($query) use ($entity) {
                 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
             });
         }
@@ -332,7 +346,7 @@ class PermissionService
         // Create a mapping of role permissions
         $rolePermissionMap = [];
         foreach ($roles as $role) {
-            foreach ($role->getRelationValue('permissions') as $permission) {
+            foreach ($role->permissions as $permission) {
                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
             }
         }
@@ -346,7 +360,7 @@ class PermissionService
             }
         }
 
-        $this->db->transaction(function() use ($jointPermissions) {
+        $this->db->transaction(function () use ($jointPermissions) {
             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
                 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
             }
@@ -362,8 +376,12 @@ class PermissionService
     protected function getActions(Entity $entity)
     {
         $baseActions = ['view', 'update', 'delete'];
-        if ($entity->isA('chapter') || $entity->isA('book')) $baseActions[] = 'page-create';
-        if ($entity->isA('book')) $baseActions[] = 'chapter-create';
+        if ($entity->isA('chapter') || $entity->isA('book')) {
+            $baseActions[] = 'page-create';
+        }
+        if ($entity->isA('book')) {
+            $baseActions[] = 'chapter-create';
+        }
         return $baseActions;
     }
 
@@ -412,7 +430,10 @@ class PermissionService
             }
         }
 
-        return $this->createJointPermissionDataArray($entity, $role, $action,
+        return $this->createJointPermissionDataArray(
+            $entity,
+            $role,
+            $action,
             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
         );
@@ -426,7 +447,8 @@ class PermissionService
      * @param $action
      * @return bool
      */
-    protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action) {
+    protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
+    {
         $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
         return isset($entityMap[$key]) ? $entityMap[$key] : false;
     }
@@ -545,11 +567,12 @@ class PermissionService
      * @param bool $fetchPageContent
      * @return QueryBuilder
      */
-    public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false) {
-        $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function($query) use ($filterDrafts) {
+    public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
+    {
+        $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
             $query->where('draft', '=', 0);
             if (!$filterDrafts) {
-                $query->orWhere(function($query) {
+                $query->orWhere(function ($query) {
                     $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
                 });
             }
@@ -562,8 +585,8 @@ class PermissionService
             $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) {
+                ->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);
                     });
                 });
@@ -611,16 +634,17 @@ class PermissionService
      * @param string $tableName
      * @param string $entityIdColumn
      * @param string $entityTypeColumn
+     * @param string $action
      * @return mixed
      */
-    public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn)
+    public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
     {
         if ($this->isAdmin()) {
             $this->clean();
             return $query;
         }
 
-        $this->currentAction = 'view';
+        $this->currentAction = $action;
         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
 
         $q = $query->where(function ($query) use ($tableDetails) {
@@ -715,5 +739,4 @@ class PermissionService
         $this->userRoles = false;
         $this->isAdminUser = null;
     }
-
-}
\ No newline at end of file
+}