]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/JointPermissionBuilder.php
Addressed additional unsupported array spread operation
[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      * @var array<string, array<int, SimpleEntityData>>
24      */
25     protected array $entityCache;
26
27     /**
28      * Re-generate all entity permission from scratch.
29      */
30     public function rebuildForAll()
31     {
32         JointPermission::query()->truncate();
33
34         // Get all roles (Should be the most limited dimension)
35         $roles = Role::query()->with('permissions')->get()->all();
36
37         // Chunk through all books
38         $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
39             $this->buildJointPermissionsForBooks($books, $roles);
40         });
41
42         // Chunk through all bookshelves
43         Bookshelf::query()->withTrashed()->select(['id', 'owned_by'])
44             ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
45                 $this->createManyJointPermissions($shelves->all(), $roles);
46             });
47     }
48
49     /**
50      * Rebuild the entity jointPermissions for a particular entity.
51      */
52     public function rebuildForEntity(Entity $entity)
53     {
54         $entities = [$entity];
55         if ($entity instanceof Book) {
56             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
57             $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
58
59             return;
60         }
61
62         /** @var BookChild $entity */
63         if ($entity->book) {
64             $entities[] = $entity->book;
65         }
66
67         if ($entity instanceof Page && $entity->chapter_id) {
68             $entities[] = $entity->chapter;
69         }
70
71         if ($entity instanceof Chapter) {
72             foreach ($entity->pages as $page) {
73                 $entities[] = $page;
74             }
75         }
76
77         $this->buildJointPermissionsForEntities($entities);
78     }
79
80     /**
81      * Build the entity jointPermissions for a particular role.
82      */
83     public function rebuildForRole(Role $role)
84     {
85         $roles = [$role];
86         $role->jointPermissions()->delete();
87         $role->load('permissions');
88
89         // Chunk through all books
90         $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
91             $this->buildJointPermissionsForBooks($books, $roles);
92         });
93
94         // Chunk through all bookshelves
95         Bookshelf::query()->select(['id', 'owned_by'])
96             ->chunk(50, function ($shelves) use ($roles) {
97                 $this->createManyJointPermissions($shelves->all(), $roles);
98             });
99     }
100
101     /**
102      * Prepare the local entity cache and ensure it's empty.
103      *
104      * @param SimpleEntityData[] $entities
105      */
106     protected function readyEntityCache(array $entities)
107     {
108         $this->entityCache = [];
109
110         foreach ($entities as $entity) {
111             if (!isset($this->entityCache[$entity->type])) {
112                 $this->entityCache[$entity->type] = [];
113             }
114
115             $this->entityCache[$entity->type][$entity->id] = $entity;
116         }
117     }
118
119     /**
120      * Get a book via ID, Checks local cache.
121      */
122     protected function getBook(int $bookId): SimpleEntityData
123     {
124         return $this->entityCache['book'][$bookId];
125     }
126
127     /**
128      * Get a chapter via ID, Checks local cache.
129      */
130     protected function getChapter(int $chapterId): SimpleEntityData
131     {
132         return $this->entityCache['chapter'][$chapterId];
133     }
134
135     /**
136      * Get a query for fetching a book with its children.
137      */
138     protected function bookFetchQuery(): Builder
139     {
140         return Book::query()->withTrashed()
141             ->select(['id', 'owned_by'])->with([
142                 'chapters' => function ($query) {
143                     $query->withTrashed()->select(['id', 'owned_by', 'book_id']);
144                 },
145                 'pages' => function ($query) {
146                     $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
147                 },
148             ]);
149     }
150
151     /**
152      * Build joint permissions for the given book and role combinations.
153      */
154     protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
155     {
156         $entities = clone $books;
157
158         /** @var Book $book */
159         foreach ($books->all() as $book) {
160             foreach ($book->getRelation('chapters') as $chapter) {
161                 $entities->push($chapter);
162             }
163             foreach ($book->getRelation('pages') as $page) {
164                 $entities->push($page);
165             }
166         }
167
168         if ($deleteOld) {
169             $this->deleteManyJointPermissionsForEntities($entities->all());
170         }
171
172         $this->createManyJointPermissions($entities->all(), $roles);
173     }
174
175     /**
176      * Rebuild the entity jointPermissions for a collection of entities.
177      */
178     protected function buildJointPermissionsForEntities(array $entities)
179     {
180         $roles = Role::query()->get()->values()->all();
181         $this->deleteManyJointPermissionsForEntities($entities);
182         $this->createManyJointPermissions($entities, $roles);
183     }
184
185     /**
186      * Delete all the entity jointPermissions for a list of entities.
187      *
188      * @param Entity[] $entities
189      */
190     protected function deleteManyJointPermissionsForEntities(array $entities)
191     {
192         $simpleEntities = $this->entitiesToSimpleEntities($entities);
193         $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
194
195         DB::transaction(function () use ($idsByType) {
196             foreach ($idsByType as $type => $ids) {
197                 foreach (array_chunk($ids, 1000) as $idChunk) {
198                     DB::table('joint_permissions')
199                         ->where('entity_type', '=', $type)
200                         ->whereIn('entity_id', $idChunk)
201                         ->delete();
202                 }
203             }
204         });
205     }
206
207     /**
208      * @param Entity[] $entities
209      *
210      * @return SimpleEntityData[]
211      */
212     protected function entitiesToSimpleEntities(array $entities): array
213     {
214         $simpleEntities = [];
215
216         foreach ($entities as $entity) {
217             $attrs = $entity->getAttributes();
218             $simple = new SimpleEntityData();
219             $simple->id = $attrs['id'];
220             $simple->type = $entity->getMorphClass();
221             $simple->owned_by = $attrs['owned_by'] ?? 0;
222             $simple->book_id = $attrs['book_id'] ?? null;
223             $simple->chapter_id = $attrs['chapter_id'] ?? null;
224             $simpleEntities[] = $simple;
225         }
226
227         return $simpleEntities;
228     }
229
230     /**
231      * Create & Save entity jointPermissions for many entities and roles.
232      *
233      * @param Entity[] $originalEntities
234      * @param Role[]   $roles
235      */
236     protected function createManyJointPermissions(array $originalEntities, array $roles)
237     {
238         $entities = $this->entitiesToSimpleEntities($originalEntities);
239         $this->readyEntityCache($entities);
240         $jointPermissions = [];
241
242         // Fetch related entity permissions
243         $permissions = $this->getEntityPermissionsForEntities($entities);
244
245         // Create a mapping of explicit entity permissions
246         $permissionMap = [];
247         foreach ($permissions as $permission) {
248             $key = $permission->entity_type . ':' . $permission->entity_id . ':' . $permission->role_id;
249             $permissionMap[$key] = $permission->view;
250         }
251
252         // Create a mapping of role permissions
253         $rolePermissionMap = [];
254         foreach ($roles as $role) {
255             foreach ($role->permissions as $permission) {
256                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
257             }
258         }
259
260         // Create Joint Permission Data
261         foreach ($entities as $entity) {
262             foreach ($roles as $role) {
263                 $jointPermissions[] = $this->createJointPermissionData(
264                     $entity,
265                     $role->getRawAttribute('id'),
266                     $permissionMap,
267                     $rolePermissionMap,
268                     $role->system_name === 'admin'
269                 );
270             }
271         }
272
273         DB::transaction(function () use ($jointPermissions) {
274             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
275                 DB::table('joint_permissions')->insert($jointPermissionChunk);
276             }
277         });
278     }
279
280     /**
281      * From the given entity list, provide back a mapping of entity types to
282      * the ids of that given type. The type used is the DB morph class.
283      *
284      * @param SimpleEntityData[] $entities
285      *
286      * @return array<string, int[]>
287      */
288     protected function entitiesToTypeIdMap(array $entities): array
289     {
290         $idsByType = [];
291
292         foreach ($entities as $entity) {
293             if (!isset($idsByType[$entity->type])) {
294                 $idsByType[$entity->type] = [];
295             }
296
297             $idsByType[$entity->type][] = $entity->id;
298         }
299
300         return $idsByType;
301     }
302
303     /**
304      * Get the entity permissions for all the given entities.
305      *
306      * @param SimpleEntityData[] $entities
307      *
308      * @return EntityPermission[]
309      */
310     protected function getEntityPermissionsForEntities(array $entities): array
311     {
312         $idsByType = $this->entitiesToTypeIdMap($entities);
313         $permissionFetch = EntityPermission::query()
314             ->where(function (Builder $query) use ($idsByType) {
315                 foreach ($idsByType as $type => $ids) {
316                     $query->orWhere(function (Builder $query) use ($type, $ids) {
317                         $query->where('entity_type', '=', $type)->whereIn('entity_id', $ids);
318                     });
319                 }
320             });
321
322         return $permissionFetch->get()->all();
323     }
324
325     /**
326      * Create entity permission data for an entity and role
327      * for a particular action.
328      */
329     protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, array $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
330     {
331         $permissionPrefix = $entity->type . '-view';
332         $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
333         $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
334
335         if ($isAdminRole) {
336             return $this->createJointPermissionDataArray($entity, $roleId, true, true);
337         }
338
339         if ($this->entityPermissionsActiveForRole($permissionMap, $entity, $roleId)) {
340             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $roleId);
341
342             return $this->createJointPermissionDataArray($entity, $roleId, $hasAccess, $hasAccess);
343         }
344
345         if ($entity->type === 'book' || $entity->type === 'bookshelf') {
346             return $this->createJointPermissionDataArray($entity, $roleId, $roleHasPermission, $roleHasPermissionOwn);
347         }
348
349         // For chapters and pages, Check if explicit permissions are set on the Book.
350         $book = $this->getBook($entity->book_id);
351         $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $roleId);
352         $hasPermissiveAccessToParents = !$this->entityPermissionsActiveForRole($permissionMap, $book, $roleId);
353
354         // For pages with a chapter, Check if explicit permissions are set on the Chapter
355         if ($entity->type === 'page' && $entity->chapter_id !== 0) {
356             $chapter = $this->getChapter($entity->chapter_id);
357             $chapterRestricted = $this->entityPermissionsActiveForRole($permissionMap, $chapter, $roleId);
358             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapterRestricted;
359             if ($chapterRestricted) {
360                 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $roleId);
361             }
362         }
363
364         return $this->createJointPermissionDataArray(
365             $entity,
366             $roleId,
367             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
368             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
369         );
370     }
371
372     /**
373      * Check if entity permissions are defined within the given map, for the given entity and role.
374      * Checks for the default `role_id=0` backup option as a fallback.
375      */
376     protected function entityPermissionsActiveForRole(array $permissionMap, SimpleEntityData $entity, int $roleId): bool
377     {
378         $keyPrefix = $entity->type . ':' . $entity->id . ':';
379         return isset($permissionMap[$keyPrefix . $roleId]) || isset($permissionMap[$keyPrefix . '0']);
380     }
381
382     /**
383      * Check for an active restriction in an entity map.
384      */
385     protected function mapHasActiveRestriction(array $entityMap, SimpleEntityData $entity, int $roleId): bool
386     {
387         $roleKey = $entity->type . ':' . $entity->id . ':' . $roleId;
388         $defaultKey = $entity->type . ':' . $entity->id . ':0';
389
390         return $entityMap[$roleKey] ?? $entityMap[$defaultKey] ?? false;
391     }
392
393     /**
394      * Create an array of data with the information of an entity jointPermissions.
395      * Used to build data for bulk insertion.
396      */
397     protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, bool $permissionAll, bool $permissionOwn): array
398     {
399         return [
400             'entity_id'          => $entity->id,
401             'entity_type'        => $entity->type,
402             'has_permission'     => $permissionAll,
403             'has_permission_own' => $permissionOwn,
404             'owned_by'           => $entity->owned_by,
405             'role_id'            => $roleId,
406         ];
407     }
408 }