PluginProbe
Push Notifications for WP – Self Hosted Web Push Notifications / 1.2
Push Notifications for WP – Self Hosted Web Push Notifications v1.2
1.52 1.51 trunk 1.0 1.1 1.10 1.11 1.12 1.12.1 1.13 1.14 1.15 1.16 1.17 1.18 1.19 1.2 1.20 1.21 1.22 1.23 1.24 1.25 1.25.1 1.26 All 58 releases
push-notification / inc / admin / admin.php

admin.php in Push Notifications for WP – Self Hosted Web Push Notifications 1.2, at inc/admin/admin.php

488 lines 19.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 // Exit if accessed directly.
3 if ( ! defined( 'ABSPATH' ) ) exit;
4
5 if(file_exists(PUSH_NOTIFICATION_PLUGIN_DIR."inc/admin/class-function.php")){
6 require_once PUSH_NOTIFICATION_PLUGIN_DIR."inc/admin/class-function.php";
7 }
8 class Push_Notification_Admin{
9
10 public function __construct(){}
11
12 public function init(){
13 add_action( 'admin_menu', array( $this, 'add_menu_links') );
14 add_action( 'admin_init', array( $this, 'settings_init') );
15 add_action( 'admin_enqueue_scripts', array( $this, 'load_admin_scripts' ) );
16
17 add_action( 'wp_ajax_pn_verify_user', array( $this, 'pn_verify_user' ) );
18 add_action( 'wp_ajax_pn_revoke_keys', array( $this, 'pn_revoke_keys' ) );
19 add_action( 'wp_ajax_pn_subscribers_data', array( $this, 'pn_subscribers_data' ) );
20 add_action( 'wp_ajax_pn_send_notification', array( $this, 'pn_send_notification' ) );
21
22
23
24 //Send push on publish and update
25 add_action( 'transition_post_status', array( $this, 'send_notification_on_update' ), 10, 3 );
26
27 /** pwaforwp installed than work with that */
28 if( function_exists('pwaforwp_init_plugin') ){
29 /** service worker change */
30 $settings = pwaforwp_defaultSettings();
31 if($settings['notification_feature']==1 && $settings['notification_options']=='pushnotifications_io'){
32 add_filter( "pwaforwp_sw_js_template", array($this, 'add_sw_js_content') , 10, 1);
33 add_filter( "pwaforwp_pn_config", array($this, 'add_pn_config') , 10, 1);
34 add_filter( "pwaforwp_pn_use_sw", array($this, 'add_pn_use_sw') , 10, 1);
35 add_filter( "pwaforwp_sw_register_template", array($this, 'add_sw_register_template') , 10, 1);
36 }
37
38
39
40
41 }
42 }
43
44
45 /*
46 * This function will Messaging functions in service worker
47 *
48 */
49 function add_sw_js_content($swJsContent){
50 $messageSw = $this->pn_get_layout_files('messaging-sw.js');
51 $settings = $this->json_settings();
52 $messageSw = str_replace('{{pnScriptSetting}}', json_encode($settings), $messageSw);
53 $swJsContent .= $messageSw;
54 return $swJsContent;
55 }
56
57 function add_pn_config($firebaseconfig){
58 $firebaseconfig = 'var config = pnScriptSetting.pn_config;'
59 .'if (!firebase.apps.length) {firebase.initializeApp(config);}
60 const messaging = firebase.messaging();';
61 return $firebaseconfig;
62 }
63
64 function add_pn_use_sw($useserviceworker){
65 $useserviceworker = 'messaging.useServiceWorker(reg);';
66 return $useserviceworker;
67 }
68
69 function add_sw_register_template($swHtmlContent){
70 $sw_registerContent = $this->pn_get_layout_files('public/app.js');
71 $replaceCnt = "var config=pnScriptSetting.pn_config;
72 if (!firebase.apps.length) {
73 firebase.initializeApp(config);
74 }
75 var swsource = pnScriptSetting.swsource;
76 const messaging = firebase.messaging();
77 if(\"serviceWorker\" in navigator) {
78 window.addEventListener('load', function() {
79 navigator.serviceWorker.register(swsource, {scope: pnScriptSetting.scope}).then(function(reg){
80 messaging.useServiceWorker(reg);
81 console.log('Congratulations!!Service Worker Registered ServiceWorker scope: ', reg.scope);
82
83 }).catch(function(err) {
84 console.log('ServiceWorker registration failed: ', err);
85 });
86 })
87 }";
88 $sw_registerContent = str_replace($replaceCnt, '', $sw_registerContent);
89 //Concatnate content in main service worker register
90 $swHtmlContent .= $sw_registerContent;
91 return $swHtmlContent;
92 }
93
94 public function json_settings(){
95 if ( is_multisite() ) {
96 $link = get_site_url();
97 }
98 else {
99 $link = home_url();
100 }
101 $auth_settings = push_notification_auth_settings();
102 $messageConfig = '';
103 if(isset($auth_settings['user_token']) && isset($auth_settings['token_details']['validated']) && $auth_settings['token_details']['validated'] == 1){
104 $messageConfig = json_decode($auth_settings['messageManager'], true);
105 }
106 $settings = array(
107 'nonce' => wp_create_nonce("pn_notification"),
108 'pn_config'=> $messageConfig,
109 "swsource" => esc_url_raw(trailingslashit($link)."?push_notification_sw=1"),
110 "scope" => esc_url_raw(trailingslashit($link)),
111 "ajax_url"=> esc_url_raw(admin_url('admin-ajax.php'))
112 );
113 return $settings;
114 }
115
116 function load_admin_scripts($hook_suffix){
117 if($hook_suffix=='toplevel_page_push-notification'){
118 wp_enqueue_script('push_notification_script', PUSH_NOTIFICATION_PLUGIN_URL.'/assets/main-admin-script.js', array('jquery'), PUSH_NOTIFICATION_PLUGIN_VERSION, true);
119 wp_enqueue_style('push-notification-style', PUSH_NOTIFICATION_PLUGIN_URL.'/assets/main-admin-style.css', array('dashboard'), PUSH_NOTIFICATION_PLUGIN_VERSION, 'all');
120 if ( is_multisite() ) {
121 $link = get_site_url();
122 }
123 else {
124 $link = home_url();
125 }
126 wp_localize_script("push_notification_script", 'pn_setings',
127 array(
128 "home_url"=> esc_url_raw($link),
129 "remote_nonce"=> wp_create_nonce("pn_notification")
130 )
131 );
132 }
133 }
134
135 public function add_menu_links(){
136 // Main menu page
137 add_menu_page( esc_html__( 'Push Notification-Admin', 'push-notification' ),
138 esc_html__( 'Push Notifications Options', 'push-notification' ),
139 'manage_options',
140 'push-notification',
141 array($this, 'admin_interface_render'),
142 '', 100 );
143
144 // Settings page - Same as main menu page
145 add_submenu_page( 'push-notification',
146 esc_html__( 'Push Notifications Options', 'push-notification' ),
147 esc_html__( 'Settings', 'push-notification' ),
148 'manage_options',
149 'push-notification',
150 array($this, 'admin_interface_render')
151 );
152 }
153 function admin_interface_render(){
154
155 // Authentication
156 if ( ! current_user_can( 'manage_options' ) ) {
157 return;
158 }
159 ?><div class="wrap push_notification-settings-wrap">
160 <h1 class="page-title"><?php echo esc_html__('Push Notifications Options', 'push-notification'); ?></h1>
161 <form action="options.php" method="post" enctype="multipart/form-data" class="push_notification-settings-form">
162 <div class="form-wrap">
163 <?php
164 settings_fields( 'push_notification_setting_dashboard_group' );
165 echo "<div class='push_notification-dashboard'>";
166 // Status
167 do_settings_sections( 'push_notification_dashboard_section' ); // Page slug
168 $authData = push_notification_auth_settings();
169 if(isset($authData['token_details']['validated']) && $authData['token_details']['validated']==1){
170 $this->shownotificationData();
171 }
172 echo "</div>";
173 ?>
174 </div>
175 </form>
176 </div><?php
177 }
178
179 public function settings_init(){
180 register_setting( 'push_notification_setting_dashboard_group', 'push_notification_settings' );
181
182 add_settings_section('push_notification_dashboard_section',
183 esc_html__('','push-notification'),
184 '__return_false',
185 'push_notification_dashboard_section');
186
187 add_settings_field(
188 'pn_key_validate_status', // ID
189 esc_html__('API', 'push-notification'), // Title
190 array( $this, 'pn_key_validate_status_callback'),// Callback
191 'push_notification_dashboard_section', // Page slug
192 'push_notification_dashboard_section' // Settings Section ID
193 );
194
195 add_settings_section('push_notification_user_settings_section',
196 esc_html__('','push-notification'),
197 '__return_false',
198 'push_notification_user_settings_section');
199
200 add_settings_field(
201 'pn_key_sendpush_edit', // ID
202 esc_html__('Send notification on editing', 'push-notification'),// Title
203 array( $this, 'user_settings_callback'),// Callback
204 'push_notification_user_settings_section', // Page slug
205 'push_notification_user_settings_section' // Settings Section ID
206 );
207 add_settings_field(
208 'pn_key_sendpush_publish', // ID
209 esc_html__('Send notification on publish', 'push-notification'),// Title
210 array( $this, 'user_settings_onpublish_callback'),// Callback
211 'push_notification_user_settings_section', // Page slug
212 'push_notification_user_settings_section' // Settings Section ID
213 );
214
215 }
216
217 function shownotificationData(){
218 $auth_settings = push_notification_auth_settings();
219 $detail_settings = push_notification_details_settings();
220 if( !$detail_settings && isset( $auth_settings['user_token'] ) ){
221 PN_Server_Request::getsubscribersData( $auth_settings['user_token'] );
222 $detail_settings = push_notification_details_settings();
223 }
224
225 $updated_at = '';
226 if(isset($detail_settings['updated_at'])){
227 //echo $detail_settings['updated_at'];die;
228 $updated_at = human_time_diff( strtotime( $detail_settings['updated_at'] ), strtotime( date('Y-m-d H:i:s') ) );
229 if(!empty( $updated_at ) ){
230 $updated_at .= " ago";
231 }
232
233
234 }
235 $subscriber_count = 0;
236 if(isset($detail_settings['subscriber_count'])){ $subscriber_count = $detail_settings['subscriber_count']; }
237 echo '<section class="pn_general_wrapper">
238 <div class="action-wrapper"> '.esc_html__($updated_at, 'push-notification').' <button type="button" class="button" id="grab-subscribers-data" class="dashicons dashicons-update">'.esc_html__('Refresh data', 'push-notification').'</button>
239 </div>
240 <div class="pn-content">
241 <div class="pn-card-wrapper">
242 <div class="pn-card">
243 <div class="title-name">'.esc_html__('Total Subscribers', 'push-notification').':</div>
244 <div class="desc column-description">
245 '.esc_html($subscriber_count).'
246 </div>
247 </div>
248 </div>
249 </div>
250 ';
251 do_settings_sections( 'push_notification_user_settings_section' );
252 echo '<input type="submit" value="'.esc_html__('Save Settings', 'push-notification').'" class="button">
253 </section>
254 ';
255 echo '<br/><br/><div class="pn-other-settings-options">
256 <div id="dashboard_right_now" class="postbox " >
257 <h2 class="hndle">'.esc_html__('Send Custom Notification', 'push-notification').'</h2>
258 <div class="inside">
259 <div class="main">
260 <div class="form-group">
261 <label for="notification-title">'.esc_html__('Title','push-notification').'</label>
262 <input type="text" id="notification-title" class="regular-text">
263 </div>
264 <div class="form-group">
265 <label for="notification-link">'.esc_html__('Link', 'push-notification').'</label>
266 <input type="text" id="notification-link" class="regular-text">
267 </div>
268 <div class="form-group">
269 <label for="notification-imageurl">'.esc_html__('Image url', 'push-notification').'</label>
270 <input type="text" id="notification-imageurl" class="regular-text">
271 </div>
272 <div class="form-group">
273 <label for="notification-message">'.esc_html__('Message', 'push-notification').'</label>
274 <textarea type="text" id="notification-message" class="regular-text"></textarea>
275 </div>
276 <input type="button" class="button" id="pn-send-custom-notification" value="'.esc_html__('Send Notification', 'push-notification').'">
277 <div class="pn-send-messageDiv"></div>
278 </div>
279 </div>
280 </div>
281 </div>';
282 }
283
284 public function pn_key_validate_status_callback(){
285 $authData = push_notification_auth_settings();
286 if( !isset($authData['token_details']['validated'])
287 || (isset($authData['token_details']) && $authData['token_details']['validated']!=1) ){
288 echo "<fieldset>";
289 PN_Field_Generator::get_input_password('user_token', 'user_auth_token_key');
290 PN_Field_Generator::get_button('Validate', 'user_auth_vadation');
291 echo '<span class="resp_message"></span></fieldset>
292 <p>'.esc_html__('This plugin requires a free API key for PushNotification.io', 'push-notification').' <a target="_blank" href="'.esc_url_raw(PN_Server_Request::$notificationlanding."register").'">'.esc_html__('Get the Key', 'push-notification').'</a></p>';
293 }else{
294 echo "<input type='text' class='regular-text' value='xxxxxxxxxxxxxxxxxx'>
295 <span class='text-success resp_message' style='color:green;'>".esc_html__('User Verified', 'push-notification')."</span>
296 <button type='button' class='button dashicons-before dashicons-no-alt' id='pn-remove-apikey' style='margin-left:10%; line-height: 1.4;'>".esc_html__('Revoke key', 'push-notification')."</button>";
297 }
298
299 }//function closed
300
301 public function user_settings_callback(){
302 $notification = push_notification_settings();
303 PN_Field_Generator::get_input_checkbox('on_edit', '1', 'pn_push_on_edit', 'pn-checkbox pn_push_on_edit');
304
305 }
306 public function user_settings_onpublish_callback(){
307 $notification = push_notification_settings();
308 PN_Field_Generator::get_input_checkbox('on_publish', '1', 'pn_push_on_publish', 'pn-checkbox pn_push_on_publish');
309
310 }
311
312 public function pn_verify_user(){
313 $nonce = sanitize_text_field($_POST['nonce']);
314 if( !wp_verify_nonce($nonce, 'pn_notification') ){
315 echo json_encode(array("status"=> 503, 'message'=>'Request not authorized'));die;
316 }else{
317 $user_token = sanitize_text_field($_POST['user_token']);
318 $response = PN_Server_Request::varifyUser($user_token);
319
320 echo json_encode($response);die;
321 }
322
323
324 echo json_encode(array("status"=> 503, 'message'=>'Request not identified'));die;
325 }
326
327 public function pn_revoke_keys(){
328 $nonce = sanitize_text_field($_POST['nonce']);
329 if( !wp_verify_nonce($nonce, 'pn_notification') ){
330 echo json_encode(array("status"=> 503, 'message'=>'Request not authorized'));die;
331 }else{
332 delete_option('push_notification_auth_settings');
333 echo json_encode(array("status"=> 200, 'message'=>'API key removed successfully'));die;
334 }
335 }
336
337 public function pn_subscribers_data(){
338 $nonce = sanitize_text_field($_POST['nonce']);
339 if( !wp_verify_nonce($nonce, 'pn_notification') ){
340 echo json_encode(array("status"=> 503, 'message'=>'Request not authorized'));die;
341 }else{
342 $auth_settings = push_notification_auth_settings();
343 if( isset( $auth_settings['user_token'] ) ){
344 PN_Server_Request::getsubscribersData( $auth_settings['user_token'] );
345 echo json_encode(array("status"=> 200, 'message'=>'Data updated'));die;
346 }else{
347 echo json_encode(array("status"=> 503, 'message'=>'User token not found'));die;
348 }
349
350 }
351 }
352 public function pn_send_notification(){
353 $nonce = sanitize_text_field($_POST['nonce']);
354 if( !wp_verify_nonce($nonce, 'pn_notification') ){
355 echo json_encode(array("status"=> 503, 'message'=>'Request not authorized'));die;
356 }else{
357 $auth_settings = push_notification_auth_settings();
358 $title = sanitize_text_field($_POST['title']);
359 $message = sanitize_textarea_field($_POST['message']);
360 $link_url = esc_url_raw($_POST['link_url']);
361 $image_url = esc_url_raw($_POST['image_url']);
362 if( isset( $auth_settings['user_token'] ) ){
363 $response = PN_Server_Request::sendPushNotificatioData( $auth_settings['user_token'], $title,$message, $link_url, $image_url );
364 echo json_encode($response);die;
365 }else{
366 echo json_encode(array("status"=> 503, 'message'=>'User token not found'));die;
367 }
368
369 }
370 }
371
372 public function send_notification_on_update($new_status, $old_status, $post){
373 $pn_settings = push_notification_settings();
374 $auth_settings = push_notification_auth_settings();
375
376 if ( 'publish' !== $new_status ){
377 return;
378 }
379
380 $send_notification = false;
381 //for Edit
382 if(isset($pn_settings['on_edit']) && $pn_settings['on_edit']==1){
383 if ( $new_status === $old_status) {
384 $this->send_notification($post);
385 $send_notification = true;
386 }
387 }
388 //for publish
389 if(!$send_notification && isset($pn_settings['on_publish']) && $pn_settings['on_publish']==1){
390 if ( $new_status !== $old_status) {
391 $this->send_notification($post);
392 }
393 }
394
395
396 }
397 protected function send_notification($post){
398 $post_id = $post->ID;
399 $post_content = $post->post_content;
400 $post_title = $post->post_title;
401 $auth_settings = push_notification_auth_settings();
402
403 //API Data
404 $title = sanitize_text_field(wp_strip_all_tags($post_title) );
405 $message = wp_trim_words(wp_strip_all_tags(sanitize_text_field($post_content)), 20);
406 $link_url = esc_url_raw(get_permalink( $post_id ));
407 $image_url = '';
408 if(has_post_thumbnail($post_id)){
409 $image_url = esc_url_raw(get_the_post_thumbnail_url($post_id));
410 }
411
412 if( isset( $auth_settings['user_token'] ) && !empty($auth_settings['user_token']) ){
413 $response = PN_Server_Request::sendPushNotificatioData( $auth_settings['user_token'], $title, $message, $link_url, $image_url );
414 }//auth token check
415
416 }
417
418 public function pn_get_layout_files($filePath){
419 $fileContentResponse = @wp_remote_get(esc_url_raw(PUSH_NOTIFICATION_PLUGIN_URL.'/assets/'.$filePath));
420 if(wp_remote_retrieve_response_code($fileContentResponse)!=200){
421 if(!function_exists('get_filesystem_method')){
422 require_once( ABSPATH . 'wp-admin/includes/file.php' );
423 }
424 $access_type = get_filesystem_method();
425 if($access_type === 'direct')
426 {
427 $file = PUSH_NOTIFICATION_PLUGIN_DIR.($filePath);
428 $creds = request_filesystem_credentials($file, '', false, false, array());
429 if ( ! WP_Filesystem($creds) ) {
430 return false;
431 }
432 global $wp_filesystem;
433 $htmlContentbody = $wp_filesystem->get_contents($file);
434 return $htmlContentbody;
435 }
436 return false;
437 }else{
438 return wp_remote_retrieve_body( $fileContentResponse );
439 }
440 }
441
442
443 }
444
445 if(is_admin() || wp_doing_ajax()){
446 $push_Notification_Admin_Obj = new Push_Notification_Admin();
447 $push_Notification_Admin_Obj->init();
448 }
449
450 function push_notification_settings(){
451 $push_notification_settings = get_option( 'push_notification_settings', array() );
452 return $push_notification_settings;
453 }
454 function push_notification_auth_settings(){
455 $push_notification_auth_settings = get_option( 'push_notification_auth_settings', array() );
456 return $push_notification_auth_settings;
457 }
458 function push_notification_details_settings(){
459 $push_notification_details_settings = get_option( 'push_notification_details_settings', array() );
460 return $push_notification_details_settings;
461 }
462
463
464 /**
465 * Server Side fields generation class
466 */
467 class PN_Field_Generator{
468 static $settingName = 'push_notification_settings';
469
470 public static function get_input($name, $id="", $class=""){
471 $settings = push_notification_settings();
472 ?><input type="text" name="<?php echo esc_attr(self::$settingName); ?>[<?php echo esc_attr($name); ?>]" class="regular-text" id="<?php echo esc_attr($id); ?>" value="<?php if ( isset( $settings[$name] ) && ( ! empty($settings[$name]) ) ) echo esc_attr($settings[$name]); ?>"/><?php
473 }
474 public static function get_input_checkbox($name, $value, $id="", $class=""){
475 $settings = push_notification_settings();
476 ?><input type="checkbox" name="<?php echo esc_attr(self::$settingName); ?>[<?php echo esc_attr($name); ?>]" class="regular-text" id="<?php echo esc_attr($id); ?>" <?php if ( isset( $settings[$name] ) && $settings[$name]==$value ) echo esc_attr("checked"); ?> value="<?php echo esc_attr($value); ?>"/><?php
477 }
478 public static function get_input_password($name, $id="", $class=""){
479 $settings = push_notification_settings();
480 ?><input type="password" name="<?php echo esc_attr(self::$settingName); ?>[<?php echo esc_attr($name); ?>]" class="regular-text" id="<?php echo esc_attr($id); ?>" value="<?php if ( isset( $settings[$name] ) && ( ! empty($settings[$name]) ) ) echo esc_attr($settings[$name]); ?>"/><?php
481 }
482 public static function get_button($name, $id="", $class=""){
483 $settings = push_notification_settings();
484 ?>
485 <button type="button" class="button <?php echo esc_attr($class); ?>" id="<?php echo esc_attr($id); ?>"><?php echo esc_html__($name) ?></button>
486 <?php
487 }
488 }