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
469 lines (396 loc) · 13.5 KB
/
webpush.php
File metadata and controls
469 lines (396 loc) · 13.5 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
<?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\ucp\controller;
use phpbb\config\config;
use phpbb\controller\helper as controller_helper;
use phpbb\db\driver\driver_interface;
use phpbb\exception\http_exception;
use phpbb\language\language;
use phpbb\notification\manager;
use phpbb\webpushnotifications\ext;
use phpbb\webpushnotifications\form\form_helper;
use phpbb\webpushnotifications\json\sanitizer as json_sanitizer;
use phpbb\path_helper;
use phpbb\request\request_interface;
use phpbb\symfony_request;
use phpbb\user;
use phpbb\user_loader;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
class webpush
{
/** @var string UCP form token name */
public const FORM_TOKEN_UCP = 'ucp_webpush';
/** @var array Allowed push service endpoint hosts https://github.com/pushpad/known-push-services */
public const PUSH_SERVICE_WHITELIST = [
'android.googleapis.com',
'fcm.googleapis.com',
'updates.push.services.mozilla.com',
'updates-autopush.stage.mozaws.net',
'updates-autopush.dev.mozaws.net',
];
/** @var array Allowed push service endpoint host wildcard suffixes (e.g. *.notify.windows.com) https://github.com/pushpad/known-push-services */
public const PUSH_SERVICE_WILDCARD_SUFFIXES = [
'.notify.windows.com',
'.push.apple.com',
];
/** @var config */
protected $config;
/** @var controller_helper */
protected $controller_helper;
/** @var driver_interface */
protected $db;
/** @var form_helper */
protected $form_helper;
/** @var language */
protected $language;
/** @var manager */
protected $notification_manager;
/** @var path_helper */
protected $path_helper;
/** @var request_interface */
protected $request;
/** @var user_loader */
protected $user_loader;
/** @var user */
protected $user;
/** @var Environment */
protected $template;
/** @var string */
protected $notification_webpush_table;
/** @var string */
protected $push_subscriptions_table;
/**
* Constructor for webpush controller
*
* @param config $config
* @param controller_helper $controller_helper
* @param driver_interface $db
* @param form_helper $form_helper
* @param language $language
* @param manager $notification_manager
* @param path_helper $path_helper
* @param request_interface $request
* @param user_loader $user_loader
* @param user $user
* @param Environment $template
* @param string $notification_webpush_table
* @param string $push_subscriptions_table
*/
public function __construct(config $config, controller_helper $controller_helper, driver_interface $db, form_helper $form_helper, language $language, manager $notification_manager,
path_helper $path_helper, request_interface $request, user_loader $user_loader, user $user, Environment $template, string $notification_webpush_table, string $push_subscriptions_table)
{
$this->config = $config;
$this->controller_helper = $controller_helper;
$this->db = $db;
$this->form_helper = $form_helper;
$this->language = $language;
$this->notification_manager = $notification_manager;
$this->path_helper = $path_helper;
$this->request = $request;
$this->user_loader = $user_loader;
$this->user = $user;
$this->template = $template;
$this->notification_webpush_table = $notification_webpush_table;
$this->push_subscriptions_table = $push_subscriptions_table;
}
/**
* Handle request to retrieve notification data
*
* @return JsonResponse
*/
public function notification(): JsonResponse
{
if (!$this->request->is_ajax() || $this->user->data['is_bot'] || $this->user->data['user_type'] == USER_INACTIVE)
{
throw new http_exception(Response::HTTP_FORBIDDEN, 'NO_AUTH_OPERATION');
}
return new JsonResponse($this->get_user_notifications(), 200, [], true);
}
/**
* Get notification data for logged in user
*
* @return string Notification data
*/
private function get_user_notifications(): string
{
if ($this->user->id() === ANONYMOUS)
{
return $this->get_anonymous_notifications();
}
// Subscribe should only be available for logged-in "normal" users
if ($this->user->data['user_type'] == USER_IGNORE)
{
throw new http_exception(Response::HTTP_FORBIDDEN, 'NO_AUTH_OPERATION');
}
$item_id = $this->request->variable('item_id', 0);
$type_id = $this->request->variable('type_id', 0);
$sql = 'SELECT push_data
FROM ' . $this->notification_webpush_table . '
WHERE user_id = ' . (int) $this->user->id() . '
AND notification_type_id = ' . (int) $type_id . '
AND item_id = ' . (int) $item_id;
$result = $this->db->sql_query($sql);
$notification_data = $this->db->sql_fetchfield('push_data');
$this->db->sql_freeresult($result);
if (!$notification_data)
{
throw new http_exception(Response::HTTP_BAD_REQUEST, 'AJAX_ERROR_TEXT');
}
return $this->get_notification_data($notification_data);
}
/**
* Get notification data for not logged in user via token
*
* @return string
*/
private function get_anonymous_notifications(): string
{
$token = $this->request->variable('token', '');
if ($token)
{
$item_id = $this->request->variable('item_id', 0);
$type_id = $this->request->variable('type_id', 0);
$user_id = $this->request->variable('user_id', 0);
$sql = 'SELECT push_data, push_token
FROM ' . $this->notification_webpush_table . '
WHERE user_id = ' . (int) $user_id . '
AND notification_type_id = ' . (int) $type_id . '
AND item_id = ' . (int) $item_id;
$result = $this->db->sql_query($sql);
$notification_row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
if (!isset($notification_row['push_data'], $notification_row['push_token']) || !$notification_row)
{
throw new http_exception(Response::HTTP_BAD_REQUEST, 'AJAX_ERROR_TEXT');
}
$notification_data = $notification_row['push_data'];
$push_token = $notification_row['push_token'];
// Check if passed push token is valid
$sql = 'SELECT user_form_salt, user_lang
FROM ' . USERS_TABLE . '
WHERE user_id = ' . (int) $user_id;
$result = $this->db->sql_query($sql);
$row = $this->db->sql_fetchrow($result);
$this->db->sql_freeresult($result);
$user_form_token = $row['user_form_salt'];
$user_lang = $row['user_lang'];
$expected_push_token = hash('sha256', $user_form_token . $push_token);
if ($expected_push_token === $token)
{
if ($user_lang !== $this->language->get_used_language())
{
$this->language->set_user_language($user_lang, true);
}
return $this->get_notification_data($notification_data);
}
}
throw new http_exception(Response::HTTP_FORBIDDEN, 'NO_AUTH_OPERATION');
}
/**
* Get notification data for output from json encoded data stored in database
*
* @param string $notification_data Encoded data stored in database
*
* @return string Data for notification output with javascript
*/
private function get_notification_data(string $notification_data): string
{
$row_data = json_decode($notification_data, true);
// Old notification data is pre-parsed and just needs to be returned
if (isset($row_data['heading']))
{
return $notification_data;
}
// Get notification from row_data
$notification = $this->notification_manager->get_item_type_class($row_data['notification_type_name'], $row_data);
// Load users for notification
$this->user_loader->load_users($notification->users_to_query());
return json_encode([
'heading' => ext::decode_entities($this->config['sitename'], ENT_QUOTES),
'title' => strip_tags(ext::decode_entities($notification->get_title())),
'text' => strip_tags(ext::decode_entities($notification->get_reference())),
'url' => htmlspecialchars_decode($notification->get_url()),
'avatar' => $this->prepare_avatar($notification->get_avatar()),
]);
}
/**
* Handle request to push worker javascript
*
* @return Response
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function worker(): Response
{
$content = $this->template->render('@phpbb_webpushnotifications/push_worker.js.twig', [
'U_WEBPUSH_GET_NOTIFICATION' => $this->controller_helper->route('phpbb_webpushnotifications_ucp_push_get_notification_controller'),
'ASSETS_VERSION' => $this->config['assets_version'],
]);
$response = new Response($content);
$response->headers->set('Content-Type', 'text/javascript; charset=UTF-8');
if (!empty($this->user->data['is_bot']))
{
// Let reverse proxies know we detected a bot.
$response->headers->set('X-PHPBB-IS-BOT', 'yes');
}
return $response;
}
/**
* Check if a push subscription endpoint belongs to an allowed push service
*
* @param string $endpoint The push subscription endpoint URL
* @return bool True if the endpoint host matches a known/allowed push service
*/
public function is_valid_endpoint(string $endpoint): bool
{
$host = parse_url($endpoint, PHP_URL_HOST);
if (empty($host))
{
return false;
}
if (in_array($host, self::PUSH_SERVICE_WHITELIST, true))
{
return true;
}
foreach (self::PUSH_SERVICE_WILDCARD_SUFFIXES as $suffix)
{
if (substr($host, -strlen($suffix)) === $suffix)
{
return true;
}
}
return false;
}
/**
* Check (un)subscribe form for valid link hash
*
* @throws http_exception If form is invalid or user should not request (un)subscription
* @return void
*/
protected function check_subscribe_requests(): void
{
if (!$this->form_helper->check_form_tokens(self::FORM_TOKEN_UCP))
{
throw new http_exception(Response::HTTP_BAD_REQUEST, 'FORM_INVALID');
}
// Subscribe should only be available for logged-in "normal" users
if (!$this->request->is_ajax() || $this->user->id() === ANONYMOUS || $this->user->data['is_bot']
|| $this->user->data['user_type'] == USER_IGNORE || $this->user->data['user_type'] == USER_INACTIVE)
{
throw new http_exception(Response::HTTP_FORBIDDEN, 'NO_AUTH_OPERATION');
}
}
/**
* Handle subscribe requests
*
* @param symfony_request $symfony_request
* @return JsonResponse
*/
public function subscribe(symfony_request $symfony_request): JsonResponse
{
$this->check_subscribe_requests();
$data = json_sanitizer::decode($symfony_request->get('data', ''));
if (!$this->is_valid_endpoint($data['endpoint']))
{
throw new http_exception(Response::HTTP_BAD_REQUEST, 'WEBPUSH_INVALID_ENDPOINT');
}
$sql = 'INSERT INTO ' . $this->push_subscriptions_table . ' ' . $this->db->sql_build_array('INSERT', [
'user_id' => $this->user->id(),
'endpoint' => $data['endpoint'],
'expiration_time' => $data['expiration_time'] ?? 0,
'p256dh' => $data['keys']['p256dh'],
'auth' => $data['keys']['auth'],
]);
$this->db->sql_query($sql);
return new JsonResponse([
'success' => true,
'form_tokens' => $this->form_helper->get_form_tokens(self::FORM_TOKEN_UCP),
]);
}
/**
* Handle unsubscribe requests
*
* @param symfony_request $symfony_request
* @return JsonResponse
*/
public function unsubscribe(symfony_request $symfony_request): JsonResponse
{
$this->check_subscribe_requests();
$data = json_sanitizer::decode($symfony_request->get('data', ''));
$endpoint = $data['endpoint'];
$sql = 'DELETE FROM ' . $this->push_subscriptions_table . '
WHERE user_id = ' . (int) $this->user->id() . "
AND endpoint = '" . $this->db->sql_escape($endpoint) . "'";
$this->db->sql_query($sql);
return new JsonResponse([
'success' => true,
'form_tokens' => $this->form_helper->get_form_tokens(self::FORM_TOKEN_UCP),
]);
}
/**
* Handle toggle popup prompt requests
*
* @return JsonResponse
*/
public function toggle_popup(): JsonResponse
{
$this->check_subscribe_requests();
// Toggle the user preference
$new_value = !$this->user->data['user_wpn_popup_disabled'];
$sql = 'UPDATE ' . USERS_TABLE . '
SET user_wpn_popup_disabled = ' . (int) $new_value . '
WHERE user_id = ' . (int) $this->user->id();
$this->db->sql_query($sql);
return new JsonResponse([
'success' => true,
'disabled' => $new_value,
'form_tokens' => $this->form_helper->get_form_tokens(self::FORM_TOKEN_UCP),
]);
}
/**
* Takes an avatar string (usually in full html format already) and extracts the url.
* If the avatar url is a relative path, it's converted to an absolute path.
*
* Converts:
* <img class="avatar" src="./path/to/avatar=123456789.gif" width="123" height="123" alt="User avatar" />
* or <img class="avatar" src="./styles/prosilver/theme/images/no_avatar.gif" data-src="./path/to/avatar=123456789.gif" width="123" height="123" alt="User avatar" />
* into https://myboard.url/path/to/avatar=123456789.gif
*
* @param string $avatar
* @return array 'src' => Absolute path to avatar image
*/
protected function prepare_avatar($avatar): array
{
$pattern = '/src=["\']?([^"\'>]+)["\']?/';
preg_match_all($pattern, $avatar, $matches);
$path = !empty($matches[1]) ? end($matches[1]) : $avatar;
return ['src' => preg_replace('#^' . preg_quote($this->path_helper->get_web_root_path(), '#') . '#', $this->get_board_url(), $path, 1)];
}
/**
* Returns the board url (and caches it in the function)
*
* @return string the generated board url
*/
protected function get_board_url()
{
static $board_url;
if (empty($board_url))
{
$board_url = generate_board_url() . '/';
}
return $board_url;
}
}