]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/PermissionsUpdater.php
8a27ce75b6f2722aace9c279dda670267db03804
[bookstack] / app / Entities / Tools / PermissionsUpdater.php
1 <?php namespace BookStack\Entities\Tools;
2
3 use BookStack\Actions\ActivityType;
4 use BookStack\Auth\User;
5 use BookStack\Entities\Models\Entity;
6 use BookStack\Facades\Activity;
7 use Illuminate\Http\Request;
8 use Illuminate\Support\Collection;
9
10 class PermissionsUpdater
11 {
12
13     /**
14      * Update an entities permissions from a permission form submit request.
15      */
16     public function updateFromPermissionsForm(Entity $entity, Request $request)
17     {
18         $restricted = $request->get('restricted') === 'true';
19         $permissions = $request->get('restrictions', null);
20         $ownerId = $request->get('owned_by', null);
21
22         $entity->restricted = $restricted;
23         $entity->permissions()->delete();
24
25         if (!is_null($permissions)) {
26             $entityPermissionData = $this->formatPermissionsFromRequestToEntityPermissions($permissions);
27             $entity->permissions()->createMany($entityPermissionData);
28         }
29
30         if (!is_null($ownerId)) {
31             $this->updateOwnerFromId($entity, intval($ownerId));
32         }
33
34         $entity->save();
35         $entity->rebuildPermissions();
36
37         Activity::addForEntity($entity, ActivityType::PERMISSIONS_UPDATE);
38     }
39
40     /**
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.
44      */
45     protected function updateOwnerFromId(Entity $entity, int $newOwnerId)
46     {
47         $newOwner = User::query()->find($newOwnerId);
48         if (!is_null($newOwner)) {
49             $entity->owned_by = $newOwner->id;
50         }
51     }
52
53     /**
54      * Format permissions provided from a permission form to be
55      * EntityPermission data.
56      */
57     protected function formatPermissionsFromRequestToEntityPermissions(array $permissions): Collection
58     {
59         return collect($permissions)->flatMap(function ($restrictions, $roleId) {
60             return collect($restrictions)->keys()->map(function ($action) use ($roleId) {
61                 return [
62                     'role_id' => $roleId,
63                     'action' => strtolower($action),
64                 ] ;
65             });
66         });
67     }
68 }