2021-06-26 17:23:15 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace BookStack\Entities\Tools;
|
2021-01-01 18:49:48 +01:00
|
|
|
|
|
|
|
use BookStack\Actions\ActivityType;
|
2022-10-08 14:52:59 +02:00
|
|
|
use BookStack\Auth\Permissions\EntityPermission;
|
2021-01-01 18:49:48 +01:00
|
|
|
use BookStack\Auth\User;
|
|
|
|
use BookStack\Entities\Models\Entity;
|
|
|
|
use BookStack\Facades\Activity;
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
use Illuminate\Support\Collection;
|
|
|
|
|
|
|
|
class PermissionsUpdater
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Update an entities permissions from a permission form submit request.
|
|
|
|
*/
|
|
|
|
public function updateFromPermissionsForm(Entity $entity, Request $request)
|
|
|
|
{
|
2022-10-08 14:52:59 +02:00
|
|
|
$permissions = $request->get('permissions', null);
|
2021-01-01 18:49:48 +01:00
|
|
|
$ownerId = $request->get('owned_by', null);
|
|
|
|
|
|
|
|
$entity->permissions()->delete();
|
|
|
|
|
|
|
|
if (!is_null($permissions)) {
|
|
|
|
$entityPermissionData = $this->formatPermissionsFromRequestToEntityPermissions($permissions);
|
|
|
|
$entity->permissions()->createMany($entityPermissionData);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!is_null($ownerId)) {
|
2021-01-01 19:38:54 +01:00
|
|
|
$this->updateOwnerFromId($entity, intval($ownerId));
|
2021-01-01 18:49:48 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
$entity->save();
|
|
|
|
$entity->rebuildPermissions();
|
|
|
|
|
2021-12-11 18:29:33 +01:00
|
|
|
Activity::add(ActivityType::PERMISSIONS_UPDATE, $entity);
|
2021-01-01 18:49:48 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update the owner of the given entity.
|
|
|
|
* Checks the user exists in the system first.
|
|
|
|
* Does not save the model, just updates it.
|
|
|
|
*/
|
|
|
|
protected function updateOwnerFromId(Entity $entity, int $newOwnerId)
|
|
|
|
{
|
|
|
|
$newOwner = User::query()->find($newOwnerId);
|
|
|
|
if (!is_null($newOwner)) {
|
|
|
|
$entity->owned_by = $newOwner->id;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-10-08 14:52:59 +02:00
|
|
|
* Format permissions provided from a permission form to be EntityPermission data.
|
2021-01-01 18:49:48 +01:00
|
|
|
*/
|
2022-10-08 14:52:59 +02:00
|
|
|
protected function formatPermissionsFromRequestToEntityPermissions(array $permissions): array
|
2021-01-01 18:49:48 +01:00
|
|
|
{
|
2022-10-08 14:52:59 +02:00
|
|
|
$formatted = [];
|
|
|
|
|
|
|
|
foreach ($permissions as $roleId => $info) {
|
|
|
|
$entityPermissionData = ['role_id' => $roleId];
|
|
|
|
foreach (EntityPermission::PERMISSIONS as $permission) {
|
|
|
|
$entityPermissionData[$permission] = (($info[$permission] ?? false) === "true");
|
|
|
|
}
|
|
|
|
$formatted[] = $entityPermissionData;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $formatted;
|
2021-01-01 18:49:48 +01:00
|
|
|
}
|
|
|
|
}
|