Plugin Directory

Changeset 2775920


Ignore:
Timestamp:
08/26/2022 06:15:10 AM (4 years ago)
Author:
wiloke
Message:

Updated changelog and release 1.0.3

Location:
myshopkit-multi-currency-converter-wp/trunk
Files:
11 edited

Legend:

Unmodified
Added
Removed
  • myshopkit-multi-currency-converter-wp/trunk/README.txt

    r2634543 r2775920  
    1 === MyShopKit Multi Currency Converter WP - Auto currency switcher and multi currency conversion for international
    2 customers ===
     1=== Currency Converter - MyShopKit ===
    32Contributors: wiloke
    43Tags: woocommerce, currency, switcher, exchange, wordpress, currency for woocommerce, multi currency for woocommerce, woocommerce multi currency, woocommerce currency, currency switcher, woocommerce currency, bitcoin
    54Requires at least: 5.6
    6 Tested up to: 5.8
     5Tested up to: 6.0.1
    76Requires PHP: 7.4
    8 Stable tag: 1.0.1
     7Stable tag: 1.0.3
    98License: GPLv2 or later
    109
     
    1514Multi Currency Converter will help you to do without coding required!!
    1615
    17 >[Try the Demo](https://wookit.myshopkit.app/multi-currency-converter-demo/ "Demo") |
    18 [Documents](https://docs.wiloke.com/myshopkit-multi-currency-converter/ "Documents") |
    19 [PRO version](https://codecanyon.net/item/myshopkit-multi-currency-converter/34441693 "PRO version")
     16>[Try the Demo](https://wookit.myshopkit.app/multi-currency-converter-demo/ "Demo") | [Documents]
     17(https://docs.wiloke.com/myshopkit-multi-currency-converter/ "Documents") | [PRO version]
     18                                                                          (https://codecanyon.net/item/myshopkit-multi-currency-converter/34441693 "PRO version")
    2019
    21 [youtube https://youtu.be/UGueTvcYaL0]
     20[youtube https://www.youtube.com/watch?v=_HDUl1tQCnY]
    2221
    2322### Important Notice:
     
    5756== Screenshots ==
    58571. Admin Dashboard
    59 2. Multi Currency On Your Site
    60 2. Hovering on the currency and the Currency Control will be shown up
    6158
    6259== Changelog ==
  • myshopkit-multi-currency-converter-wp/trunk/myshopkit-multi-currency-converter-wp.php

    r2634543 r2775920  
    11<?php
    22/**
    3  * Plugin Name: Myshopkit Multi Currency Converter WP
    4  * Plugin URI: https://wiloke.com
     3 * Plugin Name: WooCommerce Currency Converter | MyShopKit
     4 * Plugin URI: https://woocommerce.myshopkit.app
    55 * Author: wiloke
    6  * Author URI: https://wiloke.com/product/multi-currency-converter/
    7  * Version: 1.0.1
     6 * Author URI: https://woocommerce.myshopkit.app/product/woocommerce-currency-converter-myshopkit/
     7 * Version: 1.0.3
    88 * Tested up to: 5.8
    99 * WC requires at least: 4.0
     
    4747
    4848define( 'MSKMC_PREFIX', 'mskmc_' );
    49 define( 'MSKMC_VERSION', '1.0.2' );
     49define( 'MSKMC_VERSION', uniqid() );
    5050define( 'MSKMC_HOOK_PREFIX', 'mskmc/' );
    5151define( 'MSKMC_REST_VERSION', 'v1' );
  • myshopkit-multi-currency-converter-wp/trunk/src/Dashboard/Assets/Css/Style.css

    r2634535 r2775920  
    1 
    2 #multi-currency-dashboard iframe#currency-iframe {
     1/*
     2#multi-currency-dashboard {
    33    height: 100%;
    44    width: 100%;
     
    77    padding: 20px 20px 20px 0;
    88    max-width: 1700px;
    9 }
     9} */
    1010
    1111#btn-Revoke-Purchase-Code {
     
    2020    padding: 20px;
    2121}
     22
     23iframe#currency-iframe {
     24    padding-top: 20px;
     25    max-height: 750px;
     26}
  • myshopkit-multi-currency-converter-wp/trunk/src/Dashboard/Assets/Js/Script.js

    r2634535 r2775920  
    1 (function () {
    2     "use strict";
    3 
    4     jQuery(document).ready(function () {
    5         const iframe = document.getElementById("currency-iframe");
    6 
    7         function authen() {
     1jQuery(document).ready(function () {
     2    const iframe = document.getElementById("currency-iframe");
     3    const body = document.body;
     4    const sidebar = document.querySelector('#adminmenuwrap');
     5
     6
     7    iframe.style.width = body.clientWidth - sidebar.clientWidth - 30 + 'px';
     8    iframe.style.maxWidth = '1500px';
     9    iframe.style.maxHeight = '800px';
     10    iframe.style.minHeight = '800px';
     11
     12    window.addEventListener('resize', () => {
     13        iframe.style.width = body.clientWidth - sidebar.clientWidth - 30 + 'px';
     14    })
     15
     16
     17    function authen() {
     18        jQuery.ajax({
     19            data: {
     20                action: "mskmc_getCodeAuth", //Tên action, dữ liệu gởi lên cho server
     21            },
     22            method: "POST",
     23            url: ajaxurl,
     24            success: function (response) {
     25                iframe.addEventListener("load", function () {
     26                    iframe.contentWindow.postMessage(
     27                        {
     28                            payload: {
     29                                url: window.MSKMC_GLOBAL.restBase,
     30                                token: response.data.code,
     31                                tidioId: window.MSKMC_GLOBAL.tidio || "",
     32                                clientSite: window.MSKMC_GLOBAL.clientSite || "",
     33                                email: window.MSKMC_GLOBAL.email || "",
     34                                purchaseCode: window.MSKMC_GLOBAL.purchaseCode || "",
     35                                purchaseCodeLink: window.MSKMC_GLOBAL.purchaseCodeLink || "",
     36                                productName: window.MSKMC_GLOBAL.productName || "",
     37                                endpointVerification:
     38                                    window.MSKMC_GLOBAL.endpointVerification || "",
     39                            },
     40                            type: "@InitializePage/getWPInfoRequest",
     41                        },
     42                        "*"
     43                    );
     44                    iframe.classList.remove("hidden");
     45                });
     46
     47                // check trường hợp login thành công
     48                if (iframe) {
     49                    iframe.contentWindow.postMessage(
     50                        {
     51                            payload: {
     52                                url: window.MSKMC_GLOBAL.restBase,
     53                                token: response.data.code,
     54                                tidioId: window.MSKMC_GLOBAL.tidio || "",
     55                                clientSite: window.MSKMC_GLOBAL.clientSite || "",
     56                                email: window.MSKMC_GLOBAL.email || "",
     57                                purchaseCode: window.MSKMC_GLOBAL.purchaseCode || "",
     58                                purchaseCodeLink: window.MSKMC_GLOBAL.purchaseCodeLink || "",
     59                                productName: window.MSKMC_GLOBAL.productName || "",
     60                                endpointVerification:
     61                                    window.MSKMC_GLOBAL.endpointVerification || "",
     62                            },
     63                            type: "@InitializePage/getWPInfoRequest",
     64                        },
     65                        "*"
     66                    );
     67                }
     68            },
     69            error: function (response) {
     70                iframe.addEventListener("load", function () {
     71                    iframe.contentWindow.postMessage(
     72                        {
     73                            payload: {
     74                                url: window.MSKMC_GLOBAL.restBase,
     75                                token: "",
     76                                tidioId: window.MSKMC_GLOBAL.tidio || "",
     77                                clientSite: window.MSKMC_GLOBAL.clientSite || "",
     78                                email: window.MSKMC_GLOBAL.email || "",
     79                                purchaseCode: window.MSKMC_GLOBAL.purchaseCode || "",
     80                                purchaseCodeLink: window.MSKMC_GLOBAL.purchaseCodeLink || "",
     81                                productName: window.MSKMC_GLOBAL.productName || "",
     82                                endpointVerification:
     83                                    window.MSKMC_GLOBAL.endpointVerification || "",
     84                            },
     85                            type: "@InitializePage/getWPInfoRequest",
     86                        },
     87                        "*"
     88                    );
     89                    iframe.classList.remove("hidden");
     90                });
     91            },
     92        });
     93    }
     94
     95    authen();
     96
     97    window.addEventListener("message", (event) => {
     98        if (event.source !== iframe.contentWindow) {
     99            return;
     100        }
     101
     102        const { payload, type } = event.data
     103
     104        if (type === "@HasPassed") {
     105            if (payload.hasPassed === true) {
     106                authen();
     107            }
     108        }
     109
     110        // api get me/settings
     111        if ('getMeSettings/request') {
    8112            jQuery.ajax({
     113                type: "POST",
     114                url: ajaxurl,
    9115                data: {
    10                     action: "mskmc_getCodeAuth", //Tên action, dữ liệu gởi lên cho server
    11                 },
    12                 method: "POST",
     116                    action: "mskmc_getMeSettings",
     117                    params: payload,
     118                },
     119                success: function (response) {
     120                    iframe.contentWindow.postMessage(
     121                        {
     122                            payload: response,
     123                            type: "getMeSettings/success",
     124                        },
     125                        "*"
     126                    );
     127                },
     128                error: function (jqXHR, error, errorThrown) {
     129                    alert(jqXHR.responseJSON.message);
     130                },
     131            });
     132        }
     133
     134        // api get registered-menus
     135        if (type === "getMenuWP/request") {
     136            jQuery.ajax({
     137                type: "POST",
    13138                url: ajaxurl,
     139                data: {
     140                    action: "mskmc_getMenuWP",
     141                    params: payload,
     142                },
    14143                success: function (response) {
    15                     iframe.addEventListener("load", function () {
     144                    iframe.contentWindow.postMessage(
     145                        {
     146                            payload: response,
     147                            type: "getMenuWP/success",
     148                        },
     149                        "*"
     150                    );
     151                },
     152                error: function (jqXHR, error, errorThrown) {
     153                    alert(jqXHR.responseJSON.message);
     154                },
     155            });
     156        }
     157
     158        // api save setting
     159        if (type === 'saveSettings/request') {
     160            const { isNew, settings } = payload;
     161            if (isNew){
     162                // Nếu isNew = true thì là create
     163                jQuery.ajax({
     164                    type: "POST",
     165                    url: ajaxurl+"?action=mskmc_saveSettings",
     166                    data: JSON.stringify({
     167                        action: "mskmc_saveSettings",
     168                        params: payload,
     169                    }),
     170                    dataType: "json",
     171                    contentType: "application/json;charset=utf-8",
     172                    success: function (response) {
    16173                        iframe.contentWindow.postMessage(
    17174                            {
    18                                 payload: {
    19                                     url: window.MSKMC_GLOBAL.restBase,
    20                                     token: response.data.code,
    21                                     tidioId: window.MSKMC_GLOBAL.tidio || "",
    22                                     clientSite: window.MSKMC_GLOBAL.clientSite || "",
    23                                     email: window.MSKMC_GLOBAL.email || "",
    24                                     purchaseCode: window.MSKMC_GLOBAL.purchaseCode || "",
    25                                     purchaseCodeLink: window.MSKMC_GLOBAL.purchaseCodeLink || "",
    26                                     productName: window.MSKMC_GLOBAL.productName || "",
    27                                     endpointVerification:
    28                                         window.MSKMC_GLOBAL.endpointVerification || "",
    29                                 },
    30                                 type: "@InitializePage/getWPInfoRequest",
     175                                payload: response,
     176                                type: "saveSettings/success",
    31177                            },
    32178                            "*"
    33179                        );
    34                         iframe.classList.remove("hidden");
    35                     });
    36 
    37                     // check trường hợp login thành công
    38                     if (iframe) {
     180                    },
     181                    error: function (jqXHR, error, errorThrown) {
     182                        alert(jqXHR.responseJSON.message);
     183                    },
     184                });
     185            }else {
     186                // Nếu isNew = false thì là update
     187                jQuery.ajax({
     188                    type: "POST",
     189                    url: ajaxurl+"?action=mskmc_updateSettings",
     190                    data: JSON.stringify({
     191                        action: "mskmc_updateSettings",
     192                        params: payload,
     193                    }),
     194                    dataType: "json",
     195                    contentType: "application/json;charset=utf-8",
     196                    success: function (response) {
    39197                        iframe.contentWindow.postMessage(
    40198                            {
    41                                 payload: {
    42                                     url: window.MSKMC_GLOBAL.restBase,
    43                                     token: response.data.code,
    44                                     tidioId: window.MSKMC_GLOBAL.tidio || "",
    45                                     clientSite: window.MSKMC_GLOBAL.clientSite || "",
    46                                     email: window.MSKMC_GLOBAL.email || "",
    47                                     purchaseCode: window.MSKMC_GLOBAL.purchaseCode || "",
    48                                     purchaseCodeLink: window.MSKMC_GLOBAL.purchaseCodeLink || "",
    49                                     productName: window.MSKMC_GLOBAL.productName || "",
    50                                     endpointVerification:
    51                                         window.MSKMC_GLOBAL.endpointVerification || "",
    52                                 },
    53                                 type: "@InitializePage/getWPInfoRequest",
     199                                payload: response,
     200                                type: "saveSettings/success",
    54201                            },
    55202                            "*"
    56203                        );
    57                     }
    58                 },
    59                 error: function (response) {
    60                     iframe.addEventListener("load", function () {
    61                         iframe.contentWindow.postMessage(
    62                             {
    63                                 payload: {
    64                                     url: window.MSKMC_GLOBAL.restBase,
    65                                     token: "",
    66                                     tidioId: window.MSKMC_GLOBAL.tidio || "",
    67                                     clientSite: window.MSKMC_GLOBAL.clientSite || "",
    68                                     email: window.MSKMC_GLOBAL.email || "",
    69                                     purchaseCode: window.MSKMC_GLOBAL.purchaseCode || "",
    70                                     purchaseCodeLink: window.MSKMC_GLOBAL.purchaseCodeLink || "",
    71                                     productName: window.MSKMC_GLOBAL.productName || "",
    72                                     endpointVerification:
    73                                         window.MSKMC_GLOBAL.endpointVerification || "",
    74                                 },
    75                                 type: "@InitializePage/getWPInfoRequest",
    76                             },
    77                             "*"
    78                         );
    79                         iframe.classList.remove("hidden");
    80                     });
    81                 },
    82             });
    83         }
    84 
    85         authen();
    86 
    87         window.addEventListener(
    88             "message",
    89             (event) => {
    90                 if (event.data.type === "@HasPassed") {
    91                     console.log(event.data);
    92                     if (event.data.payload.hasPassed === true) {
    93                         authen();
    94                     }
    95                 }
    96             },
    97             false
    98         );
    99         jQuery("#btn-Revoke-Purchase-Code").on('click', function () {
    100             let status = confirm("Are you sure you want to revoke the Purchase Code?");
    101             if (status) {
    102                 jQuery.ajax({
    103                     type: "POST",
    104                     url: ajaxurl,
    105                     data: {
    106                         action: "mskmc_revokePurchaseCode",
    107                         purchaseCode: MSKMC_GLOBAL.purchaseCode
    108                     },
    109                     success: function (response) {
    110                         if (response.status === 'success') {
    111                             location.reload();
    112                         } else {
    113                             alert(response.data.message);
    114                         }
    115204                    },
    116205                    error: function (jqXHR, error, errorThrown) {
     
    119208                });
    120209            }
    121         });
     210        }
     211
     212
     213
     214    }, false);
     215
     216    jQuery("#btn-Revoke-Purchase-Code").on('click', function () {
     217        let status = confirm("Are you sure you want to revoke the Purchase Code?");
     218        if (status) {
     219            jQuery.ajax({
     220                type: "POST",
     221                url: ajaxurl,
     222                data: {
     223                    action: "mskmc_revokePurchaseCode",
     224                    purchaseCode: MSKMC_GLOBAL.purchaseCode
     225                },
     226                success: function (response) {
     227                    if (response.status === 'success') {
     228                        location.reload();
     229                    } else {
     230                        alert(response.data.message);
     231                    }
     232                },
     233                error: function (jqXHR, error, errorThrown) {
     234                    alert(jqXHR.responseJSON.message);
     235                },
     236            });
     237        }
    122238    });
    123 
    124 })(jQuery);
     239});
  • myshopkit-multi-currency-converter-wp/trunk/src/Dashboard/Controllers/AuthController.php

    r2634535 r2775920  
    1616    const WP_AJAX_GET_CODE_APP_PASS    = 'wp_ajax_' . MSKMC_PREFIX . 'getCodeAuth';
    1717    const WP_AJAX_REVOKE_PURCHASE_CODE = 'wp_ajax_' . MSKMC_PREFIX . 'revokePurchaseCode';
    18     public array   $aOptions       = [];
    19     private string $deleteEndpoint = 'https://wookit.myshopkit.app/wp-json/ev/v1/verifications';
     18    public   $aOptions       = [];
     19    private $deleteEndpoint;
    2020
    2121    public function __construct() {
     22        $this->deleteEndpoint = ( is_ssl() ? 'https' : 'http' ) . '://wookit.myshopkit
     23    .app/wp-json/ev/v1/verifications';
    2224        add_action( self::WP_AJAX_GET_CODE_APP_PASS, [ $this, 'getCodeAuth' ] );
    2325        add_action( self::WP_AJAX_REVOKE_PURCHASE_CODE, [ $this, 'revokePurchaseCode' ] );
    24         add_action( 'admin_menu', [ $this, 'registerMenu' ] );
     26        //add_action( 'admin_menu', [ $this, 'registerMenu' ] );
    2527        add_action( 'rest_api_init', [ $this, 'registerRouter' ] );
     28        //add_action( 'admin_head', [ $this, 'resolveHttpRequestIssue' ] );
     29    }
     30
     31
     32    public function resolveHttpRequestIssue() {
     33        ?>
     34        <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
     35        <?php
    2636    }
    2737
     
    239249
    240250            if ( empty( $username ) || empty( $appPassword ) ) {
    241                 throw new Exception( esc_html__( 'Please go to Users -> Profile -> Create a new Application password to complete this setting.',
    242                     'myshopkit-multi-currency-converter-wp' ), 400 );
     251                $aResponse = WP_Application_Passwords::create_new_application_password(
     252                    get_current_user_id(),
     253                    [
     254                        'name' => 'MSKMC'
     255                    ]
     256                );
     257
     258                if ( ! is_wp_error( $aResponse ) ) {
     259                    Option::saveAuthSettings( [
     260                        'username'     => ( new WP_User( get_current_user_id() ) )->user_login,
     261                        'app_password' => $aResponse[0],
     262                        'uuid'         => $aResponse[1]['uuid']
     263                    ] );
     264                }
     265                return MessageFactory::factory( 'ajax' )->success( 'Success', [
     266                    'code' => base64_encode( Option::getUsername() . ':' . Option::getApplicationPassword() )
     267                ] );
    243268            }
    244269
  • myshopkit-multi-currency-converter-wp/trunk/src/Dashboard/Controllers/DashboardController.php

    r2634535 r2775920  
    7474
    7575    private function getIframe(): string {
    76         return defined( 'MYSHOPKIT_DEBUG' ) ? 'https://wordpress-currency.netlify.app/' :
    77             'https://currency-converter-dashboard.netlify.app/';
     76        return "https://wordpress-currency.netlify.app/";
    7877    }
    7978}
  • myshopkit-multi-currency-converter-wp/trunk/src/Dashboard/Shared/GeneralHelper.php

    r2634535 r2775920  
    99trait GeneralHelper
    1010{
    11     protected string $dashboardSlug = 'dashboard';
    12     protected string $authSlug      = 'auth-settings';
     11    protected $dashboardSlug = 'dashboard';
     12    protected $authSlug      = 'auth-settings';
    1313
    1414    protected function getDashboardSlug(): string
  • myshopkit-multi-currency-converter-wp/trunk/src/Dashboard/Shared/Option.php

    r2634535 r2775920  
    55class Option
    66{
    7     private static string $optionKey = MSKMC_PREFIX.'auth';
     7    private static $optionKey = MSKMC_PREFIX.'auth';
    88
    9     private static array $aDataOptions = [];
     9    private static $aDataOptions = [];
    1010
    1111    public static function saveAuthSettings(array $aValues)
  • myshopkit-multi-currency-converter-wp/trunk/src/PostScript/Controllers/PostScriptController.php

    r2634535 r2775920  
    1010{
    1111    const Woocommerce = 'Woocommerce';
    12     private string $urlJs = 'https://currency-converter-client.netlify.app/main.js';
     12    private $urlJs = '//currency-converter-client.netlify.app/main.js';
    1313
    1414    public function __construct()
  • myshopkit-multi-currency-converter-wp/trunk/src/RateExchange/Controllers/RateExchangeController.php

    r2634535 r2775920  
    33namespace MSKMCWP\RateExchange\Controllers;
    44
     5use MSKMCWP\Illuminate\Message\MessageFactory;
    56use WP_REST_Request;
    67
     
    89    public function __construct() {
    910        add_action( 'rest_api_init', [ $this, 'registerRouter' ] );
     11        add_action('wp_ajax_' . MSKMC_PREFIX . 'getMenuWP', [$this, 'ajaxGetMenuWP']);
    1012    }
     13    public function ajaxGetMenuWP()
     14    {
     15        $aParams = $_POST['params'] ?? [];
     16        $oRequest = new WP_REST_Request();
     17        if (!empty($aParams)) {
     18            foreach ($aParams as $key => $val) {
     19                $oRequest->set_param($key, $val);
     20            }
     21        }
    1122
     23        $this->getRateExchanges($oRequest);
     24    }
    1225    public function registerRouter() {
    1326        register_rest_route( MSKMC_REST, 'rate-exchanges', [
     
    2336        header( 'content-type: text/javascript; charset=utf-8' );
    2437        $response = wp_remote_retrieve_body(
    25             wp_remote_get( 'https://multicurrency.myshopkit.app/vge/mskmc/v1/rate-exchanges' )
     38            wp_remote_get( '//multicurrency.myshopkit.app/vge/mskmc/v1/rate-exchanges' )
    2639        );
    2740        echo esc_html( $response);
  • myshopkit-multi-currency-converter-wp/trunk/src/Store/Controllers/StoreController.php

    r2634535 r2775920  
    1313class StoreController
    1414{
    15     protected string $optionKey = '';
    16 
    17     public function __construct()
    18     {
    19         add_action('rest_api_init', [$this, 'registerRouter']);
    20         $this->optionKey = AutoPrefix::namePrefix('currency_settings');
    21     }
    22 
    23     public function registerRouter()
    24     {
    25         register_rest_route(MSKMC_REST, 'me/settings', [
    26             [
    27                 'methods'             => 'POST',
    28                 'permission_callback' => '__return_true',
    29                 'callback'            => [$this, 'createSettings']
    30             ],
    31             [
    32                 'methods'             => 'DELETE',
    33                 'permission_callback' => '__return_true',
    34                 'callback'            => [$this, 'deleteSettings']
    35             ],
    36             [
    37                 'methods'             => 'PUT',
    38                 'permission_callback' => '__return_true',
    39                 'callback'            => [$this, 'updateSettings']
    40             ],
    41             [
    42                 'methods'             => 'GET',
    43                 'permission_callback' => '__return_true',
    44                 'callback'            => [$this, 'getSettings']
    45             ]
    46         ]);
    47     }
    48 
    49     public function createSettings(WP_REST_Request $oRequest)
    50     {
    51         try {
    52             $this->isShopLoggedIn();
    53             $aSettings = $oRequest->get_param('settings');
    54             if (empty($aSettings)) {
    55                 throw new Exception(esc_html__('The settings is required', 'myshopkit-multi-currency-converter-wp'), 400);
    56             }
    57 
    58             if (!is_array($aSettings)) {
    59                 throw new Exception(esc_html__('Invalid setting format data', 'myshopkit-multi-currency-converter-wp'), 400);
    60             }
    61             update_option($this->optionKey, Json::encode($aSettings));
    62             return MessageFactory::factory('rest')
    63                 ->success(esc_html__('Congrats, Your settings have been saved successfully', 'myshopkit-multi-currency-converter-wp'),
    64                     []);
    65         } catch (Exception $oException) {
    66             return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
    67         }
    68     }
    69 
    70     /**
    71      * @throws Exception
    72      */
    73     private function isShopLoggedIn()
    74     {
    75         if (empty(get_current_user_id())) {
    76             throw new Exception(esc_html__('You must log into the site', 'myshopkit-multi-currency-converter-wp'), 403);
    77         }
    78         if (!current_user_can('manage_options')) {
    79             throw new Exception(esc_html__('You do not have permission to access this area', 'myshopkit-multi-currency-converter-wp'),
    80                 403);
    81         }
    82     }
    83 
    84     public function deleteSettings(WP_REST_Request $oRequest)
    85     {
    86         try {
    87             $this->isShopLoggedIn();
    88             update_option($this->optionKey, '');
    89             return MessageFactory::factory('rest')
    90                 ->success(esc_html__('Congrats, The data has been deleted successfully', 'myshopkit-multi-currency-converter-wp'));
    91         } catch (Exception $oException) {
    92             return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
    93         }
    94     }
    95 
    96     public function updateSettings(WP_REST_Request $oRequest)
    97     {
    98         try {
    99             $this->isShopLoggedIn();
    100             if ($aSettings = $oRequest->get_param('settings')) {
    101                 if (!is_array($aSettings)) {
    102                     throw new Exception(esc_html__('Invalid setting format data', 'myshopkit-multi-currency-converter-wp'), 400);
    103                 }
    104             }
    105             update_option($this->optionKey, Json::encode($aSettings));
    106             return MessageFactory::factory('rest')
    107                 ->success(esc_html__('Congrats, Your settings have been saved successfully', 'myshopkit-multi-currency-converter-wp'));
    108         } catch (Exception $oException) {
    109             return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
    110         }
    111     }
    112 
    113     public function getSettings(WP_REST_Request $oRequest)
    114     {
    115         try {
    116             $this->isShopLoggedIn();
    117             $settings = get_option($this->optionKey);
    118             $aSettings = empty($settings) ? [] : Json::decode($settings);
    119 
    120             return MessageFactory::factory('rest')->success(esc_html__('Congrats, The data has been got
     15    protected $optionKey = '';
     16
     17    public function __construct()
     18    {
     19        add_action('rest_api_init', [$this, 'registerRouter']);
     20        $this->optionKey = AutoPrefix::namePrefix('currency_settings');
     21        add_action('wp_ajax_' . MSKMC_PREFIX . 'getMeSettings', [$this, 'ajaxGetMeSettings']);
     22        add_action('wp_ajax_' . MSKMC_PREFIX . 'saveSettings', [$this, 'ajaxSaveSettings']);
     23        add_action('wp_ajax_' . MSKMC_PREFIX . 'updateSettings', [$this, 'ajaxUpdateSettings']);
     24    }
     25
     26    public function ajaxGetMeSettings()
     27    {
     28        $aParams = $_POST['params'] ?? [];
     29        $oRequest = new WP_REST_Request();
     30        if (!empty($aParams)) {
     31            foreach ($aParams as $key => $val) {
     32                $oRequest->set_param($key, $val);
     33            }
     34        }
     35
     36        $oResponse = $this->getSettings($oRequest);
     37        MessageFactory::factory('ajax')->success(
     38            $oResponse->get_data()['message'],
     39            $oResponse->get_data()['data']
     40        );
     41    }
     42
     43    public function ajaxSaveSettings()
     44    {
     45        if (isset($_POST['params']) && !empty($_POST['params'])) {
     46            $aParams = $_POST['params'];
     47        } else {
     48            $aData = json_decode(file_get_contents('php://input'), true);
     49            $aParams = $aData['params'];
     50        }
     51        $oRequest = new WP_REST_Request();
     52        if (!empty($aParams)) {
     53            foreach ($aParams as $key => $val) {
     54                $oRequest->set_param($key, $val);
     55            }
     56        }
     57
     58        $oResponse = $this->createSettings($oRequest);
     59        MessageFactory::factory('ajax')->success(
     60            $oResponse->get_data()['message'],
     61            $oResponse->get_data()['data']
     62        );
     63    }
     64
     65    public function ajaxUpdateSettings()
     66    {
     67        if (isset($_POST['params']) && !empty($_POST['params'])) {
     68            $aParams = $_POST['params'];
     69        } else {
     70            $aData = json_decode(file_get_contents('php://input'), true);
     71            $aParams = $aData['params'];
     72        }
     73        $oRequest = new WP_REST_Request();
     74        if (!empty($aParams)) {
     75            foreach ($aParams as $key => $val) {
     76                $oRequest->set_param($key, $val);
     77            }
     78        }
     79
     80        $oResponse = $this->updateSettings($oRequest);
     81        MessageFactory::factory('ajax')->success(
     82            $oResponse->get_data()['message'],
     83            $oResponse->get_data()['data']
     84        );
     85    }
     86
     87    public function registerRouter()
     88    {
     89        register_rest_route(MSKMC_REST, 'me/settings', [
     90            [
     91                'methods'             => 'POST',
     92                'permission_callback' => '__return_true',
     93                'callback'            => [$this, 'createSettings']
     94            ],
     95            [
     96                'methods'             => 'DELETE',
     97                'permission_callback' => '__return_true',
     98                'callback'            => [$this, 'deleteSettings']
     99            ],
     100            [
     101                'methods'             => 'PUT',
     102                'permission_callback' => '__return_true',
     103                'callback'            => [$this, 'updateSettings']
     104            ],
     105            [
     106                'methods'             => 'GET',
     107                'permission_callback' => '__return_true',
     108                'callback'            => [$this, 'getSettings']
     109            ]
     110        ]);
     111    }
     112
     113    public function createSettings(WP_REST_Request $oRequest)
     114    {
     115        try {
     116            $this->isShopLoggedIn();
     117            $aSettings = $oRequest->get_param('settings');
     118            if (empty($aSettings)) {
     119                throw new Exception(esc_html__('The settings is required', 'myshopkit-multi-currency-converter-wp'),
     120                    400);
     121            }
     122
     123            if (!is_array($aSettings)) {
     124                throw new Exception(esc_html__('Invalid setting format data', 'myshopkit-multi-currency-converter-wp'),
     125                    400);
     126            }
     127            update_option($this->optionKey, Json::encode($aSettings));
     128            return MessageFactory::factory('rest')
     129                ->success(esc_html__('Congrats, Your settings have been saved successfully',
     130                    'myshopkit-multi-currency-converter-wp'),
     131                    []);
     132        }
     133        catch (Exception $oException) {
     134            return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
     135        }
     136    }
     137
     138    /**
     139     * @throws Exception
     140     */
     141    private function isShopLoggedIn()
     142    {
     143        if (empty(get_current_user_id())) {
     144            throw new Exception(esc_html__('You must log into the site', 'myshopkit-multi-currency-converter-wp'), 403);
     145        }
     146        if (!current_user_can('manage_options')) {
     147            throw new Exception(esc_html__('You do not have permission to access this area',
     148                'myshopkit-multi-currency-converter-wp'),
     149                403);
     150        }
     151    }
     152
     153    public function deleteSettings(WP_REST_Request $oRequest)
     154    {
     155        try {
     156            $this->isShopLoggedIn();
     157            update_option($this->optionKey, '');
     158            return MessageFactory::factory('rest')
     159                ->success(esc_html__('Congrats, The data has been deleted successfully',
     160                    'myshopkit-multi-currency-converter-wp'));
     161        }
     162        catch (Exception $oException) {
     163            return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
     164        }
     165    }
     166
     167    public function updateSettings(WP_REST_Request $oRequest)
     168    {
     169        try {
     170            $this->isShopLoggedIn();
     171            if ($aSettings = $oRequest->get_param('settings')) {
     172                if (!is_array($aSettings)) {
     173                    throw new Exception(esc_html__('Invalid setting format data',
     174                        'myshopkit-multi-currency-converter-wp'), 400);
     175                }
     176            }
     177            update_option($this->optionKey, Json::encode($aSettings));
     178            return MessageFactory::factory('rest')
     179                ->success(esc_html__('Congrats, Your settings have been saved successfully',
     180                    'myshopkit-multi-currency-converter-wp'));
     181        }
     182        catch (Exception $oException) {
     183            return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
     184        }
     185    }
     186
     187    public function getSettings(WP_REST_Request $oRequest)
     188    {
     189        try {
     190            $this->isShopLoggedIn();
     191            $settings = get_option($this->optionKey);
     192            $aSettings = empty($settings) ? [] : Json::decode($settings);
     193
     194            return MessageFactory::factory('rest')->success(esc_html__('Congrats, The data has been got
    121195            successfully', 'myshopkit-multi-currency-converter-wp'), [
    122                 'settings' => empty($aSettings) ? null : $aSettings
    123             ]);
    124         } catch (Exception $oException) {
    125             return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
    126         }
    127     }
     196                'settings' => empty($aSettings) ? null : $aSettings
     197            ]);
     198        }
     199        catch (Exception $oException) {
     200            return MessageFactory::factory('rest')->error($oException->getMessage(), $oException->getCode());
     201        }
     202    }
    128203}
Note: See TracChangeset for help on using the changeset viewer.