3 namespace BookStack\Entities\Tools;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Permissions\EntityPermission;
7 use BookStack\Auth\User;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Facades\Activity;
10 use Illuminate\Http\Request;
11 use Illuminate\Support\Collection;
13 class PermissionsUpdater
16 * Update an entities permissions from a permission form submit request.
18 public function updateFromPermissionsForm(Entity $entity, Request $request)
20 $permissions = $request->get('permissions', null);
21 $ownerId = $request->get('owned_by', null);
23 $entity->permissions()->delete();
25 if (!is_null($permissions)) {
26 $entityPermissionData = $this->formatPermissionsFromRequestToEntityPermissions($permissions);
27 $entity->permissions()->createMany($entityPermissionData);
30 if (!is_null($ownerId)) {
31 $this->updateOwnerFromId($entity, intval($ownerId));
35 $entity->rebuildPermissions();
37 Activity::add(ActivityType::PERMISSIONS_UPDATE, $entity);
41 * Update the owner of the given entity.
42 * Checks the user exists in the system first.
43 * Does not save the model, just updates it.
45 protected function updateOwnerFromId(Entity $entity, int $newOwnerId)
47 $newOwner = User::query()->find($newOwnerId);
48 if (!is_null($newOwner)) {
49 $entity->owned_by = $newOwner->id;
54 * Format permissions provided from a permission form to be EntityPermission data.
56 protected function formatPermissionsFromRequestToEntityPermissions(array $permissions): array
60 foreach ($permissions as $roleId => $info) {
61 $entityPermissionData = ['role_id' => $roleId];
62 foreach (EntityPermission::PERMISSIONS as $permission) {
63 $entityPermissionData[$permission] = (($info[$permission] ?? false) === "true");
65 $formatted[] = $entityPermissionData;