/
druproid_notifications.module
1059 lines (908 loc) · 33.9 KB
/
druproid_notifications.module
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Druproid Notifications functionality.
*/
/**
* Constants Definition.
*/
//
// Device Types.
//
define('DRUPROID_NOTIFICATIONS_TYPE_ID_IOS', variable_get('druproid_notifications_type_id_ios', 0));
define('DRUPROID_NOTIFICATIONS_TYPE_ID_ANDROID', variable_get('druproid_notifications_type_id_anroid', 1));
//
// Apple Variables
//
// Apple Server
define('DRUPROID_NOTIFICATIONS_APNS_HOST', variable_get('druproid_notifications_apns_host', 'gateway.push.apple.com'));
// Apple Server port.
define('DRUPROID_NOTIFICATIONS_APNS_PORT', 2195);
// Apple Feedback Server, initially set to development server.
define('DRUPROID_NOTIFICATIONS_APNS_FEEDBACK_HOST', variable_get('druproid_notifications_apns_feedback_host', 'feedback.push.apple.com'));
// Apple Feedback Server port.
define('DRUPROID_NOTIFICATIONS_APNS_FEEDBACK_PORT', 2196);
// Name of certificate, initially set to development certificate.
define('DRUPROID_NOTIFICATIONS_APNS_CERTIFICATE', variable_get('druproid_notifications_apns_certificate', 'apns-production.pem'));
// Size limit for individual payload, in bytes.
define('DRUPROID_NOTIFICATIONS_APNS_PAYLOAD_SIZE_LIMIT', 255);
// Payload sound
define('DRUPROID_NOTIFICATIONS_APNS_NOTIFICATION_SOUND', variable_get('druproid_notifications_apns_notification_sound', 'default'));
// Boolean value to indicate wether Apple's feedback service should be called
// on cron to remove unused tokens from our database.
define('DRUPROID_NOTIFICATIONS_APNS_QUERY_FEEDBACK_SERVICE', variable_get('druproid_notifications_apns_query_feedback_service', 1));
// Maximum of messages to send per stream context.
define('DRUPROID_NOTIFICATIONS_APNS_STREAM_CONTEXT_LIMIT', variable_get('druproid_notifications_apns_stream_context_limit', 1));
//
// Google Variables
//
// Google Push Notification Types
// 0 => Cloud 2 Device Messaging
// 1 => Google Cloud Messaging
define('DRUPROID_NOTIFICATIONS_GOOGLE_TYPE_C2DM', 0);
define('DRUPROID_NOTIFICATIONS_GOOGLE_TYPE_GCM', 1);
define('DRUPROID_NOTIFICATIONS_GOOGLE_TYPE', variable_get('druproid_notifications_google_type', DRUPROID_NOTIFICATIONS_GOOGLE_TYPE_GCM));
//
// C2DM Variables
//
// C2DM Credentials.
define('DRUPROID_NOTIFICATIONS_C2DM_USERNAME', variable_get('druproid_notifications_c2dm_username', ''));
define('DRUPROID_NOTIFICATIONS_C2DM_PASSWORD', variable_get('druproid_notifications_c2dm_password', ''));
define('DRUPROID_NOTIFICATIONS_C2DM_CLIENT_LOGIN_ACTION_URL', variable_get('druproid_notifications_c2dm_client_login_action_url', 'https://www.google.com/accounts/ClientLogin'));
// C2DM Server Post URL
define('DRUPROID_NOTIFICATIONS_C2DM_SERVER_POST_URL', variable_get('druproid_notifications_c2dm_server_post_url', 'https://android.apis.google.com/c2dm/send'));
//
// GCM Variables
//
// set GCM API KEY
define('DRUPROID_NOTIFICATIONS_GCM_API_KEY_SET', variable_set('druproid_notifications_gcm_api_key', 'AIzaSyAEc4e4oiAAmTaIE8Wy9azXbNCgOGBxWrA'));
// GCM API KEY Credentials.
define('DRUPROID_NOTIFICATIONS_GCM_API_KEY', variable_get('druproid_notifications_gcm_api_key', ''));
// GCM Server Post URL
define('DRUPROID_NOTIFICATIONS_GCM_SERVER_POST_URL', variable_get('druproid_notifications_gcm_server_post_url', 'https://android.googleapis.com/gcm/send'));
/**
* Implements of hook_menu().
*/
function druproid_notifications_menu() {
$items = array();
$items['admin/config/services/druproid_notifications'] = array(
'type' => MENU_NORMAL_ITEM,
'title' => 'Druproid Notifications',
'access arguments' => array('send druproid notifications'),
'page callback' => 'drupal_get_form',
'page arguments' => array('druproid_notifications_admin_overview_form'),
'description' => 'Druproid Notifications Settings.',
'file' => 'druproid_notifications.admin.inc',
'file path' => drupal_get_path('module', 'druproid_notifications') . '/includes',
);
$items['admin/config/services/druproid_notifications/overview'] = array(
'type' => MENU_DEFAULT_LOCAL_TASK,
'title' => 'Overview',
'weight' => -50,
'access arguments' => array('send druproid notifications'),
'page callback' => 'drupal_get_form',
'page arguments' => array('druproid_notifications_admin_overview_form'),
'description' => 'Druproid Notifications Settings.',
'file' => 'druproid_notifications.admin.inc',
'file path' => drupal_get_path('module', 'druproid_notifications') . '/includes',
);
$items['admin/config/services/druproid_notifications/configure'] = array(
'type' => MENU_LOCAL_TASK,
'title' => 'Configuration',
'access arguments' => array('administer site configuration'),
'page callback' => 'drupal_get_form',
'page arguments' => array('druproid_notifications_admin_form'),
'description' => 'Druproid Notifications Settings.',
'file' => 'druproid_notifications.admin.inc',
'file path' => drupal_get_path('module', 'druproid_notifications') . '/includes',
);
$items['admin/config/services/druproid_notifications/message'] = array(
'type' => MENU_LOCAL_TASK,
'title' => 'Send druproid',
'access arguments' => array('send druproid notifications'),
'page callback' => 'drupal_get_form',
'page arguments' => array('druproid_notifications_mass_druproid_form'),
'description' => 'Send a Druproid Notification',
'file' => 'druproid_notifications.admin.inc',
'file path' => drupal_get_path('module', 'druproid_notifications') . '/includes',
);
return $items;
}
/**
* Implements of hook_cron().
*/
function druproid_notifications_cron() {
if (DRUPROID_NOTIFICATIONS_APNS_QUERY_FEEDBACK_SERVICE) {
druproid_notifications_apns_feedback_service();
}
}
/**
* Implements hook_permission().
*/
function druproid_notifications_permission() {
return array(
'register device token' => array(
'title' => t('Register Device Token'),
'description' => t('Allows users to register a device token.'),
),
'remove device token' => array(
'title' => t('Remove Device Token'),
'description' => t('Allows users to remove a device token.'),
),
'send druproid notifications' => array(
'title' => t('Send druproid notifications'),
'description' => t('Allow users to send a druproid notification to devices'),
),
);
}
/**
* Implements hook_services_resources().
*/
function druproid_notifications_services_resources() {
return array(
'druproid_notifications' => array(
'create' => array(
'help' => 'Registers a device token. For type, pass \'ios\' for iOS devices and \'android\' for Android devices.',
'callback' => '_druproid_notifications_service_create_device_token',
'file' => array(
'type' => 'inc',
'module' => 'druproid_notifications',
'name' => 'includes/druproid_notifications.service'
),
'access arguments' => array('register device token'),
'access arguments append' => FALSE,
'args' => array(
array(
'name' => 'token',
'type' => 'string',
'description' => 'Device Token',
'optional' => FALSE,
'source' => 'data',
),
array(
'name' => 'type',
'type' => 'string',
'description' => 'Device Type',
'optional' => FALSE,
'source' => 'data',
),
array(
'name' => 'language',
'type' => 'string',
'description' => 'Language',
'optional' => TRUE,
'source' => 'data',
),
),
),
'delete' => array(
'help' => 'Removes a registered a device token. Only needs the token.',
'callback' => '_druproid_notifications_service_delete_device_token',
'file' => array(
'type' => 'inc',
'module' => 'druproid_notifications',
'name' => 'includes/druproid_notifications.service'
),
'access arguments' => array('remove device token'),
'access arguments append' => FALSE,
'args' => array(
array(
'name' => 'token',
'type' => 'string',
'description' => 'Device Token',
'optional' => FALSE,
'source' => array('path' => '0'),
),
),
),
),
);
}
/**
* Implements hook_privatemsg_message_insert.
*/
function druproid_notifications_privatemsg_message_insert($message) {
if (variable_get('druproidnotifications_privatemsg_integration', 0)) {
// Compose the payload. If the body is empty, just use the subject line.
// Otherwise, combine subject and body.
$payload = (empty($message->body)) ? $message->subject : $message->subject . ' ' . $message->body;
$payload = 'From ' . $message->author->name . ': ' . $payload;
// Compose an array of recipients.
$recipients = array();
foreach ($message->recipients as $recipient) {
$recipients[] = $recipient->uid;
}
druproid_notifications_send_message($recipients, $payload);
}
}
/**
* Determine if this user has already stored a token
* in the database. The same device token can be
* registered for multiple users, because multiple
* users can login from the same device.
*
* @param $token
* Device Token.
* @param $uid
* User ID.
* @param $exclude
* Set this to true to find (at least one) other user(s) who have this
* token stored. Optional, defaults to false.
*
* @return
* User ID of token, if found.
*/
function druproid_notifications_find_token($token = '', $uid = '', $exclude = FALSE) {
if ($token == '') {
return FALSE;
}
$query = db_select('druproid_notifications_tokens', 'dnt');
$query->fields('dnt', array('token'));
$query->condition('dnt.token', $token);
if ($exclude) {
$query->condition('dnt.uid', $uid, '!=');
$query->range(0, 1);
}
else {
$query->condition('dnt.uid', $uid);
}
$result = $query->execute();
return $result->fetchField();
}
/**
* Store a token in the database.
* Removes all spaces in the token.
*
* @param $token
* Device token.
* @param $type_id
* Device type id.
* @param $uid
* User ID.
* @param $language
* Language that this token is registered for, optional.
*
* @return
* Failure to write a record will return FALSE, Otherwise SAVED_NEW.
*/
function druproid_notifications_store_token($token = '', $type_id = '', $uid = '', $language = '') {
// Let modules modify the token before it is saved to the database.
foreach(module_implements('druproid_notifications_store_token') as $module) {
$function = $module . '_druproid_notifications_store_token';
$function($token, $type_id, $uid);
}
if (!is_string($token) || !is_numeric($type_id) || !is_numeric($uid)) {
return FALSE;
}
// Default language to site default.
if ($language == '') {
$default_language = language_default();
$language = $default_language->language;
}
// Write record.
$table = 'druproid_notifications_tokens';
$record = new stdClass();
$record->token = $token;
$record->uid = $uid;
$record->type = $type_id;
$record->language = $language;
$record->timestamp = time();
return drupal_write_record($table, $record);
}
/**
* Open an APNS connection.
* Should be closed by calling fclose($connection) after usage.
*/
function druproid_notifications_open_apns() {
// Determine the absolute path of the certificate.
// @see http://stackoverflow.com/questions/809682
$apns_cert = _druproid_notifications_get_apns_certificate();
// Create a stream context.
$stream_context = stream_context_create();
// Set options on the stream context.
stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
//If the user has a passphrase stored, we use it.
$passphrase = variable_get('druproid_notifications_apns_passphrase', '');
if(strlen($passphrase)) {
stream_context_set_option($stream_context, 'ssl', 'passphrase', $passphrase);
}
// Open an Internet socket connection.
$apns = stream_socket_client('ssl://' . DRUPROID_NOTIFICATIONS_APNS_HOST . ':' . DRUPROID_NOTIFICATIONS_APNS_PORT, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
if (!$apns) {
watchdog('druproid_notifications', 'Connection to Apple Notification Server failed.', NULL, WATCHDOG_ERROR);
return FALSE;
}
else {
return $apns;
}
}
/**
* Check size of a druproid notification payload.
* Payload can't exceed DRUPROID_NOTIFICATIONS_APNS_PAYLOAD_SIZE_LIMIT.
*
* @param $payload
* Message.
*
* @return
* Returns true if message is below the limit, false otherwise.
*/
function druproid_notifications_check_payload_size($payload = '') {
if ($payload == '') {
return FALSE;
}
// JSON-encode the payload.
$payload = json_encode($payload);
// Verify that the payload doesn't exceed limit.
$payload_size = mb_strlen($payload, '8bit');
$size_valid = ($payload_size > DRUPROID_NOTIFICATIONS_APNS_PAYLOAD_SIZE_LIMIT) ? FALSE : TRUE;
return $size_valid;
}
/**
* Send out druproid notifications, switch automatically between delivery method.
*
* @param $recipients
* Array of user ids.
* @param $message
* Payload to send.
*/
function druproid_notifications_send_message($recipients, $message) {
if (!is_array($recipients) || !is_string($message)) {
return FALSE;
}
// Let modules modify the message before it is sent.
foreach(module_implements('druproid_notifications_send_message') as $module) {
$function = $module . '_druproid_notifications_send_message';
$function($message);
}
// Shorten the message to 255 characters / 8 bit.
$message = truncate_utf8($message, DRUPROID_NOTIFICATIONS_APNS_PAYLOAD_SIZE_LIMIT, TRUE, TRUE);
// Convert the payload into the correct format for delivery.
$payload = array('alert' => $message);
// Determine if any of the recipients have one or multiple tokens stored.
$tokens = array();
foreach ($recipients as $uid) {
$user_tokens = druproid_notification_get_user_tokens($uid);
if (!empty($user_tokens)) {
$tokens = array_merge($tokens, $user_tokens);
}
}
// Stop right here if none of these users have any tokens.
if (empty($tokens)) {
return FALSE;
}
// Group tokens into types.
$tokens_ios = array();
$tokens_android = array();
foreach ($tokens as $token) {
switch ($token['type']) {
case DRUPROID_NOTIFICATIONS_TYPE_ID_IOS:
$tokens_ios[] = $token['token'];
break;
case DRUPROID_NOTIFICATIONS_TYPE_ID_ANDROID:
$tokens_android[] = $token['token'];
break;
}
}
// Send payload to iOS recipients.
if (!empty($tokens_ios)) {
// Convert the payload into the correct format for APNS.
$payload_apns = array('aps' => $payload);
$result = druproid_notifications_apns_send_message($tokens_ios, $payload_apns);
}
// Send payload to Android recipients if configured correctly.
if (!empty($tokens_android) && ((DRUPROID_NOTIFICATIONS_C2DM_USERNAME && DRUPROID_NOTIFICATIONS_C2DM_PASSWORD) || DRUPROID_NOTIFICATIONS_GCM_API_KEY)) {
// Determine which method to use for Google push notifications.
switch (DRUPROID_NOTIFICATIONS_GOOGLE_TYPE) {
case DRUPROID_NOTIFICATIONS_GOOGLE_TYPE_C2DM:
$result = druproid_notifications_c2dm_send_message($tokens_android, $payload);
break;
case DRUPROID_NOTIFICATIONS_GOOGLE_TYPE_GCM:
$result = druproid_notifications_gcm_send_message($tokens_android, $payload);
break;
}
}
}
/**
* Send out druproid notifications through APNS.
*
* @param $tokens
* Array of iOS tokens
* @param $payload
* Payload to send. Minimum requirement
* is a nested array in this format:
* $payload = array(
* 'aps' => array(
* 'alert' => 'Druproid Notification Test',
* );
* );
*
* @return
* Array with the following keys:
* - count_attempted (# of attempted messages sent)
* - count_success (# of successful sends)
* - success (# boolean)
* - message (Prepared result message)
*/
function druproid_notifications_apns_send_message($tokens, $payload) {
if (!is_array($tokens) || empty($payload) || (is_array($tokens) && empty($tokens))) {
return FALSE;
}
$payload_apns = array();
// Allow for inclusion of custom payloads.
foreach ($payload as $key => $value) {
if ($key != 'aps') {
$payload_apns[$key] = $value;
}
}
// Add the default 'aps' key for the payload.
$payload_apns['aps'] = $payload['aps'];
// Set the default sound if no sound was set.
if (!isset($payload_apns['aps']['sound'])) {
$payload_apns['aps']['sound'] = DRUPROID_NOTIFICATIONS_APNS_NOTIFICATION_SOUND;
}
// JSON-encode the payload.
$payload_apns = json_encode($payload_apns);
$result = array(
'count_attempted' => 0,
'count_success' => 0,
'success' => 0,
'message' => '',
);
// Send a druproid notification to every recipient.
$stream_counter = 0;
foreach ($tokens as $token) {
// Open an apns connection, if necessary.
if ($stream_counter == 0) {
$apns = druproid_notifications_open_apns();
if (!$apns) {
$result['message'] = t('APNS connection could not be established. Check to make sure you are using a valid certificate file.');
return $result;
}
}
$stream_counter++;
$result['count_attempted']++;
$apns_message = chr(0) . chr(0) . chr(32) . pack('H*', $token) . chr(0) . chr(strlen($payload_apns)) . $payload_apns;
// Write the payload to the currently active streaming connection.
$success = fwrite($apns, $apns_message);
if ($success) {
$result['count_success']++;
}
elseif ($success == 0 || $success == FALSE || $success < strlen($apns_message)) {
$error_message = array(
'message' => t('APNS message could not be sent.'),
'token' => 'Token: ' . $token,
'data' => 'fwrite returned: ' . $success,
);
watchdog('druproid_notifications', implode($error_message, '<br />'));
}
// Reset the stream counter if no more messages should
// be sent with the current stream context.
// This results in the generation of a new stream context
// at the beginning of this loop.
if ($stream_counter >= DRUPROID_NOTIFICATIONS_APNS_STREAM_CONTEXT_LIMIT) {
$stream_counter = 0;
}
}
// Close the apns connection.
fclose($apns);
$result['message'] = t('Successfully sent !count_success iOS push messages (attempted to send !count messages).', array('!count_success' => $result['count_success'], '!count' => $result['count_attempted']));
$result['success'] = TRUE;
return $result;
}
/**
* Determine the auth string from C2DM server.
*/
function druproid_notifications_c2dm_token() {
$data = array(
'Email' => DRUPROID_NOTIFICATIONS_C2DM_USERNAME,
'Passwd' => DRUPROID_NOTIFICATIONS_C2DM_PASSWORD,
'accountType' => 'HOSTED_OR_GOOGLE',
'source' => 'Company-AppName-Version',
'service' => 'ac2dm',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, DRUPROID_NOTIFICATIONS_C2DM_CLIENT_LOGIN_ACTION_URL);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
// Get the auth token.
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth_token = $matches[1];
if (!$auth_token) {
watchdog('druproid_notifications', 'Google C2DM Server did not provide an authentication token.', NULL, WATCHDOG_ERROR);
}
else {
return $auth_token;
}
}
/**
* Send out druproid notifications through C2DM.
*
* @param $tokens
* Array of iOS tokens
* @param $payload
* Payload to send.
*
* @return
* Array with the following keys:
* - count_attempted (# of attempted messages sent)
* - count_success (# of successful sends)
* - success (# boolean)
* - message (Prepared result message)
*/
function druproid_notifications_c2dm_send_message($tokens, $payload) {
if (!is_array($tokens) || empty($payload) || (is_array($tokens) && empty($tokens))) {
return FALSE;
}
// Determine an updated authentication token.
// Google is very vague about how often this token changes,
// so we'll just get a new token every time.
$auth_token = druproid_notifications_c2dm_token();
if (!$auth_token) {
$result['message'] = t('Google C2DM Server did not provide an authentication token. Check your C2DM credentials.');
return $result;
}
// Define an array of result values.
$result = array(
'count_attempted' => 0,
'count_success' => 0,
'success' => 0,
'message' => '',
);
// Define the header.
$headers = array();
$headers[] = 'Authorization: GoogleLogin auth=' . $auth_token;
// Send a druproid notification to every recipient.
foreach ($tokens as $token) {
$result['count_attempted']++;
// Convert the payload into the correct format for C2DM payloads.
// Prefill an array with values from other modules first.
$data = array();
foreach ($payload as $key => $value) {
if ($key != 'alert') {
$data['data.' . $key] = $value;
}
}
// Fill the default values required for each payload.
$data['registration_id'] = $token;
$data['collapse_key'] = time();
$data['data.message'] = $payload['alert'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, druproid_NOTIFICATIONS_C2DM_SERVER_POST_URL);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
// If Google's server returns a reply, but that reply includes an error, log the error message.
if ($info['http_code'] == 200 && (isset($response) && preg_match('/Error/', $response))) {
watchdog('druproid_notifications', "Google's Server returned an error: " . $response, NULL, WATCHDOG_ERROR);
// If the device token is invalid or not registered (anymore because the user
// has uninstalled the application), remove this device token.
if (preg_match('/InvalidRegistration/', $response) || preg_match('/NotRegistered/', $response)) {
druproid_notifications_purge_token($token);
watchdog('daddyhunt_apns', 'C2DM token not valid anymore. Removing token ' . $token);
}
}
// Success if the http response status is 200 and the response
// data does not containt the word "Error".
if ($info['http_code'] == 200 && (isset($response) && !preg_match('/Error/', $response))) {
$result['count_success']++;
}
}
$result['message'] = t('Successfully sent !count_success Android push messages (attempted to send !count messages).', array('!count_success' => $result['count_success'], '!count' => $result['count_attempted']));
$result['success'] = TRUE;
return $result;
}
/**
* Send out druproid notifications through GCM.
*
* @link http://developer.android.com/guide/google/gcm/index.html
*
* @param $tokens
* Array of gcm tokens
* @param $payload
* Payload to send.
*
* @return
* Array with the following keys:
* - count_attempted (# of attempted messages sent)
* - count_success (# of successful sends)
* - success (# boolean)
* - message (Prepared result message)
*/
function druproid_notifications_gcm_send_message($tokens, $payload) {
if (!is_array($tokens) || empty($payload) || (is_array($tokens) && empty($tokens))) {
return FALSE;
}
// Define an array of result values.
$result = array(
'count_attempted' => 0,
'count_success' => 0,
'success' => 0,
'message' => '',
);
// Define the header.
$headers = array();
$headers[] = 'Content-Type:application/json';
$headers[] = 'Authorization:key=' . DRUPROID_NOTIFICATIONS_GCM_API_KEY;
// Check of many token bundles can be build.
$token_bundles = ceil(count($tokens) / 1000);
$result['count_attempted'] = count($tokens);
// Send a druproid notification to every recipient.
for ($i = 0; $i < $token_bundles; $i++) {
// Create a token bundle.
$bundle_tokens = array_slice($tokens, $i * 1000, 1000, FALSE);
// Convert the payload into the correct format for C2DM payloads.
// Prefill an array with values from other modules first.
$data = array();
foreach ($payload as $key => $value) {
if ($key != 'alert') {
$data['data'][$key] = $value;
}
}
// Fill the default values required for each payload.
$data['registration_ids'] = $bundle_tokens;
$data['collapse_key'] = (string) time();
$data['data']['message'] = $payload['alert'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, DRUPROID_NOTIFICATIONS_GCM_SERVER_POST_URL);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
$response_raw = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close($curl);
$response = FALSE;
if (isset($response_raw)) {
$response = json_decode($response_raw);
}
// If Google's server returns a reply, but that reply includes an error,
// log the error message.
if ($info['http_code'] == 200 && (!empty($response->failure))) {
watchdog('druproid_notifications', "Google's Server returned an error: " . $response_raw, NULL, WATCHDOG_ERROR);
// Analyze the failure.
foreach ($response->results as $token_index => $message_result) {
if (!empty($message_result->error)) {
// If the device token is invalid or not registered (anymore because the user
// has uninstalled the application), remove this device token.
if ($message_result->error == 'NotRegistered' || $message_result->error == 'InvalidRegistration') {
druproid_notifications_purge_token($bundle_tokens[$token_index]);
watchdog('druproid_notifications', 'GCM token not valid anymore. Removing token ' . $bundle_tokens[$token_index]);
}
}
}
}
// Count the successful sent druproid notifications if there are any.
if ($info['http_code'] == 200 && !empty($response->success)) {
$result['count_success'] += $response->success;
}
}
$result['message'] = t('Successfully sent !count_success Android push messages (attempted to send !count messages).', array('!count_success' => $result['count_success'], '!count' => $result['count_attempted']));
$result['success'] = TRUE;
return $result;
}
/**
* Determine all recipients from a specific device type.
*
* @param $type_id
* Device Type ID.
* @param $language
* Language code, optional.
* @param $raw
* Boolean, set true to retrieve the raw query results.
*
* @return
* Array of results, null if no entries.
*/
function druproid_notifications_get_tokens($type_id = '', $language = FALSE, $raw = FALSE) {
// Make sure this type_id is supported.
$valid_type_ids = array(DRUPROID_NOTIFICATIONS_TYPE_ID_IOS, DRUPROID_NOTIFICATIONS_TYPE_ID_ANDROID);
if (!in_array($type_id, $valid_type_ids)) {
return FALSE;
}
// Select all tokens for this type id.
$query = db_select('druproid_notifications_tokens', 'dnt');
$query->fields('dnt', array('token'));
$query->condition('dnt.type', $type_id);
// If language code is passed, limit the results by language.
if ($language) {
$query->condition('dnt.language', $language);
}
$result = $query->execute();
// Return raw result, if needed.
if ($raw) {
return $result;
}
// Otherwise, create an array of tokens.
else {
$tokens = array();
foreach ($result as $record) {
$tokens[] = $record->token;
}
return $tokens;
}
}
/**
* Determine all tokens for a specfic user.
*
* @param @uid
* User ID.
*
* @return
* Nested array of tokens, with user id, druproid notification type
* and token.
*/
function druproid_notification_get_user_tokens($uid = '') {
if ($uid == '' || !is_numeric($uid)) {
return FALSE;
}
// Select all tokens for this user.
$query = db_select('druproid_notifications_tokens', 'dnt');
$query->fields('dnt', array('token', 'uid', 'type'));
$query->condition('dnt.uid', $uid);
$result = $query->execute();
$tokens = array();
foreach ($result as $record) {
$tokens[$record->token] = array(
'token' => $record->token,
'uid' => $record->uid,
'type' => $record->type,
);
}
return $tokens;
}
/**
* Determine any languages used in the push
* notifications table.
*/
function druproid_notifications_used_languages() {
$query = db_select('druproid_notifications_tokens', 'dnt');
$query->fields('dnt', array('language'));
$query->distinct();
$result = $query->execute();
// Convert the records into an array with
// full language code available.
include_once DRUPAL_ROOT . '/includes/iso.inc';
$languages = _locale_get_predefined_list();
$used_languages = array();
foreach ($result as $record) {
$used_languages[$record->language] = $languages[$record->language][0];
}
if (!empty($used_languages)) {
// Sort the languages alphabetically.
$used_langauges = asort($used_languages);
// Add an "All" option.
array_unshift($used_languages, 'All Recipients');
}
return $used_languages;
}
/**
* Delete a token.
*
* @param $token
*/
function druproid_notifications_purge_token($token = '') {
if ($token == '' || !is_string($token)) {
return FALSE;
}
$query = db_delete('druproid_notifications_tokens');
$query->condition('token', $token);
return $query->execute();
}
/**
* Connect to Apple's feedback server to remove unused device tokens.
* Connection modeled after daddyhunt_apns_send_notifications function.
*
* @see http://stackoverflow.com/questions/4774681/php-script-for-apple-push-notification-feedback-service-gets-timeout-every-time
* @see http://stackoverflow.com/questions/1278834/php-technique-to-query-the-apns-feedback-server/2298882#2298882
*/
function druproid_notifications_apns_feedback_service() {
// Create a Stream context and open an Internet socket connection.
$stream_context = stream_context_create();
$apns_cert = _druproid_notifications_get_apns_certificate();
stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
$apns = stream_socket_client('ssl://' . DRUPROID_NOTIFICATIONS_APNS_FEEDBACK_HOST . ':' . DRUPROID_NOTIFICATIONS_APNS_FEEDBACK_PORT, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
if (!$apns) {
return;
}
// Gather expired tokens in an array
$tokens = array();
while (!feof($apns)) {
$data = fread($apns, 38);
if (strlen($data)) {
$tokens[] = unpack("N1timestamp/n1length/H*devtoken", $data);
}
}
// Close connection.
fclose($apns);
if (empty($tokens)) {
watchdog('druproid_notifications', 'Apple\'s feedback service returned no tokens to be removed.');
return;
}
// Remove all tokens that are not valid anymore.
$counter = 0;
foreach ($tokens as $token) {
druproid_notifications_purge_token($token['devtoken']);
$counter++;
}
// Give some feedback after the process finished.
watchdog('druproid_notifications', '!count were removed after pulling the Apple feedback service.', array('!count' => $counter));
}
/**
* Get the full path to the APNS certificate.
*
* @return string
* The path to the certificate file on the server.
*/
function _druproid_notifications_get_apns_certificate() {
$path = variable_get('druproid_notifications_apns_certificate_folder', '');
if (empty($path)) {
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'certificates' . DIRECTORY_SEPARATOR;
}
$path .= DRUPROID_NOTIFICATIONS_APNS_CERTIFICATE;
if (!file_exists($path)) {
watchdog('druproid_notifications', 'Cannot find apns certificate file at @path', array('@path' => $path), WATCHDOG_WARNING, l(t('settings'), 'admin/config/services/druproid_notifications/configure'));
}
return $path;
}