Plugin Directory

Changeset 2962781


Ignore:
Timestamp:
09/05/2023 05:49:44 AM (3 years ago)
Author:
thrivedesk
Message:

Update to version 1.1.0 from GitHub

Location:
thrivedesk
Files:
10 edited
1 copied

Legend:

Unmodified
Added
Removed
  • thrivedesk/tags/1.1.0/readme.txt

    r2957963 r2962781  
    33Tags: livechat, chat, help desk, chat plugin, free live chat, community, helpdesk, chatbot, knowledge base, support, help center, customer care,  woocommerce, surecart, freemius, thrivedesk, zendesk, mailchimp
    44Requires at least: 4.9
    5 Tested up to: 6.3
    6 Stable Tag: 1.0.18
     5Tested up to: 6.3.1
     6Stable Tag: 1.1.0
    77Requires PHP: 5.5
    88License: GNU General Public License v2.0 or later
     
    224224
    225225== Changelog ==
     226= 1.1.0
     227- Update: Woocommerce Integration V2
     228
    226229= 1.0.18 =
    227230- Fix: Revert pro plan
  • thrivedesk/tags/1.1.0/src/Abstracts/Plugin.php

    r2839767 r2962781  
    44
    55// Exit if accessed directly.
    6 if (!defined('ABSPATH')) {
     6if ( ! defined( 'ABSPATH' ) ) {
    77    exit;
    88}
     
    6565     * @return mixed
    6666     */
    67     abstract public function get_plugin_data(string $key = '');
     67    abstract public function get_plugin_data( string $key = '' );
    6868
    6969    /**
     
    8888     * @return string
    8989     */
    90     public function get_formated_amount(float $amount): string {
     90    public function get_formated_amount( float $amount ): string {
    9191        return $amount;
    9292    }
     
    106106     * @return array
    107107     */
    108     public function filter_accepted_orders(array $orders): array {
     108    public function filter_accepted_orders( array $orders ): array {
    109109        $accepted_statuses = $this->accepted_statuses() ?? [];
    110110
    111         return array_filter($orders, function ($order) use ($accepted_statuses) {
    112             return in_array($order['order_status'], $accepted_statuses);
    113         });
     111        return array_filter( $orders, function ( $order ) use ( $accepted_statuses ) {
     112            return in_array( $order['order_status'], $accepted_statuses );
     113        } );
    114114    }
    115115
     
    121121     * @return float
    122122     */
    123     public function get_lifetime_order(array $orders): float {
     123    public function get_lifetime_order( array $orders ): float {
    124124        // TODO: Ignore pending or refunded amounts
    125         $amount = array_sum(array_column($orders, 'amount'));
    126 
    127         return $amount;
     125        return array_sum( array_column( $orders, 'amount' ) );
    128126    }
    129127
     
    135133     * @return float
    136134     */
    137     public function get_this_year_order(array $orders): float {
     135    public function get_this_year_order( array $orders ): float {
    138136        // TODO: Ignore pending or refunded amounts
    139         $amount = 0;
    140 
    141         $amount = array_reduce($orders, function ($carry, $item) {
    142             if (strtotime($item['date']) >= strtotime('-1 year')) {
    143                 $carry += $item['amount'];
     137        return array_reduce( $orders, function ( $carry, $item ) {
     138            if ( strtotime( $item['date'] ) >= strtotime( '-1 year' ) ) {
     139                $carry += (float) $item['amount'];
    144140            }
    145141
    146142            return $carry;
    147         }, 0);
    148 
    149         return $amount;
     143        }, 0 );
    150144    }
    151145
     
    160154        $orders = $this->get_orders();
    161155
    162         $accepted_orders = $this->filter_accepted_orders($orders);
     156        $accepted_orders = $this->filter_accepted_orders( $orders );
    163157
    164         $this_year_order = $this->get_this_year_order($accepted_orders);
     158        $this_year_order = $this->get_this_year_order( $accepted_orders );
    165159
    166         $lifetime_order = $this->get_lifetime_order($accepted_orders);
     160        $lifetime_order = $this->get_lifetime_order( $accepted_orders );
    167161
    168         $avg_order = $lifetime_order ? ($lifetime_order / count($accepted_orders)) : 0;
     162        $avg_order = $lifetime_order ? ( $lifetime_order / count( $accepted_orders ) ) : 0;
    169163
    170         $avg_order = number_format((float) $avg_order, 2, '.', '');
     164        $avg_order = number_format( (float) $avg_order, 2, '.', '' );
    171165
    172166        return [
    173             "customer"        => $customer ?? [],
     167            "customer"        => $customer,
    174168            "customer_since"  => $customer['registered_at'] ?? '',
    175             "lifetime_order"  => $this->get_formated_amount($lifetime_order),
    176             "this_year_order" => $this->get_formated_amount($this_year_order),
    177             "avg_order"       => $this->get_formated_amount($avg_order),
     169            "lifetime_order"  => $this->get_formated_amount( $lifetime_order ),
     170            "this_year_order" => $this->get_formated_amount( $this_year_order ),
     171            "avg_order"       => $this->get_formated_amount( $avg_order ),
    178172            "orders"          => $orders,
     173            'add_order'       => admin_url( "post-new.php?post_type=shop_order" ) ?? '',
    179174        ];
    180175    }
  • thrivedesk/tags/1.1.0/src/Api.php

    r2839767 r2962781  
    44
    55use ThriveDesk\Api\ApiResponse;
     6use WC_Product_Query;
     7use WC_Order;
     8use WC_Order_Item_Product;
    69
    710// Exit if accessed directly.
    8 if (!defined('ABSPATH')) {
     11if ( ! defined( 'ABSPATH' ) ) {
    912    exit;
    1013}
     
    1720
    1821    private $apiResponse;
    19 
    2022    private $plugin = null;
     23    private $order_id = null;
     24    private $order_status = null;
     25    private $quantity = null;
     26    private $item = null;
     27    private $coupon = null;
     28    private $amount = null;
     29    private $reason = null;
     30    private $item_id = null;
    2131
    2232    /**
     
    2737     */
    2838    private function __construct() {
    29         add_action('init', [$this, 'api_listener']);
     39        add_action( 'init', [ $this, 'api_listener' ] );
    3040
    3141        $this->apiResponse = new ApiResponse();
     
    4454     */
    4555    public static function instance(): object {
    46         if (!isset(self::$instance) && !(self::$instance instanceof Admin)) {
     56        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Admin ) ) {
    4757            self::$instance = new self();
    4858        }
     
    7484     */
    7585    public function api_listener(): void {
    76         $listener = sanitize_key($_GET['listener'] ?? '');
    77         if (!isset($listener) || 'thrivedesk' !== $listener) {
     86        $listener = sanitize_key( $_GET['listener'] ?? '' );
     87        if ( ! isset( $listener ) || 'thrivedesk' !== $listener ) {
    7888            return;
    7989        }
    8090
    8191        try {
    82             $action = strtolower(sanitize_key($_GET['action'] ?? ''));
    83             $plugin = strtolower(sanitize_key($_GET['plugin'] ?? 'edd'));
     92            $action = strtolower( sanitize_key( $_GET['action'] ?? '' ) );
     93            $plugin = strtolower( sanitize_key( $_GET['plugin'] ?? 'edd' ) );
     94
     95            $this->order_id     = sanitize_key( $_GET['order_id'] ?? '' );
     96            $this->order_status = sanitize_key( $_GET['order_status'] ?? '' );
     97            $this->quantity     = sanitize_key( $_GET['quantity'] ?? '' );
     98            $this->item         = sanitize_key( $_GET['item'] ?? '' );
     99            $this->item_id      = sanitize_key( $_GET['item_id'] ?? '' );
     100            $this->coupon       = sanitize_key( $_GET['coupon'] ?? '' );
     101            $this->amount       = sanitize_key( $_GET['amount'] ?? '' );
     102            $this->reason       = sanitize_key( $_GET['reason'] ?? '' );
    84103
    85104            // Plugin invalid response
    86             if (!in_array($plugin, array_keys($this->_available_plugins()))) {
    87                 $this->apiResponse->error(401, 'Plugin is invalid or not available now.');
    88             }
    89 
    90             $plugin_name       = $this->_available_plugins()[$plugin] ?? 'EDD';
     105            if ( ! in_array( $plugin, array_keys( $this->_available_plugins() ) ) ) {
     106                $this->apiResponse->error( 401, 'Plugin is invalid or not available now.' );
     107            }
     108
     109            $plugin_name       = $this->_available_plugins()[ $plugin ] ?? 'EDD';
    91110            $plugin_class_name = 'ThriveDesk\\Plugins\\' . $plugin_name;
    92111
    93             if (!class_exists($plugin_class_name)) {
    94                 $this->apiResponse->error(500, "Class not found for the '{$plugin_name}' plugin");
     112            if ( ! class_exists( $plugin_class_name ) ) {
     113                $this->apiResponse->error( 500, "Class not found for the '{$plugin_name}' plugin" );
    95114            }
    96115
    97116            $this->plugin = $plugin_class_name::instance();
    98117
    99             if (!method_exists($this->plugin, 'is_plugin_active')) {
    100                 $this->apiResponse->error(500, "Method 'prepare_data' not exist in class '{$plugin_class_name}'");
    101             }
    102 
    103             if (!$this->plugin->is_plugin_active()) {
    104                 $this->apiResponse->error(500, "The plugin '{$plugin_name}' isn't installed or active.");
    105             }
    106 
    107             if (!$this->verify_token()) {
    108                 $this->apiResponse->error(401, 'Request unauthorized');
    109             }
    110 
    111             if (isset($action) && 'connect' === $action) {
     118            if ( ! method_exists( $this->plugin, 'is_plugin_active' ) ) {
     119                $this->apiResponse->error( 500, "Method 'prepare_data' not exist in class '{$plugin_class_name}'" );
     120            }
     121
     122            if ( ! $this->plugin->is_plugin_active() ) {
     123                $this->apiResponse->error( 500, "The plugin '{$plugin_name}' isn't installed or active." );
     124            }
     125
     126            if ( ! $this->verify_token() ) {
     127                $this->apiResponse->error( 401, 'Request unauthorized' );
     128            }
     129
     130            if ( isset( $action ) && 'connect' === $action ) {
    112131                $this->connect_action_handler();
    113             } elseif (isset($action) && 'disconnect' === $action) {
     132            } elseif ( isset( $action ) && 'disconnect' === $action ) {
    114133                $this->disconnect_action_handler();
    115             } elseif (isset($action) && 'get_fluentcrm_data' === $action) {
     134            } elseif ( isset( $action ) && 'get_fluentcrm_data' === $action ) {
    116135                $this->fluentcrm_handler();
    117             } elseif (isset($action) && 'handle_autonami' === $action) {
     136            } elseif ( isset( $action ) && 'handle_autonami' === $action ) {
    118137                $this->autonami_handler();
    119             } elseif (isset($action) && 'get_wppostsync_data' === $action) {
    120                 $remote_query_string = strtolower($_GET['query'] ?? '');
    121                 $this->wp_postsync_data_handler($remote_query_string);
    122             } elseif (isset($action) && 'get_woocommerce_order_status' === $action) {
     138            } elseif ( isset( $action ) && 'get_wppostsync_data' === $action ) {
     139                $remote_query_string = strtolower( $_GET['query'] ?? '' );
     140                $this->wp_postsync_data_handler( $remote_query_string );
     141            } elseif ( isset( $action ) && 'get_woocommerce_product_list' === $action ) {
     142                $this->get_woocommerce_product_list();
     143            } elseif ( isset( $action ) && 'get_woocommerce_order_status' === $action ) {
    123144                $this->get_woocommerce_order_status();
     145            } elseif ( isset( $action ) && 'get_woocommerce_order_status_list' === $action ) {
     146                $this->get_woocommerce_status_list();
     147            } elseif ( isset( $action ) && 'woocommerce_order_status_update' === $action ) {
     148                $this->woocommerce_order_status_update( $this->order_id, $this->order_status );
     149            } elseif ( isset( $action ) && 'woocommerce_order_quantity_update' === $action ) {
     150                $this->woocommerce_order_quantity_update( $this->order_id, $this->item_id, $this->quantity );
     151            } elseif ( isset( $action ) && 'woocommerce_order_apply_coupon' === $action ) {
     152                $this->woocommerce_order_apply_coupon( $this->order_id, $this->coupon );
     153            } elseif ( isset( $action ) && 'add_item_on_woocommerce_order' === $action ) {
     154                $this->wc_order_add_new_item( $this->order_id, $this->item );
     155            } elseif ( isset( $action ) && 'remove_item_from_woocommerce_order' === $action ) {
     156                $this->wc_order_remove_item( $this->order_id, $this->item );
    124157            } else {
    125158                $this->plugin_data_action_handler();
    126159            }
    127         } catch (\Exception $e) {
    128             $this->apiResponse->error(500, 'Can\'t not prepare data');
     160        } catch ( \Exception $e ) {
     161            $this->apiResponse->error( 500, 'Can\'t not prepare data' );
    129162        }
    130163
     
    136169     */
    137170    public function autonami_handler() {
    138         $syncType                     = strtolower(sanitize_key($_REQUEST['sync_type'] ?? ''));
    139         $this->plugin->customer_email = sanitize_email($_GET['email'] ?? '');
    140 
    141         if ($syncType) {
    142             $this->plugin->sync_conversation_with_autonami($syncType, $_REQUEST['extra'] ?? []);
     171        $syncType                     = strtolower( sanitize_key( $_REQUEST['sync_type'] ?? '' ) );
     172        $this->plugin->customer_email = sanitize_email( $_GET['email'] ?? '' );
     173
     174        if ( $syncType ) {
     175            $this->plugin->sync_conversation_with_autonami( $syncType, $_REQUEST['extra'] ?? [] );
    143176        } else {
    144             if (!method_exists($this->plugin, 'prepare_data')) {
    145                 $this->apiResponse->error(500, "Method 'prepare_data' not exist in plugin");
    146             }
    147 
    148             if (!$this->plugin->is_customer_exist()) {
    149                 $this->apiResponse->error(404, "Customer not found.");
     177            if ( ! method_exists( $this->plugin, 'prepare_data' ) ) {
     178                $this->apiResponse->error( 500, "Method 'prepare_data' not exist in plugin" );
     179            }
     180
     181            if ( ! $this->plugin->is_customer_exist() ) {
     182                $this->apiResponse->error( 404, "Customer not found." );
    150183            }
    151184
    152185            $data = $this->plugin->prepare_data();
    153186
    154             $this->apiResponse->success(200, $data, 'Success');
     187            $this->apiResponse->success( 200, $data, 'Success' );
    155188        }
    156189    }
     
    162195     */
    163196    public function get_woocommerce_order_status() {
    164         $email    = sanitize_email($_REQUEST['email'] ?? '');
    165         $order_id = strtolower(sanitize_key($_REQUEST['order_id'] ?? ''));
    166 
    167         if (!method_exists($this->plugin, 'order_status')) {
    168             $this->apiResponse->error(500, "Method 'order_status' not exist in plugin");
     197        $email    = sanitize_email( $_REQUEST['email'] ?? '' );
     198        $order_id = strtolower( sanitize_key( $_REQUEST['order_id'] ?? '' ) );
     199
     200        if ( ! method_exists( $this->plugin, 'order_status' ) ) {
     201            $this->apiResponse->error( 500, "Method 'order_status' not exist in plugin" );
    169202        }
    170203
    171204        $this->plugin->customer_email = $email;
    172205
    173         if (!$this->plugin->is_customer_exist()) {
    174             $this->apiResponse->error(404, "Customer not found.");
    175         }
    176 
    177         $data = $this->plugin->order_status($order_id);
    178 
    179         $this->apiResponse->success(200, $data, 'Success');
     206        if ( ! $this->plugin->is_customer_exist() ) {
     207            $this->apiResponse->error( 404, "Customer not found." );
     208        }
     209
     210        $data = $this->plugin->order_status( $order_id );
     211
     212        $this->apiResponse->success( 200, $data, 'Success' );
     213    }
     214
     215    /**
     216     * @return void
     217     */
     218    public function get_woocommerce_product_list() {
     219
     220        $query = new WC_Product_Query( array(
     221            'status' => 'publish',
     222            'return' => 'ids',
     223        ) );
     224
     225        $products    = $query->get_products();
     226        $productList = [];
     227
     228        foreach ( $products as $product_id ) {
     229            $product = wc_get_product( $product_id );
     230
     231            $productInfo = array(
     232                "product_id"        => $product_id,
     233                "title"             => $product->get_name(),
     234                "product_permalink" => get_permalink( $product_id ),
     235                "image"             => wp_get_attachment_image_src( get_post_thumbnail_id( $product_id ) )[0],
     236                "sale_price"        => get_woocommerce_currency_symbol() . $product->get_regular_price(),
     237                "stock"             => ( 'instock' === $product->get_stock_status() ) ? 'In Stock' : 'Out of Stock',
     238            );
     239
     240            array_push( $productList, $productInfo );
     241        }
     242
     243        $data = $productList;
     244
     245        $this->apiResponse->success( 200, $data, 'Success' );
     246    }
     247
     248    /**
     249     * @return void
     250     */
     251    public function get_woocommerce_status_list() {
     252
     253        $statuses = wc_get_order_statuses();
     254
     255        $this->apiResponse->success( 200, $statuses, 'Success' );
     256    }
     257
     258    /**
     259     * @param $order_id
     260     * @param $item
     261     *
     262     * @return void
     263     */
     264    public function wc_order_add_new_item( string $order_id, $item ) {
     265        $product = wc_get_product_object( 'line_item', $item );
     266
     267        $item = new WC_Order_Item_Product();
     268        $item->set_name( $product->name );
     269        $item->set_quantity( $this->quantity );
     270        $item->set_product_id( $product->id );
     271        $item->set_subtotal( $product->price ?? 0 );
     272        $item->set_total( $product->price * $this->quantity ?? 0 );
     273        $order = wc_get_order( $order_id );
     274        $order->add_item( $item );
     275        $order->calculate_totals();
     276
     277        $this->apiResponse->success( 200, [], 'Success' );
     278    }
     279
     280    /**
     281     * @param $order_id
     282     * @param $product_id
     283     *
     284     * @return void
     285     */
     286    public function wc_order_remove_item( string $order_id, string $product_id ) {
     287        $order = wc_get_order( $order_id );
     288
     289        foreach ( $order->get_items() as $item_id => $item ) {
     290            if ( $item["product_id"] == $product_id ) {
     291                wc_delete_order_item( $item_id );
     292            }
     293        }
     294
     295        $order->calculate_totals();
     296
     297        $this->apiResponse->success( 200, [], 'Success' );
     298    }
     299
     300
     301    /**
     302     * @param $order_id
     303     * @param $orderStatus
     304     *
     305     * @return void
     306     */
     307    public function woocommerce_order_status_update( string $order_id, string $orderStatus ) {
     308        $order = new WC_Order( $order_id );
     309        $order->update_status( $orderStatus, '' );
     310
     311        $this->apiResponse->success( 200, [], 'Success' );
     312    }
     313
     314    /**
     315     * @param $order_id
     316     * @param $product_id
     317     * @param $quantity
     318     *
     319     * @return void
     320     */
     321    public function woocommerce_order_quantity_update( string $order_id, string $product_id, string $quantity ) {
     322
     323        $order = wc_get_order( $order_id );
     324        if ( $quantity > 0 ) {
     325            foreach ( $order->get_items() as $item_id => $item ) {
     326
     327                if ( $item["product_id"] == (string) $product_id ) {
     328                    wc_update_order_item_meta( $item_id, '_qty', $quantity );
     329                    $order->calculate_totals();
     330                }
     331            }
     332            $this->apiResponse->success( 200, [], 'Success' );
     333        }
     334    }
     335
     336    /**
     337     * @param $order_id
     338     * @param $coupon
     339     *
     340     * @return void
     341     */
     342    public function woocommerce_order_apply_coupon( string $order_id, string $coupon ) {
     343        $order = wc_get_order( $order_id );
     344
     345        if ( $coupon ) {
     346            $res = $order->apply_coupon( $coupon );
     347            if ( isset( $res->errors ) ) {
     348                $this->apiResponse->error( 404, "Coupon does not exist!." );
     349            } else {
     350                $this->apiResponse->success( 200, [], 'Success' );
     351            }
     352        }
     353
    180354    }
    181355
     
    187361     */
    188362    public function fluentcrm_handler(): void {
    189         $syncType                     = strtolower(sanitize_key($_REQUEST['sync_type'] ?? ''));
    190         $this->plugin->customer_email = sanitize_email($_REQUEST['email'] ?? '');
    191 
    192         if ($syncType) {
    193             $this->plugin->sync_conversation_with_fluentcrm($syncType, $_REQUEST['extra'] ?? []);
     363        $syncType                     = strtolower( sanitize_key( $_REQUEST['sync_type'] ?? '' ) );
     364        $this->plugin->customer_email = sanitize_email( $_REQUEST['email'] ?? '' );
     365
     366        if ( $syncType ) {
     367            $this->plugin->sync_conversation_with_fluentcrm( $syncType, $_REQUEST['extra'] ?? [] );
    194368        } else {
    195             if (!method_exists($this->plugin, 'prepare_fluentcrm_data')) {
    196                 $this->apiResponse->error(500, "Method 'prepare_fluentcrm_data' not exist in plugin");
    197             }
    198 
    199             if (!$this->plugin->is_customer_exist()) {
    200                 $this->apiResponse->error(404, "Customer not found.");
     369            if ( ! method_exists( $this->plugin, 'prepare_fluentcrm_data' ) ) {
     370                $this->apiResponse->error( 500, "Method 'prepare_fluentcrm_data' not exist in plugin" );
     371            }
     372
     373            if ( ! $this->plugin->is_customer_exist() ) {
     374                $this->apiResponse->error( 404, "Customer not found." );
    201375            }
    202376            $data = $this->plugin->prepare_fluentcrm_data();
    203377
    204             $this->apiResponse->success(200, $data, 'Success');
     378            $this->apiResponse->success( 200, $data, 'Success' );
    205379        }
    206380    }
     
    213387     * @since 0.8.0
    214388     */
    215     public function wp_postsync_data_handler($remote_query_string): void {
    216         $search_data = $this->plugin->get_post_search_result($remote_query_string);
    217         $this->apiResponse->success(200, $search_data, 'Success');
     389    public function wp_postsync_data_handler( $remote_query_string ): void {
     390        $search_data = $this->plugin->get_post_search_result( $remote_query_string );
     391
     392        $this->apiResponse->success( 200, $search_data, 'Success' );
    218393    }
    219394
     
    227402        $this->plugin->connect();
    228403
    229         $this->apiResponse->success(200, [], 'Site connected successfully');
     404        $this->apiResponse->success( 200, [], 'Site connected successfully' );
    230405    }
    231406
     
    239414        $this->plugin->disconnect();
    240415
    241         $this->apiResponse->success(200, [], 'Site has been disconnected');
     416        $this->apiResponse->success( 200, [], 'Site has been disconnected' );
    242417    }
    243418
     
    249424     */
    250425    public function plugin_data_action_handler() {
    251         $email          = sanitize_email($_REQUEST['email'] ?? '');
     426
     427        $email          = sanitize_email( $_REQUEST['email'] ?? '' );
    252428        $enableShipping = $_REQUEST['shipping_param'] == 1 ? true : false;
    253429
    254         if (!method_exists($this->plugin, 'prepare_data')) {
    255             $this->apiResponse->error(500, "Method 'prepare_data' not exist in plugin");
     430        if ( ! method_exists( $this->plugin, 'prepare_data' ) ) {
     431            $this->apiResponse->error( 500, "Method 'prepare_data' not exist in plugin" );
    256432        }
    257433
     
    259435        $this->plugin->shipping_param = $enableShipping;
    260436
    261         if (!$this->plugin->is_customer_exist()) {
    262             $this->apiResponse->error(404, "Customer not found.");
     437        if ( ! $this->plugin->is_customer_exist() ) {
     438            $this->apiResponse->error( 404, "Customer not found." );
    263439        }
    264440
    265441        $data = $this->plugin->prepare_data();
    266442
    267         $this->apiResponse->success(200, $data, 'Success');
     443        $this->apiResponse->success( 200, $data, 'Success' );
    268444    }
    269445
     
    277453        $payload = $_REQUEST;
    278454
    279         if ($payload) {
    280             foreach ($payload as $key => $value) {
    281                 if (!is_string($value)) {
     455        if ( $payload ) {
     456            foreach ( $payload as $key => $value ) {
     457                if ( ! is_string( $value ) ) {
    282458                    continue;
    283459                }
    284                 switch (strtolower($value)) {
    285                     case "1":
     460                switch ( strtolower( $value ) ) {
    286461                    case "true":
    287                         $payload[$key] = true;
     462                        $payload[ $key ] = true;
    288463                        break;
    289464
    290                     case "0":
    291465                    case "false":
    292                         $payload[$key] = false;
     466                        $payload[ $key ] = false;
    293467                        break;
    294468                }
     
    296470        }
    297471
    298         $api_token = $this->plugin->get_plugin_data('api_token');
     472        $api_token = $this->plugin->get_plugin_data( 'api_token' );
    299473
    300474        $signature = $_SERVER['HTTP_X_TD_SIGNATURE'];
    301475
    302         return hash_equals($signature, hash_hmac('SHA1', json_encode($payload), $api_token));
     476        return hash_equals( $signature, hash_hmac( 'SHA1', json_encode( $payload ), $api_token ) );
    303477    }
    304478}
  • thrivedesk/tags/1.1.0/src/Plugins/WooCommerce.php

    r2839767 r2962781  
    55use ThriveDesk\Plugin;
    66use WC_Order_Query;
     7use WC_Subscriptions_Product;
    78
    89// Exit if accessed directly.
    9 if (!defined('ABSPATH')) {
     10if ( ! defined( 'ABSPATH' ) ) {
    1011    exit;
    1112}
     
    4849     */
    4950    public static function instance() {
    50         if (!isset(self::$instance) && !(self::$instance instanceof WooCommerce)) {
     51        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WooCommerce ) ) {
    5152            self::$instance = new self();
    5253        }
     
    6162     */
    6263    public static function is_plugin_active(): bool {
    63         if (!function_exists('WC') || !class_exists('WooCommerce', false)) {
     64        if ( ! function_exists( 'WC' ) || ! class_exists( 'WooCommerce', false ) ) {
    6465            return false;
    6566        }
     
    7273     *
    7374     * @return boolean
     75     * @throws \Exception
    7476     */
    7577    public function is_guest() {
    76         if (empty($this->orders)) {
     78        if ( empty( $this->orders ) ) {
    7779            $this->orders = $this->get_orders();
    7880        }
    79         if (!empty($this->orders)) {
     81        if ( ! empty( $this->orders ) ) {
    8082            return true;
    8183        }
     
    8890     *
    8991     * @return boolean
     92     * @throws \Exception
    9093     */
    9194    public function is_customer_exist(): bool {
    92         if (!$this->customer_email) {
     95        if ( ! $this->customer_email ) {
    9396            return false;
    9497        }
    9598
    96         if (!$this->customer) {
    97             $user_id        = get_user_by('email', $this->customer_email)->ID ?? 0;
    98             $this->customer = new \WC_Customer($user_id);
    99         }
    100 
    101         if (!$this->customer->get_id() && !$this->is_guest()) {
     99        if ( ! $this->customer ) {
     100            $user_id        = get_user_by( 'email', $this->customer_email )->ID ?? 0;
     101            $this->customer = new \WC_Customer( $user_id );
     102        }
     103
     104        if ( ! $this->customer->get_id() && ! $this->is_guest() ) {
    102105            return false;
    103106        }
     
    112115     */
    113116    public function accepted_statuses(): array {
    114         return ['Completed'];
     117        return [ 'Completed' ];
    115118    }
    116119
     
    121124     */
    122125    public function get_customer(): array {
    123         if (!$this->customer_email) {
     126        if ( ! $this->customer_email ) {
    124127            return [];
    125128        }
    126129
    127         if (!$this->customer) {
    128             $user_id        = get_user_by('email', $this->customer_email)->ID ?? 0;
    129             $this->customer = new \WC_Customer($user_id);
    130         }
    131 
    132         if (!$this->customer->get_id()) {
     130        if ( ! $this->customer ) {
     131            $user_id        = get_user_by( 'email', $this->customer_email )->ID ?? 0;
     132            $this->customer = new \WC_Customer( $user_id );
     133        }
     134
     135        if ( ! $this->customer->get_id() ) {
    133136            return [];
    134137        }
     
    136139        return [
    137140            'name'          => $this->customer->get_display_name() ?? '',
    138             'registered_at' => date('d M Y', strtotime($this->customer->get_date_created())) ?? '',
     141            'registered_at' => date( 'd M Y', strtotime( $this->customer->get_date_created() ) ) ?? '',
    139142        ];
    140143    }
     
    147150     * @return string
    148151     */
    149     public function get_formated_amount(float $amount): string {
     152    public function get_formated_amount( float $amount ): string {
    150153        return get_woocommerce_currency_symbol() . $amount;
    151154    }
     
    158161     */
    159162    public function get_orders(): array {
    160         if (empty($this->orders) && !$this->isCalled) {
     163        if ( empty( $this->orders ) && ! $this->isCalled ) {
    161164            $query = new WC_Order_Query();
    162             $query->set('customer', $this->customer_email);
     165            $query->set( 'customer', $this->customer_email );
    163166            $customer_orders = $query->get_orders();
    164167            $this->isCalled  = true;
    165168
    166             foreach ($customer_orders as $order) {
    167                 array_push($this->orders, [
     169            foreach ( $customer_orders as $order ) {
     170                array_push( $this->orders, [
    168171                    'order_id'        => $order->get_id(),
    169                     'amount'          => (float) $order->get_total(),
    170                     'amount_formated' => $this->get_formated_amount($order->get_total()),
    171                     'date'            => date('d M Y', strtotime($order->get_date_created())),
    172                     'order_status'    => ucfirst($order->get_status()),
    173                     'shipping'        => $this->shipping_param ? $this->get_shipping_details($order) : [],
    174                     'downloads'       => $this->get_order_items($order),
    175                     'order_url'       => method_exists($order,
    176                         'get_edit_order_url') ? $order->get_edit_order_url() : '#',
    177                 ]);
     172                    'amount'          => $this->get_formated_amount( (float) $order->get_total() ),
     173                    'amount_formated' => $this->get_formated_amount( $order->get_total() ),
     174                    'date'            => date( 'd M Y', strtotime( $order->get_date_created() ) ),
     175                    'order_status'    => ucfirst( $order->get_status() ),
     176                    'shipping'        => $this->shipping_param ? $this->get_shipping_details( $order ) : [],
     177                    'downloads'       => $this->get_order_items( $order ),
     178                    'order_url'       => method_exists( $order,
     179                        'get_edit_order_url' ) ? $order->get_edit_order_url() : '#',
     180                    'coupon'          => $order->get_coupon_codes() ?? null,
     181
     182                ] );
    178183            }
    179184        }
     
    189194     * @return array
    190195     *
     196     * @throws \Exception
    191197     * @since 0.8.4
    192198     */
    193     public function order_status($order_id): array {
    194         if (!$this->is_customer_exist()) {
     199    public function order_status( $order_id ): array {
     200        if ( ! $this->is_customer_exist() ) {
    195201            return [];
    196202        }
    197203
    198         $order = wc_get_order($order_id);
    199 
    200         if (!$order) {
     204        $order = wc_get_order( $order_id );
     205
     206        if ( ! $order ) {
    201207            return [];
    202208        }
     
    205211            'order_id'         => $order->get_id(),
    206212            'amount'           => $order->get_total(),
    207             'amount_formatted' => $this->get_formated_amount($order->get_total()),
    208             'date'             => date('d M Y', strtotime($order->get_date_created())),
    209             'order_status'     => ucfirst($order->get_status()),
    210             'shipping'         => $this->get_shipping_details($order),
    211             'downloads'        => $this->get_order_items($order),
     213            'amount_formatted' => $this->get_formated_amount( $order->get_total() ),
     214            'date'             => date( 'd M Y', strtotime( $order->get_date_created() ) ),
     215            'order_status'     => ucfirst( $order->get_status() ),
     216            'shipping'         => $this->get_shipping_details( $order ),
     217            'downloads'        => $this->get_order_items( $order ),
    212218        ];
    213219    }
     
    221227     * @return array
    222228     */
    223     public function get_shipping_details($order): array {
    224         $states = WC()->countries->get_states($order->get_shipping_country());
    225         $state  = !empty($states[$order->get_shipping_state()]) ? $states[$order->get_shipping_state()] : '';
     229    public function get_shipping_details( $order ): array {
     230        $states = WC()->countries->get_states( $order->get_shipping_country() );
     231        $state  = ! empty( $states[ $order->get_shipping_state() ] ) ? $states[ $order->get_shipping_state() ] : '';
    226232
    227233        $shipping_details = [];
    228234
    229         array_push($shipping_details, [
    230             'street'  => $order->get_shipping_address_1() ?? '',
    231             'city'    => $order->get_shipping_city() ?? '',
    232             'zip'     => $order->get_shipping_postcode() ?? '',
    233             'state'   => $state,
    234             'country' => WC()->countries->countries[$order->get_shipping_country()] ?? '',
    235         ]);
     235        array_push( $shipping_details, [
     236            'street'                    => $order->get_shipping_address_1() . ' ' . ( $order->get_shipping_address_2() ?? '' ),
     237            'city'                      => $order->get_shipping_city() ?? '',
     238            'zip'                       => $order->get_shipping_postcode() ?? '',
     239            'state'                     => $state,
     240            'country'                   => WC()->countries->countries[ $order->get_shipping_country() ] ?? '',
     241            'shipping_address_overview' => $order->get_formatted_shipping_address() ?? '',
     242        ] );
    236243
    237244        return $shipping_details;
     
    245252     * @return bool
    246253     */
    247     public function check_site_url($site_url): bool {
    248         return substr($site_url, 0, 7) === "http://" ||
    249                substr($site_url, 0, 8) === "https://";
     254    public function check_site_url( $site_url ): bool {
     255        return substr( $site_url, 0, 7 ) === "http://" || substr( $site_url, 0, 8 ) === "https://";
    250256    }
    251257
     
    257263     * @return array
    258264     */
    259     public function get_order_items($order): array {
     265    public function get_order_items( $order ): array {
    260266        $items = $order->get_items();
    261267
    262         $download_item = [];
    263         $license_info  = [];
    264 
    265         if (method_exists('WOO_SL_functions', 'get_order_licence_details')) {
    266 
    267             $orderLicenseDetails = \WOO_SL_functions::get_order_licence_details($order->get_id());
    268 
    269             foreach ($orderLicenseDetails as $orderLicenses) {
    270                 foreach ($orderLicenses as $orderLicense) {
     268        $download_item     = [];
     269        $license_info      = [];
     270        $subscription_info = [];
     271
     272        if ( method_exists( 'WOO_SL_functions', 'get_order_licence_details' ) ) {
     273
     274            $orderLicenseDetails = \WOO_SL_functions::get_order_licence_details( $order->get_id() );
     275
     276            foreach ( $orderLicenseDetails as $orderLicenses ) {
     277                foreach ( $orderLicenses as $orderLicense ) {
    271278
    272279                    $license = \WOO_SL_functions::get_order_product_generated_keys(
     
    284291                    $sites = [];
    285292
    286                     $expire_date = intval(\WOO_SL_functions::get_order_item_meta($orderLicense->order_item_id,
    287                         '_woo_sl_licensing_expire_at') ?? '');
    288                     $expire_date = $expire_date == 0 ? '' : date("d M Y", $expire_date);
     293                    $expire_date = intval( \WOO_SL_functions::get_order_item_meta( $orderLicense->order_item_id,
     294                        '_woo_sl_licensing_expire_at' ) ?? '' );
     295                    $expire_date = $expire_date == 0 ? '' : date( "d M Y", $expire_date );
    289296
    290297                    $woo_site_url = '';
    291298
    292                     foreach ($key_instances as $key_instance) {
    293                         if ($key_instance->active_domain) {
    294                             $this->check_site_url($key_instance->active_domain) ?
     299                    foreach ( $key_instances as $key_instance ) {
     300                        if ( $key_instance->active_domain ) {
     301                            $this->check_site_url( $key_instance->active_domain ) ?
    295302                                $woo_site_url = $key_instance->active_domain :
    296303                                $woo_site_url = "http://" . $key_instance->active_domain;
    297                             array_push($sites, $woo_site_url);
     304                            array_push( $sites, $woo_site_url );
    298305                        }
    299306                    }
    300307
    301                     $license_info[$license->order_item_id] = [
     308                    $license_info[ $license->order_item_id ] = [
    302309                        'key'              => $license->licence ?? '',
    303310                        'activation_limit' => $orderLicense->license_data["max_instances_per_key"],
     
    306313                        'expiration'       => $expire_date,
    307314                        'is_lifetime'      => $orderLicense->license_data['product_use_expire'] == 'no',
    308                         'status'           => \WOO_SL_functions::get_licence_key_status($license->id) ?? '',
     315                        'status'           => \WOO_SL_functions::get_licence_key_status( $license->id ) ?? '',
    309316                    ];
    310317                }
    311318            }
    312319        }
    313         foreach ($items as $item) {
    314             if (array_key_exists($item->get_id(), $license_info)) {
    315                 array_push($download_item, [
    316                     "title"             => $item["name"],
    317                     "product_id"        => $item["product_id"],
    318                     "product_permalink" => get_permalink($item["product_id"]),
    319                     "quantity"          => $item["quantity"],
    320                     "total_tax"         => $this->get_formated_amount((float) $item["total_tax"]),
    321                     "price"             => $this->get_formated_amount((float) $item["subtotal"]),
    322                     "license"           => $license_info[$item->get_id()],
    323                 ]);
    324             } else {
    325                 array_push($download_item, [
    326                     "title"             => $item["name"],
    327                     "product_id"        => $item["product_id"],
    328                     "product_permalink" => get_permalink($item["product_id"]),
    329                     "quantity"          => $item["quantity"],
    330                     "total_tax"         => $this->get_formated_amount((float) $item["total_tax"]),
    331                     "price"             => $this->get_formated_amount((float) $item["subtotal"]),
    332                 ]);
     320
     321        foreach ( $items as $item ) {
     322
     323            $product = wc_get_product( $item["product_id"] );
     324
     325            if ( class_exists( 'WC_Subscriptions_Product' ) && WC_Subscriptions_Product::is_subscription( $product ) ) {
     326
     327                $subscription_info = [
     328                    "is_subscription"       => true,
     329                    "period"                => WC_Subscriptions_Product::get_period( $product ),
     330                    "trial_length"          => WC_Subscriptions_Product::get_trial_length( $product ),
     331                    "trial_period"          => WC_Subscriptions_Product::get_trial_period( $product ),
     332                    "trial_expiration_date" => WC_Subscriptions_Product::get_trial_expiration_date( $product ),
     333                    "sign_up_fee"           => WC_Subscriptions_Product::get_sign_up_fee( $product ),
     334                    "expiration_date"       => WC_Subscriptions_Product::get_expiration_date( $product ),
     335                ];
    333336            }
     337
     338            $productInfo = array(
     339                "product_id"        => $item["product_id"],
     340                "title"             => $product->get_name(),
     341                "product_permalink" => get_permalink( $item["product_id"] ),
     342                "quantity"          => $item["quantity"],
     343                "total_tax"         => $this->get_formated_amount( (float) $item["total_tax"] ),
     344                "image"             => wp_get_attachment_image_src( get_post_thumbnail_id( $item["product_id"] ) )[0],
     345                "type"              => $product->get_type(),
     346                "status"            => $product->get_status(),
     347                "sku"               => $product->get_sku(),
     348                "price"             => $this->get_formated_amount( (float) $item["subtotal"] ),
     349                "regular_price"     => $this->get_formated_amount( (float) $product->get_regular_price() ),
     350                "sale_price"        => $this->get_formated_amount( (float) $product->get_sale_price() ),
     351                "tax_status"        => $product->get_tax_status(),
     352                "stock"             => $product->get_stock_quantity(),
     353                "stock_status"      => $product->get_stock_status(),
     354                "weight"            => $product->get_weight(),
     355                "discount"          => $this->get_formated_amount( (float) $item->get_total() ),
     356                "subscription"      => $subscription_info,
     357
     358            );
     359
     360            $subscription_info = [];
     361
     362            if ( array_key_exists( $item->get_id(), $license_info ) ) {
     363                $productInfo['license'] = $license_info[ $item->get_id() ];
     364            }
     365
     366            array_push( $download_item, $productInfo );
    334367        }
    335368
     
    337370    }
    338371
    339     public function get_plugin_data(string $key = '') {
     372    public function get_plugin_data( string $key = '' ) {
    340373        $thrivedesk_options = thrivedesk_options();
    341374
    342375        $options = $thrivedesk_options['woocommerce'] ?? [];
    343376
    344         return $key ? ($options[$key] ?? '') : $options;
     377        return $key ? ( $options[ $key ] ?? '' ) : $options;
    345378    }
    346379
    347380    public function connect() {
    348         $thrivedesk_options                = get_option('thrivedesk_options', []);
     381        $thrivedesk_options                = get_option( 'thrivedesk_options', [] );
    349382        $thrivedesk_options['woocommerce'] = $thrivedesk_options['woocommerce'] ?? [];
    350383
    351384        $thrivedesk_options['woocommerce']['connected'] = true;
    352385
    353         update_option('thrivedesk_options', $thrivedesk_options);
     386        update_option( 'thrivedesk_options', $thrivedesk_options );
    354387    }
    355388
    356389    public function disconnect() {
    357         $thrivedesk_options                = get_option('thrivedesk_options', []);
     390        $thrivedesk_options                = get_option( 'thrivedesk_options', [] );
    358391        $thrivedesk_options['woocommerce'] = $thrivedesk_options['woocommerce'] ?? [];
    359392
     
    363396        ];
    364397
    365         update_option('thrivedesk_options', $thrivedesk_options);
     398        update_option( 'thrivedesk_options', $thrivedesk_options );
    366399    }
    367400}
  • thrivedesk/tags/1.1.0/thrivedesk.php

    r2957963 r2962781  
    66 * Plugin URI:          https://www.thrivedesk.com/?utm_source=wp-plugins&utm_campaign=plugin-uri&utm_medium=wp-dash
    77 * Tags:                live chat, helpdesk, free live chat, knowledge base, thrivedesk
    8  * Version:             1.0.18
     8 * Version:             1.1.0
    99 * Author:              ThriveDesk
    1010 * Author URI:          https://profiles.wordpress.org/thrivedesk/
     
    1414 * Requires PHP:        5.5
    1515 * Requires at least:   4.9
    16  * Tested up to:        6.3
     16 * Tested up to:        6.3.1
    1717 *
    1818 * ThriveDesk is free software: you can redistribute it and/or modify
     
    5050     * @var string
    5151     */
    52     public $version = '1.0.18';
     52    public $version = '1.1.0';
    5353
    5454    /**
  • thrivedesk/trunk/readme.txt

    r2957963 r2962781  
    33Tags: livechat, chat, help desk, chat plugin, free live chat, community, helpdesk, chatbot, knowledge base, support, help center, customer care,  woocommerce, surecart, freemius, thrivedesk, zendesk, mailchimp
    44Requires at least: 4.9
    5 Tested up to: 6.3
    6 Stable Tag: 1.0.18
     5Tested up to: 6.3.1
     6Stable Tag: 1.1.0
    77Requires PHP: 5.5
    88License: GNU General Public License v2.0 or later
     
    224224
    225225== Changelog ==
     226= 1.1.0
     227- Update: Woocommerce Integration V2
     228
    226229= 1.0.18 =
    227230- Fix: Revert pro plan
  • thrivedesk/trunk/src/Abstracts/Plugin.php

    r2839767 r2962781  
    44
    55// Exit if accessed directly.
    6 if (!defined('ABSPATH')) {
     6if ( ! defined( 'ABSPATH' ) ) {
    77    exit;
    88}
     
    6565     * @return mixed
    6666     */
    67     abstract public function get_plugin_data(string $key = '');
     67    abstract public function get_plugin_data( string $key = '' );
    6868
    6969    /**
     
    8888     * @return string
    8989     */
    90     public function get_formated_amount(float $amount): string {
     90    public function get_formated_amount( float $amount ): string {
    9191        return $amount;
    9292    }
     
    106106     * @return array
    107107     */
    108     public function filter_accepted_orders(array $orders): array {
     108    public function filter_accepted_orders( array $orders ): array {
    109109        $accepted_statuses = $this->accepted_statuses() ?? [];
    110110
    111         return array_filter($orders, function ($order) use ($accepted_statuses) {
    112             return in_array($order['order_status'], $accepted_statuses);
    113         });
     111        return array_filter( $orders, function ( $order ) use ( $accepted_statuses ) {
     112            return in_array( $order['order_status'], $accepted_statuses );
     113        } );
    114114    }
    115115
     
    121121     * @return float
    122122     */
    123     public function get_lifetime_order(array $orders): float {
     123    public function get_lifetime_order( array $orders ): float {
    124124        // TODO: Ignore pending or refunded amounts
    125         $amount = array_sum(array_column($orders, 'amount'));
    126 
    127         return $amount;
     125        return array_sum( array_column( $orders, 'amount' ) );
    128126    }
    129127
     
    135133     * @return float
    136134     */
    137     public function get_this_year_order(array $orders): float {
     135    public function get_this_year_order( array $orders ): float {
    138136        // TODO: Ignore pending or refunded amounts
    139         $amount = 0;
    140 
    141         $amount = array_reduce($orders, function ($carry, $item) {
    142             if (strtotime($item['date']) >= strtotime('-1 year')) {
    143                 $carry += $item['amount'];
     137        return array_reduce( $orders, function ( $carry, $item ) {
     138            if ( strtotime( $item['date'] ) >= strtotime( '-1 year' ) ) {
     139                $carry += (float) $item['amount'];
    144140            }
    145141
    146142            return $carry;
    147         }, 0);
    148 
    149         return $amount;
     143        }, 0 );
    150144    }
    151145
     
    160154        $orders = $this->get_orders();
    161155
    162         $accepted_orders = $this->filter_accepted_orders($orders);
     156        $accepted_orders = $this->filter_accepted_orders( $orders );
    163157
    164         $this_year_order = $this->get_this_year_order($accepted_orders);
     158        $this_year_order = $this->get_this_year_order( $accepted_orders );
    165159
    166         $lifetime_order = $this->get_lifetime_order($accepted_orders);
     160        $lifetime_order = $this->get_lifetime_order( $accepted_orders );
    167161
    168         $avg_order = $lifetime_order ? ($lifetime_order / count($accepted_orders)) : 0;
     162        $avg_order = $lifetime_order ? ( $lifetime_order / count( $accepted_orders ) ) : 0;
    169163
    170         $avg_order = number_format((float) $avg_order, 2, '.', '');
     164        $avg_order = number_format( (float) $avg_order, 2, '.', '' );
    171165
    172166        return [
    173             "customer"        => $customer ?? [],
     167            "customer"        => $customer,
    174168            "customer_since"  => $customer['registered_at'] ?? '',
    175             "lifetime_order"  => $this->get_formated_amount($lifetime_order),
    176             "this_year_order" => $this->get_formated_amount($this_year_order),
    177             "avg_order"       => $this->get_formated_amount($avg_order),
     169            "lifetime_order"  => $this->get_formated_amount( $lifetime_order ),
     170            "this_year_order" => $this->get_formated_amount( $this_year_order ),
     171            "avg_order"       => $this->get_formated_amount( $avg_order ),
    178172            "orders"          => $orders,
     173            'add_order'       => admin_url( "post-new.php?post_type=shop_order" ) ?? '',
    179174        ];
    180175    }
  • thrivedesk/trunk/src/Api.php

    r2839767 r2962781  
    44
    55use ThriveDesk\Api\ApiResponse;
     6use WC_Product_Query;
     7use WC_Order;
     8use WC_Order_Item_Product;
    69
    710// Exit if accessed directly.
    8 if (!defined('ABSPATH')) {
     11if ( ! defined( 'ABSPATH' ) ) {
    912    exit;
    1013}
     
    1720
    1821    private $apiResponse;
    19 
    2022    private $plugin = null;
     23    private $order_id = null;
     24    private $order_status = null;
     25    private $quantity = null;
     26    private $item = null;
     27    private $coupon = null;
     28    private $amount = null;
     29    private $reason = null;
     30    private $item_id = null;
    2131
    2232    /**
     
    2737     */
    2838    private function __construct() {
    29         add_action('init', [$this, 'api_listener']);
     39        add_action( 'init', [ $this, 'api_listener' ] );
    3040
    3141        $this->apiResponse = new ApiResponse();
     
    4454     */
    4555    public static function instance(): object {
    46         if (!isset(self::$instance) && !(self::$instance instanceof Admin)) {
     56        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Admin ) ) {
    4757            self::$instance = new self();
    4858        }
     
    7484     */
    7585    public function api_listener(): void {
    76         $listener = sanitize_key($_GET['listener'] ?? '');
    77         if (!isset($listener) || 'thrivedesk' !== $listener) {
     86        $listener = sanitize_key( $_GET['listener'] ?? '' );
     87        if ( ! isset( $listener ) || 'thrivedesk' !== $listener ) {
    7888            return;
    7989        }
    8090
    8191        try {
    82             $action = strtolower(sanitize_key($_GET['action'] ?? ''));
    83             $plugin = strtolower(sanitize_key($_GET['plugin'] ?? 'edd'));
     92            $action = strtolower( sanitize_key( $_GET['action'] ?? '' ) );
     93            $plugin = strtolower( sanitize_key( $_GET['plugin'] ?? 'edd' ) );
     94
     95            $this->order_id     = sanitize_key( $_GET['order_id'] ?? '' );
     96            $this->order_status = sanitize_key( $_GET['order_status'] ?? '' );
     97            $this->quantity     = sanitize_key( $_GET['quantity'] ?? '' );
     98            $this->item         = sanitize_key( $_GET['item'] ?? '' );
     99            $this->item_id      = sanitize_key( $_GET['item_id'] ?? '' );
     100            $this->coupon       = sanitize_key( $_GET['coupon'] ?? '' );
     101            $this->amount       = sanitize_key( $_GET['amount'] ?? '' );
     102            $this->reason       = sanitize_key( $_GET['reason'] ?? '' );
    84103
    85104            // Plugin invalid response
    86             if (!in_array($plugin, array_keys($this->_available_plugins()))) {
    87                 $this->apiResponse->error(401, 'Plugin is invalid or not available now.');
    88             }
    89 
    90             $plugin_name       = $this->_available_plugins()[$plugin] ?? 'EDD';
     105            if ( ! in_array( $plugin, array_keys( $this->_available_plugins() ) ) ) {
     106                $this->apiResponse->error( 401, 'Plugin is invalid or not available now.' );
     107            }
     108
     109            $plugin_name       = $this->_available_plugins()[ $plugin ] ?? 'EDD';
    91110            $plugin_class_name = 'ThriveDesk\\Plugins\\' . $plugin_name;
    92111
    93             if (!class_exists($plugin_class_name)) {
    94                 $this->apiResponse->error(500, "Class not found for the '{$plugin_name}' plugin");
     112            if ( ! class_exists( $plugin_class_name ) ) {
     113                $this->apiResponse->error( 500, "Class not found for the '{$plugin_name}' plugin" );
    95114            }
    96115
    97116            $this->plugin = $plugin_class_name::instance();
    98117
    99             if (!method_exists($this->plugin, 'is_plugin_active')) {
    100                 $this->apiResponse->error(500, "Method 'prepare_data' not exist in class '{$plugin_class_name}'");
    101             }
    102 
    103             if (!$this->plugin->is_plugin_active()) {
    104                 $this->apiResponse->error(500, "The plugin '{$plugin_name}' isn't installed or active.");
    105             }
    106 
    107             if (!$this->verify_token()) {
    108                 $this->apiResponse->error(401, 'Request unauthorized');
    109             }
    110 
    111             if (isset($action) && 'connect' === $action) {
     118            if ( ! method_exists( $this->plugin, 'is_plugin_active' ) ) {
     119                $this->apiResponse->error( 500, "Method 'prepare_data' not exist in class '{$plugin_class_name}'" );
     120            }
     121
     122            if ( ! $this->plugin->is_plugin_active() ) {
     123                $this->apiResponse->error( 500, "The plugin '{$plugin_name}' isn't installed or active." );
     124            }
     125
     126            if ( ! $this->verify_token() ) {
     127                $this->apiResponse->error( 401, 'Request unauthorized' );
     128            }
     129
     130            if ( isset( $action ) && 'connect' === $action ) {
    112131                $this->connect_action_handler();
    113             } elseif (isset($action) && 'disconnect' === $action) {
     132            } elseif ( isset( $action ) && 'disconnect' === $action ) {
    114133                $this->disconnect_action_handler();
    115             } elseif (isset($action) && 'get_fluentcrm_data' === $action) {
     134            } elseif ( isset( $action ) && 'get_fluentcrm_data' === $action ) {
    116135                $this->fluentcrm_handler();
    117             } elseif (isset($action) && 'handle_autonami' === $action) {
     136            } elseif ( isset( $action ) && 'handle_autonami' === $action ) {
    118137                $this->autonami_handler();
    119             } elseif (isset($action) && 'get_wppostsync_data' === $action) {
    120                 $remote_query_string = strtolower($_GET['query'] ?? '');
    121                 $this->wp_postsync_data_handler($remote_query_string);
    122             } elseif (isset($action) && 'get_woocommerce_order_status' === $action) {
     138            } elseif ( isset( $action ) && 'get_wppostsync_data' === $action ) {
     139                $remote_query_string = strtolower( $_GET['query'] ?? '' );
     140                $this->wp_postsync_data_handler( $remote_query_string );
     141            } elseif ( isset( $action ) && 'get_woocommerce_product_list' === $action ) {
     142                $this->get_woocommerce_product_list();
     143            } elseif ( isset( $action ) && 'get_woocommerce_order_status' === $action ) {
    123144                $this->get_woocommerce_order_status();
     145            } elseif ( isset( $action ) && 'get_woocommerce_order_status_list' === $action ) {
     146                $this->get_woocommerce_status_list();
     147            } elseif ( isset( $action ) && 'woocommerce_order_status_update' === $action ) {
     148                $this->woocommerce_order_status_update( $this->order_id, $this->order_status );
     149            } elseif ( isset( $action ) && 'woocommerce_order_quantity_update' === $action ) {
     150                $this->woocommerce_order_quantity_update( $this->order_id, $this->item_id, $this->quantity );
     151            } elseif ( isset( $action ) && 'woocommerce_order_apply_coupon' === $action ) {
     152                $this->woocommerce_order_apply_coupon( $this->order_id, $this->coupon );
     153            } elseif ( isset( $action ) && 'add_item_on_woocommerce_order' === $action ) {
     154                $this->wc_order_add_new_item( $this->order_id, $this->item );
     155            } elseif ( isset( $action ) && 'remove_item_from_woocommerce_order' === $action ) {
     156                $this->wc_order_remove_item( $this->order_id, $this->item );
    124157            } else {
    125158                $this->plugin_data_action_handler();
    126159            }
    127         } catch (\Exception $e) {
    128             $this->apiResponse->error(500, 'Can\'t not prepare data');
     160        } catch ( \Exception $e ) {
     161            $this->apiResponse->error( 500, 'Can\'t not prepare data' );
    129162        }
    130163
     
    136169     */
    137170    public function autonami_handler() {
    138         $syncType                     = strtolower(sanitize_key($_REQUEST['sync_type'] ?? ''));
    139         $this->plugin->customer_email = sanitize_email($_GET['email'] ?? '');
    140 
    141         if ($syncType) {
    142             $this->plugin->sync_conversation_with_autonami($syncType, $_REQUEST['extra'] ?? []);
     171        $syncType                     = strtolower( sanitize_key( $_REQUEST['sync_type'] ?? '' ) );
     172        $this->plugin->customer_email = sanitize_email( $_GET['email'] ?? '' );
     173
     174        if ( $syncType ) {
     175            $this->plugin->sync_conversation_with_autonami( $syncType, $_REQUEST['extra'] ?? [] );
    143176        } else {
    144             if (!method_exists($this->plugin, 'prepare_data')) {
    145                 $this->apiResponse->error(500, "Method 'prepare_data' not exist in plugin");
    146             }
    147 
    148             if (!$this->plugin->is_customer_exist()) {
    149                 $this->apiResponse->error(404, "Customer not found.");
     177            if ( ! method_exists( $this->plugin, 'prepare_data' ) ) {
     178                $this->apiResponse->error( 500, "Method 'prepare_data' not exist in plugin" );
     179            }
     180
     181            if ( ! $this->plugin->is_customer_exist() ) {
     182                $this->apiResponse->error( 404, "Customer not found." );
    150183            }
    151184
    152185            $data = $this->plugin->prepare_data();
    153186
    154             $this->apiResponse->success(200, $data, 'Success');
     187            $this->apiResponse->success( 200, $data, 'Success' );
    155188        }
    156189    }
     
    162195     */
    163196    public function get_woocommerce_order_status() {
    164         $email    = sanitize_email($_REQUEST['email'] ?? '');
    165         $order_id = strtolower(sanitize_key($_REQUEST['order_id'] ?? ''));
    166 
    167         if (!method_exists($this->plugin, 'order_status')) {
    168             $this->apiResponse->error(500, "Method 'order_status' not exist in plugin");
     197        $email    = sanitize_email( $_REQUEST['email'] ?? '' );
     198        $order_id = strtolower( sanitize_key( $_REQUEST['order_id'] ?? '' ) );
     199
     200        if ( ! method_exists( $this->plugin, 'order_status' ) ) {
     201            $this->apiResponse->error( 500, "Method 'order_status' not exist in plugin" );
    169202        }
    170203
    171204        $this->plugin->customer_email = $email;
    172205
    173         if (!$this->plugin->is_customer_exist()) {
    174             $this->apiResponse->error(404, "Customer not found.");
    175         }
    176 
    177         $data = $this->plugin->order_status($order_id);
    178 
    179         $this->apiResponse->success(200, $data, 'Success');
     206        if ( ! $this->plugin->is_customer_exist() ) {
     207            $this->apiResponse->error( 404, "Customer not found." );
     208        }
     209
     210        $data = $this->plugin->order_status( $order_id );
     211
     212        $this->apiResponse->success( 200, $data, 'Success' );
     213    }
     214
     215    /**
     216     * @return void
     217     */
     218    public function get_woocommerce_product_list() {
     219
     220        $query = new WC_Product_Query( array(
     221            'status' => 'publish',
     222            'return' => 'ids',
     223        ) );
     224
     225        $products    = $query->get_products();
     226        $productList = [];
     227
     228        foreach ( $products as $product_id ) {
     229            $product = wc_get_product( $product_id );
     230
     231            $productInfo = array(
     232                "product_id"        => $product_id,
     233                "title"             => $product->get_name(),
     234                "product_permalink" => get_permalink( $product_id ),
     235                "image"             => wp_get_attachment_image_src( get_post_thumbnail_id( $product_id ) )[0],
     236                "sale_price"        => get_woocommerce_currency_symbol() . $product->get_regular_price(),
     237                "stock"             => ( 'instock' === $product->get_stock_status() ) ? 'In Stock' : 'Out of Stock',
     238            );
     239
     240            array_push( $productList, $productInfo );
     241        }
     242
     243        $data = $productList;
     244
     245        $this->apiResponse->success( 200, $data, 'Success' );
     246    }
     247
     248    /**
     249     * @return void
     250     */
     251    public function get_woocommerce_status_list() {
     252
     253        $statuses = wc_get_order_statuses();
     254
     255        $this->apiResponse->success( 200, $statuses, 'Success' );
     256    }
     257
     258    /**
     259     * @param $order_id
     260     * @param $item
     261     *
     262     * @return void
     263     */
     264    public function wc_order_add_new_item( string $order_id, $item ) {
     265        $product = wc_get_product_object( 'line_item', $item );
     266
     267        $item = new WC_Order_Item_Product();
     268        $item->set_name( $product->name );
     269        $item->set_quantity( $this->quantity );
     270        $item->set_product_id( $product->id );
     271        $item->set_subtotal( $product->price ?? 0 );
     272        $item->set_total( $product->price * $this->quantity ?? 0 );
     273        $order = wc_get_order( $order_id );
     274        $order->add_item( $item );
     275        $order->calculate_totals();
     276
     277        $this->apiResponse->success( 200, [], 'Success' );
     278    }
     279
     280    /**
     281     * @param $order_id
     282     * @param $product_id
     283     *
     284     * @return void
     285     */
     286    public function wc_order_remove_item( string $order_id, string $product_id ) {
     287        $order = wc_get_order( $order_id );
     288
     289        foreach ( $order->get_items() as $item_id => $item ) {
     290            if ( $item["product_id"] == $product_id ) {
     291                wc_delete_order_item( $item_id );
     292            }
     293        }
     294
     295        $order->calculate_totals();
     296
     297        $this->apiResponse->success( 200, [], 'Success' );
     298    }
     299
     300
     301    /**
     302     * @param $order_id
     303     * @param $orderStatus
     304     *
     305     * @return void
     306     */
     307    public function woocommerce_order_status_update( string $order_id, string $orderStatus ) {
     308        $order = new WC_Order( $order_id );
     309        $order->update_status( $orderStatus, '' );
     310
     311        $this->apiResponse->success( 200, [], 'Success' );
     312    }
     313
     314    /**
     315     * @param $order_id
     316     * @param $product_id
     317     * @param $quantity
     318     *
     319     * @return void
     320     */
     321    public function woocommerce_order_quantity_update( string $order_id, string $product_id, string $quantity ) {
     322
     323        $order = wc_get_order( $order_id );
     324        if ( $quantity > 0 ) {
     325            foreach ( $order->get_items() as $item_id => $item ) {
     326
     327                if ( $item["product_id"] == (string) $product_id ) {
     328                    wc_update_order_item_meta( $item_id, '_qty', $quantity );
     329                    $order->calculate_totals();
     330                }
     331            }
     332            $this->apiResponse->success( 200, [], 'Success' );
     333        }
     334    }
     335
     336    /**
     337     * @param $order_id
     338     * @param $coupon
     339     *
     340     * @return void
     341     */
     342    public function woocommerce_order_apply_coupon( string $order_id, string $coupon ) {
     343        $order = wc_get_order( $order_id );
     344
     345        if ( $coupon ) {
     346            $res = $order->apply_coupon( $coupon );
     347            if ( isset( $res->errors ) ) {
     348                $this->apiResponse->error( 404, "Coupon does not exist!." );
     349            } else {
     350                $this->apiResponse->success( 200, [], 'Success' );
     351            }
     352        }
     353
    180354    }
    181355
     
    187361     */
    188362    public function fluentcrm_handler(): void {
    189         $syncType                     = strtolower(sanitize_key($_REQUEST['sync_type'] ?? ''));
    190         $this->plugin->customer_email = sanitize_email($_REQUEST['email'] ?? '');
    191 
    192         if ($syncType) {
    193             $this->plugin->sync_conversation_with_fluentcrm($syncType, $_REQUEST['extra'] ?? []);
     363        $syncType                     = strtolower( sanitize_key( $_REQUEST['sync_type'] ?? '' ) );
     364        $this->plugin->customer_email = sanitize_email( $_REQUEST['email'] ?? '' );
     365
     366        if ( $syncType ) {
     367            $this->plugin->sync_conversation_with_fluentcrm( $syncType, $_REQUEST['extra'] ?? [] );
    194368        } else {
    195             if (!method_exists($this->plugin, 'prepare_fluentcrm_data')) {
    196                 $this->apiResponse->error(500, "Method 'prepare_fluentcrm_data' not exist in plugin");
    197             }
    198 
    199             if (!$this->plugin->is_customer_exist()) {
    200                 $this->apiResponse->error(404, "Customer not found.");
     369            if ( ! method_exists( $this->plugin, 'prepare_fluentcrm_data' ) ) {
     370                $this->apiResponse->error( 500, "Method 'prepare_fluentcrm_data' not exist in plugin" );
     371            }
     372
     373            if ( ! $this->plugin->is_customer_exist() ) {
     374                $this->apiResponse->error( 404, "Customer not found." );
    201375            }
    202376            $data = $this->plugin->prepare_fluentcrm_data();
    203377
    204             $this->apiResponse->success(200, $data, 'Success');
     378            $this->apiResponse->success( 200, $data, 'Success' );
    205379        }
    206380    }
     
    213387     * @since 0.8.0
    214388     */
    215     public function wp_postsync_data_handler($remote_query_string): void {
    216         $search_data = $this->plugin->get_post_search_result($remote_query_string);
    217         $this->apiResponse->success(200, $search_data, 'Success');
     389    public function wp_postsync_data_handler( $remote_query_string ): void {
     390        $search_data = $this->plugin->get_post_search_result( $remote_query_string );
     391
     392        $this->apiResponse->success( 200, $search_data, 'Success' );
    218393    }
    219394
     
    227402        $this->plugin->connect();
    228403
    229         $this->apiResponse->success(200, [], 'Site connected successfully');
     404        $this->apiResponse->success( 200, [], 'Site connected successfully' );
    230405    }
    231406
     
    239414        $this->plugin->disconnect();
    240415
    241         $this->apiResponse->success(200, [], 'Site has been disconnected');
     416        $this->apiResponse->success( 200, [], 'Site has been disconnected' );
    242417    }
    243418
     
    249424     */
    250425    public function plugin_data_action_handler() {
    251         $email          = sanitize_email($_REQUEST['email'] ?? '');
     426
     427        $email          = sanitize_email( $_REQUEST['email'] ?? '' );
    252428        $enableShipping = $_REQUEST['shipping_param'] == 1 ? true : false;
    253429
    254         if (!method_exists($this->plugin, 'prepare_data')) {
    255             $this->apiResponse->error(500, "Method 'prepare_data' not exist in plugin");
     430        if ( ! method_exists( $this->plugin, 'prepare_data' ) ) {
     431            $this->apiResponse->error( 500, "Method 'prepare_data' not exist in plugin" );
    256432        }
    257433
     
    259435        $this->plugin->shipping_param = $enableShipping;
    260436
    261         if (!$this->plugin->is_customer_exist()) {
    262             $this->apiResponse->error(404, "Customer not found.");
     437        if ( ! $this->plugin->is_customer_exist() ) {
     438            $this->apiResponse->error( 404, "Customer not found." );
    263439        }
    264440
    265441        $data = $this->plugin->prepare_data();
    266442
    267         $this->apiResponse->success(200, $data, 'Success');
     443        $this->apiResponse->success( 200, $data, 'Success' );
    268444    }
    269445
     
    277453        $payload = $_REQUEST;
    278454
    279         if ($payload) {
    280             foreach ($payload as $key => $value) {
    281                 if (!is_string($value)) {
     455        if ( $payload ) {
     456            foreach ( $payload as $key => $value ) {
     457                if ( ! is_string( $value ) ) {
    282458                    continue;
    283459                }
    284                 switch (strtolower($value)) {
    285                     case "1":
     460                switch ( strtolower( $value ) ) {
    286461                    case "true":
    287                         $payload[$key] = true;
     462                        $payload[ $key ] = true;
    288463                        break;
    289464
    290                     case "0":
    291465                    case "false":
    292                         $payload[$key] = false;
     466                        $payload[ $key ] = false;
    293467                        break;
    294468                }
     
    296470        }
    297471
    298         $api_token = $this->plugin->get_plugin_data('api_token');
     472        $api_token = $this->plugin->get_plugin_data( 'api_token' );
    299473
    300474        $signature = $_SERVER['HTTP_X_TD_SIGNATURE'];
    301475
    302         return hash_equals($signature, hash_hmac('SHA1', json_encode($payload), $api_token));
     476        return hash_equals( $signature, hash_hmac( 'SHA1', json_encode( $payload ), $api_token ) );
    303477    }
    304478}
  • thrivedesk/trunk/src/Plugins/WooCommerce.php

    r2839767 r2962781  
    55use ThriveDesk\Plugin;
    66use WC_Order_Query;
     7use WC_Subscriptions_Product;
    78
    89// Exit if accessed directly.
    9 if (!defined('ABSPATH')) {
     10if ( ! defined( 'ABSPATH' ) ) {
    1011    exit;
    1112}
     
    4849     */
    4950    public static function instance() {
    50         if (!isset(self::$instance) && !(self::$instance instanceof WooCommerce)) {
     51        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WooCommerce ) ) {
    5152            self::$instance = new self();
    5253        }
     
    6162     */
    6263    public static function is_plugin_active(): bool {
    63         if (!function_exists('WC') || !class_exists('WooCommerce', false)) {
     64        if ( ! function_exists( 'WC' ) || ! class_exists( 'WooCommerce', false ) ) {
    6465            return false;
    6566        }
     
    7273     *
    7374     * @return boolean
     75     * @throws \Exception
    7476     */
    7577    public function is_guest() {
    76         if (empty($this->orders)) {
     78        if ( empty( $this->orders ) ) {
    7779            $this->orders = $this->get_orders();
    7880        }
    79         if (!empty($this->orders)) {
     81        if ( ! empty( $this->orders ) ) {
    8082            return true;
    8183        }
     
    8890     *
    8991     * @return boolean
     92     * @throws \Exception
    9093     */
    9194    public function is_customer_exist(): bool {
    92         if (!$this->customer_email) {
     95        if ( ! $this->customer_email ) {
    9396            return false;
    9497        }
    9598
    96         if (!$this->customer) {
    97             $user_id        = get_user_by('email', $this->customer_email)->ID ?? 0;
    98             $this->customer = new \WC_Customer($user_id);
    99         }
    100 
    101         if (!$this->customer->get_id() && !$this->is_guest()) {
     99        if ( ! $this->customer ) {
     100            $user_id        = get_user_by( 'email', $this->customer_email )->ID ?? 0;
     101            $this->customer = new \WC_Customer( $user_id );
     102        }
     103
     104        if ( ! $this->customer->get_id() && ! $this->is_guest() ) {
    102105            return false;
    103106        }
     
    112115     */
    113116    public function accepted_statuses(): array {
    114         return ['Completed'];
     117        return [ 'Completed' ];
    115118    }
    116119
     
    121124     */
    122125    public function get_customer(): array {
    123         if (!$this->customer_email) {
     126        if ( ! $this->customer_email ) {
    124127            return [];
    125128        }
    126129
    127         if (!$this->customer) {
    128             $user_id        = get_user_by('email', $this->customer_email)->ID ?? 0;
    129             $this->customer = new \WC_Customer($user_id);
    130         }
    131 
    132         if (!$this->customer->get_id()) {
     130        if ( ! $this->customer ) {
     131            $user_id        = get_user_by( 'email', $this->customer_email )->ID ?? 0;
     132            $this->customer = new \WC_Customer( $user_id );
     133        }
     134
     135        if ( ! $this->customer->get_id() ) {
    133136            return [];
    134137        }
     
    136139        return [
    137140            'name'          => $this->customer->get_display_name() ?? '',
    138             'registered_at' => date('d M Y', strtotime($this->customer->get_date_created())) ?? '',
     141            'registered_at' => date( 'd M Y', strtotime( $this->customer->get_date_created() ) ) ?? '',
    139142        ];
    140143    }
     
    147150     * @return string
    148151     */
    149     public function get_formated_amount(float $amount): string {
     152    public function get_formated_amount( float $amount ): string {
    150153        return get_woocommerce_currency_symbol() . $amount;
    151154    }
     
    158161     */
    159162    public function get_orders(): array {
    160         if (empty($this->orders) && !$this->isCalled) {
     163        if ( empty( $this->orders ) && ! $this->isCalled ) {
    161164            $query = new WC_Order_Query();
    162             $query->set('customer', $this->customer_email);
     165            $query->set( 'customer', $this->customer_email );
    163166            $customer_orders = $query->get_orders();
    164167            $this->isCalled  = true;
    165168
    166             foreach ($customer_orders as $order) {
    167                 array_push($this->orders, [
     169            foreach ( $customer_orders as $order ) {
     170                array_push( $this->orders, [
    168171                    'order_id'        => $order->get_id(),
    169                     'amount'          => (float) $order->get_total(),
    170                     'amount_formated' => $this->get_formated_amount($order->get_total()),
    171                     'date'            => date('d M Y', strtotime($order->get_date_created())),
    172                     'order_status'    => ucfirst($order->get_status()),
    173                     'shipping'        => $this->shipping_param ? $this->get_shipping_details($order) : [],
    174                     'downloads'       => $this->get_order_items($order),
    175                     'order_url'       => method_exists($order,
    176                         'get_edit_order_url') ? $order->get_edit_order_url() : '#',
    177                 ]);
     172                    'amount'          => $this->get_formated_amount( (float) $order->get_total() ),
     173                    'amount_formated' => $this->get_formated_amount( $order->get_total() ),
     174                    'date'            => date( 'd M Y', strtotime( $order->get_date_created() ) ),
     175                    'order_status'    => ucfirst( $order->get_status() ),
     176                    'shipping'        => $this->shipping_param ? $this->get_shipping_details( $order ) : [],
     177                    'downloads'       => $this->get_order_items( $order ),
     178                    'order_url'       => method_exists( $order,
     179                        'get_edit_order_url' ) ? $order->get_edit_order_url() : '#',
     180                    'coupon'          => $order->get_coupon_codes() ?? null,
     181
     182                ] );
    178183            }
    179184        }
     
    189194     * @return array
    190195     *
     196     * @throws \Exception
    191197     * @since 0.8.4
    192198     */
    193     public function order_status($order_id): array {
    194         if (!$this->is_customer_exist()) {
     199    public function order_status( $order_id ): array {
     200        if ( ! $this->is_customer_exist() ) {
    195201            return [];
    196202        }
    197203
    198         $order = wc_get_order($order_id);
    199 
    200         if (!$order) {
     204        $order = wc_get_order( $order_id );
     205
     206        if ( ! $order ) {
    201207            return [];
    202208        }
     
    205211            'order_id'         => $order->get_id(),
    206212            'amount'           => $order->get_total(),
    207             'amount_formatted' => $this->get_formated_amount($order->get_total()),
    208             'date'             => date('d M Y', strtotime($order->get_date_created())),
    209             'order_status'     => ucfirst($order->get_status()),
    210             'shipping'         => $this->get_shipping_details($order),
    211             'downloads'        => $this->get_order_items($order),
     213            'amount_formatted' => $this->get_formated_amount( $order->get_total() ),
     214            'date'             => date( 'd M Y', strtotime( $order->get_date_created() ) ),
     215            'order_status'     => ucfirst( $order->get_status() ),
     216            'shipping'         => $this->get_shipping_details( $order ),
     217            'downloads'        => $this->get_order_items( $order ),
    212218        ];
    213219    }
     
    221227     * @return array
    222228     */
    223     public function get_shipping_details($order): array {
    224         $states = WC()->countries->get_states($order->get_shipping_country());
    225         $state  = !empty($states[$order->get_shipping_state()]) ? $states[$order->get_shipping_state()] : '';
     229    public function get_shipping_details( $order ): array {
     230        $states = WC()->countries->get_states( $order->get_shipping_country() );
     231        $state  = ! empty( $states[ $order->get_shipping_state() ] ) ? $states[ $order->get_shipping_state() ] : '';
    226232
    227233        $shipping_details = [];
    228234
    229         array_push($shipping_details, [
    230             'street'  => $order->get_shipping_address_1() ?? '',
    231             'city'    => $order->get_shipping_city() ?? '',
    232             'zip'     => $order->get_shipping_postcode() ?? '',
    233             'state'   => $state,
    234             'country' => WC()->countries->countries[$order->get_shipping_country()] ?? '',
    235         ]);
     235        array_push( $shipping_details, [
     236            'street'                    => $order->get_shipping_address_1() . ' ' . ( $order->get_shipping_address_2() ?? '' ),
     237            'city'                      => $order->get_shipping_city() ?? '',
     238            'zip'                       => $order->get_shipping_postcode() ?? '',
     239            'state'                     => $state,
     240            'country'                   => WC()->countries->countries[ $order->get_shipping_country() ] ?? '',
     241            'shipping_address_overview' => $order->get_formatted_shipping_address() ?? '',
     242        ] );
    236243
    237244        return $shipping_details;
     
    245252     * @return bool
    246253     */
    247     public function check_site_url($site_url): bool {
    248         return substr($site_url, 0, 7) === "http://" ||
    249                substr($site_url, 0, 8) === "https://";
     254    public function check_site_url( $site_url ): bool {
     255        return substr( $site_url, 0, 7 ) === "http://" || substr( $site_url, 0, 8 ) === "https://";
    250256    }
    251257
     
    257263     * @return array
    258264     */
    259     public function get_order_items($order): array {
     265    public function get_order_items( $order ): array {
    260266        $items = $order->get_items();
    261267
    262         $download_item = [];
    263         $license_info  = [];
    264 
    265         if (method_exists('WOO_SL_functions', 'get_order_licence_details')) {
    266 
    267             $orderLicenseDetails = \WOO_SL_functions::get_order_licence_details($order->get_id());
    268 
    269             foreach ($orderLicenseDetails as $orderLicenses) {
    270                 foreach ($orderLicenses as $orderLicense) {
     268        $download_item     = [];
     269        $license_info      = [];
     270        $subscription_info = [];
     271
     272        if ( method_exists( 'WOO_SL_functions', 'get_order_licence_details' ) ) {
     273
     274            $orderLicenseDetails = \WOO_SL_functions::get_order_licence_details( $order->get_id() );
     275
     276            foreach ( $orderLicenseDetails as $orderLicenses ) {
     277                foreach ( $orderLicenses as $orderLicense ) {
    271278
    272279                    $license = \WOO_SL_functions::get_order_product_generated_keys(
     
    284291                    $sites = [];
    285292
    286                     $expire_date = intval(\WOO_SL_functions::get_order_item_meta($orderLicense->order_item_id,
    287                         '_woo_sl_licensing_expire_at') ?? '');
    288                     $expire_date = $expire_date == 0 ? '' : date("d M Y", $expire_date);
     293                    $expire_date = intval( \WOO_SL_functions::get_order_item_meta( $orderLicense->order_item_id,
     294                        '_woo_sl_licensing_expire_at' ) ?? '' );
     295                    $expire_date = $expire_date == 0 ? '' : date( "d M Y", $expire_date );
    289296
    290297                    $woo_site_url = '';
    291298
    292                     foreach ($key_instances as $key_instance) {
    293                         if ($key_instance->active_domain) {
    294                             $this->check_site_url($key_instance->active_domain) ?
     299                    foreach ( $key_instances as $key_instance ) {
     300                        if ( $key_instance->active_domain ) {
     301                            $this->check_site_url( $key_instance->active_domain ) ?
    295302                                $woo_site_url = $key_instance->active_domain :
    296303                                $woo_site_url = "http://" . $key_instance->active_domain;
    297                             array_push($sites, $woo_site_url);
     304                            array_push( $sites, $woo_site_url );
    298305                        }
    299306                    }
    300307
    301                     $license_info[$license->order_item_id] = [
     308                    $license_info[ $license->order_item_id ] = [
    302309                        'key'              => $license->licence ?? '',
    303310                        'activation_limit' => $orderLicense->license_data["max_instances_per_key"],
     
    306313                        'expiration'       => $expire_date,
    307314                        'is_lifetime'      => $orderLicense->license_data['product_use_expire'] == 'no',
    308                         'status'           => \WOO_SL_functions::get_licence_key_status($license->id) ?? '',
     315                        'status'           => \WOO_SL_functions::get_licence_key_status( $license->id ) ?? '',
    309316                    ];
    310317                }
    311318            }
    312319        }
    313         foreach ($items as $item) {
    314             if (array_key_exists($item->get_id(), $license_info)) {
    315                 array_push($download_item, [
    316                     "title"             => $item["name"],
    317                     "product_id"        => $item["product_id"],
    318                     "product_permalink" => get_permalink($item["product_id"]),
    319                     "quantity"          => $item["quantity"],
    320                     "total_tax"         => $this->get_formated_amount((float) $item["total_tax"]),
    321                     "price"             => $this->get_formated_amount((float) $item["subtotal"]),
    322                     "license"           => $license_info[$item->get_id()],
    323                 ]);
    324             } else {
    325                 array_push($download_item, [
    326                     "title"             => $item["name"],
    327                     "product_id"        => $item["product_id"],
    328                     "product_permalink" => get_permalink($item["product_id"]),
    329                     "quantity"          => $item["quantity"],
    330                     "total_tax"         => $this->get_formated_amount((float) $item["total_tax"]),
    331                     "price"             => $this->get_formated_amount((float) $item["subtotal"]),
    332                 ]);
     320
     321        foreach ( $items as $item ) {
     322
     323            $product = wc_get_product( $item["product_id"] );
     324
     325            if ( class_exists( 'WC_Subscriptions_Product' ) && WC_Subscriptions_Product::is_subscription( $product ) ) {
     326
     327                $subscription_info = [
     328                    "is_subscription"       => true,
     329                    "period"                => WC_Subscriptions_Product::get_period( $product ),
     330                    "trial_length"          => WC_Subscriptions_Product::get_trial_length( $product ),
     331                    "trial_period"          => WC_Subscriptions_Product::get_trial_period( $product ),
     332                    "trial_expiration_date" => WC_Subscriptions_Product::get_trial_expiration_date( $product ),
     333                    "sign_up_fee"           => WC_Subscriptions_Product::get_sign_up_fee( $product ),
     334                    "expiration_date"       => WC_Subscriptions_Product::get_expiration_date( $product ),
     335                ];
    333336            }
     337
     338            $productInfo = array(
     339                "product_id"        => $item["product_id"],
     340                "title"             => $product->get_name(),
     341                "product_permalink" => get_permalink( $item["product_id"] ),
     342                "quantity"          => $item["quantity"],
     343                "total_tax"         => $this->get_formated_amount( (float) $item["total_tax"] ),
     344                "image"             => wp_get_attachment_image_src( get_post_thumbnail_id( $item["product_id"] ) )[0],
     345                "type"              => $product->get_type(),
     346                "status"            => $product->get_status(),
     347                "sku"               => $product->get_sku(),
     348                "price"             => $this->get_formated_amount( (float) $item["subtotal"] ),
     349                "regular_price"     => $this->get_formated_amount( (float) $product->get_regular_price() ),
     350                "sale_price"        => $this->get_formated_amount( (float) $product->get_sale_price() ),
     351                "tax_status"        => $product->get_tax_status(),
     352                "stock"             => $product->get_stock_quantity(),
     353                "stock_status"      => $product->get_stock_status(),
     354                "weight"            => $product->get_weight(),
     355                "discount"          => $this->get_formated_amount( (float) $item->get_total() ),
     356                "subscription"      => $subscription_info,
     357
     358            );
     359
     360            $subscription_info = [];
     361
     362            if ( array_key_exists( $item->get_id(), $license_info ) ) {
     363                $productInfo['license'] = $license_info[ $item->get_id() ];
     364            }
     365
     366            array_push( $download_item, $productInfo );
    334367        }
    335368
     
    337370    }
    338371
    339     public function get_plugin_data(string $key = '') {
     372    public function get_plugin_data( string $key = '' ) {
    340373        $thrivedesk_options = thrivedesk_options();
    341374
    342375        $options = $thrivedesk_options['woocommerce'] ?? [];
    343376
    344         return $key ? ($options[$key] ?? '') : $options;
     377        return $key ? ( $options[ $key ] ?? '' ) : $options;
    345378    }
    346379
    347380    public function connect() {
    348         $thrivedesk_options                = get_option('thrivedesk_options', []);
     381        $thrivedesk_options                = get_option( 'thrivedesk_options', [] );
    349382        $thrivedesk_options['woocommerce'] = $thrivedesk_options['woocommerce'] ?? [];
    350383
    351384        $thrivedesk_options['woocommerce']['connected'] = true;
    352385
    353         update_option('thrivedesk_options', $thrivedesk_options);
     386        update_option( 'thrivedesk_options', $thrivedesk_options );
    354387    }
    355388
    356389    public function disconnect() {
    357         $thrivedesk_options                = get_option('thrivedesk_options', []);
     390        $thrivedesk_options                = get_option( 'thrivedesk_options', [] );
    358391        $thrivedesk_options['woocommerce'] = $thrivedesk_options['woocommerce'] ?? [];
    359392
     
    363396        ];
    364397
    365         update_option('thrivedesk_options', $thrivedesk_options);
     398        update_option( 'thrivedesk_options', $thrivedesk_options );
    366399    }
    367400}
  • thrivedesk/trunk/thrivedesk.php

    r2957963 r2962781  
    66 * Plugin URI:          https://www.thrivedesk.com/?utm_source=wp-plugins&utm_campaign=plugin-uri&utm_medium=wp-dash
    77 * Tags:                live chat, helpdesk, free live chat, knowledge base, thrivedesk
    8  * Version:             1.0.18
     8 * Version:             1.1.0
    99 * Author:              ThriveDesk
    1010 * Author URI:          https://profiles.wordpress.org/thrivedesk/
     
    1414 * Requires PHP:        5.5
    1515 * Requires at least:   4.9
    16  * Tested up to:        6.3
     16 * Tested up to:        6.3.1
    1717 *
    1818 * ThriveDesk is free software: you can redistribute it and/or modify
     
    5050     * @var string
    5151     */
    52     public $version = '1.0.18';
     52    public $version = '1.1.0';
    5353
    5454    /**
Note: See TracChangeset for help on using the changeset viewer.