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