]> BookStack Code Mirror - bookstack/blob - app/Activity/Notifications/Handlers/BaseNotificationHandler.php
Permissions: Updated usage of controller methods to use enum
[bookstack] / app / Activity / Notifications / Handlers / BaseNotificationHandler.php
1 <?php
2
3 namespace BookStack\Activity\Notifications\Handlers;
4
5 use BookStack\Activity\Models\Loggable;
6 use BookStack\Activity\Notifications\Messages\BaseActivityNotification;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Permissions\Permission;
9 use BookStack\Permissions\PermissionApplicator;
10 use BookStack\Users\Models\User;
11 use Illuminate\Support\Facades\Log;
12
13 abstract class BaseNotificationHandler implements NotificationHandler
14 {
15     /**
16      * @param class-string<BaseActivityNotification> $notification
17      * @param int[] $userIds
18      */
19     protected function sendNotificationToUserIds(string $notification, array $userIds, User $initiator, string|Loggable $detail, Entity $relatedModel): void
20     {
21         $users = User::query()->whereIn('id', array_unique($userIds))->get();
22
23         foreach ($users as $user) {
24             // Prevent sending to the user that initiated the activity
25             if ($user->id === $initiator->id) {
26                 continue;
27             }
28
29             // Prevent sending of the user does not have notification permissions
30             if (!$user->can(Permission::ReceiveNotifications)) {
31                 continue;
32             }
33
34             // Prevent sending if the user does not have access to the related content
35             $permissions = new PermissionApplicator($user);
36             if (!$permissions->checkOwnableUserAccess($relatedModel, 'view')) {
37                 continue;
38             }
39
40             // Send the notification
41             try {
42                 $user->notify(new $notification($detail, $initiator));
43             } catch (\Exception $exception) {
44                 Log::error("Failed to send email notification to user [id:{$user->id}] with error: {$exception->getMessage()}");
45             }
46         }
47     }
48 }