]> BookStack Code Mirror - bookstack/blob - app/Permissions/JointPermissionBuilder.php
Perms: Fixed some issues made when adding transactions
[bookstack] / app / Permissions / JointPermissionBuilder.php
1 <?php
2
3 namespace BookStack\Permissions;
4
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Queries\EntityQueries;
11 use BookStack\Permissions\Models\JointPermission;
12 use BookStack\Users\Models\Role;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Eloquent\Collection as EloquentCollection;
15 use Illuminate\Support\Facades\DB;
16
17 /**
18  * Joint permissions provide a pre-query "cached" table of view permissions for all core entity
19  * types for all roles in the system. This class generates out that table for different scenarios.
20  */
21 class JointPermissionBuilder
22 {
23     public function __construct(
24         protected EntityQueries $queries,
25     ) {
26     }
27
28
29     /**
30      * Re-generate all entity permission from scratch.
31      */
32     public function rebuildForAll(): void
33     {
34         JointPermission::query()->truncate();
35
36         // Get all roles (Should be the most limited dimension)
37         $roles = Role::query()->with('permissions')->get()->all();
38
39         // Chunk through all books
40         $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
41             $this->buildJointPermissionsForBooks($books, $roles);
42         });
43
44         // Chunk through all bookshelves
45         $this->queries->shelves->start()->withTrashed()->select(['id', 'owned_by'])
46             ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
47                 $this->createManyJointPermissions($shelves->all(), $roles);
48             });
49     }
50
51     /**
52      * Rebuild the entity jointPermissions for a particular entity.
53      */
54     public function rebuildForEntity(Entity $entity): void
55     {
56         $entities = [$entity];
57         if ($entity instanceof Book) {
58             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
59             $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
60
61             return;
62         }
63
64         /** @var BookChild $entity */
65         if ($entity->book) {
66             $entities[] = $entity->book;
67         }
68
69         if ($entity instanceof Page && $entity->chapter_id) {
70             $entities[] = $entity->chapter;
71         }
72
73         if ($entity instanceof Chapter) {
74             foreach ($entity->pages as $page) {
75                 $entities[] = $page;
76             }
77         }
78
79         $this->buildJointPermissionsForEntities($entities);
80     }
81
82     /**
83      * Build the entity jointPermissions for a particular role.
84      */
85     public function rebuildForRole(Role $role)
86     {
87         $roles = [$role];
88         $role->jointPermissions()->delete();
89         $role->load('permissions');
90
91         // Chunk through all books
92         $this->bookFetchQuery()->chunk(10, function ($books) use ($roles) {
93             $this->buildJointPermissionsForBooks($books, $roles);
94         });
95
96         // Chunk through all bookshelves
97         $this->queries->shelves->start()->select(['id', 'owned_by'])
98             ->chunk(100, function ($shelves) use ($roles) {
99                 $this->createManyJointPermissions($shelves->all(), $roles);
100             });
101     }
102
103     /**
104      * Get a query for fetching a book with its children.
105      */
106     protected function bookFetchQuery(): Builder
107     {
108         return $this->queries->books->start()->withTrashed()
109             ->select(['id', 'owned_by'])->with([
110                 'chapters' => function ($query) {
111                     $query->withTrashed()->select(['id', 'owned_by', 'book_id']);
112                 },
113                 'pages' => function ($query) {
114                     $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
115                 },
116             ]);
117     }
118
119     /**
120      * Build joint permissions for the given book and role combinations.
121      */
122     protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false): void
123     {
124         $entities = clone $books;
125
126         /** @var Book $book */
127         foreach ($books->all() as $book) {
128             foreach ($book->getRelation('chapters') as $chapter) {
129                 $entities->push($chapter);
130             }
131             foreach ($book->getRelation('pages') as $page) {
132                 $entities->push($page);
133             }
134         }
135
136         if ($deleteOld) {
137             $this->deleteManyJointPermissionsForEntities($entities->all());
138         }
139
140         $this->createManyJointPermissions($entities->all(), $roles);
141     }
142
143     /**
144      * Rebuild the entity jointPermissions for a collection of entities.
145      */
146     protected function buildJointPermissionsForEntities(array $entities): void
147     {
148         $roles = Role::query()->get()->values()->all();
149         $this->deleteManyJointPermissionsForEntities($entities);
150         $this->createManyJointPermissions($entities, $roles);
151     }
152
153     /**
154      * Delete all the entity jointPermissions for a list of entities.
155      *
156      * @param Entity[] $entities
157      */
158     protected function deleteManyJointPermissionsForEntities(array $entities): void
159     {
160         $simpleEntities = $this->entitiesToSimpleEntities($entities);
161         $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
162
163         foreach ($idsByType as $type => $ids) {
164             foreach (array_chunk($ids, 1000) as $idChunk) {
165                 DB::table('joint_permissions')
166                     ->where('entity_type', '=', $type)
167                     ->whereIn('entity_id', $idChunk)
168                     ->delete();
169             }
170         }
171     }
172
173     /**
174      * @param Entity[] $entities
175      *
176      * @return SimpleEntityData[]
177      */
178     protected function entitiesToSimpleEntities(array $entities): array
179     {
180         $simpleEntities = [];
181
182         foreach ($entities as $entity) {
183             $simple = SimpleEntityData::fromEntity($entity);
184             $simpleEntities[] = $simple;
185         }
186
187         return $simpleEntities;
188     }
189
190     /**
191      * Create & Save entity jointPermissions for many entities and roles.
192      *
193      * @param Entity[] $originalEntities
194      * @param Role[]   $roles
195      */
196     protected function createManyJointPermissions(array $originalEntities, array $roles): void
197     {
198         $entities = $this->entitiesToSimpleEntities($originalEntities);
199         $jointPermissions = [];
200
201         // Fetch related entity permissions
202         $permissions = new MassEntityPermissionEvaluator($entities, 'view');
203
204         // Create a mapping of role permissions
205         $rolePermissionMap = [];
206         foreach ($roles as $role) {
207             foreach ($role->permissions as $permission) {
208                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
209             }
210         }
211
212         // Create Joint Permission Data
213         foreach ($entities as $entity) {
214             foreach ($roles as $role) {
215                 $jp = $this->createJointPermissionData(
216                     $entity,
217                     $role->getRawAttribute('id'),
218                     $permissions,
219                     $rolePermissionMap,
220                     $role->system_name === 'admin'
221                 );
222                 $jointPermissions[] = $jp;
223             }
224         }
225
226         foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
227             DB::table('joint_permissions')->insert($jointPermissionChunk);
228         }
229     }
230
231     /**
232      * From the given entity list, provide back a mapping of entity types to
233      * the ids of that given type. The type used is the DB morph class.
234      *
235      * @param SimpleEntityData[] $entities
236      *
237      * @return array<string, int[]>
238      */
239     protected function entitiesToTypeIdMap(array $entities): array
240     {
241         $idsByType = [];
242
243         foreach ($entities as $entity) {
244             if (!isset($idsByType[$entity->type])) {
245                 $idsByType[$entity->type] = [];
246             }
247
248             $idsByType[$entity->type][] = $entity->id;
249         }
250
251         return $idsByType;
252     }
253
254     /**
255      * Create entity permission data for an entity and role
256      * for a particular action.
257      */
258     protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, MassEntityPermissionEvaluator $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
259     {
260         // Ensure system admin role retains permissions
261         if ($isAdminRole) {
262             return $this->createJointPermissionDataArray($entity, $roleId, PermissionStatus::EXPLICIT_ALLOW, true);
263         }
264
265         // Return evaluated entity permission status if it has an affect.
266         $entityPermissionStatus = $permissionMap->evaluateEntityForRole($entity, $roleId);
267         if ($entityPermissionStatus !== null) {
268             return $this->createJointPermissionDataArray($entity, $roleId, $entityPermissionStatus, false);
269         }
270
271         // Otherwise default to the role-level permissions
272         $permissionPrefix = $entity->type . '-view';
273         $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
274         $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
275         $status = $roleHasPermission ? PermissionStatus::IMPLICIT_ALLOW : PermissionStatus::IMPLICIT_DENY;
276         return $this->createJointPermissionDataArray($entity, $roleId, $status, $roleHasPermissionOwn);
277     }
278
279     /**
280      * Create an array of data with the information of an entity jointPermissions.
281      * Used to build data for bulk insertion.
282      */
283     protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, int $permissionStatus, bool $hasPermissionOwn): array
284     {
285         $ownPermissionActive = ($hasPermissionOwn && $permissionStatus !== PermissionStatus::EXPLICIT_DENY && $entity->owned_by);
286
287         return [
288             'entity_id'   => $entity->id,
289             'entity_type' => $entity->type,
290             'role_id'     => $roleId,
291             'status'      => $permissionStatus,
292             'owner_id'    => $ownPermissionActive ? $entity->owned_by : null,
293         ];
294     }
295 }