]> BookStack Code Mirror - bookstack/blob - app/Activity/Controllers/WatchController.php
Merge pull request #4390 from BookStackApp/content_notifications
[bookstack] / app / Activity / Controllers / WatchController.php
1 <?php
2
3 namespace BookStack\Activity\Controllers;
4
5 use BookStack\Activity\Tools\UserEntityWatchOptions;
6 use BookStack\App\Model;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Http\Controller;
9 use Exception;
10 use Illuminate\Http\Request;
11 use Illuminate\Validation\ValidationException;
12
13 class WatchController extends Controller
14 {
15     public function update(Request $request)
16     {
17         $this->checkPermission('receive-notifications');
18         $this->preventGuestAccess();
19
20         $requestData = $this->validate($request, [
21             'level' => ['required', 'string'],
22         ]);
23
24         $watchable = $this->getValidatedModelFromRequest($request);
25         $watchOptions = new UserEntityWatchOptions(user(), $watchable);
26         $watchOptions->updateLevelByName($requestData['level']);
27
28         $this->showSuccessNotification(trans('activities.watch_update_level_notification'));
29
30         return redirect()->back();
31     }
32
33     /**
34      * @throws ValidationException
35      * @throws Exception
36      */
37     protected function getValidatedModelFromRequest(Request $request): Entity
38     {
39         $modelInfo = $this->validate($request, [
40             'type' => ['required', 'string'],
41             'id'   => ['required', 'integer'],
42         ]);
43
44         if (!class_exists($modelInfo['type'])) {
45             throw new Exception('Model not found');
46         }
47
48         /** @var Model $model */
49         $model = new $modelInfo['type']();
50         if (!$model instanceof Entity) {
51             throw new Exception('Model not an entity');
52         }
53
54         $modelInstance = $model->newQuery()
55             ->where('id', '=', $modelInfo['id'])
56             ->first(['id', 'name', 'owned_by']);
57
58         $inaccessibleEntity = ($modelInstance instanceof Entity && !userCan('view', $modelInstance));
59         if (is_null($modelInstance) || $inaccessibleEntity) {
60             throw new Exception('Model instance not found');
61         }
62
63         return $modelInstance;
64     }
65 }