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