2021-06-26 23:23:15 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace BookStack\Entities\Tools;
|
2021-01-02 01:49:48 +08:00
|
|
|
|
|
|
|
use BookStack\Actions\ActivityType;
|
|
|
|
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)
|
|
|
|
{
|
|
|
|
$restricted = $request->get('restricted') === 'true';
|
|
|
|
$permissions = $request->get('restrictions', null);
|
|
|
|
$ownerId = $request->get('owned_by', null);
|
|
|
|
|
|
|
|
$entity->restricted = $restricted;
|
|
|
|
$entity->permissions()->delete();
|
|
|
|
|
|
|
|
if (!is_null($permissions)) {
|
|
|
|
$entityPermissionData = $this->formatPermissionsFromRequestToEntityPermissions($permissions);
|
|
|
|
$entity->permissions()->createMany($entityPermissionData);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!is_null($ownerId)) {
|
2021-01-02 02:38:54 +08:00
|
|
|
$this->updateOwnerFromId($entity, intval($ownerId));
|
2021-01-02 01:49:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
$entity->save();
|
|
|
|
$entity->rebuildPermissions();
|
|
|
|
|
2021-12-12 01:29:33 +08:00
|
|
|
Activity::add(ActivityType::PERMISSIONS_UPDATE, $entity);
|
2021-01-02 01:49:48 +08: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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Format permissions provided from a permission form to be
|
|
|
|
* EntityPermission data.
|
|
|
|
*/
|
|
|
|
protected function formatPermissionsFromRequestToEntityPermissions(array $permissions): Collection
|
|
|
|
{
|
|
|
|
return collect($permissions)->flatMap(function ($restrictions, $roleId) {
|
|
|
|
return collect($restrictions)->keys()->map(function ($action) use ($roleId) {
|
|
|
|
return [
|
|
|
|
'role_id' => $roleId,
|
2021-06-26 23:23:15 +08:00
|
|
|
'action' => strtolower($action),
|
|
|
|
];
|
2021-01-02 01:49:48 +08:00
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|