diff --git a/ayecode-connect.php b/ayecode-connect.php index 14ff87e..279d662 100755 --- a/ayecode-connect.php +++ b/ayecode-connect.php @@ -4,7 +4,7 @@ * Plugin Name: AyeCode Connect * Plugin URI: https://ayecode.io/ * Description: A service plugin letting users connect AyeCode Services to their site. - * Version: 1.2.19 + * Version: 1.3.0 * Author: AyeCode * Author URI: https://ayecode.io * Requires at least: 4.7 @@ -20,7 +20,7 @@ } if ( !defined( 'AYECODE_CONNECT_VERSION' ) ) { - define( 'AYECODE_CONNECT_VERSION', '1.2.19' ); + define( 'AYECODE_CONNECT_VERSION', '1.3.0' ); } if ( !defined( 'AYECODE_CONNECT_SSL_VERIFY' ) ) { @@ -65,18 +65,19 @@ function ayecode_connect() { * * @return array */ -function ayecode_connect_args(){ - $base_url = 'https://ayecode.io'; - return array( - 'remote_url' => $base_url, //URL to the WP site containing the WP_Service_Provider class - 'connection_url' => $base_url.'/connect', //This should be a custom page the authinticates a user the calls the WP_Service_Provider::connect_site() method - 'api_url' => $base_url.'/wp-json/', //Might be different for you - 'api_namespace' => 'ayecode/v1', - 'local_api_namespace' => 'ayecode-connect/v1', //Should be unique for each client implementation - 'prefix' => 'ayecode_connect', //A unique prefix for things (accepts alphanumerics and underscores). Each client on a given site should have it's own unique prefix - 'textdomain' => 'ayecode-connect', - 'version' => AYECODE_CONNECT_VERSION, - ); +function ayecode_connect_args() { + $base_url = 'https://ayecode.io'; + + return array( + 'remote_url' => $base_url, //URL to the WP site containing the WP_Service_Provider class + 'connection_url' => $base_url . '/connect', //This should be a custom page the authinticates a user the calls the WP_Service_Provider::connect_site() method + 'api_url' => $base_url . '/wp-json/', //Might be different for you + 'api_namespace' => 'ayecode/v1', + 'local_api_namespace' => 'ayecode-connect/v1', //Should be unique for each client implementation + 'prefix' => 'ayecode_connect', //A unique prefix for things (accepts alphanumerics and underscores). Each client on a given site should have it's own unique prefix + 'textdomain' => 'ayecode-connect', + 'version' => AYECODE_CONNECT_VERSION, + ); } /** diff --git a/includes/class-ayecode-connect-remote-actions.php b/includes/class-ayecode-connect-remote-actions.php index d9c6e88..c44dd89 100755 --- a/includes/class-ayecode-connect-remote-actions.php +++ b/includes/class-ayecode-connect-remote-actions.php @@ -10,7 +10,6 @@ exit; } - if ( ! class_exists( 'AyeCode_Connect_Remote_Actions' ) ) { /** @@ -41,7 +40,7 @@ class AyeCode_Connect_Remote_Actions { * * @var */ - public $debug; + public $debug = false; /** * Holds the settings values. @@ -89,6 +88,11 @@ public static function instance( $prefix = '', $client = '' ) { 'update_options' => 'update_options', 'import_menus' => 'import_menus', 'import_content' => 'import_content', + 'remote_import_options' => 'remote_import_options', + 'remote_import_categories' => 'remote_import_categories', + 'remote_import_templates' => 'remote_import_templates', + 'remote_import_posts' => 'remote_import_posts', + 'remote_import_menus' => 'remote_import_menus' ); // set php limits @@ -106,37 +110,24 @@ public static function instance( $prefix = '', $client = '' ) { add_action( $prefix . '_remote_action_' . $action, array( self::$instance, $call - ) ); // set settings + ), 10,2 ); // set settings } - } - } return self::$instance; } - public function debug_log( $call, $type, $args = array() ){ - $error_str = "AC Debug: $call: $type : ".memory_get_usage()." "; - if ( ! empty( $args ) ) { - $error_str .= print_r($args,true); - } - - if ( $error_str ) { - error_log($error_str); - } - } - /** * Delete the old categories. * * @param $cpt */ - public function delete_gd_categories($cpt){ - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + public function delete_gd_categories( $cpt ) { + $this->debug_log( 'start', __METHOD__ . ':' . $cpt, __FILE__, __LINE__ ); $taxonomy = $cpt.'category'; + $terms = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false, @@ -144,23 +135,24 @@ public function delete_gd_categories($cpt){ if ( ! empty( $terms ) ) { foreach ( $terms as $term ) { - - // maybe delete default image and logo + // Maybe delete default image and logo $attachment_data = get_term_meta( $term->term_id, 'ct_cat_icon', true ); + if ( is_array( $attachment_data ) && ! empty( $attachment_data['id'] ) ) { wp_delete_attachment($attachment_data['id'], true); } + $attachment_data = get_term_meta( $term->term_id, 'ct_cat_default_img', true ); + if ( is_array( $attachment_data ) && ! empty( $attachment_data['id'] ) ) { wp_delete_attachment($attachment_data['id'], true); } wp_delete_term( $term->term_id, $taxonomy ); } - } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__ . ':' . $cpt, __FILE__, __LINE__ ); } /** @@ -172,30 +164,41 @@ public function delete_gd_categories($cpt){ */ public function sanitize_categories( $categories ) { $sanitized = array(); + if ( ! empty( $categories ) ) { foreach ( $categories as $cpt => $cats ) { - $cpt = sanitize_title_with_dashes($cpt); + $cpt = sanitize_title_with_dashes( $cpt ); + if ( ! empty( $cats ) ) { foreach ( $cats as $key => $cat ) { $key = sanitize_title_with_dashes( $key ); + //$this->debug_log( $cat, __METHOD__ . ':before', __FILE__, __LINE__ ); + if ( ! empty( $cat['name'] ) ) { - $sanitized[ $cpt ][ $key ]['name'] = sanitize_title( $cat['name'] ); + $sanitized[ $cpt ][ $key ]['name'] = sanitize_text_field( $cat['name'] ); } + if ( ! empty( $cat['icon'] ) ) { $sanitized[ $cpt ][ $key ]['icon'] = esc_url_raw( $cat['icon'] ); } + if ( ! empty( $cat['default_img'] ) ) { $sanitized[ $cpt ][ $key ]['default_img'] = esc_url_raw( $cat['default_img'] ); } + if ( ! empty( $cat['font_icon'] ) ) { $sanitized[ $cpt ][ $key ]['font_icon'] = sanitize_text_field( $cat['font_icon'] ); } + if ( ! empty( $cat['color'] ) ) { $sanitized[ $cpt ][ $key ]['color'] = sanitize_hex_color( $cat['color'] ); } + if ( ! empty( $cat['demo_post_id'] ) ) { $sanitized[ $cpt ][ $key ]['demo_post_id'] = absint( $cat['demo_post_id'] ); } + + //$this->debug_log( $sanitized[ $cpt ][ $key ], __METHOD__ . ':after', __FILE__, __LINE__ ); } } } @@ -210,14 +213,12 @@ public function sanitize_categories( $categories ) { * @return array */ public function import_content() { - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); $result = array( "success" => false ); // validate if ( $this->validate_request() ) { - // de-sanitize for mod-security if ( ! empty( $_REQUEST['categories'] ) ) { $_REQUEST['categories'] = str_replace( $this->str_replace_args( true ), $this->str_replace_args( false ), $_REQUEST['categories'] ); @@ -235,12 +236,12 @@ public function import_content() { if ( ! empty( $categories ) && class_exists( 'GeoDir_Admin_Dummy_Data' ) ) { foreach ( $categories as $cpt => $cats ) { - // delete cats self::delete_gd_categories($cpt); GeoDir_Admin_Dummy_Data::create_taxonomies( $cpt, $cats ); $tax = new GeoDir_Admin_Taxonomies(); + // set the replacements ids foreach ( $cats as $cat ) { $term = get_term_by('name', $cat['name'], $cpt.'category'); @@ -250,19 +251,17 @@ public function import_content() { } // regenerate term icons - if(method_exists($tax,'regenerate_term_icon')) - $tax->regenerate_term_icon( $term->term_id ); + if ( method_exists( $tax,'regenerate_term_icon' ) ) { + $tax->regenerate_term_icon( $term->term_id ); + } } - } update_option('_acdi_replacement_cat_ids',$cat_old_and_new); } - // maybe remove dummy data if ( ! empty( $_REQUEST['remove_dummy_data'] ) ) { - $post_types = geodir_get_posttypes( 'names' ); if ( ! empty( $post_types ) ) { @@ -282,8 +281,8 @@ public function import_content() { // maybe set page featured images $fi = get_option('_acdi_page_featured_images'); - if ( ! empty( $fi ) ) { + if ( ! empty( $fi ) ) { foreach($fi as $p => $i){ $image = (array) GeoDir_Media::get_external_media( $i, '',array('image/jpg', 'image/jpeg', 'image/gif', 'image/png', 'image/webp'),array('ext'=>'png','type'=>'image/png') ); @@ -298,18 +297,15 @@ public function import_content() { delete_option('_acdi_page_featured_images'); } - } - // posts, note that everything is sanitised further down, wp_insert_post passes everything through sanitize_post() $posts = ! empty( $_REQUEST['posts'] ) ? json_decode( stripslashes( $_REQUEST['posts'] ), true ) : array(); if ( ! empty( $posts ) && class_exists( 'GeoDir_Admin_Dummy_Data' ) ) { - $hello_world_trashed = false; - foreach ( $posts as $post_info ) { + foreach ( $posts as $post_info ) { unset( $post_info['ID'] ); $post_info['post_title'] = wp_strip_all_tags( $post_info['post_title'] ); // WP does not automatically do this @@ -326,7 +322,6 @@ public function import_content() { // post stuff if($post_info['post_type']=='post' && $insert_result){ - // maybe soft delete original hello world post if ( ! $hello_world_trashed ) { wp_delete_post(1,false); @@ -370,16 +365,10 @@ public function import_content() { } } } - - - } - } - } - // page templates, note that everything is sanitised further down, wp_insert_post passes everything through sanitize_post() $pages = ! empty( $_REQUEST['pages'] ) ? json_decode( stripslashes( $_REQUEST['pages'] ), true ) : array(); @@ -387,7 +376,6 @@ public function import_content() { $old_and_new = array(); if ( ! empty( $pages ) && function_exists( 'geodir_get_settings' ) ) { - // remove pages self::delete_demo_posts( 'page' ); @@ -421,7 +409,6 @@ public function import_content() { } } - // WP if ( ! empty( $pages['wp'] ) ) { foreach ( $pages['wp'] as $type => $page ) { @@ -437,34 +424,30 @@ public function import_content() { if ( $image_url ) { $featured_images_assign[$post_id] = $image_url; } - - } if ( ! empty( $featured_images_assign ) ) { update_option('_acdi_page_featured_images', $featured_images_assign); } - } // Elementor @todo add check for elementor pro if ( ! empty( $pages['elementor'] ) ) { - $default_kit_id = get_option( 'elementor_active_kit' ); $new_kit_id = 0; + delete_option( 'elementor_active_kit' ); - foreach ( $pages['elementor'] as $cpt => $page_templates ) { - // remove old demos + foreach ( $pages['elementor'] as $cpt => $page_templates ) { + // Remove old demos $this->delete_demo_posts( $cpt ); $archives = array(); $items = array(); if ( ! empty( $page_templates ) ) { - foreach ( $page_templates as $page ) { - $post_id = $this->import_page_template( $page, 'elementor', $cpt ); + if ( $post_id && $page['demo_post_id'] ) { $old_id = absint( $page['demo_post_id'] ); $old_and_new[ $old_id ] = $post_id; @@ -491,24 +474,20 @@ public function import_content() { update_option( 'elementor_active_kit', $new_kit_id); } - // temp save replace ids - update_option('_acdi_replacement_post_ids',$old_and_new); - update_option('_acdi_replacement_archive_item_ids',$items); - update_option( '_acdi_original_elementor_active_kit', $default_kit_id); + update_option( '_acdi_replacement_post_ids', $old_and_new ); + update_option( '_acdi_replacement_archive_item_ids', $items ); + update_option( '_acdi_original_elementor_active_kit', $default_kit_id ); // extras if ( ! empty( $old_and_new ) ) { - // update the elementor display conditions $display_conditions = get_option( 'elementor_pro_theme_builder_conditions' ); $new_display_conditions = $display_conditions; if ( ! empty( $display_conditions ) ) { foreach ( $display_conditions as $type => $condition ) { if ( ! empty( $condition ) ) { - foreach ( $condition as $id => $rule ) { - if ( isset( $old_and_new[ $id ] ) ) { unset( $new_display_conditions[ $type ][ $id ] ); $new_id = absint( $old_and_new[ $id ] ); @@ -518,8 +497,8 @@ public function import_content() { } } } - update_option( 'elementor_pro_theme_builder_conditions', $new_display_conditions ); + update_option( 'elementor_pro_theme_builder_conditions', $new_display_conditions ); // check pages for replaceable data if ( ! empty( $old_and_new ) ) { @@ -527,45 +506,39 @@ public function import_content() { $this->parse_elementor_data( $id ); } } - } - } // clear elementor cache after changes if ( defined( 'ELEMENTOR_VERSION' ) ) { \Elementor\Plugin::$instance->files_manager->clear_cache(); } - } - - } - // set as success $result = array( "success" => true ); } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); return $result; } - public function parse_elementor_data($post_id){ - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + public function parse_elementor_data( $post_id ) { + //$this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); $_elementor_data = get_post_meta( $post_id, '_elementor_data', true ); - if ( ! empty( $_elementor_data ) ) { - $old_and_new = get_option('_acdi_replacement_post_ids'); - $cat_old_and_new = get_option('_acdi_replacement_cat_ids'); - $items = get_option('_acdi_replacement_archive_item_ids'); - $demo_url = get_option('_acdi_demo_url'); + if ( ! empty( $_elementor_data ) ) { + $old_and_new = get_option( '_acdi_replacement_post_ids' ); + $cat_old_and_new = get_option( '_acdi_replacement_cat_ids' ); + $items = get_option( '_acdi_replacement_archive_item_ids' ); + $demo_url = get_option( '_acdi_demo_url' ); - // replace archive item ids + // Replace archive item ids $original = $_elementor_data; + if ( ! empty( $items ) ) { foreach ( $items as $old_item => $new_item ) { $_elementor_data = str_replace( @@ -584,8 +557,7 @@ public function parse_elementor_data($post_id){ } } - - // replace cat ids + // Replace cat ids if ( ! empty( $cat_old_and_new ) ) { foreach ( $cat_old_and_new as $old_item => $new_item ) { $_elementor_data = str_replace( @@ -602,7 +574,7 @@ public function parse_elementor_data($post_id){ } } - // replace URL + // Replace URL if ( $demo_url ) { $_elementor_data = str_replace( array( @@ -617,14 +589,12 @@ public function parse_elementor_data($post_id){ ); } - if ( $original !== $_elementor_data ) { update_post_meta( $post_id, '_elementor_data', wp_slash( $_elementor_data ) ); } } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } - + //$this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); } /** @@ -633,8 +603,7 @@ public function parse_elementor_data($post_id){ * @param $cpt */ public function delete_demo_posts( $cpt ) { - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); // Elementor allow delete kit (without this it throws a confirmation page and blocks import) $_GET['force_delete_kit'] = 1; @@ -647,17 +616,16 @@ public function delete_demo_posts( $cpt ) { 'numberposts' => - 1 ) ); + if ( ! empty( $posts ) ) { foreach ( $posts as $p ) { - if($p->post_name != 'default-kit'){ + if ( $p->post_name != 'default-kit' ) { wp_delete_post( $p->ID, true ); } - } } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } - + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); } /** @@ -667,12 +635,11 @@ public function delete_demo_posts( $cpt ) { * @param $files */ public function set_external_media( $post_id, $files ) { - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + //$this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); if ( ! empty( $files ) && class_exists( 'GeoDir_Media' ) ) { - $field = !empty($file['type']) ? esc_attr($file['type'] ) : 'post_images'; foreach ( $files as $file ) { + $field = ! empty( $file['type'] ) ? esc_attr( $file['type'] ) : 'post_images'; $file_url = ! empty( $file['file'] ) ? esc_url_raw( $file['file'] ) : ''; $file_title = ! empty( $file['title'] ) ? esc_attr( $file['title'] ) : ''; $file_caption = ! empty( $file['caption'] ) ? esc_url_raw( $file['caption'] ) : ''; @@ -682,15 +649,23 @@ public function set_external_media( $post_id, $files ) { $placeholder = true; $metadata = ! empty( $file['metadata'] ) ? maybe_unserialize( $file['metadata'] ) : ''; + if ( ! empty( $metadata ) && is_array( $metadata ) && $file_url && ( geodir_is_full_url( $file_url ) || strpos( $file_url, '#' ) === 0 ) ) { + if ( isset( $metadata['file'] ) ) { + unset( $metadata['file'] ); + } + + if ( isset( $metadata['sizes'] ) ) { + unset( $metadata['sizes'] ); + } + } + GeoDir_Media::insert_attachment( $post_id, $field, $file_url, $file_title, $file_caption, $order, $approved, $placeholder, $other_id, $metadata ); } } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } - + //$this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); } - /** * Import page templates. * @@ -701,8 +676,7 @@ public function set_external_media( $post_id, $files ) { * @return int|WP_Error */ public function import_page_template( $page_template, $type = '', $cpt = '' ) { - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); /* * The API can't insert unfiltered HTML which is needed for some page builders, so we allow this here and add the filters back at the end. @@ -711,26 +685,27 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { $settings = geodir_get_settings(); - // some meta data may need to be unserialized + // Some meta data may need to be unserialized $page_template = (array) $page_template; + if ( ! empty( $page_template['meta_input'] ) ) { foreach ( $page_template['meta_input'] as $key => $val ) { - // elementor json needs slashed + // Elementor json needs slashed if ( $key != '_elementor_data' ) { $val = wp_unslash( $val ); } - $page_template['meta_input'][$key] = maybe_unserialize( $val ); + $page_template['meta_input'][$key] = maybe_unserialize( $val ); } } - $post_id = 0; - if ( $type == 'elementor' ) { - // skip Default kit (maybe we want to update this in future? - //if( isset($page_template['meta_input']['_elementor_template_type']) && $page_template['meta_input']['_elementor_template_type'] == 'kit' ){return 0;} + if ( ! empty( $page_template['post_title'] ) ) { + //$this->debug_log( $page_template['post_title'], __METHOD__ . ':' . $type, __FILE__, __LINE__ ); + } + if ( $type == 'elementor' ) { $page_template['post_title'] = wp_strip_all_tags( $page_template['post_title'] ); $page_template['post_author'] = 1; $page_template['post_type'] = $cpt; @@ -739,18 +714,16 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { $post_id = wp_insert_post( $page_template, true ); if ( is_wp_error( $post_id ) ) { - $error_string = $post_id->get_error_message(); - if ( $this->debug ) { $this->debug_log( __METHOD__, 'post insert error', $error_string ); } - }else{ - if ( $this->debug ) { $this->debug_log( __METHOD__, 'post inserted', $post_id ); } + $this->debug_log( $post_id->get_error_message(), __METHOD__ . ':wp_insert_post error', __FILE__, __LINE__ ); + } else { + $this->debug_log( $post_id, __METHOD__ . ':wp_insert_post', __FILE__, __LINE__ ); } // maybe set tax (not working from wp_insert_post) if ( $post_id && ! empty( $page_template['tax_input'] ) ) { - - // default kit - if(!empty($page_template['meta_input']['active_kit'])){ - update_option( 'elementor_active_kit', $post_id); + // Default kit + if ( ! empty( $page_template['meta_input']['active_kit'] ) ) { + update_option( 'elementor_active_kit', $post_id ); } if ( ! function_exists( 'wp_create_term' ) ) { @@ -763,11 +736,9 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { wp_set_object_terms( $post_id, $slug, $tax ); } } - - } elseif ( $type && $cpt ) { - $type = sanitize_title_with_dashes( $type ); - $cpt = sanitize_title_with_dashes( $cpt ); + $type = sanitize_title_with_dashes( $type ); + $cpt = sanitize_title_with_dashes( $cpt ); // GD $page_templates = array( @@ -779,10 +750,11 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { 'page_archive_item', 'page_details', ); + if ( in_array( $type, $page_templates ) ) { $page_template = (array) $page_template; - $current_page_id = 0; + if ( $cpt == 'core' ) { $current_page_id = ! empty( $settings[ $type ] ) ? absint( $settings[ $type ] ) : 0; } else { @@ -790,10 +762,9 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { } if ( false === get_post_status( $current_page_id ) ) { - // we create a new page + // We create a new page } else { -// $page_template['ID'] = absint( $current_page_id ); - // send to trash + // Send to trash wp_delete_post( absint( $current_page_id ), false ); } @@ -803,21 +774,16 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { $page_template['post_author'] = 1; $post_id = wp_insert_post( $page_template, true ); - if ( ! is_wp_error( $post_id ) && $post_id ) { - if ( $cpt == 'core' ) { geodir_update_option( $type, $post_id ); } else { $settings['post_types'][ $cpt ][ $type ] = $post_id; geodir_update_option( 'post_types', $settings['post_types'] ); } - } - } - // UWP $page_templates = array( 'register_page', @@ -830,20 +796,20 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { 'users_page', 'user_list_item_page', ); - if ( function_exists('uwp_get_settings') && in_array( $type, $page_templates ) ) { + + if ( function_exists( 'uwp_get_settings' ) && in_array( $type, $page_templates ) ) { $settings = uwp_get_settings(); $page_template = (array) $page_template; - $current_page_id = 0; + if ( $cpt == 'core' ) { $current_page_id = ! empty( $settings[ $type ] ) ? absint( $settings[ $type ] ) : 0; } if ( false === get_post_status( $current_page_id ) ) { - // we create a new page + // We create a new page } else { - //$page_template['ID'] = absint( $current_page_id ); - // send to trash + // Send to trash wp_delete_post( absint( $current_page_id ), false ); } @@ -853,28 +819,22 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { $page_template['post_author'] = 1; $post_id = wp_insert_post( $page_template, true ); - if ( ! is_wp_error( $post_id ) && $post_id ) { - if ( $cpt == 'core' ) { uwp_update_option( $type, $post_id ); } - } - } - - } elseif ( $type == 'page_on_front' ) { - $current_page_id = get_option( 'page_on_front' ); + if ( false === get_post_status( $current_page_id ) ) { - // we create a new page + // We create a new page } else { -// $page_template['ID'] = absint( $current_page_id ); - // send to trash + // Send to trash wp_delete_post( absint( $current_page_id ), false ); } + $page_template['post_title'] = wp_strip_all_tags( $page_template['post_title'] ); $page_template['post_type'] = 'page'; $page_template['post_status'] = 'publish'; @@ -886,37 +846,33 @@ public function import_page_template( $page_template, $type = '', $cpt = '' ) { update_option( 'show_on_front', 'page' ); update_option( 'page_on_front', $post_id ); } - }elseif($type && $cpt==''){ - + } elseif ( $type && $cpt == '' ) { $page_template['post_title'] = wp_strip_all_tags( $page_template['post_title'] ); $page_template['post_type'] = 'page'; $page_template['post_status'] = 'publish'; $page_template['post_author'] = 1; $post_id = wp_insert_post( $page_template, true ); - if(!empty($page_template['meta_input']['_page_for_posts'])){ + if ( ! empty( $page_template['meta_input']['_page_for_posts'] ) ) { update_option( 'page_for_posts', $post_id ); } - } // We add back the filters for security kses_init_filters(); - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); return $post_id; } - /** * Import menus. * * @return array */ public function import_menus() { - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); $result = array( "success" => false ); @@ -932,12 +888,11 @@ public function import_menus() { } } - // set as success $result = array( "success" => true ); } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); return $result; } @@ -951,8 +906,7 @@ public function import_menus() { * @return bool */ public function import_menu( $location, $menu ) { - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); $result = false; @@ -1056,14 +1010,11 @@ public function import_menu( $location, $menu ) { } } } - } - } - } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); return $result; } @@ -1074,14 +1025,12 @@ public function import_menu( $location, $menu ) { * @return array */ public function update_options() { - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); $result = array( "success" => false ); // validate if ( $this->validate_request() ) { - // de-sanitize for mod-security if ( ! empty( $_REQUEST['update'] ) ) { $_REQUEST['update'] = str_replace( $this->str_replace_args( true ), $this->str_replace_args( false ), $_REQUEST['update'] ); @@ -1184,7 +1133,7 @@ public function update_options() { $result = array( "success" => true ); } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); return $result; } @@ -1200,18 +1149,21 @@ public function can_modify_option( $key ){ $can_modify = false; $white_list = array( - 'elementor_pro_theme_builder_conditions', 'ayecode-ui-settings', 'aui_options', 'custom_css', 'geodir_settings', 'widget_block', - 'sidebars_widgets', - 'elementor_disable_color_schemes', - 'elementor_disable_typography_schemes', + 'sidebars_widgets' ); - if( in_array($key,$white_list) || substr( $key, 0, 11 ) === "theme_mods_" || substr( $key, 0, 7 ) === "widget_" ){ + if ( defined( 'ELEMENTOR_VERSION' ) ) { + $white_list[] = 'elementor_pro_theme_builder_conditions'; + $white_list[] = 'elementor_disable_color_schemes'; + $white_list[] = 'elementor_disable_typography_schemes'; + } + + if ( in_array( $key,$white_list ) || substr( $key, 0, 11 ) === "theme_mods_" || substr( $key, 0, 7 ) === "widget_" ) { $can_modify = true; } @@ -1226,15 +1178,27 @@ public function can_modify_option( $key ){ public function import_geodirectory_settings( $settings ) { global $wpdb; - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); // custom_fields if ( ! empty( $settings['custom_fields'] ) && defined( 'GEODIR_CUSTOM_FIELDS_TABLE' ) ) { + $this->debug_log( 'start', __METHOD__ . ':custom_fields', __FILE__, __LINE__ ); + // empty the table first $wpdb->query( "TRUNCATE TABLE " . GEODIR_CUSTOM_FIELDS_TABLE ); + $has_event_table = $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}geodir_gd_event_detail'" ); // insert foreach ( $settings['custom_fields'] as $custom_field ) { + if ( ! empty( $custom_field['post_type'] ) && $custom_field['post_type'] == 'gd_event' && ! $has_event_table ) { + continue; + } + + // Create check & default package. + if ( ! empty( $custom_field['htmlvar_name'] ) && $custom_field['htmlvar_name'] == 'package_id' && function_exists( 'geodir_pricing_default_package_id' ) ) { + geodir_pricing_default_package_id( $custom_field['post_type'] ); + } + // maybe unserialize and change name if ( ! empty( $custom_field['extra_fields'] ) ) { $custom_field['extra'] = maybe_unserialize( $custom_field['extra_fields'] ); @@ -1246,10 +1210,12 @@ public function import_geodirectory_settings( $settings ) { } unset( $custom_field['id'] ); - $r = geodir_custom_field_save( $custom_field ); - } + //$this->debug_log( $custom_field, __METHOD__ . ':custom_field', __FILE__, __LINE__ ); + $r = geodir_custom_field_save( $custom_field ); + } + $this->debug_log( 'end', __METHOD__ . ':custom_fields', __FILE__, __LINE__ ); } // sort_fields @@ -1261,7 +1227,6 @@ public function import_geodirectory_settings( $settings ) { foreach ( $settings['sort_fields'] as $sort_fields ) { GeoDir_Settings_Cpt_Sorting::save_custom_field( $sort_fields ); } - } // tabs @@ -1274,7 +1239,6 @@ public function import_geodirectory_settings( $settings ) { unset( $tab['id'] );// we need insert not update GeoDir_Settings_Cpt_Tabs::save_tab_item( $tab ); } - } // Advanced Search @@ -1295,8 +1259,7 @@ public function import_geodirectory_settings( $settings ) { // not implemented yet } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } - + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); } /** @@ -1305,11 +1268,11 @@ public function import_geodirectory_settings( $settings ) { * @return array */ public function update_licences() { - $result = array( "success" => false ); + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } + $result = array( "success" => false ); - // validate + // Validate if ( $this->validate_request() ) { $result = array( "success" => true ); $installed = ! empty( $_REQUEST['installed'] ) ? $this->sanitize_licences( $_REQUEST['installed'] ) : array(); @@ -1346,7 +1309,7 @@ public function update_licences() { } } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); return $result; } @@ -1501,6 +1464,8 @@ private function validate_request() { $result = true; } + $result = true; // @TODO validate for remote request instead from server. + return $result; } @@ -1510,7 +1475,6 @@ private function validate_request() { * @return string */ private function get_server_ip() { - if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; @@ -1529,7 +1493,6 @@ private function get_server_ip() { return $ip; } - /** * Validate a download url is from our own server: 173.208.153.114 * @@ -1542,12 +1505,16 @@ private function validate_download_url( $url ) { if ( $url ) { $parse = parse_url( $url ); + if ( ! empty( $parse['host'] ) ) { $ip = gethostbyname( $parse['host'] ); + if ( $ip === "173.208.153.114" ) { // AyeCode.io Server $result = true; - } elseif ( $ip === "198.143.164.252" ) { // wordpress.org server + } else if ( $ip === "198.143.164.252" ) { // wordpress.org server $result = true; + } else if ( $ip === "127.0.0.1" ) { + //$result = true; // @todo localhost } } } @@ -1562,42 +1529,58 @@ private function validate_download_url( $url ) { * * @return mixed */ - public function install_plugin( $result ) { + public function install_plugin( $result, $request = array() ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } - - // validate + // Validate if ( ! $this->validate_request() ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return array( "success" => false ); } - include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); //for plugins_api.. + if ( ! function_exists( 'plugins_api' ) ) { + include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); // For plugins_api. + } + + if ( ! empty( $request ) && is_object( $request ) && is_a( $request, 'WP_REST_Request' ) ) { + $params = $request->get_params(); + } else { + $params = $_REQUEST; + } + + $plugin_slug = isset( $params['slug'] ) ? sanitize_title_for_query( $params['slug'] ) : ''; - $plugin_slug = isset( $_REQUEST['slug'] ) ? sanitize_title_for_query( $_REQUEST['slug'] ) : ''; $plugin = array( - 'name' => isset( $_REQUEST['name'] ) ? esc_attr( $_REQUEST['name'] ) : '', + 'name' => isset( $params['name'] ) ? esc_attr( $params['name'] ) : '', 'repo-slug' => $plugin_slug, - 'file-slug' => isset( $_REQUEST['file-slug'] ) ? sanitize_title_for_query( $_REQUEST['file-slug'] ) : '', - 'download_link' => isset( $_REQUEST['download_link'] ) ? esc_url_raw( $_REQUEST['download_link'] ) : '', - 'activate' => isset( $_REQUEST['activate'] ) && $_REQUEST['activate'] ? true : false, - 'network_activate' => isset( $_REQUEST['network_activate'] ) && $_REQUEST['network_activate'] ? true : false, + 'file-slug' => isset( $params['file-slug'] ) ? sanitize_title_for_query( $params['file-slug'] ) : '', + 'download_link' => isset( $params['download_link'] ) ? esc_url_raw( $params['download_link'] ) : '', + 'activate' => isset( $params['activate'] ) && $params['activate'] ? true : false, + 'network_activate' => isset( $params['network_activate'] ) && $params['network_activate'] ? true : false, ); - if ( $this->debug ) { $this->debug_log( __METHOD__, 'plugin', $plugin ); } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'plugin_request', $_REQUEST ); } + if ( empty( $plugin['repo-slug'] ) ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return array( "success" => false ); + } $install = $this->background_installer( $plugin_slug, $plugin ); - if ( $install ) { + if ( is_wp_error( $install ) ) { + $this->debug_log( $install->get_error_message(), __METHOD__ . ':background_installer error', __FILE__, __LINE__ ); + + $result = array( "success" => false, 'error' => $install->get_error_message() ); + } else if ( $install ) { $result = array( "success" => true ); } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'end' ); } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); return $result; } - /** * Get slug from path * @@ -1607,7 +1590,7 @@ public function install_plugin( $result ) { */ private function format_plugin_slug( $key ) { $slug = explode( '/', $key ); - $slug = explode( '.', end( $slug ) ); + //$slug = explode( '.', end( $slug ) ); // @todo We use plugin folder as slug, so it breaks when plugin folder is renamed. return $slug[0]; } @@ -1624,17 +1607,26 @@ private function format_plugin_slug( $key ) { * @return bool */ public function background_installer( $plugin_to_install_id, $plugin_to_install ) { - - - if ( $this->debug ) { $this->debug_log( __METHOD__, 'start' ); } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'args', $plugin_to_install ); } + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); + $this->debug_log( $plugin_to_install_id, __METHOD__ . ':plugin_to_install_id', __FILE__, __LINE__ ); + $this->debug_log( $plugin_to_install, __METHOD__ . ':plugin_to_install', __FILE__, __LINE__ ); $task_result = false; + $error = false; + if ( ! empty( $plugin_to_install['repo-slug'] ) ) { - require_once( ABSPATH . 'wp-admin/includes/file.php' ); - require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); - require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); - require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); + if ( ! function_exists( 'WP_Filesystem' ) ) { + require_once( ABSPATH . 'wp-admin/includes/file.php' ); + } + if ( ! function_exists( 'plugins_api' ) ) { + require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' ); + } + if ( ! class_exists( 'WP_Upgrader' ) ) { + require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); + } + if ( ! function_exists( 'get_plugins' ) ) { + require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); + } WP_Filesystem(); @@ -1653,17 +1645,21 @@ public function background_installer( $plugin_to_install_id, $plugin_to_install $installed = true; } + $this->debug_log( $plugin, __METHOD__ . ':plugin', __FILE__, __LINE__ ); + $this->debug_log( $installed, __METHOD__ . ':installed', __FILE__, __LINE__ ); + $this->debug_log( $activate, __METHOD__ . ':activate', __FILE__, __LINE__ ); + // Install this thing! if ( ! $installed ) { // Suppress feedback ob_start(); try { - // if a download link is provided then validate it. if ( ! empty( $plugin_to_install['download_link'] ) ) { - if ( ! $this->validate_download_url( $plugin_to_install['download_link'] ) ) { + ob_end_clean(); + return new WP_Error( 'download_invalid', __( "Download source not valid.", "ayecode-connect" ) ); } @@ -1673,7 +1669,8 @@ public function background_installer( $plugin_to_install_id, $plugin_to_install 'download_link' => esc_url( $plugin_to_install['download_link'] ), ); } else { - if ( $this->debug ) { $this->debug_log( __METHOD__, 'plugin-slug',$plugin_to_install['repo-slug'] ); } + $this->debug_log( $plugin_to_install['repo-slug'], __METHOD__ . ':plugin-slug', __FILE__, __LINE__ ); + $plugin_information = plugins_api( 'plugin_information', array( 'slug' => $plugin_to_install['repo-slug'], 'fields' => array( @@ -1695,25 +1692,44 @@ public function background_installer( $plugin_to_install_id, $plugin_to_install } if ( is_wp_error( $plugin_information ) ) { - throw new Exception( $plugin_information->get_error_message() ); + $this->debug_log( $plugin_information->get_error_message(), __METHOD__ . ':plugins_api error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + ob_end_clean(); + + return $plugin_information; } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'plugin-info' ); } + //$this->debug_log( $plugin_information, __METHOD__ . ':plugin_information', __FILE__, __LINE__ ); + + $package = $plugin_information->download_link; + $this->debug_log( $package, __METHOD__ . ':' . $plugin_to_install['repo-slug'] . ':download_link', __FILE__, __LINE__ ); - $package = $plugin_information->download_link; + $upgrader->init(); $download = $upgrader->download_package( $package ); if ( is_wp_error( $download ) ) { - throw new Exception( $download->get_error_message() ); + $this->debug_log( $download->get_error_message(), __METHOD__ . ':download_package error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + ob_end_clean(); + + return $download; } - if ( $this->debug ) { $this->debug_log( __METHOD__, 'plugin-downloaded' ); } + + $this->debug_log( 'plugin-downloaded', __METHOD__, __FILE__, __LINE__ ); $working_dir = $upgrader->unpack_package( $download, true ); if ( is_wp_error( $working_dir ) ) { - throw new Exception( $working_dir->get_error_message() ); - } + //throw new Exception( $working_dir->get_error_message() ); + ob_end_clean(); + $this->debug_log( $working_dir->get_error_message(), __METHOD__ . ':unpack_package error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $working_dir; + } $result = $upgrader->install_package( array( 'source' => $working_dir, @@ -1723,19 +1739,29 @@ public function background_installer( $plugin_to_install_id, $plugin_to_install 'clear_working' => true, 'hook_extra' => array( 'type' => 'plugin', - 'action' => 'install', - ), + 'action' => 'install' + ) ) ); - if ( $this->debug ) { $this->debug_log( __METHOD__, 'plugin-install', print_r($result, true) ); } - if ( ! is_wp_error( $result ) ) { + //$this->debug_log( $result, __METHOD__ . ':plugin-install', __FILE__, __LINE__ ); + + if ( is_wp_error( $result ) ) { + ob_end_clean(); + + $this->debug_log( $result->get_error_message(), __METHOD__ . ':install_package error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } else { $task_result = true; } + } catch ( Exception $e ) { + ob_end_clean(); -// $activate = true; + $this->debug_log( $e->getMessage(), __METHOD__ . ':plugin_to_install error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); - } catch ( Exception $e ) { -// + return new WP_Error( 'plugin_install_fail', __METHOD__ . ' - ' . $e->getMessage() ); } // Discard feedback @@ -1747,22 +1773,27 @@ public function background_installer( $plugin_to_install_id, $plugin_to_install // Activate this thing if ( $activate ) { try { - if ( $this->debug ) { $this->debug_log( __METHOD__, 'activate_plugin', $plugin ); } - + $this->debug_log( $plugin, __METHOD__ . ':activate_plugin', __FILE__, __LINE__ ); $result = activate_plugin( $plugin, "", $network_activate ); - if ( $this->debug ) { $this->debug_log( __METHOD__, 'plugin-activate', print_r($result, true) ); } + //$this->debug_log( $result, __METHOD__ . ':plugin-activate', __FILE__, __LINE__ ); - if ( ! is_wp_error( $result ) ) { + if ( is_wp_error( $result ) ) { + $task_result = $result; + } else { $task_result = true; } } catch ( Exception $e ) { - $task_result = false; + $this->debug_log( $e->getMessage(), __METHOD__ . ':activate_plugin error', __FILE__, __LINE__ ); + + $task_result = new WP_Error( 'activate_plugin_fail', __METHOD__ . ' - ' . $e->getMessage() ); } } } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return $task_result; } @@ -1774,18 +1805,32 @@ public function background_installer( $plugin_to_install_id, $plugin_to_install * @return mixed */ public function install_theme( $result ) { - // validate + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); + + // Validate if ( ! $this->validate_request() ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return array( "success" => false ); } - require_once ABSPATH . 'wp-admin/includes/file.php'; - require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; - include_once ABSPATH . 'wp-admin/includes/theme.php'; + if ( ! function_exists( 'WP_Filesystem' ) ) { + require_once( ABSPATH . 'wp-admin/includes/file.php' ); + } + + if ( ! class_exists( 'WP_Upgrader' ) ) { + require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' ); + } + + if ( ! function_exists( 'themes_api' ) ) { + require_once( ABSPATH . 'wp-admin/includes/theme.php' ); + } $slug = isset( $_REQUEST['slug'] ) ? sanitize_title_for_query( $_REQUEST['slug'] ) : ''; $download_link = ! empty( $_REQUEST['download_link'] ) ? esc_url_raw( $_REQUEST['download_link'] ) : ''; + $this->debug_log( $slug, __METHOD__ . ':slug', __FILE__, __LINE__ ); + $this->debug_log( $download_link, __METHOD__ . ':download_link', __FILE__, __LINE__ ); if ( empty( $download_link ) ) { $api = themes_api( @@ -1796,56 +1841,709 @@ public function install_theme( $result ) { ) ); + $this->debug_log( $api, __METHOD__ . . ':' . $slug . ':themes_api', __FILE__, __LINE__ ); + if ( is_wp_error( $api ) ) { - array( "success" => false ); + $this->debug_log( $api->get_error_message(), __METHOD__ . ':themes_api error', __FILE__, __LINE__ ); + + $result = array( "success" => false ); + } else if ( ! empty( $api->download_link ) ) { + $download_link = $api->download_link; } + } - $download_link = $api->download_link; + $this->debug_log( $download_link, __METHOD__ . ':' . $slug . ':download_link', __FILE__, __LINE__ ); - } + if ( ! empty( $download_link ) ) { + WP_Filesystem(); + $skin = new WP_Ajax_Upgrader_Skin(); + $upgrader = new Theme_Upgrader( $skin ); + $install = $upgrader->install( $download_link ); + + if ( is_wp_error( $install ) ) { + $error = $install->get_error_message(); + } elseif ( is_wp_error( $skin->result ) ) { + $error = $skin->result->get_error_message(); + } elseif ( $skin->get_errors()->has_errors() ) { + $error = $skin->get_error_messages(); + } elseif ( is_null( $result ) ) { + global $wp_filesystem; + + // Pass through the error from WP_Filesystem if one was raised. + if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { + $error = esc_html( $wp_filesystem->errors->get_error_message() ); + } else { + $error = __( 'Unable to connect to the filesystem. Please confirm your credentials.', 'ayecode-connect' ); + } + } else { + $error = false; + } - $skin = new WP_Ajax_Upgrader_Skin(); - $upgrader = new Theme_Upgrader( $skin ); - $install = $upgrader->install( $download_link ); + if ( $error ) { + $upgrade_messages = $skin->get_upgrade_messages(); - if ( $install ) { - $result = array( "success" => true ); + if ( ! empty( $upgrade_messages ) ) { + $_error = count( $upgrade_messages ) > 1 ? implode( " ", array_slice( $upgrade_messages, -2, 2, true ) ) : $upgrade_messages[0]; + $error .= ' ' . str_replace( $error, "", $_error ); + } + + $this->debug_log( $error, __METHOD__ . ':' . $slug . ':install error', __FILE__, __LINE__ ); + + $result = new WP_Error( 'install_theme_fail', $error ); + } else { + $result = array( "success" => true ); + } } + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return $result; } /** - * Try to set higher limits on the fly + * Update settings. + * + * @param $result + * @param $request + * + * @return mixed */ - public static function set_php_limits() { -// if ( ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) { -// error_reporting( 0 ); -// } -// @ini_set( 'display_errors', 0 ); - - // try to set higher limits for import - $max_input_time = ini_get( 'max_input_time' ); - $max_execution_time = ini_get( 'max_execution_time' ); - $memory_limit = ini_get( 'memory_limit' ); + public function remote_import_options( $result = array(), $request = array() ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); - if ( $max_input_time !== 0 && $max_input_time != -1 && ( ! $max_input_time || $max_input_time < 3000 ) ) { - ini_set( 'max_input_time', 3000 ); + if ( empty( $result ) ) { + $result = array( 'success' => false ); } - if ( $max_execution_time !== 0 && ( ! $max_execution_time || $max_execution_time < 3000 ) ) { - ini_set( 'max_execution_time', 3000 ); + // Validate + if ( ! $this->validate_request() ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; } - if ( $memory_limit && str_replace( 'M', '', $memory_limit ) ) { - if ( str_replace( 'M', '', $memory_limit ) < 256 ) { - ini_set( 'memory_limit', '256M' ); - } + if ( ! empty( $request ) && is_object( $request ) && is_a( $request, 'WP_REST_Request' ) ) { + $params = $request->get_params(); + } else { + $params = array(); } + //$this->debug_log( $update_options, __METHOD__ . ' - params', __FILE__, __LINE__ ); - /* - * The `auto_detect_line_endings` setting has been deprecated in PHP 8.1, + $update_options = ! empty( $params['update'] ) ? $params['update'] : array(); + $merge_options = ! empty( $params['merge'] ) ? $params['merge'] : array(); + $delete_options = ! empty( $params['delete'] ) ? $params['delete'] : array(); + $geodir_settings = ! empty( $params['geodirectory_settings'] ) ? $params['geodirectory_settings'] : array(); + + $errors = array(); + + // Update WP options. + if ( ! empty( $update_options ) ) { + foreach ( $update_options as $option_key => $option_value ) { + if ( $option_key == 'custom_css' ) { + $option_value = wp_strip_all_tags( $option_value ); + + $post_css = wp_update_custom_css_post( $option_value ); + + if ( ! empty( $post_css ) && isset( $post_css->ID ) ) { + set_theme_mod( 'custom_css_post_id', $post_css->ID ); + } + } + + // Theme logo + if ( is_array( $option_value ) && isset( $option_value['custom_logo_src'] ) ) { + $image = (array) GeoDir_Media::get_external_media( esc_url_raw( $option_value['custom_logo_src'] ), '', array( 'image/jpg', 'image/jpeg', 'image/gif', 'image/png', 'image/webp', 'image/svg' ), array( 'ext' => 'png', 'type' => 'image/png' ) ); + + if ( is_wp_error( $image ) ) { + $errors['update'][ $option_key ] = $image->get_error_message(); + } elseif ( is_array( $image ) && ! empty( $image['url'] ) ) { + $attachment_id = GeoDir_Media::set_uploaded_image_as_attachment( $image ); + + if ( is_wp_error( $attachment_id ) ) { + $errors['update'][ $option_key ] = $attachment_id->get_error_message(); + } elseif ( $attachment_id ) { + update_post_meta( $attachment_id, '_ayecode_demo_img', 1 ); + + $option_value['custom_logo'] = $attachment_id; + } + } + } + + if ( $this->can_modify_option( $option_key ) ) { + update_option( sanitize_title_with_dashes( $option_key ), $option_value ); + } + } + } + + // Merge WP options. + if ( ! empty( $merge_options ) ) { + foreach ( $merge_options as $option_key => $option_value ) { + $option_key = sanitize_title_with_dashes( $option_key ); + $current = get_option( $option_key ); + + if( $this->can_modify_option( $option_key ) ) { + // Disable auto terms count to speedup add listing. + if ( is_array( $option_value ) && isset( $option_value['lm_disable_term_auto_count'] ) ) { + $option_value['lm_disable_term_auto_count'] = 1; + } + + if ( ! empty( $current ) && is_array( $current ) ) { + update_option( $option_key, array_merge( $current, $option_value ) ); + } else { + update_option( $option_key, $option_value ); + } + } + } + } + + // Delete WP options + if ( ! empty( $delete_options ) ) { + foreach ( $delete_options as $option_key => $option_value ) { + $option_key = sanitize_title_with_dashes( $option_key ); + + if ( $this->can_modify_option( $option_key ) ){ + delete_option( $option_key ); + } + } + } + + // GD Settings. + if ( ! empty( $geodir_settings ) ) { + // Run the create tables function to add our new columns. + if ( class_exists( 'GeoDir_Admin_Install' ) ) { + global $geodir_options; + + $geodir_options = geodir_get_settings(); // We need to update the global settings values with the new values. + + GeoDir_Admin_Install::create_tables(); + } + + $this->import_geodirectory_settings( $geodir_settings ); + } + + $result = array( 'success' => true, 'errors' => $errors ); + + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + /** + * Import categories. + * + * @param $result + * @param $request + * + * @return mixed + */ + public function remote_import_categories( $result = array(), $request = array() ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); + + if ( empty( $result ) ) { + $result = array( 'success' => false ); + } + + // Validate + if ( ! $this->validate_request() ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + if ( ! empty( $request ) && is_object( $request ) && is_a( $request, 'WP_REST_Request' ) ) { + $params = $request->get_params(); + } else { + $params = array(); + } + + $errors = array(); + $categories = ! empty( $params['categories'] ) ? $this->sanitize_categories( $params['categories'] ) : array(); + //$this->debug_log( $categories, __METHOD__ . ' - categories', __FILE__, __LINE__ ); + + // Import Categories. + if ( ! empty( $categories ) && class_exists( 'GeoDir_Admin_Dummy_Data' ) ) { + foreach ( $categories as $cpt => $cats ) { + self::delete_gd_categories( $cpt ); + + GeoDir_Admin_Dummy_Data::create_taxonomies( $cpt, $cats ); + + $taxonomy = new GeoDir_Admin_Taxonomies(); + + // Set the replacements ids + foreach ( $cats as $cat ) { + $term = get_term_by( 'name', $cat['name'], $cpt . 'category' ); + + if ( ! empty( $term ) && isset( $term->term_id ) && ! empty( $term->term_id ) ) { + $old_cat_id = absint( $cat['demo_post_id'] ); + $cat_old_and_new[ $old_cat_id ] = absint( $term->term_id ); + + // Regenerate term icons + if ( method_exists( $taxonomy, 'regenerate_term_icon' ) ) { + $taxonomy->regenerate_term_icon( $term->term_id ); + } + } + } + } + } + + $result = array( 'success' => true, 'errors' => $errors ); + + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + /** + * Import templates. + * + * @param $result + * @param $request + * + * @return mixed + */ + public function remote_import_templates( $result = array(), $request = array() ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); + + if ( empty( $result ) ) { + $result = array( 'success' => false ); + } + + // Validate + if ( ! $this->validate_request() ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + if ( ! empty( $request ) && is_object( $request ) && is_a( $request, 'WP_REST_Request' ) ) { + $params = $request->get_params(); + } else { + $params = array(); + } + + $errors = array(); + $pages = ! empty( $params['templates'] ) ? $params['templates'] : array(); + //$this->debug_log( $pages, __METHOD__ . ' - pages', __FILE__, __LINE__ ); + + if ( ! ( ! empty( $pages ) && function_exists( 'geodir_get_settings' ) ) ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + $result = array( 'success' => true ); + + return $result; + } + + // Remove pages + self::delete_demo_posts( 'page' ); + + $featured_images_assign = array(); + $old_and_new = array(); + + // GD page templates + if ( ! empty( $pages['gd'] ) ) { + $this->debug_log( count( $pages['gd'] ), __METHOD__ . ':templates:gd', __FILE__, __LINE__ ); + + foreach ( $pages['gd'] as $cpt => $page_templates ) { + if ( ! empty( $page_templates ) ) { + foreach ( $page_templates as $type => $page ) { + $post_id = $this->import_page_template( $page, $type, $cpt ); + + $old_id = isset($page['demo_post_id']) ? absint( $page['demo_post_id'] ) : ''; + + if ( $post_id && $old_id ) { + $old_and_new[ $old_id ] = $post_id; + } + } + } + } + } + + // UWP page templates + if ( ! empty( $pages['uwp'] ) ) { + $this->debug_log( count( $pages['uwp'] ), __METHOD__ . ':templates:uwp', __FILE__, __LINE__ ); + + foreach ( $pages['uwp'] as $cpt => $page_templates ) { + if ( ! empty( $page_templates ) ) { + foreach ( $page_templates as $type => $page ) { + $post_id = $this->import_page_template( $page, $type, $cpt ); + + $old_id = isset($page['demo_post_id']) ? absint( $page['demo_post_id'] ) : ''; + + if ( $post_id && $old_id ) { + $old_and_new[ $old_id ] = $post_id; + } + } + } + } + } + + // WP + if ( ! empty( $pages['wp'] ) ) { + $this->debug_log( count( $pages['wp'] ), __METHOD__ . ':templates:wp', __FILE__, __LINE__ ); + + foreach ( $pages['wp'] as $type => $page ) { + $post_id = $this->import_page_template( $page, $type ); + + $old_id = isset($page['demo_post_id']) ? absint( $page['demo_post_id'] ) : ''; + + if ( $post_id && $old_id ) { + $old_and_new[ $old_id ] = $post_id; + } + + // Featured image + $image_url = ! empty( $page['_featured_image_url'] ) ? esc_url_raw( $page['_featured_image_url'] ) : ''; + + if ( $image_url ) { + $featured_images_assign[$post_id] = $image_url; + } + } + + if ( ! empty( $featured_images_assign ) ) { + update_option( '_acdi_page_featured_images', $featured_images_assign ); + } + } + + // Elementor @todo add check for elementor pro + if ( ! empty( $pages['elementor'] ) && defined( 'ELEMENTOR_VERSION' ) ) { + $this->debug_log( count( $pages['elementor'] ), __METHOD__ . ':templates:elementor', __FILE__, __LINE__ ); + $default_kit_id = get_option( 'elementor_active_kit' ); + $new_kit_id = 0; + + delete_option( 'elementor_active_kit' ); + + foreach ( $pages['elementor'] as $cpt => $page_templates ) { + // Remove old demos + $this->delete_demo_posts( $cpt ); + + $archives = array(); + $items = array(); + + if ( ! empty( $page_templates ) ) { + foreach ( $page_templates as $page ) { + $post_id = $this->import_page_template( $page, 'elementor', $cpt ); + + if ( $post_id && $page['demo_post_id'] ) { + $old_id = absint( $page['demo_post_id'] ); + $old_and_new[ $old_id ] = $post_id; + + // Archives + if ( ! empty( $page['meta_input']['_elementor_template_type'] ) && $page['meta_input']['_elementor_template_type'] == 'geodirectory-archive' ) { + $archives[ $old_id ] = absint( $post_id ); + } + + // Items + if ( ! empty( $page['meta_input']['_elementor_template_type'] ) && $page['meta_input']['_elementor_template_type'] == 'geodirectory-archive-item' ) { + $items[ $old_id ] = absint( $post_id ); + } + + // Kit + if ( ! empty( $page['meta_input']['_elementor_template_type'] ) && $page['meta_input']['_elementor_template_type'] == 'kit' ) { + $new_kit_id = absint( $post_id ); + } + } + } + } + + if ( $new_kit_id ) { + update_option( 'elementor_active_kit', $new_kit_id); + } + + // Temp save replace ids + update_option( '_acdi_replacement_archive_item_ids', $items ); + update_option( '_acdi_original_elementor_active_kit', $default_kit_id ); + + // Extras + if ( ! empty( $old_and_new ) ) { + // Update the elementor display conditions + $display_conditions = get_option( 'elementor_pro_theme_builder_conditions' ); + $new_display_conditions = $display_conditions; + + if ( ! empty( $display_conditions ) ) { + foreach ( $display_conditions as $type => $condition ) { + if ( ! empty( $condition ) ) { + foreach ( $condition as $id => $rule ) { + if ( isset( $old_and_new[ $id ] ) ) { + unset( $new_display_conditions[ $type ][ $id ] ); + $new_id = absint( $old_and_new[ $id ] ); + $new_display_conditions[ $type ][ $new_id ] = $rule; + } + } + } + } + } + + update_option( 'elementor_pro_theme_builder_conditions', $new_display_conditions ); + + // Check pages for replaceable data + if ( ! empty( $old_and_new ) ) { + foreach ( $old_and_new as $id ) { + $this->parse_elementor_data( $id ); + } + } + } + } + + // Clear elementor cache after changes + \Elementor\Plugin::$instance->files_manager->clear_cache(); + } + + // Temp save replace ids + update_option( '_acdi_replacement_post_ids', $old_and_new ); + + $result = array( 'success' => true, 'errors' => $errors ); + + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + /** + * Import dummy posts. + * + * @param $result + * @param $request + * + * @return mixed + */ + public function remote_import_posts( $result = array(), $request = array() ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); + + if ( empty( $result ) ) { + $result = array( 'success' => false ); + } + + // Validate + if ( ! $this->validate_request() ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + if ( ! empty( $request ) && is_object( $request ) && is_a( $request, 'WP_REST_Request' ) ) { + $params = $request->get_params(); + } else { + $params = array(); + } + + $errors = array(); + $total = ! empty( $params['total'] ) ? absint( $params['total'] ) : 0; + //$this->debug_log( $total, __METHOD__ . ' - total', __FILE__, __LINE__ ); + $page = ! empty( $params['page'] ) ? absint( $params['page'] ) : 0; + $this->debug_log( $page, __METHOD__ . ' - page', __FILE__, __LINE__ ); + $offset = ! empty( $params['offset'] ) ? absint( $params['offset'] ) : 0; + //$this->debug_log( $offset, __METHOD__ . ' - offset', __FILE__, __LINE__ ); + $remove_dummy_data = ! empty( $params['remove_dummy_data'] ) ? true : false; + //$this->debug_log( $remove_dummy_data, __METHOD__ . ' - remove_dummy_data', __FILE__, __LINE__ ); + $posts = ! empty( $params['posts'] ) ? $params['posts'] : array(); + //$this->debug_log( $posts, __METHOD__ . ' - posts', __FILE__, __LINE__ ); + + // Maybe remove dummy data + if ( ! empty( $remove_dummy_data ) ) { + $post_types = geodir_get_posttypes( 'names' ); + + if ( ! empty( $post_types ) ) { + foreach ( $post_types as $post_type ) { + $table = geodir_db_cpt_table( $post_type ); + + if ( $table ) { + geodir_add_column_if_not_exist( $table, 'post_dummy', "TINYINT(1) NULL DEFAULT '0'" ); + } + + GeoDir_Admin_Dummy_Data::delete_dummy_posts( $post_type ); + } + } + + // Delete any previous posts + self::delete_demo_posts( 'post' ); + self::delete_demo_posts( 'attachment' ); + + // Maybe set page featured images + $featured_images = get_option('_acdi_page_featured_images'); + + if ( ! empty( $featured_images ) ) { + foreach( $featured_images as $p => $i ) { + $image = (array) GeoDir_Media::get_external_media( $i, '',array( 'image/jpg', 'image/jpeg', 'image/gif', 'image/png', 'image/webp' ), array( 'ext' => 'png', 'type' => 'image/png' ) ); + + if ( ! empty( $image['url'] ) ) { + $attachment_id = GeoDir_Media::set_uploaded_image_as_attachment( $image ); + + if ( is_wp_error( $attachment_id ) ) { + $this->debug_log( $attachment_id->get_error_message(), __METHOD__ . ' - set_uploaded_image_as_attachment - ' . $i, __FILE__, __LINE__ ); + } elseif ( $attachment_id ) { + set_post_thumbnail( $p, $attachment_id ); // This will not set if there are dummy posts. + update_post_meta( $attachment_id, '_ayecode_demo', 1 ); + } + } + } + + delete_option('_acdi_page_featured_images'); + } + } + + if ( ! empty( $posts ) && class_exists( 'GeoDir_Admin_Dummy_Data' ) ) { + $hello_world_trashed = false; + + foreach ( $posts as $post_info ) { + $this->debug_log( $post_info['post_title'], __METHOD__ . ':' . $post_info['post_type'] . ':wp_insert_post', __FILE__, __LINE__ ); + + unset( $post_info['ID'] ); + + $post_info['post_title'] = wp_strip_all_tags( $post_info['post_title'] ); // WP does not automatically do this + $post_info['post_status'] = 'publish'; + $post_info['post_dummy'] = '1'; + $post_info['post_author'] = 1; + // Set post data + $insert_result = wp_insert_post( $post_info, true ); // We hook into the save_post hook + + // Maybe insert attachments + if ( is_wp_error( $insert_result ) ) { + $this->debug_log( $insert_result->get_error_message(), __METHOD__ . ':wp_insert_post:' . $post_info['post_title'], __FILE__, __LINE__ ); + } elseif ( ! is_wp_error( $insert_result ) && ! empty( $insert_result ) && ! empty( $post_info['_raw_post_images'] ) ) { + $this->set_external_media( $insert_result, $post_info['_raw_post_images'] ); + } + + // Post stuff + if ( $post_info['post_type'] == 'post' && ! empty( $insert_result ) && ! is_wp_error( $insert_result ) ) { + // Maybe soft delete original hello world post + if ( ! $hello_world_trashed ) { + wp_delete_post( 1, false ); + + $hello_world_trashed = true; + } + + // Set cats + $terms = isset( $post_info['_cats'] ) ? $post_info['_cats'] : array(); + $post_terms = array(); + + if ( ! empty( $terms ) ) { + if ( ! function_exists( 'wp_create_category' ) ) { + require_once( ABSPATH . '/wp-admin/includes/taxonomy.php' ); + } + + foreach( $terms as $term_name ) { + $term = get_term_by( 'name', $term_name, 'category' ); + + if ( ! empty( $term->term_id ) ) { + $post_terms[] = absint( $term->term_id ); + } else { + $term_name = sanitize_title( $term_name ); + $term_id = wp_create_category( $term_name ); + + if ( is_wp_error( $term_id ) ) { + $this->debug_log( $term_id->get_error_message(), __METHOD__ . ' - wp_create_category - ' . $term_name, __FILE__, __LINE__ ); + } elseif ( $term_id ) { + $post_terms[] = absint( $term_id ); + } + } + } + + if ( ! empty( $post_terms ) ) { + wp_set_post_categories( $insert_result, $post_terms, false ); + } + } + + // Featured image + $image_url = ! empty( $post_info['_featured_image_url'] ) ? esc_url_raw( $post_info['_featured_image_url'] ) : ''; + + if ( $image_url ) { + $image = (array) GeoDir_Media::get_external_media( $image_url, '', array( 'image/jpg', 'image/jpeg', 'image/gif', 'image/png', 'image/webp' ), array( 'ext' => 'png', 'type' => 'image/png' ) ); + + if ( ! empty( $image['url'] ) ) { + $attachment_id = GeoDir_Media::set_uploaded_image_as_attachment( $image ); + + if ( is_wp_error( $attachment_id ) ) { + $this->debug_log( $attachment_id->get_error_message(), __METHOD__ . ' - set_uploaded_image_as_attachment - ' . $image['url'], __FILE__, __LINE__ ); + } elseif ( $attachment_id ){ + set_post_thumbnail( $insert_result, $attachment_id ); + + update_post_meta( $attachment_id, '_ayecode_demo', 1 ); + } + } + } + } + } + } + + $result = array( 'success' => true, 'errors' => $errors, 'total' => $total, 'page' => $page, 'offset' => $offset ); + + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + /** + * Import menus. + * + * @param $result + * @param $request + * + * @return mixed + */ + public function remote_import_menus( $result = array(), $request = array() ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); + + if ( empty( $result ) ) { + $result = array( 'success' => false ); + } + + // Validate + if ( ! $this->validate_request() ) { + return $result; + } + + if ( ! empty( $request ) && is_object( $request ) && is_a( $request, 'WP_REST_Request' ) ) { + $params = $request->get_params(); + } else { + $params = array(); + } + + $menus = ! empty( $params['menus'] ) ? $params['menus'] : array(); + //$this->debug_log( $menus, __METHOD__ . ' - menus', __FILE__, __LINE__ ); + $errors = array(); + + if ( ! empty( $menus ) ) { + foreach ( $menus as $location => $menu ) { + $import = $this->import_menu( $location, $menu ); + } + } + + $result = array( 'success' => true, 'errors' => $errors ); + + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $result; + } + + /** + * Try to set higher limits on the fly + */ + public static function set_php_limits() { +// if ( ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) { +// error_reporting( 0 ); +// } +// @ini_set( 'display_errors', 0 ); + + // try to set higher limits for import + $max_input_time = ini_get( 'max_input_time' ); + $max_execution_time = ini_get( 'max_execution_time' ); + $memory_limit = ini_get( 'memory_limit' ); + + if ( $max_input_time !== 0 && $max_input_time != -1 && ( ! $max_input_time || $max_input_time < 3000 ) ) { + ini_set( 'max_input_time', 3000 ); + } + + if ( $max_execution_time !== 0 && ( ! $max_execution_time || $max_execution_time < 3000 ) ) { + ini_set( 'max_execution_time', 3000 ); + } + + if ( $memory_limit && str_replace( 'M', '', $memory_limit ) ) { + if ( str_replace( 'M', '', $memory_limit ) < 256 ) { + ini_set( 'memory_limit', '256M' ); + } + } + + /* + * The `auto_detect_line_endings` setting has been deprecated in PHP 8.1, * but will continue to work until PHP 9.0. * For now, we're silencing the deprecation notice as there may still be * translation files around which haven't been updated in a long time and @@ -1884,7 +2582,43 @@ public function str_replace_args( $values = false ) { return $values ? array_values( $args ) : array_keys( $args ); } + public function debug_log( $log, $title = '', $file = '', $line = '', $exit = false ) { + $should_log = $this->debug; - } + if ( defined( 'AYECODE_CONNECT_DEBUG' ) ) { + $should_log = AYECODE_CONNECT_DEBUG; + } + + $should_log = apply_filters( 'ayecode_connect_debug_log', $should_log ); + + if ( $should_log ) { + $label = ''; + if ( $file && $file !== '' ) { + $label .= basename( $file ) . ( $line ? '(' . $line . ')' : '' ); + } + + if ( $title && $title !== '' ) { + $label = $label !== '' ? $label . ' ' : ''; + $label .= $title . ' '; + } + + $label = $label !== '' ? trim( $label ) . ' : ' : ''; + $append = ''; + if ( is_scalar( $log ) && ( $log === 'start' || $log === 'end' ) ) { + $append = " " . memory_get_usage(); + } + + if ( is_array( $log ) || is_object( $log ) ) { + error_log( $label . print_r( $log, true ) ); + } else { + error_log( $label . $log . $append ); + } + + if ( $exit ) { + exit; + } + } + } + } } \ No newline at end of file diff --git a/includes/class-ayecode-connect.php b/includes/class-ayecode-connect.php index 42a37e7..af48152 100755 --- a/includes/class-ayecode-connect.php +++ b/includes/class-ayecode-connect.php @@ -73,19 +73,24 @@ class AyeCode_Connect { */ public $version = ''; + /** + * If debugging is enabled. + * + * @var + */ + public $debug = false; + /** * Class constructor * */ public function __construct( array $args = array() ) { - foreach ( $args as $key => $value ) { $this->{$key} = $value; } $this->api_url = trailingslashit( $this->api_url ); $this->api_namespace = ltrim( $this->api_namespace, '/' ); - } /** @@ -93,11 +98,8 @@ public function __construct( array $args = array() ) { * */ public function init() { - - - if ( $this->is_active() ) { - - //Connected + if ( $this->is_active() ) { + // Connected do_action( $this->prefix . '_connected_to_remote' ); add_action( 'rest_api_init', array( $this, 'register_connected_routes' ) ); add_action( 'edd_api_button_args', array( $this, 'edd_api_button_args' ), 8 ); @@ -105,8 +107,9 @@ public function init() { add_filter( 'upgrader_post_install',array( $this, 'maybe_sync_licenses'),10,3); // Support Widget - if(is_admin()){ + if ( is_admin() ) { require_once plugin_dir_path( __FILE__ ) . 'class-ayecode-connect-support.php'; + $support_args = array( 'prefix'=>$this->prefix, 'name' => $this->get_connected_name(), @@ -114,122 +117,106 @@ public function init() { 'enabled' => get_option( $this->prefix . '_support', true ), 'support_user' => get_option( $this->prefix . '_support_user', true ), ); - new AyeCode_Connect_Support($support_args); + + new AyeCode_Connect_Support( $support_args ); } - // maybe show connected notice + // Maybe show connected notice if ( is_admin() && isset( $_REQUEST['ayecode-connected'] ) ) { add_action( 'admin_notices', array( $this, 'connected_notice' ) ); } - - } else { - - //Not Connected + // Not Connected add_action( 'rest_api_init', array( $this, 'register_connection_routes' ) ); add_action( 'init', array( $this, 'maybe_redirect_to_connection_page' ) ); add_action( 'admin_notices', array( $this, 'website_url_change_error') ); do_action( $this->prefix . '_not_connected_to_remote' ); - } - // register test route + // Register test route add_action( 'rest_api_init', array( $this, 'register_test_routes' ) ); - // register blocks - add_action( 'widgets_init', array( $this, 'register_blocks' ) ); - add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) ); - + // Register blocks + add_action( 'widgets_init', array( $this, 'register_blocks' ) ); + add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_assets' ) ); - if ( is_admin() ){ - // add AUI on our backend pages + if ( is_admin() ) { + // Add AUI on our backend pages add_filter( 'aui_screen_ids', array( $this, 'add_aui_screens') ); - // check for demo site redirect + // Check for demo site redirect add_action( 'current_screen', array( $this, 'demo_site_redirect' ) ); } + } + /** + * Enqueue editor JS required for blocks. + * + * @return void + */ + public function enqueue_editor_assets() { + if ( $this->maybe_load_blocks() ) { + global $pagenow,$wp_version; + + $AyeCode_Connect_Settings = AyeCode_Connect_Settings::instance(); + $deps = ( $pagenow == 'widgets.php' || ( $pagenow == 'site-editor.php' && ( function_exists( 'wp_is_block_theme' ) && wp_is_block_theme() ) ) ) && version_compare( $wp_version, '5.8', '>=' ) ? array( 'wp-blocks', 'wp-element') : array( 'wp-blocks', 'wp-element', 'wp-editor' ); + wp_enqueue_script( + 'ayecode-editor', + $AyeCode_Connect_Settings->base_url . 'assets/js/blocks.js', + $deps, + AYECODE_CONNECT_VERSION + ); + } } - /** - * Enqueue editor JS required for blocks. - * - * @return void - */ - public function enqueue_editor_assets() - { - if ($this->maybe_load_blocks()) { - global $pagenow,$wp_version; - $AyeCode_Connect_Settings = AyeCode_Connect_Settings::instance(); - $deps = ( $pagenow == 'widgets.php' || ( $pagenow == 'site-editor.php' && ( function_exists( 'wp_is_block_theme' ) && wp_is_block_theme() ) ) ) && version_compare( $wp_version, '5.8', '>=' ) ? array( 'wp-blocks', 'wp-element') : array( 'wp-blocks', 'wp-element', 'wp-editor' ); - wp_enqueue_script( - 'ayecode-editor', - $AyeCode_Connect_Settings->base_url . 'assets/js/blocks.js', - $deps, - AYECODE_CONNECT_VERSION - ); - } - } - - /** - * Check if we should load our blocks, check if one of our plugin are active. - * - * @return mixed|null - */ - public function maybe_load_blocks() - { - $load = false; - - if( - defined('GEODIRLOCATION_VERSION') - || defined('USERSWP_VERSION') -// || defined('WPINV_VERSION') // not currently used - ){ - $load = true; - } - - return apply_filters( $this->prefix . '_load_blocks', $load ); - - } - - /** - * Register blocks if one of our plugins active. - * - * @return void - */ - public function register_blocks() - { - - if ($this->maybe_load_blocks()) { - require_once plugin_dir_path(__FILE__) . '../blocks/class-ayecode-wp-nav.php'; - register_widget( 'AyeCode_WP_Nav' ); - } - - } - - /** - * @return void - */ - public function demo_site_redirect(){ + /** + * Check if we should load our blocks, check if one of our plugin are active. + * + * @return mixed|null + */ + public function maybe_load_blocks() { + $load = false; + + if ( + defined( 'GEODIRLOCATION_VERSION' ) + || defined( 'USERSWP_VERSION' ) + //|| defined( 'WPINV_VERSION' ) // not currently used + ) { + $load = true; + } + + return apply_filters( $this->prefix . '_load_blocks', $load ); + } + /** + * Register blocks if one of our plugins active. + * + * @return void + */ + public function register_blocks() { + if ( $this->maybe_load_blocks() ) { + require_once plugin_dir_path( __FILE__ ) . '../blocks/class-ayecode-wp-nav.php'; + register_widget( 'AyeCode_WP_Nav' ); + } + } + + public function demo_site_redirect(){ $currentScreen = get_current_screen(); - if( $currentScreen->id === "plugin-install" && !empty($_REQUEST['ac-demo-import']) ) { - // if installed and active then open the correct demo importer + if ( $currentScreen->id === "plugin-install" && ! empty( $_REQUEST['ac-demo-import'] ) ) { + // If installed and active then open the correct demo importer if ( $this->is_active() ) { $demo = sanitize_title_with_dashes($_REQUEST['ac-demo-import']); - wp_redirect(admin_url( "admin.php?page=ayecode-demo-content&ac-demo-import=".$demo )); + wp_redirect(admin_url( "admin.php?page=ayecode-demo-content&ac-demo-import=" . $demo )); } } - } - /** - * @param $screen_ids - * @return mixed - */ - public function add_aui_screens($screen_ids){ - + /** + * @param $screen_ids + * @return mixed + */ + public function add_aui_screens( $screen_ids ) { // AC screens that need AUI $screen_ids[] = 'toplevel_page_ayecode-connect'; $screen_ids[] = 'ayecode_page_ayecode-demo-content'; @@ -253,8 +240,6 @@ public function maybe_sync_licenses($result,$extra_hooks,$upgrader) { return $result; } - - /** * A notice to show that the site is now connected. */ @@ -274,13 +259,12 @@ public function connected_notice() { * @return mixed */ public function edd_api_button_args( $button_args ) { - if ( defined( 'WP_EASY_UPDATES_ACTIVE' ) ) { - if ( ! empty( $button_args['licensing'] ) && ! empty( $button_args['update_url'] ) && ! empty( $button_args['id'] ) && empty( $button_args['license'] ) ) { $update_url = esc_url_raw( $button_args['update_url'] ); $item_id = absint( $button_args['id'] ); $domain = ''; + if ( trailingslashit( $update_url ) == "https://wpgeodirectory.com/" || trailingslashit( $update_url ) == "http://wpgeodirectory.com/" ) { $domain = 'wpgeodirectory.com'; } elseif ( trailingslashit( $update_url ) == "https://userswp.io/" || trailingslashit( $update_url ) == "http://userswp.io/" ) { @@ -298,7 +282,6 @@ public function edd_api_button_args( $button_args ) { } } } - } } @@ -323,12 +306,10 @@ public function is_active() { * @return bool */ public function is_registered() { - $blog_id = (bool) $this->get_blog_id(); $has_token = $this->is_active(); return $blog_id && $has_token; - } /** @@ -339,7 +320,6 @@ public function is_registered() { * @return String API URL. */ public function get_api_url( $relative_url ) { - $api_url = $this->api_url; $api_base = trailingslashit( $api_url . $this->api_namespace ); @@ -348,6 +328,22 @@ public function get_api_url( $relative_url ) { return $api_base . $relative_url; } + /** + * Returns the requested local API URL. + * + * @param String $relative_url the relative API path. + * + * @return String API URL. + */ + public function get_local_api_url( $relative_url ) { + $api_url = $this->api_url; + + $api_base = trailingslashit( $api_url . $this->local_api_namespace ); + $relative_url = ltrim( $relative_url, '/' ); + + return $api_base . $relative_url; + } + /** * Builds the timeout limit for queries talking with the remote servers. * @@ -357,7 +353,6 @@ public function get_api_url( $relative_url ) { * @return int **/ public function get_max_execution_time() { - $timeout = (int) ini_get( 'max_execution_time' ); // Ensure exec time set in php.ini. @@ -366,7 +361,6 @@ public function get_max_execution_time() { } return $timeout; - } /** @@ -379,15 +373,15 @@ public function get_max_execution_time() { * @return int The timeout value. **/ public function set_min_time_limit( $min_timeout ) { - $timeout = $this->get_max_execution_time(); + if ( $timeout < $min_timeout ) { $timeout = $min_timeout; + set_time_limit( $timeout ); } return $timeout; - } /** @@ -436,7 +430,6 @@ public function get_assumed_site_creation_date() { * Deletes secret tokens in case they, for example, have expired. */ public function delete_secrets() { - delete_option( $this->prefix . '_blog_id' ); delete_option( $this->prefix . '_blog_token' ); delete_option( $this->prefix . '_connected_username' ); @@ -453,7 +446,6 @@ public function delete_secrets() { delete_transient( $this->prefix . '_activation_secret' ); delete_transient( $this->prefix . '_support_user_key' ); delete_transient( $this->prefix . '_site_moved' ); - } /** @@ -474,7 +466,6 @@ public function handle_registration( array $registration_data ) { return new WP_Error( 'invalid_secret', __( 'Invalid Secret', 'ayecode-connect' ), 401 ); } - update_option( $this->prefix . '_connected_username', $username ); update_option( $this->prefix . '_connected_email', $user_email ); update_option( $this->prefix . '_connected_name', $user_display_name); @@ -492,12 +483,10 @@ public function handle_registration( array $registration_data ) { delete_option( $this->prefix . '_activation_secret' ); } - - // make the licence sync run on next load -// wp_schedule_single_event( time(), $this->prefix . "_callback" ); + // Make the licence sync run on next load + //wp_schedule_single_event( time(), $this->prefix . "_callback" ); return rest_ensure_response( true ); - } /** @@ -506,16 +495,15 @@ public function handle_registration( array $registration_data ) { * @return mixed|string */ public function get_activation_secret() { - //Prepare transient name $transient = $this->prefix . '_activation_secret'; // Persistent cache hates transients, either not changing or always changing. if ( wp_using_ext_object_cache() ) { - // Fetch its value + // Fetch its value $secret = get_option( $transient ); }else{ - // Fetch its value + // Fetch its value $secret = get_transient( $transient ); } @@ -535,26 +523,24 @@ public function get_activation_secret() { set_transient( $transient, $secret, 3 * HOUR_IN_SECONDS ); } - //Return the new activation secret return $secret; - } /** - * Our own non-cached version. - * + * Our own non-cached version. + * * @param $transient * * @return false|mixed|void */ - public function get_transient( $transient ){ - global $wpdb; + public function get_transient( $transient ){ + global $wpdb; - $transient_option = '_transient_' . $transient; + $transient_option = '_transient_' . $transient; - return $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->prefix}options WHERE option_name = %s", $transient_option ) ); - } + return $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->prefix}options WHERE option_name = %s", $transient_option ) ); + } /** * Builds a URL to the remote connection auth page. @@ -566,7 +552,6 @@ public function get_transient( $transient ){ * @return string Connect URL */ public function build_connect_url( $redirect = true ) { - $user = wp_get_current_user(); $admin_page = esc_url_raw( admin_url( "admin.php?page=ayecode-connect" ) ); @@ -575,11 +560,12 @@ public function build_connect_url( $redirect = true ) { ? wp_validate_redirect( esc_url_raw( $redirect ), $admin_page ) : $admin_page; - //Build the connection URL + // Build the connection URL $args = urlencode_deep( array( 'redirect_uri' => urlencode( $redirect ), 'remote_user_id' => $user->ID, + 'remote_user_id' => $user->ID, 'user_email' => $user->user_email, 'user_login' => $user->user_login, 'activation_secret' => $this->get_activation_secret(), @@ -596,15 +582,13 @@ public function build_connect_url( $redirect = true ) { ); return add_query_arg( $args, $this->connection_url ); - } /** * Disconnects from the remote servers. * Forgets all connection details and tells the remote servers to do the same. */ - public function disconnect_site($disconnect_remote = true) { - + public function disconnect_site( $disconnect_remote = true ) { $site_id = $this->get_blog_id(); //Abort early if it is not connected @@ -623,8 +607,6 @@ public function disconnect_site($disconnect_remote = true) { $response = true; } - - //Then delete local secrets $this->delete_secrets(); @@ -655,7 +637,6 @@ public function disconnect_site($disconnect_remote = true) { } return $response; - } /** @@ -664,15 +645,14 @@ public function disconnect_site($disconnect_remote = true) { * @return array|mixed|void|WP_Error */ public function request_licences( $site = '' ) { - $site_id = $this->get_blog_id(); - //Abort early if it is not connected + // Abort early if it is not connected if ( ! $site_id ) { return; } - //Disconnect from remote... + // Disconnect from remote... $args = array( 'url' => $this->get_api_url( '/licenses' ), 'method' => 'GET' @@ -680,7 +660,7 @@ public function request_licences( $site = '' ) { $response = self::remote_request( $args ); - //in case the request failed... + // In case the request failed... if ( is_wp_error( $response ) ) { return $response; } @@ -696,8 +676,9 @@ public function request_licences( $site = '' ) { * @return array|bool|mixed|WP_Error */ public function sync_licences() { - error_log('sync_licenses'); - // only run if WPEU is active + error_log( 'sync_licenses' ); + + // Only run if WPEU is active if ( ! defined( 'WP_EASY_UPDATES_ACTIVE' ) ) { return false; } @@ -716,27 +697,29 @@ public function sync_licences() { ); require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); + $plugins = get_plugins(); - // remove any non AyeCode plugins. + // Remove any non AyeCode plugins. foreach ( $plugins as $slug => $plugin ) { if ( empty( $plugin['Update URL'] ) ) { - // check if a main plugin + // Check if a main plugin if ( isset( $plugin['TextDomain'] ) && in_array( $plugin['TextDomain'], array( "geodirectory", "userswp", "invoicing" ) ) ) { - // don't remove + // Don't remove } else { unset( $plugins[ $slug ] ); // remove } } } - // maybe add current licence keys + // Maybe add current licence keys $keys = get_option( 'exup_keys', array() ); + if ( ! empty( $keys ) ) { foreach ( $keys as $plugin_slug => $key_info ) { if ( isset( $plugins[ $plugin_slug ] ) && isset( $key_info->key ) ) { @@ -752,17 +735,14 @@ public function sync_licences() { $response = self::remote_request( $args, $body ); - - //in case the request failed... + // In case the request failed... if ( is_wp_error( $response ) ) { return $response; } $body = json_decode( wp_remote_retrieve_body( $response ) ); - return $body; - } /** @@ -816,7 +796,7 @@ public function is_usable_domain( $domain ) { } /** - * Skips the usuable domain check when connecting a site. + * Skips the usable domain check when connecting a site. * * Allows site administrators with domains that fail gethostname-based checks to pass the request to remote * @@ -875,11 +855,9 @@ public function is_usable_domain( $domain ) { * @return string|false */ public function get_access_token() { - $option_name = $this->prefix . '_blog_token'; return get_option( $option_name, false ); - } /** @@ -888,7 +866,6 @@ public function get_access_token() { * @return mixed|void */ public function get_connected_username() { - $option_name = $this->prefix . '_connected_username'; return get_option( $option_name, false ); @@ -900,7 +877,6 @@ public function get_connected_username() { * @return mixed|void */ public function get_connected_name() { - $option_name = $this->prefix . '_connected_name'; $value = get_option( $option_name, false ); @@ -926,7 +902,6 @@ public function get_connected_name() { * @return mixed|void */ public function get_connected_email() { - $option_name = $this->prefix . '_connected_email'; $value = get_option( $option_name, false ); @@ -952,18 +927,20 @@ public function get_connected_email() { * @return mixed|void */ public function get_connected_user_id() { - $option_name = $this->prefix . '_connected_user_id'; $value = get_option( $option_name, false ); // if no value maybe try and get it. - if($value === false){ + if ( $value === false ) { $username = $this->get_connected_username(); - if($username){ + + if ( $username ) { $user = $this->get_remote_user_info(); - if(!empty($user->ID)){ - $value = sanitize_text_field($user->ID); + + if ( ! empty( $user->ID ) ) { + $value = sanitize_text_field( $user->ID ); + update_option( $option_name, $value ); } } @@ -978,7 +955,6 @@ public function get_connected_user_id() { * @return mixed|void */ public function get_connected_user_signatures($type = '') { - $option_name = $this->prefix . '_connected_user_signatures'; $value = get_option( $option_name, false ); @@ -992,7 +968,6 @@ public function get_connected_user_signatures($type = '') { * @return mixed|void */ public function get_connected_user_sites() { - $option_name = $this->prefix . '_connected_user_sites'; $value = get_option( $option_name, false ); @@ -1003,7 +978,6 @@ public function get_connected_user_sites() { $site_id = $this->get_blog_id(); //unset($value[$site_id]); } - return $value; } @@ -1059,7 +1033,7 @@ public function get_remote_user_info(){ * * @return array|mixed|void|WP_Error */ - public function set_remote_support_user($enable = false){ + public function set_remote_support_user( $enable = false ) { $site_id = $this->get_blog_id(); //Abort early if it is not connected @@ -1067,7 +1041,6 @@ public function set_remote_support_user($enable = false){ return; } - // enable support user if($enable){ // Generate a temp key @@ -1098,15 +1071,12 @@ public function set_remote_support_user($enable = false){ $body = json_decode( wp_remote_retrieve_body( $response ) ); - // Set a transient set_transient( $this->prefix . "_support_user_key", $hash, $valid_seconds ); update_option( $this->prefix . "_support_user", $expires ); - } - // disable support user - else{ - - // remove info early incase remote request fails + } else { + // Disable support user + // Remove info early incase remote request fails delete_transient( $this->prefix . "_support_user_key" ); update_option( $this->prefix . "_support_user", false ); @@ -1143,18 +1113,14 @@ public function set_remote_support_user($enable = false){ $response = self::remote_request( $args, $body ); - // in case the request failed... + // In case the request failed... if ( is_wp_error( $response ) ) { return $response; } $body = json_decode( wp_remote_retrieve_body( $response ) ); - } -// print_r($body);exit; - - return $body; } @@ -1164,11 +1130,9 @@ public function set_remote_support_user($enable = false){ * @return string|false */ public function get_blog_id() { - $option_name = $this->prefix . '_blog_id'; return get_option( $option_name, false ); - } /** @@ -1177,27 +1141,26 @@ public function get_blog_id() { * @return void */ public function maybe_redirect_to_connection_page() { - - //Only admins have the capability to connect + // Only admins have the capability to connect if ( ! current_user_can( 'manage_options' ) ) { return; } - //Ensure that this is an admin page + // Ensure that this is an admin page if ( ! is_admin() ) { return; } - //And that the user wants to be redirected + // And that the user wants to be redirected $action = $this->prefix . '_redirect_to_activation_url'; if ( empty( $_GET['action'] ) || $action != $_GET['action'] ) { return; } - //Prepare the connect URL + // Prepare the connect URL $url = $this->build_connect_url(); - //Then redirect the user to the URL + // Then redirect the user to the URL wp_redirect( esc_url( $url ) ); exit; } @@ -1210,49 +1173,47 @@ public function maybe_redirect_to_connection_page() { * @since 1.0.0 */ public function is_api_request_authenticated( $request ) { - $headers = $request->get_header_as_array( 'Authorization' ); + if ( empty( $headers ) ) { return new WP_Error( 'rest_forbidden', esc_html__( 'Missing Authorization Header.', 'ayecode-connect' ), array( 'status' => 401 ) ); } $jwt = ''; foreach ( $headers as $header ) { - $header = trim( $header ); + if ( strpos( $header, 'X_AUTH' ) === 0 ) { $jwt = trim( substr( $header, 7 ) ); break; } - } - //Ensure the jwt auth is set... + // Ensure the jwt auth is set... if ( empty( $jwt ) ) { return new WP_Error( 'rest_forbidden', esc_html__( 'Missing Authorization Header.', 'ayecode-connect' ), array( 'status' => 401 ) ); } - //And is valid + // And is valid $tokens = explode( '.', $jwt ); if ( count( $tokens ) != 3 ) { return new WP_Error( 'rest_forbidden', esc_html__( 'Invalid Authorization Header.', 'ayecode-connect' ), array( 'status' => 401 ) ); } - //The key used to authenticate the request + // The key used to authenticate the request $key = $this->get_access_token(); if ( empty( $key ) ) { return new WP_Error( 'missing_token', esc_html__( 'Missing blog token.', 'ayecode-connect' ), array( 'status' => 401 ) ); } - //Use it to decode the jwt token + // Use it to decode the jwt token if ( false === self::decode( $jwt, $key ) ) { return new WP_Error( 'rest_forbidden', esc_html__( 'You are not authorized to do that.', 'ayecode-connect' ), array( 'status' => 401 ) ); } - //This request is authentic + // This request is authentic return true; - } /** @@ -1264,7 +1225,6 @@ public function is_api_request_authenticated( $request ) { * @return false|object The JWT's payload as a PHP object */ public static function decode( $jwt, $key ) { - $tokens = explode( '.', $jwt ); if ( count( $tokens ) != 3 ) { return false; @@ -1272,22 +1232,22 @@ public static function decode( $jwt, $key ) { list( $header_64, $body_64, $hash_64 ) = $tokens; - //Header contains the algorithym used to encode the jwt + // Header contains the algorithym used to encode the jwt if ( null === ( $header = json_decode( self::url_safe_base64_decode( $header_64 ) ) ) ) { return false; } - //Payload contains the blog id etc + // Payload contains the blog id etc if ( null === $payload = json_decode( self::url_safe_base64_decode( $body_64 ) ) ) { return false; } - //Signature is a hs256 encoding of the header and the payload + // Signature is a hs256 encoding of the header and the payload if ( false === ( $signature = self::url_safe_base64_decode( $hash_64 ) ) ) { return false; } - //Only HS256 is supported + // Only HS256 is supported if ( empty( $header->alg ) || 'HS256' != $header->alg ) { return false; } @@ -1299,7 +1259,6 @@ public static function decode( $jwt, $key ) { } return $payload; - } /** @@ -1313,7 +1272,6 @@ public static function decode( $jwt, $key ) { * */ public static function encode( $payload, $key ) { - $header = array( 'typ' => 'JWT', 'alg' => 'HS256' ); $segments = array(); @@ -1324,7 +1282,6 @@ public static function encode( $payload, $key ) { $segments[] = self::url_safe_base64_encode( $signature ); return implode( '.', $segments ); - } /** @@ -1335,8 +1292,8 @@ public static function encode( $payload, $key ) { * @return string A decoded string */ public static function url_safe_base64_decode( $input ) { - $remainder = strlen( $input ) % 4; + if ( $remainder ) { $padlen = 4 - $remainder; $input .= str_repeat( '=', $padlen ); @@ -1366,6 +1323,7 @@ public static function url_safe_base64_encode( $input ) { * @return array|WP_Error WP HTTP response on success */ public function remote_request( $args, $body = null ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); $defaults = array( 'url' => '', @@ -1386,7 +1344,11 @@ public function remote_request( $args, $body = null ) { $token = $this->get_access_token(); if ( ! $token ) { - return new WP_Error( 'missing_token' ); + $error = new WP_Error( 'missing_token', __( 'Missing token', 'ayecode-connect' ) ); + + $this->debug_log( $error->get_error_message(), __METHOD__ . ':get_access_token error', __FILE__, __LINE__ ); + + return $error; } $method = strtoupper( $args['method'] ); @@ -1400,9 +1362,10 @@ public function remote_request( $args, $body = null ) { $request = compact( 'method', 'body', 'timeout', 'redirection', 'stream', 'filename', 'sslverify' ); - $url = esc_url( $args['url'] ); + $this->debug_log( $url, __METHOD__ . ':url', __FILE__, __LINE__ ); + $signature = self::encode( array( 'blog_id' => $args['blog_id'] ), $token ); $request['headers'] = array_merge( @@ -1413,8 +1376,9 @@ public function remote_request( $args, $body = null ) { ) ); - return wp_remote_request( $url, $request ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return wp_remote_request( $url, $request ); } /** @@ -1422,7 +1386,6 @@ public function remote_request( $args, $body = null ) { * */ public function register_connected_routes() { - // Initiates a given action register_rest_route( $this->local_api_namespace, @@ -1433,7 +1396,6 @@ public function register_connected_routes() { 'permission_callback' => array( $this, 'has_permission' ), ) ); - } /** @@ -1442,28 +1404,27 @@ public function register_connected_routes() { * @since 1.0.0 */ public function has_permission( $request ) { - - //Retrieve the jwt for the request + // Retrieve the jwt for the request $jwt = $this->get_jwt( $request ); - //Ensure the jwt auth is set... + // Ensure the jwt auth is set... if ( empty( $jwt ) ) { return new WP_Error( 'rest_forbidden', esc_html__( 'Missing Authorization Header.', 'ayecode-connect' ), array( 'status' => 401 ) ); } - //And is valid + // And is valid $tokens = explode( '.', $jwt ); if ( count( $tokens ) != 3 ) { return new WP_Error( 'rest_forbidden', esc_html__( 'Invalid Authorization Header.', 'ayecode-connect' ), array( 'status' => 401 ) ); } - //Ensure the body is not empty + // Ensure the body is not empty $body = json_decode( self::url_safe_base64_decode( $tokens[1] ) ); if ( empty( $body ) ) { return new WP_Error( 'rest_forbidden', esc_html__( 'Invalid Authorization Header.', 'ayecode-connect' ), array( 'status' => 401 ) ); } - //Retrieve the secret key associated with the blog id + // Retrieve the secret key associated with the blog id $key = $this->get_access_token(); //... then use it to decrypt the jwt @@ -1472,7 +1433,6 @@ public function has_permission( $request ) { } return true; - } /** @@ -1481,8 +1441,7 @@ public function has_permission( $request ) { * @since 1.0.0 */ public function get_jwt( $request ) { - - //Prepare authorization headers + // Prepare authorization headers $auth_headers = $request->get_header_as_array( 'Authorization' ); // If empty this might be because of the server removes the auth header https://github.com/WP-API/WP-API/issues/2512 @@ -1490,10 +1449,10 @@ public function get_jwt( $request ) { $auth_headers = $request->get_header_as_array( 'X-AYE-Authorization' ); } - //The provided json web token + // The provided json web token $jwt = ''; - //Loop through them and retrieve our auth header + // Loop through them and retrieve our auth header if ( ! empty( $auth_headers ) ) { foreach ( $auth_headers as $header ) { @@ -1502,7 +1461,6 @@ public function get_jwt( $request ) { $jwt = trim( substr( $header, 7 ) ); break; } - } } @@ -1514,26 +1472,30 @@ public function get_jwt( $request ) { * */ public function do_action( $request ) { -// wp_mail("stiofansisland@gmail.com","update settings debug request",print_r($request ,true)); + //$this->debug_log( $request, __METHOD__ . ':request', __FILE__, __LINE__ ); + //wp_mail("stiofansisland@gmail.com","update settings debug request", print_r( $request, true ) ); $prefix = $this->prefix; $action = sanitize_title_with_dashes( $request->get_param( 'action' ) ); + $this->debug_log( $action, __METHOD__ . ':action', __FILE__, __LINE__ ); if ( empty( $action ) ) { return new WP_Error( 'missing_action', __( 'Specify an action', 'ayecode-connect' ) ); } - /** - * Run the remote actions class. - * - * This is only loaded if authenticated. - */ - require_once plugin_dir_path( __FILE__ ) . 'class-ayecode-connect-remote-actions.php'; - AyeCode_Connect_Remote_Actions::instance( $prefix, $this ); + if ( ! class_exists( 'AyeCode_Connect_Remote_Actions' ) ) { + /** + * Run the remote actions class. + * + * This is only loaded if authenticated. + */ + require_once plugin_dir_path( __FILE__ ) . 'class-ayecode-connect-remote-actions.php'; - $response = apply_filters( "{$prefix}_remote_action_{$action}", array( "success" => false ) ); + AyeCode_Connect_Remote_Actions::instance( $prefix, $this ); + } - return rest_ensure_response( $response ); + $response = apply_filters( "{$prefix}_remote_action_{$action}", array( "success" => false ), $request ); + return rest_ensure_response( $response ); } /** @@ -1541,7 +1503,6 @@ public function do_action( $request ) { * */ public function register_connection_routes() { - // Verifies registration register_rest_route( $this->local_api_namespace, @@ -1563,14 +1524,12 @@ public function register_connection_routes() { 'permission_callback' => '__return_true' ) ); - } /** * Register routes used for testing. */ public function register_test_routes() { - // Returns a url to the connection page. register_rest_route( $this->local_api_namespace, @@ -1581,10 +1540,8 @@ public function register_test_routes() { 'permission_callback' => '__return_true' ) ); - } - /** * Allow our server to reply to a test connection request. * @@ -1593,8 +1550,7 @@ public function register_test_routes() { * @return array */ public function test_connection( $request ) { - - // validate + // Validate if ( ! $this->validate_request() ) { return array( "success" => false ); } @@ -1602,13 +1558,14 @@ public function test_connection( $request ) { $hash = esc_attr( $request['hash'] ); $stored_hash = esc_attr( get_transient('ac_test_connection') ); $success = false; - if(!$stored_hash || !$hash){ + + if ( ! $stored_hash || ! $hash ) { $success = false; $code = "no_hash"; - }elseif($hash && $stored_hash && $stored_hash!=$hash){ + } elseif ( $hash && $stored_hash && $stored_hash != $hash ) { $success = false; $code = "hash_not_equal"; - }elseif($hash && $stored_hash && $stored_hash == $hash){ + } elseif ( $hash && $stored_hash && $stored_hash == $hash ) { $success = true; $code = "success"; } @@ -1618,7 +1575,6 @@ public function test_connection( $request ) { "code" => $code ); - return $result; } @@ -1645,7 +1601,6 @@ private function validate_request() { * @return string */ private function get_server_ip() { - if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; @@ -1692,8 +1647,7 @@ public function verify_registration_permission_callback(){ * @return string|WP_Error */ public function verify_registration( WP_REST_Request $request ) { - - // delete the URL change transient if set + // Delete the URL change transient if set delete_transient( $this->prefix . '_site_moved'); //Prepare the registration data @@ -1707,9 +1661,8 @@ public function verify_registration( WP_REST_Request $request ) { $request['user_display_name'], ); - //Then (maybe) save it + // Then (maybe) save it return $this->handle_registration( $registration_data ); - } /** @@ -1722,45 +1675,41 @@ public function verify_registration( WP_REST_Request $request ) { * @return string|WP_Error */ public function connection_page( WP_REST_Request $request ) { - $action = $this->prefix . '_redirect_to_activation_url'; $url = add_query_arg( 'action', $action, get_admin_url() ); return rest_ensure_response( $url ); - } - /** * Check if the website URL changes and disconnect the site and show re-connect notice if so. */ - public function check_for_url_change($connected_site_url = ''){ - - // if WPML is installed then bail as this can dynamically change the URL - if(defined('ICL_LANGUAGE_CODE')){ + public function check_for_url_change( $connected_site_url = '' ) { + // If WPML is installed then bail as this can dynamically change the URL + if ( defined( 'ICL_LANGUAGE_CODE' ) ) { return false; } $result = false; - // get current site URL - $connected_site_url = $connected_site_url ? trailingslashit( str_replace( array("http://","https://"),"", $connected_site_url ) ): get_option( $this->prefix . "_url" ); + // Get current site URL + $connected_site_url = $connected_site_url ? trailingslashit( str_replace( array( "http://", "https://" ), "", $connected_site_url ) ): get_option( $this->prefix . "_url" ); - // get the current site URL - $site_url = trailingslashit( str_replace( array("http://","https://"),"", site_url() ) ); + // Get the current site URL + $site_url = trailingslashit( str_replace( array( "http://","https://" ),"", site_url() ) ); - // if current site URL is empty then add it - if(empty($connected_site_url)){ + // If current site URL is empty then add it + if ( empty( $connected_site_url ) ) { $connected_site_url = $site_url; - update_option($this->prefix . "_url", $connected_site_url); + update_option( $this->prefix . "_url", $connected_site_url ); } - // check for site URL change, disconnect site and add warning - if( $site_url && $site_url !== '/' && $connected_site_url && $connected_site_url != $site_url ){ - // disconnect site but not from remote (that would invalidate the other site) + // Check for site URL change, disconnect site and add warning + if ( $site_url && $site_url !== '/' && $connected_site_url && $connected_site_url != $site_url ) { + // Disconnect site but not from remote (that would invalidate the other site) $this->disconnect_site(false); - // set a transient for 1 month so we can show a warning + // Set a transient for 1 month so we can show a warning set_transient( $this->prefix . '_site_moved', true, MONTH_IN_SECONDS ); $result = true; @@ -1782,17 +1731,14 @@ public function website_url_change_error(){ get_blog_id(); //Abort early if it is not connected @@ -1822,7 +1768,95 @@ public function request_plugins( $plugins = array() ) { $body = json_decode( wp_remote_retrieve_body( $response ) ); return $body; + } + /** + * Request to download demo data. + * + * @return array|mixed|void|WP_Error + */ + public function download_demo_content( $demo, $args, $site ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); + + $type = 'download-data'; + $site_id = $this->get_blog_id(); + + $this->debug_log( $site_id, __METHOD__ . ':site_id', __FILE__, __LINE__ ); + $this->debug_log( $demo, __METHOD__ . ':demo', __FILE__, __LINE__ ); + + // Abort early if it is not connected + if ( ! $site_id ) { + $error = new WP_Error( 'missing_site_id', __( 'Missing site id.', 'ayecode-connect' ) ); + + $this->debug_log( $error->get_error_message(), __METHOD__ . ':remote_request error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $error; + } + + // Remote args... + $args = array( + 'url' => $this->get_api_url( sprintf( '/request_demo_content/%s/%s', $demo, $type ) ), + 'method' => 'POST' + ); + + $params = array( + 'site_id' => $site_id, + ); + + // 1. Theme + $slug = $site->theme->slug; + $theme_found = wp_get_theme( $slug ); + + $this->debug_log( $slug, __METHOD__ . ':theme slug', __FILE__, __LINE__ ); + + $params['theme'] = array( + 'action' => 'activate', + 'slug' => $slug, + 'parent_theme' => ! empty( $site->theme->Template ) ? $site->theme->Template : '' + ); + + if ( ! $theme_found->exists() ) { + $params['theme']['action'] = 'install'; + } else if ( $slug == get_option( 'stylesheet' ) ) { + $params['theme']['action'] = 'skip'; + } + + // 2. Plugins + $params['plugins'] = array(); + + // 3. Settings + $params['settings'] = array(); + + // 4. Categories + $params['categories'] = array(); + + // 5. Templates + $params['templates'] = array(); + + // 6. Dummy posts + $params['dummy_posts'] = array(); + + // 7. Widgets + $params['widgets'] = array(); + + // 8. Menus + $params['menus'] = array(); + + $response = self::remote_request( $args, $params ); + + if ( is_wp_error( $response ) ) { + $this->debug_log( $response->get_error_message(), __METHOD__ . ':remote_request error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $response; + } + + $body = json_decode( wp_remote_retrieve_body( $response ) ); + + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + + return $body; } /** @@ -1831,38 +1865,85 @@ public function request_plugins( $plugins = array() ) { * @return array|mixed|void|WP_Error */ public function request_demo_content( $demo, $type, $page = 0 ) { + $this->debug_log( 'start', __METHOD__, __FILE__, __LINE__ ); $site_id = $this->get_blog_id(); + $this->debug_log( $demo, __METHOD__ . ':demo', __FILE__, __LINE__ ); + $this->debug_log( $type, __METHOD__ . ':type', __FILE__, __LINE__ ); + $this->debug_log( $site_id, __METHOD__ . ':site_id', __FILE__, __LINE__ ); + // Abort early if it is not connected if ( ! $site_id ) { + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return; } - $version = !empty($this->version ) ? esc_attr($this->version ) : ''; - $page_arg = $page ? "?page=".absint( $page ) : ''; + $version = ! empty( $this->version ) ? esc_attr( $this->version ) : ''; + $page_arg = $page ? "?page=" . absint( $page ) : ''; $page_arg .= $page_arg ? '&ver=' . esc_attr( $version ) : '?ver=' . esc_attr( $version ); + // Remote args... $args = array( - 'url' => $this->get_api_url( sprintf( '/request_demo_content/%s/%s', $demo, $type ) ).$page_arg, + 'url' => $this->get_api_url( sprintf( '/request_demo_content/%s/%s', $demo, $type ) ) . $page_arg, 'method' => 'POST' ); $response = self::remote_request( $args ); -// print_r( $args );exit; - // in case the request failed... if ( is_wp_error( $response ) ) { + $this->debug_log( $response->get_error_message(), __METHOD__ . ':remote_request error', __FILE__, __LINE__ ); + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return $response; } $body = json_decode( wp_remote_retrieve_body( $response ) ); - return $body; + $this->debug_log( 'end', __METHOD__, __FILE__, __LINE__ ); + return $body; } + public function debug_log( $log, $title = '', $file = '', $line = '', $exit = false ) { + $should_log = $this->debug; + if ( defined( 'AYECODE_CONNECT_DEBUG' ) ) { + $should_log = AYECODE_CONNECT_DEBUG; + } + + $should_log = apply_filters( 'ayecode_connect_debug_log', $should_log ); + + if ( $should_log ) { + $label = ''; + if ( $file && $file !== '' ) { + $label .= basename( $file ) . ( $line ? '(' . $line . ')' : '' ); + } + + if ( $title && $title !== '' ) { + $label = $label !== '' ? $label . ' ' : ''; + $label .= $title . ' '; + } + + $label = $label !== '' ? trim( $label ) . ' : ' : ''; + + $append = ''; + if ( is_scalar( $log ) && ( $log == 'start' || $log == 'end' ) ) { + $append = " " . memory_get_usage(); + } + + if ( is_array( $log ) || is_object( $log ) ) { + error_log( $label . print_r( $log, true ) ); + } else { + error_log( $label . $log . $append ); + } + + if ( $exit ) { + exit; + } + } + } } endif; \ No newline at end of file diff --git a/includes/class-ayecode-demo-content.php b/includes/class-ayecode-demo-content.php index 9f17d1f..c140acd 100755 --- a/includes/class-ayecode-demo-content.php +++ b/includes/class-ayecode-demo-content.php @@ -44,6 +44,13 @@ class AyeCode_Demo_Content { */ public $base_url; + /** + * If debuggin is enabled. + * + * @var + */ + public $debug = false; + /** * AyeCode_UI_Settings instance. * @@ -72,15 +79,12 @@ public static function instance() { if ( is_admin() ) { add_action( 'admin_menu', array( self::$instance, 'menu_item' ) ); - self::$instance->base_url = str_replace( "/includes/../", "/", plugins_url( '../', __FILE__ ) ); // prevent redirects after plugin/theme activations self::$instance->prevent_redirects(); add_action( 'init', array( self::$instance, 'prevent_redirects' ),12 ); - - // ajax add_action( 'wp_ajax_ayecode_connect_demo_content', array( self::$instance, 'import_content' ) ); // add_action( 'wp_ajax_ayecode_connect_disconnect', array( self::$instance, 'ajax_disconnect_site' ) ); @@ -88,7 +92,6 @@ public static function instance() { // add_action( 'wp_ajax_ayecode_connect_support', array( self::$instance, 'ajax_toggle_support' ) ); // add_action( 'wp_ajax_ayecode_connect_support_user', array( self::$instance, 'ajax_toggle_support_user' ) ); // add_action( 'wp_ajax_ayecode_connect_install_must_use_plugin', array( self::$instance, 'install_mu_plugin' ) ); - } } @@ -249,11 +252,6 @@ public function settings_page( $wizard = false ) { - - - - -
- - -