]> BookStack Code Mirror - hacks/blob - content/notify-favourited-pages/functions.php
Updated notify-favourite-pages hack
[hacks] / content / notify-favourited-pages / functions.php
1 <?php
2
3 use BookStack\Activity\ActivityType;
4 use BookStack\Activity\Notifications\Messages\BaseActivityNotification;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Facades\Theme;
7 use BookStack\Theming\ThemeEvents;
8 use BookStack\Users\Models\User;
9 use Illuminate\Notifications\Messages\MailMessage;
10
11 // This customization notifies page-updates via email to all users that have marked
12 // that updated page as a favourite, excluding the user performing the update
13
14 // This notification class represents the notification that'll be sent to users.
15 // The text of the notification can be customized within the 'toMail' function.
16 class PageUpdatedNotification extends BaseActivityNotification {
17     public function toMail($notifiable): MailMessage
18     {
19         /** @var Page $page */
20         $page = $this->detail;
21         $updater = $this->user;
22         return (new MailMessage())
23             ->subject('BookStack page update notification')
24             ->line("The page \"{$page->name}\" has been updated by \"{$updater->name}\"")
25             ->action('View Page', $page->getUrl());
26     }
27 }
28
29 // This function does the work of sending notifications to the relevant users that have
30 // marked the given page as a favourite.
31 function notifyThoseThatHaveFavouritedPage(Page $page): void {
32     // Find those we need to notify, and find the current updater of the page
33     $userIds = $page->favourites()->pluck('user_id');
34     $usersToNotify = User::query()->whereIn('id', $userIds)
35         ->where('id', '!=', $page->updated_by)
36         ->get();
37     $updater = User::query()->findOrFail($page->updated_by);
38
39     // Send a notification to each of the users we want to notify
40     foreach ($usersToNotify as $user) {
41         $user->notify(new PageUpdatedNotification($page, $updater));
42     }
43 }
44
45 // Listen to page update events and kick-start our notification logic
46 Theme::listen(ThemeEvents::ACTIVITY_LOGGED, function (string $type, $detail) {
47     if ($type === ActivityType::PAGE_UPDATE && $detail instanceof Page) {
48         notifyThoseThatHaveFavouritedPage($detail);
49     }
50 });