]> BookStack Code Mirror - bookstack/blobdiff - app/Services/PermissionService.php
Updated Spanish translation
[bookstack] / app / Services / PermissionService.php
index 35e5640d63ccffce6c51aac1ac8a0b9392abed22..331ed06c87e10e8e96fb098f63a0fd714eb4ce9e 100644 (file)
@@ -11,8 +11,8 @@ use BookStack\Role;
 use BookStack\User;
 use Illuminate\Database\Connection;
 use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Query\Builder as QueryBuilder;
 use Illuminate\Support\Collection;
-use Illuminate\Support\Facades\Log;
 
 class PermissionService
 {
@@ -56,6 +56,15 @@ class PermissionService
         // TODO - Update so admin still goes through filters
     }
 
+    /**
+     * Set the database connection
+     * @param Connection $connection
+     */
+    public function setConnection(Connection $connection)
+    {
+        $this->db = $connection;
+    }
+
     /**
      * Prepare the local entity cache and ensure it's empty
      */
@@ -79,7 +88,9 @@ class PermissionService
         }
 
         $book = $this->book->find($bookId);
-        if ($book === null) $book = false;
+        if ($book === null) {
+            $book = false;
+        }
         if (isset($this->entityCache['books'])) {
             $this->entityCache['books']->put($bookId, $book);
         }
@@ -99,7 +110,9 @@ class PermissionService
         }
 
         $chapter = $this->chapter->find($chapterId);
-        if ($chapter === null) $chapter = false;
+        if ($chapter === null) {
+            $chapter = false;
+        }
         if (isset($this->entityCache['chapters'])) {
             $this->entityCache['chapters']->put($chapterId, $chapter);
         }
@@ -113,7 +126,9 @@ class PermissionService
      */
     protected function getRoles()
     {
-        if ($this->userRoles !== false) return $this->userRoles;
+        if ($this->userRoles !== false) {
+            return $this->userRoles;
+        }
 
         $roles = [];
 
@@ -138,33 +153,50 @@ class PermissionService
         $this->readyEntityCache();
 
         // Get all roles (Should be the most limited dimension)
-        $roles = $this->role->with('permissions')->get();
+        $roles = $this->role->with('permissions')->get()->all();
 
         // Chunk through all books
-        $this->book->newQuery()->with('chapters', 'pages')->chunk(5, function ($books) use ($roles) {
+        $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
             $this->buildJointPermissionsForBooks($books, $roles);
         });
     }
 
+    /**
+     * Get a query for fetching a book with it's children.
+     * @return QueryBuilder
+     */
+    protected function bookFetchQuery()
+    {
+        return $this->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']);
+        }]);
+    }
+
     /**
      * Build joint permissions for an array of books
      * @param Collection $books
-     * @param Collection $roles
+     * @param array $roles
      * @param bool $deleteOld
      */
-    protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false) {
+    protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
+    {
         $entities = clone $books;
 
-        foreach ($books as $book) {
-            foreach ($book->chapters as $chapter) {
+        /** @var Book $book */
+        foreach ($books->all() as $book) {
+            foreach ($book->getRelation('chapters') as $chapter) {
                 $entities->push($chapter);
             }
-            foreach ($book->pages as $page) {
+            foreach ($book->getRelation('pages') as $page) {
                 $entities->push($page);
             }
         }
 
-        if ($deleteOld) $this->deleteManyJointPermissionsForEntities($entities->all());
+        if ($deleteOld) {
+            $this->deleteManyJointPermissionsForEntities($entities->all());
+        }
         $this->createManyJointPermissions($entities, $roles);
     }
 
@@ -174,9 +206,27 @@ class PermissionService
      */
     public function buildJointPermissionsForEntity(Entity $entity)
     {
-        $roles = $this->role->newQuery()->get();
-        $book = ($entity->isA('book')) ? $entity : $entity->book;
-        $this->buildJointPermissionsForBooks(collect([$book]), $roles, true);
+        $entities = [$entity];
+        if ($entity->isA('book')) {
+            $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
+            $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
+            return;
+        }
+
+        $entities[] = $entity->book;
+
+        if ($entity->isA('page') && $entity->chapter_id) {
+            $entities[] = $entity->chapter;
+        }
+
+        if ($entity->isA('chapter')) {
+            foreach ($entity->pages as $page) {
+                $entities[] = $page;
+            }
+        }
+
+        $this->deleteManyJointPermissionsForEntities($entities);
+        $this->buildJointPermissionsForEntities(collect($entities));
     }
 
     /**
@@ -185,7 +235,7 @@ class PermissionService
      */
     public function buildJointPermissionsForEntities(Collection $entities)
     {
-        $roles = $this->role->get();
+        $roles = $this->role->newQuery()->get();
         $this->deleteManyJointPermissionsForEntities($entities->all());
         $this->createManyJointPermissions($entities, $roles);
     }
@@ -196,12 +246,11 @@ class PermissionService
      */
     public function buildJointPermissionForRole(Role $role)
     {
-        $roles = collect([$role]);
-
+        $roles = [$role];
         $this->deleteManyJointPermissionsForRoles($roles);
 
         // Chunk through all books
-        $this->book->with('chapters', 'pages')->chunk(5, function ($books) use ($roles) {
+        $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
             $this->buildJointPermissionsForBooks($books, $roles);
         });
     }
@@ -221,9 +270,10 @@ class PermissionService
      */
     protected function deleteManyJointPermissionsForRoles($roles)
     {
-        foreach ($roles as $role) {
-            $role->jointPermissions()->delete();
-        }
+        $roleIds = array_map(function ($role) {
+            return $role->id;
+        }, $roles);
+        $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
     }
 
     /**
@@ -241,23 +291,29 @@ class PermissionService
      */
     protected function deleteManyJointPermissionsForEntities($entities)
     {
-        if (count($entities) === 0) return;
-        $query = $this->jointPermission->newQuery();
-
-        foreach ($entities as $entity) {
-            $query->orWhere(function($query) use ($entity) {
-                $query->where('entity_id', '=', $entity->id)
-                    ->where('entity_type', '=', $entity->getMorphClass());
-            });
+        if (count($entities) === 0) {
+            return;
         }
 
-        $query->delete();
+        $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->where('entity_id', '=', $entity->id)
+                            ->where('entity_type', '=', $entity->getMorphClass());
+                    });
+                }
+                $query->delete();
+            }
+        });
     }
 
     /**
      * Create & Save entity jointPermissions for many entities and jointPermissions.
      * @param Collection $entities
-     * @param Collection $roles
+     * @param array $roles
      */
     protected function createManyJointPermissions($entities, $roles)
     {
@@ -269,7 +325,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());
             });
         }
@@ -299,9 +355,12 @@ class PermissionService
                 }
             }
         }
-        foreach (array_chunk($jointPermissions, 5000) as $jointPermissionChunk) {
-            $this->jointPermission->insert($jointPermissionChunk);
-        }
+
+        $this->db->transaction(function () use ($jointPermissions) {
+            foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
+                $this->db->table('joint_permissions')->insert($jointPermissionChunk);
+            }
+        });
     }
 
 
@@ -313,8 +372,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;
     }
 
@@ -355,7 +418,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) {
+        if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
             $chapter = $this->getChapter($entity->chapter_id);
             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
             if ($chapter->restricted) {
@@ -363,7 +426,10 @@ class PermissionService
             }
         }
 
-        return $this->createJointPermissionDataArray($entity, $role, $action,
+        return $this->createJointPermissionDataArray(
+            $entity,
+            $role,
+            $action,
             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
         );
@@ -377,7 +443,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;
     }
@@ -424,7 +491,7 @@ class PermissionService
         $action = end($explodedPermission);
         $this->currentAction = $action;
 
-        $nonJointPermissions = ['restrictions', 'image', 'attachment'];
+        $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
 
         // Handle non entity specific jointPermissions
         if (in_array($explodedPermission[0], $nonJointPermissions)) {
@@ -494,13 +561,14 @@ class PermissionService
      * @param integer $book_id
      * @param bool $filterDrafts
      * @param bool $fetchPageContent
-     * @return \Illuminate\Database\Query\Builder
+     * @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);
                 });
             }
@@ -513,8 +581,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);
                     });
                 });
@@ -666,5 +734,4 @@ class PermissionService
         $this->userRoles = false;
         $this->isAdminUser = null;
     }
-
-}
\ No newline at end of file
+}