Aleksandr Trofimov 6 месяцев назад
Родитель
Сommit
e48954d4f3

+ 134 - 0
inc/classes/BxDolPushWonderPush.php

@@ -0,0 +1,134 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) UNA, Inc - https://una.io
+ * MIT License - https://opensource.org/licenses/MIT
+ *
+ * @defgroup    UnaCore UNA Core
+ * @{
+ */
+
+class BxDolPushWonderPush extends BxDolPush
+{
+    protected $_sEndpoint;
+
+    protected $_sAppId;
+    protected $_sAcessToken;
+    protected $_sWebKey;
+
+    protected $_bCodeAdded;
+
+    protected function __construct($aObject, $oTemplate = null, $sDbClassName = '')
+    {
+        parent::__construct($aObject, $oTemplate, $sDbClassName);
+
+        $this->_sEndpoint = 'https://management-api.wonderpush.com/v1/deliveries';
+
+        $this->_sAppId = getParam('sys_push_wonderpush_app_id');
+        $this->_sAcessToken = getParam('sys_push_wonderpush_access_token');
+        $this->_sWebKey = getParam('sys_push_wonderpush_web_key');
+
+        $this->_bCodeAdded = false;
+    }
+
+    public function send($iProfileId, $aMessage, $bAddToQueue = false)
+    {
+        if(empty($this->_sAppId) || empty($this->_sAcessToken))
+            return false;
+
+        if($bAddToQueue && BxDolQueuePush::getInstance()->add($iProfileId, $aMessage))
+            return true;
+
+        // prepare params
+
+        $sUrlWeb = $sUrlApp = !empty($aMessage['url']) ? $aMessage['url'] : '';
+
+        if($this->_sApiUrlRootEmail !== false) {
+            if($sUrlWeb)
+                $sUrlWeb = str_replace(BX_DOL_URL_ROOT, $this->_sApiUrlRootEmail, $sUrlWeb);
+
+            if(!empty($aMessage['contents']) && is_array($aMessage['contents']))
+                foreach($aMessage['contents'] as $sKey => $sValue)
+                    $aMessage['contents'][$sKey] = str_replace(BX_DOL_URL_ROOT, $this->_sApiUrlRootEmail, $sValue);
+        }
+
+        if($this->_sApiUrlRootPush !== false) {
+            if($sUrlApp)
+                $sUrlApp = str_replace(BX_DOL_URL_ROOT, $this->_sApiUrlRootPush, $sUrlApp);
+        }
+        else
+            $sUrlApp = $sUrlWeb;
+        
+        if(empty($aMessage['icon']))
+            $aMessage['icon'] = BxTemplFunctions::getInstance()->getMainLogoUrl();
+
+        // construct notification object 
+
+        $aFields = [
+            'accessToken' => $this->_sAcessToken,
+            'targetUserIds' => $iProfileId,
+        ];
+        $aNotification = [
+            'alert' => [],
+        ];
+        if (!empty($aMessage['contents'])) {
+            $aNotification['alert']['text'] = is_array($aMessage['contents']) ? $aMessage['contents']['en'] : $aMessage['contents'];
+        }
+        if (!empty($aMessage['headings'])) {
+            $aNotification['alert']['title'] = is_array($aMessage['headings']) ? $aMessage['headings']['en'] : $aMessage['headings'];
+        }
+
+        if(!empty($aMessage['icon'])){
+            $aNotification['alert']['web'] = $aNotification['alert']['web'] ?? [];
+            $aNotification['alert']['web']['icon'] = $aMessage['icon'];
+
+            $aNotification['alert']['android'] = $aNotification['alert']['android'] ?? [];
+            $aNotification['alert']['android']['smallIcon'] = $aMessage['icon'];
+        }
+
+        if('on' == getParam('bx_nexus_option_push_notifications_count')) {
+            $iBadgeCount = $this->getNotificationsCount($iProfileId);
+            $aNotification['alert']['ios'] = $aNotification['alert']['ios'] ?? [];
+            $aNotification['alert']['ios']['badge'] = $iBadgeCount;
+        }
+
+        if (!empty($sUrlWeb)) {
+            $aNotification['alert']['targetUrl'] = $sUrlWeb;
+
+            $aFields['push'] = $aFields['push'] ?? [];
+            $aFields['push']['custom'] = $aFields['push']['custom'] ?? [];
+            $aFields['push']['custom']['url'] = $sUrlWeb;
+        }
+        if (!empty($sUrlApp)) {
+            // TODO: ??? https://docs.wonderpush.com/reference/notification
+        }
+
+        $aFields['notifications'] = json_encode($aNotification);
+
+        // send request
+
+        $oChannel = curl_init();
+        curl_setopt($oChannel, CURLOPT_URL, $this->_sEndpoint);
+        curl_setopt($oChannel, CURLOPT_HTTPHEADER, [
+            'Content-Type: application/json; charset=utf-8',
+        ]);
+        curl_setopt($oChannel, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($oChannel, CURLOPT_HEADER, false);
+        curl_setopt($oChannel, CURLOPT_POST, true);
+        curl_setopt($oChannel, CURLOPT_POSTFIELDS, json_encode($aFields));
+        if (getParam('sys_curl_ssl_allow_untrusted') == 'on')
+            curl_setopt($oChannel, CURLOPT_SSL_VERIFYPEER, false);
+
+        $sResult = curl_exec($oChannel);
+        curl_close($oChannel);
+
+        $oResult = @json_decode($sResult, true);
+        
+        if(isset($oResult['error'])) {
+            bx_log('sys_push', $sError . " Message:" . $oResult['error']['message'], BX_LOG_ERR);
+        }
+
+        return $sResult;
+    }
+}
+
+/** @} */

+ 77 - 0
inc/js/classes/BxDolPushWonderPush.js

@@ -0,0 +1,77 @@
+/**
+<script src="https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js" async></script>
+<script>
+window.WonderPush = window.WonderPush || [];
+WonderPush.push(["init", {
+    webKey: "cf4d2facd6a1c50b2fdaadec76b88ad8322397c11b28a4789648df6251cbfb74",
+}]);
+</script>
+ */
+function BxDolPushOneSignal(oOptions) {
+    this._sObjName = oOptions.sObjName == undefined ? 'oBxDolPushOneSignal' : oOptions.sObjName;
+    this._sSiteName = oOptions.sSiteName == undefined ? '' : oOptions.sSiteName;
+    this._aTags = oOptions.aTags == undefined ? {} : oOptions.aTags;
+    this._sWebKey = oOptions.sWebKey == undefined ? '' : oOptions.sAppId;
+
+    var $this = this;
+    $(document).ready(function() {
+    	$this.init();
+    });
+}
+
+BxDolPushOneSignal.prototype.init = function() {
+    var $this = this;
+    window.WonderPush = window.WonderPush || [];
+
+    OneSignal.push(function() {
+        OneSignal.SERVICE_WORKER_UPDATER_PATH = "OneSignalSDKUpdaterWorker.js.php";
+        OneSignal.SERVICE_WORKER_PATH = "OneSignalSDKWorker.js.php";
+        OneSignal.SERVICE_WORKER_PARAM = { scope: '/' }; /* This registers the workers at the root scope, which is allowed by the HTTP header "Service-Worker-Allowed: /" */
+    });
+
+    OneSignal.push(["init", {
+        appId: $this._sAppId,
+        autoRegister: true, /* Set to true to automatically prompt visitors */
+        subdomainName: $this._sShortName, /* required only for http  sites */
+        safari_web_id: $this._sSafariWebId,
+        path: $this._sSubfolder, /* A trailing slash is required */
+        persistNotification: false,
+        welcomeNotification: {
+            disable:false
+        },
+        httpPermissionRequest: {
+            enable: true
+        },
+        promptOptions: {
+            /* These prompt options values configure both the HTTP prompt and the HTTP popup. */
+            /* actionMessage limited to 90 characters */
+            actionMessage: $this._sTxtNotificationRequest, 
+            /* acceptButtonText limited to 15 characters */
+            acceptButtonText: $this._sTxtNotificationRequestYes,
+            /* cancelButtonText limited to 15 characters */
+            cancelButtonText: $this._sTxtNotificationRequestNo
+        }
+    }]);
+
+    OneSignal.push(function() {
+        var isPushSupported = OneSignal.isPushNotificationsSupported();
+        OneSignal.setDefaultNotificationUrl($this._sNotificationUrl);
+        OneSignal.isPushNotificationsEnabled().then(function(isEnabled) {
+            if('undefined' !== typeof($this._aTags['email'])) {
+                OneSignal.setEmail($this._aTags['email'], $this._aTags['email_hash']);
+                delete $this._aTags['email'];
+                delete $this._aTags['email_hash'];
+            }
+            OneSignal.sendTags($this._aTags); // set tags for onesiganl, some of these tags will be used to send notification
+            if(!isEnabled && isPushSupported)
+                OneSignal.showHttpPermissionRequest();													
+        });
+    });
+
+    if(navigator.userAgent.indexOf('gonative') > -1) {
+        var json = JSON.stringify($this._aTags);
+        $(document).ready(function () {
+            window.location.href='gonative://registration/send?customData=' + encodeURIComponent(json);        
+        });
+    }
+};

+ 8 - 3
install/sql/system.sql

@@ -92,8 +92,8 @@ CREATE TABLE `sys_objects_push` (
 );
 
 INSERT INTO `sys_objects_push` (`object`, `title`, `override_class_name`, `override_class_file`) VALUES
-('sys_onesignal', 'OneSignal', 'BxTemplPushOneSignal', '');
-
+('sys_onesignal', 'OneSignal', 'BxTemplPushOneSignal', ''),
+('sys_wonderpush', 'WonderPush', 'BxTemplPushWonderPush', '');
 
 -- --------------------------------------------------------
 
@@ -767,7 +767,12 @@ INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `ex
 (@iCategoryId, 'sys_push_onesignal_app_id', '_adm_stg_cpt_option_sys_push_onesignal_app_id', '', 'digit', '', '', '', 21),
 (@iCategoryId, 'sys_push_onesignal_rest_api', '_adm_stg_cpt_option_sys_push_onesignal_rest_api', '', 'digit', '', '', '', 22),
 (@iCategoryId, 'sys_push_onesignal_short_name', '_adm_stg_cpt_option_sys_push_onesignal_short_name', '', 'digit', '', '', '', 23),
-(@iCategoryId, 'sys_push_onesignal_safari_id', '_adm_stg_cpt_option_sys_push_onesignal_safari_id', '', 'digit', '', '', '', 24);
+(@iCategoryId, 'sys_push_onesignal_safari_id', '_adm_stg_cpt_option_sys_push_onesignal_safari_id', '', 'digit', '', '', '', 24),
+
+(@iCategoryId, 'sys_push_wonderpush_app_id', '_adm_stg_cpt_option_sys_push_wonderpush_app_id', '', 'digit', '', '', '', 30),
+(@iCategoryId, 'sys_push_wonderpush_access_token', '_adm_stg_cpt_option_sys_push_wonderpush_access_token', '', 'digit', '', '', '', 32),
+(@iCategoryId, 'sys_push_wonderpush_web_key', '_adm_stg_cpt_option_sys_push_wonderpush_web_key', '', 'digit', '', '', '', 34),
+(@iCategoryId, 'sys_push_wonderpush_requires_user_consent', '_adm_stg_cpt_option_sys_push_wonderpush_requires_user_consent', 'on', 'checkbox', '', '', '', 36);
 
 
 --

+ 1 - 0
package.json

@@ -105,6 +105,7 @@
     "build:leaflet-providers": "mkdir -p plugins_public/leaflet-providers; cd plugins_public/leaflet-providers; cp ../../node_modules/leaflet-providers/leaflet-providers.js .",
     "build:marka": "mkdir -p plugins_public/marka; cd plugins_public/marka; cp ../../node_modules/marka/dist/css/* .; cp ../../node_modules/marka/dist/js/* .",
     "build:onesignal": "mkdir -p plugins_public/onesignal; cd plugins_public/onesignal; echo '<?php\\nheader(\"Service-Worker-Allowed: /\");\\nheader(\"Content-Type: application/javascript\");\\n?>\\nimportScripts(\"https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js\");' > OneSignalSDKUpdaterWorker.js.php; echo '<?php\\nheader(\"Service-Worker-Allowed: /\");\\nheader(\"Content-Type: application/javascript\");\\nheader(\"X-Robots-Tag: none\");\\n?>\\nimportScripts(\"https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js\");' > OneSignalSDKWorker.js.php",
+    "build:wonderpush": "mkdir -p plugins_public/wonderpush; cd plugins_public/wonderpush; echo 'importScripts(\"https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js\");\\nWonderPush.init({\\nwebKey: (location.search.match(/[?&]webKey=([^&]*)/) || [])[1],\\n});' > wonderpush-worker-loader.min.js; echo '<!DOCTYPE html>\\n<html><head><title>Push Notifications by WonderPush</title>\\n<meta name=\"robots\" content=\"noindex, follow\">\\n<meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><meta name=\"wonderpush-integration\" content=\"frame,popup\">\\n<script id=\"wonderpush-jssdk-loader\" src=\"https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js\"></script>\\n<style>.default-style{font-family: sans-serif;}</style></head>\\n<body><div id=\"whole-content\"><div id=\"main-content\"><p id=\"text-content\" class=\"default-style\">Please wait...</p></div></div></body></html>' > wonderpush.min.html",
     "build:ovenplayer": "mkdir -p plugins_public/ovenplayer; cd plugins_public/ovenplayer; cp ../../node_modules/ovenplayer/dist/* .; cp ../../node_modules/dashjs/dist/dash.all.min.* .; cp ../../node_modules/hls.js/dist/hls.min.* .",
     "build:pdfjs": "mkdir -p plugins_public/pdfjs; cd plugins_public/pdfjs; cp ../../node_modules/pdfjs-dist/legacy/build/pdf.min.mjs pdf.min.mjs.js; cp ../../node_modules/pdfjs-dist/legacy/build/pdf.worker.min.mjs pdf.worker.min.mjs.js",
     "build:photoswipe": "mkdir -p plugins_public/photo-swipe; cd plugins_public/photo-swipe; cp ../../node_modules/photoswipe/dist/umd/*.js .; cp ../../node_modules/photoswipe/dist/*.css .",

+ 42 - 0
template/scripts/BxBasePushWonderPush.php

@@ -0,0 +1,42 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) UNA, Inc - https://una.io
+ * MIT License - https://opensource.org/licenses/MIT
+ *
+ * @defgroup    UnaBaseView UNA Base Representation Classes
+ * @{
+ */
+
+/**
+ * WonderPush integration.
+ * @see BxDolPush
+ */
+class BxBasePushWonderPush extends BxDolPushWonderPush
+{
+    protected function _getCodePageHeader()
+    {
+        if($this->_bCodeAdded || !$this->_sAppId)
+            return '';
+
+        $iProfileId = bx_get_logged_profile_id();
+        if(empty($iProfileId))
+            return '';
+
+        $aTags = self::getTags($iProfileId);
+        if(!$aTags)
+            return '';
+
+        $this->_bCodeAdded = true;
+        return $this->_oTemplate->parseHtmlByName('wonderpush.html', [
+            'params' => json_encode([
+                'webKey' => $this->_sWebKey,
+                'userId' => $aTags['user_hash'],
+                'applicationName' => getParam('site_title'),
+                'requiresUserConsent' => getParam('sys_push_wonderpush_requires_user_consent') ? true : false,
+            ]),
+            'tags' => json_encode($aTags),
+        ]);
+    }
+}
+
+/** @} */

+ 15 - 0
template/scripts_templ/BxTemplPushWonderPush.php

@@ -0,0 +1,15 @@
+<?php defined('BX_DOL') or die('hack attempt');
+/**
+ * Copyright (c) UNA, Inc - https://una.io
+ * MIT License - https://opensource.org/licenses/MIT
+ *
+ * @defgroup    UnaTemplate UNA Template Classes
+ * @{
+ */
+
+/**
+ * @see BxDolPush
+ */
+class BxTemplPushWonderPush extends BxBasePushWonderPush {}
+
+/** @} */

+ 11 - 0
template/wonderpush.html

@@ -0,0 +1,11 @@
+<script src="https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js" async></script>
+<script>
+window.WonderPush = window.WonderPush || [];
+WonderPush.push(["init", __params__]);
+WonderPush.push(function() {
+    var oTags = __tags__;
+    for (const [key, value] of Object.entries(oTags)) {
+        WonderPush.addTag(key, value);
+    }
+});
+</script>