forked from phpbb-extensions/webpushnotifications
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpush.php
More file actions
626 lines (555 loc) · 18.7 KB
/
webpush.php
File metadata and controls
626 lines (555 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
<?php
/**
*
* phpBB Browser Push Notifications. An extension for the phpBB Forum Software package.
*
* @copyright (c) 2023, phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
namespace phpbb\webpushnotifications\notification\method;
use Minishlink\WebPush\Subscription;
use phpbb\config\config;
use phpbb\controller\helper;
use phpbb\db\driver\driver_interface;
use phpbb\log\log_interface;
use phpbb\notification\method\base;
use phpbb\notification\type\type_interface;
use phpbb\user;
use phpbb\user_loader;
use phpbb\webpushnotifications\form\form_helper;
use phpbb\webpushnotifications\json\sanitizer as json_sanitizer;
/**
* Web Push notification method class
* This class handles sending push messages for notifications
*/
class webpush extends base implements extended_method_interface
{
/** @var config */
protected $config;
/** @var driver_interface */
protected $db;
/** @var log_interface */
protected $log;
/** @var user_loader */
protected $user_loader;
/** @var user */
protected $user;
/** @var string */
protected $phpbb_root_path;
/** @var string */
protected $php_ext;
/** @var string Notification Web Push table */
protected $notification_webpush_table;
/** @var string Notification push subscriptions table */
protected $push_subscriptions_table;
/** @var int Fallback size for padding if endpoint is mozilla, see https://github.com/web-push-libs/web-push-php/issues/108#issuecomment-2133477054 */
public const MOZILLA_FALLBACK_PADDING = 2820;
/** @var array Map for storing push token between db insertion and sending of notifications */
private $push_token_map = [];
/**
* Notification Method Web Push constructor
*
* @param config $config
* @param driver_interface $db
* @param log_interface $log
* @param user_loader $user_loader
* @param user $user
* @param string $phpbb_root_path
* @param string $php_ext
* @param string $notification_webpush_table
* @param string $push_subscriptions_table
*/
public function __construct(config $config, driver_interface $db, log_interface $log, user_loader $user_loader, user $user,
string $phpbb_root_path, string $php_ext, string $notification_webpush_table, string $push_subscriptions_table)
{
$this->config = $config;
$this->db = $db;
$this->log = $log;
$this->user_loader = $user_loader;
$this->user = $user;
$this->phpbb_root_path = $phpbb_root_path;
$this->php_ext = $php_ext;
$this->notification_webpush_table = $notification_webpush_table;
$this->push_subscriptions_table = $push_subscriptions_table;
}
/**
* {@inheritDoc}
*/
public function get_type(): string
{
return 'notification.method.phpbb.wpn.webpush';
}
/**
* {@inheritDoc}
*/
public function is_available(type_interface $notification_type = null): bool
{
return $this->config->offsetGet('wpn_webpush_enable')
&& $this->config->offsetGet('wpn_webpush_vapid_public')
&& $this->config->offsetGet('wpn_webpush_vapid_private');
}
/**
* {@inheritDoc}
*/
public function is_enabled_by_default()
{
return (bool) $this->config['wpn_webpush_method_enabled'];
}
/**
* {@inheritdoc}
*/
public function get_notified_users($notification_type_id, array $options): array
{
$notified_users = [];
$sql = 'SELECT user_id
FROM ' . $this->notification_webpush_table . '
WHERE notification_type_id = ' . (int) $notification_type_id .
(isset($options['item_id']) ? ' AND item_id = ' . (int) $options['item_id'] : '') .
(isset($options['item_parent_id']) ? ' AND item_parent_id = ' . (int) $options['item_parent_id'] : '') .
(isset($options['user_id']) ? ' AND user_id = ' . (int) $options['user_id'] : '');
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
$notified_users[$row['user_id']] = $row;
}
$this->db->sql_freeresult($result);
return $notified_users;
}
/**
* Parse the queue and notify the users
*/
public function notify()
{
$insert_buffer = new \phpbb\db\sql_insert_buffer($this->db, $this->notification_webpush_table);
/** @var type_interface $notification */
foreach ($this->queue as $notification)
{
$data = $notification->get_insert_array();
$data += [
'push_data' => json_encode(array_merge(
$data,
['notification_type_name' => $notification->get_type()]
)),
'notification_time' => time(),
'push_token' => hash('sha256', random_bytes(32))
];
$data = self::clean_data($data);
$insert_buffer->insert($data);
$this->push_token_map[$notification->notification_type_id][$notification->item_id] = $data['push_token'];
}
$insert_buffer->flush();
$this->notify_using_webpush();
return false;
}
/**
* Notify using Web Push
*
* @return void
*/
protected function notify_using_webpush(): void
{
if (empty($this->queue))
{
return;
}
// Load all users we want to notify
$user_ids = [];
foreach ($this->queue as $notification)
{
$user_ids[] = $notification->user_id;
}
// Do not send push notifications to banned users
if (!function_exists('phpbb_get_banned_user_ids'))
{
include($this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext);
}
$banned_users = phpbb_get_banned_user_ids($user_ids);
// Load all the users we need
$notify_users = array_diff($user_ids, $banned_users);
if (empty($notify_users))
{
return;
}
$this->user_loader->load_users($notify_users, [USER_IGNORE]);
// Get subscriptions for users
$user_subscription_map = $this->get_user_subscription_map($notify_users);
$auth = [
'VAPID' => [
'subject' => generate_board_url(false),
'publicKey' => $this->config['wpn_webpush_vapid_public'],
'privateKey' => $this->config['wpn_webpush_vapid_private'],
],
];
$web_push = new \Minishlink\WebPush\WebPush($auth);
$number_of_notifications = 0;
$remove_subscriptions = [];
// Time to go through the queue and send notifications
/** @var type_interface $notification */
foreach ($this->queue as $notification)
{
$user = $this->user_loader->get_user($notification->user_id);
$user_subscriptions = $user_subscription_map[$notification->user_id] ?? [];
if (($user['user_type'] == USER_INACTIVE && $user['user_inactive_reason'] == INACTIVE_MANUAL)
|| empty($user_subscriptions))
{
continue;
}
// Add actual Web Push data
$data = [
'item_id' => $notification->item_id,
'type_id' => $notification->notification_type_id,
'user_id' => $notification->user_id,
'version' => $this->config['assets_version'],
'token' => hash('sha256', $user['user_form_salt'] . $this->push_token_map[$notification->notification_type_id][$notification->item_id]),
];
$json_data = json_encode($data);
foreach ($user_subscriptions as $subscription)
{
try
{
$this->set_endpoint_padding($web_push, $subscription['endpoint']);
$push_subscription = Subscription::create([
'endpoint' => $subscription['endpoint'],
'keys' => [
'p256dh' => $subscription['p256dh'],
'auth' => $subscription['auth'],
],
]);
$web_push->queueNotification($push_subscription, $json_data);
$number_of_notifications++;
}
catch (\ErrorException $exception)
{
$remove_subscriptions[] = $subscription['subscription_id'];
$this->log->add('user', $user['user_id'], $user['user_ip'] ?? '', 'LOG_WEBPUSH_SUBSCRIPTION_REMOVED', false, [
'reportee_id' => $user['user_id'],
$user['username'],
]);
}
}
}
// Remove any subscriptions that couldn't be queued, i.e. that have invalid data
$this->remove_subscriptions($remove_subscriptions);
// List to fill with expired subscriptions based on return
$expired_endpoints = [];
try
{
foreach ($web_push->flush($number_of_notifications) as $report)
{
if (!$report->isSuccess())
{
// Fill array of endpoints to remove if subscription has expired
if ($report->isSubscriptionExpired())
{
$expired_endpoints[] = $report->getEndpoint();
}
else
{
$report_data = json_sanitizer::sanitize($report->jsonSerialize());
$this->log->add('admin', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$report_data['reason']]);
}
}
}
}
catch (\ErrorException $exception)
{
$this->log->add('critical', ANONYMOUS, '', 'LOG_WEBPUSH_MESSAGE_FAIL', false, [$exception->getMessage()]);
}
$this->clean_expired_subscriptions($user_subscription_map, $expired_endpoints);
// We're done, empty the queue
$this->empty_queue();
}
/**
* {@inheritdoc}
*/
public function mark_notifications($notification_type_id, $item_id, $user_id, $time = false, $mark_read = true)
{
// Send dismiss push messages BEFORE deleting to close the browser notifications
// This is called by the notification manager when phpBB marks notifications as read
// (e.g., viewing a PM, viewing a topic, clicking "mark all read", etc.)
if ($notification_type_id !== false && $item_id !== false && $user_id !== false)
{
// When item_id and user_id are specific, send dismiss for each notification
// Arrays are typically same-length parallel arrays or single notification type with specific item
$type_ids = is_array($notification_type_id) ? $notification_type_id : [$notification_type_id];
$item_ids = is_array($item_id) ? $item_id : [$item_id];
$user_ids = is_array($user_id) ? $user_id : [$user_id];
// Most common case: single notification (single type, item, user)
if (count($type_ids) === 1 && count($item_ids) === 1 && count($user_ids) === 1)
{
$this->dismiss_using_webpush($type_ids[0], $item_ids[0], $user_ids[0]);
}
// Parallel arrays case: matching length arrays
else if (count($type_ids) === count($item_ids) && count($item_ids) === count($user_ids))
{
for ($i = 0, $iMax = count($type_ids); $i < $iMax; $i++)
{
$this->dismiss_using_webpush($type_ids[$i], $item_ids[$i], $user_ids[$i]);
}
}
// Mixed case: iterate combinations (rare but handle it)
else
{
foreach ($type_ids as $type)
{
foreach ($item_ids as $iid)
{
foreach ($user_ids as $uid)
{
$this->dismiss_using_webpush($type, $iid, $uid);
}
}
}
}
}
// Delete the notifications from our table
$sql = 'DELETE FROM ' . $this->notification_webpush_table . '
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') .
($user_id !== false ? ' AND ' . $this->db->sql_in_set('user_id', $user_id) : '') .
($item_id !== false ? ' AND ' . $this->db->sql_in_set('item_id', $item_id) : '');
$this->db->sql_query($sql);
}
/**
* {@inheritdoc}
*/
public function mark_notifications_by_parent($notification_type_id, $item_parent_id, $user_id, $time = false, $mark_read = true)
{
// Send dismiss push messages BEFORE deleting
// Query needed because service worker uses item_id (not item_parent_id) to match notification tags
if ($notification_type_id !== false && $user_id !== false && $item_parent_id !== false)
{
$sql = 'SELECT notification_type_id, item_id, user_id
FROM ' . $this->notification_webpush_table . '
WHERE ' . $this->db->sql_in_set('notification_type_id', is_array($notification_type_id) ? $notification_type_id : [$notification_type_id]) .
' AND ' . $this->db->sql_in_set('user_id', is_array($user_id) ? $user_id : [$user_id]) .
' AND ' . $this->db->sql_in_set('item_parent_id', is_array($item_parent_id) ? $item_parent_id : [$item_parent_id], false, true);
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
$this->dismiss_using_webpush($row['notification_type_id'], $row['item_id'], $row['user_id']);
}
$this->db->sql_freeresult($result);
}
// Delete the notifications from our table
$sql = 'DELETE FROM ' . $this->notification_webpush_table . '
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') .
($user_id !== false ? ' AND ' . $this->db->sql_in_set('user_id', $user_id) : '') .
($item_parent_id !== false ? ' AND ' . $this->db->sql_in_set('item_parent_id', $item_parent_id, false, true) : '');
$this->db->sql_query($sql);
}
/**
* {@inheritDoc}
*/
public function prune_notifications($timestamp, $only_read = true): void
{
$sql = 'DELETE FROM ' . $this->notification_webpush_table . '
WHERE notification_time < ' . (int) $timestamp;
$this->db->sql_query($sql);
$this->config->set('read_notification_last_gc', (string) time(), false);
}
/**
* Clean data to contain only what we need for webpush notifications table
*
* @param array $data Notification data
* @return array Cleaned notification data
*/
public static function clean_data(array $data): array
{
$row = [
'notification_type_id' => null,
'item_id' => null,
'item_parent_id' => null,
'user_id' => null,
'push_data' => null,
'push_token' => null,
'notification_time' => null,
];
return array_intersect_key($data, $row);
}
/**
* Get template data for the UCP
*
* @param helper $controller_helper
* @param form_helper $form_helper
*
* @return array
*/
public function get_ucp_template_data(helper $controller_helper, form_helper $form_helper): array
{
$subscription_map = $this->get_user_subscription_map([$this->user->id()]);
$subscriptions = [];
if (isset($subscription_map[$this->user->id()]))
{
foreach ($subscription_map[$this->user->id()] as $subscription)
{
$subscriptions[] = [
'endpoint' => $subscription['endpoint'],
'expirationTime' => (int) $subscription['expiration_time'],
];
}
}
return [
'NOTIFICATIONS_WEBPUSH_ENABLE' => ($this->config['load_notifications'] && $this->config['allow_board_notifications'] && $this->config['wpn_webpush_dropdown_subscribe']) || stripos($this->user->page['page'], 'notification_options'),
'U_WEBPUSH_SUBSCRIBE' => $controller_helper->route('phpbb_webpushnotifications_ucp_push_subscribe_controller'),
'U_WEBPUSH_UNSUBSCRIBE' => $controller_helper->route('phpbb_webpushnotifications_ucp_push_unsubscribe_controller'),
'VAPID_PUBLIC_KEY' => $this->config['wpn_webpush_vapid_public'],
'U_WEBPUSH_WORKER_URL' => $controller_helper->route('phpbb_webpushnotifications_ucp_push_worker_controller'),
'SUBSCRIPTIONS' => $subscriptions,
'WEBPUSH_FORM_TOKENS' => $form_helper->get_form_tokens(\phpbb\webpushnotifications\ucp\controller\webpush::FORM_TOKEN_UCP),
'S_WEBPUSH_POPUP_PROMPT' => $this->config['wpn_webpush_popup_prompt'] && $this->user->id() != ANONYMOUS && $this->user->data['user_type'] != USER_IGNORE,
];
}
/**
* Get subscriptions for notify users
*
* @param array $notify_users Users to notify
*
* @return array Subscription map
*/
protected function get_user_subscription_map(array $notify_users): array
{
// Get subscriptions for users
$user_subscription_map = [];
$sql = 'SELECT subscription_id, user_id, endpoint, p256dh, auth, expiration_time
FROM ' . $this->push_subscriptions_table . '
WHERE ' . $this->db->sql_in_set('user_id', $notify_users);
$result = $this->db->sql_query($sql);
while ($row = $this->db->sql_fetchrow($result))
{
$user_subscription_map[$row['user_id']][] = $row;
}
$this->db->sql_freeresult($result);
return $user_subscription_map;
}
/**
* Remove subscriptions
*
* @param array $subscription_ids Subscription ids to remove
* @return void
*/
public function remove_subscriptions(array $subscription_ids): void
{
if (count($subscription_ids))
{
$sql = 'DELETE FROM ' . $this->push_subscriptions_table . '
WHERE ' . $this->db->sql_in_set('subscription_id', $subscription_ids);
$this->db->sql_query($sql);
}
}
/**
* Clean expired subscriptions from the database
*
* @param array $user_subscription_map User subscription map
* @param array $expired_endpoints Expired endpoints
* @return void
*/
protected function clean_expired_subscriptions(array $user_subscription_map, array $expired_endpoints): void
{
if (!count($expired_endpoints))
{
return;
}
$remove_subscriptions = [];
foreach ($expired_endpoints as $endpoint)
{
foreach ($user_subscription_map as $subscriptions)
{
foreach ($subscriptions as $subscription)
{
if (isset($subscription['endpoint']) && $subscription['endpoint'] == $endpoint)
{
$remove_subscriptions[] = $subscription['subscription_id'];
}
}
}
}
$this->remove_subscriptions($remove_subscriptions);
}
/**
* Set web push padding for endpoint
*
* @param \Minishlink\WebPush\WebPush $web_push
* @param string $endpoint
*
* @return void
*/
protected function set_endpoint_padding(\Minishlink\WebPush\WebPush $web_push, string $endpoint): void
{
if (strpos($endpoint, 'mozilla.com') || strpos($endpoint, 'mozaws.net'))
{
try
{
$web_push->setAutomaticPadding(self::MOZILLA_FALLBACK_PADDING);
}
catch (\Exception $e)
{
// This shouldn't happen since we won't pass padding length outside limits
}
}
}
/**
* Send dismiss message via Web Push to close a browser notification
*
* @param int $notification_type_id Notification type ID
* @param int $item_id Item ID
* @param int $user_id User ID
* @return void
*/
protected function dismiss_using_webpush(int $notification_type_id, int $item_id, int $user_id): void
{
// Get user subscriptions
$user_subscription_map = $this->get_user_subscription_map([$user_id]);
$user_subscriptions = $user_subscription_map[$user_id] ?? [];
if (empty($user_subscriptions))
{
return;
}
$auth = [
'VAPID' => [
'subject' => generate_board_url(false),
'publicKey' => $this->config['wpn_webpush_vapid_public'],
'privateKey' => $this->config['wpn_webpush_vapid_private'],
],
];
$web_push = new \Minishlink\WebPush\WebPush($auth);
// Create dismiss message
$data = [
'action' => 'dismiss',
'notifications' => [[
'type_id' => $notification_type_id,
'item_id' => $item_id,
]],
];
$json_data = json_encode($data);
// Send dismiss message to all user's subscriptions
foreach ($user_subscriptions as $subscription)
{
try
{
$this->set_endpoint_padding($web_push, $subscription['endpoint']);
$push_subscription = Subscription::create([
'endpoint' => $subscription['endpoint'],
'keys' => [
'p256dh' => $subscription['p256dh'],
'auth' => $subscription['auth'],
],
]);
$web_push->queueNotification($push_subscription, $json_data);
}
catch (\ErrorException $exception)
{
// Ignore - dismiss is best-effort
}
}
// Flush and ignore any errors - dismiss messages are best-effort
try
{
$web_push->flush();
}
catch (\ErrorException $exception)
{
// Ignore errors
}
}
}