forked from OneSignal/OneSignal-WordPress-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonesignal-admin.php
847 lines (731 loc) · 40.1 KB
/
onesignal-admin.php
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
<?php
defined( 'ABSPATH' ) or die('This page may not be accessed directly.');
function onesignal_change_footer_admin() {
return '';
}
class OneSignal_Admin {
/**
* Increment $RESOURCES_VERSION any time the CSS or JavaScript changes to view the latest changes.
*/
private static $RESOURCES_VERSION = '40';
private static $SAVE_POST_NONCE_KEY = 'onesignal_meta_box_nonce';
private static $SAVE_POST_NONCE_ACTION = 'onesignal_meta_box';
public static $SAVE_CONFIG_NONCE_KEY = 'onesignal_config_page_nonce';
public static $SAVE_CONFIG_NONCE_ACTION = 'onesignal_config_page';
public function __construct() {
}
public static function init() {
$onesignal = new self();
if (class_exists('WDS_Log_Post')) {
function exception_error_handler($errno, $errstr, $errfile, $errline) {
try {
switch ($errno) {
case E_USER_ERROR:
onesignal_debug('[ERROR]', $errstr . ' @ ' . $errfile . ':' . $errline);
exit(1);
break;
case E_USER_WARNING:
onesignal_debug('[WARNING]', $errstr . ' @ ' . $errfile . ':' . $errline);
break;
case E_USER_NOTICE || E_NOTICE:
//onesignal_debug('NOTICE: ' . $errstr . ' @ ' . $errfile . ':' . $errline);
break;
case E_STRICT:
//onesignal_debug('DEPRECATED: ' . $errstr . ' @ ' . $errfile . ':' . $errline);
break;
default:
onesignal_debug('[UNKNOWN ERROR]', '(' . $errno . '): ' . $errstr . ' @ ' . $errfile . ':' . $errline);
break;
}
return true;
} catch (Exception $ex) {
return true;
}
}
set_error_handler("exception_error_handler");
function fatal_exception_error_handler() {
$error = error_get_last();
try {
switch ($error['type']) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_PARSE:
onesignal_debug('[CRITICAL ERROR]', '(' . $error['type'] . ') ' . $error['message'] . ' @ ' . $error['file'] . ':' . $error['line']);
}
} catch (Exception $ex) {
return true;
}
}
register_shutdown_function('fatal_exception_error_handler');
}
if (OneSignalUtils::can_modify_plugin_settings()) {
add_action( 'admin_menu', array(__CLASS__, 'add_admin_page') );
}
if (OneSignalUtils::can_send_notifications()) {
add_action('admin_init', array( __CLASS__, 'add_onesignal_post_options' ));
}
add_action( 'save_post', array(__CLASS__, 'on_save_post'), 1, 3 );
add_action( 'transition_post_status', array( __CLASS__, 'on_transition_post_status' ), 10, 3 );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'admin_styles' ) );
return $onesignal;
}
public static function admin_styles() {
wp_enqueue_style( 'onesignal-admin-styles', plugin_dir_url( __FILE__ ) . 'views/css/onesignal-menu-styles.css', false, OneSignal_Admin::$RESOURCES_VERSION);
}
/**
* Save the meta when the post is saved.
* @param int $post_id The ID of the post being saved.
*/
public static function on_save_post($post_id, $post, $updated) {
if ($post->post_type == 'wdslp-wds-log') {
// Prevent recursive post logging
return;
}
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if (!isset( $_POST[OneSignal_Admin::$SAVE_POST_NONCE_KEY] ) ) {
// This is called on every new post ... not necessary to log it.
// onesignal_debug('Nonce is not set for post ' . $post->post_title . ' (ID ' . $post_id . ')');
return $post_id;
}
$nonce = $_POST[OneSignal_Admin::$SAVE_POST_NONCE_KEY];
// Verify that the nonce is valid.
if (!wp_verify_nonce($nonce, OneSignal_Admin::$SAVE_POST_NONCE_ACTION)) {
onesignal_debug('Nonce is not valid for ' . $post->post_title . ' (ID ' . $post_id . ')');
return $post_id;
}
/*
* If this is an autosave, our form has not been submitted,
* so we don't want to do anything.
*/
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
/* OK, it's safe for us to save the data now. */
/* Some WordPress environments seem to be inconsistent about whether on_save_post is called before transition_post_status
* Check flag in case we just sent a notification for this post (this on_save_post is called after a successful send)
*/
$just_sent_notification = (get_post_meta($post_id, 'onesignal_notification_already_sent', true) == true);
if ($just_sent_notification) {
// Reset our flag
update_post_meta($post_id, 'onesignal_notification_already_sent', false);
onesignal_debug('A notification was just sent, so ignoring on_save_post. Resetting check flag.');
return;
}
if (array_key_exists('onesignal_meta_box_present', $_POST)) {
update_post_meta($post_id, 'onesignal_meta_box_present', true);
onesignal_debug('Set post metadata "onesignal_meta_box_present" to true.');
} else {
update_post_meta($post_id, 'onesignal_meta_box_present', false);
onesignal_debug('Set post metadata "onesignal_meta_box_present" to false.');
}
/* Even though the meta box always contains the checkbox, if an HTML checkbox is not checked, it is not POSTed to the server */
if (array_key_exists('send_onesignal_notification', $_POST)) {
update_post_meta($post_id, 'onesignal_send_notification', true);
onesignal_debug('Set post metadata "onesignal_send_notification" to true.');
} else {
update_post_meta($post_id, 'onesignal_send_notification', false);
onesignal_debug('Set post metadata "onesignal_send_notification" to false.');
}
}
public static function add_onesignal_post_options() {
// If there is an error or success message we should display, display it now
function admin_notice_error() {
$onesignal_transient_error = get_transient('onesignal_transient_error');
if ( !empty($onesignal_transient_error) ) {
delete_transient( 'onesignal_transient_error' );
echo $onesignal_transient_error;
}
$onesignal_transient_success = get_transient('onesignal_transient_success');
if ( !empty($onesignal_transient_success) ) {
delete_transient( 'onesignal_transient_success' );
echo $onesignal_transient_success;
}
}
add_action( 'admin_notices', 'admin_notice_error');
// Add our meta box for the "post" post type (default)
add_meta_box('onesignal_notif_on_post',
'OneSignal Push Notifications',
array( __CLASS__, 'onesignal_notif_on_post_html_view' ),
'post',
'side',
'high');
// Then add our meta box for all other post types that are public but not built in to WordPress
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names';
$operator = 'and';
$post_types = get_post_types( $args, $output, $operator );
foreach ( $post_types as $post_type ) {
add_meta_box(
'onesignal_notif_on_post',
'OneSignal Push Notifications',
array( __CLASS__, 'onesignal_notif_on_post_html_view' ),
$post_type,
'side',
'high'
);
}
}
/**
* Render Meta Box content.
* @param WP_Post $post The post object.
*/
public static function onesignal_notif_on_post_html_view($post) {
$post_type = $post->post_type;
$onesignal_wp_settings = OneSignal::get_onesignal_settings();
// Add an nonce field so we can check for it later.
wp_nonce_field(OneSignal_Admin::$SAVE_POST_NONCE_ACTION, OneSignal_Admin::$SAVE_POST_NONCE_KEY, true);
// Our plugin config setting "Automatically send a push notification when I publish a post from the WordPress editor"
$settings_send_notification_on_wp_editor_post = $onesignal_wp_settings['notification_on_post'];
/* This is a scheduled post and the user checked "Send a notification on post publish/update". */
$post_metadata_was_send_notification_checked = (get_post_meta($post->ID, 'onesignal_send_notification', true) == true);
// We check the checkbox if: setting is enabled on Config page, post type is ONLY "post", and the post has not been published (new posts are status "auto-draft")
$meta_box_checkbox_send_notification = ($settings_send_notification_on_wp_editor_post && // If setting is enabled
$post->post_type == "post" && // Post type must be type post for checkbox to be auto-checked
in_array($post->post_status, array("future", "draft", "auto-draft", "pending"))) || // Post is scheduled, incomplete, being edited, or is awaiting publication
($post_metadata_was_send_notification_checked);
if (has_filter('onesignal_meta_box_send_notification_checkbox_state')) {
$meta_box_checkbox_send_notification = apply_filters('onesignal_meta_box_send_notification_checkbox_state', $post, $onesignal_wp_settings);
}
onesignal_debug('$meta_box_checkbox_send_notification:', $meta_box_checkbox_send_notification);
onesignal_debug(' [$meta_box_checkbox_send_notification]', 'has_filter(onesignal_meta_box_send_notification_checkbox_state):', has_filter('onesignal_meta_box_send_notification_checkbox_state'));
onesignal_debug(' [$meta_box_checkbox_send_notification]', 'onesignal_meta_box_send_notification_checkbox_state filter result:', apply_filters('onesignal_meta_box_send_notification_checkbox_state', $post, $onesignal_wp_settings));
onesignal_debug(' [$meta_box_checkbox_send_notification]', '$settings_send_notification_on_wp_editor_post:', $settings_send_notification_on_wp_editor_post);
onesignal_debug(' [$meta_box_checkbox_send_notification]', '$settings_send_notification_on_wp_editor_post:', $settings_send_notification_on_wp_editor_post);
onesignal_debug(' [$meta_box_checkbox_send_notification]', '$post->post_type == "post":', $post->post_type == "post", '(' . $post->post_type . ')');
onesignal_debug(' [$meta_box_checkbox_send_notification]', 'in_array($post->post_status, array("future", "draft", "auto-draft", "pending"):', in_array($post->post_status, array("future", "draft", "auto-draft", "pending")), '(' . $post->post_status . ')');
?>
<input type="hidden" name="onesignal_meta_box_present" value="true"></input>
<input type="checkbox" name="send_onesignal_notification" value="true" <?php if ($meta_box_checkbox_send_notification) { echo "checked"; } ?>></input>
<label>
<?php if ($post->post_status == "publish") {
echo "Send notification on " . $post_type . " update";
} else {
echo "Send notification on " . $post_type . " publish";
} ?>
</label>
<?php
}
public static function save_config_page($config) {
if (!OneSignalUtils::can_modify_plugin_settings()) {
onesignal_debug('Not saving plugin settings because the current user is not an administrator.');
set_transient( 'onesignal_transient_error', '<div class="error notice onesignal-error-notice">
<p><strong>OneSignal Push:</strong><em> Only administrators are allowed to save plugin settings.</em></p>
</div>', 86400 );
return;
}
$sdk_dir = plugin_dir_path( __FILE__ ) . 'sdk_files/';
$onesignal_wp_settings = OneSignal::get_onesignal_settings();
$new_app_id = $config['app_id'];
// Validate the UUID
if( preg_match('/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/', $new_app_id, $m))
$onesignal_wp_settings['app_id'] = trim($new_app_id);
if (array_key_exists('gcm_sender_id', $config) && (is_numeric($config['gcm_sender_id']) || $config['gcm_sender_id'] === '')) {
$onesignal_wp_settings['gcm_sender_id'] = trim($config['gcm_sender_id']);
}
if (array_key_exists('subdomain', $config)) {
$onesignal_wp_settings['subdomain'] = str_replace(' ', '', $config['subdomain']);
} else {
$onesignal_wp_settings['subdomain'] = "";
}
$onesignal_wp_settings['subdomain'] = trim($onesignal_wp_settings['subdomain']);
$onesignal_wp_settings['is_site_https_firsttime'] = 'set';
$booleanSettings = array(
'is_site_https',
'prompt_auto_register',
'use_modal_prompt',
'send_welcome_notification',
'notification_on_post',
'notification_on_post_from_plugin',
'showNotificationIconFromPostThumbnail',
'showNotificationImageFromPostThumbnail',
'chrome_auto_dismiss_notifications',
'prompt_customize_enable',
'notifyButton_showAfterSubscribed',
'notifyButton_enable',
'notifyButton_prenotify',
'notifyButton_showcredit',
'notifyButton_customize_enable',
'notifyButton_customize_colors_enable',
'notifyButton_customize_offset_enable',
'send_to_mobile_platforms',
'show_gcm_sender_id',
'use_custom_manifest',
'use_custom_sdk_init',
'show_notification_send_status_message',
'use_http_permission_request',
'customize_http_permission_request',
'use_slidedown_permission_message_for_https'
);
OneSignal_Admin::saveBooleanSettings($onesignal_wp_settings, $config, $booleanSettings);
$stringSettings = array(
'app_rest_api_key',
'safari_web_id',
'prompt_action_message',
'prompt_example_notification_title_desktop',
'prompt_example_notification_message_desktop',
'prompt_example_notification_title_mobile',
'prompt_example_notification_message_mobile',
'prompt_example_notification_caption',
'prompt_auto_accept_title',
'prompt_site_name',
'prompt_cancel_button_text',
'prompt_accept_button_text',
'welcome_notification_title',
'welcome_notification_message',
'welcome_notification_url',
'notifyButton_size',
'notifyButton_theme',
'notifyButton_position',
'notifyButton_color_background',
'notifyButton_color_foreground',
'notifyButton_color_badge_background',
'notifyButton_color_badge_foreground',
'notifyButton_color_badge_border',
'notifyButton_color_pulse',
'notifyButton_color_popup_button_background',
'notifyButton_color_popup_button_background_hover',
'notifyButton_color_popup_button_background_active',
'notifyButton_color_popup_button_color',
'notifyButton_offset_bottom',
'notifyButton_offset_left',
'notifyButton_offset_right',
'notifyButton_message_prenotify',
'notifyButton_tip_state_unsubscribed',
'notifyButton_tip_state_subscribed',
'notifyButton_tip_state_blocked',
'notifyButton_message_action_subscribed',
'notifyButton_message_action_resubscribed',
'notifyButton_message_action_unsubscribed',
'notifyButton_dialog_main_title',
'notifyButton_dialog_main_button_subscribe',
'notifyButton_dialog_main_button_unsubscribe',
'notifyButton_dialog_blocked_title',
'notifyButton_dialog_blocked_message',
'utm_additional_url_params',
'allowed_custom_post_types',
'notification_title',
'custom_manifest_url',
'http_permission_request_modal_title',
'http_permission_request_modal_message',
'http_permission_request_modal_button_text',
'persist_notifications'
);
OneSignal_Admin::saveStringSettings($onesignal_wp_settings, $config, $stringSettings);
OneSignal::save_onesignal_settings($onesignal_wp_settings);
return $onesignal_wp_settings;
}
public static function saveBooleanSettings(&$onesignal_wp_settings, &$config, $settings) {
foreach ($settings as $setting) {
if (array_key_exists($setting, $config)) {
$onesignal_wp_settings[$setting] = true;
} else {
$onesignal_wp_settings[$setting] = false;
}
}
}
public static function saveStringSettings(&$onesignal_wp_settings, &$config, $settings) {
foreach ($settings as $setting) {
if (array_key_exists($setting, $config)) {
$value = $config[$setting];
$value = OneSignalUtils::normalize($value);
$onesignal_wp_settings[$setting] = $value;
}
}
}
public static function add_admin_page() {
$OneSignal_menu = add_menu_page('OneSignal Push',
'OneSignal Push',
'manage_options',
'onesignal-push',
array(__CLASS__, 'admin_menu')
);
OneSignal_Admin::save_config_settings_form();
add_action( 'load-' . $OneSignal_menu, array(__CLASS__, 'admin_custom_load') );
}
public static function save_config_settings_form() {
// If the user is trying to save the form, require a valid nonce or die
if (array_key_exists('app_id', $_POST)) {
// check_admin_referer dies if not valid; no if statement necessary
check_admin_referer(OneSignal_Admin::$SAVE_CONFIG_NONCE_ACTION, OneSignal_Admin::$SAVE_CONFIG_NONCE_KEY);
$onesignal_wp_settings = OneSignal_Admin::save_config_page($_POST);
}
}
public static function admin_menu() {
require_once( plugin_dir_path( __FILE__ ) . '/views/config.php' );
}
public static function admin_custom_load() {
add_action('admin_enqueue_scripts', array(__CLASS__, 'admin_custom_scripts'));
$onesignal_wp_settings = OneSignal::get_onesignal_settings();
if (
$onesignal_wp_settings['app_id'] == '' ||
$onesignal_wp_settings['app_rest_api_key'] == ''
) {
function admin_notice_setup_not_complete() {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {
activateSetupTab('setup/0');
});
</script>
<div class="error notice onesignal-error-notice">
<p><strong>OneSignal Push:</strong> <em>Your setup is not complete. Please follow the Setup guide to set up web push notifications. Both the App ID and REST API Key fields are required.</em></p>
</div>
<?php
}
add_action('admin_notices', 'admin_notice_setup_not_complete');
}
if (!function_exists('curl_init')) {
function admin_notice_curl_not_installed() {
?>
<div class="error notice onesignal-error-notice">
<p><strong>OneSignal Push:</strong> <em>cURL is not installed on this server. cURL is required to send notifications. Please make sure cURL is installed on your server before continuing.</em></p>
</div>
<?php
}
add_action( 'admin_notices', 'admin_notice_curl_not_installed');
}
}
public static function admin_custom_scripts() {
add_filter('admin_footer_text', 'onesignal_change_footer_admin', 9999); // 9999 means priority, execute after the original fn executes
wp_enqueue_style( 'icons', plugin_dir_url( __FILE__ ) . 'views/css/icons.css', false, OneSignal_Admin::$RESOURCES_VERSION);
wp_enqueue_style( 'semantic-ui', plugin_dir_url( __FILE__ ) . 'views/css/semantic-ui.css', false, OneSignal_Admin::$RESOURCES_VERSION);
wp_enqueue_style( 'site', plugin_dir_url( __FILE__ ) . 'views/css/site.css', false, OneSignal_Admin::$RESOURCES_VERSION);
wp_enqueue_script( 'jquery.min', plugin_dir_url( __FILE__ ) . 'views/javascript/jquery.min.js', false, OneSignal_Admin::$RESOURCES_VERSION);
wp_enqueue_script( 'semantic-ui', plugin_dir_url( __FILE__ ) . 'views/javascript/semantic-ui.js', false, OneSignal_Admin::$RESOURCES_VERSION);
wp_enqueue_script( 'jquery.cookie', plugin_dir_url( __FILE__ ) . 'views/javascript/jquery.cookie.js', false, OneSignal_Admin::$RESOURCES_VERSION);
wp_enqueue_script( 'site', plugin_dir_url( __FILE__ ) . 'views/javascript/site-admin.js', false, OneSignal_Admin::$RESOURCES_VERSION);
}
/**
* Returns true if more than one notification has been sent in the last minute.
*/
public static function get_sending_rate_limit_wait_time() {
onesignal_debug('Called is_over_sending_rate_limit()');
$last_send_time = get_option('onesignal.last_send_time');
onesignal_debug(' [is_over_sending_rate_limit] Last send time:', $last_send_time);
if ($last_send_time) {
$time_elapsed_since_last_send = ONESIGNAL_API_RATE_LIMIT_SECONDS - (current_time('timestamp') - intval($last_send_time));
if ($time_elapsed_since_last_send > 0) {
onesignal_debug(' [is_over_sending_rate_limit] Current send time (' . current_time('timestamp') . ') is less than rate limit time after the last send time.');
return $time_elapsed_since_last_send;
}
}
return false;
}
/**
* Updates the last sent timestamp, used in rate limiting notifications sent more than 1 per minute.
*/
public static function update_last_sent_timestamp() {
update_option('onesignal.last_send_time', current_time('timestamp'));
}
/**
* The main function that actually sends a notification to OneSignal.
*/
public static function send_notification_on_wp_post($new_status, $old_status, $post) {
try {
if (!function_exists('curl_init')) {
onesignal_debug('Canceling send_notification_on_wp_post because curl_init() is not a defined function.');
return;
}
$time_to_wait = self::get_sending_rate_limit_wait_time();
if ($time_to_wait > 0) {
set_transient('onesignal_transient_error', '<div class="error notice onesignal-error-notice">
<p><strong>OneSignal Push:</strong><em> Please try again in ' . $time_to_wait . ' seconds. Only one notification can be sent every ' . ONESIGNAL_API_RATE_LIMIT_SECONDS . ' seconds.</em></p>
</div>', 86400);
return;
}
$onesignal_wp_settings = OneSignal::get_onesignal_settings();
/* Looks like on_save_post is called after transition_post_status so we'll have to check POST data in addition to post meta data */
/* Settings related to creating a post involving the WordPress editor displaying the OneSignal meta box
**********************************************************************************************************/
/* Returns true if there is POST data */
$was_posted = !empty($_POST);
/* When this post was created or updated, the OneSignal meta box in the WordPress post editor screen was visible */
$onesignal_meta_box_present = $was_posted && array_key_exists('onesignal_meta_box_present', $_POST) && $_POST['onesignal_meta_box_present'] == 'true';
/* The checkbox "Send notification on post publish/update" on the OneSignal meta box is checked */
$onesignal_meta_box_send_notification_checked = $was_posted && array_key_exists('send_onesignal_notification', $_POST) && $_POST['send_onesignal_notification'] == 'true';
/* This is a scheduled post and the OneSignal meta box was present. */
$post_metadata_was_onesignal_meta_box_present = (get_post_meta($post->ID, 'onesignal_meta_box_present', true) == true);
/* This is a scheduled post and the user checked "Send a notification on post publish/update". */
$post_metadata_was_send_notification_checked = (get_post_meta($post->ID, 'onesignal_send_notification', true) == true);
/* Either we were just posted from the WordPress post editor form, or this is a scheduled notification and it was previously submitted from the post editor form */
$posted_from_wordpress_editor = $onesignal_meta_box_present || $post_metadata_was_onesignal_meta_box_present;
/* ********************************************************************************************************* */
/* Settings related to creating a post outside of the WordPress editor NOT displaying the OneSignal meta box
************************************************************************************************************/
/* OneSignal plugin setting "Automatically send a push notification when I create a post from 3rd party plugins"
* If set to true, send only if *publishing* a post type *post* from *something other than the default WordPress editor*.
* The filter hooks "onesignal_exclude_post" and "onesignal_include_post" can override this behavior as long as the option to automatically send from 3rd party plugins is set.
*/
$settings_send_notification_on_non_editor_post_publish = $onesignal_wp_settings['notification_on_post_from_plugin'];
$additional_custom_post_types_string = str_replace(' ', '', $onesignal_wp_settings['allowed_custom_post_types']);
$additional_custom_post_types_array = array_filter(explode(',', $additional_custom_post_types_string));
onesignal_debug('Additional allowed custom post types:', $additional_custom_post_types_string);
$non_editor_post_publish_do_send_notification = $settings_send_notification_on_non_editor_post_publish &&
($post->post_type == "post" || in_array($post->post_type, $additional_custom_post_types_array)) &&
$old_status !== "publish";
/* ********************************************************************************************************* */
if ($posted_from_wordpress_editor) {
// Decide to send based on whether the checkbox "Send notification on post publish/update" is checked
// This post may be scheduled or just submitted from the WordPress editor
// Metadata may not be saved into post yet, so use $_POST form data if metadata not available
$do_send_notification = ($was_posted && $onesignal_meta_box_send_notification_checked) ||
(!$was_posted && $post_metadata_was_send_notification_checked);
} else {
// This was definitely not submitted via the WordPress editor
// Decide to send based on whether the 3rd-party plugins setting is checked
$do_send_notification = $non_editor_post_publish_do_send_notification;
}
if (has_filter('onesignal_include_post')) {
if (apply_filters('onesignal_include_post', $new_status, $old_status, $post)) {
onesignal_debug('Will actually send a notification for this post because the filter opted to include the post.');
$do_send_notification = true;
}
}
onesignal_debug('Post Status:', $old_status, '-->', $new_status);
onesignal_debug_post($post);
onesignal_debug('Has onesignal_include_post filter:', has_filter('onesignal_include_post'));
onesignal_debug(' [onesignal_include_post Filter]', 'Filter Result:' , apply_filters('onesignal_include_post', $new_status, $old_status, $post));
onesignal_debug('Has onesignal_exclude_post filter:', has_filter('onesignal_exclude_post'));
onesignal_debug(' [onesignal_exclude_post Filter]', 'Filter Result:' , apply_filters('onesignal_exclude_post', $new_status, $old_status, $post));
onesignal_debug('Posted from WordPress editor:', $posted_from_wordpress_editor);
onesignal_debug(' [Posted from WordPress editor]', 'Just Posted Meta Box Present:', $onesignal_meta_box_present);
onesignal_debug(' [Posted from WordPress editor]', 'Was Meta Box Ever Present:', $post_metadata_was_onesignal_meta_box_present);
onesignal_debug('Editor Post Send:', $posted_from_wordpress_editor && $do_send_notification);
onesignal_debug(' [Editor Post Send]', 'Meta Box Send Notification Just Checked:', $onesignal_meta_box_send_notification_checked);
onesignal_debug(' [Editor Post Send]', 'Meta Box Send Notification Previously Checked:', $post_metadata_was_send_notification_checked);
onesignal_debug('Non-Editor Post Send:', $non_editor_post_publish_do_send_notification);
onesignal_debug(' [Non-Editor Post Send]', 'Auto Send Config Setting:', $settings_send_notification_on_non_editor_post_publish);
onesignal_debug(' [Non-Editor Post Send]', 'Post Type:', ($post->post_type == "post" || in_array($post->post_type, $additional_custom_post_types_array)), '(' . $post->post_type . ')');
onesignal_debug(' [Non-Editor Post Send]', 'Old Post Status:' , ($old_status !== "publish"), '(' . $old_status . ')');
onesignal_debug('Actually Sending Notification:', $do_send_notification);
if ($do_send_notification) {
/* Now that all settings are retrieved, and we are actually sending the notification, reset the post's metadata
* If this post is sent through a plugin in the future, existing metadata will interfere with the send condition logic
* If this post is re-sent through the WordPress editor, the metadata will be added back automatically
*/
update_post_meta($post->ID, 'onesignal_meta_box_present', false);
update_post_meta($post->ID, 'onesignal_send_notification', false);
onesignal_debug('Removed OneSignal metadata from post.');
/* Some WordPress environments seem to be inconsistent about whether on_save_post is called before transition_post_status
* This sets the metadata back to true, and will cause a post to be sent even if the checkbox is not checked the next time
* We remove all related $_POST data to prevent this
*/
if ($was_posted) {
if (array_key_exists('onesignal_meta_box_present', $_POST)) {
unset($_POST['onesignal_meta_box_present']);
onesignal_debug('Unset $_POST[\'onesignal_meta_box_present\']');
}
if (array_key_exists('send_onesignal_notification', $_POST)) {
unset($_POST['send_onesignal_notification']);
onesignal_debug('Unset $_POST[\'send_onesignal_notification\']');
}
}
$notif_content = OneSignalUtils::decode_entities(get_the_title($post->ID));
$site_title = "";
if ($onesignal_wp_settings['notification_title'] != "") {
$site_title = OneSignalUtils::decode_entities($onesignal_wp_settings['notification_title']);
} else {
$site_title = OneSignalUtils::decode_entities(get_bloginfo('name'));
}
if (function_exists('qtrans_getLanguage')) {
try {
$qtransLang = qtrans_getLanguage();
$site_title = qtrans_use($qtransLang, $site_title, false);
$notif_content = qtrans_use($qtransLang, $notif_content, false);
} catch (Exception $e) {
onesignal_debug('Caught qTrans exception:', $e->getMessage());
}
}
$fields = array(
'app_id' => $onesignal_wp_settings['app_id'],
'headings' => array("en" => $site_title),
'included_segments' => array('All'),
'isAnyWeb' => true,
'url' => get_permalink($post->ID),
'contents' => array("en" => $notif_content)
);
$send_to_mobile_platforms = $onesignal_wp_settings['send_to_mobile_platforms'];
if ($send_to_mobile_platforms == true) {
$fields['isIos'] = true;
$fields['isAndroid'] = true;
}
$config_utm_additional_url_params = $onesignal_wp_settings['utm_additional_url_params'];
if (!empty($config_utm_additional_url_params)) {
$fields['url'] .= '?' . $config_utm_additional_url_params;
}
if (has_post_thumbnail($post->ID)) {
onesignal_debug('Post has featured image.');
$post_thumbnail_id = get_post_thumbnail_id($post->ID);
// Higher resolution (2x retina, + a little more) for the notification small icon
$thumbnail_sized_images_array = wp_get_attachment_image_src($post_thumbnail_id, array(192, 192), true);
// Much higher resolution for the notification large image
$large_sized_images_array = wp_get_attachment_image_src($post_thumbnail_id, 'large', true);
$config_use_featured_image_as_icon = $onesignal_wp_settings['showNotificationIconFromPostThumbnail'] == "1";
onesignal_debug('Post should use featured image for notification icon (small):', $config_use_featured_image_as_icon);
$config_use_featured_image_as_image = $onesignal_wp_settings['showNotificationImageFromPostThumbnail'] == "1";
onesignal_debug('Post should use featured image for notification image (large):', $config_use_featured_image_as_image);
// get the icon image from wordpress if it exists
if ($config_use_featured_image_as_icon) {
onesignal_debug('Featured post image thumbnail-sized array:', $thumbnail_sized_images_array);
$thumbnail_image = $thumbnail_sized_images_array[0];
// set the icon image for both chrome and firefox-1
$fields['chrome_web_icon'] = $thumbnail_image;
$fields['firefox_icon'] = $thumbnail_image;
onesignal_debug('Setting Chrome and Firefox notification icon to:', $thumbnail_image);
}
if ($config_use_featured_image_as_image) {
onesignal_debug('Featured post image large-sized array:', $large_sized_images_array);
$large_image = $large_sized_images_array[0];
$fields['chrome_web_image'] = $large_image;
onesignal_debug('Setting Chrome notification large image to:', $large_image);
}
}
if (has_filter('onesignal_send_notification')) {
onesignal_debug('Applying onesignal_send_notification filter.');
$fields = apply_filters('onesignal_send_notification', $fields, $new_status, $old_status, $post);
onesignal_debug('onesignal_send_notification filter $fields result:', $fields);
// If the filter adds "do_send_notification: false", do not send a notification
if (array_key_exists('do_send_notification', $fields) && $fields['do_send_notification'] == false) {
return;
}
}
if (defined('ONESIGNAL_DEBUG') || class_exists('WDS_Log_Post')) {
// http://blog.kettle.io/debugging-curl-requests-in-php/
ob_start();
$out = fopen('php://output', 'w');
}
onesignal_debug('Initializing cURL.');
$ch = curl_init();
$onesignal_post_url = "https://onesignal.com/api/v1/notifications";
if (defined('ONESIGNAL_DEBUG') && defined('ONESIGNAL_LOCAL')) {
$onesignal_post_url = "https://localhost:3001/api/v1/notifications";
}
$onesignal_auth_key = $onesignal_wp_settings['app_rest_api_key'];
curl_setopt($ch, CURLOPT_URL, $onesignal_post_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Basic ' . $onesignal_auth_key
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if (defined('ONESIGNAL_DEBUG')) {
// Turn off host verification for localhost testing since we're using a self-signed certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
if (class_exists('WDS_Log_Post')) {
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_HTTP200ALIASES, array(400));
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $out);
}
$response = curl_exec($ch);
$curl_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
onesignal_debug('$curl_http_code:', $curl_http_code);
if ($curl_http_code != 200) {
if ($curl_http_code != 0) {
set_transient( 'onesignal_transient_error', '<div class="error notice onesignal-error-notice">
<p><strong>OneSignal Push:</strong><em> There was a ' . $curl_http_code . ' error sending your notification:</em></p>
<pre>' . print_r($response, true) . '</pre>
</div>', 86400 );
} else {
// A 0 HTTP status code means the connection couldn't be established
set_transient( 'onesignal_transient_error', '<div class="error notice onesignal-error-notice">
<p><strong>OneSignal Push:</strong><em> There was an error establishing a network connection. Please make sure outgoing network connections from cURL are allowed.</em></p>
</div>', 86400 );
}
} else {
$parsed_response = json_decode($response, true);
if (!empty($parsed_response)) {
onesignal_debug('OneSignal API Raw Response:', $response);
onesignal_debug('OneSignal API Parsed Response:', $parsed_response);
// API can send a 200 OK even if the notification failed to send
$recipient_count = $parsed_response['recipients'];
$sent_or_scheduled = array_key_exists('send_after', $fields) ? 'scheduled' : 'sent';
$config_show_notification_send_status_message = $onesignal_wp_settings['show_notification_send_status_message'] == "1";
if ($config_show_notification_send_status_message) {
if ($recipient_count != 0) {
set_transient('onesignal_transient_success', '<div class="updated notice notice-success is-dismissible">
<p><strong>OneSignal Push:</strong><em> Successfully ' . $sent_or_scheduled . ' a notification to ' . $parsed_response['recipients'] . ' recipients.</em></p>
</div>', 86400);
} else {
set_transient('onesignal_transient_success', '<div class="updated notice notice-success is-dismissible">
<p><strong>OneSignal Push:</strong><em> A notification was ' . $sent_or_scheduled . ', but there were no recipients.</em></p>
</div>', 86400);
}
}
}
}
if (defined('ONESIGNAL_DEBUG') || class_exists('WDS_Log_Post')) {
fclose($out);
$debug_output = ob_get_clean();
$curl_effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$curl_total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
onesignal_debug('OneSignal API POST Data:', $fields);
onesignal_debug('OneSignal API URL:', $curl_effective_url);
onesignal_debug('OneSignal API Response Status Code:', $curl_http_code);
if ($curl_http_code != 200) {
onesignal_debug('cURL Request Time:', $curl_total_time, 'seconds');
onesignal_debug('cURL Error Number:', curl_errno($ch));
onesignal_debug('cURL Error Description:', curl_error($ch));
onesignal_debug('cURL Response:', print_r($response, true));
onesignal_debug('cURL Verbose Log:', $debug_output);
}
}
curl_close($ch);
self::update_last_sent_timestamp();
return $response;
}
}
catch (Exception $e) {
onesignal_debug('Caught Exception:', $e->getMessage());
}
}
public static function was_post_restored_from_trash($old_status, $new_status) {
return $old_status === 'trash' && $new_status === 'publish';
}
public static function on_transition_post_status( $new_status, $old_status, $post ) {
if ($post->post_type == 'wdslp-wds-log' ||
self::was_post_restored_from_trash($old_status, $new_status)) {
// It's important not to call onesignal_debug() on posts of type wdslp-wds-log, otherwise each post will recursively generate 4 more posts
return;
}
if (has_filter('onesignal_include_post')) {
onesignal_debug('Applying onesignal_include_post filter.');
if (apply_filters('onesignal_include_post', $new_status, $old_status, $post)) {
// If the filter returns "$do_include_post: true", always process this post
onesignal_debug('Processing post because the filter opted to include the post.');
self::send_notification_on_wp_post($new_status, $old_status, $post);
return;
}
}
if (has_filter('onesignal_exclude_post')) {
onesignal_debug('Applying onesignal_exclude_post filter.');
if (apply_filters('onesignal_exclude_post', $new_status, $old_status, $post)) {
// If the filter returns "$do_exclude_post: false", do not process this post at all
onesignal_debug('Not processing post because the filter opted to exclude the post.');
return;
}
}
if (!(empty($post) ||
$new_status !== "publish" ||
$post->post_type == 'page')) {
self::send_notification_on_wp_post($new_status, $old_status, $post);
}
}
}
?>