-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMillcoPush.module
More file actions
537 lines (385 loc) · 12.7 KB
/
MillcoPush.module
File metadata and controls
537 lines (385 loc) · 12.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
<?php
namespace ProcessWire;
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
/**
* MillcoPush
*
* Playing around with push notifications,
*
*/
class MillcoPush extends WireData implements Module, ConfigurableModule
{
public static function getModuleInfo()
{
return [
'title' => 'MillcoPush',
'summary' => 'Playing around with pushin',
'version' => 1.1,
'autoload' => true, // needs to be autoload for hooks.
'singular' => true,
'permanent' => false,
'permission' => '',
'icon' => 'arrow-right',
'requires' => [
'PHP>=8.0.0',
'ProcessWire>=3.0.16',
],
'installs' => ['ProcessMillcoPush']
];
}
// Add config fields.
function getModuleConfigInputfields(InputfieldWrapper $inputfields)
{
// Add a new Inputfield to it
$f = $this->wire('modules')->get('InputfieldText');
$f->attr('name', 'public_key');
// $f->attr('initValue', 'default thing');
$f->attr('value', $this->get('public_key'));
$f->label = 'Public key';
$inputfields->add($f);
// Add a new Inputfield to it
$f = $this->wire('modules')->get('InputfieldText');
$f->attr('name', 'private_key');
// $f->attr('initValue', 'default thing');
$f->attr('value', $this->get('private_key'));
$f->label = 'Private key';
$inputfields->add($f);
return $inputfields;
}
static protected $defaults = array(
'private_key' => '',
'public_key' => ''
);
public function __construct()
{
// populate defaults, which will get replaced with actual
// configured values before the init/ready methods are called
// again this is done in ProcessMillcoPush now.
$this->setArray(self::$defaults);
}
// init() method: This is called during the initialization after all modules have been loaded but before ProcessWire has fully bootstrapped and started delivering content.
// It’s the right place to add hooks or events that occur before page rendering starts.
public function init()
{
/** @var MillcoPush $this */
// Add a deck
wire()->addHook('/millcopush/subscription/manage/', function ($event) {
include('ajax_subscription_manage.php');
});
}
//ready() method: This is called after ProcessWire is fully bootstrapped, and is about to start rendering a page. At this point, the entire API is available and ready for use. This method can be used when you depend on the current page being accessed, like changing or adding certain behaviors or settings based on the current page or user.
public function ready() {}
/**
*
* If we have a public key then write out a subscribe
* button and the relevant javascript
* @return String $markup
*/
public function markup_subs_butts()
{
$public_key = $this->get('public_key');
$markup = '';
if ($public_key) {
$markup .= wire('files')->render(wire('config')->paths->siteModules . 'MillcoPush/markup/subs_buttons.php', ['mp' => $this, 'public_key' => $public_key]);
} else {
$markup .= '<div class="alert">Missing public key.</div>';
}
return $markup;
}
/**
* Add a subscription
* @param Array $params
*/
public function subscription_add($sub_array)
{
$db = $this->wire('database');
// TODO should check params here before trying
// to do an update.
$i = "INSERT INTO `millco_push_subscriptions` (
user_key,
mp_authToken,
mp_contentEncoding,
mp_endpoint,
mp_subscription_json
) VALUES (:user_key, :authtoken, :contentEncoding, :endpoint, :subscription_json);";
$params = array(
":user_key" => $sub_array['user_key'],
":authtoken" => $sub_array['authToken'],
":contentEncoding" => $sub_array['contentEncoding'],
":endpoint" => $sub_array['endpoint'],
":subscription_json" => $sub_array['subscription_json'],
);
$query = $db->prepare($i);
$query->execute($params);
return $db->lastInsertId();;
}
/**
* Delete a subscription
* @param Array $params
*/
public function subscription_delete($sub_array)
{
$db = $this->wire('database');
$d = "DELETE FROM `millco_push_subscriptions` WHERE
user_key = :user_key
AND mp_authToken = :authtoken
LIMIT 10";
$params = array(
":user_key" => $sub_array['user_key'],
":authtoken" => $sub_array['authToken']
);
$deleted = $db->prepare($d);
$result = $deleted->execute($params);
return $result;
}
/**
* Update a subscription
* Apparenrly the endpoint can change...
* @param Array $params
*/
public function subscription_update($sub_array)
{
$db = $this->wire('database');
// let's also zero the strikes if we've updated the endpoint
$q = "UPDATE `millco_push_subscriptions`
SET mp_endpoint=:mp_endpoint, strikes=0
WHERE user_key= :user_key AND mp_authToken = :authtoken
LIMIT 1
";
$params = array(
":mp_endpoint" => $sub_array['endpoint'],
":user_key" => $sub_array['user_key'],
":authtoken" => $sub_array['authToken'],
);
$updated = $db->prepare($q);
$result = $updated->execute($params);
return $result;
}
/**
* Send a notification to an array of users. For example, when a page that is being followed has been updated we can
* pull out a list of users who are following and push a message to them.
* @param Array of user IDs
* @param String message
*/
function send_push_notification_to_users($users_array, $message, $url='')
{
// get subscription objects for these users.
$user_subs = $this->users_subscriptions($users_array);
require __DIR__ . '/webpush/vendor/autoload.php';
// Build message options.
$message_options=[];
$message_options['message']= $message;
// $message_options['icon']='/android-chrome-192x192.png';
// if we've been passed a url then add it to our data value
// We need to look for this click_action in the service worker js.
if($url!='' && filter_var($url, FILTER_VALIDATE_URL)){
$data=array("click_action"=>$url);
$message_options['data'] = $data;
}
$message_options_json= json_encode($message_options);
// array of notifications
$notifications = [];
// loop through our subscriptions and
// add them to our list
foreach ($user_subs as $user_sub) {
// store the client-side `PushSubscription` object (calling `.toJSON` on it) as-is and then create a WebPush\Subscription from it
$subscription = Subscription::create(json_decode($user_sub['mp_subscription_json'], true));
$notification = [];
$notification['user_key'] = $user_sub['user_key'];
$notification['subscription'] = $subscription;
$notification['payload'] = $message_options_json;
$notifications[] = $notification;
}
// TODO:
$auth = array(
'VAPID' => array(
'subject' => 'https://millipedia.com/',
'publicKey' => $this->get('public_key'),
'privateKey' => $this->get('private_key')
),
);
// $defaultOptions = [
// 'TTL' => 300, // defaults to 4 weeks
// 'urgency' => 'normal', // protocol defaults to "normal". (very-low, low, normal, or high)
// 'topic' => 'Update', // not defined by default. Max. 32 characters from the URL or filename-safe Base64 characters sets
// 'batchSize' => 1000, // defaults to 1000
// ];
$webPush = new WebPush($auth);
// $webPush->setDefaultOptions($defaultOptions);
// send multiple notifications with payload
foreach ($notifications as $notification) {
$webPush->queueNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
);
}
$notifications_sent=0;
/**
* Check sent results
* @var MessageSentReport $report
*/
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
$notifications_sent++;
$this->log("[v] Message sent successfully for subscription {$endpoint}.");
} else {
$this->log("[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}");
// Add a strike against this endpoint.
$this->strike($endpoint);
}
}
return $notifications_sent;
}
/**
* Strike!
* If a message has failed to send then increment the strikes against it.
* We use the endpoint as a key ... cos hey, that's what we get back from WebPush
*
* @var String $endpoint
*/
public function strike($endpoint){
$database = $this->wire('database');
$sql = "SELECT strikes, user_key FROM `millco_push_subscriptions` WHERE `mp_endpoint` = :endpoint";
$select = $database->prepare($sql);
try {
$select->execute([':endpoint' => $endpoint]);
$row = $select->fetch();
if($row['strikes'] > 3){
// We've had 3 goes. Let's delete this subscription.
$query = $this->database->prepare("DELETE FROM `millco_push_subscriptions` WHERE mp_endpoint=:endpoint LIMIT 1");
$delete_result = $query->execute(
array(
':endpoint' => $endpoint
)
);
if($delete_result){
$this->log("Subscription for user " . $row['user_key'] . " deleted");
}else{
$this->log("Unable to delete subscription for user " . $row['user_key'] . "");
}
}else{
// increment strikes for this endpoint
$sql = "UPDATE `millco_push_subscriptions` SET `strikes` = `strikes` + 1 WHERE `mp_endpoint` = :endpoint";
$update = $database->prepare($sql);
try {
$update->execute([':endpoint' => $endpoint]);
} catch (PDOException $e) {
throw new WireException("Database query error: " . $e->getMessage());
}
}
} catch (PDOException $e) {
throw new WireException("Database query error: " . $e->getMessage());
}
// If this is the
}
/**
* Return an array of unique user ids from the subscriptions table.
*/
public function subscribed_users()
{
// get a list of our subscribed users.
$db = $this->wire('database');
$q = "SELECT DISTINCT user_key
FROM `millco_push_subscriptions`
";
$query = $db->prepare($q);
$query->execute();
$subscribed_users = $query->fetchAll();
return $subscribed_users;
}
/**
* Return subscriptions for a user.
* They might have subscribed several times of course
*/
public function user_subscriptions($user_key)
{
// get a list of our subscribed users.
$db = $this->wire('database');
$user_key = (int)$user_key;
$q = "SELECT * FROM `millco_push_subscriptions` WHERE user_key = $user_key ";
$query = $db->prepare($q);
$query->execute();
$users_subs = $query->fetchAll();
return $users_subs;
}
/**
* Return subscriptions for an array of users.
* They might have subscribed several times of course
* @param Array $user_key_array - an array of user ids.
*/
public function users_subscriptions($user_key_array)
{
$db = $this->wire('database');
$users_subs = array();
if (is_array($user_key_array) && count($user_key_array)) {
// pdo wants a string
$user_key_array_string = implode(',', $user_key_array);
// $q = "SELECT * FROM `millco_push_subscriptions` WHERE user_key IN (:user_key_array_string)";
// $params = array(
// ":user_key_array_string" => $user_key_array_string
// );
// $query = $db->prepare($q);
// $query->execute($params);
// $users_subs = $query->fetchAll();
$q = "SELECT * FROM `millco_push_subscriptions` WHERE user_key IN ($user_key_array_string)";
$query = $db->prepare($q);
$query->execute();
while($row=$query->fetch()){
$users_subs[]=$row;
}
}
return $users_subs;
}
public function notify_user($user_key, $message, $url='')
{
// All this does now is stick the user id into an
// array and pass it over to send_push_notification_to_users
$users_array=[];
$users_array[]=$user_key;
$success=$this->send_push_notification_to_users($users_array,$message, $url);
return $success;
}
public function ___install()
{
$database = $this->wire('database');
$sql = "CREATE TABLE IF NOT EXISTS `millco_push_subscriptions` (
`mp_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`user_key` INT(10) NOT NULL,
`mp_authToken` VARCHAR(255) NOT NULL,
`mp_contentEncoding` VARCHAR(255) NOT NULL,
`mp_endpoint` VARCHAR(255) NOT NULL,
`mp_subscription_json` TEXT NOT NULL,
`strikes` INT NOT NULL DEFAULT 0
);";
try {
$database->exec($sql);
} catch (Exception $e) {
$this->message("Could not create table: " . $e->getMessage());
}
return true;
}
public function ___uninstall()
{
$database = $this->wire('database');
$sql = "DROP TABLE `millco_push_subscriptions`;";
try {
$database->exec($sql);
} catch (Exception $e) {
$this->message("Could not drop table: " . $e->getMessage());
}
return true;
}
/**
* Upgrade bits
*/
public function upgrade($fromVersion, $toVersion) {
if ($fromVersion < 1.1) {
$database = $this->wire('database');
// Add the column 'strikes'
$database->query("ALTER TABLE `millco_push_subscriptions` ADD `strikes` INT NOT NULL DEFAULT 0");
$this->log("Subscriptions table updated to include strike col");
}
}
}