3 namespace BookStack\Permissions;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Queries\EntityQueries;
11 use BookStack\Permissions\Models\JointPermission;
12 use BookStack\Users\Models\Role;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Eloquent\Collection as EloquentCollection;
15 use Illuminate\Support\Facades\DB;
18 * Joint permissions provide a pre-query "cached" table of view permissions for all core entity
19 * types for all roles in the system. This class generates out that table for different scenarios.
21 class JointPermissionBuilder
23 public function __construct(
24 protected EntityQueries $queries,
30 * Re-generate all entity permission from scratch.
32 public function rebuildForAll(): void
34 JointPermission::query()->truncate();
36 // Get all roles (Should be the most limited dimension)
37 $roles = Role::query()->with('permissions')->get()->all();
39 // Chunk through all books
40 $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
41 $this->buildJointPermissionsForBooks($books, $roles);
44 // Chunk through all bookshelves
45 $this->queries->shelves->start()->withTrashed()->select(['id', 'owned_by'])
46 ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
47 $this->createManyJointPermissions($shelves->all(), $roles);
52 * Rebuild the entity jointPermissions for a particular entity.
54 public function rebuildForEntity(Entity $entity): void
56 $entities = [$entity];
57 if ($entity instanceof Book) {
58 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
59 $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
64 /** @var BookChild $entity */
66 $entities[] = $entity->book;
69 if ($entity instanceof Page && $entity->chapter_id) {
70 $entities[] = $entity->chapter;
73 if ($entity instanceof Chapter) {
74 foreach ($entity->pages as $page) {
79 $this->buildJointPermissionsForEntities($entities);
83 * Build the entity jointPermissions for a particular role.
85 public function rebuildForRole(Role $role)
88 $role->jointPermissions()->delete();
89 $role->load('permissions');
91 // Chunk through all books
92 $this->bookFetchQuery()->chunk(10, function ($books) use ($roles) {
93 $this->buildJointPermissionsForBooks($books, $roles);
96 // Chunk through all bookshelves
97 $this->queries->shelves->start()->select(['id', 'owned_by'])
98 ->chunk(100, function ($shelves) use ($roles) {
99 $this->createManyJointPermissions($shelves->all(), $roles);
104 * Get a query for fetching a book with its children.
106 protected function bookFetchQuery(): Builder
108 return $this->queries->books->start()->withTrashed()
109 ->select(['id', 'owned_by'])->with([
110 'chapters' => function ($query) {
111 $query->withTrashed()->select(['id', 'owned_by', 'book_id']);
113 'pages' => function ($query) {
114 $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
120 * Build joint permissions for the given book and role combinations.
122 protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false): void
124 $entities = clone $books;
126 /** @var Book $book */
127 foreach ($books->all() as $book) {
128 foreach ($book->getRelation('chapters') as $chapter) {
129 $entities->push($chapter);
131 foreach ($book->getRelation('pages') as $page) {
132 $entities->push($page);
137 $this->deleteManyJointPermissionsForEntities($entities->all());
140 $this->createManyJointPermissions($entities->all(), $roles);
144 * Rebuild the entity jointPermissions for a collection of entities.
146 protected function buildJointPermissionsForEntities(array $entities): void
148 $roles = Role::query()->get()->values()->all();
149 $this->deleteManyJointPermissionsForEntities($entities);
150 $this->createManyJointPermissions($entities, $roles);
154 * Delete all the entity jointPermissions for a list of entities.
156 * @param Entity[] $entities
158 protected function deleteManyJointPermissionsForEntities(array $entities): void
160 $simpleEntities = $this->entitiesToSimpleEntities($entities);
161 $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
163 foreach ($idsByType as $type => $ids) {
164 foreach (array_chunk($ids, 1000) as $idChunk) {
165 DB::table('joint_permissions')
166 ->where('entity_type', '=', $type)
167 ->whereIn('entity_id', $idChunk)
174 * @param Entity[] $entities
176 * @return SimpleEntityData[]
178 protected function entitiesToSimpleEntities(array $entities): array
180 $simpleEntities = [];
182 foreach ($entities as $entity) {
183 $simple = SimpleEntityData::fromEntity($entity);
184 $simpleEntities[] = $simple;
187 return $simpleEntities;
191 * Create & Save entity jointPermissions for many entities and roles.
193 * @param Entity[] $originalEntities
194 * @param Role[] $roles
196 protected function createManyJointPermissions(array $originalEntities, array $roles): void
198 $entities = $this->entitiesToSimpleEntities($originalEntities);
199 $jointPermissions = [];
201 // Fetch related entity permissions
202 $permissions = new MassEntityPermissionEvaluator($entities, 'view');
204 // Create a mapping of role permissions
205 $rolePermissionMap = [];
206 foreach ($roles as $role) {
207 foreach ($role->permissions as $permission) {
208 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
212 // Create Joint Permission Data
213 foreach ($entities as $entity) {
214 foreach ($roles as $role) {
215 $jp = $this->createJointPermissionData(
217 $role->getRawAttribute('id'),
220 $role->system_name === 'admin'
222 $jointPermissions[] = $jp;
226 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
227 DB::table('joint_permissions')->insert($jointPermissionChunk);
232 * From the given entity list, provide back a mapping of entity types to
233 * the ids of that given type. The type used is the DB morph class.
235 * @param SimpleEntityData[] $entities
237 * @return array<string, int[]>
239 protected function entitiesToTypeIdMap(array $entities): array
243 foreach ($entities as $entity) {
244 if (!isset($idsByType[$entity->type])) {
245 $idsByType[$entity->type] = [];
248 $idsByType[$entity->type][] = $entity->id;
255 * Create entity permission data for an entity and role
256 * for a particular action.
258 protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, MassEntityPermissionEvaluator $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
260 // Ensure system admin role retains permissions
262 return $this->createJointPermissionDataArray($entity, $roleId, PermissionStatus::EXPLICIT_ALLOW, true);
265 // Return evaluated entity permission status if it has an affect.
266 $entityPermissionStatus = $permissionMap->evaluateEntityForRole($entity, $roleId);
267 if ($entityPermissionStatus !== null) {
268 return $this->createJointPermissionDataArray($entity, $roleId, $entityPermissionStatus, false);
271 // Otherwise default to the role-level permissions
272 $permissionPrefix = $entity->type . '-view';
273 $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
274 $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
275 $status = $roleHasPermission ? PermissionStatus::IMPLICIT_ALLOW : PermissionStatus::IMPLICIT_DENY;
276 return $this->createJointPermissionDataArray($entity, $roleId, $status, $roleHasPermissionOwn);
280 * Create an array of data with the information of an entity jointPermissions.
281 * Used to build data for bulk insertion.
283 protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, int $permissionStatus, bool $hasPermissionOwn): array
285 $ownPermissionActive = ($hasPermissionOwn && $permissionStatus !== PermissionStatus::EXPLICIT_DENY && $entity->owned_by);
288 'entity_id' => $entity->id,
289 'entity_type' => $entity->type,
290 'role_id' => $roleId,
291 'status' => $permissionStatus,
292 'owner_id' => $ownPermissionActive ? $entity->owned_by : null,