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()
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)
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)
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)
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)
160 $simpleEntities = $this->entitiesToSimpleEntities($entities);
161 $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
163 DB::transaction(function () use ($idsByType) {
164 foreach ($idsByType as $type => $ids) {
165 foreach (array_chunk($ids, 1000) as $idChunk) {
166 DB::table('joint_permissions')
167 ->where('entity_type', '=', $type)
168 ->whereIn('entity_id', $idChunk)
176 * @param Entity[] $entities
178 * @return SimpleEntityData[]
180 protected function entitiesToSimpleEntities(array $entities): array
182 $simpleEntities = [];
184 foreach ($entities as $entity) {
185 $simple = SimpleEntityData::fromEntity($entity);
186 $simpleEntities[] = $simple;
189 return $simpleEntities;
193 * Create & Save entity jointPermissions for many entities and roles.
195 * @param Entity[] $originalEntities
196 * @param Role[] $roles
198 protected function createManyJointPermissions(array $originalEntities, array $roles)
200 $entities = $this->entitiesToSimpleEntities($originalEntities);
201 $jointPermissions = [];
203 // Fetch related entity permissions
204 $permissions = new MassEntityPermissionEvaluator($entities, 'view');
206 // Create a mapping of role permissions
207 $rolePermissionMap = [];
208 foreach ($roles as $role) {
209 foreach ($role->permissions as $permission) {
210 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
214 // Create Joint Permission Data
215 foreach ($entities as $entity) {
216 foreach ($roles as $role) {
217 $jp = $this->createJointPermissionData(
219 $role->getRawAttribute('id'),
222 $role->system_name === 'admin'
224 $jointPermissions[] = $jp;
228 DB::transaction(function () use ($jointPermissions) {
229 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
230 DB::table('joint_permissions')->insert($jointPermissionChunk);
236 * From the given entity list, provide back a mapping of entity types to
237 * the ids of that given type. The type used is the DB morph class.
239 * @param SimpleEntityData[] $entities
241 * @return array<string, int[]>
243 protected function entitiesToTypeIdMap(array $entities): array
247 foreach ($entities as $entity) {
248 if (!isset($idsByType[$entity->type])) {
249 $idsByType[$entity->type] = [];
252 $idsByType[$entity->type][] = $entity->id;
259 * Create entity permission data for an entity and role
260 * for a particular action.
262 protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, MassEntityPermissionEvaluator $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
264 // Ensure system admin role retains permissions
266 return $this->createJointPermissionDataArray($entity, $roleId, PermissionStatus::EXPLICIT_ALLOW, true);
269 // Return evaluated entity permission status if it has an affect.
270 $entityPermissionStatus = $permissionMap->evaluateEntityForRole($entity, $roleId);
271 if ($entityPermissionStatus !== null) {
272 return $this->createJointPermissionDataArray($entity, $roleId, $entityPermissionStatus, false);
275 // Otherwise default to the role-level permissions
276 $permissionPrefix = $entity->type . '-view';
277 $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
278 $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
279 $status = $roleHasPermission ? PermissionStatus::IMPLICIT_ALLOW : PermissionStatus::IMPLICIT_DENY;
280 return $this->createJointPermissionDataArray($entity, $roleId, $status, $roleHasPermissionOwn);
284 * Create an array of data with the information of an entity jointPermissions.
285 * Used to build data for bulk insertion.
287 protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, int $permissionStatus, bool $hasPermissionOwn): array
289 $ownPermissionActive = ($hasPermissionOwn && $permissionStatus !== PermissionStatus::EXPLICIT_DENY && $entity->owned_by);
292 'entity_id' => $entity->id,
293 'entity_type' => $entity->type,
294 'role_id' => $roleId,
295 'status' => $permissionStatus,
296 'owner_id' => $ownPermissionActive ? $entity->owned_by : null,