Plugin Directory

Changeset 2303204


Ignore:
Timestamp:
05/12/2020 07:38:39 AM (6 years ago)
Author:
rnlab
Message:

feat: update code

Location:
mobile-builder/trunk
Files:
26 added
21 edited

Legend:

Unmodified
Added
Removed
  • mobile-builder/trunk

    • Property svn:ignore set to
      .git
  • mobile-builder/trunk/admin/class-mobile-builder-admin.php

    r2247251 r2303204  
    11<?php
    2 
    3 /**
    4  * The admin-specific functionality of the plugin.
    5  *
    6  * @link       https://rnlab.io
    7  * @since      1.0.0
    8  *
    9  * @package    Mobile_Builder
    10  * @subpackage Mobile_Builder/admin
    11  */
    122
    133/**
     
    199 * @package    Mobile_Builder
    2010 * @subpackage Mobile_Builder/admin
    21  * @author     Ngoc Dang <ngocdt@rnlab.io>
     11 * @author     RNLAB <ngocdt@rnlab.io>
    2212 */
    2313class Mobile_Builder_Admin {
     
    4232
    4333    /**
    44      * The table name save in database.
    45      *
    46      * @since    1.0.0
    47      * @access   private
    48      * @var      string $table_name The table name save in database.
    49      */
    50     private $table_name;
    51 
    52     /**
    53      * The api endpoint.
    54      *
    55      * @since    1.0.0
    56      * @access   private
    57      * @var      string $namespace The api endpoint.
    58      */
    59     private $namespace;
    60 
    61     /**
    6234     * Initialize the class and set its properties.
    6335     *
     
    6840     */
    6941    public function __construct( $plugin_name, $version ) {
    70         global $wpdb;
    7142
    7243        $this->plugin_name = $plugin_name;
    7344        $this->version     = $version;
    74         $this->table_name  = $wpdb->prefix . "mobile_builder_templates";
    75         $this->namespace   = $plugin_name . '/v' . intval( $version );
     45
    7646    }
    7747
     
    8252     */
    8353    public function enqueue_styles() {
    84         wp_enqueue_style( $this->plugin_name, 'https://cdnjs.rnlab.io/' . MOBILE_BUILDER_JS_VERSION . '/static/css/main.css', array(), MOBILE_BUILDER_JS_VERSION, 'all' );
     54
     55        /**
     56         * This function is provided for demonstration purposes only.
     57         *
     58         * An instance of this class should be passed to the run() function
     59         * defined in Mobile_Builder_Loader as all of the hooks are defined
     60         * in that particular class.
     61         *
     62         * The Mobile_Builder_Loader will then create the relationship
     63         * between the defined hooks and the functions defined in this
     64         * class.
     65         */
     66
     67        wp_enqueue_style( $this->plugin_name, 'https://cdnjs.rnlab.io/' . $this->version . '/static/css/main.css', array(), $this->version,
     68            'all' );
     69
    8570    }
    8671
     
    9176     */
    9277    public function enqueue_scripts() {
     78
     79        /**
     80         * This function is provided for demonstration purposes only.
     81         *
     82         * An instance of this class should be passed to the run() function
     83         * defined in Wp_Auth_Loader as all of the hooks are defined
     84         * in that particular class.
     85         *
     86         * The Wp_Auth_Loader will then create the relationship
     87         * between the defined hooks and the functions defined in this
     88         * class.
     89         */
     90
     91        $namespace = $this->plugin_name . '/v' . intval( $this->version );
     92
    9393        wp_enqueue_media();
    94         wp_enqueue_script( $this->plugin_name, 'https://cdnjs.rnlab.io/' . MOBILE_BUILDER_JS_VERSION . '/static/js/main.js', array(
     94
     95        wp_enqueue_script( $this->plugin_name, 'https://cdnjs.rnlab.io/' . $this->version . '/static/js/main.js', array(
    9596            'jquery',
    9697            'media-upload'
    97         ), MOBILE_BUILDER_JS_VERSION, true );
     98        ), $this->version, true );
     99
    98100        wp_localize_script( $this->plugin_name, 'wp_rnlab_configs', array(
    99101                'api_nonce' => wp_create_nonce( 'wp_rest' ),
    100102                'api_url'   => rest_url( '' ),
     103                'plugin_name'   => $this->plugin_name,
    101104            )
    102105        );
     106
    103107    }
    104108
    105109    /**
    106110     * Registers a REST API route
    107      *
    108111     * @since 1.0.0
    109112     */
    110113    public function add_api_routes() {
    111         $templates_endpoint = 'templates';
    112 
    113         register_rest_route( $this->namespace, $templates_endpoint, array(
     114        $namespace        = $this->plugin_name . '/v' . intval( $this->version );
     115        $endpoint         = 'template-mobile';
     116        $endpoint_configs = 'configs';
     117
     118        register_rest_route( $namespace, $endpoint, array(
    114119            array(
    115120                'methods'  => \WP_REST_Server::READABLE,
    116                 'callback' => array( $this, 'get_templates' ),
    117             ),
    118         ) );
    119 
    120         register_rest_route( $this->namespace, $templates_endpoint, array(
     121                'callback' => array( $this, 'get_template_config' ),
     122                // 'permission_callback'   => array( $this, 'admin_permissions_check' ),
     123            ),
     124        ) );
     125
     126        register_rest_route( $namespace, $endpoint, array(
    121127            array(
    122128                'methods'             => \WP_REST_Server::CREATABLE,
    123                 'callback'            => array( $this, 'add_templates' ),
     129                'callback'            => array( $this, 'add_template_config' ),
    124130                'permission_callback' => array( $this, 'admin_permissions_check' ),
    125131                'args'                => array(),
     
    127133        ) );
    128134
    129         register_rest_route( $this->namespace, $templates_endpoint, array(
     135        register_rest_route( $namespace, $endpoint, array(
    130136            array(
    131137                'methods'             => \WP_REST_Server::EDITABLE,
    132                 'callback'            => array( $this, 'update_templates' ),
     138                'callback'            => array( $this, 'update_template_config' ),
    133139                'permission_callback' => array( $this, 'admin_permissions_check' ),
    134140                'args'                => array(),
     
    136142        ) );
    137143
    138         register_rest_route( $this->namespace, $templates_endpoint, array(
     144        register_rest_route( $namespace, $endpoint, array(
    139145            array(
    140146                'methods'             => \WP_REST_Server::DELETABLE,
    141                 'callback'            => array( $this, 'delete_templates' ),
     147                'callback'            => array( $this, 'delete_template_config' ),
    142148                'permission_callback' => array( $this, 'admin_permissions_check' ),
    143149                'args'                => array(),
    144150            ),
    145151        ) );
     152
     153        register_rest_route( $namespace, $endpoint_configs, array(
     154            array(
     155                'methods'  => \WP_REST_Server::READABLE,
     156                'callback' => array( $this, 'get_configs' ),
     157            ),
     158        ) );
     159
     160        register_rest_route( $namespace, $endpoint_configs, array(
     161            array(
     162                'methods'             => \WP_REST_Server::CREATABLE,
     163                'callback'            => array( $this, 'update_configs' ),
     164                'permission_callback' => array( $this, 'admin_permissions_check' ),
     165                'args'                => array(),
     166            ),
     167        ) );
     168
     169    }
     170
     171    /**
     172     * @return array|object|null
     173     * @since 1.0.0
     174     */
     175    public function template_configs() {
     176        global $wpdb;
     177        $table_name = $wpdb->prefix . MOBILE_BUILDER_TABLE_NAME;
     178        return $wpdb->get_results( "SELECT * FROM $table_name", OBJECT );
     179    }
     180
     181    /**
     182     * @param $request
     183     *
     184     * @return WP_REST_Response
     185     * @since    1.0.0
     186     */
     187    public function get_template_config( $request ) {
     188        return new WP_REST_Response( $this->template_configs(), 200 );
     189    }
     190
     191    /**
     192     * @param $request
     193     *
     194     * @return WP_REST_Response
     195     * @since    1.0.0
     196     */
     197    public function add_template_config( $request ) {
     198        global $wpdb;
     199        $table_name = $wpdb->prefix . MOBILE_BUILDER_TABLE_NAME;
     200
     201        $data = $request->get_param( 'data' );
     202
     203        $results = $wpdb->insert(
     204            $table_name,
     205            $data
     206        );
     207
     208        return new WP_REST_Response( $results, 200 );
     209    }
     210
     211    /**
     212     * @param $request
     213     *
     214     * @return WP_REST_Response
     215     * @since    1.0.0
     216     */
     217    public function update_template_config( $request ) {
     218        global $wpdb;
     219        $table_name = $wpdb->prefix . MOBILE_BUILDER_TABLE_NAME;
     220
     221        $data  = $request->get_param( 'data' );
     222        $where = $request->get_param( 'where' );
     223
     224        $results = $wpdb->update(
     225            $table_name,
     226            $data,
     227            $where
     228        );
     229
     230        return new WP_REST_Response( $results, 200 );
     231    }
     232
     233    /**
     234     * @param $request
     235     *
     236     * @return WP_REST_Response
     237     * @since    1.0.0
     238     */
     239    public function delete_template_config( $request ) {
     240        global $wpdb;
     241        $table_name = $wpdb->prefix . MOBILE_BUILDER_TABLE_NAME;
     242
     243        $where = $request->get_param( 'where' );
     244
     245        $results = $wpdb->delete(
     246            $table_name,
     247            $where
     248        );
     249
     250        return new WP_REST_Response( $results, 200 );
     251    }
     252
     253    /**
     254     * @param $request
     255     *
     256     * @return WP_REST_Response
     257     * @since    1.0.0
     258     */
     259    public function get_configs( $request ) {
     260
     261        $configs = get_option( 'mobile_builder_configs', array(
     262            "requireLogin"       => false,
     263            "toggleSidebar"      => false,
     264            "isBeforeNewProduct" => 5
     265        ) );
     266
     267        return new WP_REST_Response( maybe_unserialize( $configs ), 200 );
     268    }
     269
     270    /**
     271     * @param $request
     272     *
     273     * @return WP_REST_Response
     274     * @since    1.0.0
     275     */
     276    public function update_configs( $request ) {
     277
     278        $data   = $request->get_param( 'data' );
     279        $status = false;
     280
     281        if ( get_option( 'mobile_builder_configs' ) ) {
     282            $status = update_option( 'mobile_builder_configs', maybe_serialize( $data ) );
     283        } else {
     284            $status = add_option( 'mobile_builder_configs', maybe_serialize( $data ) );
     285        }
     286
     287        return new WP_REST_Response( array( 'status' => $status ), 200 );
    146288    }
    147289
     
    150292     *
    151293     * @return mixed
     294     * @since    1.0.0
    152295     */
    153296    public function admin_permissions_check( $request ) {
     
    156299
    157300    /**
    158      * @param $request
    159      *
    160      * @return WP_REST_Response
    161      */
    162     public function get_templates( $request ) {
    163         global $wpdb;
    164         $results = $wpdb->get_results( "SELECT * FROM {$this->table_name}", OBJECT );
    165 
    166         return new WP_REST_Response( $results, 200 );
    167     }
    168 
    169     /**
    170      * @param $request
    171      *
    172      * @return WP_REST_Response
    173      */
    174     public function add_templates( $request ) {
    175         global $wpdb;
    176 
    177         $data    = $request->get_param( 'data' );
    178         $results = $wpdb->insert(
    179             $this->table_name,
    180             $data
    181         );
    182 
    183         return new WP_REST_Response( $results, 200 );
    184     }
    185 
    186     /**
    187      * @param $request
    188      *
    189      * @return WP_REST_Response
    190      */
    191     public function update_templates( $request ) {
    192         global $wpdb;
    193 
    194         $data  = $request->get_param( 'data' );
    195         $where = $request->get_param( 'where' );
    196 
    197         $results = $wpdb->update(
    198             $this->table_name,
    199             $data,
    200             $where
    201         );
    202 
    203         return new WP_REST_Response( $results, 200 );
    204     }
    205 
    206     /**
    207      * @param $request
    208      *
    209      * @return WP_REST_Response
    210      */
    211     public function delete_templates( $request ) {
    212         global $wpdb;
    213 
    214         $where   = $request->get_param( 'where' );
    215         $results = $wpdb->delete(
    216             $this->table_name,
    217             $where
    218         );
    219 
    220         return new WP_REST_Response( $results, 200 );
    221     }
    222 
    223     /**
    224301     * Register the administration menu for this plugin into the WordPress Dashboard menu.
    225302     *
     
    228305    public function add_plugin_admin_menu() {
    229306        /*
    230          * Add a settings page for this plugin to the sidebar.
     307         * Add a settings page for this plugin to the Settings menu.
    231308         */
     309        $hook_suffix = add_options_page(
     310            __( 'Mobile Builder', $this->plugin_name ),
     311            __( 'Mobile Builder', $this->plugin_name ),
     312            'manage_options',
     313            $this->plugin_name,
     314            array( $this, 'display_plugin_admin_page' )
     315        );
    232316
    233317        $hook_suffix = add_menu_page(
     
    269353    }
    270354
    271 
    272355}
  • mobile-builder/trunk/composer.json

    r2247209 r2303204  
    11{
    2     "name": "rnlab.io/mobile-builder",
    3     "description": "The most advanced drag & drop app builder. Create multi templates and app controls.",
    4     "type": "project",
    5     "require": {
    6         "facebook/graph-sdk": "^5.7",
    7         "firebase/php-jwt": "^5.0"
    8     },
    9     "license": "GNU",
     2    "name": "rnlab/wp-app-control",
     3    "description": "libs",
    104    "authors": [
    115        {
    12             "name": "Rnlab.io",
     6            "name": "Ngoc Dang",
    137            "email": "ngocdt@rnlab.io"
    148        }
    15     ]
     9    ],
     10    "require": {
     11        "firebase/php-jwt": "^5.0",
     12        "facebook/graph-sdk": "^5.7"
     13    }
    1614}
  • mobile-builder/trunk/composer.lock

    r2247209 r2303204  
    55        "This file is @generated automatically"
    66    ],
    7     "content-hash": "c4e66c9bf29ee23156b31208e7d5e674",
     7    "content-hash": "76bdd58d2f9c902b61f7b321dad5d3ad",
    88    "packages": [
    99        {
     
    6767        {
    6868            "name": "firebase/php-jwt",
    69             "version": "v5.0.0",
     69            "version": "v5.2.0",
    7070            "source": {
    7171                "type": "git",
    7272                "url": "https://github.com/firebase/php-jwt.git",
    73                 "reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e"
     73                "reference": "feb0e820b8436873675fd3aca04f3728eb2185cb"
    7474            },
    7575            "dist": {
    7676                "type": "zip",
    77                 "url": "https://api.github.com/repos/firebase/php-jwt/zipball/9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
    78                 "reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
     77                "url": "https://api.github.com/repos/firebase/php-jwt/zipball/feb0e820b8436873675fd3aca04f3728eb2185cb",
     78                "reference": "feb0e820b8436873675fd3aca04f3728eb2185cb",
    7979                "shasum": ""
    8080            },
     
    8383            },
    8484            "require-dev": {
    85                 "phpunit/phpunit": " 4.8.35"
     85                "phpunit/phpunit": ">=4.8 <=9"
    8686            },
    8787            "type": "library",
     
    109109            "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
    110110            "homepage": "https://github.com/firebase/php-jwt",
    111             "time": "2017-06-27T22:17:23+00:00"
     111            "keywords": [
     112                "jwt",
     113                "php"
     114            ],
     115            "time": "2020-03-25T18:49:23+00:00"
    112116        }
    113117    ],
  • mobile-builder/trunk/includes/class-mobile-builder-activator.php

    r2247251 r2303204  
    1919 * @package    Mobile_Builder
    2020 * @subpackage Mobile_Builder/includes
    21  * @author     Ngoc Dang <ngocdt@rnlab.io>
     21 * @author     RNLAB <ngocdt@rnlab.io>
    2222 */
    23 class Mobile_Builder_Activator
    24 {
     23class Mobile_Builder_Activator {
    2524
    26     /**
    27      * Short Description. (use period)
    28      *
    29      * Long Description.
    30      *
    31      * @since    1.0.0
    32      */
    33     public static function activate()
    34     {
    35         global $wpdb;
     25    /**
     26     * Active plugin action
     27     *
     28     * Create table to store mobile template
     29     *
     30     * @since    1.0.0
     31     */
     32    public static function activate() {
     33        global $wpdb;
    3634
    37         $table_name = $wpdb->prefix . "mobile_builder_templates";
    38         $charset_collate = $wpdb->get_charset_collate();
     35        $table_name      = $wpdb->prefix . MOBILE_BUILDER_TABLE_NAME;
     36        $charset_collate = $wpdb->get_charset_collate();
    3937
    40         $sql = "CREATE TABLE $table_name (
     38        $sql = "CREATE TABLE $table_name (
    4139          id mediumint(9) NOT NULL AUTO_INCREMENT,
    42           name VARCHAR(254) NULL DEFAULT 'Default template',
     40          name VARCHAR(254) NULL DEFAULT 'Template Name',
    4341          data longtext NULL DEFAULT NULL,
    4442          settings longtext NULL DEFAULT NULL,
     
    4947        ) $charset_collate;";
    5048
    51         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    52         dbDelta($sql);
    53     }
     49        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
     50        dbDelta( $sql );
     51    }
    5452
    5553}
  • mobile-builder/trunk/includes/class-mobile-builder-deactivator.php

    r2247251 r2303204  
    1919 * @package    Mobile_Builder
    2020 * @subpackage Mobile_Builder/includes
    21  * @author     Ngoc Dang <ngocdt@rnlab.io>
     21 * @author     RNLAB <ngocdt@rnlab.io>
    2222 */
    2323class Mobile_Builder_Deactivator {
  • mobile-builder/trunk/includes/class-mobile-builder-i18n.php

    r2247251 r2303204  
    2323 * @package    Mobile_Builder
    2424 * @subpackage Mobile_Builder/includes
    25  * @author     Ngoc Dang <ngocdt@rnlab.io>
     25 * @author     RNLAB <ngocdt@rnlab.io>
    2626 */
    2727class Mobile_Builder_i18n {
  • mobile-builder/trunk/includes/class-mobile-builder-loader.php

    r2247251 r2303204  
    2020 * @package    Mobile_Builder
    2121 * @subpackage Mobile_Builder/includes
    22  * @author     Ngoc Dang <ngocdt@rnlab.io>
     22 * @author     RNLAB <ngocdt@rnlab.io>
    2323 */
    2424class Mobile_Builder_Loader {
  • mobile-builder/trunk/includes/class-mobile-builder.php

    r2247251 r2303204  
    2626 * @package    Mobile_Builder
    2727 * @subpackage Mobile_Builder/includes
    28  * @author     Ngoc Dang <ngocdt@rnlab.io>
     28 * @author     RNLAB <ngocdt@rnlab.io>
    2929 */
    3030class Mobile_Builder {
     
    3636     * @since    1.0.0
    3737     * @access   protected
    38      * @var      Mobile_Builder_Loader    $loader    Maintains and registers all hooks for the plugin.
     38     * @var      Mobile_Builder_Loader $loader Maintains and registers all hooks for the plugin.
    3939     */
    4040    protected $loader;
     
    4545     * @since    1.0.0
    4646     * @access   protected
    47      * @var      string    $plugin_name    The string used to uniquely identify this plugin.
     47     * @var      string $plugin_name The string used to uniquely identify this plugin.
    4848     */
    4949    protected $plugin_name;
     
    5454     * @since    1.0.0
    5555     * @access   protected
    56      * @var      string    $version    The current version of the plugin.
     56     * @var      string $version The current version of the plugin.
    5757     */
    5858    protected $version;
     
    6868     */
    6969    public function __construct() {
    70         if ( defined( 'MOBILE_BUILDER_VERSION' ) ) {
    71             $this->version = MOBILE_BUILDER_VERSION;
    72         } else {
    73             $this->version = '1.0.0';
    74         }
    75         $this->plugin_name = 'mobile-builder';
     70        $this->version     = MOBILE_BUILDER_CONTROL_VERSION;
     71        $this->plugin_name = MOBILE_BUILDER_PLUGIN_NAME;
    7672
    7773        $this->load_dependencies();
     
    7975        $this->define_admin_hooks();
    8076        $this->define_public_hooks();
     77        $this->define_product_hooks();
     78        $this->define_api_hooks();
    8179
    8280    }
     
    10199
    102100        /**
     101         * Load function
     102         */
     103        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'helpers/mobile-builder-functions.php';
     104
     105        /**
    103106         * Load dependency install by composer
    104107         */
     
    118121
    119122        /**
     123         * The class responsible for loading payment gateways
     124         * @author Ngoc Dang
     125         * @since 1.1.0
     126         */
     127        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/gateways/class-mobile-builder-gateway-paypal.php';
     128        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/gateways/class-mobile-builder-gateway-razorpay.php';
     129
     130        /**
    120131         * The class responsible for defining all actions that occur in the admin area.
    121132         */
     
    128139        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-mobile-builder-public.php';
    129140
     141        /**
     142         * The class responsible for defining all actions that occur in the product-facing
     143         * side of the site.
     144         */
     145        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'product/class-mobile-builder-product.php';
     146
     147        /**
     148         * The class responsible for defining all actions that occur in the api
     149         * side of the site.
     150         */
     151        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'api/class-mobile-builder-cart.php';
     152        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'api/class-mobile-builder-vendor.php';
     153
     154        /**
     155         * Load library
     156         * @since 1.2.3
     157         */
     158        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/libraries/class-mobile-builder-public-key.php';
     159
    130160        $this->loader = new Mobile_Builder_Loader();
    131161
     
    160190        $plugin_admin = new Mobile_Builder_Admin( $this->get_plugin_name(), $this->get_version() );
    161191
    162         // Define admin routers
    163192        $this->loader->add_action( 'rest_api_init', $plugin_admin, 'add_api_routes' );
    164193
    165194        // Add the options page and menu item.
    166         $this->loader->add_action( 'admin_menu', $plugin_admin, 'add_plugin_admin_menu' );
     195        add_action( 'admin_menu', array( $plugin_admin, 'add_plugin_admin_menu' ) );
    167196
    168197        // Add plugin action link point to settings page
    169         $this->loader->add_filter( 'plugin_action_links_' . $this->plugin_name . '/' . $this->plugin_name . '.php', $plugin_admin, 'add_plugin_action_links' );
     198        add_filter( 'plugin_action_links_' . $this->plugin_name . '/' . $this->plugin_name . '.php', array(
     199            $plugin_admin,
     200            'add_plugin_action_links'
     201        ) );
     202
     203    }
     204
     205
     206    private function define_api_hooks() {
     207
     208        // Cart
     209        $plugin_cart = new Mobile_Builder_Cart( $this->get_plugin_name(), $this->get_version() );
     210        $this->loader->add_action( 'wp_loaded', $plugin_cart, 'rnlab_pre_car_rest_api', 5 );
     211        $this->loader->add_action( 'rest_api_init', $plugin_cart, 'add_api_routes', 10 );
     212
     213        // Vendor
     214        $plugin_api = new Mobile_Builder_Vendor( $this->get_plugin_name(), $this->get_version() );
     215        $this->loader->add_action( 'rest_api_init', $plugin_api, 'add_api_routes', 10 );
     216        $this->loader->add_filter( 'posts_clauses', $plugin_api, 'mbd_product_list_geo_location_filter_post_clauses', 500, 2 );
     217        $this->loader->add_filter( 'posts_clauses', $plugin_api, 'mbd_product_list_by_vendor', 501, 2 );
    170218
    171219    }
     
    182230        $plugin_public = new Mobile_Builder_Public( $this->get_plugin_name(), $this->get_version() );
    183231
     232        $rnlab_gateways = array();
     233
     234        // Payment Gateway via PayPal Standard
     235        $gateway_paypal = new Mobile_Builder_Gateway_PayPal();
     236        array_push( $rnlab_gateways, $gateway_paypal );
     237
     238        // Payment Gateway via Razorpay Standard
     239        $gateway_razorpay = new Mobile_Builder_Gateway_Razorpay();
     240        array_push( $rnlab_gateways, $gateway_razorpay );
     241
     242        // Register Payment Endpoint for all Gateways
     243        foreach ( $rnlab_gateways as &$rnlab_gateway ) {
     244            $this->loader->add_filter( 'rnlab_pre_process_' . $rnlab_gateway->gateway_id . '_payment', $rnlab_gateway, 'rnlab_pre_process_payment' );
     245        }
     246
     247        $this->loader->add_action( 'rest_api_init', $plugin_public, 'add_api_routes' );
     248        $this->loader->add_filter( 'determine_current_user', $plugin_public, 'determine_current_user' );
     249
     250        /**
     251         * Fillter locate template
     252         * @since 1.2.0
     253         */
     254        $this->loader->add_filter( 'woocommerce_locate_template', $plugin_public, 'woocommerce_locate_template', 100, 3 );
     255
     256        /**
     257         * Fillter add to cart before redirect to checkout page
     258         * @since 1.2.0
     259         */
     260        $this->loader->add_action( 'template_redirect', $plugin_public, 'template_redirect' );
     261
     262        /**
     263         * Add style for checkout page
     264         * @since 1.2.0
     265         */
    184266        $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
    185         $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );
     267
     268        /**
     269         * Filter token digits
     270         * @since 1.3.3
     271         */
     272        $this->loader->add_filter( 'digits_rest_token_data', $plugin_public, 'custom_digits_rest_token_data', 100, 2 );
     273
     274    }
     275
     276    /**
     277     * Register all of the hooks related to the public-facing functionality
     278     * of the plugin.
     279     *
     280     * @since    1.0.0
     281     * @access   private
     282     */
     283    private function define_product_hooks() {
     284
     285        $plugin_product = new Mobile_Builder_Product( $this->get_plugin_name(), $this->get_version() );
     286
     287        $this->loader->add_action( 'rest_api_init', $plugin_product, 'add_api_routes' );
     288
     289        // Product variation
     290        $this->loader->add_filter( 'woocommerce_rest_prepare_product_variation_object', $plugin_product,
     291            'custom_woocommerce_rest_prepare_product_variation_object' );
     292
     293        $this->loader->add_filter( 'woocommerce_rest_prepare_product_variation_object', $plugin_product,
     294            'prepare_product_variation_images', 10, 3 );
     295
     296        // Product
     297        $this->loader->add_filter( 'woocommerce_rest_prepare_product_object', $plugin_product,
     298            'custom_change_product_response', 20, 3 );
     299
     300        // Category
     301        $this->loader->add_filter( 'woocommerce_rest_prepare_product_cat', $plugin_product,
     302            'custom_change_product_cat', 20, 3 );
     303
     304        // Blog
     305        $this->loader->add_filter( 'the_title', $plugin_product,
     306            'custom_the_title', 20, 3 );
     307
     308        $this->loader->add_filter( 'woocommerce_rest_prepare_product_object', $plugin_product,
     309            'prepare_product_images', 30, 3 );
     310
     311        // Product Attribute
     312        $this->loader->add_filter( 'woocommerce_rest_prepare_product_attribute', $plugin_product,
     313            'custom_woocommerce_rest_prepare_product_attribute', 10, 3 );
     314
     315        $this->loader->add_filter( 'woocommerce_rest_prepare_pa_color', $plugin_product, 'add_value_pa_color' );
     316        $this->loader->add_filter( 'woocommerce_rest_prepare_pa_image', $plugin_product, 'add_value_pa_image' );
     317
     318        $this->loader->add_filter( 'wcml_client_currency', $plugin_product, 'mbd_wcml_client_currency' );
    186319
    187320    }
     
    200333     * WordPress and to define internationalization functionality.
    201334     *
     335     * @return    string    The name of the plugin.
    202336     * @since     1.0.0
    203      * @return    string    The name of the plugin.
    204337     */
    205338    public function get_plugin_name() {
     
    210343     * The reference to the class that orchestrates the hooks with the plugin.
    211344     *
     345     * @return    Mobile_Builder_Loader    Orchestrates the hooks of the plugin.
    212346     * @since     1.0.0
    213      * @return    Mobile_Builder_Loader    Orchestrates the hooks of the plugin.
    214347     */
    215348    public function get_loader() {
     
    220353     * Retrieve the version number of the plugin.
    221354     *
     355     * @return    string    The version number of the plugin.
    222356     * @since     1.0.0
    223      * @return    string    The version number of the plugin.
    224357     */
    225358    public function get_version() {
  • mobile-builder/trunk/mobile-builder.php

    r2247246 r2303204  
    2020 */
    2121
     22
    2223// If this file is called directly, abort.
    2324if ( ! defined( 'WPINC' ) ) {
     
    3031 * Rename this for your plugin and update it as you release new versions.
    3132 */
    32 define( 'MOBILE_BUILDER_VERSION', '1.0.0' );
    33 define( 'MOBILE_BUILDER_APP_VERSION', '1.3.1' );
    34 define( 'MOBILE_BUILDER_JS_VERSION', '1.3.0' );
     33define( 'MOBILE_BUILDER_CONTROL_VERSION', '1.4.4' );
     34
     35define( 'MOBILE_BUILDER_PLUGIN_NAME', 'mobile-builder' );
     36
     37define( 'MOBILE_BUILDER_TABLE_NAME', 'mobile_builder' );
    3538
    3639/**
     
    7679
    7780}
     81
    7882run_mobile_builder();
  • mobile-builder/trunk/public/class-mobile-builder-public.php

    r2247251 r2303204  
    11<?php
     2
     3use \Firebase\JWT\JWT;
    24
    35/**
     
    1921 * @package    Mobile_Builder
    2022 * @subpackage Mobile_Builder/public
    21  * @author     Ngoc Dang <ngocdt@rnlab.io>
     23 * @author     RNLAB <ngocdt@rnlab.io>
    2224 */
    2325class Mobile_Builder_Public {
     
    2830     * @since    1.0.0
    2931     * @access   private
    30      * @var      string    $plugin_name    The ID of this plugin.
     32     * @var      string $plugin_name The ID of this plugin.
    3133     */
    3234    private $plugin_name;
     
    3739     * @since    1.0.0
    3840     * @access   private
    39      * @var      string    $version    The current version of this plugin.
     41     * @var      string $version The current version of this plugin.
    4042     */
    4143    private $version;
    4244
    4345    /**
     46     *  Then key to encode token
     47     * @since    1.0.0
     48     * @access   private
     49     * @var      string $key The key to encode token
     50     */
     51    private $key;
     52
     53    /**
    4454     * Initialize the class and set its properties.
    4555     *
    46      * @since    1.0.0
    47      * @param      string    $plugin_name       The name of the plugin.
    48      * @param      string    $version    The version of this plugin.
     56     * @param string $plugin_name The name of the plugin.
     57     * @param string $version The version of this plugin.
     58     *
     59     * @since      1.0.0
    4960     */
    5061    public function __construct( $plugin_name, $version ) {
    5162
    5263        $this->plugin_name = $plugin_name;
    53         $this->version = $version;
     64        $this->version     = $version;
     65        $this->key         = defined( 'JWT_SECRET_KEY' ) ? JWT_SECRET_KEY : "example_key";
    5466
    5567    }
     
    5870     * Register the stylesheets for the public-facing side of the site.
    5971     *
    60      * @since    1.0.0
     72     * @since    1.2.0
    6173     */
    6274    public function enqueue_styles() {
     
    6678         *
    6779         * An instance of this class should be passed to the run() function
    68          * defined in Mobile_Builder_Loader as all of the hooks are defined
     80         * defined in Blog_1_Loader as all of the hooks are defined
    6981         * in that particular class.
    7082         *
    71          * The Mobile_Builder_Loader will then create the relationship
     83         * The Blog_1_Loader will then create the relationship
    7284         * between the defined hooks and the functions defined in this
    7385         * class.
    7486         */
    75 
    76         wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/mobile-builder-public.css', array(), $this->version, 'all' );
    77 
    78     }
    79 
    80     /**
    81      * Register the JavaScript for the public-facing side of the site.
    82      *
    83      * @since    1.0.0
    84      */
    85     public function enqueue_scripts() {
     87        if ( isset( $_GET['mobile'] ) ) {
     88            wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/checkout.css', array(), $this->version, 'all' );
     89        }
     90
     91    }
     92
     93    /**
     94     * Registers a REST API route
     95     *
     96     * @since 1.0.0
     97     */
     98    public function add_api_routes() {
     99        $namespace = $this->plugin_name . '/v' . intval( $this->version );
     100        $review    = new WC_REST_Product_Reviews_Controller();
     101        $customer  = new WC_REST_Customers_Controller();
    86102
    87103        /**
    88          * This function is provided for demonstration purposes only.
     104         * @since 1.3.4
     105         */
     106        register_rest_route( $namespace, 'reviews', array(
     107            'methods'  => WP_REST_Server::CREATABLE,
     108            'callback' => array( $review, 'create_item' ),
     109        ) );
     110
     111        /**
     112         * @since 1.3.4
     113         */
     114        register_rest_route( $namespace, 'customers/(?P<id>[\d]+)', array(
     115            'methods'             => WP_REST_Server::EDITABLE,
     116            'callback'            => array( $customer, 'update_item' ),
     117            'permission_callback' => array( $this, 'update_item_permissions_check' ),
     118        ) );
     119
     120        register_rest_route( $namespace, 'token', array(
     121            'methods'  => WP_REST_Server::READABLE,
     122            'callback' => array( $this, 'app_token' ),
     123        ) );
     124
     125        register_rest_route( $namespace, 'login', array(
     126            'methods'  => WP_REST_Server::CREATABLE,
     127            'callback' => array( $this, 'login' ),
     128        ) );
     129
     130        register_rest_route( $namespace, 'login-otp', array(
     131            'methods'  => WP_REST_Server::CREATABLE,
     132            'callback' => array( $this, 'login_otp' ),
     133        ) );
     134
     135        register_rest_route( $namespace, 'current', array(
     136            'methods'  => WP_REST_Server::READABLE,
     137            'callback' => array( $this, 'current' ),
     138        ) );
     139
     140        register_rest_route( $namespace, 'facebook', array(
     141            'methods'  => WP_REST_Server::CREATABLE,
     142            'callback' => array( $this, 'login_facebook' ),
     143        ) );
     144
     145        register_rest_route( $namespace, 'google', array(
     146            'methods'  => WP_REST_Server::CREATABLE,
     147            'callback' => array( $this, 'login_google' ),
     148        ) );
     149
     150        register_rest_route( $namespace, 'apple', array(
     151            'methods'  => WP_REST_Server::CREATABLE,
     152            'callback' => array( $this, 'login_apple' ),
     153        ) );
     154
     155        register_rest_route( $namespace, 'register', array(
     156            'methods'  => WP_REST_Server::CREATABLE,
     157            'callback' => array( $this, 'register' ),
     158        ) );
     159
     160        register_rest_route( $namespace, 'lost-password', array(
     161            'methods'  => WP_REST_Server::CREATABLE,
     162            'callback' => array( $this, 'retrieve_password' ),
     163        ) );
     164
     165        register_rest_route( $namespace, 'settings', array(
     166            'methods'  => WP_REST_Server::READABLE,
     167            'callback' => array( $this, 'settings' ),
     168        ) );
     169
     170        register_rest_route( $namespace, 'change-password', array(
     171            'methods'  => WP_REST_Server::CREATABLE,
     172            'callback' => array( $this, 'change_password' ),
     173        ) );
     174
     175        register_rest_route( $namespace, 'update-location', array(
     176            'methods'  => WP_REST_Server::CREATABLE,
     177            'callback' => array( $this, 'update_location' ),
     178        ) );
     179
     180        register_rest_route( $namespace, 'zones', array(
     181            'methods'  => WP_REST_Server::READABLE,
     182            'callback' => array( $this, 'zones' ),
     183        ) );
     184
     185        register_rest_route( $namespace, 'get-continent-code-for-country', array(
     186            'methods'  => WP_REST_Server::READABLE,
     187            'callback' => array( $this, 'get_continent_code_for_country' ),
     188        ) );
     189
     190        register_rest_route( $namespace, 'payment-stripe', array(
     191            'methods'  => WP_REST_Server::CREATABLE,
     192            'callback' => array( $this, 'payment_stripe' ),
     193        ) );
     194
     195        register_rest_route( $namespace, 'payment-hayperpay', array(
     196            'methods'  => WP_REST_Server::CREATABLE,
     197            'callback' => array( $this, 'payment_hayperpay' ),
     198        ) );
     199
     200        /**
     201         * Add payment router
    89202         *
    90          * An instance of this class should be passed to the run() function
    91          * defined in Mobile_Builder_Loader as all of the hooks are defined
    92          * in that particular class.
     203         * @author Ngoc Dang
     204         * @since 1.1.0
     205         */
     206        register_rest_route( $namespace, 'process_payment', array(
     207            'methods'  => WP_REST_Server::CREATABLE,
     208            'callback' => array( $this, 'rnlab_process_payment' ),
     209        ) );
     210
     211        register_rest_field( 'post', '_categories', array(
     212            'get_callback' => function ( $post ) {
     213                $cats = array();
     214                foreach ( $post['categories'] as $c ) {
     215                    $cat    = get_category( $c );
     216                    $cats[] = $cat->name;
     217                }
     218
     219                return $cats;
     220            },
     221        ) );
     222
     223        /**
     224         * register rest post field
    93225         *
    94          * The Mobile_Builder_Loader will then create the relationship
    95          * between the defined hooks and the functions defined in this
    96          * class.
     226         * @author Ngoc Dang
     227         * @since 1.1.0
    97228         */
    98 
    99         wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/mobile-builder-public.js', array( 'jquery' ), $this->version, false );
    100 
    101     }
    102 
     229        register_rest_field( 'post', 'rnlab_featured_media_url',
     230            array(
     231                'get_callback'    => array( $this, 'get_featured_media_url' ),
     232                'update_callback' => null,
     233                'schema'          => null,
     234            )
     235        );
     236
     237        /**
     238         * Check mobile phone number
     239         *
     240         * @author Ngoc Dang
     241         * @since 1.2.0
     242         */
     243        register_rest_route( $namespace, 'check-phone-number', array(
     244            'methods'  => WP_REST_Server::CREATABLE,
     245            'callback' => array( $this, 'mbd_check_phone_number' ),
     246        ) );
     247
     248        /**
     249         * Check email and username
     250         *
     251         * @author Ngoc Dang
     252         * @since 1.2.0
     253         */
     254        register_rest_route( $namespace, 'check-info', array(
     255            'methods'  => WP_REST_Server::CREATABLE,
     256            'callback' => array( $this, 'mbd_validate_user_info' ),
     257        ) );
     258
     259        /**
     260         * Get recursion category
     261         *
     262         * @author Ngoc Dang
     263         * @since 1.3.4
     264         */
     265        register_rest_route( $namespace, 'categories', array(
     266            'methods'  => WP_REST_Server::READABLE,
     267            'callback' => array( $this, 'categories' ),
     268        ) );
     269
     270    }
     271
     272    /**
     273     * Check mobile phone number
     274     *
     275     * @author Ngoc Dang
     276     * @since 1.2.0
     277     */
     278    public function mbd_check_phone_number( $request ) {
     279        $digits_phone = $request->get_param( 'digits_phone' );
     280        $type         = $request->get_param( 'type' );
     281
     282        $users = get_users( array(
     283            "meta_key"     => "digits_phone",
     284            "meta_value"   => $digits_phone,
     285            "meta_compare" => "="
     286        ) );
     287
     288        if ( $type == "register" ) {
     289            if ( count( $users ) > 0 ) {
     290                $error = new WP_Error();
     291                $error->add( 403, "Your phone number already exist in database!", array( 'status' => 400 ) );
     292
     293                return $error;
     294            }
     295
     296            return new WP_REST_Response( array( "data" => "Phone number not exits!" ), 200 );
     297        }
     298
     299        // Login folow
     300        if ( count( $users ) == 0 ) {
     301            $error = new WP_Error();
     302            $error->add( 403, "Your phone number not exist in database!", array( 'status' => 400 ) );
     303
     304            return $error;
     305        }
     306
     307        return new WP_REST_Response( array( "data" => "Phone number number exist!" ), 200 );
     308    }
     309
     310    /**
     311     * Change the way encode token
     312     *
     313     * @author Ngoc Dang
     314     * @since 1.3.4
     315     */
     316    public function custom_digits_rest_token_data( $token, $user_id ) {
     317        $user = get_user_by( 'id', $user_id );
     318        if ( $user ) {
     319            $token = $this->generate_token( $user );
     320            $data  = array(
     321                'token' => $token,
     322                'user'  => $this->mbd_get_userdata( $user ),
     323            );
     324            wp_send_json_success( $data );
     325        } else {
     326            wp_send_json_error( new WP_Error(
     327                404,
     328                'Something wrong!.',
     329                array(
     330                    'status' => 403,
     331                )
     332            ) );
     333        }
     334    }
     335
     336    /**
     337     * Change checkout template
     338     *
     339     * @author Ngoc Dang
     340     * @since 1.2.0
     341     */
     342    public function woocommerce_locate_template( $template, $template_name, $template_path ) {
     343        if ( 'checkout/form-checkout.php' == $template_name && isset( $_GET['mobile'] ) ) {
     344            return plugin_dir_path( __DIR__ ) . 'templates/checkout/form-checkout.php';
     345        }
     346
     347        if ( 'checkout/thankyou.php' == $template_name && isset( $_GET['mobile'] ) ) {
     348            return plugin_dir_path( __DIR__ ) . 'templates/checkout/thankyou.php';
     349        }
     350
     351        if ( 'checkout/form-pay.php' == $template_name && isset( $_GET['mobile'] ) ) {
     352            return plugin_dir_path( __DIR__ ) . 'templates/checkout/form-pay.php';
     353        }
     354
     355        return $template;
     356    }
     357
     358    /**
     359     * Add product to cart before redirect to checkout page
     360     *
     361     * @author Ngoc Dang
     362     * @since 1.2.0
     363     */
     364    public function template_redirect() {
     365
     366        if ( isset( $_GET['mobile'] ) && isset( $_GET['line_items'] ) ) {
     367
     368            if ( is_user_logged_in() && isset( $_GET['token'] ) ) {
     369
     370                $decode = $this->decode( $_GET['token'] );
     371
     372                if ( ! is_wp_error( $decode ) && get_current_user_id() != $decode->data->user_id ) {
     373
     374                    $user_id = $decode->data->user_id;
     375
     376                    wp_set_current_user( 0 );
     377
     378                    $user = get_user_by( 'id', $user_id );
     379                    wp_set_current_user( $user_id, $user->user_login );
     380                    wp_set_auth_cookie( $user_id );
     381
     382                    header( "Refresh:0" );
     383                }
     384
     385            } else if ( is_user_logged_in() && ! isset( $_GET['token'] ) ) {
     386
     387                wp_logout();
     388                wp_set_current_user( 0 );
     389                header( "Refresh:0" );
     390
     391            } else if ( ! is_user_logged_in() && isset( $_GET['token'] ) ) {
     392
     393                $decode = $this->decode( $_GET['token'] );
     394
     395                if ( ! is_wp_error( $decode ) ) {
     396                    $user_id = $decode->data->user_id;
     397                    $user    = get_user_by( 'id', $user_id );
     398                    wp_set_current_user( $user_id, $user->user_login );
     399                    wp_set_auth_cookie( $user_id );
     400
     401                    header( "Refresh:0" );
     402                }
     403            }
     404
     405            $line_items = json_decode( html_entity_decode( stripslashes( $_GET['line_items'] ) ), true );
     406
     407            WC()->session->set( 'refresh_totals', true );
     408            WC()->cart->empty_cart();
     409
     410            foreach ( $line_items as $item ) {
     411                WC()->cart->add_to_cart( $item['product_id'], $item['quantity'], $item['variation_id'] );
     412            }
     413        }
     414    }
     415
     416    /**
     417     * Find the selected Gateway, and process payment
     418     *
     419     * @author Ngoc Dang
     420     * @since 1.1.0
     421     */
     422    public function rnlab_process_payment( $request = null ) {
     423
     424        // Create a Response Object
     425        $response = array();
     426
     427        // Get parameters
     428        $order_id       = $request->get_param( 'order_id' );
     429        $payment_method = $request->get_param( 'payment_method' );
     430
     431        $error = new WP_Error();
     432
     433        // Perform Pre Checks
     434        if ( ! class_exists( 'WooCommerce' ) ) {
     435            $error->add( 400, __( "Failed to process payment. WooCommerce either missing or deactivated.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     436
     437            return $error;
     438        }
     439        if ( empty( $order_id ) ) {
     440            $error->add( 401, __( "Order ID 'order_id' is required.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     441
     442            return $error;
     443        } else if ( wc_get_order( $order_id ) == false ) {
     444            $error->add( 402, __( "Order ID 'order_id' is invalid. Order does not exist.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     445
     446            return $error;
     447        } else if ( wc_get_order( $order_id )->get_status() !== 'pending' && wc_get_order( $order_id )->get_status() !== 'failed' ) {
     448            $error->add( 403, __( "Order status is '" . wc_get_order( $order_id )->get_status() . "', meaning it had already received a successful payment. Duplicate payments to the order is not allowed. The allow status it is either 'pending' or 'failed'. ", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     449
     450            return $error;
     451        }
     452        if ( empty( $payment_method ) ) {
     453            $error->add( 404, __( "Payment Method 'payment_method' is required.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     454
     455            return $error;
     456        }
     457
     458        // Find Gateway
     459        $avaiable_gateways = WC()->payment_gateways->get_available_payment_gateways();
     460        $gateway           = $avaiable_gateways[ $payment_method ];
     461
     462        if ( empty( $gateway ) ) {
     463            $all_gateways = WC()->payment_gateways->payment_gateways();
     464            $gateway      = $all_gateways[ $payment_method ];
     465
     466            if ( empty( $gateway ) ) {
     467                $error->add( 405, __( "Failed to process payment. WooCommerce Gateway '" . $payment_method . "' is missing.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     468
     469                return $error;
     470            } else {
     471                $error->add( 406, __( "Failed to process payment. WooCommerce Gateway '" . $payment_method . "' exists, but is not available.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     472
     473                return $error;
     474            }
     475        } else if ( ! has_filter( 'rnlab_pre_process_' . $payment_method . '_payment' ) ) {
     476            $error->add( 407, __( "Failed to process payment. WooCommerce Gateway '" . $payment_method . "' exists, but 'REST Payment - " . $payment_method . "' is not available.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     477
     478            return $error;
     479        } else {
     480
     481            // Pre Process Payment
     482            $parameters = apply_filters( 'rnlab_pre_process_' . $payment_method . '_payment', array(
     483                "order_id"       => $order_id,
     484                "payment_method" => $payment_method
     485            ) );
     486
     487            if ( $parameters['pre_process_result'] === true ) {
     488
     489                // Process Payment
     490                $payment_result = $gateway->process_payment( $order_id );
     491                if ( $payment_result['result'] === "success" ) {
     492                    $response['code']    = 200;
     493                    $response['message'] = __( "Payment Successful.", "rnlab-rest-payment" );
     494                    $response['data']    = $payment_result;
     495
     496                    // Return Successful Response
     497                    return new WP_REST_Response( $response, 200 );
     498                } else {
     499                    return new WP_Error( 500, 'Payment Failed, Check WooCommerce Status Log for further information.', $payment_result );
     500                }
     501            } else {
     502                return new WP_Error( 408, 'Payment Failed, Pre Process Failed.', $parameters['pre_process_result'] );
     503            }
     504
     505        }
     506
     507    }
     508
     509    /**
     510     * Registers a REST API route
     511     *
     512     * @since 1.0.5
     513     */
     514    public function payment_hayperpay( $request ) {
     515        $response = array();
     516
     517        $order_id             = $request->get_param( 'order_id' );
     518        $wc_gate2play_gateway = new WC_gate2play_Gateway();
     519        $payment_result       = $wc_gate2play_gateway->process_payment( $order_id );
     520
     521        if ( $payment_result['result'] === "success" ) {
     522            $response['code']     = 200;
     523            $response['message']  = __( "Your Payment was Successful", "rnlab-rest-payment" );
     524            $response['redirect'] = $payment_result['redirect'];
     525        } else {
     526            $response['code']    = 401;
     527            $response['message'] = __( "Please enter valid card details", "rnlab-rest-payment" );
     528        }
     529
     530        return new WP_REST_Response( $response );
     531    }
     532
     533    public function payment_stripe( $request ) {
     534        $response = array();
     535
     536        $order_id      = $request->get_param( 'order_id' );
     537        $stripe_source = $request->get_param( 'stripe_source' );
     538
     539        $error = new WP_Error();
     540
     541        if ( empty( $order_id ) ) {
     542            $error->add( 401, __( "Order ID 'order_id' is required.", 'rnlab-rest-payment' ), array( 'status' => 400 ) );
     543
     544            return $error;
     545        } else if ( wc_get_order( $order_id ) == false ) {
     546            $error->add( 402, __( "Order ID 'order_id' is invalid. Order does not exist.", 'rnlab-rest-payment' ),
     547                array( 'status' => 400 ) );
     548
     549            return $error;
     550        }
     551
     552        if ( empty( $stripe_source ) ) {
     553            $error->add( 404, __( "Payment source 'stripe_source' is required.", 'rnlab-rest-payment' ),
     554                array( 'status' => 400 ) );
     555
     556            return $error;
     557        }
     558
     559        $wc_gateway_stripe = new WC_Gateway_Stripe();
     560
     561        $_POST['stripe_source']  = $stripe_source;
     562        $_POST['payment_method'] = "stripe";
     563
     564        // Fix empty cart in process_payment
     565        WC()->session = new WC_Session_Handler();
     566        WC()->session->init();
     567        WC()->customer = new WC_Customer( get_current_user_id(), true );
     568        WC()->cart     = new WC_Cart();
     569
     570        $payment_result = $wc_gateway_stripe->process_payment( $order_id );
     571
     572        if ( $payment_result['result'] === "success" ) {
     573            $response['code']    = 200;
     574            $response['message'] = __( "Your Payment was Successful", "rnlab-rest-payment" );
     575
     576            // $order = wc_get_order( $order_id );
     577
     578            // set order to completed
     579            // if ( $order->get_status() == 'processing' ) {
     580            //  $order->update_status( 'completed' );
     581            // }
     582
     583        } else {
     584            $response['code']    = 401;
     585            $response['message'] = __( "Please enter valid card details", "rnlab-rest-payment" );
     586        }
     587
     588        return new WP_REST_Response( $response );
     589    }
     590
     591    public function get_continent_code_for_country( $request ) {
     592        $cc         = $request->get_param( 'cc' );
     593        $wc_country = new WC_Countries();
     594
     595        wp_send_json( $wc_country->get_continent_code_for_country( $cc ) );
     596    }
     597
     598    public function zones() {
     599        $delivery_zones = (array) WC_Shipping_Zones::get_zones();
     600
     601        $data = [];
     602        foreach ( $delivery_zones as $key => $the_zone ) {
     603
     604            $shipping_methods = [];
     605
     606            foreach ( $the_zone['shipping_methods'] as $value ) {
     607
     608                $shipping_methods[] = array(
     609                    'instance_id'        => $value->instance_id,
     610                    'id'                 => $value->instance_id,
     611                    'method_id'          => $value->id,
     612                    'method_title'       => $value->title,
     613                    'method_description' => $value->method_description,
     614                    'settings'           => array(
     615                        'cost' => array(
     616                            'value' => $value->cost
     617                        )
     618                    ),
     619                );
     620            }
     621
     622            $data[] = array(
     623                'id'               => $the_zone['id'],
     624                'zone_name'        => $the_zone['zone_name'],
     625                'zone_locations'   => $the_zone['zone_locations'],
     626                'shipping_methods' => $shipping_methods,
     627            );
     628
     629        }
     630
     631        wp_send_json( $data );
     632    }
     633
     634    public function change_password( $request ) {
     635
     636        $current_user = wp_get_current_user();
     637        if ( ! $current_user->exists() ) {
     638            return new WP_Error(
     639                'user_not_login',
     640                'Please login first.',
     641                array(
     642                    'status' => 403,
     643                )
     644            );
     645        }
     646
     647        $username     = $current_user->user_login;
     648        $password_old = $request->get_param( 'password_old' );
     649        $password_new = $request->get_param( 'password_new' );
     650
     651        // try login with username and password
     652        $user = wp_authenticate( $username, $password_old );
     653
     654        if ( is_wp_error( $user ) ) {
     655            $error_code = $user->get_error_code();
     656
     657            return new WP_Error(
     658                $error_code,
     659                $user->get_error_message( $error_code ),
     660                array(
     661                    'status' => 403,
     662                )
     663            );
     664        }
     665
     666        wp_set_password( $password_new, $current_user->ID );
     667
     668        return $current_user->ID;
     669    }
     670
     671    /**
     672     *
     673     * Update User Location
     674     *
     675     * @param $request
     676     *
     677     * @return int|WP_Error
     678     * @since 1.4.3
     679     *
     680     */
     681    public function update_location( $request ) {
     682
     683        $current_user = wp_get_current_user();
     684
     685        if ( ! $current_user->exists() ) {
     686            return new WP_Error(
     687                'user_not_login',
     688                'Please login first.',
     689                array(
     690                    'status' => 403,
     691                )
     692            );
     693        }
     694
     695        $location = $request->get_param( 'location' );
     696
     697        update_user_meta( $current_user->ID, 'mbd_location', $location );
     698
     699        return $current_user->ID;
     700    }
     701
     702
     703    public function settings( $request ) {
     704
     705        $decode = $request->get_param( 'decode' );
     706
     707        $result = wp_cache_get( 'settings_' . $decode, 'rnlab' );
     708
     709        if ( $result ) {
     710            return $result;
     711        }
     712
     713        try {
     714            global $woocommerce_wpml;
     715
     716            $admin = new Mobile_Builder_Admin( MOBILE_BUILDER_PLUGIN_NAME, MOBILE_BUILDER_CONTROL_VERSION );
     717
     718            $currencies = array();
     719
     720            $languages    = apply_filters( 'wpml_active_languages', array(), 'orderby=id&order=desc' );
     721            $default_lang = apply_filters( 'wpml_default_language', substr( get_locale(), 0, 2 ) );
     722
     723            $currency = function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD';
     724
     725            if ( ! empty( $woocommerce_wpml->multi_currency ) && ! empty( $woocommerce_wpml->settings['currencies_order'] ) ) {
     726                $currencies = $woocommerce_wpml->multi_currency->get_currencies( 'include_default = true' );
     727            }
     728
     729            $configs = get_option( 'mobile_builder_configs', array(
     730                "requireLogin"       => false,
     731                "toggleSidebar"      => false,
     732                "isBeforeNewProduct" => 5
     733            ) );
     734
     735            $templates      = array();
     736            $templates_data = $admin->template_configs();
     737
     738            if ( $decode ) {
     739                foreach ( $templates_data as $template ) {
     740                    $template->data     = json_decode( $template->data );
     741                    $template->settings = json_decode( $template->settings );
     742                    $templates[]        = $template;
     743                }
     744            }
     745
     746            $result = array(
     747                'language'              => $default_lang,
     748                'languages'             => $languages,
     749                'currencies'            => $currencies,
     750                'currency'              => $currency,
     751                'enable_guest_checkout' => get_option( 'woocommerce_enable_guest_checkout', true ),
     752                'timezone_string'       => get_option( 'timezone_string' ) ? get_option( 'timezone_string' ) : wc_timezone_string(),
     753                'date_format'           => get_option( 'date_format' ),
     754                'time_format'           => get_option( 'time_format' ),
     755                'configs'               => maybe_unserialize( $configs ),
     756                'templates'             => $decode ? $templates : $templates_data,
     757            );
     758
     759            wp_cache_set( 'settings_' . $decode, $result, 'rnlab' );
     760
     761            wp_send_json( $result );
     762        } catch ( Exception $e ) {
     763            return new WP_Error(
     764                'error_setting',
     765                'Some thing wrong.',
     766                array(
     767                    'status' => 403,
     768                )
     769            );
     770        }
     771    }
     772
     773    /**
     774     * Create token for app
     775     *
     776     * @param $request
     777     *
     778     * @return bool|WP_Error
     779     */
     780    public function app_token() {
     781
     782        $wp_auth_user = defined( 'WP_AUTH_USER' ) ? WP_AUTH_USER : "wp_auth_user";
     783
     784        $user = get_user_by( 'login', $wp_auth_user );
     785
     786        if ( $user ) {
     787            $token = $this->generate_token( $user, array( 'read_only' => true ) );
     788
     789            return $token;
     790        } else {
     791            return new WP_Error(
     792                'create_token_error',
     793                'You did not create user wp_auth_user',
     794                array(
     795                    'status' => 403,
     796                )
     797            );
     798        }
     799    }
     800
     801    /**
     802     * Lost password for user
     803     *
     804     * @param $request
     805     *
     806     * @return bool|WP_Error
     807     */
     808    public function retrieve_password( $request ) {
     809        $errors = new WP_Error();
     810
     811        $user_login = $request->get_param( 'user_login' );
     812
     813        if ( empty( $user_login ) || ! is_string( $user_login ) ) {
     814            $errors->add( 'empty_username', __( '<strong>ERROR</strong>: Enter a username or email address.' ) );
     815        } elseif ( strpos( $user_login, '@' ) ) {
     816            $user_data = get_user_by( 'email', trim( wp_unslash( $user_login ) ) );
     817            if ( empty( $user_data ) ) {
     818                $errors->add( 'invalid_email',
     819                    __( '<strong>ERROR</strong>: There is no account with that username or email address.' ) );
     820            }
     821        } else {
     822            $login     = trim( $user_login );
     823            $user_data = get_user_by( 'login', $login );
     824        }
     825
     826        if ( $errors->has_errors() ) {
     827            return $errors;
     828        }
     829
     830        if ( ! $user_data ) {
     831            $errors->add( 'invalidcombo',
     832                __( '<strong>ERROR</strong>: There is no account with that username or email address.' ) );
     833
     834            return $errors;
     835        }
     836
     837        // Redefining user_login ensures we return the right case in the email.
     838        $user_login = $user_data->user_login;
     839        $user_email = $user_data->user_email;
     840        $key        = get_password_reset_key( $user_data );
     841
     842        if ( is_wp_error( $key ) ) {
     843            return $key;
     844        }
     845
     846        if ( is_multisite() ) {
     847            $site_name = get_network()->site_name;
     848        } else {
     849            /*
     850             * The blogname option is escaped with esc_html on the way into the database
     851             * in sanitize_option we want to reverse this for the plain text arena of emails.
     852             */
     853            $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
     854        }
     855
     856        $message = __( 'Someone has requested a password reset for the following account:' ) . "\r\n\r\n";
     857        /* translators: %s: site name */
     858        $message .= sprintf( __( 'Site Name: %s' ), $site_name ) . "\r\n\r\n";
     859        /* translators: %s: user login */
     860        $message .= sprintf( __( 'Username: %s' ), $user_login ) . "\r\n\r\n";
     861        $message .= __( 'If this was a mistake, just ignore this email and nothing will happen.' ) . "\r\n\r\n";
     862        $message .= __( 'To reset your password, visit the following address:' ) . "\r\n\r\n";
     863        $message .= '<' . network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user_login ),
     864                'login' ) . ">\r\n";
     865
     866        /* translators: Password reset notification email subject. %s: Site title */
     867        $title = sprintf( __( '[%s] Password Reset' ), $site_name );
     868
     869        /**
     870         * Filters the subject of the password reset email.
     871         *
     872         * @param string $title Default email title.
     873         * @param string $user_login The username for the user.
     874         * @param WP_User $user_data WP_User object.
     875         *
     876         * @since 4.4.0 Added the `$user_login` and `$user_data` parameters.
     877         *
     878         * @since 2.8.0
     879         */
     880        $title = apply_filters( 'retrieve_password_title', $title, $user_login, $user_data );
     881
     882        /**
     883         * Filters the message body of the password reset mail.
     884         *
     885         * If the filtered message is empty, the password reset email will not be sent.
     886         *
     887         * @param string $message Default mail message.
     888         * @param string $key The activation key.
     889         * @param string $user_login The username for the user.
     890         * @param WP_User $user_data WP_User object.
     891         *
     892         * @since 2.8.0
     893         * @since 4.1.0 Added `$user_login` and `$user_data` parameters.
     894         *
     895         */
     896        $message = apply_filters( 'retrieve_password_message', $message, $key, $user_login, $user_data );
     897
     898        if ( $message && ! wp_mail( $user_email, wp_specialchars_decode( $title ), $message ) ) {
     899            return new WP_Error(
     900                'send_email',
     901                'Possible reason: your host may have disabled the mail() function.',
     902                array(
     903                    'status' => 403,
     904                )
     905            );
     906        }
     907
     908        return true;
     909    }
     910
     911    /**
     912     *  Get current user login
     913     *
     914     * @param $request
     915     *
     916     * @return mixed
     917     */
     918    public function current( $request ) {
     919        $current_user = wp_get_current_user();
     920
     921        return $current_user->data;
     922    }
     923
     924    /**
     925     *  Validate user
     926     *
     927     * @param $request
     928     *
     929     * @return mixed
     930     */
     931    public function mbd_validate_user_info( $request ) {
     932
     933        $email = $request->get_param( 'email' );
     934        $name  = $request->get_param( 'name' );
     935
     936        // Validate email
     937        if ( ! is_email( $email ) || email_exists( $email ) ) {
     938            return new WP_Error(
     939                "email",
     940                "Your input email not valid or exist in database.",
     941                array(
     942                    'status' => 403,
     943                )
     944            );
     945        }
     946
     947        // Validate username
     948        if ( username_exists( $name ) || empty( $name ) ) {
     949            return new WP_Error(
     950                "name",
     951                "Your username exist.",
     952                array(
     953                    'status' => 403,
     954                )
     955            );
     956        }
     957
     958        return array( "message" => "success!" );
     959    }
     960
     961    /**
     962     *  Register new user
     963     *
     964     * @param $request
     965     *
     966     * @return mixed
     967     */
     968    public function register( $request ) {
     969        $email      = $request->get_param( 'email' );
     970        $name       = $request->get_param( 'name' );
     971        $first_name = $request->get_param( 'first_name' );
     972        $last_name  = $request->get_param( 'last_name' );
     973        $password   = $request->get_param( 'password' );
     974        $subscribe  = $request->get_param( 'subscribe' );
     975
     976        $enable_phone_number = $request->get_param( 'enable_phone_number' );
     977
     978        // Validate email
     979        if ( ! is_email( $email ) || email_exists( $email ) ) {
     980            return new WP_Error(
     981                "email",
     982                "Your input email not valid or exist in database.",
     983                array(
     984                    'status' => 403,
     985                )
     986            );
     987        }
     988
     989        // Validate username
     990        if ( username_exists( $name ) || empty( $name ) ) {
     991            return new WP_Error(
     992                "name",
     993                "Your username exist.",
     994                array(
     995                    'status' => 403,
     996                )
     997            );
     998        }
     999
     1000        // Validate first name
     1001        if ( mb_strlen( $first_name ) < 2 ) {
     1002            return new WP_Error(
     1003                "first_name",
     1004                "First name not valid.",
     1005                array(
     1006                    'status' => 403,
     1007                )
     1008            );
     1009        }
     1010
     1011        // Validate last name
     1012        if ( mb_strlen( $last_name ) < 2 ) {
     1013            return new WP_Error(
     1014                "last_name",
     1015                "Last name not valid.",
     1016                array(
     1017                    'status' => 403,
     1018                )
     1019            );
     1020        }
     1021
     1022        // Validate password
     1023        if ( empty( $password ) ) {
     1024            return new WP_Error(
     1025                "password",
     1026                "Password is required.",
     1027                array(
     1028                    'status' => 403,
     1029                )
     1030            );
     1031        }
     1032
     1033        $user_id = wp_insert_user( array(
     1034            "user_pass"    => $password,
     1035            "user_email"   => $email,
     1036            "user_login"   => $name,
     1037            "display_name" => "$first_name $last_name",
     1038            "first_name"   => $first_name,
     1039            "last_name"    => $last_name
     1040
     1041        ) );
     1042
     1043        if ( is_wp_error( $user_id ) ) {
     1044            $error_code = $user_id->get_error_code();
     1045
     1046            return new WP_Error(
     1047                $error_code,
     1048                $user_id->get_error_message( $error_code ),
     1049                array(
     1050                    'status' => 403,
     1051                )
     1052            );
     1053        }
     1054
     1055        // Update phone number
     1056        if ( $enable_phone_number ) {
     1057            $digits_phone     = $request->get_param( 'digits_phone' );
     1058            $digt_countrycode = $request->get_param( 'digt_countrycode' );
     1059            $digits_phone_no  = $request->get_param( 'digits_phone_no' );
     1060
     1061            // Validate phone
     1062            if ( ! $digits_phone || ! $digt_countrycode || ! $digits_phone_no ) {
     1063                wp_delete_user( $user_id );
     1064
     1065                return new WP_Error(
     1066                    'number_not_validate',
     1067                    'Your phone number not validate',
     1068                    array(
     1069                        'status' => 403,
     1070                    )
     1071                );
     1072            }
     1073
     1074            // Check phone number in database
     1075            $users = get_users( array(
     1076                "meta_key"     => "digits_phone",
     1077                "meta_value"   => $digits_phone,
     1078                "meta_compare" => "="
     1079            ) );
     1080
     1081            if ( count( $users ) > 0 ) {
     1082                wp_delete_user( $user_id );
     1083
     1084                return new WP_Error(
     1085                    'phone_number_exist',
     1086                    "Your phone number already exist in database!",
     1087                    array( 'status' => 400 )
     1088                );
     1089            }
     1090
     1091            add_user_meta( $user_id, 'digits_phone', $digits_phone, true );
     1092            add_user_meta( $user_id, 'digt_countrycode', $digits_phone, true );
     1093            add_user_meta( $user_id, 'digits_phone_no', $digits_phone, true );
     1094
     1095        }
     1096
     1097        // Subscribe
     1098        add_user_meta( $user_id, 'mbd_subscribe', $subscribe, true );
     1099
     1100        $user  = get_user_by( 'id', $user_id );
     1101        $token = $this->generate_token( $user );
     1102        $data  = array(
     1103            'token' => $token,
     1104            'user'  => $this->mbd_get_userdata( $user ),
     1105        );
     1106
     1107        return $data;
     1108
     1109    }
     1110
     1111    public function getUrlContent( $url ) {
     1112        $parts  = parse_url( $url );
     1113        $host   = $parts['host'];
     1114        $ch     = curl_init();
     1115        $header = array(
     1116            'GET /1575051 HTTP/1.1',
     1117            "Host: {$host}",
     1118            'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
     1119            'Accept-Language:en-US,en;q=0.8',
     1120            'Cache-Control:max-age=0',
     1121            'Connection:keep-alive',
     1122            'Host:adfoc.us',
     1123            'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
     1124        );
     1125
     1126        curl_setopt( $ch, CURLOPT_URL, $url );
     1127        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
     1128        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 0 );
     1129        curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
     1130        $result = curl_exec( $ch );
     1131        curl_close( $ch );
     1132
     1133        return $result;
     1134    }
     1135
     1136    /**
     1137     * Login with google
     1138     *
     1139     * @param $request
     1140     */
     1141    public function login_google( $request ) {
     1142        $idToken = $request->get_param( 'idToken' );
     1143
     1144        $url  = 'https://oauth2.googleapis.com/tokeninfo?id_token=' . $idToken;
     1145        $data = array( 'idToken' => $idToken );
     1146
     1147        // use key 'http' even if you send the request to https://...
     1148        $options = array(
     1149            'http' => array(
     1150                'header' => "application/json; charset=UTF-8\r\n",
     1151                'method' => 'GET'
     1152            )
     1153        );
     1154
     1155        $context = stream_context_create( $options );
     1156        $json    = $this->getUrlContent( $url );
     1157        $result  = json_decode( $json );
     1158
     1159        if ( $result === false ) {
     1160            $error = new WP_Error();
     1161            $error->add( 403, "Get Firebase user info error!", array( 'status' => 400 ) );
     1162
     1163            return $error;
     1164        }
     1165
     1166        // Email not exist
     1167        $email = $result->email;
     1168        if ( ! $email ) {
     1169            return new WP_Error(
     1170                'email_not_exist',
     1171                'User not provider email',
     1172                array(
     1173                    'status' => 403,
     1174                )
     1175            );
     1176        }
     1177
     1178        $user = get_user_by( 'email', $email );
     1179
     1180        // Return data if user exist in database
     1181        if ( $user ) {
     1182            $token = $this->generate_token( $user );
     1183            $data  = array(
     1184                'token' => $token,
     1185                'user'  => $this->mbd_get_userdata( $user ),
     1186            );
     1187
     1188            return $data;
     1189        } else {
     1190
     1191            $user_id = wp_insert_user( array(
     1192                "user_pass"     => wp_generate_password(),
     1193                "user_login"    => $result->email,
     1194                "user_nicename" => $result->name,
     1195                "user_email"    => $result->email,
     1196                "display_name"  => $result->name,
     1197                "first_name"    => $result->given_name,
     1198                "last_name"     => $result->family_name
     1199
     1200            ) );
     1201
     1202            if ( is_wp_error( $user_id ) ) {
     1203                $error_code = $user->get_error_code();
     1204
     1205                return new WP_Error(
     1206                    $error_code,
     1207                    $user_id->get_error_message( $error_code ),
     1208                    array(
     1209                        'status' => 403,
     1210                    )
     1211                );
     1212            }
     1213
     1214            $user = get_user_by( 'id', $user_id );
     1215
     1216            $token = $this->generate_token( $user );
     1217            $data  = array(
     1218                'token' => $token,
     1219                'user'  => $this->mbd_get_userdata( $user ),
     1220            );
     1221
     1222            add_user_meta( $user_id, 'mbd_login_method', 'google', true );
     1223            add_user_meta( $user_id, 'mbd_avatar', $result->picture, true );
     1224
     1225            return $data;
     1226        }
     1227    }
     1228
     1229    /**
     1230     * Login With Apple
     1231     *
     1232     * @param $request
     1233     *
     1234     * @return array | object
     1235     * @throws Exception
     1236     */
     1237    public function login_apple( $request ) {
     1238        try {
     1239            $identityToken = $request->get_param( 'identityToken' );
     1240            $userIdentity  = $request->get_param( 'user' );
     1241            $fullName      = $request->get_param( 'fullName' );
     1242
     1243            $tks = \explode( '.', $identityToken );
     1244            if ( \count( $tks ) != 3 ) {
     1245                return new WP_Error(
     1246                    'error_login_apple',
     1247                    'Wrong number of segments',
     1248                    array(
     1249                        'status' => 403,
     1250                    )
     1251                );
     1252            }
     1253
     1254            list( $headb64 ) = $tks;
     1255
     1256            if ( null === ( $header = JWT::jsonDecode( JWT::urlsafeB64Decode( $headb64 ) ) ) ) {
     1257                return new WP_Error(
     1258                    'error_login_apple',
     1259                    'Invalid header encoding',
     1260                    array(
     1261                        'status' => 403,
     1262                    )
     1263                );
     1264            }
     1265
     1266            if ( ! isset( $header->kid ) ) {
     1267                return new WP_Error(
     1268                    'error_login_apple',
     1269                    '"kid" empty, unable to lookup correct key',
     1270                    array(
     1271                        'status' => 403,
     1272                    )
     1273                );
     1274            }
     1275
     1276            $publicKeyDetails = Mobile_Builder_Public_Key::getPublicKey( $header->kid );
     1277            $publicKey        = $publicKeyDetails['publicKey'];
     1278            $alg              = $publicKeyDetails['alg'];
     1279
     1280            $payload = JWT::decode( $identityToken, $publicKey, [ $alg ] );
     1281
     1282            if ( $payload->sub !== $userIdentity ) {
     1283                return new WP_Error(
     1284                    'validate-user',
     1285                    'User not validate',
     1286                    array(
     1287                        'status' => 403,
     1288                    )
     1289                );
     1290            }
     1291
     1292            $user1 = get_user_by( 'email', $payload->email );
     1293            $user2 = get_user_by( 'login', $userIdentity );
     1294
     1295            // Return data if user exist in database
     1296            if ( $user1 ) {
     1297                $token = $this->generate_token( $user1 );
     1298
     1299                return array(
     1300                    'token' => $token,
     1301                    'user'  => $this->mbd_get_userdata( $user1 ),
     1302                );
     1303            }
     1304
     1305            if ( $user2 ) {
     1306                $token = $this->generate_token( $user2 );
     1307
     1308                return array(
     1309                    'token' => $token,
     1310                    'user'  => $this->mbd_get_userdata( $user2 ),
     1311                );
     1312            }
     1313
     1314            $userdata = array(
     1315                "user_pass"    => wp_generate_password(),
     1316                "user_login"   => $userIdentity,
     1317                "user_email"   => $payload->email,
     1318                "display_name" => $fullName['familyName'] . " " . $fullName['givenName'],
     1319                "first_name"   => $fullName['familyName'],
     1320                "last_name"    => $fullName['givenName']
     1321            );
     1322
     1323            $user_id = wp_insert_user( $userdata );
     1324
     1325            if ( is_wp_error( $user_id ) ) {
     1326                $error_code = $user_id->get_error_code();
     1327
     1328                return new WP_Error(
     1329                    $error_code,
     1330                    $user_id->get_error_message( $error_code ),
     1331                    array(
     1332                        'status' => 403,
     1333                    )
     1334                );
     1335            }
     1336
     1337            $user = get_user_by( 'id', $user_id );
     1338
     1339            $token = $this->generate_token( $user );
     1340
     1341            add_user_meta( $user_id, 'mbd_login_method', 'apple', true );
     1342
     1343            return array(
     1344                'token' => $token,
     1345                'user'  => $this->mbd_get_userdata( $user ),
     1346            );
     1347
     1348        } catch ( Exception $e ) {
     1349            return new WP_Error(
     1350                'error_login_apple',
     1351                $e->getMessage(),
     1352                array(
     1353                    'status' => 403,
     1354                )
     1355            );
     1356        }
     1357    }
     1358
     1359    public function login_facebook( $request ) {
     1360        $token = $request->get_param( 'token' );
     1361
     1362        $fb = new \Facebook\Facebook( [
     1363            'app_id'                => FB_APP_ID,
     1364            'app_secret'            => FB_APP_SECRET,
     1365            'default_graph_version' => 'v2.10',
     1366            //'default_access_token' => '{access-token}', // optional
     1367        ] );
     1368
     1369        try {
     1370            // Get the \Facebook\GraphNodes\GraphUser object for the current user.
     1371            // If you provided a 'default_access_token', the '{access-token}' is optional.
     1372            $response = $fb->get( '/me?fields=id,first_name,last_name,name,picture,email', $token );
     1373        } catch ( \Facebook\Exceptions\FacebookResponseException $e ) {
     1374            // When Graph returns an error
     1375            echo 'Graph returned an error: ' . $e->getMessage();
     1376            exit;
     1377        } catch ( \Facebook\Exceptions\FacebookSDKException $e ) {
     1378            // When validation fails or other local issues
     1379            echo 'Facebook SDK returned an error: ' . $e->getMessage();
     1380            exit;
     1381        }
     1382
     1383        $me = $response->getGraphUser();
     1384
     1385        // Email not exist
     1386        $email = $me->getEmail();
     1387        if ( ! $email ) {
     1388            return new WP_Error(
     1389                'email_not_exist',
     1390                'User not provider email',
     1391                array(
     1392                    'status' => 403,
     1393                )
     1394            );
     1395        }
     1396
     1397        $user = get_user_by( 'email', $email );
     1398
     1399        // Return data if user exist in database
     1400        if ( $user ) {
     1401            $token = $this->generate_token( $user );
     1402            $data  = array(
     1403                'token' => $token,
     1404                'user'  => $this->mbd_get_userdata( $user ),
     1405            );
     1406
     1407            return $data;
     1408        } else {
     1409            // Will create new user
     1410            $first_name  = $me->getFirstName();
     1411            $last_name   = $me->getLastName();
     1412            $picture     = $me->getPicture();
     1413            $name        = $me->getName();
     1414            $facebook_id = $me->getId();
     1415
     1416            $user_id = wp_insert_user( array(
     1417                "user_pass"     => wp_generate_password(),
     1418                "user_login"    => $email,
     1419                "user_nicename" => $name,
     1420                "user_email"    => $email,
     1421                "display_name"  => $name,
     1422                "first_name"    => $first_name,
     1423                "last_name"     => $last_name
     1424
     1425            ) );
     1426
     1427            if ( is_wp_error( $user_id ) ) {
     1428                $error_code = $user->get_error_code();
     1429
     1430                return new WP_Error(
     1431                    $error_code,
     1432                    $user_id->get_error_message( $error_code ),
     1433                    array(
     1434                        'status' => 403,
     1435                    )
     1436                );
     1437            }
     1438
     1439            $user = get_user_by( 'id', $user_id );
     1440
     1441            $token = $this->generate_token( $user );
     1442            $data  = array(
     1443                'token' => $token,
     1444                'user'  => $this->mbd_get_userdata( $user ),
     1445            );
     1446
     1447            add_user_meta( $user_id, 'mbd_login_method', 'facebook', true );
     1448            add_user_meta( $user_id, 'mbd_avatar', $picture, true );
     1449
     1450            return $data;
     1451        }
     1452
     1453    }
     1454
     1455    /**
     1456     * Do login with email and password
     1457     */
     1458    public function login( $request ) {
     1459
     1460        $username = $request->get_param( 'username' );
     1461        $password = $request->get_param( 'password' );
     1462
     1463        // try login with username and password
     1464        $user = wp_authenticate( $username, $password );
     1465
     1466        if ( is_wp_error( $user ) ) {
     1467            return $user;
     1468        }
     1469
     1470        // Generate token
     1471        $token = $this->generate_token( $user );
     1472
     1473        // Return data
     1474        $data = array(
     1475            'token' => $token,
     1476            'user'  => $this->mbd_get_userdata( $user ),
     1477        );
     1478
     1479        return $data;
     1480    }
     1481
     1482    /**
     1483     * Do login with with otp
     1484     */
     1485    public function login_otp( $request ) {
     1486
     1487        try {
     1488
     1489            if ( ! defined( 'MBD_FIREBASE_SERVER_KEY' ) ) {
     1490                return new WP_Error(
     1491                    'not_exist_firebase_server_key',
     1492                    'The MBD_FIREBASE_SERVER_KEY not define in wp-config.php',
     1493                    array(
     1494                        'status' => 403,
     1495                    )
     1496                );
     1497            }
     1498
     1499            $idToken = $request->get_param( 'idToken' );
     1500
     1501            $url  = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=' . MBD_FIREBASE_SERVER_KEY;
     1502            $data = array( 'idToken' => $idToken );
     1503
     1504            // use key 'http' even if you send the request to https://...
     1505            $options = array(
     1506                'http' => array(
     1507                    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
     1508                    'method'  => 'POST',
     1509                    'content' => http_build_query( $data )
     1510                )
     1511            );
     1512
     1513            $context = stream_context_create( $options );
     1514            $json    = file_get_contents( $url, false, $context );
     1515            $result  = json_decode( $json );
     1516
     1517            if ( $result === false ) {
     1518                $error = new WP_Error();
     1519                $error->add( 403, "Get Firebase user info error!", array( 'status' => 400 ) );
     1520
     1521                return $error;
     1522            }
     1523
     1524            if ( ! isset( $result->users[0]->phoneNumber ) ) {
     1525                return new WP_Error(
     1526                    'not_exist_firebase_user',
     1527                    'The user not exist.',
     1528                    array(
     1529                        'status' => 403,
     1530                    )
     1531                );
     1532            }
     1533
     1534            $phone_number = $result->users[0]->phoneNumber;
     1535
     1536            $users = get_users( array(
     1537                "meta_key"     => "digits_phone",
     1538                "meta_value"   => $phone_number,
     1539                "meta_compare" => "="
     1540            ) );
     1541
     1542            if ( count( $users ) == 0 ) {
     1543                $error = new WP_Error();
     1544                $error->add( 403, "Did not find any members matching the phone number!", array( 'status' => 400 ) );
     1545
     1546                return $error;
     1547            }
     1548
     1549            $user = $users[0];
     1550
     1551            // Generate token
     1552            $token = $this->generate_token( $user );
     1553
     1554            // Return data
     1555            $data = array(
     1556                'token' => $token,
     1557                'user'  => $this->mbd_get_userdata( $user ),
     1558            );
     1559
     1560            return $data;
     1561
     1562        } catch ( Exception $err ) {
     1563            return $err;
     1564        }
     1565    }
     1566
     1567    /**
     1568     *  General token
     1569     *
     1570     * @param $user
     1571     *
     1572     * @return string
     1573     */
     1574    public function generate_token( $user, $data = array() ) {
     1575        $iat = time();
     1576        $nbf = $iat;
     1577        $exp = $iat + ( DAY_IN_SECONDS * 30 );
     1578
     1579        $token = array(
     1580            'iss'  => get_bloginfo( 'url' ),
     1581            'iat'  => $iat,
     1582            'nbf'  => $nbf,
     1583            'exp'  => $exp,
     1584            'data' => array_merge( array(
     1585                'user_id' => $user->data->ID
     1586            ), $data ),
     1587        );
     1588
     1589        // Generate token
     1590        return JWT::encode( $token, $this->key );
     1591    }
     1592
     1593    public function determine_current_user( $user ) {
     1594        // Run only on REST API
     1595        $rest_url_prefix = rest_get_url_prefix();
     1596
     1597        $valid_rest_url = strpos( $_SERVER['REQUEST_URI'], $rest_url_prefix );
     1598        if ( ! $valid_rest_url ) {
     1599            return $user;
     1600        }
     1601
     1602        $token = $this->decode();
     1603
     1604        if ( is_wp_error( $token ) ) {
     1605            return $user;
     1606        }
     1607
     1608        // only read data to
     1609        // if (isset($token->data->read_only) && $token->data->read_only && $_SERVER['REQUEST_METHOD'] != "GET") {
     1610        //     return $user;
     1611        // }
     1612
     1613        return $token->data->user_id;
     1614    }
     1615
     1616    /**
     1617     * Decode token
     1618     * @return array|WP_Error
     1619     */
     1620    public function decode( $token = null ) {
     1621        /*
     1622         * Get token on header
     1623         */
     1624
     1625        if ( ! $token ) {
     1626
     1627            $headers = $this->headers();
     1628
     1629            if ( ! isset( $headers['Authorization'] ) ) {
     1630                return new WP_Error(
     1631                    'no_auth_header',
     1632                    'Authorization header not found.',
     1633                    array(
     1634                        'status' => 403,
     1635                    )
     1636                );
     1637            }
     1638
     1639
     1640            $match = preg_match( '/Bearer\s(\S+)/', $headers['Authorization'], $matches );
     1641
     1642            if ( ! $match ) {
     1643                return new WP_Error(
     1644                    'token_not_validate',
     1645                    'Token not validate format.',
     1646                    array(
     1647                        'status' => 403,
     1648                    )
     1649                );
     1650            }
     1651
     1652            $token = $matches[1];
     1653
     1654        }
     1655
     1656        /** decode token */
     1657        try {
     1658            $data = JWT::decode( $token, $this->key, array( 'HS256' ) );
     1659
     1660            if ( $data->iss != get_bloginfo( 'url' ) ) {
     1661                return new WP_Error(
     1662                    'bad_iss',
     1663                    'The iss do not match with this server',
     1664                    array(
     1665                        'status' => 403,
     1666                    )
     1667                );
     1668            }
     1669            if ( ! isset( $data->data->user_id ) ) {
     1670                return new WP_Error(
     1671                    'id_not_found',
     1672                    'User ID not found in the token',
     1673                    array(
     1674                        'status' => 403,
     1675                    )
     1676                );
     1677            }
     1678
     1679            return $data;
     1680
     1681        } catch ( Exception $e ) {
     1682            return new WP_Error(
     1683                'invalid_token',
     1684                $e->getMessage(),
     1685                array(
     1686                    'status' => 403,
     1687                )
     1688            );
     1689        }
     1690    }
     1691
     1692    public function get_featured_media_url( $object, $field_name, $request ) {
     1693        $featured_media_url = '';
     1694        $image_attributes   = wp_get_attachment_image_src(
     1695            get_post_thumbnail_id( $object['id'] ),
     1696            'full'
     1697        );
     1698        if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) {
     1699            $featured_media_url = (string) $image_attributes[0];
     1700        }
     1701
     1702        return $featured_media_url;
     1703    }
     1704
     1705    /**
     1706     * Get request headers
     1707     * @return array|false
     1708     */
     1709    function headers() {
     1710        if ( function_exists( 'apache_request_headers' ) ) {
     1711            return apache_request_headers();
     1712        } else {
     1713
     1714            foreach ( $_SERVER as $key => $value ) {
     1715                if ( substr( $key, 0, 5 ) == "HTTP_" ) {
     1716                    $key         = str_replace( " ", "-",
     1717                        ucwords( strtolower( str_replace( "_", " ", substr( $key, 5 ) ) ) ) );
     1718                    $out[ $key ] = $value;
     1719                } else {
     1720                    $out[ $key ] = $value;
     1721                }
     1722            }
     1723
     1724            return $out;
     1725        }
     1726    }
     1727
     1728    /**
     1729     * Get categories by parent
     1730     *
     1731     * @param $request
     1732     *
     1733     * @return array
     1734     * @since 1.3.4
     1735     * @author ngocdt
     1736     */
     1737    function categories( $request ) {
     1738        $parent = $request->get_param( 'parent' );
     1739
     1740        $result = wp_cache_get( 'category_' . $parent, 'rnlab' );
     1741
     1742        if ( $result ) {
     1743            return $result;
     1744        }
     1745
     1746        $result = $this->get_category_by_parent_id( $parent );
     1747        wp_cache_set( 'category_' . $parent, $result, 'rnlab' );
     1748
     1749        return $result;
     1750    }
     1751
     1752    function get_category_by_parent_id( $parent ) {
     1753        $args = array(
     1754            'hierarchical'     => 1,
     1755            'show_option_none' => '',
     1756            'hide_empty'       => 0,
     1757            'parent'           => $parent,
     1758            'taxonomy'         => 'product_cat',
     1759        );
     1760
     1761        $categories = get_categories( $args );
     1762
     1763        if ( count( $categories ) ) {
     1764            $with_subs = [];
     1765            foreach ( $categories as $category ) {
     1766
     1767                $image = null;
     1768
     1769                // Get category image.
     1770                $image_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
     1771                if ( $image_id ) {
     1772                    $attachment = get_post( $image_id );
     1773
     1774                    $image = array(
     1775                        'id'   => (int) $image_id,
     1776                        'src'  => wp_get_attachment_url( $image_id ),
     1777                        'name' => get_the_title( $attachment ),
     1778                        'alt'  => get_post_meta( $image_id, '_wp_attachment_image_alt', true ),
     1779                    );
     1780                }
     1781
     1782                $with_subs[] = array(
     1783                    'id'         => (int) $category->term_id,
     1784                    'name'       => $category->name,
     1785                    'parent'     => $category->parent,
     1786                    'categories' => $this->get_category_by_parent_id( (int) $category->term_id ),
     1787                    'image'      => $image,
     1788                    'count'      => (int) $category->count
     1789                );
     1790            }
     1791
     1792            return $with_subs;
     1793
     1794        } else {
     1795            return [];
     1796        }
     1797    }
     1798
     1799    /**
     1800     * Check if a given request has access to read a customer.
     1801     *
     1802     * @param WP_REST_Request $request Full details about the request.
     1803     *
     1804     * @return WP_Error|boolean
     1805     *
     1806     * @since 1.3.4
     1807     */
     1808    public function update_item_permissions_check( $request ) {
     1809        $id = (int) $request['id'];
     1810
     1811        if ( get_current_user_id() != $id ) {
     1812            return new WP_Error( 'mobile_builder', __( 'Sorry, you cannot change info.', 'rnlab' ), array( 'status' => rest_authorization_required_code() ) );
     1813        }
     1814
     1815        return true;
     1816    }
     1817
     1818    /**
     1819     * @param $user
     1820     *
     1821     * Add more info to user data response
     1822     *
     1823     * @return mixed
     1824     * @since 1.3.7
     1825     *
     1826     */
     1827    public function mbd_get_userdata( $user ) {
     1828
     1829        $user_data             = $user->data;
     1830        $user_data->first_name = $user->first_name;
     1831        $user_data->last_name  = $user->last_name;
     1832        $user_data->avatar     = 'https://www.gravatar.com/avatar/' . md5( $user_data->user_email );
     1833        $user_data->location   = get_user_meta( $user->ID, 'mbd_location', true );
     1834
     1835        return $user_data;
     1836    }
    1031837}
  • mobile-builder/trunk/vendor/autoload.php

    r2247209 r2303204  
    55require_once __DIR__ . '/composer/autoload_real.php';
    66
    7 return ComposerAutoloaderInit27dabd66d1d893576d6a1c14394417b9::getLoader();
     7return ComposerAutoloaderInit0c988ac8ff415cdb4ab2f537c76b5c10::getLoader();
  • mobile-builder/trunk/vendor/composer/autoload_real.php

    r2247209 r2303204  
    33// autoload_real.php @generated by Composer
    44
    5 class ComposerAutoloaderInit27dabd66d1d893576d6a1c14394417b9
     5class ComposerAutoloaderInit0c988ac8ff415cdb4ab2f537c76b5c10
    66{
    77    private static $loader;
     
    2020        }
    2121
    22         spl_autoload_register(array('ComposerAutoloaderInit27dabd66d1d893576d6a1c14394417b9', 'loadClassLoader'), true, true);
     22        spl_autoload_register(array('ComposerAutoloaderInit0c988ac8ff415cdb4ab2f537c76b5c10', 'loadClassLoader'), true, true);
    2323        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
    24         spl_autoload_unregister(array('ComposerAutoloaderInit27dabd66d1d893576d6a1c14394417b9', 'loadClassLoader'));
     24        spl_autoload_unregister(array('ComposerAutoloaderInit0c988ac8ff415cdb4ab2f537c76b5c10', 'loadClassLoader'));
    2525
    2626        $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
     
    2828            require_once __DIR__ . '/autoload_static.php';
    2929
    30             call_user_func(\Composer\Autoload\ComposerStaticInit27dabd66d1d893576d6a1c14394417b9::getInitializer($loader));
     30            call_user_func(\Composer\Autoload\ComposerStaticInit0c988ac8ff415cdb4ab2f537c76b5c10::getInitializer($loader));
    3131        } else {
    3232            $map = require __DIR__ . '/autoload_namespaces.php';
     
    4949
    5050        if ($useStaticLoader) {
    51             $includeFiles = Composer\Autoload\ComposerStaticInit27dabd66d1d893576d6a1c14394417b9::$files;
     51            $includeFiles = Composer\Autoload\ComposerStaticInit0c988ac8ff415cdb4ab2f537c76b5c10::$files;
    5252        } else {
    5353            $includeFiles = require __DIR__ . '/autoload_files.php';
    5454        }
    5555        foreach ($includeFiles as $fileIdentifier => $file) {
    56             composerRequire27dabd66d1d893576d6a1c14394417b9($fileIdentifier, $file);
     56            composerRequire0c988ac8ff415cdb4ab2f537c76b5c10($fileIdentifier, $file);
    5757        }
    5858
     
    6161}
    6262
    63 function composerRequire27dabd66d1d893576d6a1c14394417b9($fileIdentifier, $file)
     63function composerRequire0c988ac8ff415cdb4ab2f537c76b5c10($fileIdentifier, $file)
    6464{
    6565    if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
  • mobile-builder/trunk/vendor/composer/autoload_static.php

    r2247209 r2303204  
    55namespace Composer\Autoload;
    66
    7 class ComposerStaticInit27dabd66d1d893576d6a1c14394417b9
     7class ComposerStaticInit0c988ac8ff415cdb4ab2f537c76b5c10
    88{
    99    public static $files = array (
     
    3333    {
    3434        return \Closure::bind(function () use ($loader) {
    35             $loader->prefixLengthsPsr4 = ComposerStaticInit27dabd66d1d893576d6a1c14394417b9::$prefixLengthsPsr4;
    36             $loader->prefixDirsPsr4 = ComposerStaticInit27dabd66d1d893576d6a1c14394417b9::$prefixDirsPsr4;
     35            $loader->prefixLengthsPsr4 = ComposerStaticInit0c988ac8ff415cdb4ab2f537c76b5c10::$prefixLengthsPsr4;
     36            $loader->prefixDirsPsr4 = ComposerStaticInit0c988ac8ff415cdb4ab2f537c76b5c10::$prefixDirsPsr4;
    3737
    3838        }, null, ClassLoader::class);
  • mobile-builder/trunk/vendor/composer/installed.json

    r2247202 r2303204  
    6262    {
    6363        "name": "firebase/php-jwt",
    64         "version": "v5.0.0",
    65         "version_normalized": "5.0.0.0",
     64        "version": "v5.2.0",
     65        "version_normalized": "5.2.0.0",
    6666        "source": {
    6767            "type": "git",
    6868            "url": "https://github.com/firebase/php-jwt.git",
    69             "reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e"
     69            "reference": "feb0e820b8436873675fd3aca04f3728eb2185cb"
    7070        },
    7171        "dist": {
    7272            "type": "zip",
    73             "url": "https://api.github.com/repos/firebase/php-jwt/zipball/9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
    74             "reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
     73            "url": "https://api.github.com/repos/firebase/php-jwt/zipball/feb0e820b8436873675fd3aca04f3728eb2185cb",
     74            "reference": "feb0e820b8436873675fd3aca04f3728eb2185cb",
    7575            "shasum": ""
    7676        },
     
    7979        },
    8080        "require-dev": {
    81             "phpunit/phpunit": " 4.8.35"
     81            "phpunit/phpunit": ">=4.8 <=9"
    8282        },
    83         "time": "2017-06-27T22:17:23+00:00",
     83        "time": "2020-03-25T18:49:23+00:00",
    8484        "type": "library",
    8585        "installation-source": "dist",
     
    106106        ],
    107107        "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
    108         "homepage": "https://github.com/firebase/php-jwt"
     108        "homepage": "https://github.com/firebase/php-jwt",
     109        "keywords": [
     110            "jwt",
     111            "php"
     112        ]
    109113    }
    110114]
  • mobile-builder/trunk/vendor/firebase/php-jwt/README.md

    r2247202 r2303204  
    2424
    2525$key = "example_key";
    26 $token = array(
     26$payload = array(
    2727    "iss" => "http://example.org",
    2828    "aud" => "http://example.com",
     
    3737 * for a list of spec-compliant algorithms.
    3838 */
    39 $jwt = JWT::encode($token, $key);
     39$jwt = JWT::encode($payload, $key);
    4040$decoded = JWT::decode($jwt, $key, array('HS256'));
    4141
     
    9494EOD;
    9595
    96 $token = array(
     96$payload = array(
    9797    "iss" => "example.org",
    9898    "aud" => "example.com",
     
    101101);
    102102
    103 $jwt = JWT::encode($token, $privateKey, 'RS256');
     103$jwt = JWT::encode($payload, $privateKey, 'RS256');
    104104echo "Encode:\n" . print_r($jwt, true) . "\n";
    105105
  • mobile-builder/trunk/vendor/firebase/php-jwt/composer.json

    r2247202 r2303204  
    33    "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
    44    "homepage": "https://github.com/firebase/php-jwt",
     5    "keywords": [
     6        "php",
     7        "jwt"
     8    ],
    59    "authors": [
    610        {
     
    2529    },
    2630    "require-dev": {
    27         "phpunit/phpunit": " 4.8.35"
     31        "phpunit/phpunit": ">=4.8 <=9"
    2832    }
    2933}
  • mobile-builder/trunk/vendor/firebase/php-jwt/src/BeforeValidException.php

    r2247202 r2303204  
    44class BeforeValidException extends \UnexpectedValueException
    55{
    6 
    76}
  • mobile-builder/trunk/vendor/firebase/php-jwt/src/ExpiredException.php

    r2247202 r2303204  
    44class ExpiredException extends \UnexpectedValueException
    55{
    6 
    76}
  • mobile-builder/trunk/vendor/firebase/php-jwt/src/JWT.php

    r2247202 r2303204  
    22
    33namespace Firebase\JWT;
     4
    45use \DomainException;
    56use \InvalidArgumentException;
     
    2223class JWT
    2324{
     25    const ASN1_INTEGER = 0x02;
     26    const ASN1_SEQUENCE = 0x10;
     27    const ASN1_BIT_STRING = 0x03;
    2428
    2529    /**
     
    3943
    4044    public static $supported_algs = array(
     45        'ES256' => array('openssl', 'SHA256'),
    4146        'HS256' => array('hash_hmac', 'SHA256'),
     47        'HS384' => array('hash_hmac', 'SHA384'),
    4248        'HS512' => array('hash_hmac', 'SHA512'),
    43         'HS384' => array('hash_hmac', 'SHA384'),
    4449        'RS256' => array('openssl', 'SHA256'),
    4550        'RS384' => array('openssl', 'SHA384'),
     
    5055     * Decodes a JWT string into a PHP object.
    5156     *
    52      * @param string        $jwt            The JWT
    53      * @param string|array  $key            The key, or map of keys.
    54      *                                      If the algorithm used is asymmetric, this is the public key
    55      * @param array         $allowed_algs   List of supported verification algorithms
    56      *                                      Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     57     * @param string                    $jwt            The JWT
     58     * @param string|array|resource     $key            The key, or map of keys.
     59     *                                                  If the algorithm used is asymmetric, this is the public key
     60     * @param array                     $allowed_algs   List of supported verification algorithms
     61     *                                                  Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
    5762     *
    5863     * @return object The JWT's payload as a PHP object
     
    6974    public static function decode($jwt, $key, array $allowed_algs = array())
    7075    {
    71         $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
     76        $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
    7277
    7378        if (empty($key)) {
    7479            throw new InvalidArgumentException('Key may not be empty');
    7580        }
    76         $tks = explode('.', $jwt);
    77         if (count($tks) != 3) {
     81        $tks = \explode('.', $jwt);
     82        if (\count($tks) != 3) {
    7883            throw new UnexpectedValueException('Wrong number of segments');
    7984        }
     
    9499            throw new UnexpectedValueException('Algorithm not supported');
    95100        }
    96         if (!in_array($header->alg, $allowed_algs)) {
     101        if (!\in_array($header->alg, $allowed_algs)) {
    97102            throw new UnexpectedValueException('Algorithm not allowed');
    98103        }
    99         if (is_array($key) || $key instanceof \ArrayAccess) {
     104        if ($header->alg === 'ES256') {
     105            // OpenSSL expects an ASN.1 DER sequence for ES256 signatures
     106            $sig = self::signatureToDER($sig);
     107        }
     108
     109        if (\is_array($key) || $key instanceof \ArrayAccess) {
    100110            if (isset($header->kid)) {
    101111                if (!isset($key[$header->kid])) {
     
    113123        }
    114124
    115         // Check if the nbf if it is defined. This is the time that the
     125        // Check the nbf if it is defined. This is the time that the
    116126        // token can actually be used. If it's not yet that time, abort.
    117127        if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
    118128            throw new BeforeValidException(
    119                 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
     129                'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->nbf)
    120130            );
    121131        }
     
    126136        if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
    127137            throw new BeforeValidException(
    128                 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
     138                'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->iat)
    129139            );
    130140        }
     
    145155     *                                  If the algorithm used is asymmetric, this is the private key
    146156     * @param string        $alg        The signing algorithm.
    147      *                                  Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     157     *                                  Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
    148158     * @param mixed         $keyId
    149159     * @param array         $head       An array with header elements to attach
     
    160170            $header['kid'] = $keyId;
    161171        }
    162         if ( isset($head) && is_array($head) ) {
    163             $header = array_merge($head, $header);
     172        if (isset($head) && \is_array($head)) {
     173            $header = \array_merge($head, $header);
    164174        }
    165175        $segments = array();
    166176        $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
    167177        $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
    168         $signing_input = implode('.', $segments);
     178        $signing_input = \implode('.', $segments);
    169179
    170180        $signature = static::sign($signing_input, $key, $alg);
    171181        $segments[] = static::urlsafeB64Encode($signature);
    172182
    173         return implode('.', $segments);
     183        return \implode('.', $segments);
    174184    }
    175185
     
    180190     * @param string|resource   $key    The secret key
    181191     * @param string            $alg    The signing algorithm.
    182      *                                  Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     192     *                                  Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
    183193     *
    184194     * @return string An encrypted message
     
    192202        }
    193203        list($function, $algorithm) = static::$supported_algs[$alg];
    194         switch($function) {
     204        switch ($function) {
    195205            case 'hash_hmac':
    196                 return hash_hmac($algorithm, $msg, $key, true);
     206                return \hash_hmac($algorithm, $msg, $key, true);
    197207            case 'openssl':
    198208                $signature = '';
    199                 $success = openssl_sign($msg, $signature, $key, $algorithm);
     209                $success = \openssl_sign($msg, $signature, $key, $algorithm);
    200210                if (!$success) {
    201211                    throw new DomainException("OpenSSL unable to sign data");
    202212                } else {
     213                    if ($alg === 'ES256') {
     214                        $signature = self::signatureFromDER($signature, 256);
     215                    }
    203216                    return $signature;
    204217                }
     
    226239
    227240        list($function, $algorithm) = static::$supported_algs[$alg];
    228         switch($function) {
     241        switch ($function) {
    229242            case 'openssl':
    230                 $success = openssl_verify($msg, $signature, $key, $algorithm);
     243                $success = \openssl_verify($msg, $signature, $key, $algorithm);
    231244                if ($success === 1) {
    232245                    return true;
     
    236249                // returns 1 on success, 0 on failure, -1 on error.
    237250                throw new DomainException(
    238                     'OpenSSL error: ' . openssl_error_string()
     251                    'OpenSSL error: ' . \openssl_error_string()
    239252                );
    240253            case 'hash_hmac':
    241254            default:
    242                 $hash = hash_hmac($algorithm, $msg, $key, true);
    243                 if (function_exists('hash_equals')) {
    244                     return hash_equals($signature, $hash);
     255                $hash = \hash_hmac($algorithm, $msg, $key, true);
     256                if (\function_exists('hash_equals')) {
     257                    return \hash_equals($signature, $hash);
    245258                }
    246                 $len = min(static::safeStrlen($signature), static::safeStrlen($hash));
     259                $len = \min(static::safeStrlen($signature), static::safeStrlen($hash));
    247260
    248261                $status = 0;
    249262                for ($i = 0; $i < $len; $i++) {
    250                     $status |= (ord($signature[$i]) ^ ord($hash[$i]));
     263                    $status |= (\ord($signature[$i]) ^ \ord($hash[$i]));
    251264                }
    252265                $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
     
    267280    public static function jsonDecode($input)
    268281    {
    269         if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
     282        if (\version_compare(PHP_VERSION, '5.4.0', '>=') && !(\defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
    270283            /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
    271284             * to specify that large ints (like Steam Transaction IDs) should be treated as
    272285             * strings, rather than the PHP default behaviour of converting them to floats.
    273286             */
    274             $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
     287            $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
    275288        } else {
    276289            /** Not all servers will support that, however, so for older versions we must
     
    278291             *them to strings) before decoding, hence the preg_replace() call.
    279292             */
    280             $max_int_length = strlen((string) PHP_INT_MAX) - 1;
    281             $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
    282             $obj = json_decode($json_without_bigints);
    283         }
    284 
    285         if (function_exists('json_last_error') && $errno = json_last_error()) {
     293            $max_int_length = \strlen((string) PHP_INT_MAX) - 1;
     294            $json_without_bigints = \preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
     295            $obj = \json_decode($json_without_bigints);
     296        }
     297
     298        if ($errno = \json_last_error()) {
    286299            static::handleJsonError($errno);
    287300        } elseif ($obj === null && $input !== 'null') {
     
    302315    public static function jsonEncode($input)
    303316    {
    304         $json = json_encode($input);
    305         if (function_exists('json_last_error') && $errno = json_last_error()) {
     317        $json = \json_encode($input);
     318        if ($errno = \json_last_error()) {
    306319            static::handleJsonError($errno);
    307320        } elseif ($json === 'null' && $input !== null) {
     
    320333    public static function urlsafeB64Decode($input)
    321334    {
    322         $remainder = strlen($input) % 4;
     335        $remainder = \strlen($input) % 4;
    323336        if ($remainder) {
    324337            $padlen = 4 - $remainder;
    325             $input .= str_repeat('=', $padlen);
    326         }
    327         return base64_decode(strtr($input, '-_', '+/'));
     338            $input .= \str_repeat('=', $padlen);
     339        }
     340        return \base64_decode(\strtr($input, '-_', '+/'));
    328341    }
    329342
     
    337350    public static function urlsafeB64Encode($input)
    338351    {
    339         return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
     352        return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
    340353    }
    341354
     
    366379     * Get the number of bytes in cryptographic strings.
    367380     *
    368      * @param string
     381     * @param string $str
    369382     *
    370383     * @return int
     
    372385    private static function safeStrlen($str)
    373386    {
    374         if (function_exists('mb_strlen')) {
    375             return mb_strlen($str, '8bit');
    376         }
    377         return strlen($str);
     387        if (\function_exists('mb_strlen')) {
     388            return \mb_strlen($str, '8bit');
     389        }
     390        return \strlen($str);
     391    }
     392
     393    /**
     394     * Convert an ECDSA signature to an ASN.1 DER sequence
     395     *
     396     * @param   string $sig The ECDSA signature to convert
     397     * @return  string The encoded DER object
     398     */
     399    private static function signatureToDER($sig)
     400    {
     401        // Separate the signature into r-value and s-value
     402        list($r, $s) = \str_split($sig, (int) (\strlen($sig) / 2));
     403
     404        // Trim leading zeros
     405        $r = \ltrim($r, "\x00");
     406        $s = \ltrim($s, "\x00");
     407
     408        // Convert r-value and s-value from unsigned big-endian integers to
     409        // signed two's complement
     410        if (\ord($r[0]) > 0x7f) {
     411            $r = "\x00" . $r;
     412        }
     413        if (\ord($s[0]) > 0x7f) {
     414            $s = "\x00" . $s;
     415        }
     416
     417        return self::encodeDER(
     418            self::ASN1_SEQUENCE,
     419            self::encodeDER(self::ASN1_INTEGER, $r) .
     420            self::encodeDER(self::ASN1_INTEGER, $s)
     421        );
     422    }
     423
     424    /**
     425     * Encodes a value into a DER object.
     426     *
     427     * @param   int     $type DER tag
     428     * @param   string  $value the value to encode
     429     * @return  string  the encoded object
     430     */
     431    private static function encodeDER($type, $value)
     432    {
     433        $tag_header = 0;
     434        if ($type === self::ASN1_SEQUENCE) {
     435            $tag_header |= 0x20;
     436        }
     437
     438        // Type
     439        $der = \chr($tag_header | $type);
     440
     441        // Length
     442        $der .= \chr(\strlen($value));
     443
     444        return $der . $value;
     445    }
     446
     447    /**
     448     * Encodes signature from a DER object.
     449     *
     450     * @param   string  $der binary signature in DER format
     451     * @param   int     $keySize the number of bits in the key
     452     * @return  string  the signature
     453     */
     454    private static function signatureFromDER($der, $keySize)
     455    {
     456        // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
     457        list($offset, $_) = self::readDER($der);
     458        list($offset, $r) = self::readDER($der, $offset);
     459        list($offset, $s) = self::readDER($der, $offset);
     460
     461        // Convert r-value and s-value from signed two's compliment to unsigned
     462        // big-endian integers
     463        $r = \ltrim($r, "\x00");
     464        $s = \ltrim($s, "\x00");
     465
     466        // Pad out r and s so that they are $keySize bits long
     467        $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
     468        $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
     469
     470        return $r . $s;
     471    }
     472
     473    /**
     474     * Reads binary DER-encoded data and decodes into a single object
     475     *
     476     * @param string $der the binary data in DER format
     477     * @param int $offset the offset of the data stream containing the object
     478     * to decode
     479     * @return array [$offset, $data] the new offset and the decoded object
     480     */
     481    private static function readDER($der, $offset = 0)
     482    {
     483        $pos = $offset;
     484        $size = \strlen($der);
     485        $constructed = (\ord($der[$pos]) >> 5) & 0x01;
     486        $type = \ord($der[$pos++]) & 0x1f;
     487
     488        // Length
     489        $len = \ord($der[$pos++]);
     490        if ($len & 0x80) {
     491            $n = $len & 0x1f;
     492            $len = 0;
     493            while ($n-- && $pos < $size) {
     494                $len = ($len << 8) | \ord($der[$pos++]);
     495            }
     496        }
     497
     498        // Value
     499        if ($type == self::ASN1_BIT_STRING) {
     500            $pos++; // Skip the first contents octet (padding indicator)
     501            $data = \substr($der, $pos, $len - 1);
     502            $pos += $len - 1;
     503        } elseif (!$constructed) {
     504            $data = \substr($der, $pos, $len);
     505            $pos += $len;
     506        } else {
     507            $data = null;
     508        }
     509
     510        return array($pos, $data);
    378511    }
    379512}
  • mobile-builder/trunk/vendor/firebase/php-jwt/src/SignatureInvalidException.php

    r2247202 r2303204  
    44class SignatureInvalidException extends \UnexpectedValueException
    55{
    6 
    76}
Note: See TracChangeset for help on using the changeset viewer.