]> BookStack Code Mirror - hacks/blob - content/notify-favourited-pages/functions.php
Added license and hacks from gists
[hacks] / content / notify-favourited-pages / functions.php
1 <?php
2
3 use BookStack\Actions\ActivityType;
4 use BookStack\Auth\User;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Facades\Theme;
7 use BookStack\Notifications\MailNotification;
8 use BookStack\Theming\ThemeEvents;
9 use Illuminate\Notifications\Messages\MailMessage;
10
11 // This customization notifies page-updates via email to users that have marked
12 // that updated page as a favourite.
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 MailNotification {
17
18     protected Page $page;
19     protected User $updater;
20
21     public function __construct(Page $page, User $updater)
22     {
23         $this->page = $page;
24         $this->updater = $updater;
25     }
26
27     public function toMail($notifiable)
28     {
29         return (new MailMessage())
30             ->subject('BookStack page update notification')
31             ->line("The page \"{$this->page->name}\" has been updated by \"{$this->updater->name}\"")
32             ->action('View Page', $this->page->getUrl());
33     }
34 }
35
36 // This function does the work of sending notifications to the relevant users that have
37 // marked the given page as a favourite.
38 function notifyThoseThatHaveFavouritedPage(Page $page) {
39     // Find those we need to notify, and find the current updater of the page
40     $userIds = $page->favourites()->pluck('user_id');
41     $usersToNotify = User::query()->whereIn('id', $userIds)
42         ->where('id', '!=', $page->updated_by)
43         ->get();
44     $updater = User::query()->findOrFail($page->updated_by);
45
46     // Send a notification to each of the users we want to notify
47     foreach ($usersToNotify as $user) {
48         $user->notify(new PageUpdatedNotification($page, $updater));
49     }
50 }
51
52 // Listen to page update events and kick-start our notification logic
53 Theme::listen(ThemeEvents::ACTIVITY_LOGGED, function(string $type, $detail) {
54     if ($type === ActivityType::PAGE_UPDATE && $detail instanceof Page) {
55         notifyThoseThatHaveFavouritedPage($detail);
56     }
57 });