]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/JointPermissionBuilder.php
Merge pull request #3556 from GongMingCai/development
[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 $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', 'restricted', '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', 'restricted', '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', 'restricted', 'owned_by'])->with([
142                 'chapters' => function ($query) {
143                     $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
144                 },
145                 'pages' => function ($query) {
146                     $query->withTrashed()->select(['id', 'restricted', '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->restricted = boolval($attrs['restricted'] ?? 0);
222             $simple->owned_by = $attrs['owned_by'] ?? 0;
223             $simple->book_id = $attrs['book_id'] ?? null;
224             $simple->chapter_id = $attrs['chapter_id'] ?? null;
225             $simpleEntities[] = $simple;
226         }
227
228         return $simpleEntities;
229     }
230
231     /**
232      * Create & Save entity jointPermissions for many entities and roles.
233      *
234      * @param Entity[] $entities
235      * @param Role[]   $roles
236      */
237     protected function createManyJointPermissions(array $originalEntities, array $roles)
238     {
239         $entities = $this->entitiesToSimpleEntities($originalEntities);
240         $this->readyEntityCache($entities);
241         $jointPermissions = [];
242
243         // Create a mapping of entity restricted statuses
244         $entityRestrictedMap = [];
245         foreach ($entities as $entity) {
246             $entityRestrictedMap[$entity->type . ':' . $entity->id] = $entity->restricted;
247         }
248
249         // Fetch related entity permissions
250         $permissions = $this->getEntityPermissionsForEntities($entities);
251
252         // Create a mapping of explicit entity permissions
253         $permissionMap = [];
254         foreach ($permissions as $permission) {
255             $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id;
256             $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
257             $permissionMap[$key] = $isRestricted;
258         }
259
260         // Create a mapping of role permissions
261         $rolePermissionMap = [];
262         foreach ($roles as $role) {
263             foreach ($role->permissions as $permission) {
264                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
265             }
266         }
267
268         // Create Joint Permission Data
269         foreach ($entities as $entity) {
270             foreach ($roles as $role) {
271                 $jointPermissions[] = $this->createJointPermissionData(
272                     $entity,
273                     $role->getRawAttribute('id'),
274                     $permissionMap,
275                     $rolePermissionMap,
276                     $role->system_name === 'admin'
277                 );
278             }
279         }
280
281         DB::transaction(function () use ($jointPermissions) {
282             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
283                 DB::table('joint_permissions')->insert($jointPermissionChunk);
284             }
285         });
286     }
287
288     /**
289      * From the given entity list, provide back a mapping of entity types to
290      * the ids of that given type. The type used is the DB morph class.
291      *
292      * @param SimpleEntityData[] $entities
293      *
294      * @return array<string, int[]>
295      */
296     protected function entitiesToTypeIdMap(array $entities): array
297     {
298         $idsByType = [];
299
300         foreach ($entities as $entity) {
301             if (!isset($idsByType[$entity->type])) {
302                 $idsByType[$entity->type] = [];
303             }
304
305             $idsByType[$entity->type][] = $entity->id;
306         }
307
308         return $idsByType;
309     }
310
311     /**
312      * Get the entity permissions for all the given entities.
313      *
314      * @param SimpleEntityData[] $entities
315      *
316      * @return EntityPermission[]
317      */
318     protected function getEntityPermissionsForEntities(array $entities): array
319     {
320         $idsByType = $this->entitiesToTypeIdMap($entities);
321         $permissionFetch = EntityPermission::query()
322             ->where('action', '=', 'view')
323             ->where(function (Builder $query) use ($idsByType) {
324                 foreach ($idsByType as $type => $ids) {
325                     $query->orWhere(function (Builder $query) use ($type, $ids) {
326                         $query->where('restrictable_type', '=', $type)->whereIn('restrictable_id', $ids);
327                     });
328                 }
329             });
330
331         return $permissionFetch->get()->all();
332     }
333
334     /**
335      * Create entity permission data for an entity and role
336      * for a particular action.
337      */
338     protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, array $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
339     {
340         $permissionPrefix = $entity->type . '-view';
341         $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
342         $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
343
344         if ($isAdminRole) {
345             return $this->createJointPermissionDataArray($entity, $roleId, true, true);
346         }
347
348         if ($entity->restricted) {
349             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $roleId);
350
351             return $this->createJointPermissionDataArray($entity, $roleId, $hasAccess, $hasAccess);
352         }
353
354         if ($entity->type === 'book' || $entity->type === 'bookshelf') {
355             return $this->createJointPermissionDataArray($entity, $roleId, $roleHasPermission, $roleHasPermissionOwn);
356         }
357
358         // For chapters and pages, Check if explicit permissions are set on the Book.
359         $book = $this->getBook($entity->book_id);
360         $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $roleId);
361         $hasPermissiveAccessToParents = !$book->restricted;
362
363         // For pages with a chapter, Check if explicit permissions are set on the Chapter
364         if ($entity->type === 'page' && $entity->chapter_id !== 0) {
365             $chapter = $this->getChapter($entity->chapter_id);
366             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
367             if ($chapter->restricted) {
368                 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $roleId);
369             }
370         }
371
372         return $this->createJointPermissionDataArray(
373             $entity,
374             $roleId,
375             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
376             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
377         );
378     }
379
380     /**
381      * Check for an active restriction in an entity map.
382      */
383     protected function mapHasActiveRestriction(array $entityMap, SimpleEntityData $entity, int $roleId): bool
384     {
385         $key = $entity->type . ':' . $entity->id . ':' . $roleId;
386
387         return $entityMap[$key] ?? false;
388     }
389
390     /**
391      * Create an array of data with the information of an entity jointPermissions.
392      * Used to build data for bulk insertion.
393      */
394     protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, bool $permissionAll, bool $permissionOwn): array
395     {
396         return [
397             'entity_id'          => $entity->id,
398             'entity_type'        => $entity->type,
399             'has_permission'     => $permissionAll,
400             'has_permission_own' => $permissionOwn,
401             'owned_by'           => $entity->owned_by,
402             'role_id'            => $roleId,
403         ];
404     }
405 }