Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 170
0.00% covered (danger)
0.00%
0 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
webpush
0.00% covered (danger)
0.00%
0 / 170
0.00% covered (danger)
0.00%
0 / 16
3540
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 get_type
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_available
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
20
 is_enabled_by_default
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_notified_users
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 notify
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
6
 notify_using_webpush
0.00% covered (danger)
0.00%
0 / 64
0.00% covered (danger)
0.00%
0 / 1
210
 mark_notifications
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
30
 mark_notifications_by_parent
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
30
 prune_notifications
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 clean_data
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 get_ucp_template_data
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 get_user_subscription_map
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 remove_subscriptions
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 clean_expired_subscriptions
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
56
 set_endpoint_padding
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3*
4* This file is part of the phpBB Forum Software package.
5*
6* @copyright (c) phpBB Limited <https://www.phpbb.com>
7* @license GNU General Public License, version 2 (GPL-2.0)
8*
9* For full copyright and license information, please see
10* the docs/CREDITS.txt file.
11*
12*/
13
14namespace phpbb\notification\method;
15
16use Minishlink\WebPush\Subscription;
17use phpbb\config\config;
18use phpbb\controller\helper;
19use phpbb\db\driver\driver_interface;
20use phpbb\form\form_helper;
21use phpbb\log\log_interface;
22use phpbb\notification\type\type_interface;
23use phpbb\user;
24use phpbb\user_loader;
25
26/**
27* Web Push notification method class
28* This class handles sending push messages for notifications
29*/
30
31class webpush extends messenger_base implements extended_method_interface
32{
33    /** @var config */
34    protected $config;
35
36    /** @var driver_interface */
37    protected $db;
38
39    /** @var log_interface */
40    protected $log;
41
42    /** @var user */
43    protected $user;
44
45    /** @var string Notification Web Push table */
46    protected $notification_webpush_table;
47
48    /** @var string Notification push subscriptions table */
49    protected $push_subscriptions_table;
50
51    /** @var int Fallback size for padding if endpoint is mozilla, see https://github.com/web-push-libs/web-push-php/issues/108#issuecomment-2133477054 */
52    const MOZILLA_FALLBACK_PADDING = 2820;
53
54    /** @var array Map for storing push token between db insertion and sending of notifications */
55    private array $push_token_map = [];
56
57    /**
58     * Notification Method Web Push constructor
59     *
60     * @param config $config
61     * @param driver_interface $db
62     * @param log_interface $log
63     * @param user_loader $user_loader
64     * @param user $user
65     * @param string $phpbb_root_path
66     * @param string $php_ext
67     * @param string $notification_webpush_table
68     * @param string $push_subscriptions_table
69     */
70    public function __construct(config $config, driver_interface $db, log_interface $log, user_loader $user_loader, user $user, string $phpbb_root_path,
71                                string $php_ext, string $notification_webpush_table, string $push_subscriptions_table)
72    {
73        parent::__construct($user_loader, $phpbb_root_path, $php_ext);
74
75        $this->config = $config;
76        $this->db = $db;
77        $this->log = $log;
78        $this->user = $user;
79        $this->notification_webpush_table = $notification_webpush_table;
80        $this->push_subscriptions_table = $push_subscriptions_table;
81    }
82
83    /**
84    * {@inheritDoc}
85    */
86    public function get_type(): string
87    {
88        return 'notification.method.webpush';
89    }
90
91    /**
92    * {@inheritDoc}
93    */
94    public function is_available(type_interface $notification_type = null): bool
95    {
96        return parent::is_available($notification_type) && $this->config['webpush_enable']
97            && !empty($this->config['webpush_vapid_public']) && !empty($this->config['webpush_vapid_private']);
98    }
99
100    /**
101     * {@inheritDoc}
102     */
103    public function is_enabled_by_default()
104    {
105        return (bool) $this->config['webpush_method_default_enable'];
106    }
107
108    /**
109    * {@inheritdoc}
110    */
111    public function get_notified_users($notification_type_id, array $options): array
112    {
113        $notified_users = [];
114
115        $sql = 'SELECT user_id
116            FROM ' . $this->notification_webpush_table . '
117            WHERE notification_type_id = ' . (int) $notification_type_id .
118            (isset($options['item_id']) ? ' AND item_id = ' . (int) $options['item_id'] : '') .
119            (isset($options['item_parent_id']) ? ' AND item_parent_id = ' . (int) $options['item_parent_id'] : '') .
120            (isset($options['user_id']) ? ' AND user_id = ' . (int) $options['user_id'] : '');
121        $result = $this->db->sql_query($sql);
122        while ($row = $this->db->sql_fetchrow($result))
123        {
124            $notified_users[$row['user_id']] = $row;
125        }
126        $this->db->sql_freeresult($result);
127
128        return $notified_users;
129    }
130
131    /**
132    * Parse the queue and notify the users
133    */
134    public function notify()
135    {
136        $insert_buffer = new \phpbb\db\sql_insert_buffer($this->db, $this->notification_webpush_table);
137
138        /** @var type_interface $notification */
139        foreach ($this->queue as $notification)
140        {
141            $data = $notification->get_insert_array();
142            $data += [
143                'push_data'                => json_encode(array_merge(
144                    $data,
145                    ['notification_type_name' => $notification->get_type()],
146                )),
147                'notification_time'        => time(),
148                'push_token'            => hash('sha256', random_bytes(32))
149            ];
150            $data = self::clean_data($data);
151            $insert_buffer->insert($data);
152            $this->push_token_map[$notification->notification_type_id][$notification->item_id] = $data['push_token'];
153        }
154
155        $insert_buffer->flush();
156
157        $this->notify_using_webpush();
158
159        return false;
160    }
161
162    /**
163     * Notify using Web Push
164     *
165     * @return void
166     */
167    protected function notify_using_webpush(): void
168    {
169        if (empty($this->queue))
170        {
171            return;
172        }
173
174        // Load all users we want to notify
175        $user_ids = [];
176        foreach ($this->queue as $notification)
177        {
178            $user_ids[] = $notification->user_id;
179        }
180
181        // Do not send push notifications to banned users
182        if (!function_exists('phpbb_get_banned_user_ids'))
183        {
184            include($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext);
185        }
186        $banned_users = phpbb_get_banned_user_ids($user_ids);
187
188        // Load all the users we need
189        $notify_users = array_diff($user_ids, $banned_users);
190        $this->user_loader->load_users($notify_users, array(USER_IGNORE));
191
192        // Get subscriptions for users
193        $user_subscription_map = $this->get_user_subscription_map($notify_users);
194
195        $auth = [
196            'VAPID' => [
197                'subject' => generate_board_url(false),
198                'publicKey' => $this->config['webpush_vapid_public'],
199                'privateKey' => $this->config['webpush_vapid_private'],
200            ],
201        ];
202
203        $web_push = new \Minishlink\WebPush\WebPush($auth);
204
205        $number_of_notifications = 0;
206        $remove_subscriptions = [];
207
208        // Time to go through the queue and send notifications
209        /** @var type_interface $notification */
210        foreach ($this->queue as $notification)
211        {
212            $user = $this->user_loader->get_user($notification->user_id);
213
214            $user_subscriptions = $user_subscription_map[$notification->user_id] ?? [];
215
216            if ($user['user_type'] == USER_INACTIVE && $user['user_inactive_reason'] == INACTIVE_MANUAL
217                || empty($user_subscriptions))
218            {
219                continue;
220            }
221
222            // Add actual Web Push data
223            $data = [
224                'item_id'    => $notification->item_id,
225                'type_id'    => $notification->notification_type_id,
226                'user_id'    => $notification->user_id,
227                'version'    => $this->config['assets_version'],
228                'token'        => hash('sha256', $user['user_form_salt'] . $this->push_token_map[$notification->notification_type_id][$notification->item_id]),
229            ];
230            $json_data = json_encode($data);
231
232            foreach ($user_subscriptions as $subscription)
233            {
234                try
235                {
236                    $this->set_endpoint_padding($web_push, $subscription['endpoint']);
237                    $push_subscription = Subscription::create([
238                        'endpoint'            => $subscription['endpoint'],
239                        'keys'                => [
240                            'p256dh'    => $subscription['p256dh'],
241                            'auth'        => $subscription['auth'],
242                        ],
243                    ]);
244                    $web_push->queueNotification($push_subscription, $json_data);
245                    $number_of_notifications++;
246                }
247                catch (\ErrorException $exception)
248                {
249                    $remove_subscriptions[] = $subscription['subscription_id'];
250                    $this->log->add('user', $user['user_id'], $user['user_ip'] ?? '', 'LOG_WEBPUSH_SUBSCRIPTION_REMOVED', false, [
251                        'reportee_id' => $user['user_id'],
252                        $user['username'],
253                    ]);
254                }
255            }
256        }
257
258        // Remove any subscriptions that couldn't be queued, i.e. that have invalid data
259        $this->remove_subscriptions($remove_subscriptions);
260
261        // List to fill with expired subscriptions based on return
262        $expired_endpoints = [];
263
264        try
265        {
266            foreach ($web_push->flush($number_of_notifications) as $report)
267            {
268                if (!$report->isSuccess())
269                {
270                    // Fill array of endpoints to remove if subscription has expired
271                    if ($report->isSubscriptionExpired())
272                    {
273                        $expired_endpoints[] = $report->getEndpoint();
274                    }
275                    else
276                    {
277                        $report_data = \phpbb\json\sanitizer::sanitize($report->jsonSerialize());
278                        $this->log->add('admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$report_data['reason']]);
279                    }
280                }
281            }
282        }
283        catch (\ErrorException $exception)
284        {
285            $this->log->add('critical', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$exception->getMessage()]);
286        }
287
288        $this->clean_expired_subscriptions($user_subscription_map, $expired_endpoints);
289
290        // We're done, empty the queue
291        $this->empty_queue();
292    }
293
294    /**
295    * {@inheritdoc}
296    */
297    public function mark_notifications($notification_type_id, $item_id, $user_id, $time = false, $mark_read = true)
298    {
299        $sql = 'DELETE FROM ' . $this->notification_webpush_table . '
300            WHERE ' . ($notification_type_id !== false ? $this->db->sql_in_set('notification_type_id', is_array($notification_type_id) ? $notification_type_id : [$notification_type_id]) : '1=1') .
301            ($user_id !== false ? ' AND ' . $this->db->sql_in_set('user_id', $user_id) : '') .
302            ($item_id !== false ? ' AND ' . $this->db->sql_in_set('item_id', $item_id) : '');
303        $this->db->sql_query($sql);
304    }
305
306    /**
307    * {@inheritdoc}
308    */
309    public function mark_notifications_by_parent($notification_type_id, $item_parent_id, $user_id, $time = false, $mark_read = true)
310    {
311        $sql = 'DELETE FROM ' . $this->notification_webpush_table . '
312            WHERE ' . ($notification_type_id !== false ? $this->db->sql_in_set('notification_type_id', is_array($notification_type_id) ? $notification_type_id : [$notification_type_id]) : '1=1') .
313            ($user_id !== false ? ' AND ' . $this->db->sql_in_set('user_id', $user_id) : '') .
314            ($item_parent_id !== false ? ' AND ' . $this->db->sql_in_set('item_parent_id', $item_parent_id, false, true) : '');
315        $this->db->sql_query($sql);
316    }
317
318    /**
319     * {@inheritDoc}
320     */
321    public function prune_notifications($timestamp, $only_read = true): void
322    {
323        $sql = 'DELETE FROM ' . $this->notification_webpush_table . '
324            WHERE notification_time < ' . (int) $timestamp;
325        $this->db->sql_query($sql);
326
327        $this->config->set('read_notification_last_gc', (string) time(), false);
328    }
329
330    /**
331     * Clean data to contain only what we need for webpush notifications table
332     *
333     * @param array $data Notification data
334     * @return array Cleaned notification data
335     */
336    public static function clean_data(array $data): array
337    {
338        $row = [
339            'notification_type_id'    => null,
340            'item_id'                => null,
341            'item_parent_id'        => null,
342            'user_id'                => null,
343            'push_data'                => null,
344            'push_token'            => null,
345            'notification_time'        => null,
346        ];
347
348        return array_intersect_key($data, $row);
349    }
350
351    /**
352     * Get template data for the UCP
353     *
354     * @param helper $controller_helper
355     * @param form_helper $form_helper
356     *
357     * @return array
358     */
359    public function get_ucp_template_data(helper $controller_helper, form_helper $form_helper): array
360    {
361        $subscription_map = $this->get_user_subscription_map([$this->user->id()]);
362        $subscriptions = [];
363
364        if (isset($subscription_map[$this->user->id()]))
365        {
366            foreach ($subscription_map[$this->user->id()] as $subscription)
367            {
368                $subscriptions[] = [
369                    'endpoint'            => $subscription['endpoint'],
370                    'expirationTime'    => $subscription['expiration_time'],
371                ];
372            }
373        }
374
375        return [
376            'NOTIFICATIONS_WEBPUSH_ENABLE'    => $this->config['webpush_dropdown_subscribe'] || stripos($this->user->page['page'], 'notification_options'),
377            'U_WEBPUSH_SUBSCRIBE'            => $controller_helper->route('phpbb_ucp_push_subscribe_controller'),
378            'U_WEBPUSH_UNSUBSCRIBE'            => $controller_helper->route('phpbb_ucp_push_unsubscribe_controller'),
379            'VAPID_PUBLIC_KEY'                => $this->config['webpush_vapid_public'],
380            'U_WEBPUSH_WORKER_URL'            => $controller_helper->route('phpbb_ucp_push_worker_controller'),
381            'SUBSCRIPTIONS'                    => $subscriptions,
382            'WEBPUSH_FORM_TOKENS'            => $form_helper->get_form_tokens(\phpbb\ucp\controller\webpush::FORM_TOKEN_UCP),
383        ];
384    }
385
386    /**
387     * Get subscriptions for notify users
388     *
389     * @param array $notify_users Users to notify
390     *
391     * @return array Subscription map
392     */
393    protected function get_user_subscription_map(array $notify_users): array
394    {
395        // Get subscriptions for users
396        $user_subscription_map = [];
397
398        $sql = 'SELECT subscription_id, user_id, endpoint, p256dh, auth, expiration_time
399            FROM ' . $this->push_subscriptions_table . '
400            WHERE ' . $this->db->sql_in_set('user_id', $notify_users);
401        $result = $this->db->sql_query($sql);
402        while ($row = $this->db->sql_fetchrow($result))
403        {
404            $user_subscription_map[$row['user_id']][] = $row;
405        }
406        $this->db->sql_freeresult($result);
407
408        return $user_subscription_map;
409    }
410
411    /**
412     * Remove subscriptions
413     *
414     * @param array $subscription_ids Subscription ids to remove
415     * @return void
416     */
417    public function remove_subscriptions(array $subscription_ids): void
418    {
419        if (count($subscription_ids))
420        {
421            $sql = 'DELETE FROM ' . $this->push_subscriptions_table . '
422                    WHERE ' . $this->db->sql_in_set('subscription_id', $subscription_ids);
423            $this->db->sql_query($sql);
424        }
425    }
426
427    /**
428     * Clean expired subscriptions from the database
429     *
430     * @param array $user_subscription_map User subscription map
431     * @param array $expired_endpoints Expired endpoints
432     * @return void
433     */
434    protected function clean_expired_subscriptions(array $user_subscription_map, array $expired_endpoints): void
435    {
436        if (!count($expired_endpoints))
437        {
438            return;
439        }
440
441        $remove_subscriptions = [];
442        foreach ($expired_endpoints as $endpoint)
443        {
444            foreach ($user_subscription_map as $subscriptions)
445            {
446                foreach ($subscriptions as $subscription)
447                {
448                    if (isset($subscription['endpoint']) && $subscription['endpoint'] == $endpoint)
449                    {
450                        $remove_subscriptions[] = $subscription['subscription_id'];
451                    }
452                }
453            }
454        }
455
456        $this->remove_subscriptions($remove_subscriptions);
457    }
458
459    /**
460     * Set web push padding for endpoint
461     *
462     * @param \Minishlink\WebPush\WebPush $web_push
463     * @param string $endpoint
464     *
465     * @return void
466     */
467    protected function set_endpoint_padding(\Minishlink\WebPush\WebPush $web_push, string $endpoint): void
468    {
469        if (str_contains($endpoint, 'mozilla.com') || str_contains($endpoint, 'mozaws.net'))
470        {
471            try
472            {
473                $web_push->setAutomaticPadding(self::MOZILLA_FALLBACK_PADDING);
474            }
475            catch (\Exception)
476            {
477                // This shouldn't happen since we won't pass padding length outside limits
478            }
479        }
480    }
481}