3 namespace BookStack\Permissions;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\Entity;
10 use BookStack\Entities\Models\Page;
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
24 * Re-generate all entity permission from scratch.
26 public function rebuildForAll()
28 JointPermission::query()->truncate();
30 // Get all roles (Should be the most limited dimension)
31 $roles = Role::query()->with('permissions')->get()->all();
33 // Chunk through all books
34 $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
35 $this->buildJointPermissionsForBooks($books, $roles);
38 // Chunk through all bookshelves
39 Bookshelf::query()->withTrashed()->select(['id', 'owned_by'])
40 ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
41 $this->createManyJointPermissions($shelves->all(), $roles);
46 * Rebuild the entity jointPermissions for a particular entity.
48 public function rebuildForEntity(Entity $entity)
50 $entities = [$entity];
51 if ($entity instanceof Book) {
52 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
53 $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
58 /** @var BookChild $entity */
60 $entities[] = $entity->book;
63 if ($entity instanceof Page && $entity->chapter_id) {
64 $entities[] = $entity->chapter;
67 if ($entity instanceof Chapter) {
68 foreach ($entity->pages as $page) {
73 $this->buildJointPermissionsForEntities($entities);
77 * Build the entity jointPermissions for a particular role.
79 public function rebuildForRole(Role $role)
82 $role->jointPermissions()->delete();
83 $role->load('permissions');
85 // Chunk through all books
86 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
87 $this->buildJointPermissionsForBooks($books, $roles);
90 // Chunk through all bookshelves
91 Bookshelf::query()->select(['id', 'owned_by'])
92 ->chunk(50, function ($shelves) use ($roles) {
93 $this->createManyJointPermissions($shelves->all(), $roles);
98 * Get a query for fetching a book with its children.
100 protected function bookFetchQuery(): Builder
102 return Book::query()->withTrashed()
103 ->select(['id', 'owned_by'])->with([
104 'chapters' => function ($query) {
105 $query->withTrashed()->select(['id', 'owned_by', 'book_id']);
107 'pages' => function ($query) {
108 $query->withTrashed()->select(['id', 'owned_by', 'book_id', 'chapter_id']);
114 * Build joint permissions for the given book and role combinations.
116 protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
118 $entities = clone $books;
120 /** @var Book $book */
121 foreach ($books->all() as $book) {
122 foreach ($book->getRelation('chapters') as $chapter) {
123 $entities->push($chapter);
125 foreach ($book->getRelation('pages') as $page) {
126 $entities->push($page);
131 $this->deleteManyJointPermissionsForEntities($entities->all());
134 $this->createManyJointPermissions($entities->all(), $roles);
138 * Rebuild the entity jointPermissions for a collection of entities.
140 protected function buildJointPermissionsForEntities(array $entities)
142 $roles = Role::query()->get()->values()->all();
143 $this->deleteManyJointPermissionsForEntities($entities);
144 $this->createManyJointPermissions($entities, $roles);
148 * Delete all the entity jointPermissions for a list of entities.
150 * @param Entity[] $entities
152 protected function deleteManyJointPermissionsForEntities(array $entities)
154 $simpleEntities = $this->entitiesToSimpleEntities($entities);
155 $idsByType = $this->entitiesToTypeIdMap($simpleEntities);
157 DB::transaction(function () use ($idsByType) {
158 foreach ($idsByType as $type => $ids) {
159 foreach (array_chunk($ids, 1000) as $idChunk) {
160 DB::table('joint_permissions')
161 ->where('entity_type', '=', $type)
162 ->whereIn('entity_id', $idChunk)
170 * @param Entity[] $entities
172 * @return SimpleEntityData[]
174 protected function entitiesToSimpleEntities(array $entities): array
176 $simpleEntities = [];
178 foreach ($entities as $entity) {
179 $simple = SimpleEntityData::fromEntity($entity);
180 $simpleEntities[] = $simple;
183 return $simpleEntities;
187 * Create & Save entity jointPermissions for many entities and roles.
189 * @param Entity[] $originalEntities
190 * @param Role[] $roles
192 protected function createManyJointPermissions(array $originalEntities, array $roles)
194 $entities = $this->entitiesToSimpleEntities($originalEntities);
195 $jointPermissions = [];
197 // Fetch related entity permissions
198 $permissions = new MassEntityPermissionEvaluator($entities, 'view');
200 // Create a mapping of role permissions
201 $rolePermissionMap = [];
202 foreach ($roles as $role) {
203 foreach ($role->permissions as $permission) {
204 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
208 // Create Joint Permission Data
209 foreach ($entities as $entity) {
210 foreach ($roles as $role) {
211 $jp = $this->createJointPermissionData(
213 $role->getRawAttribute('id'),
216 $role->system_name === 'admin'
218 $jointPermissions[] = $jp;
222 DB::transaction(function () use ($jointPermissions) {
223 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
224 DB::table('joint_permissions')->insert($jointPermissionChunk);
230 * From the given entity list, provide back a mapping of entity types to
231 * the ids of that given type. The type used is the DB morph class.
233 * @param SimpleEntityData[] $entities
235 * @return array<string, int[]>
237 protected function entitiesToTypeIdMap(array $entities): array
241 foreach ($entities as $entity) {
242 if (!isset($idsByType[$entity->type])) {
243 $idsByType[$entity->type] = [];
246 $idsByType[$entity->type][] = $entity->id;
253 * Create entity permission data for an entity and role
254 * for a particular action.
256 protected function createJointPermissionData(SimpleEntityData $entity, int $roleId, MassEntityPermissionEvaluator $permissionMap, array $rolePermissionMap, bool $isAdminRole): array
258 // Ensure system admin role retains permissions
260 return $this->createJointPermissionDataArray($entity, $roleId, PermissionStatus::EXPLICIT_ALLOW, true);
263 // Return evaluated entity permission status if it has an affect.
264 $entityPermissionStatus = $permissionMap->evaluateEntityForRole($entity, $roleId);
265 if ($entityPermissionStatus !== null) {
266 return $this->createJointPermissionDataArray($entity, $roleId, $entityPermissionStatus, false);
269 // Otherwise default to the role-level permissions
270 $permissionPrefix = $entity->type . '-view';
271 $roleHasPermission = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-all']);
272 $roleHasPermissionOwn = isset($rolePermissionMap[$roleId . ':' . $permissionPrefix . '-own']);
273 $status = $roleHasPermission ? PermissionStatus::IMPLICIT_ALLOW : PermissionStatus::IMPLICIT_DENY;
274 return $this->createJointPermissionDataArray($entity, $roleId, $status, $roleHasPermissionOwn);
278 * Create an array of data with the information of an entity jointPermissions.
279 * Used to build data for bulk insertion.
281 protected function createJointPermissionDataArray(SimpleEntityData $entity, int $roleId, int $permissionStatus, bool $hasPermissionOwn): array
283 $ownPermissionActive = ($hasPermissionOwn && $permissionStatus !== PermissionStatus::EXPLICIT_DENY && $entity->owned_by);
286 'entity_id' => $entity->id,
287 'entity_type' => $entity->type,
288 'role_id' => $roleId,
289 'status' => $permissionStatus,
290 'owner_id' => $ownPermissionActive ? $entity->owned_by : null,