MP_Addon_Push_WebPushNotification

Class WebPushNotification.


Source Source

File: calculator-push-notification-add-on/inc/MP_Addon_Push_WebPushNotification.php

class MP_Addon_Push_WebPushNotification {


	/**
	 * Public key.
	 *
	 * @var mixed|void
	 *
	 * @since 1.0.0
	 * @access private
	 */
	private $public_key;

	/**
	 * Private key.
	 *
	 * @var mixed|void
	 *
	 * @since 1.0.0
	 * @access private
	 */
	private $private_key;



	/**
	 * WebPushNotification constructor.
	 *
	 * @since 1.0.0
	 * @access public
	 */
	public function __construct() {
		$this->public_key  = get_option( MortgagePlatform::$prefix . 'vapid_public' );
		$this->private_key = get_option( MortgagePlatform::$prefix . 'vapid_private' );
	}


	/**
	 * Create VAPID public and private keys.
	 *
	 * Save them in the wp_option table of DataBase.
	 *
	 * @since 1.0.0
	 * @access public
	 * @static
	 */
	public static function create_vapid() {

		$vapid = VAPID::createVapidKeys();

		$vapid_public  = $vapid['publicKey'];
		$vapid_private = $vapid['privateKey'];

		if ( ! get_option( MortgagePlatform::$prefix . 'vapid_public' ) ) {
			add_option( MortgagePlatform::$prefix . 'vapid_public', $vapid_public );
		}

		if ( ! get_option( MortgagePlatform::$prefix . 'vapid_private' ) ) {
			add_option( MortgagePlatform::$prefix . 'vapid_private', $vapid_private );
		}

	}


	/**
	 * Init Service Worker.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @global $wp_filesystem
	 */
	public function init() {

		global $wp_filesystem;

		$target       = ABSPATH . 'webpush-sw.js';
		$target_admin = ABSPATH . 'wp-admin/webpush-sw.js';
		if ( is_null( $wp_filesystem ) ) {
			/**
			 * WP file.php
			 */
			require_once ABSPATH . 'wp-admin/includes/file.php';
			WP_Filesystem();
		}

		$webpush_sw_data = 'self.addEventListener("push", function(event) {
    let notificationData = {};
    try {
        notificationData = event.data.json()
    } catch (e) {
        notificationData = {
            title: "Default title",
            body: "Default message",
            icon: "/default-icon.png",
            data: {
                url: "' . site_url( '/' ) . '"
            },
        }
    }
    event.waitUntil(
	    self.registration.showNotification(notificationData.title, {
	        body: notificationData.body,
	        icon: notificationData.icon,
	        data: notificationData.data
	    })
    )
});
self.addEventListener("notificationclick", function(event) {
    event.notification.close();
    
let urlToOpen =  "' . site_url( '/' ) . '"

    console.log(event.notification);
    if (event.notification.data.url !== "undefined") {
        urlToOpen = event.notification.data.url
    } 
const promiseChain = clients.matchAll({
    type: "window",
    includeUncontrolled: true
  })
  .then((windowClients) => {
    let matchingClient = null
    for (let i = 0; i < windowClients.length; i++) {
      const windowClient = windowClients[i];
      if (windowClient.url === urlToOpen) {
        matchingClient = windowClient;
        break;
      }
    }

    if (matchingClient) {
      return matchingClient.focus();
    } else {
      return clients.openWindow(urlToOpen);
    }
  });

  event.waitUntil(promiseChain);
})';
		$wp_filesystem->put_contents( $target, $webpush_sw_data );
		$wp_filesystem->put_contents( $target_admin, $webpush_sw_data );
	}


	/**
	 * Deactivate Service Worker.
	 *
	 * @since 1.0.0
	 * @access public
	 */
	public static function deactivate() {

		$target       = ABSPATH . 'webpush-sw.js';
		$target_admin = ABSPATH . 'wp-admin/webpush-sw.js';

		echo "<script> 

            if ('serviceWorker' in navigator) {
            
                    navigator.serviceWorker.getRegistrations().then(function(registrations) {
            
                        for(let registration of registrations) {
            
                            console.log(registration.active.scriptURL);
                            if (registration.active.scriptURL === '" . esc_url( site_url( '/' ) ) . 'webpush-sw.js' . "') {
                                registration.unregister()
                            }
            
                        }}).catch(function(err) {
            
                        console.log('Service Worker registration failed: ', err);
            
                    });
                }
            
            </script>";

		wp_delete_file( $target );
		wp_delete_file( $target_admin );

	}



	/**
	 * Send Push Notification.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @param Subscription $subscription
	 * @param string|null $payload If you want to send an array, json_encode it
	 *
	 * @return string
	 */
	public function send_push( $subscription, $payload ) {

		$auth = array(
			'VAPID' => array(
				'subject'    => get_site_url(),
				'publicKey'  => $this->public_key,
				'privateKey' => $this->private_key,
			),
		);

		$web_push = new WebPush( $auth );
		$web_push->sendNotification( $subscription, $payload );

		foreach ( $web_push->flush() as $report ) {
			$endpoint = $report->getRequest()->getUri()->__toString();

			if ( $report->isSuccess() ) {
				return __( '[v] Message sent successfully for subscription ', 'CalculatorsPushNotificationAddon' ) . $endpoint . '.';
			} else {
				return __( '[x] Message failed to sent for subscription ', 'CalculatorsPushNotificationAddon' ) . $endpoint . ' : ' . $report->getReason();
			}
		}

	}



	/**
	 * Register 'admin_browser_push' Post Type.
	 *
	 * @since 1.0.0
	 * @access public
	 * @static
	 *
	 * @return WP_Post_Type|WP_Error The registered 'admin_browser_push' post type object on success,
	 *                               WP_Error object on failure.
	 */
	public static function admin_browser_push() {

		return register_post_type(
			'admin_browser_push',
			array(
				'labels'              => array(
					'name'               => __( 'Browser Push', 'CalculatorsPushNotificationAddon' ),
					'singular_name'      => __( 'Browser Push', 'CalculatorsPushNotificationAddon' ),
					'add_new'            => __( 'Add Browser Push', 'CalculatorsPushNotificationAddon' ),
					'add_new_item'       => __( 'Add new Browser Push', 'CalculatorsPushNotificationAddon' ),
					'edit_item'          => __( 'Edit Browser Push', 'CalculatorsPushNotificationAddon' ),
					'new_item'           => __( 'New Browser Push', 'CalculatorsPushNotificationAddon' ),
					'view_item'          => __( 'Look Browser Push', 'CalculatorsPushNotificationAddon' ),
					'search_items'       => __( 'Find Browser Push', 'CalculatorsPushNotificationAddon' ),
					'not_found'          => __( 'Browser Push not found', 'CalculatorsPushNotificationAddon' ),
					'not_found_in_trash' => __( 'At cart Browser Push not found', 'CalculatorsPushNotificationAddon' ),
					'parent_item_colon'  => '',
					'menu_name'          => __( 'Browser Push', 'CalculatorsPushNotificationAddon' ),

				),
				'public'              => false,
				'publicly_queryable'  => false,
				'show_ui'             => false,
				'show_in_menu'        => false,
				'query_var'           => true,
				'show_in_rest'        => false,
				'exclude_from_search' => false,
				'rewrite'             => false,
				'show_in_nav_menus'   => false,
				'show_in_admin_bar'   => false,
				'capability_type'     => 'post',
				'has_archive'         => false,
				'hierarchical'        => false,
				'menu_position'       => null,
				'supports'            => array( 'title' ),
			)
		);

	}

}

Top ↑

Methods Methods


Top ↑

Changelog Changelog

Changelog
Version Description
1.0.0 Introduced.