3 namespace BookStack\Auth\Permissions;
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;
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.
20 class JointPermissionBuilder
23 * @var array<string, array<int, SimpleEntityData>>
25 protected array $entityCache;
28 * Re-generate all entity permission from scratch.
30 public function rebuildForAll()
32 JointPermission::query()->truncate();
33 JointUserPermission::query()->truncate();
35 // Get all roles (Should be the most limited dimension)
36 $roles = Role::query()->with('permissions')->get()->all();
38 // Chunk through all books
39 $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
40 $this->buildJointPermissionsForBooks($books, $roles);
43 // Chunk through all bookshelves
44 Bookshelf::query()->withTrashed()->select(['id', 'owned_by'])
45 ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
46 $this->createManyJointPermissions($shelves->all(), $roles);
51 * Rebuild the entity jointPermissions for a particular entity.
53 public function rebuildForEntity(Entity $entity)
55 $entities = [$entity];
56 if ($entity instanceof Book) {
57 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
58 $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
63 /** @var BookChild $entity */
65 $entities[] = $entity->book;
68 if ($entity instanceof Page && $entity->chapter_id) {
69 $entities[] = $entity->chapter;
72 if ($entity instanceof Chapter) {
73 foreach ($entity->pages as $page) {
78 $this->buildJointPermissionsForEntities($entities);
82 * Build the entity jointPermissions for a particular role.
84 public function rebuildForRole(Role $role)
87 $role->jointPermissions()->delete();
88 $role->load('permissions');
90 // Chunk through all books
91 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
92 $this->buildJointPermissionsForBooks($books, $roles);
95 // Chunk through all bookshelves
96 Bookshelf::query()->select(['id', 'owned_by'])
97 ->chunk(50, function ($shelves) use ($roles) {
98 $this->createManyJointPermissions($shelves->all(), $roles);
103 * Prepare the local entity cache and ensure it's empty.
105 * @param SimpleEntityData[] $entities
107 protected function readyEntityCache(array $entities)
109 $this->entityCache = [];
111 foreach ($entities as $entity) {
112 if (!isset($this->entityCache[$entity->type])) {
113 $this->entityCache[$entity->type] = [];
116 $this->entityCache[$entity->type][$entity->id] = $entity;
121 * Get a book via ID, Checks local cache.
123 protected function getBook(int $bookId): SimpleEntityData
125 return $this->entityCache['book'][$bookId];
129 * Get a chapter via ID, Checks local cache.
131 protected function getChapter(int $chapterId): SimpleEntityData
133 return $this->entityCache['chapter'][$chapterId];
137 * Get a query for fetching a book with its children.
139 protected function bookFetchQuery(): Builder
141 return Book::query()->withTrashed()
142 ->select(['id', 'owned_by'])->with([
143 'chapters' => function ($query) {
144 $query->withTrashed()->select(['id', 'owned_by', 'book_id']);
146 'pages' => function ($query) {
147 $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
153 * Build joint permissions for the given book and role combinations.
155 protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
157 $entities = clone $books;
159 /** @var Book $book */
160 foreach ($books->all() as $book) {
161 foreach ($book->getRelation('chapters') as $chapter) {
162 $entities->push($chapter);
164 foreach ($book->getRelation('pages') as $page) {
165 $entities->push($page);
170 $this->deleteManyJointPermissionsForEntities($entities->all());
173 $this->createManyJointPermissions($entities->all(), $roles);
177 * Rebuild the entity jointPermissions for a collection of entities.
179 protected function buildJointPermissionsForEntities(array $entities)
181 $roles = Role::query()->get()->values()->all();
182 $this->deleteManyJointPermissionsForEntities($entities);
183 $this->createManyJointPermissions($entities, $roles);
187 * Delete all the entity jointPermissions for a list of entities.
189 * @param Entity[] $entities
191 protected function deleteManyJointPermissionsForEntities(array $entities)
193 $simpleEntities = $this->entitiesToSimpleEntities($entities);
194 $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
196 DB::transaction(function () use ($idsByType) {
197 foreach ($idsByType as $type => $ids) {
198 foreach (array_chunk($ids, 1000) as $idChunk) {
199 DB::table('joint_permissions')
200 ->where('entity_type', '=', $type)
201 ->whereIn('entity_id', $idChunk)
203 DB::table('joint_user_permissions')
204 ->where('entity_type', '=', $type)
205 ->whereIn('entity_id', $idChunk)
213 * @param Entity[] $entities
215 * @return SimpleEntityData[]
217 protected function entitiesToSimpleEntities(array $entities): array
219 $simpleEntities = [];
221 foreach ($entities as $entity) {
222 $attrs = $entity->getAttributes();
223 $simple = new SimpleEntityData();
224 $simple->id = $attrs['id'];
225 $simple->type = $entity->getMorphClass();
226 $simple->owned_by = $attrs['owned_by'] ?? 0;
227 $simple->book_id = $attrs['book_id'] ?? null;
228 $simple->chapter_id = $attrs['chapter_id'] ?? null;
229 $simpleEntities[] = $simple;
232 return $simpleEntities;
236 * Create & Save entity jointPermissions for many entities and roles.
238 * @param Entity[] $originalEntities
239 * @param Role[] $roles
241 protected function createManyJointPermissions(array $originalEntities, array $roles)
243 $entities = $this->entitiesToSimpleEntities($originalEntities);
244 $this->readyEntityCache($entities);
245 $jointPermissions = [];
246 $jointUserPermissions = [];
248 // Fetch related entity permissions
249 $permissions = $this->getEntityPermissionsForEntities($entities);
251 // Create a mapping of explicit entity permissions
253 $controlledUserIds = [];
254 foreach ($permissions as $permission) {
255 $type = $permission->role_id ? 'role' : ($permission->user_id ? 'user' : 'fallback');
256 $id = $permission->role_id ?? $permission->user_id ?? '0';
257 $key = $permission->entity_type . ':' . $permission->entity_id . ':' . $type . ':' . $id;
258 if ($type === 'user') {
259 $controlledUserIds[$id] = true;
261 $permissionMap[$key] = $permission->view;
264 // Create a mapping of role permissions
265 $rolePermissionMap = [];
266 foreach ($roles as $role) {
267 foreach ($role->permissions as $permission) {
268 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
272 // Create Joint Permission Data
273 foreach ($entities as $entity) {
274 foreach ($roles as $role) {
275 $jointPermissions[] = $this->createJointPermissionData(
277 $role->getRawAttribute('id'),
280 $role->system_name === 'admin'
283 foreach ($controlledUserIds as $userId => $exists) {
284 $userPermitted = $this->getUserPermissionOverrideStatus($entity, $userId, $permissionMap);
285 if ($userPermitted !== null) {
286 $jointUserPermissions[] = $this->createJointUserPermissionDataArray($entity, $userId, $userPermitted);
291 DB::transaction(function () use ($jointPermissions) {
292 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
293 DB::table('joint_permissions')->insert($jointPermissionChunk);
297 DB::transaction(function () use ($jointUserPermissions) {
298 foreach (array_chunk($jointUserPermissions, 1000) as $jointUserPermissionsChunk) {
299 DB::table('joint_user_permissions')->insert($jointUserPermissionsChunk);
305 * From the given entity list, provide back a mapping of entity types to
306 * the ids of that given type. The type used is the DB morph class.
308 * @param SimpleEntityData[] $entities
310 * @return array<string, int[]>
312 protected function entitiesToTypeIdMap(array $entities): array
316 foreach ($entities as $entity) {
317 if (!isset($idsByType[$entity->type])) {
318 $idsByType[$entity->type] = [];
321 $idsByType[$entity->type][] = $entity->id;
328 * Get the entity permissions for all the given entities.
330 * @param SimpleEntityData[] $entities
332 * @return EntityPermission[]
334 protected function getEntityPermissionsForEntities(array $entities): array
336 $idsByType = $this->entitiesToTypeIdMap($entities);
337 $permissionFetch = EntityPermission::query()
338 ->where(function (Builder $query) use ($idsByType) {
339 foreach ($idsByType as $type => $ids) {
340 $query->orWhere(function (Builder $query) use ($type, $ids) {
341 $query->where('entity_type', '=', $type)->whereIn('entity_id', $ids);
346 return $permissionFetch->get()->all();
350 * Create entity permission data for an entity and role
351 * for a particular action.
353 protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, array $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
355 $permissionPrefix = $entity->type . '-view';
356 $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
357 $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
360 return $this->createJointPermissionDataArray($entity, $roleId, true, true);
363 if ($this->entityPermissionsActiveForRole($permissionMap, $entity, $roleId)) {
364 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $roleId);
366 return $this->createJointPermissionDataArray($entity, $roleId, $hasAccess, $hasAccess);
369 if ($entity->type === 'book' || $entity->type === 'bookshelf') {
370 return $this->createJointPermissionDataArray($entity, $roleId, $roleHasPermission, $roleHasPermissionOwn);
373 // For chapters and pages, Check if explicit permissions are set on the Book.
374 $book = $this->getBook($entity->book_id);
375 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $roleId);
376 $hasPermissiveAccessToParents = !$this->entityPermissionsActiveForRole($permissionMap, $book, $roleId);
378 // For pages with a chapter, Check if explicit permissions are set on the Chapter
379 if ($entity->type === 'page' && $entity->chapter_id !== 0) {
380 $chapter = $this->getChapter($entity->chapter_id);
381 $chapterRestricted = $this->entityPermissionsActiveForRole($permissionMap, $chapter, $roleId);
382 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapterRestricted;
383 if ($chapterRestricted) {
384 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $roleId);
388 return $this->createJointPermissionDataArray(
391 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
392 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
397 * Get the status of a user-specific permission override for the given entity user combo if existing.
398 * This can return null where no user-specific permission overrides are applicable.
400 protected function getUserPermissionOverrideStatus(SimpleEntityData $entity, int $userId, array $permissionMap): ?bool
402 // If direct permissions exists, return those
403 $directKey = $entity->type . ':' . $entity->id . ':user:' . $userId;
404 if (isset($permissionMap[$directKey])) {
405 return $permissionMap[$directKey];
408 // If a book or shelf, exit out since no parents to check
409 if ($entity->type === 'book' || $entity->type === 'bookshelf') {
413 // If a chapter or page, get the parent book permission status.
414 // defaults to null where no permission is set.
415 $bookKey = 'book:' . $entity->book_id . ':user:' . $userId;
416 $bookPermission = $permissionMap[$bookKey] ?? null;
418 // If a page within a chapter, return the chapter permission if existing otherwise
419 // default ot the parent book permission.
420 if ($entity->type === 'page' && $entity->chapter_id !== 0) {
421 $chapterKey = 'chapter:' . $entity->chapter_id . ':user:' . $userId;
422 $chapterPermission = $permissionMap[$chapterKey] ?? null;
423 return $chapterPermission ?? $bookPermission;
426 // Return the book permission status
427 return $bookPermission;
431 * Check if entity permissions are defined within the given map, for the given entity and role.
432 * Checks for the default `role_id=0` backup option as a fallback.
434 protected function entityPermissionsActiveForRole(array $permissionMap, SimpleEntityData $entity, int $roleId): bool
436 $keyPrefix = $entity->type . ':' . $entity->id . ':';
437 return isset($permissionMap[$keyPrefix . 'role:' . $roleId]) || isset($permissionMap[$keyPrefix . 'fallback:0']);
441 * Check for an active restriction in an entity map.
443 protected function mapHasActiveRestriction(array $permissionMap, SimpleEntityData $entity, int $roleId): bool
445 $roleKey = $entity->type . ':' . $entity->id . ':role:' . $roleId;
446 $defaultKey = $entity->type . ':' . $entity->id . ':fallback:0';
448 return $permissionMap[$roleKey] ?? $permissionMap[$defaultKey] ?? false;
452 * Create an array of data with the information of an entity jointPermissions.
453 * Used to build data for bulk insertion.
455 protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, bool $permissionAll, bool $permissionOwn): array
458 'entity_id' => $entity->id,
459 'entity_type' => $entity->type,
460 'has_permission' => $permissionAll,
461 'has_permission_own' => $permissionOwn,
462 'owned_by' => $entity->owned_by,
463 'role_id' => $roleId,
468 * Create an array of data with the information of an JointUserPermission.
469 * Used to build data for bulk insertion.
471 protected function createJointUserPermissionDataArray(SimpleEntityData $entity, int $userId, bool $hasPermission): array
474 'entity_id' => $entity->id,
475 'entity_type' => $entity->type,
476 'has_permission' => $hasPermission,
477 'user_id' => $userId,