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 $entityCache;
28 * Re-generate all entity permission from scratch.
30 public function rebuildForAll()
32 JointPermission::query()->truncate();
34 // Get all roles (Should be the most limited dimension)
35 $roles = Role::query()->with('permissions')->get()->all();
37 // Chunk through all books
38 $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
39 $this->buildJointPermissionsForBooks($books, $roles);
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);
50 * Rebuild the entity jointPermissions for a particular entity.
52 public function rebuildForEntity(Entity $entity)
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);
62 /** @var BookChild $entity */
64 $entities[] = $entity->book;
67 if ($entity instanceof Page && $entity->chapter_id) {
68 $entities[] = $entity->chapter;
71 if ($entity instanceof Chapter) {
72 foreach ($entity->pages as $page) {
77 $this->buildJointPermissionsForEntities($entities);
81 * Build the entity jointPermissions for a particular role.
83 public function rebuildForRole(Role $role)
86 $role->jointPermissions()->delete();
87 $role->load('permissions');
89 // Chunk through all books
90 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
91 $this->buildJointPermissionsForBooks($books, $roles);
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);
102 * Prepare the local entity cache and ensure it's empty.
104 * @param SimpleEntityData[] $entities
106 protected function readyEntityCache(array $entities)
108 $this->entityCache = [];
110 foreach ($entities as $entity) {
111 if (!isset($this->entityCache[$entity->type])) {
112 $this->entityCache[$entity->type] = [];
115 $this->entityCache[$entity->type][$entity->id] = $entity;
120 * Get a book via ID, Checks local cache.
122 protected function getBook(int $bookId): SimpleEntityData
124 return $this->entityCache['book'][$bookId];
128 * Get a chapter via ID, Checks local cache.
130 protected function getChapter(int $chapterId): SimpleEntityData
132 return $this->entityCache['chapter'][$chapterId];
136 * Get a query for fetching a book with its children.
138 protected function bookFetchQuery(): Builder
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']);
145 'pages' => function ($query) {
146 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
152 * Build joint permissions for the given book and role combinations.
154 protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
156 $entities = clone $books;
158 /** @var Book $book */
159 foreach ($books->all() as $book) {
160 foreach ($book->getRelation('chapters') as $chapter) {
161 $entities->push($chapter);
163 foreach ($book->getRelation('pages') as $page) {
164 $entities->push($page);
169 $this->deleteManyJointPermissionsForEntities($entities->all());
172 $this->createManyJointPermissions($entities->all(), $roles);
176 * Rebuild the entity jointPermissions for a collection of entities.
178 protected function buildJointPermissionsForEntities(array $entities)
180 $roles = Role::query()->get()->values()->all();
181 $this->deleteManyJointPermissionsForEntities($entities);
182 $this->createManyJointPermissions($entities, $roles);
186 * Delete all the entity jointPermissions for a list of entities.
188 * @param Entity[] $entities
190 protected function deleteManyJointPermissionsForEntities(array $entities)
192 $simpleEntities = $this->entitiesToSimpleEntities($entities);
193 $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
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)
208 * @param Entity[] $entities
210 * @return SimpleEntityData[]
212 protected function entitiesToSimpleEntities(array $entities): array
214 $simpleEntities = [];
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;
228 return $simpleEntities;
232 * Create & Save entity jointPermissions for many entities and roles.
234 * @param Entity[] $entities
235 * @param Role[] $roles
237 protected function createManyJointPermissions(array $originalEntities, array $roles)
239 $entities = $this->entitiesToSimpleEntities($originalEntities);
240 $this->readyEntityCache($entities);
241 $jointPermissions = [];
243 // Create a mapping of entity restricted statuses
244 $entityRestrictedMap = [];
245 foreach ($entities as $entity) {
246 $entityRestrictedMap[$entity->type . ':' . $entity->id] = $entity->restricted;
249 // Fetch related entity permissions
250 $permissions = $this->getEntityPermissionsForEntities($entities);
252 // Create a mapping of explicit entity permissions
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;
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;
268 // Create Joint Permission Data
269 foreach ($entities as $entity) {
270 foreach ($roles as $role) {
271 $jointPermissions[] = $this->createJointPermissionData(
273 $role->getRawAttribute('id'),
276 $role->system_name === 'admin'
281 DB::transaction(function () use ($jointPermissions) {
282 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
283 DB::table('joint_permissions')->insert($jointPermissionChunk);
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.
292 * @param SimpleEntityData[] $entities
294 * @return array<string, int[]>
296 protected function entitiesToTypeIdMap(array $entities): array
300 foreach ($entities as $entity) {
301 if (!isset($idsByType[$entity->type])) {
302 $idsByType[$entity->type] = [];
305 $idsByType[$entity->type][] = $entity->id;
312 * Get the entity permissions for all the given entities.
314 * @param SimpleEntityData[] $entities
316 * @return EntityPermission[]
318 protected function getEntityPermissionsForEntities(array $entities): array
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);
331 return $permissionFetch->get()->all();
335 * Create entity permission data for an entity and role
336 * for a particular action.
338 protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, array $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
340 $permissionPrefix = $entity->type . '-view';
341 $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
342 $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
345 return $this->createJointPermissionDataArray($entity, $roleId, true, true);
348 if ($entity->restricted) {
349 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $roleId);
351 return $this->createJointPermissionDataArray($entity, $roleId, $hasAccess, $hasAccess);
354 if ($entity->type === 'book' || $entity->type === 'bookshelf') {
355 return $this->createJointPermissionDataArray($entity, $roleId, $roleHasPermission, $roleHasPermissionOwn);
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;
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);
372 return $this->createJointPermissionDataArray(
375 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
376 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
381 * Check for an active restriction in an entity map.
383 protected function mapHasActiveRestriction(array $entityMap, SimpleEntityData $entity, int $roleId): bool
385 $key = $entity->type . ':' . $entity->id . ':' . $roleId;
387 return $entityMap[$key] ?? false;
391 * Create an array of data with the information of an entity jointPermissions.
392 * Used to build data for bulk insertion.
394 protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, bool $permissionAll, bool $permissionOwn): array
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,