]> BookStack Code Mirror - bookstack/blob - app/Permissions/JointPermissionBuilder.php
Opensearch: Fixed XML declaration when php short tags enabled
[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()
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)
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)
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)
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)
159     {
160         $simpleEntities = $this->entitiesToSimpleEntities($entities);
161         $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
162
163         DB::transaction(function () use ($idsByType) {
164             foreach ($idsByType as $type => $ids) {
165                 foreach (array_chunk($ids, 1000) as $idChunk) {
166                     DB::table('joint_permissions')
167                         ->where('entity_type', '=', $type)
168                         ->whereIn('entity_id', $idChunk)
169                         ->delete();
170                 }
171             }
172         });
173     }
174
175     /**
176      * @param Entity[] $entities
177      *
178      * @return SimpleEntityData[]
179      */
180     protected function entitiesToSimpleEntities(array $entities): array
181     {
182         $simpleEntities = [];
183
184         foreach ($entities as $entity) {
185             $simple = SimpleEntityData::fromEntity($entity);
186             $simpleEntities[] = $simple;
187         }
188
189         return $simpleEntities;
190     }
191
192     /**
193      * Create & Save entity jointPermissions for many entities and roles.
194      *
195      * @param Entity[] $originalEntities
196      * @param Role[]   $roles
197      */
198     protected function createManyJointPermissions(array $originalEntities, array $roles)
199     {
200         $entities = $this->entitiesToSimpleEntities($originalEntities);
201         $jointPermissions = [];
202
203         // Fetch related entity permissions
204         $permissions = new MassEntityPermissionEvaluator($entities, 'view');
205
206         // Create a mapping of role permissions
207         $rolePermissionMap = [];
208         foreach ($roles as $role) {
209             foreach ($role->permissions as $permission) {
210                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
211             }
212         }
213
214         // Create Joint Permission Data
215         foreach ($entities as $entity) {
216             foreach ($roles as $role) {
217                 $jp = $this->createJointPermissionData(
218                     $entity,
219                     $role->getRawAttribute('id'),
220                     $permissions,
221                     $rolePermissionMap,
222                     $role->system_name === 'admin'
223                 );
224                 $jointPermissions[] = $jp;
225             }
226         }
227
228         DB::transaction(function () use ($jointPermissions) {
229             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
230                 DB::table('joint_permissions')->insert($jointPermissionChunk);
231             }
232         });
233     }
234
235     /**
236      * From the given entity list, provide back a mapping of entity types to
237      * the ids of that given type. The type used is the DB morph class.
238      *
239      * @param SimpleEntityData[] $entities
240      *
241      * @return array<string, int[]>
242      */
243     protected function entitiesToTypeIdMap(array $entities): array
244     {
245         $idsByType = [];
246
247         foreach ($entities as $entity) {
248             if (!isset($idsByType[$entity->type])) {
249                 $idsByType[$entity->type] = [];
250             }
251
252             $idsByType[$entity->type][] = $entity->id;
253         }
254
255         return $idsByType;
256     }
257
258     /**
259      * Create entity permission data for an entity and role
260      * for a particular action.
261      */
262     protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, MassEntityPermissionEvaluator $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
263     {
264         // Ensure system admin role retains permissions
265         if ($isAdminRole) {
266             return $this->createJointPermissionDataArray($entity, $roleId, PermissionStatus::EXPLICIT_ALLOW, true);
267         }
268
269         // Return evaluated entity permission status if it has an affect.
270         $entityPermissionStatus = $permissionMap->evaluateEntityForRole($entity, $roleId);
271         if ($entityPermissionStatus !== null) {
272             return $this->createJointPermissionDataArray($entity, $roleId, $entityPermissionStatus, false);
273         }
274
275         // Otherwise default to the role-level permissions
276         $permissionPrefix = $entity->type . '-view';
277         $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
278         $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
279         $status = $roleHasPermission ? PermissionStatus::IMPLICIT_ALLOW : PermissionStatus::IMPLICIT_DENY;
280         return $this->createJointPermissionDataArray($entity, $roleId, $status, $roleHasPermissionOwn);
281     }
282
283     /**
284      * Create an array of data with the information of an entity jointPermissions.
285      * Used to build data for bulk insertion.
286      */
287     protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, int $permissionStatus, bool $hasPermissionOwn): array
288     {
289         $ownPermissionActive = ($hasPermissionOwn && $permissionStatus !== PermissionStatus::EXPLICIT_DENY && $entity->owned_by);
290
291         return [
292             'entity_id'   => $entity->id,
293             'entity_type' => $entity->type,
294             'role_id'     => $roleId,
295             'status'      => $permissionStatus,
296             'owner_id'    => $ownPermissionActive ? $entity->owned_by : null,
297         ];
298     }
299 }