Plugin Directory

source: ladipage/trunk/ladipage.php

Last change on this file was 3030486, checked in by binhnguyenplus, 15 months ago

Fixed str_contain

  • Property svn:executable set to *
File size: 66.1 KB
Line 
1<?php
2/*
3Plugin Name: LadiPage - Landing Page Builder
4Plugin URI: http://ladipage.com
5Description: Connector to access content from LadiPage service. (LadiPage: Landing Page Platform for Advertiser)
6Author: LadiPage
7Author URI: http://ladipage.com
8Version: 4.4
9*/
10
11ini_set('display_errors', 0);
12ini_set('display_startup_errors', 0);
13error_reporting(E_ALL);
14
15if( ! class_exists( "PageTemplater" ) ){
16        require plugin_dir_path( __FILE__ ) . 'add-template.php';
17}
18
19if ( isset( $_SERVER['HTTP_ORIGIN'] ) ) {
20        header( "Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}" );
21        header( 'Access-Control-Allow-Credentials: true' );
22        header( 'Access-Control-Max-Age: 86400' ); // cache for 1 day
23}
24
25if ( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ) {
26        if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] ) ) {
27                header( "Access-Control-Allow-Methods: GET, POST, OPTIONS" );
28        }
29        if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ) ) {
30                header( "Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}" );
31        }
32        exit( 0 );
33}
34
35if ( ! defined( 'ABSPATH' ) ) {
36        exit;
37}
38
39// Update ladipage_tracking_url for woo
40add_action('wp_footer', 'ladiapp_add_cookie');
41function ladiapp_add_cookie()
42{
43        $actual_link = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
44        if (strpos($actual_link, 'trigger_id=') || strpos($actual_link, 'source_platform=LADIFLOW') || strpos($actual_link, 'source_platform=LADIPAGE')) { 
45                setcookie("ladipage_tracking_url", $actual_link, time() + (86400 * 90), "/");
46        }
47}
48
49if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
50        add_action( 'woocommerce_checkout_update_order_meta', 'ladipage_update_order_custom_field' );
51        function ladipage_update_order_custom_field( $order_id ) {
52                update_post_meta( $order_id, 'ladipage_tracking_url', @$_COOKIE['ladipage_tracking_url'] );
53        }
54}
55
56// Send Data To LadiFlow from Contact Form 7
57add_action( 'wpcf7_before_send_mail', 'wpcf7_handle_data');
58function wpcf7_handle_data( $wpcf7 ) {
59    $submission = WPCF7_Submission::get_instance();
60        $data = $submission->get_posted_data();
61        $data['source'] = 'WPFORM7';
62        $data['channels'] = array('WPFORM7');
63        if ( $wpcf7->id()) {
64                $data['wpform7_id'] = $wpcf7->id();
65                $data['form_id'] = $wpcf7->id();
66        }
67       
68        if ($submission->get_meta('user_agent' ))
69                $data['user_agent'] = $submission->get_meta('user_agent');
70       
71        if ($submission->get_meta('url'))
72                $data['last_url'] = $submission->get_meta('url');
73       
74        if ($submission->get_meta('remote_ip'))
75                $data['last_ip'] = $submission->get_meta('remote_ip');
76
77                sendToLadiFlow($data);
78}
79
80// Send Data To LadiFlow from WPForms
81add_action( 'wpforms_process_complete', 'wpforms_handle_data', 10, 4 );
82function wpforms_handle_data( $fields, $entry, $form_data, $entry_id) {
83        $data = [];
84        foreach ($fields as $key => $value) {
85                $_field = 'f' . $key;
86                $data[$_field] = $value['value'];
87        }
88       
89        $data['form_id'] = $form_data['id'];
90        $data['last_ip'] = $_SERVER['REMOTE_ADDR'];
91        $data['last_url'] = $_SERVER['HTTP_REFERER'];
92        $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
93        $data['source'] = 'WPFORMS';
94        $data['channels'] = array('WPFORMS');
95        sendToLadiFlow($data);
96}
97
98function sendToLadiFlow($data) {
99        $config = get_option( 'ladipage_config', '');
100        $ladiflowHookConfig = get_option('ladiflow_hook_configs', array());
101        if ($data['form_id'] && $ladiflowHookConfig[$data['form_id']] && $ladiflowHookConfig[$data['form_id']]['url']) {
102                $url = $ladiflowHookConfig[$data['form_id']]['url'];
103        } else {
104                if ($config['ladiflow_api_key'] && $config['ladiflow_webhook_active'] == 1) {
105                        $url = @$config['ladiflow_api_url'] . '/customer/create-or-update';
106                }
107        }
108       
109        if ($url)
110                curlPost($url, $data, $config['ladiflow_api_key']);
111        return;
112}
113
114function getRandomUserAgent()
115{
116    $userAgents = array(
117        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6)    Gecko/20070725 Firefox/2.0.0.6",
118        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
119        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)",
120        "Opera/9.20 (Windows NT 6.0; U; en)",
121        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 8.50",
122        "Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.02 [en]",
123        "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; fr; rv:1.7) Gecko/20040624 Firefox/0.9",
124        "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/48 (like Gecko) Safari/48"       
125    );
126    $random = rand(0,count($userAgents)-1);
127    return $userAgents[$random];
128}
129
130function curlPost($url, $data, $apiKey = '4fb4d9fbd59070b3a5e5706bdc6e80c3cf8678c4083d6ae6') {
131        $data_string = json_encode($data);
132        $curl = curl_init($url);
133        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
134        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
135        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
136        curl_setopt($curl,CURLOPT_USERAGENT,getRandomUserAgent());
137        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
138            'Content-Type: application/json',
139            'Content-Length: ' . strlen($data_string),
140                'Api-Key:' . $apiKey
141        ));
142
143        $result = curl_exec($curl);
144        curl_close($curl);
145        return $result;
146}
147
148
149if ( ! class_exists( 'Ladipage' ) ) {
150
151        class Ladipage {
152                protected static $_instance = null;
153
154                protected $_notices = array();
155
156                public static function instance() {
157                        if ( is_null( self::$_instance ) ) {
158                                self::$_instance = new self();
159                        }
160
161                        return self::$_instance;
162                }
163
164                public function __construct() {
165                        try {
166                                _mkdir();
167                        } catch (Exception $ex) {
168
169                        }
170                        add_action( 'init', array( $this, 'init_endpoint' ) );
171                        add_action( 'admin_init', array( $this, 'check_environment' ) );
172                        add_action( 'admin_notices', array( $this, 'admin_notices' ), 15 );
173                        add_action( 'admin_menu', array( $this, 'add_ladipage_menu_item' ) );
174                        add_action( 'wp_ajax_ladipage_save_config', array( $this, 'save_config' ) );
175                        add_action( 'wp_ajax_ladipage_publish_lp', array( $this, 'publish_lp' ) );
176                        add_action( 'wp_ajax_ladiflow_save_hook', array( $this, 'ladiflow_save_hook' ) );
177
178                        register_activation_hook( __FILE__, array( $this, 'activation_process' ) );
179                        register_deactivation_hook( __FILE__, array( $this, 'deactivation_process' ) );
180                }
181
182                public function activation_process() {
183                    $this->init_endpoint();
184                        flush_rewrite_rules();
185                }
186
187                public function deactivation_process() {
188                        flush_rewrite_rules();
189                }
190
191                /* add hook and do action */
192                public function init_endpoint() {
193                        add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
194                        add_action( 'parse_request', array( $this, 'sniff_requests' ) );
195                        add_rewrite_rule( '^ladipage/api', 'index.php?ladipage_api=1', 'top' );
196                }
197
198                public function add_query_vars( $vars ) {
199                        $vars[] = 'ladipage_api';
200
201                        return $vars;
202                }
203
204                public function sniff_requests() {
205                        global $wp, $wpdb;
206                        $query = $GLOBALS['wpdb'];
207                        $config = get_option( 'ladipage_config', '');
208                        $params      = filter_input_array( INPUT_POST );
209                        $isLadipage = isset( $wp->query_vars['ladipage_api'] ) ? $wp->query_vars['ladipage_api'] : null;
210                        // Params for products & orders
211                        $productID = isset( $_GET['product_id'] ) ? $_GET['product_id'] : null;
212                        $limit = isset( $_GET['limit'] ) ? $_GET['limit'] : 50;
213                        $paged = isset( $_GET['page'] ) ? $_GET['page'] : 0;
214                        $categoryIds = isset( $_GET['category_ids'] ) ? $_GET['category_ids'] : null;
215                        $variantID = isset( $_GET['variant_id'] ) ? $_GET['variant_id'] : null;
216                        $coupon = isset( $_GET['coupon'] ) ? $_GET['coupon'] : null;
217                        $actProduct = isset( $_GET['action'] ) ? $_GET['action'] : null;
218                        $qty = isset( $_GET['qty'] ) ? $_GET['qty'] : 1;
219                        $cartItemKey = isset( $_GET['cart_item_key'] ) ? $_GET['cart_item_key'] : null;
220                        $keyword = isset( $_GET['keyword'] ) ? $_GET['keyword'] : null;
221                       
222                        $ladiFlowApiKey = isset( $_GET['ladiflow_api_key'] ) ? $_GET['ladiflow_api_key'] : null;
223                        $appApiKey = isset( $_GET['app_api_key'] ) ? $_GET['app_api_key'] : null;
224                        $apiKey = isset( $_GET['api_key'] ) ? $_GET['api_key'] : null;
225                        $webhookURL = isset( $_GET['webhook_url'] ) ? $_GET['webhook_url'] : null;
226                        $webhookApiVersion = isset( $_GET['wh_api_version'] ) ? $_GET['wh_api_version'] : 2;
227                        $webhookApiUserId = isset( $_GET['wh_api_user_id'] ) ? $_GET['wh_api_user_id'] : 1;
228                        $isConnectedLadiFlow = (int) @$_GET['is_connected_ladiflow'];
229                        $isConnectedLadiShare = (int) @$_GET['is_connected_ladishare'];
230                        $events = isset( $_GET['events'] ) ? $_GET['events'] : 'order.created,order.updated,customer.created,customer.updated';
231                        $postType = isset( $_GET['post_type'] ) ? $_GET['post_type'] : null;
232                        $formID = isset( $_GET['form_id'] ) ? $_GET['form_id'] : null;
233                        $landingpageKey = isset( $_GET['ladipage_key'] ) ? $_GET['ladipage_key'] : null;
234                        $couponData        = isset( $params['coupon_data'] ) ? $params['coupon_data'] : null;
235
236                        $appName = '';
237                        if ($isConnectedLadiFlow) {
238                                $appName = 'LADIFLOW';
239                                $appApiKey = $ladiFlowApiKey;
240                        }
241                        if ($isConnectedLadiShare)      $appName = 'LADISHARE';
242                       
243                        if ($appApiKey && $actProduct === 'verify_webhook') {
244                               
245                                $args1 = array(
246                                         'role' => 'administrator',
247                                         'order' => 'ASC'
248                                        );
249                                 $subscribers = get_users($args1);
250                                 foreach ($subscribers as $user) {
251                                        $webhookApiUserId = $user->ID;
252                                         break;
253                                 }
254                                if ($appName)
255                                        $this->updateWebhook($appName, $appApiKey, $apiKey, $config, $webhookURL, $events, $webhookApiVersion, $webhookApiUserId);
256                        }
257                       
258                        if ($appApiKey && $actProduct === 'delete_webhook') {
259                                $this->deleteWebhook($appName, $appApiKey, $apiKey, $config);
260                        }
261                       
262                        // Action for Intergrated products & orders.
263                        if ($actProduct !== null) {
264                                switch($actProduct) {
265                                        case 'product_info': 
266                                                if ( !is_null($productID)) {
267                                                        $this->getProduct($productID);
268                                                }
269                                                break;
270                                        case 'cart_add': 
271                                                if ( !is_null($productID)) {
272                                                        $this->addToCart($productID, $qty, $variantID);
273                                                        exit;
274                                                }
275                                                break;
276                                        case 'cart_info': 
277                                                $this->cartInfo();
278                                                break;
279                                        case 'cart_empty': 
280                                                $this->cartEmpty();
281                                                break;
282                                        case 'apply_coupon': 
283                                                $this->applyCoupon($coupon);
284                                                break;
285                                        case 'remove_coupon': 
286                                                $this->removeCoupon($coupon);
287                                                break;
288                                        case 'cart_remove_item': 
289                                                $this->cartRemoveItem($cartItemKey);
290                                                break;
291                                        case 'cart_update_item_qty': 
292                                                $this->cartUpdateItemQty($cartItemKey, $qty);
293                                                break;
294                                        case 'list_category':
295                                                $this->listCategory($keyword);
296                                                break;
297                                        case 'product_list':
298                                                $this->searchProduct($keyword, $categoryIds, $paged, $limit);
299                                                break;
300                                        case 'order_create': 
301                                                $this->createOrder();
302                                                break;
303                                        case 'list_forms': 
304                                                $this->listForms($postType);
305                                                break;
306                                        case 'list_form_fields': 
307                                                $this->listFormFields($formID, $postType);
308                                                break;
309                                        case 'publishldp': 
310                                                $this->publish_lp($landingpageKey);
311                                                break;
312                                        default:
313                                }
314                        }
315                       
316                        if ( ! is_null( $isLadipage ) && $isLadipage === "1" ) {
317                                $api_key     = isset( $params['token'] ) ? sanitize_text_field($params['token']) : null;
318                                $action      = isset( $params['action'] ) ? sanitize_text_field($params['action']) : null;
319                                $url         = isset( $params['url'] ) ? sanitize_text_field($params['url']) : null;
320                                $title       = isset( $params['title'] ) ? sanitize_text_field($params['title']) : null;
321                                $html        = isset( $params['html'] ) ? $params['html'] : '';
322                                $type       = isset( $params['type'] ) ? sanitize_text_field($params['type']) : null;
323                               
324                               
325                                // Check key for action products & orders
326                                if (isset( $_GET['ldp_token'] )) {
327                                        $api_key = @$_GET['ldp_token'];
328                                }
329                                       
330                                if ( $api_key !== $config['api_key'] ) {
331                                        wp_send_json( array(
332                                                'code'    => 190
333                                        ) );
334                                }
335                               
336                                // Action for Intergrated products & orders.
337                                if ($actProduct !== null) {
338                                        switch($actProduct) {
339                                                case 'order_create': 
340                                                        $this->createOrder();
341                                                        break;
342                                        }
343                                }
344                               
345                                // Action for publish Landing Page
346                                switch ( $action ) {
347                                        case 'create':
348                                                if ( $this->get_id_by_slug($url) ) {
349                                                        wp_send_json( array(
350                                                                'code'    => 205
351                                                        ) );
352                                                }
353                                                kses_remove_filters();
354                                                if ($type==null) {
355                                                        $post_type = 'page';
356                                                } else {
357                                                        $post_type = $type;
358                                                }
359
360                                                $id = wp_insert_post(
361                                                        array(
362                                                                'post_title'=>$title, 
363                                                                'post_name'=>$url, 
364                                                                'post_type'=>$post_type, 
365                                                                'post_content'=> trim($html), 
366                                                                'post_status' => 'publish',
367                                                                'filter' => true ,
368                                                                'page_template'  => 'null-template.php'
369                                                        )
370                                                );
371
372                                                if ($id) {
373                                                        updateSource($url, $html);
374                                                        wp_send_json( array(
375                                                                'code'    => 200,
376                                                                'url'    => get_permalink($id)
377                                                        ) );
378                                                }else {
379                                                        wp_send_json( array(
380                                                                'code'    => 400,
381                                                                'message' => __( 'Create failed, please try again.' )
382                                                        ) );
383                                                }
384                                                break;
385                                       
386                                        case 'update':
387                                                if ( ! $this->get_id_by_slug($url) ) {
388                                                        wp_send_json( array(
389                                                                'code'    => 400,
390                                                                'message' => __( 'URL does not exist' )
391                                                        ) );
392                                                }else{
393                                                        $id = $this->get_id_by_slug($url);
394                                                        $post = array(
395                                                                'ID' => $id,
396                                                                'post_title'=>$title, 
397                                                    'post_content' => trim($html), 
398                                                        );
399                                                kses_remove_filters();
400                                                if (wp_update_post( $post )) {
401                                                                updateSource($url, $html);
402                                                                wp_send_json( array(
403                                                                        'code'    => 200,
404                                                                        'url'    => get_permalink($id)
405                                                                ) );
406                                                } else {
407                                                        wp_send_json( array(
408                                                                        'code'    => 400,
409                                                                        'message' => __( 'Update failed, please try again.' )
410                                                                ) );
411                                                }
412                                                }
413                                                break;
414
415                                        case 'delete':
416                                                if ( ! $this->get_id_by_slug($url) ) {
417                                                        wp_send_json( array(
418                                                                'code'    => 400,
419                                                                'message' => __( 'URL does not exist' )
420                                                        ) );
421                                                }else{
422                                                        $id = $this->get_id_by_slug($url);
423                                                        $result = wp_delete_post($id);
424                                                        try {
425                                                                stopLandingPage($url);
426                                                        } catch (Exception $ex) {
427                                                                wp_send_json( array(
428                                                                        'code'    => 400,
429                                                                        'message' => __( 'Delete failed, please try again.' )
430                                                                ) );
431                                                        }
432
433                                                if($result){
434                                                        wp_send_json( array(
435                                                                        'code'    => 200
436                                                                ) );
437                                                }else{
438                                                        wp_send_json( array(
439                                                                        'code'    => 400,
440                                                                        'message' => __( 'Delete failed, please try again.' )
441                                                                ) );
442                                                }
443                                                }
444                                                break;
445                                        case 'checkurl':
446                                                if ( ! $this->get_id_by_slug($url) ) {
447                                                        wp_send_json( array(
448                                                                'code'    => 206
449                                                        ) );
450                                                }else{
451                                                        wp_send_json( array(
452                                                                'code'    => 205
453                                                        ) );
454                                                }
455                                                break;
456                                        case 'checktoken':
457                                                if ( $api_key === $config['api_key'] ) {
458                                                        wp_send_json( array(
459                                                                'code'    => 191
460                                                        ) );
461                                                }
462                                                break;
463                                        case 'update_coupon': 
464                                                $this->updateCoupon($couponData);
465                                                break; 
466                                        default:
467                                                wp_send_json( array(
468                                                        'code'    => 400,
469                                                        'message' => __( 'LadiPage action is not set or incorrect.' )
470                                                ) );
471                                                break;
472                                }
473                        }
474                }
475               
476                function listFormFields($formID, $postType) {
477                        if ($postType === 'wpcf7_contact_form') {
478                                $form = WPCF7_ContactForm::get_instance( $formID );
479                                $fields = $form->scan_form_tags();
480                                $data = array();
481                                for ($i = 0; $i < count($fields); $i++) {
482                                        if ($fields[$i]->basetype != 'submit')
483                                                $data[$i] = array(
484                                                        'id' => $i + 1,
485                                                        'name' => $fields[$i]->name,
486                                                        'label' => $fields[$i]->label,
487                                                        'type' => $fields[$i]->basetype
488                                                );
489                                }
490                                wp_send_json(
491                                        array(
492                                                'code'    => 200,
493                                                'data' => $data
494                                        )
495                                );
496                        }
497
498                        if ($postType === 'wpforms') {
499                                $form         = wpforms()->form->get( $formID );
500                                $data = [];
501                                if ($form) {
502                                        $postContent = @json_decode($form->post_content);
503                                        if ($postContent->fields) {
504                                                $fields = (array) $postContent->fields;
505                                               
506                                                if (count($fields) > 0) {
507                                                        $i = 0;
508                                                        foreach ($fields as $field) {
509                                                                $data[$i] = array(
510                                                                        'id' => $i + 1,
511                                                                        'name' => $field->id,
512                                                                        'label' => $field->label,
513                                                                        'type' => $field->type
514                                                                );
515                                                                $i++;
516                                                        }
517                                                }
518                                        }
519                                }
520                               
521                                wp_send_json(
522                                        array(
523                                                'code'    => 200,
524                                                'data' => $data
525                                        )
526                                );
527                        }
528
529                        wp_send_json(
530                                array(
531                                        'code'    => 200,
532                                        'data' => []
533                                )
534                        );
535                }
536
537                function listForms($postType) {
538                        if (!$postType) {
539                                wp_send_json(
540                                        array(
541                                                'code'    => 200,
542                                                'data' => []
543                                        )
544                                );
545                                exit;
546                        }
547
548                        $args['post_type'] = $postType;
549                        $forms = get_posts( $args );
550                        $_forms = [];
551                        $i = 0;
552                        foreach ($forms as $form) {
553                                $_formItem = array(
554                                        'id' => $form->ID,
555                                        'name' => $form->post_title
556                                );
557                                $_forms[$i] = $_formItem;
558                                $i++;
559                        }
560                        wp_send_json(
561                                array(
562                                        'code'    => 200,
563                                        'data' => array(
564                                                'forms' => $_forms,
565                                                'post_type' => $postType
566                                        )
567                                )
568                        );
569                        exit;
570                }
571
572                function createWebhook($name, $topic, $secret, $deliveryURL, $status, $apiVersion = 2, $apiUserId = 1)
573                {
574                        $webhook = new WC_Webhook();
575                        $webhook->set_name( $name );
576                        $webhook->set_user_id($apiUserId);
577                        $webhook->set_topic( $topic ); // Event used to trigger a webhook.
578                        $webhook->set_secret( $secret ); // Secret to validate webhook when received.
579                        $webhook->set_delivery_url( $deliveryURL ); // URL where webhook should be sent.
580                        $webhook->set_status( $status ); // Webhook status.
581                        $webhook->set_api_version($apiVersion);
582                        $save = $webhook->save();
583                        return $save;
584                }
585               
586                public function deleteWebhook($appName, $appApiKey = null, $apiKey = null, $config) {
587                        try {   
588                                if (!$appApiKey || !$apiKey) {
589                                        wp_send_json(
590                                                        array(
591                                                                'code'    => 500,
592                                                                'data' => null,
593                                                                'message' => 'Request invalid!'
594                                                        )
595                                                );
596                                }
597                                               
598                                $apiURL = '';
599                                if ($appName === 'LADIFLOW') $apiURL = $config['ladiflow_api_url'];
600                                if ($appName === 'LADISHARE') $apiURL = $config['ladishare_api_url'];
601
602                                if ( $apiKey === $config['api_key'] ) {
603                                        if ($appName === 'LADIFLOW') {
604                                                $config['ladiflow_webhook_active'] = 0;
605                                        }
606
607                                        if ($appName === 'LADISHARE') {
608                                                $config['ladishare_webhook_active'] = 0;
609                                        }
610
611                                        update_option( 'ladipage_config', $config );
612                                       
613                                        if ( class_exists( 'WooCommerce' ) ) {
614                                                global $wpdb;
615                                        $results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wc_webhooks" );
616                                                foreach($results as $result) {
617                                                        if (strpos($result->delivery_url, $apiURL) !== false) {
618                                                                $wh = new WC_Webhook();
619                                                                $wh->set_id($result->webhook_id);
620                                                                $wh->delete();
621                                                        }
622                                                }
623                                        }
624                                        wp_send_json(
625                                                array(
626                                                        'code'    => 200,
627                                                        'data' => '',
628                                                        'message' => 'Delete webhook Success'
629                                                )
630                                        );
631                                } else {
632                                        wp_send_json(
633                                        array(
634                                                'code'    => 500,
635                                                'data' => null,
636                                                'message' => 'Can not verify Api Key.'
637                                        )
638                                );
639                                }
640                        } catch (Exception $ex) {
641                                wp_send_json(
642                                        array(
643                                                'code'    => 500,
644                                                'data' => null,
645                                                'message' => $ex->getMessage()
646                                        )
647                                );
648                        }
649                }
650
651                public function updateWebhook($appName, $appApiKey, $apiKey = null, $config = [], $webhookURL, $events = '') {
652                        try {   
653                                global $wpdb;
654                                if (!$apiKey || !$webhookURL) {
655                                        wp_send_json(
656                                                        array(
657                                                                'code'    => 500,
658                                                                'data' => null,
659                                                                'message' => 'Request invalid!'
660                                                        )
661                                                );
662                                }
663
664                                if ($appName == 'LADISHARE') {
665                                        $config['ladishare_api_url'] = $webhookURL;
666                                        $config['ladishare_webhook_active'] = 1;
667                                }
668
669                                if ($appName == 'LADIFLOW') {
670                                        $config['ladiflow_api_url'] = $webhookURL;
671                                        $config['ladiflow_webhook_active'] = 1;
672                                }
673                                               
674                                if ( $apiKey === $config['api_key'] ) {
675                                        update_option( 'ladipage_config', $config );
676                                        if ( class_exists( 'WooCommerce' ) ) {
677                                                $arrayEvent = [];
678                                                if ($events)
679                                                        $arrayEvent = @explode(',', $events);
680                                               
681                                        $results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}wc_webhooks" );
682                                                $currentTopic = [];
683                                                foreach ($results as $result) {
684                                                        if (strpos($result->delivery_url, $webhookURL) !== false) {
685                                                                $currentTopic[] = $result->topic;
686                                                        }
687                                                }
688                                               
689                                                $_events = [];
690                                                if (count($results) == 0) {
691                                                        $_events = $arrayEvent;
692                                                } else {
693                                                        for ($i = 0; $i < count($arrayEvent); $i++) {
694                                                                if (!in_array($arrayEvent[$i], $currentTopic)) {
695                                                                        $_events[] = $arrayEvent[$i];
696                                                                }
697                                                        }
698                                                }
699                       
700                                                if (count($_events) > 0) {
701                                                        $arrayWebhookID = array();
702                                                        for ($i = 0; $i < count($_events); $i++) {
703                                                                $name = '';
704                                                                if ($_events[$i] === 'order.created')
705                                                                        $name = $appName . " Create Order";
706
707                                                                if ($_events[$i] === 'order.updated')
708                                                                        $name = $appName . " Update Order";
709
710                                                                $_webhookURL = $webhookURL . '/webhook/wordpress';
711                                                                $webhookID = $this->createWebhook($name, $_events[$i], $appApiKey, $_webhookURL, 'active');
712                                                                if ($webhookID) {
713                                                                        $arrayWebhookID[] = $webhookID;
714                                                                }
715                                                        }
716                                                        if ($appName === 'LADISHARE') {
717                                                                $config['ladishare_webhook_ids'] = @json_decode($arrayWebhookID);
718                                                                $config['ladishare_webhook_active'] = 1;
719                                                        }
720
721                                                        if ($appName === 'LADIFLOW') {
722                                                                $config['ladiflow_webhook_ids'] = @json_decode($arrayWebhookID);
723                                                                $config['ladiflow_webhook_active'] = 1;
724                                                        }
725
726                                                        update_option( 'ladipage_config', $config );
727                                                }
728                                        }
729                                        wp_send_json(
730                                                array(
731                                                        'code'    => 200,
732                                                        'data' => 'Webhook',
733                                                        'message' => 'Success'
734                                                )
735                                        );
736                                } else {
737                                        wp_send_json(
738                                        array(
739                                                'code'    => 500,
740                                                'data' => null,
741                                                'message' => 'Can not verify Api Key.'
742                                        )
743                                );
744                                }
745                        } catch (Exception $ex) {
746                                wp_send_json(
747                                        array(
748                                                'code'    => 500,
749                                                'data' => null,
750                                                'message' => $ex->getMessage()
751                                        )
752                                );
753                        }
754                }
755
756                public function listCategory() {
757                        try {                                   
758                                $orderby = 'name';
759                                $order = 'asc';
760                                $hide_empty = false ;
761                                $args = array(
762                                        'orderby'    => $orderby,
763                                        'order'      => $order,
764                                        'hide_empty' => $hide_empty,
765                                );
766
767                                $arrayCate = [];
768                                $categories = get_terms( 'product_cat', $args );
769                                $i = 0;
770                                foreach ($categories as $category) {
771                                        $arrayCate[$i]['id'] = $category->term_id;
772                                        $arrayCate[$i]['name'] = $category->name;
773                                        $i++;
774                                }                                       
775                                wp_send_json(
776                                        array(
777                                                'code'    => 200,
778                                                'data' => $arrayCate,
779                                                'message' => 'Success'
780                                        )
781                                );
782                        } catch (Exception $ex) {
783                                wp_send_json(
784                                        array(
785                                                'code'    => 500,
786                                                'data' => null,
787                                                'message' => $ex->getMessage()
788                                        )
789                                );
790                        }
791                }
792               
793                public function searchProduct($keyword = '', $categoryIds = null, $page = 0, $limit = 50) {
794                        try {
795                               
796                                $args = array(
797                                        'posts_per_page' => $limit,
798                                        'paged' => $page,
799                                        'post_type' => array('product'),
800                                        'stock_status' => array('instock', 'outofstock')
801                                );
802                               
803                                if ($categoryIds) {
804                                        $categoryIds = explode('|', $categoryIds);
805                                        $args['tax_query'] = array(
806                                                array(
807                                                        'taxonomy' => 'product_cat',
808                                                        'terms' => $categoryIds,
809                                                        'operator' => 'IN'
810                                                )
811                                        );
812                                }
813                               
814                                if ($keyword != '') {
815                                        $args['s'] = $keyword; 
816                                }       
817                               
818                               
819                                $query = new WP_Query( $args );
820                                $count = $query->found_posts;
821                                $productData = array();
822                                $postParentID = array();
823                                $weightUnit = get_option('woocommerce_weight_unit');
824                                if ( $query->have_posts() ) {
825                $products = $query->posts;
826                                        foreach ($products as $product) {
827                                                setup_postdata( $product );
828                                                $productAttribute = get_post_meta( $product->ID, '_product_attributes' );
829                                                $_attrData = array();
830                                                $i = 0;
831                                                $product2 = new WC_product($product->ID);
832                                                $attachment_ids = $product2->get_gallery_image_ids();
833                                                $productGallery = [];
834                                                $m = 0;
835                                                foreach( $attachment_ids as $attachment_id ) {
836                                                        $m++;
837                                                        $productGallery[] = [
838                                                                'src' => wp_get_attachment_url( $attachment_id ),
839                                                                'position'=> $m,
840                                                                'product_id' => $product->ID
841                                                        ];
842                                                }
843                                               
844                                                $productAttribute = (array) @$productAttribute[0];
845                                                       
846                                                foreach ($productAttribute as $key => $attr) {
847                                                       
848                                                        if ($attr['is_taxonomy'] == 1) {       
849                                                                $label = wc_attribute_label($attr['name']);
850                                                                $_itemAttr = array(
851                                                                        'product_id' => $productID,
852                                                                        'product_option_id' => $i,
853                                                                        'name' => $label,
854                                                                        'type' => 1,
855                                                                        'position' => $attr['position'],
856                                                                        'values' => array()
857                                                                );
858                                                               
859                                                        $optionValues = [];
860                                                                $_attributeArray = woocommerce_get_product_terms($productID, $attr['name'], 'all');
861                                                                for ($k = 0; $k < count($_attributeArray); $k++) {
862                                                                        $optionValues[$k] = ['name' => @trim($_attributeArray[$k]->slug), 'label' => @trim($_attributeArray[$k]->name)];
863                                                                }
864                                                                $_itemAttr['values'] = $optionValues;
865                                                        } else {
866                                                                $_itemAttr = array(
867                                                                        'product_id' => $productID,
868                                                                        'product_option_id' => $i,
869                                                                        'name' => $attr['name'],
870                                                                        'type' => 1,
871                                                                        'position' => $attr['position'],
872                                                                        'values' => explode(' | ', $attr['value'])
873                                                                );
874                                                                $optionValues = @explode(' | ', $attr['value']);
875                                                                if (count($optionValues) > 0) {
876                                                                        for ($k = 0; $k < count($optionValues); $k++) {
877                                                                                $optionValues[$k] = ['name' => @trim($optionValues[$k]),  'label' => @trim($optionValues[$k])];
878                                                                        }       
879                                                                        $_itemAttr['values'] = $optionValues;
880                                                                }
881                                                               
882                                                        }
883                                                        $_attrData[$i] = $_itemAttr;
884                                                        $i++;
885                                                }
886                                               
887                                                $price = get_post_meta( $product->ID, '_price', true );
888                                                $productPrice = get_post_meta( $product->ID, '_sale_price', true );
889                                                if (!$productPrice)
890                                                        $productPrice = $price;
891                                                $comparePrice = get_post_meta( $product->ID, '_regular_price', true );
892
893                                                $sku = get_post_meta( $product->ID, '_sku', true );
894                                                $image = get_the_post_thumbnail_url($product->ID);
895                                                $imageObj = array();
896                                                if ($image) {
897                                                        $imageObj = array(
898                                                                'src' => $image,
899                                                                'position'=> 0,
900                                                                'product_id' => $product->ID
901                                                        );
902                                                }
903                                                $stockProduct = (int) get_post_meta( $product->ID, '_stock', true );
904                                                $_weight = (float) get_post_meta( $product->ID, '_weight', true );
905                                               
906                                                $_product = array(
907                                                        '_id' => $product->ID,
908                                                        'product_id' => $product->ID,
909                                                        'name' => $product->post_title,
910                                                        'description' => $product->post_content,
911                                                        'short_description' => $product->post_excerpt,
912                                                        'unit' => null,
913                                                        'price' => (float) $price,
914                                                        'sale_price' => (float) $productPrice,
915                                                        'price_compare' => (float) $comparePrice,
916                                                        'compare_price' => (float) $comparePrice,
917                                                        'options' => $_attrData,
918                                                        'images' => $productGallery,
919                                                        'image' => $imageObj,
920                                                        'tags' => array(),
921                                                        'variants' => array(
922                                                               
923                                                        ),
924                                                        'relates' => array(),
925                                                        'cross_sells' => array(),
926                                                        'upsells' => array(),
927                                                        'post_parent' => $product->post_parent
928                                                );
929                                                $parentManageStock = $product2->get_manage_stock() == true ? 1: 0;
930                                                $productVariants = $this->getVariants($product->ID, $product->post_title, $parentManageStock);
931                                                $_product['variants'] = $productVariants;
932                                               
933                                                $productData[] = $_product;
934                                        }
935                                }
936                                wp_reset_postdata();
937
938                                $currencyCode = 'VND';
939                                $currencySymbol = 'đ';
940                                if ( class_exists( 'WooCommerce' ) ) {
941                                        $currencyCode = get_woocommerce_currency();
942                                        $currencySymbol = get_woocommerce_currency_symbol();
943                                }
944                               
945                                for ($i = 0; $i < count($productData); $i++) {
946                                        if (count ($productData[$i]['variants']) == 0) {
947                                                $productData[$i]['variants'][] = array(
948                                                                        '_id' => $productData[$i]['product_id'],
949                                                                        'product_id' => $productData[$i]['product_id'],
950                                                                        'product_variant_id' => $productData[$i]['product_id'],
951                                                                        'store_id'=> null,
952                                                                        'product_name' => $productData[$i]['name'],
953                                                                        'description' => $productData[$i]['description'],
954                                                                        'short_description' => $productData[$i]['excerpt'],
955                                                                        'price' => (float) @$productData[$i]['price'],
956                                                                        'sale_price' => (float) @$productData[$i]['sale_price'],
957                                                                        'price_compare' => (float) @$productData[$i]['compare_price'],
958                                                                        'compare_price' => (float) @$productData[$i]['compare_price'],
959                                                                        'cost_per_item' => 0,
960                                                                        'sku' => @$productData[$i]['sku'],
961                                                                        'quantity' => (int) @$productData[$i]['stock_quantity'],
962                                                                        'inventory_checked' => @$productData[$i]['manage_stock'] === true ? 1 : 0,
963                                                                        'weight'=> @$productData[$i]['weight'],
964                                                                        'weight_unit' => @$productData[$i]['weight_unit'],
965                                                                        'currency' => $currencyCode,
966                                                                        'height'=> null,
967                                                                        'bar_code'=> null,
968                                                                        'src' => null,
969                                                                        'option_ids' => '',
970                                                                        'text_quantity' => '',
971                                                                        'title' => $productData[$i]['name'],
972                                                                        'post_parent' => @$productData[$i]['post_parent'],
973                                                                        'option1' => null,
974                                                                        'option2' => null,
975                                                                        'option3' => null,
976                                                                        'created_at' => @$productData[$i]['date_created'],
977                                                                        'updated_at' => @$productData[$i]['date_modified']
978                                                                );
979                                        }
980                                }
981                               
982                                $storeInfo = array(
983                                        'currency' => array('code' => $currencyCode, 'symbol' => $currencySymbol)
984                                );
985
986                                // Search Product
987                                wp_send_json( array(
988                                        'code'    => 200,
989                                        'data' => array('products' => $productData, 'total_record' => $count, 'store_info' => $storeInfo)
990                                ) );
991                        } catch (Exception $ex) {
992                                wp_send_json(
993                                        array(
994                                                'code'    => 500,
995                                                'data' => null,
996                                                'message' => $ex->getMessage()
997                                        )
998                                );
999                        }
1000                }
1001               
1002                public function getVariants($postParentID, $productName = '', $parentManageStock = 0) {
1003                        $argsVariant = array(
1004                                        'posts_per_page' => 500,
1005                                        'post_type' => array('product_variation'),
1006                                        'post_parent__in' => [$postParentID]
1007                                );
1008                                $productData = [];
1009                                $weightUnit = get_option('woocommerce_weight_unit');
1010                                $queryVariant = new WP_Query( $argsVariant );
1011                                if ( $queryVariant->have_posts() ) {
1012                $productVariants = $queryVariant->posts;
1013                                        foreach ($productVariants as $variant) {
1014                                                $variation = new WC_Product_Variation( $variant->ID );
1015
1016                                                $image = wp_get_attachment_url( $variation->get_image_id() );
1017                                                $imageObj = array();
1018                                                if ($image) {
1019                                                        $imageObj = array(
1020                                                                'src' => $image,
1021                                                                'position'=> 0,
1022                                                                'product_id' => $variant->ID
1023                                                        );
1024                                                }
1025                                                $variantAttributes = $variation->get_attributes();
1026                                                $arrayVariantOption = [];
1027                                                foreach ($variantAttributes as $key => $value) {
1028                                                        $arrayVariantOption[] = $value;
1029                                                }
1030                                                $option1 = @$arrayVariantOption[0];
1031                                                $option2 = @$arrayVariantOption[1];
1032                                                $option3 = @$arrayVariantOption[2];
1033                                               
1034                                                $variantSalePrice = @get_post_meta( $variant->ID, '_sale_price', true ) 
1035                                                        ? get_post_meta( $variant->ID, '_sale_price', true ) : get_post_meta( $variant->post_parent, '_sale_price', true );
1036                                                $variantPrice = (float )@get_post_meta( $variant->ID, '_price', true ) 
1037                                                        ? get_post_meta( $variant->ID, '_price', true ) : get_post_meta( $variant->post_parent, '_price', true );
1038                                                if (!$variantSalePrice)
1039                                                                $variantSalePrice = $variantPrice;
1040
1041                                                $variantComparePrice = (float) @get_post_meta( $variant->ID, '_regular_price', true ) 
1042                                                        ? get_post_meta( $variant->ID, '_regular_price', true ) : get_post_meta( $variant->post_parent, '_regular_price', true );
1043                                                $variantSKU = get_post_meta( $variant->ID, '_sku', true );
1044                                                $stockVariant = (int) get_post_meta( $variant->ID, '_stock', true );
1045                                                $_weight = (float) get_post_meta( $variant->ID, '_weight', true );
1046                                               
1047                                                $variantTitle = '';
1048                                                if ($option1)
1049                                                        $variantTitle .= $option1;
1050                                                if ($option2)
1051                                                        $variantTitle .= ', ' . $option2;
1052                                                if ($option3)
1053                                                        $variantTitle .= ', ' . $option3;
1054                                                $_variant = array(
1055                                                        '_id' => $variant->ID,
1056                                                        'product_id' => $variant->post_parent,
1057                                                        'product_variant_id' => $variant->ID,
1058                                                        'store_id'=> null,
1059                                                        'product_name' => $productName,
1060                                                        'description' => $variant->post_content,
1061                                                        'short_description' => $variant->post_excerpt,
1062                                                        'price' => (float) $variantPrice,
1063                                                        'sale_price' => (float) $variantSalePrice,
1064                                                        'price_compare' => (float) $variantComparePrice,
1065                                                        'compare_price' => (float) $variantComparePrice,
1066                                                        'cost_per_item' => 0,
1067                                                        'sku' => $variantSKU,
1068                                                        'quantity' => $stockVariant,
1069                                                        'inventory_checked' => $variation->get_manage_stock() === true ? 1 : $parentManageStock,
1070                                                        'weight'=> $_weight,
1071                                                        'weight_unit' => $weightUnit,
1072                                                        'height'=> null,
1073                                                        'bar_code'=> null,
1074                                                        'src' => null,
1075                                                        'image' => $imageObj,
1076                                                        'option_ids' => '',
1077                                                        'text_quantity' => '',
1078                                                        'title' => $variantTitle,
1079                                                        'post_parent' => $variant->post_parent,
1080                                                        'option1' => $option1,
1081                                                        'option2' => $option2,
1082                                                        'option3' => $option3,
1083                                                        'created_at' => $variant->post_date,
1084                                                        'updated_at' => $variant->post_modified
1085                                                );
1086                                                if ($_variant['price'] > 0 && $_variant['price_compare'] > 0)
1087                                                        $productData[] = $_variant;
1088                                        }
1089                        }
1090                        return $productData;
1091                }
1092               
1093                public function getProduct($productID = null) {
1094                        try {   
1095                                global $_product;
1096                                $currencyCode = 'VND';
1097                                $currencySymbol = 'đ';
1098                                if ( class_exists( 'WooCommerce' ) ) {
1099                                        $_product = wc_get_product( $productID );
1100                                        $productData = $_product->get_data();
1101                                        $productData['product_id'] = (int) $productID;
1102                                        $productData['_id'] = (int) $productID;
1103                                        $productData['price'] = (float) $_product->get_price();
1104                                        $productData['compare_price'] = (float) $_product->get_regular_price();
1105                                        $productData['price_compare'] = $productData['compare_price'];
1106                                        $productData['sale_price'] = (float) $_product->get_sale_price();
1107                                        $productName = $_product->get_name();
1108                                        $parentManageStock = $_product->get_manage_stock() == true ? 1: 0;
1109                                        $productAttribute = get_post_meta( $productID, '_product_attributes' ); 
1110
1111                                        $currencyCode = get_woocommerce_currency();
1112                                        $currencySymbol = get_woocommerce_currency_symbol();
1113
1114                                        $_attrData = array();
1115                                        $i = 0;
1116                                       
1117                                        $productAttribute = (array) @$productAttribute[0];
1118                                        foreach ($productAttribute as $key => $attr) {
1119                                                if ($attr['is_taxonomy'] == 1) {       
1120                                                        $taxonomy = $attr['name'];
1121                                                        $label = wc_attribute_label($taxonomy);
1122                                                        $_itemAttr = array(
1123                                                                'product_id' => $productID,
1124                                                                'product_option_id' => $i,
1125                                                                'name' => $label,
1126                                                                'type' => 1,
1127                                                                'position' => $attr['position'],
1128                                                                'values' => array()
1129                                                        );
1130                                                       
1131                                                        $optionValues = [];
1132                                                        $_attributeArray = woocommerce_get_product_terms($productID, $attr['name'], 'all');
1133                                                        for ($k = 0; $k < count($_attributeArray); $k++) {
1134                                                                $optionValues[$k] = ['name' => @trim($_attributeArray[$k]->slug), 'label' => @trim($_attributeArray[$k]->name)];
1135                                                        }
1136                                                        $_itemAttr['values'] = $optionValues;
1137                                                } else {
1138                                                        $_itemAttr = array(
1139                                                                'product_id' => $productID,
1140                                                                'product_option_id' => $i,
1141                                                                'name' => $attr['name'],
1142                                                                'type' => 1,
1143                                                                'position' => $attr['position'],
1144                                                                'values' => explode(' | ', $attr['value'])
1145                                                        );
1146                                                        $optionValues = @explode(' | ', $attr['value']);
1147                                                        if (count($optionValues) > 0) {
1148                                                                for ($k = 0; $k < count($optionValues); $k++) {
1149                                                                        $optionValues[$k] = ['name' => @trim($optionValues[$k]), 'label' => @trim($optionValues[$k])];
1150                                                                }       
1151                                                                $_itemAttr['values'] = $optionValues;
1152                                                        }
1153                                                       
1154                                                }       
1155                                                $_attrData[$i] = $_itemAttr;                                                           
1156                                                $i++;
1157                                        }
1158                                        $productData['options'] = $_attrData;
1159                                        if ($productData['parent_id'] == 0) {
1160                                                $variants = $this->getVariants($productID, $productName, $parentManageStock);
1161                                                if (count($variants) == 0) {
1162                                                        $productData['variants'][] = array(
1163                                                                        '_id' => $productData['id'],
1164                                                                        'product_id' => $productData['id'],
1165                                                                        'product_variant_id' => $productData['id'],
1166                                                                        'store_id'=> null,
1167                                                                        'product_name' => @$productData['name'],
1168                                                                        'description' => @$productData['description'],
1169                                                                        'short_description' => @$productData['short_description'],
1170                                                                        'price' => (float) $productData['price'],
1171                                                                        'sale_price' => (float) @$productData['sale_price'],
1172                                                                        'price_compare' => (float) @$productData['price_compare'],
1173                                                                        'compare_price' => (float) @$productData['compare_price'],
1174                                                                        'cost_per_item' => 0,
1175                                                                        'sku' => $productData['sku'],
1176                                                                        'quantity' => (int) $productData['stock_quantity'],
1177                                                                        'inventory_checked' => $productData['manage_stock'] === true ? 1 : 0,
1178                                                                        'weight'=> $productData['weight'],
1179                                                                        'weight_unit' => @$productData['weight_unit'],
1180                                                                        'currency' => $currencyCode,
1181                                                                        'height'=> null,
1182                                                                        'bar_code'=> null,
1183                                                                        'src' => null,
1184                                                                        'option_ids' => '',
1185                                                                        'text_quantity' => '',
1186                                                                        'title' => $productData['name'],
1187                                                                        'post_parent' => $productData['parent_id'],
1188                                                                        'option1' => null,
1189                                                                        'option2' => null,
1190                                                                        'option3' => null,
1191                                                                        'created_at' => $productData['date_created'],
1192                                                                        'updated_at' => $productData['date_modified']
1193                                                                );
1194                                                } else {
1195                                                        $productData['variants'] = $variants;
1196                                                }
1197                                        }
1198                                       
1199                                        $image = wp_get_attachment_url( $productData['image_id'] );
1200                                        $imageObj = array();
1201                                        if ($image) {
1202                                                $imageObj = array(
1203                                                        'src' => $image,
1204                                                        'position'=> 0,
1205                                                        'product_id' => $productID
1206                                                );
1207                                        }
1208                                       
1209                                       
1210                                        $productData['image'] = $imageObj;
1211                                        $productGallery = [];
1212                                        for ($i = 0; $i < count($productData['gallery_image_ids']); $i++) {
1213                                                $productGallery[] = [
1214                                                                'src' => wp_get_attachment_url( $productData['gallery_image_ids'][$i] ),
1215                                                                'position'=> $i,
1216                                                                'product_id' => $productID
1217                                                        ];
1218                                        }
1219                                        $productData['images'] = $productGallery;
1220
1221                                        $storeInfo = array(
1222                                                'currency' => array('code' => $currencyCode, 'symbol' => $currencySymbol)
1223                                        );
1224                                       
1225                                        if ($productData) {
1226                                                wp_send_json(
1227                                                        array(
1228                                                                'code'    => 200,
1229                                                                'data' => array('product' => $productData, 'store_info' => $storeInfo),
1230                                                                'message' => __( 'Success' )
1231                                                        )
1232                                                );
1233                                        } else {
1234                                                wp_send_json(
1235                                                        array(
1236                                                                'code'    => 404,
1237                                                                'data' => null,
1238                                                                'message' => __( 'Can not find this product.' )
1239                                                        )
1240                                                );
1241                                        }
1242                                }
1243                                wp_send_json(
1244                                        array(
1245                                                'code'    => 400,
1246                                                'data' => null,
1247                                                'message' => __( 'Bad request!' )
1248                                        )
1249                                );
1250                        } catch (Exception $ex) {
1251                                wp_send_json(
1252                                        array(
1253                                                'code'    => 500,
1254                                                'data' => null,
1255                                                'message' => $ex->getMessage()
1256                                        )
1257                                );
1258                        }
1259                }
1260               
1261                public function applyCoupon($coupon) {
1262                        try {           
1263                        if ( WC()->cart->has_discount( $coupon ) ) {
1264                                        wp_send_json(
1265                                                array(
1266                                                        'code'    => 500,
1267                                                        'data' => null,
1268                                                        'message' => 'Coupon had existed!'
1269                                                )
1270                                        );
1271                                }
1272                                $result = WC()->cart->apply_coupon( $coupon );
1273                        if ($result) {
1274                                        $money = strip_tags(WC()->cart->get_discount_total());
1275                                        wp_send_json(
1276                                                array(
1277                                                        'code'    => 200,
1278                                                        'data' => (float) $money,
1279                                                        'message' => 'Coupon applied success!'
1280                                                )
1281                                        );
1282                                }
1283                                wp_send_json(
1284                                        array(
1285                                                'code'    => 500,
1286                                                'data' => null,
1287                                                'message' => 'Can not apply this Coupon Code!'
1288                                        )
1289                                );
1290                        } catch (Exception $ex) {
1291                                wp_send_json(
1292                                        array(
1293                                                'code'    => 500,
1294                                                'data' => null,
1295                                                'message' => $ex->getMessage()
1296                                        )
1297                                );
1298                        }
1299                }       
1300               
1301                public function removeCoupon($coupon) {
1302                        try {
1303                                if (WC()->cart->remove_coupon( $coupon )) {
1304                                        wp_send_json(
1305                                                array(
1306                                                        'code'    => 200,
1307                                                        'data' => 0,
1308                                                        'message' => 'Coupon removed success!'
1309                                                )
1310                                        );
1311                                }
1312                        wp_send_json(
1313                                        array(
1314                                                'code'    => 500,
1315                                                'data' => null,
1316                                                'message' => 'Can not remove this Coupon Code!'
1317                                        )
1318                                );
1319                        } catch (Exception $ex) {
1320                                wp_send_json(
1321                                        array(
1322                                                'code'    => 500,
1323                                                'data' => null,
1324                                                'message' => $ex->getMessage()
1325                                        )
1326                                );
1327                        }
1328                }
1329
1330                public function updateCoupon($_couponData) {
1331                        try {
1332                                $couponData = json_decode($_couponData);
1333                                 if (!$couponData || !$couponData->code) {
1334                                        wp_send_json(
1335                                        array(
1336                                                'code'    => 500,
1337                                                'data' => null,
1338                                                'message' => 'Request invalid!'
1339                                        )
1340                                ); 
1341                                 }
1342                                $coupon = new WC_Coupon();
1343                                $cp = wc_get_coupon_id_by_code($couponData->code);
1344                                if ($cp) {
1345                                        $coupon = new WC_Coupon($couponData->code);
1346                                } else {
1347                                        $coupon->set_code($couponData->code);
1348                                }
1349                                $coupon->set_discount_type($couponData->discount_type);
1350                                $coupon->set_amount($couponData->discount);
1351                                if ($couponData->end_date)
1352                                        $coupon->set_date_expires($couponData->end_date);
1353                                $coupon->save();
1354
1355                                wp_send_json(
1356                                        array(
1357                                                'code'    => 200,
1358                                                'data' => null,
1359                                                'message' => 'OK'
1360                                        )
1361                                );
1362                        } catch (Exception $ex) {
1363                                wp_send_json(
1364                                        array(
1365                                                'code'    => 500,
1366                                                'data' => null,
1367                                                'message' => $ex->getMessage()
1368                                        )
1369                                );
1370                        }
1371                }
1372                       
1373                public function cartInfo() {
1374                        try {
1375                                $currencyCode = 'VND';
1376                                $currencySymbol = 'đ';
1377                                if ( class_exists( 'WooCommerce' ) ) {
1378                                        $currencyCode = get_woocommerce_currency();
1379                                        $currencySymbol = get_woocommerce_currency_symbol();
1380                                }
1381                               
1382                                $cart = WC()->cart->get_cart();
1383                                $cartData = [];
1384                                foreach($cart as $item => $values) {   
1385                                        $cartItem = $values['data'];                                   
1386                                        $values['image'] = wp_get_attachment_url( $cartItem->get_image_id());
1387                                        $values['product_name'] = $cartItem->get_name();
1388                                        $values['currency'] = $currencyCode;
1389                                        $values['sale_price'] = (float) $cartItem->get_sale_price();
1390                                        $values['regular_price'] = (float) $cartItem->get_regular_price();
1391                                        $values['price'] = (float) $cartItem->get_price();
1392                                        $cartData[] = $values;
1393                                } 
1394                               
1395                                wp_send_json(
1396                                        array(
1397                                                'code'    => 200,
1398                                                'data' => $cartData,
1399                                                'message' => 'Success'
1400                                        )
1401                                );
1402                        } catch (Exception $ex) {
1403                                wp_send_json(
1404                                        array(
1405                                                'code'    => 500,
1406                                                'data' => null,
1407                                                'message' => $ex->getMessage()
1408                                        )
1409                                );
1410                        }
1411                }
1412               
1413                public function cartEmpty() {
1414                        try {
1415                                $cart = WC()->cart->empty_cart();
1416                                wp_send_json(
1417                                        array(
1418                                                'code'    => 200,
1419                                                'data' => null,
1420                                                'message' => 'Success'
1421                                        )
1422                                );
1423                        } catch (Exception $ex) {
1424                                wp_send_json(
1425                                        array(
1426                                                'code'    => 500,
1427                                                'data' => null,
1428                                                'message' => $ex->getMessage()
1429                                        )
1430                                );
1431                        }
1432                }
1433               
1434                public function cartUpdateItemQty($key, $qty) {
1435                        try {
1436                                $currencyCode = 'VND';
1437                                $currencySymbol = 'đ';
1438                                if ( class_exists( 'WooCommerce' ) ) {
1439                                        $currencyCode = get_woocommerce_currency();
1440                                        $currencySymbol = get_woocommerce_currency_symbol();
1441                                }
1442
1443                                $qty = (int) $qty;
1444                                $result = WC()->cart->set_quantity($key, $qty);
1445                                if ($result) {
1446                                        $cart = WC()->cart->get_cart();
1447                                        $cartData = [];
1448                                        foreach($cart as $item => $values) {   
1449                                                $cartItem = $values['data'];                                   
1450                                                $values['image'] = wp_get_attachment_url( $cartItem->get_image_id());
1451                                                $values['product_name'] = $cartItem->get_name();
1452                                                $values['currency'] = $currencyCode;
1453                                                $values['sale_price'] = (float) $cartItem->get_sale_price();
1454                                                $values['regular_price'] = (float) $cartItem->get_regular_price();
1455                                                $values['price'] = (float) $cartItem->get_price();
1456                                                $cartData[] = $values;
1457                                        }                                                                                                               
1458                                        wp_send_json(
1459                                                array(
1460                                                        'code'    => 200,
1461                                                        'data' => $cartData,
1462                                                        'message' => 'Success'
1463                                                )
1464                                        );
1465                                }
1466                                wp_send_json(
1467                                                array(
1468                                                        'code'    => 500,
1469                                                        'data' => null,
1470                                                        'message' => 'Error'
1471                                                )
1472                                        );
1473                        } catch (Exception $ex) {
1474                                wp_send_json(
1475                                        array(
1476                                                'code'    => 500,
1477                                                'data' => null,
1478                                                'message' => $ex->getMessage()
1479                                        )
1480                                );
1481                        }
1482                }
1483               
1484                public function cartRemoveItem($key) {
1485                        try {
1486                                $currencyCode = 'VND';
1487                                $currencySymbol = 'đ';
1488                                if ( class_exists( 'WooCommerce' ) ) {
1489                                        $currencyCode = get_woocommerce_currency();
1490                                        $currencySymbol = get_woocommerce_currency_symbol();
1491                                }
1492
1493                                if (WC()->cart->remove_cart_item($key)) {
1494                                        $cartData = [];
1495                                        $cart = WC()->cart->get_cart();
1496                                        foreach($cart as $item => $values) {   
1497                                                $cartItem = $values['data'];                                   
1498                                                $values['image'] = wp_get_attachment_url( $cartItem->get_image_id());
1499                                                $values['product_name'] = $cartItem->get_name();
1500                                                $values['currency'] = $currencyCode;
1501                                                $values['sale_price'] = (float) $cartItem->get_sale_price();
1502                                                $values['regular_price'] = (float) $cartItem->get_regular_price();
1503                                                $values['price'] = (float) $cartItem->get_price();
1504                                                $cartData[] = $values;
1505                                        }
1506                                        wp_send_json(
1507                                                array(
1508                                                        'code'    => 200,
1509                                                        'data' => $cartData,
1510                                                        'message' => 'Success'
1511                                                )
1512                                        );
1513                                }
1514                                wp_send_json(
1515                                                array(
1516                                                        'code'    => 500,
1517                                                        'data' => null,
1518                                                        'message' => 'Error'
1519                                                )
1520                                        );
1521                        } catch (Exception $ex) {
1522                                wp_send_json(
1523                                        array(
1524                                                'code'    => 500,
1525                                                'data' => null,
1526                                                'message' => $ex->getMessage()
1527                                        )
1528                                );
1529                        }
1530                }
1531               
1532                public function addToCart($productID = 0, $qty, $variantID = 0, $arrOptions = []) {
1533                        try {
1534                                $currencyCode = 'VND';
1535                                $currencySymbol = 'đ';
1536                                if ( class_exists( 'WooCommerce' ) ) {
1537                                        $currencyCode = get_woocommerce_currency();
1538                                        $currencySymbol = get_woocommerce_currency_symbol();
1539                                }
1540
1541                                if ($productID === $variantID)
1542                                        $variantID = 0;
1543                                       
1544                                $qty = (int) $qty;
1545                                $variantAttributes = [];
1546                                if ($variantID && $variantID !== $productID) {
1547                                        $variation = new WC_Product_Variation($variantID);
1548                                        $variantAttributes = $variation->get_attributes();
1549                                }
1550                               
1551                                $result = WC()->cart->add_to_cart( $productID, $qty, $variantID, $variantAttributes);
1552                                if ($result) {
1553                                        $cart = WC()->cart->get_cart();
1554                                        $cartData = [];
1555                                        foreach($cart as $item => $values) {   
1556                                                $cartItem = $values['data'];                                   
1557                                                $values['image'] = wp_get_attachment_url( $cartItem->get_image_id());
1558                                                $values['product_name'] = $cartItem->get_name();
1559                                                $values['currency'] = $currencyCode;
1560                                                $values['sale_price'] = (float) $cartItem->get_sale_price();
1561                                                $values['regular_price'] = (float) $cartItem->get_regular_price();
1562                                                $values['price'] = (float) $cartItem->get_price();
1563                                                $cartData[] = $values;
1564                                        } 
1565                                        wp_send_json(
1566                                                array(
1567                                                        'code'    => 200,
1568                                                        'data' => $cartData,
1569                                                        'message' => 'Success'
1570                                                )
1571                                        );
1572                                }
1573                       
1574                        wp_send_json(
1575                                                array(
1576                                                        'code'    => 500,
1577                                                        'data' => null,
1578                                                        'message' => 'Can not add item to cart.'
1579                                                )
1580                                        );
1581                        } catch (Exception $ex) {
1582                                wp_send_json(
1583                                        array(
1584                                                'code'    => 500,
1585                                                'data' => null,
1586                                                'message' => $ex->getMessage()
1587                                        )
1588                                );
1589                        }
1590                }
1591               
1592                public function createOrder($data = null) {
1593                        try {
1594                                        global $woocommerce;
1595                                        $data = [];
1596                                        if (isset($_POST['form_data'])) {
1597                                                $data = @$_POST['form_data'];
1598                                                $data = str_replace ('\"','"', $data);                                         
1599                                                $data = json_decode($data, true);
1600                                        }
1601                               
1602                                        if (count($data) == 0) {
1603                                                wp_send_json(
1604                                                        array(
1605                                                                'code'    => 500,
1606                                                                'data' => null,
1607                                                                'message' => 'Data Empty'
1608                                                        )
1609                                                );
1610                                        }
1611                               
1612                                $order = wc_create_order();
1613                                for ($i = 0; $i < count($data['line_items']); $i++) {
1614                                        $pID = $data['line_items'][$i]['product_id'];
1615                                        if (isset($data['line_items'][$i]['variation_id']) && $data['line_items'][$i]['variation_id'] > 0) {
1616                                                $pID = $data['line_items'][$i]['variation_id'];
1617                                        }
1618                                       
1619                                        $__product = wc_get_product($pID); 
1620                                        $order->add_product( $__product, $data['line_items'][$i]['quantity']);
1621                                }
1622                               
1623                                $order->add_order_note(@$data['message']);
1624                                // Set addresses
1625                                $order->set_address( $data['billing'], 'billing' );
1626                                $order->set_address( $data['shipping'], 'shipping' );
1627                                if (isset($data['coupon']) && $data['coupon']) {
1628                                        try {
1629                                                $order->apply_coupon($data['coupon']);
1630                                        } catch (Exception $ex) {
1631                                               
1632                                        }
1633                                }
1634
1635                                // Set payment gateway
1636                                $payment_gateways = WC()->payment_gateways->payment_gateways();
1637                                $order->set_payment_method( $payment_gateways['bacs'] );
1638
1639                                // Calculate totals
1640                                $order->calculate_totals();
1641                                $order->update_status( 'Completed', 'Order Created From LadiPage - ', TRUE);
1642                                if ($order) {
1643                                        wp_send_json(
1644                                                array(
1645                                                        'code'    => 200,
1646                                                        'data' => $order,
1647                                                        'message' => 'SUCCESS'
1648                                                )
1649                                        );
1650                                }
1651                                wp_send_json(
1652                                                array(
1653                                                        'code'    => 500,
1654                                                        'data' => null,
1655                                                        'message' => 'ERROR'
1656                                                )
1657                                        );
1658                        } catch (Exception $ex) {
1659                                wp_send_json(
1660                                        array(
1661                                                'code'    => 500,
1662                                                'data' => null,
1663                                                'message' => $ex->getMessage()
1664                                        )
1665                                );
1666                        }
1667                }
1668               
1669                protected function get_id_by_slug($page_slug) {
1670                    $page = get_page_by_path($page_slug,'OBJECT', ['post','page','product','property']);
1671                    if ($page) {
1672                        return $page->ID;
1673                    } else {
1674                        return null;
1675                    }
1676                } 
1677
1678                public function get_option( $id, $default = '' ) {
1679                        $options = get_option( 'ladipage_config', array() );
1680                        if ( isset( $options[ $id ] ) && $options[ $id ] != '' ) {
1681                                return $options[ $id ];
1682                        } else {
1683                                return $default;
1684                        }
1685                }
1686
1687                /* Add menu and option */
1688                public function check_environment() {
1689                        if ( is_plugin_active( plugin_basename( __FILE__ ) ) ) {
1690                                if ( ! function_exists( 'curl_init' ) ) {
1691                                        $this->add_admin_notice( 'curl_not_exist', 'error', __( 'LadiPage requires cURL to be installed.', 'ladipage' ) );
1692                                }
1693                        }
1694                }
1695
1696                public function add_admin_notice( $slug, $class, $message ) {
1697                        $this->_notices[ $slug ] = array(
1698                                'class'   => $class,
1699                                'message' => $message,
1700                        );
1701                }
1702
1703                public function admin_notices() {
1704                        foreach ( $this->_notices as $notice_key => $notice ) {
1705                                echo "<div class='" . esc_attr( $notice['class'] ) . "'><p>";
1706                                echo wp_kses( $notice['message'], array( 'a' => array( 'href' => array() ) ) );
1707                                echo '</p></div>';
1708                        }
1709                }
1710
1711                public function add_ladipage_menu_item() {
1712                        add_menu_page( __( "LadiApp" ), __( "LadiApp" ), "manage_options", "ladipage-config", array(
1713                                $this,
1714                                'ladipage_settings_page'
1715                        ), null, 30 );
1716                }
1717
1718                public function ladipage_settings_page() {
1719                        if ( ! empty( $this->_notices ) ) {
1720                                ?>
1721                <div>Please install cURL to use LadiApp plugin</div>
1722                                <?php
1723                        } else {
1724                                ?>
1725                                <?php
1726                                        $tabs = array( 'general' => 'General', 'ladipage' => 'LadiPage', 'ladiflow' => 'LadiFlow' );
1727                                ?>
1728                                <div class="wrap">
1729                    <h2 class="title">LadiApp</h2><br>
1730                                        <p>An All-in-One application for businesses</p>
1731                                        <nav class="nav-tab-wrapper woo-nav-tab-wrapper">
1732                                        <?php
1733                                                $_tab = isset($_GET['tab']) ? $_GET['tab'] : 'general';
1734                                                foreach( $tabs as $tab => $name ){
1735                                                        $class = ( $tab == $_tab ) ? ' nav-tab-active' : "";
1736                                                        echo "<a class='nav-tab $class' href='?page=ladipage-config&tab=$tab'>$name</a>";
1737                                                }
1738                                        ?>
1739                                        </nav>
1740                    <div>
1741                                                <?php if ($_tab === 'general') :?>
1742                                                        <form id="ladipage_config" class="ladiui-panel">
1743                                                        <h3><strong>Config API Key</strong></h3>
1744                        <table class="form-table">
1745                            <tr>
1746                                <th scope="row">
1747                                    <label for="api_key">API KEY</label>
1748                                </th>
1749                                <td>
1750                                        <?php
1751                                                $config = get_option( 'ladipage_config', array());
1752                                               
1753                                            if(!isset($config['api_key']) || trim($config['api_key']) == ''){
1754                                                $config['api_key'] = $this->generateRandomString(32);
1755                                                update_option( 'ladipage_config', $config );
1756                                            }
1757
1758                                        ?>
1759                                    <input onClick="this.select();" readonly="readonly" name="api_key" id="api_key" type="text" class="regular-text ladiui input"
1760                                           value="<?php echo $this->get_option( 'api_key', '' ); ?>">
1761                                           <button type="button" id="ladipage_new_api" class="ladiui button primary">NEW API KEY</button>
1762                                </td>
1763                            </tr>
1764                            <tr>
1765                                <th scope="row">
1766                                                                        <label for="webiste_ladipage">Website URL</label>
1767                                </th>
1768                                <td>
1769                                    <input onClick="this.select();" readonly="readonly" name="webiste_ladipage" id="webiste_ladipage" type="text" class="regular-text ladiui input" value="<?php echo get_home_url(); ?>">
1770                                </td>
1771                            </tr>
1772                        </table>
1773
1774                        <div class="submit">
1775                            <button class="button button-primary ladiui button primary" id="ladipage_save_option" type="button">Save Changes
1776                            </button>
1777                        </div>
1778                    </form>
1779                                                <?php endif;?>
1780                                        <?php if ($_tab === 'ladipage') :?>
1781                                               
1782                    <form class="ladiui-panel" id="ladipage-publish-form">
1783                        <h3><strong>Manualy LadiPage Publish</strong></h3>
1784                        <table class="form-table">
1785                            <tr>
1786                                <th scope="row">
1787                                    <label for="api_key">LadiPage KEY</label>
1788                                </th>
1789                                <td>
1790                                    <input name="ladipage_key" id="ladipage_key" type="text" class="regular-text ladiui input" placeholder="Your LadiPage Key"><br/>
1791                                </td>
1792                            </tr>
1793                                                        <tr>
1794                                                                <td></td>
1795                                                                <td>
1796                                                                <span id="ladipage-message" class="lp-hide" style="color:#0c61f2;font-style:italic">Processing...</span>
1797                                                                <style>.lp-hide{display:none}</style>
1798                                                                </td>
1799                                                        </tr>
1800                        </table>
1801                        <div class="submit">
1802                            <button type="button" id="ladipage_publish" class="button button-primary ladiui button primary">Publish</button>
1803                                                       
1804                        </div>
1805                                                </form>
1806                                                <?php endif;?>
1807                                                <?php 
1808                                                        if ($_tab === 'ladiflow') :
1809                                                                $forms = get_posts( array('post_type' => 'wpcf7_contact_form') );
1810                                                ?>
1811                                                <form style="margin: 40px 10px;" method="post" action="" id="ladiflow_hook_form">
1812                                                        <style>
1813                                                                .ladiflow-hook label{
1814                                                                        min-width: 350px; display:inline-block
1815                                                                }
1816                                                                .ladiflow-hook input {
1817                                                                        min-width: 550px;
1818                                                                }
1819                                                                .ladiflow-hook .hook-item{
1820                                                                        display:block; margin-bottom: 10px; padding-left: 10px
1821                                                                }
1822                                                                .lp-hide{
1823                                                                        display:none;
1824                                                                }
1825                                                        </style>
1826                                                        <table class="ladiflow-hook">
1827                                                                <?php $ladiflowHookConfigs = get_option( 'ladiflow_hook_configs', array() );?>
1828                                                                <tr>
1829                                                                        <td>
1830                                                                                <h3>Webhook for Form Plugins (Contact Form 7, WPForms, ..)</h3>
1831                                                                                <p style="font-style: italic">
1832                                                                                        Enter the Catch Hook URL to receive data according to each Form below when user submit.
1833                                                                                </p>
1834                                                                        </td>
1835                                                                </tr>
1836                                                                <tr>
1837                                                                        <td>
1838                                                                                <?php foreach ($forms as $form) : ?>
1839                                                                                        <div class="hook-item">
1840                                                                                                <label><?php echo $form->post_title;?> - Contact Form 7</label>
1841                                                                                                <input id="<?php echo $form->ID;?>" data-form-type="wpcf7_contact_form" data-form-id="<?php echo $form->ID;?>" type="text" value="<?php echo @$ladiflowHookConfigs[$form->ID]['url'];?>" placeholder="Webhook URL"/>
1842                                                                                        </div>
1843                                                                                <?php endforeach;?>
1844                                                                        </td>
1845                                                                </tr>
1846                                                                <tr>
1847                                                                        <td>
1848                                                                                <?php $forms = get_posts( array('post_type' => 'wpforms') ); ?>
1849                                                                                <?php foreach ($forms as $form) : ?>
1850                                                                                <div class="hook-item">
1851                                                                                        <label><?php echo $form->post_title;?> - WPForms</label>
1852                                                                                        <input id="<?php echo $form->ID;?>" data-form-type="wpforms" data-form-id="<?php echo $form->ID;?>" type="text" value="<?php echo @$ladiflowHookConfigs[$form->ID]['url'];?>" placeholder="Webhook URL"/>
1853                                                                                </div>
1854                                                                                <?php endforeach;?>
1855                                                                        </td>
1856                                                                </tr>
1857                                                                <tr>
1858                                                                        <td>
1859                                                                                <div class="submit">
1860                            <button type="button" name="save_ladiflow_hook" id="save_ladiflow_hook" class="button button-primary ladiui button primary">Save</button>
1861                                                                                </div>
1862                                                                        </td>
1863                                                                </tr>
1864                                                                <tr>
1865                                                                        <td><span id="ladipage-message" class="lp-hide" style="color:#0c61f2;font-style:italic">Processing...</span></td>
1866                                                                </tr>
1867                                                        </table>
1868                                                </form>
1869                                                <?php endif;?>
1870                                        </div>
1871                    <script>
1872                        (function ($) {
1873                                function generateRandomString(length = 10) {
1874                                                                var text = "";
1875                                                                var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1876                                                                for (var i = 0; i < length; i++)
1877                                                            text += possible.charAt(Math.floor(Math.random() * possible.length));
1878                                                                return text;
1879                                                        }
1880                                                       
1881                                                        function validURL(str) {
1882                                                                if (str.indexOf('ladiflow.com/hooks/catch') < 0) {
1883                                                                        return false;
1884                                                                }
1885                                                          var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
1886                                                                '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
1887                                                                '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
1888                                                                '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
1889                                                                '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
1890                                                                '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
1891                                                          return !!pattern.test(str);
1892                                                        }
1893                                                       
1894                            $(document).ready(function () {
1895                                $('#ladipage_save_option').on('click', function (event) {
1896                                    var data = JSON.stringify($('#ladipage_config').serializeArray());
1897                                    $.ajax({
1898                                        url: ajaxurl,
1899                                        type: 'POST',
1900                                        data: {
1901                                            action: 'ladipage_save_config',
1902                                            data: data
1903                                        },
1904                                        success: function (response) {
1905                                            alert('Save Success');
1906                                        }
1907                                    });
1908                                    event.preventDefault();
1909                                });
1910                                $("#ladipage_new_api").click(function(){
1911                                        var api = generateRandomString(32);
1912                                        $("#ladipage_config #api_key").val(api);
1913                                });
1914
1915                                $('#ladipage_publish').on('click', function (event) {
1916                                                                        event.preventDefault();
1917                                                                        $('#ladipage-message').removeClass('lp-hide');
1918                                                                        $('#ladipage-message').empty().text('Processing...');
1919                                        var ladiPageKey = $('#ladipage_key').val();
1920                                        if (ladiPageKey == '') {
1921                                                alert('Please enter your LadiPage Key!');
1922                                                return false;
1923                                        }
1924
1925                                    $.ajax({
1926                                        url: ajaxurl,
1927                                        type: 'POST',
1928                                        data: {
1929                                            action: 'ladipage_publish_lp',
1930                                            ladipage_key: ladiPageKey
1931                                        },
1932                                        success: function (res) {
1933                                                                                        $('#ladipage-message').empty().html(res.message);
1934                                        }
1935                                    });
1936                                    event.preventDefault();
1937
1938                                });
1939                                                               
1940                                                                $('#save_ladiflow_hook').on('click', function (event) {
1941                                                                        event.preventDefault();
1942                                                                        var _data = {};
1943                                                                        $('#ladipage-message').removeClass('lp-hide');
1944                                                                        $('#ladipage-message').empty().text('Processing...');
1945                                                                        $('#ladiflow_hook_form input').each(function () {
1946                                                                                var input = $(this);
1947                                                                                var formID = input.attr('data-form-id');
1948                                                                                var postType = input.attr('data-form-type');
1949                                                                                var url = input.val();
1950                                                                                if (url) {
1951                                                                                        if (!validURL(url)) {
1952                                                                                                $('#' + formID).focus().css("border-color", "red");
1953                                                                                                return false;
1954                                                                                        } else {
1955                                                                                                $('#' + formID).focus().css("border-color", "#8c8f94");
1956                                                                                                _data[formID] = {
1957                                                                                                        id: formID,
1958                                                                                                        post_type: postType,
1959                                                                                                        url: url
1960                                                                                                };
1961                                                                                        }
1962                                                                                }       
1963                                                                        });
1964                                    $.ajax({
1965                                        url: ajaxurl,
1966                                        type: 'POST',
1967                                        data: {
1968                                            action: 'ladiflow_save_hook',
1969                                                                                        data: _data
1970                                        },
1971                                        success: function (res) {
1972                                                                                        console.log(res);
1973                                                                                        $('#ladipage-message').empty().text('Success!');
1974                                        }
1975                                    });
1976                                    event.preventDefault();
1977
1978                                });
1979
1980                            });
1981                        })(jQuery);
1982                    </script>
1983                </div>
1984                                <?php
1985                        }
1986                }
1987
1988                public function save_config() {
1989                        $data   = sanitize_text_field($_POST['data']);
1990                        $data   = json_decode( stripslashes( $data ) );
1991                        $option = array();
1992
1993                        foreach ( $data as $key => $value ) {
1994                                $option[ $value->name ] = $value->value;
1995                        }
1996                        update_option( 'ladipage_config', $option );
1997                        die;
1998                }
1999               
2000                public function ladiflow_save_hook() {
2001                        global $wp, $wpdb;
2002                        $query = $GLOBALS['wpdb'];
2003                        //echo json_decode($_POST['data']);
2004                        print_r($_POST['data']);
2005                        update_option( 'ladiflow_hook_configs', $_POST['data'] );
2006                        exit;
2007                }
2008
2009                public function publish_lp($ladiPageKey = '') {
2010                        global $wp, $wpdb;
2011                        $query = $GLOBALS['wpdb'];
2012                       
2013                        if ($ladiPageKey === '' && (isset($_POST['ladipage_key']) && trim($_POST['ladipage_key']) != ''))
2014                                $ladiPageKey = trim($_POST['ladipage_key']);
2015                       
2016                        if ($ladiPageKey) {
2017                                $url = sprintf("https://api.ladipage.com/2.0/get-source-by-ladipage-key?ladipage_key=%s", $ladiPageKey);
2018                                $jsonString = file_get_contents($url);
2019                                if (!$jsonString) {
2020                                        $jsonString = get_web_page($url);
2021                                }
2022
2023                                if ($jsonString) {
2024                                        $response = json_decode($jsonString);
2025                                        if (isset($response->code) && $response->code == 200) {
2026                                                $data = $response->data;
2027                                                if (!isset($data->url) || $data->url == '') {
2028                                                        wp_send_json( array(
2029                                                                'code'    => 403,
2030                                                                'message' => __( 'Page URL invalid!' )
2031                                                        ) ); exit;
2032                                                }
2033
2034                                                $pageId = $this->get_id_by_slug($data->url);
2035                                                if (!$pageId) {
2036                                                        try {
2037                                                                kses_remove_filters();
2038                                                                $id = wp_insert_post(
2039                                                                        array(
2040                                                                                'post_title'=>$data->title . ' - LadiPage', 
2041                                                                                'post_name'=>$data->url, 
2042                                                                                'post_type'=>'page', 
2043                                                                                'post_content'=> trim($data->html), 
2044                                                                                'post_status' => 'publish',
2045                                                                                'filter' => true ,
2046                                                                                'page_template'  => 'null-template.php'
2047                                                                        )
2048                                                                );
2049
2050                                                                if ($id) {
2051                                                                        updateSource($data->url, $data->html);
2052                                                                        wp_send_json( array(
2053                                                                                'code'    => 200,
2054                                                                                'message' => __( "Publish successfully! Page URL: " . site_url() . '/' . $data->url)
2055                                                                        ) ); exit;
2056                                                                }
2057                                                        } catch (Exception $ex) {
2058                                                                wp_send_json( array(
2059                                                                        'code'    => 500,
2060                                                                        'message' => __( $ex->message )
2061                                                                ) ); exit;
2062                                                        }
2063                                                       
2064                                                } else {                                                       
2065                                                        kses_remove_filters();
2066                                                        $post = array(
2067                                                                'ID' => $pageId,
2068                                                                'post_title' => $data->title . ' - LadiPage', 
2069                                                    'post_content' => trim($data->html), 
2070                                                        );
2071                                                if (wp_update_post( $post )) {
2072                                                                updateSource($data->url, $data->html);
2073                                                                wp_send_json( array(
2074                                                                                'code'    => 200,
2075                                                                                'message' => __( "Publish successfully! Page URL: " . site_url() . '/' . $data->url)
2076                                                                        ) ); exit;
2077                                                        }
2078                                                        wp_send_json( array(
2079                                                                'code'    => 500,
2080                                                                'message' => __( "Can not update HTML for this Page")
2081                                                        ) ); exit;
2082                                                }
2083                                        } else {
2084                                                wp_send_json( array(
2085                                                        'code'    => 500,
2086                                                        'message' => __( $response->message )
2087                                                ) ); exit;
2088                                        }
2089                                }
2090
2091                                wp_send_json( array(
2092                                        'code'    => 500,
2093                                        'message' => __( "Can not update HTML from this LadiPage Key. Please try publish again" )
2094                                ) ); exit;
2095                        }
2096                }
2097
2098                public function generateRandomString($length = 10) {
2099                    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
2100                    $charactersLength = strlen($characters);
2101                    $randomString = '';
2102                    for ($i = 0; $i < $length; $i++) {
2103                        $randomString .= $characters[rand(0, $charactersLength - 1)];
2104                    }
2105                    return $randomString;
2106                }
2107
2108        }
2109
2110        function Ladipage() {
2111                return Ladipage::instance();
2112        }
2113
2114        Ladipage();
2115}
2116
2117function get_web_page($request, $post = 0) {
2118        $data = array('message' => '', 'content' => '');
2119
2120        if (function_exists('curl_exec')) {
2121                $ch = curl_init();
2122                if ($post == 1) {
2123                        curl_setopt($ch, CURLOPT_POST,1);
2124                }
2125                curl_setopt($ch, CURLOPT_USERAGENT, getRandomUserAgent());
2126                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 5);
2127                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
2128                curl_setopt($ch, CURLOPT_URL, $request);
2129                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
2130                $response = curl_exec($ch);
2131                if (!$response) {
2132                        $data['message'] = 'cURL Error Number ' . curl_errno($ch) . ' : ' . curl_error($ch);
2133                } else {
2134                        $data['content'] = $response;
2135                }
2136                curl_close($ch);
2137        }
2138
2139        return $response;
2140}
2141
2142function _mkdir() {
2143        $sourceFolder = WP_CONTENT_DIR . '/ladipage/';
2144        if ( !file_exists( $sourceFolder ) && !is_dir( $sourceFolder ) ) {
2145                @mkdir($sourceFolder, 0777); 
2146        } 
2147}
2148
2149function stopLandingPage($url) {
2150        try {
2151                $sourceFolder = WP_CONTENT_DIR . '/ladipage/';
2152                $path = $sourceFolder . '/' . $url . '.html';
2153                if ( file_exists( $path )) {
2154                        @unlink($path);
2155                }
2156        } catch (Exception $ex) {
2157                print_r($ex);
2158        }
2159}
2160
2161function updateSource($url, $html) {
2162        try {
2163                $sourceFolder = WP_CONTENT_DIR . '/ladipage/';
2164                $path = $sourceFolder . '/' . $url . '.html';
2165                @file_put_contents($path, $html);
2166        } catch (Exception $ex) {
2167                print_r($ex);
2168        }
2169}
2170?>
Note: See TracBrowser for help on using the repository browser.