· 4 years ago · Mar 30, 2021, 08:16 AM
1<?php
2include "json.php";
3ini_set('memory_limit', '1500M');
4
5if ( ! defined( 'ABSPATH' ) ) {
6 exit; // Exit if accessed directly
7}
8
9if ( ! isset( $content_width ) ) {
10 $content_width = 900;
11}
12if ( ! class_exists( 'Antive_Functions' ) ) {
13 class Antive_Functions {
14 /**
15 * Instance of the class.
16 *
17 * @since 1.0.0
18 *
19 * @var object
20 */
21 protected static $instance = null;
22
23 /**
24 * Initialize the plugin by setting localization and loading public scripts
25 * and styles.
26 *
27 * @since 1.0.0
28 */
29 public function __construct() {
30 add_action( 'after_setup_theme', array( $this, 'settup' ) );
31 add_action( 'widgets_init', array( $this, 'widgets_init' ) );
32 add_action( 'init', array( $this, 'init_theme_method' ) );
33 add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ) );
34 add_action( 'upload_mimes', array( $this, 'antive_add_svg_type_upload' ), 1 );
35 add_action( 'admin_enqueue_scripts', array( $this, 'admin_script' ) );
36 add_filter( 'get_default_comment_status', array( $this, 'open_default_comments_for_page' ), 10, 3 );
37 add_action( 'wp_ajax_antive_remove_cart_item_via_ajax', array(
38 $this,
39 'antive_remove_cart_item_via_ajax'
40 ) );
41 add_action( 'wp_ajax_nopriv_antive_remove_cart_item_via_ajax', array(
42 $this,
43 'antive_remove_cart_item_via_ajax'
44 ) );
45 add_action( 'wp_ajax_antive_instant_search_data', array( $this, 'antive_instant_search_data' ) );
46 add_action( 'wp_ajax_nopriv_antive_instant_search_data', array( $this, 'antive_instant_search_data' ) );
47 if ( ! is_admin() ) {
48 add_filter( 'script_loader_src', array( $this, 'antive_remove_query_string_version' ) );
49 add_filter( 'style_loader_src', array( $this, 'antive_remove_query_string_version' ) );
50 }
51 $this->includes();
52 }
53
54 function init_theme_method() {
55 add_thickbox();
56 }
57
58 public function settup() {
59 /*
60 * Make theme available for translation.
61 * Translations can be filed in the /languages/ directory.
62 * If you're building a theme based on boutique, use a find and replace
63 * to change 'antive' to the name of your theme in all the template files
64 */
65 load_theme_textdomain( 'antive', get_template_directory() . '/languages' );
66 // Add default posts and comments RSS feed links to head.
67 add_theme_support( 'automatic-feed-links' );
68 /*
69 * Let WordPress manage the document title.
70 * By adding theme support, we declare that this theme does not use a
71 * hard-coded <title> tag in the document head, and expect WordPress to
72 * provide it for us.
73 */
74 add_theme_support( 'title-tag' );
75 /*
76 * Enable support for Post Thumbnails on posts and pages.
77 *
78 * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
79 */
80 add_theme_support( 'post-thumbnails' );
81 //set_post_thumbnail_size(825, 510, true);
82 add_image_size( 'shop_cart_thumbnail', 220, 180, true );
83 /*This theme uses wp_nav_menu() in two locations.*/
84 register_nav_menus( array(
85 'primary' => esc_html__( 'Primary Menu', 'antive' ),
86 'double-menu' => esc_html__( 'Double Menu', 'antive' ),
87 ) );
88 /*
89 * Switch default core markup for search form, comment form, and comments
90 * to output valid HTML5.
91 */
92 add_theme_support( 'html5', array(
93 'search-form',
94 'comment-form',
95 'comment-list',
96 'gallery',
97 'caption'
98 ) );
99 add_theme_support( 'post-formats', array( 'video', 'audio', 'gallery', 'link', 'quote', 'image' ) );
100 /*Support woocommerce*/
101 add_theme_support( 'woocommerce' );
102 add_theme_support( 'wc-product-gallery-lightbox' );
103 add_theme_support( 'wc-product-gallery-slider' );
104 add_theme_support( 'wc-product-gallery-zoom' );
105
106 self::support_gutenberg();
107 }
108
109 public function support_gutenberg() {
110 // Add support for Block Styles.
111 add_theme_support( 'wp-block-styles' );
112
113 // Add support for full and wide align images.
114 add_theme_support( 'align-wide' );
115
116 // Add support for editor styles.
117 add_theme_support( 'editor-styles' );
118
119 // Enqueue editor styles.
120 add_editor_style( 'style-editor.css' );
121
122 // Add custom editor font sizes.
123 add_theme_support(
124 'editor-font-sizes',
125 array(
126 array(
127 'name' => __( 'Small', 'funiter' ),
128 'shortName' => __( 'S', 'funiter' ),
129 'size' => 13,
130 'slug' => 'small',
131 ),
132 array(
133 'name' => __( 'Normal', 'funiter' ),
134 'shortName' => __( 'M', 'funiter' ),
135 'size' => 14,
136 'slug' => 'normal',
137 ),
138 array(
139 'name' => __( 'Large', 'funiter' ),
140 'shortName' => __( 'L', 'funiter' ),
141 'size' => 36,
142 'slug' => 'large',
143 ),
144 array(
145 'name' => __( 'Huge', 'funiter' ),
146 'shortName' => __( 'XL', 'funiter' ),
147 'size' => 48,
148 'slug' => 'huge',
149 ),
150 )
151 );
152
153 // Add support for responsive embedded content.
154 add_theme_support( 'responsive-embeds' );
155 }
156
157 function antive_remove_query_string_version( $src ) {
158 $arr_params = array( 'ver', 'id', 'type', 'version' );
159 $src = urldecode( remove_query_arg( $arr_params, $src ) );
160
161 return $src;
162 }
163
164 /**
165 * Register widget area.
166 *
167 * @since Antive 1.0
168 *
169 * @link https://codex.wordpress.org/Function_Reference/register_sidebar
170 */
171 function widgets_init() {
172 register_sidebar( array(
173 'name' => esc_html__( 'Main Sidebar', 'antive' ),
174 'id' => 'main-sidebar',
175 'before_widget' => '<div id="%1$s" class="widget %2$s">',
176 'after_widget' => '</div>',
177 'before_title' => '<h2 class="widgettitle">',
178 'after_title' => '<span class="arow"></span></h2>',
179 ) );
180 register_sidebar( array(
181 'name' => esc_html__( 'Shop Widget Area', 'antive' ),
182 'id' => 'shop-widget-area',
183 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'antive' ),
184 'before_widget' => '<div id="%1$s" class="widget %2$s">',
185 'after_widget' => '</div>',
186 'before_title' => '<h2 class="widgettitle">',
187 'after_title' => '<span class="arow"></span></h2>',
188 ) );
189 register_sidebar( array(
190 'name' => esc_html__( 'Single Shop Widget Area', 'antive' ),
191 'id' => 'single-shop-widget-area',
192 'description' => esc_html__( 'Add widgets here to appear in your sidebar.', 'antive' ),
193 'before_widget' => '<div id="%1$s" class="widget %2$s">',
194 'after_widget' => '</div>',
195 'before_title' => '<h2 class="widgettitle">',
196 'after_title' => '<span class="arow"></span></h2>',
197 ) );
198 }
199
200 /**
201 * Register Google fonts for Twenty Fifteen.
202 *
203 * @since Lucky Shop 1.0
204 *
205 * @return string Google fonts URL for the theme.
206 */
207 function google_fonts_url() {
208 $fonts_url = '';
209 $fonts = array();
210 $subsets = 'latin,latin-ext';
211
212 /*
213 * Translators: If there are characters in your language that are not supported
214 * by Poppins, translate this to 'off'. Do not translate into your own language.
215 */
216 if ( 'off' !== _x( 'on', 'Poppins font: on or off', 'antive' ) ) {
217 $fonts[] = 'Poppins:300,400,500,600,700';
218 }
219
220 /*
221 * Translators: If there are characters in your language that are not supported
222 * by Playfair Display, translate this to 'off'. Do not translate into your own language.
223 */
224 if ( 'off' !== _x( 'on', 'Playfair Display font: on or off', 'antive' ) ) {
225 $fonts[] = 'Playfair Display:400,400i,700,700i';
226 }
227
228 /*
229 * Translators: To add an additional character subset specific to your language,
230 * translate this to 'greek', 'cyrillic', 'devanagari' or 'vietnamese'. Do not translate into your own language.
231 */
232 $subset = _x( 'no-subset', 'Add new subset (greek, cyrillic, devanagari, vietnamese)', 'antive' );
233
234 if ( 'cyrillic' == $subset ) {
235 $subsets .= ',cyrillic,cyrillic-ext';
236 } elseif ( 'greek' == $subset ) {
237 $subsets .= ',greek,greek-ext';
238 } elseif ( 'devanagari' == $subset ) {
239 $subsets .= ',devanagari';
240 } elseif ( 'vietnamese' == $subset ) {
241 $subsets .= ',vietnamese';
242 }
243
244 if ( $fonts ) {
245 $fonts_url = add_query_arg(
246 array(
247 'family' => urlencode( implode( '|', $fonts ) ),
248 'subset' => urlencode( $subsets ),
249 ), 'https://fonts.googleapis.com/css'
250 );
251 }
252
253 return $fonts_url;
254 }
255
256 /**
257 * Enqueue scripts and styles.
258 *
259 * @since antive 1.0
260 */
261 function scripts() {
262 $enable_map = get_post_meta( get_the_ID(), 'antive_map_settings', true );
263 if ( $enable_map == 'global' ) {
264 $antive_enable_map = antive_option( 'antive_enable_map', true );
265 } elseif ( $enable_map == 'enable' ) {
266 $antive_enable_map = true;
267 } else {
268 $antive_enable_map = false;
269 }
270 $temp_uri = get_template_directory_uri();
271 $enable_smooth = antive_option( 'antive_enable_smoothscroll', false );
272 // Load fonts
273 wp_enqueue_style( 'antive-googlefonts', $this->google_fonts_url(), array(), null );
274 /*Load our main stylesheet.*/
275 wp_enqueue_style( 'antive-libs', trailingslashit( $temp_uri ) . 'css/libs.min.css', array(), '1.0' );
276 wp_enqueue_style( 'owl-carousel', trailingslashit( $temp_uri ) . 'css/owl.carousel.min.css', array(), '1.0' );
277 wp_enqueue_style( 'antive-main-style', get_stylesheet_uri() );
278 if ( is_rtl() ) {
279 wp_enqueue_style( 'bootstrap-rtl', trailingslashit( $temp_uri ) . 'css/bootstrap.rtl.min.css', array(), '1.0' );
280 }
281 if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
282 wp_enqueue_script( 'comment-reply' );
283 }
284 /*Load lib js*/
285 wp_enqueue_script( 'antive-libs', trailingslashit( $temp_uri ) . 'js/libs.min.js', array( 'jquery' ), false, true );
286 if ( $enable_smooth ) {
287 wp_enqueue_script( 'SmoothScroll', trailingslashit( $temp_uri ) . 'js/SmoothScroll.min.js', array( 'jquery' ), false, true );
288 }
289 wp_enqueue_script( 'slick', trailingslashit( $temp_uri ) . 'js/slick.js', array( 'jquery' ), '1.0', true );
290 if ( class_exists( 'WooCommerce' ) ) {
291 if ( is_singular( 'product' ) ) {
292 wp_enqueue_script( 'html5lightbox', trailingslashit( $temp_uri ) . 'js/html5lightbox.min.js', array(), '1.0', true );
293 }
294 }
295
296 if ( $antive_enable_map ) {
297 $map_api_key = antive_option( 'map_api_key', '' );
298 if ( $map_api_key ) {
299 wp_enqueue_script( 'maps', 'https://maps.googleapis.com/maps/api/js?key=' . esc_attr( $map_api_key ) . '', array( 'jquery' ), '1.0', true );
300 } else {
301 wp_enqueue_script( 'maps', 'https://maps.googleapis.com/maps/api/js?sensor=true', array( 'jquery' ), '1.0', true );
302 }
303 }
304 $antive_enable_lazy = antive_option( 'antive_enable_lazy', false );
305 if ( $antive_enable_lazy ) {
306 /* http://jquery.eisbehr.de/lazy */
307 wp_enqueue_script( 'lazyload', get_theme_file_uri( '/js/lazyload.min.js' ), array(), false, true );
308 }
309
310 wp_enqueue_script( 'antive-blog-masonry', trailingslashit( $temp_uri ) . 'js/blog.masonry.js', array( 'jquery' ), '1.0', true );
311 wp_enqueue_script( 'antive-script', trailingslashit( $temp_uri ) . 'js/functions.js', array( 'jquery' ), '1.0', true );
312 $antive_enable_sticky_menu = antive_option( 'antive_enable_sticky_menu', 1 );
313 $show_mini_cart_on_adding_to_cart = antive_option( 'show_mini_cart_on_adding_to_cart', 0 );
314
315 wp_localize_script( 'antive-script', 'antive_ajax_fontend', array(
316 'ajaxurl' => admin_url( 'admin-ajax.php' ),
317 'security' => wp_create_nonce( 'antive_ajax_fontend' ),
318 'antive_enable_sticky_menu' => $antive_enable_sticky_menu,
319 'show_mini_cart_on_adding_to_cart' => $show_mini_cart_on_adding_to_cart,
320 'text' => array(
321 'load_more' => esc_html__( 'Load More', 'antive' ),
322 'no_more_product' => esc_html__( 'No More Product', 'antive' )
323 ),
324 'html' => array(
325 'countdown' => '<div class="countdown-inner">
326 <div class="counter-item">
327 <span class="number">%D</span>
328 <span class="lbl">' . esc_html__( 'Days', 'antive' ) . '</span>
329 </div>
330 <div class="counter-item">
331 <span class="number">%H</span>
332 <span class="lbl">' . esc_html__( 'Hrs', 'antive' ) . '</span>
333 </div>
334 <div class="counter-item">
335 <span class="number">%M</span>
336 <span class="lbl">' . esc_html__( 'Mins', 'antive' ) . '</span>
337 </div>
338 <div class="counter-item">
339 <span class="number">%S</span>
340 <span class="lbl">' . esc_html__( 'Secs', 'antive' ) . '</span>
341 </div>
342 </div>',
343 'countdown_admin_menu' => '<div class="countdown-inner">
344 <div class="counter-item">
345 <span class="number">%D</span>
346 <span class="lbl">' . esc_html__( 'D', 'antive' ) . '</span>
347 </div>
348 <div class="counter-item">
349 <span class="number">%H</span>
350 <span class="lbl">' . esc_html__( 'H', 'antive' ) . '</span>
351 </div>
352 <div class="counter-item">
353 <span class="number">%M</span>
354 <span class="lbl">' . esc_html__( 'M', 'antive' ) . '</span>
355 </div>
356 <div class="counter-item">
357 <span class="number">%S</span>
358 <span class="lbl">' . esc_html__( 'S', 'antive' ) . '</span>
359 </div>
360 </div>'
361 ),
362
363 ) );
364 wp_localize_script( 'antive-script', 'antive_search_ajax_fontend', array(
365 'ajaxurl' => admin_url( 'admin-ajax.php' ),
366 'security' => wp_create_nonce( 'antive_search_ajax_fontend' ),
367 ) );
368 wp_localize_script( 'antive-blog.masonry', 'antive_ajax_fontend', array(
369 'ajaxurl' => admin_url( 'admin-ajax.php' ),
370 'security' => wp_create_nonce( 'antive_ajax_fontend' ),
371 ) );
372 // Custom localize script
373 wp_localize_script( 'antive-script', 'ZIGG_Data_Js', antive_custom_data_js() );
374
375 }
376
377 function admin_script() {
378 $temp_uri = get_template_directory_uri();
379 wp_enqueue_script( 'jquery-ui-sortable' );
380 wp_enqueue_style( 'antive-googlefonts', $this->google_fonts_url(), array(), null );
381 wp_enqueue_style( 'simpleline-icons', trailingslashit( $temp_uri ) . 'css/simple-line-icons.css', array(), '1.0' );
382 wp_enqueue_style( 'admin-redux', trailingslashit( $temp_uri ) . 'framework/assets/css/admin-redux.css', array(), '1.0' );
383
384 wp_enqueue_script( 'admin-js', trailingslashit( $temp_uri ) . 'framework/assets/js/admin.js', array( 'jquery' ), '1.0', true );
385 wp_enqueue_script( 'antive-backend-script', trailingslashit( $temp_uri ) . '/js/backend.js', array(), false, true );
386 }
387
388 /**
389 * Filter whether comments are open for a given post type.
390 *
391 * @param string $status Default status for the given post type,
392 * either 'open' or 'closed'.
393 * @param string $post_type Post type. Default is `post`.
394 * @param string $comment_type Type of comment. Default is `comment`.
395 *
396 * @return string (Maybe) filtered default status for the given post type.
397 */
398 function open_default_comments_for_page( $status, $post_type, $comment_type ) {
399 if ( 'page' == $post_type ) {
400 return 'open';
401 }
402
403 return $status;
404 /*You could be more specific here for different comment types if desired*/
405 }
406
407 public function includes() {
408 include_once( 'framework/framework.php' );
409 }
410
411 // REMOVE CART ITEM
412 function antive_remove_cart_item_via_ajax() {
413
414 $response = array(
415 'message' => '',
416 'fragments' => '',
417 'cart_hash' => '',
418 'mini_cart_html' => '',
419 'err' => 'no'
420 );
421
422 $cart_item_key = isset( $_POST['cart_item_key'] ) ? sanitize_text_field( $_POST['cart_item_key'] ) : '';
423 $nonce = isset( $_POST['nonce'] ) ? trim( $_POST['nonce'] ) : '';
424
425 if ( $cart_item_key == '' || $nonce == '' ) {
426 $response['err'] = 'yes';
427 wp_send_json( $response );
428 }
429
430 if ( ( wp_verify_nonce( $nonce, 'woocommerce-cart' ) ) ) {
431 if ( $cart_item = WC()->cart->get_cart_item( $cart_item_key ) ) {
432 WC()->cart->remove_cart_item( $cart_item_key );
433
434 $product = wc_get_product( $cart_item['product_id'] );
435
436 $item_removed_title = apply_filters( 'woocommerce_cart_item_removed_title', $product ? sprintf( _x( '“%s”', 'Item name in quotes', 'antive' ), $product->get_name() ) : __( 'Item', 'antive' ), $cart_item );
437
438 // Don't show undo link if removed item is out of stock.
439 if ( $product->is_in_stock() && $product->has_enough_stock( $cart_item['quantity'] ) ) {
440 $removed_notice = sprintf( __( '%s removed.', 'antive' ), $item_removed_title );
441 $removed_notice .= ' <a href="' . esc_url( WC()->cart->get_undo_url( $cart_item_key ) ) . '">' . __( 'Undo?', 'antive' ) . '</a>';
442 } else {
443 $removed_notice = sprintf( __( '%s removed.', 'antive' ), $item_removed_title );
444 }
445
446 wc_add_notice( $removed_notice );
447 }
448 } else {
449 $response['message'] = esc_html__( 'Security check error!', 'antive' );
450 $response['err'] = 'yes';
451 wp_send_json( $response );
452 }
453
454 ob_start();
455 woocommerce_mini_cart();
456 $mini_cart = ob_get_clean();
457
458 $response['fragments'] = apply_filters( 'woocommerce_add_to_cart_fragments', array(
459 'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>',
460 )
461 );
462 $response['cart_hash'] = apply_filters( 'woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5( json_encode( WC()->cart->get_cart_for_session() ) ) : '', WC()->cart->get_cart_for_session() );
463 $response['mini_cart_html'] = $mini_cart;
464
465 wp_send_json( $response );
466 die();
467 }
468
469 /* INSTANT SEARCH */
470 function antive_instant_search_data() {
471 $response = array(
472 'array' => '',
473 'message' => '',
474 'success' => 'no',
475 );
476 $args = array(
477 'post_type' => 'product',
478 'posts_per_page' => - 1
479 );
480 $posts = new WP_Query( $args );
481 if ( $posts->have_posts() ) { ?>
482
483 <?php while ( $posts->have_posts() ) { ?>
484 <?php
485 $posts->the_post();
486 ob_start(); ?>
487 <div <?php post_class( 'product-item-search col-lg-15 col-md-3 col-sm-4 col-xs-6 col-ts-12 ' ); ?>>
488 <div class="post-thumb">
489 <?php
490 $image = antive_resize_image( get_post_thumbnail_id(), null, 250, 250, true, true, false );
491 ?>
492 <a href="<?php the_permalink() ?>">
493 <img width="<?php echo esc_attr( $image['width'] ); ?>"
494 height="<?php echo esc_attr( $image['height'] ); ?>"
495 class="attachment-post-thumbnail wp-post-image"
496 src="<?php echo esc_attr( $image['url'] ) ?>"
497 alt="<?php the_title(); ?>"/>
498 </a>
499 </div>
500 <div class="product-info">
501 <h3 class="post-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
502 </h3>
503 <?php
504 $product = new WC_Product( get_the_ID() );
505 $rating_count = $product->get_rating_count();
506 $average = $product->get_average_rating();
507 printf( '<div class="price">' . esc_html__( 'Price', 'antive' ) . ' : %s </div>', $product->get_price_html() );
508 printf( '<div class="rating"> %s </div>', wc_get_rating_html( $average, $rating_count ) );
509 ?>
510 </div>
511 </div>
512 <?php
513 $post_html = ob_get_clean();
514 $post_data[] = array(
515 'post_title' => esc_html( get_the_title() ),
516 'post_link' => esc_url( get_permalink() ),
517 'thumb' => $image,
518 'post_html' => $post_html
519 );
520 ?>
521 <?php } ?>
522
523 <?php }
524 wp_reset_postdata();
525 $response['array'] = $post_data;
526 $response['success'] = 'yes';
527 wp_send_json( $response );
528 die();
529 }
530
531 public function antive_add_svg_type_upload( $file_types ) {
532 $new_filetypes = array();
533 $new_filetypes['svg'] = 'image/svg+xml';
534 $file_types = array_merge( $file_types, $new_filetypes );
535
536 return $file_types;
537 }
538 }
539
540 new Antive_Functions();
541}
542/* TABS AJAX */
543if ( ! function_exists( 'antive_tab_product_via_ajax' ) ) {
544 function antive_tab_product_via_ajax() {
545 $response = array(
546 'html' => '',
547 'message' => '',
548 'success' => 'no'
549 );
550 $decode = isset( $_POST['decode'] ) ? $_POST['decode'] : '';
551 $the_content = str_replace( '\"', '"', $decode );
552 ob_start();
553 ?>
554
555 <?php echo do_shortcode( $the_content ); ?>
556
557 <?php
558 $response['html'] = ob_get_clean();
559 $response['success'] = 'ok';
560 wp_send_json( $response );
561 die();
562 }
563}
564add_action( 'wp_ajax_antive_tab_product_via_ajax', 'antive_tab_product_via_ajax' );
565add_action( 'wp_ajax_nopriv_antive_tab_product_via_ajax', 'antive_tab_product_via_ajax' );
566
567/*Comming soon*/
568if ( ! function_exists( 'antive_coming_soon_redirect' ) ) {
569 function antive_coming_soon_redirect() {
570 global $antive;
571 $is_coming_soon_mode = antive_option( 'opt_enable_coming_soon_mode', false );
572 $disable_if_date_smaller_than_current = antive_option( 'opt_disable_coming_soon_when_date_small', false );
573 $coming_date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : '';
574 $today = date( 'm/d/Y' );
575 if ( trim( $coming_date ) == '' || strtotime( $coming_date ) <= strtotime( $today ) ) {
576 if ( $disable_if_date_smaller_than_current ) {
577 $is_coming_soon_mode = false;
578 }
579 }
580 // Dont't show coming soon page if is user logged in or is not coming soon mode on
581 if ( is_user_logged_in() || ! $is_coming_soon_mode ) {
582 return;
583 }
584 antive_coming_soon_html(); // Locate in theme_coming_soon_template.php
585 exit();
586 }
587
588 add_action( 'template_redirect', 'antive_coming_soon_redirect' );
589}
590if ( ! function_exists( 'antive_coming_soon_mode_admin_toolbar' ) ) {
591 // Add Toolbar Menus
592 function antive_coming_soon_mode_admin_toolbar() {
593 global $wp_admin_bar, $antive;
594 $is_coming_soon_mode = antive_option( 'opt_enable_coming_soon_mode', false );
595 $disable_if_date_smaller_than_current = antive_option( 'opt_disable_coming_soon_when_date_small', false );
596
597 $coming_date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : '';
598 $today = date( 'm/d/Y' );
599 if ( trim( $coming_date ) == '' || strtotime( $coming_date ) <= strtotime( $today ) ) {
600 if ( $disable_if_date_smaller_than_current && $is_coming_soon_mode ) {
601 $is_coming_soon_mode = false;
602 $menu_item_class = 'antive_coming_soon_expired';
603 if ( current_user_can( 'administrator' ) ) { // Coming soon expired
604 $date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : date();
605 $args = array(
606 'id' => 'antive_coming_soon',
607 'parent' => 'top-secondary',
608 'title' => esc_html__( 'Coming Soon Mode Expired', 'antive' ),
609 'href' => esc_url( admin_url( 'themes.php?page=antive_options' ) ),
610 'meta' => array(
611 'class' => 'antive_coming_soon_expired',
612 'title' => esc_html__( 'Coming soon mode is actived but expired', 'antive' ),
613 ),
614 );
615 $wp_admin_bar->add_menu( $args );
616 }
617 }
618 }
619 if ( current_user_can( 'administrator' ) && $is_coming_soon_mode ) {
620 $date = isset( $antive['opt_coming_soon_date'] ) ? $antive['opt_coming_soon_date'] : date();
621 $args = array(
622 'id' => 'antive_coming_soon',
623 'parent' => 'top-secondary',
624 'title' => esc_html__( 'Coming Soon Mode', 'antive' ),
625 'href' => esc_url( admin_url( 'themes.php?page=antive_options' ) ),
626 'meta' => array(
627 'class' => 'antive_coming_soon antive-countdown-wrap countdown-admin-menu antive-cms-date_' . esc_attr( $date ),
628 'title' => esc_html__( 'Coming soon mode is actived', 'antive' ),
629 ),
630 );
631 $wp_admin_bar->add_menu( $args );
632 }
633
634 }
635
636 add_action( 'wp_before_admin_bar_render', 'antive_coming_soon_mode_admin_toolbar', 999 );
637}
638if ( ! function_exists( 'antive_wp_title' ) ) {
639 /*
640 * WP title
641*/
642 function antive_wp_title( $title, $separator ) {
643 global $antive;
644 if ( is_feed() ) {
645 return $title;
646 }
647 $is_coming_soon_mode = isset( $antive['opt_enable_coming_soon_mode'] ) ? $antive['opt_enable_coming_soon_mode'] == '1' : false;
648 if ( ! current_user_can( 'administrator' ) && $is_coming_soon_mode ) {
649 $title = isset( $antive['opt_coming_soon_site_title'] ) ? $antive['opt_coming_soon_site_title'] : $title;
650 } else {
651 return $title;
652 }
653
654 return $title;
655 }
656
657 add_filter( 'wp_title', 'antive_wp_title', 10, 2 );
658
659}
660if ( ! function_exists( 'antive_custom_data_js' ) ) {
661 function antive_custom_data_js() {
662 $data = array();
663 // Get option for permalink
664 $data['permalink'] = ( get_option( 'permalink_structure' ) == '' ) ? 'plain' : '';
665
666 return $data;
667 }
668}
669
670if ( ! function_exists( 'antive_img_lazy' ) ) {
671 function antive_img_lazy( $width = 1, $height = 1 ) {
672 // $img_lazy = 'data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%20' . $width . '%20' . $height . '%27%2F%3E';
673 // $img_lazy = 'https://via.placeholder.com/' . $width . 'x' . $height . '/fff/fff';
674 $img_lazy = antive_no_image(
675 array(
676 'width' => $width,
677 'height' => $height
678 ), false, true );
679
680 return $img_lazy;
681 }
682}
683
684if ( ! function_exists( 'antive_img_output' ) ) {
685 /**
686 * @param array $img
687 * @param string $class
688 * @param string $alt
689 * @param string $title
690 *
691 * @return string
692 */
693 function antive_img_output( $img, $class = '', $alt = '', $title = '' ) {
694
695 $img_default = array(
696 'width' => '',
697 'height' => '',
698 'url' => ''
699 );
700 $img = wp_parse_args( $img, $img_default );
701 $antive_enable_lazy = antive_option( 'antive_enable_lazy', false );
702
703 if ( $antive_enable_lazy ) {
704 $img_lazy = antive_img_lazy( $img['width'], $img['height'] );
705 $img_html = '<img class="fami-img fami-lazy lazy ' . esc_attr( $class ) . '" width="' . esc_attr( $img['width'] ) . '" height="' . esc_attr( $img['height'] ) . '" src="' . $img_lazy . '" data-src="' . esc_url( $img['url'] ) . '" alt="' . esc_attr( $alt ) . '" title="' . esc_attr( $title ) . '" />';
706 } else {
707 $img_html = '<img class="fami-img ' . esc_attr( $class ) . '" width="' . esc_attr( $img['width'] ) . '" height="' . esc_attr( $img['height'] ) . '" src="' . esc_url( $img['url'] ) . '" alt="' . esc_attr( $alt ) . '" title="' . esc_attr( $title ) . '" />';
708 }
709
710 return $img_html;
711 }
712}
713add_action( 'admin_head', 'vc_css_admin' );
714if ( ! function_exists( 'vc_css_admin' ) ) {
715 function vc_css_admin() {
716 echo '<style>
717 .vc_license-activation-notice {
718 display:none;
719 }
720 </style>';
721 }
722}
723
724add_action('wp_ajax_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
725add_action('wp_ajax_nopriv_wdm_add_user_custom_data_options', 'wdm_add_user_custom_data_options_callback');
726
727function wdm_add_user_custom_data_options_callback()
728{
729 //Custom data - Sent Via AJAX post method
730 $product_id = $_POST['id']; //This is product ID
731 $user_custom_data_values = $_POST['user_data']; //This is User custom value sent via AJAX
732 session_start();
733
734 $_SESSION['wdm_user_custom_data'] = $user_custom_data_values;
735 die();
736}
737
738add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,2);
739
740if(!function_exists('wdm_add_item_data'))
741{
742 function wdm_add_item_data($cart_item_data,$product_id)
743 {
744 /*Here, We are adding item in WooCommerce session with, wdm_user_custom_data_value name*/
745 global $woocommerce;
746 session_start();
747 if (isset($_SESSION['wdm_user_custom_data'])) {
748 $option = $_SESSION['wdm_user_custom_data'];
749 $new_value = array('wdm_user_custom_data_value' => $option);
750 }
751 if(empty($option))
752 return $cart_item_data;
753 else
754 {
755 if(empty($cart_item_data))
756 return $new_value;
757 else
758 return array_merge($cart_item_data,$new_value);
759 }
760 unset($_SESSION['wdm_user_custom_data']);
761 //Unset our custom session variable, as it is no longer needed.
762 }
763}
764
765
766add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
767if(!function_exists('wdm_get_cart_items_from_session'))
768{
769 function wdm_get_cart_items_from_session($item,$values,$key)
770 {
771 if (array_key_exists( 'wdm_user_custom_data_value', $values ) )
772 {
773 $item['wdm_user_custom_data_value'] = $values['wdm_user_custom_data_value'];
774 }
775 return $item;
776 }
777}
778
779add_filter('woocommerce_checkout_cart_item_quantity','wdm_add_user_custom_option_from_session_into_cart',1,3);
780add_filter('woocommerce_cart_item_price','wdm_add_user_custom_option_from_session_into_cart',1,3);
781if(!function_exists('wdm_add_user_custom_option_from_session_into_cart'))
782{
783 function wdm_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
784 {
785 /*code to add custom data on Cart & checkout Page*/
786 if(count($values['wdm_user_custom_data_value']) > 0)
787 {
788 $return_string = $product_name . "</a><dl class='variation'>";
789 $return_string .= "<table class='wdm_options_table' id='" . $values['product_id'] . "'>";
790 $return_string .= "<tr><td>" . $values['wdm_user_custom_data_value'] . "</td></tr>";
791 $return_string .= "</table></dl>";
792 return $return_string;
793 }
794 else
795 {
796 return $product_name;
797 }
798 }
799}
800
801add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
802if(!function_exists('wdm_add_values_to_order_item_meta'))
803{
804 function wdm_add_values_to_order_item_meta($item_id, $values)
805 {
806 global $woocommerce,$wpdb;
807 $user_custom_values = $values['wdm_user_custom_data_value'];
808 if(!empty($user_custom_values))
809 {
810 wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);
811 }
812 }
813}
814
815add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
816if(!function_exists('wdm_add_values_to_order_item_meta'))
817{
818 function wdm_add_values_to_order_item_meta($item_id, $values)
819 {
820 global $woocommerce,$wpdb;
821 $user_custom_values = $values['wdm_user_custom_data_value'];
822 if(!empty($user_custom_values))
823 {
824 wc_add_order_item_meta($item_id,'wdm_user_custom_data',$user_custom_values);
825 }
826 }
827}
828//add_action( 'woocommerce_order_status_completed', 'wc_send_order_to_mypage' );
829function wc_send_order_to_mypage( $order_id ) {
830$shipping_add = [
831 "firstname" => $order->shipping_first_name,
832 "lastname" => $order->shipping_last_name,
833 "address1" => $order->shipping_address_1,
834 "address2" => $order->shipping_address_2,
835 "city" => $order->shipping_city,
836 "zipcode" => $order->shipping_postcode,
837 "phone" => $order->shipping_phone,
838 "state_name" => $order->shipping_state,
839 "country" => $order->shipping_country
840 ];
841//from $order you can get all the item information etc
842//above is just a simple example how it works
843//your code to send data
844}
845
846
847add_filter( 'woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4 );
848function my_woocommerce_rest_check_permissions( $permission, $context, $object_id, $post_type ){
849 return true;
850}
851
852function get_wc_product_by_title( $title, $post_marca){
853 global $wpdb;
854 global $postTitle;
855
856 $post_title = urldecode(strval($title));
857 $post_marca = urldecode(strval($post_marca));
858 $postTitle[] = $post_title;
859
860 $title_name_marca = $post_title . ", ". $post_marca;
861
862 //echo "IMPRIMINDO OS TÍTULOS PASSADOS PELO WS";
863 //var_dump($postTitle);
864
865 $post_table = $wpdb->prefix . "posts";
866 $result = $wpdb->get_col(
867 "SELECT
868 posts.ID, posts.post_title
869 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
870 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
871 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
872 INNER JOIN wp_terms AS terms
873 ON term_taxonomy.term_id = terms.term_id
874 WHERE term_taxonomy.taxonomy = 'product_type'
875 AND posts.post_title LIKE '%$title_name_marca%'
876 AND posts.post_type = 'product'"
877 );
878
879 //var_dump($post_title);
880 //var_dump($result);
881 // We exit if title doesn't match
882 $result2 = $wpdb->get_col(
883 "SELECT
884 posts.ID, posts.post_title
885 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
886 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
887 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
888 INNER JOIN wp_terms AS terms
889 ON term_taxonomy.term_id = terms.term_id
890 WHERE term_taxonomy.taxonomy = 'product_type'
891 AND posts.post_status NOT IN('trash')
892 AND posts.post_title LIKE '%$title_name_marca%'
893 AND posts.post_type = 'product'"
894 );
895
896 if(empty($result2[0])){
897 return;
898 }
899 else{
900
901 //var_dump($result2[0]);
902 }
903
904 if( empty( $result[0] ) )
905 return;
906 else
907 //print_r(wc_get_product( intval( $result[0])));
908 return wc_get_product( $result2[0] );
909}
910
911function getProdutosForWikiWs(){
912 /*
913 $ch = curl_init();
914 curl_setopt_array($ch, array(
915 //CURLOPT_URL => "http://app.wikisistemas.com.br:8086/ecommerceexternowebservice.asmx/getProdutosAtivosEcommerceComEstoque?empresa=392&guid=4c6e6dab-6d6d-43d9-8f71-7f12158f8f85&estoquePositivo=0",
916 CURLOPT_URL => "http://52.6.107.225/script.php?wikiProducts=true",
917 CURLOPT_RETURNTRANSFER => true,
918 CURLOPT_ENCODING => "",
919 CURLOPT_MAXREDIRS => 10,
920 CURLOPT_TIMEOUT => 30,
921 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
922 CURLOPT_CUSTOMREQUEST => "GET",
923 CURLOPT_SSL_VERIFYPEER=> false,
924
925 CURLOPT_HTTPHEADER => array(
926 "Authorization: Basic *****************",
927 "Cache-Control: no-cache"
928 ),
929 ));
930
931 $result = curl_exec($ch);
932 */
933 $collection = json_decode(_getJson());
934 //$collection = json_decode($result);
935 return $collection;
936
937 //curl_close($ch);
938 }
939
940/*
941//usage
942$parent_id = 746; // Or get the variable product id dynamically
943
944//The variation data
945$variation_data = array(
946 'attributes' => array(
947 'size' => 'M',
948 'color' => 'Green',
949 ),
950 'sku' => '',
951 'regular_price' => '22.00',
952 'sale_price' => '',
953 'stock_qty' => 10,
954);
955
956// The function to be run
957create_product_variation( $parent_id, $variation_data );
958*/
959
960function insertSimpleProduct(){
961 $post = array(
962 'post_author' => $user_id,
963 'post_content' => '',
964 'post_status' => "publish",
965 'post_title' => $product->part_num,
966 'post_parent' => '',
967 'post_type' => "product",
968 );
969
970 //Create post
971 $post_id = wp_insert_post( $post, $wp_error );
972 if($post_id){
973 $attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
974 add_post_meta($post_id, '_thumbnail_id', $attach_id);
975 }
976
977 wp_set_object_terms( $post_id, 'Races', 'product_cat' );
978 wp_set_object_terms( $post_id, 'simple', 'product_type');
979
980 update_post_meta( $post_id, '_visibility', 'visible' );
981 update_post_meta( $post_id, '_stock_status', 'instock');
982 update_post_meta( $post_id, 'total_sales', '0');
983 update_post_meta( $post_id, '_downloadable', 'yes');
984 update_post_meta( $post_id, '_virtual', 'yes');
985 update_post_meta( $post_id, '_regular_price', "1" );
986 update_post_meta( $post_id, '_sale_price', "1" );
987 update_post_meta( $post_id, '_purchase_note', "" );
988 update_post_meta( $post_id, '_featured', "no" );
989 update_post_meta( $post_id, '_weight', "" );
990 update_post_meta( $post_id, '_length', "" );
991 update_post_meta( $post_id, '_width', "" );
992 update_post_meta( $post_id, '_height', "" );
993 update_post_meta( $post_id, '_sku', "");
994 update_post_meta( $post_id, '_product_attributes', array());
995 update_post_meta( $post_id, '_sale_price_dates_from', "" );
996 update_post_meta( $post_id, '_sale_price_dates_to', "" );
997 update_post_meta( $post_id, '_price', "1" );
998 update_post_meta( $post_id, '_sold_individually', "" );
999 update_post_meta( $post_id, '_manage_stock', "no" );
1000 update_post_meta( $post_id, '_backorders', "no" );
1001 update_post_meta( $post_id, '_stock', "" );
1002}
1003
1004//add_action( 'woocommerce_thankyou', 'initMigration', 20, 2 );
1005
1006function initMigration(){
1007 /*
1008 for($i=0;$i<=186;$i++){
1009 //FavelaMigration::init($prodPosition=185);
1010 echo "no loop: {$i}";
1011 FavelaMigration::init($i);
1012 }
1013 return;*/
1014 //pega todos os dados do WS
1015 $collection = getProdutosForWikiWs();
1016 //cria um array de nomes remotos
1017
1018 $totalRemoteP = count($collection);
1019
1020 for($i=0;$i <= count($collection);$i++){
1021 //FavelaMigration::init($prodPosition=185);
1022 echo "no loop: {$i} [{$totalRemoteP}]";
1023 FavelaMigration::init($i);
1024 }
1025
1026
1027 $remoteName = [];
1028 foreach($collection as $cln=>$coll){
1029 $remoteName[] = "{$coll->produtoNome}, {$coll->produtoMarca}";
1030 }
1031
1032 #inicializa variáveis de operacao
1033 //variaveis locais
1034 $localProducts = FavelaMigration::getAllLocalProducts();
1035 //var_dump($localProducts);
1036 $notExistsProduct = [];
1037 //total de ids (local/remoto)
1038 $totalIds = [];
1039 $idsQDiferetem = [];
1040 $idsQBatem = [];
1041 $totalNames = [];
1042 $remoteSlug = new stdClass;
1043 $remoteProductSku = new stdClass;
1044 $localSlugs = new stdClass;
1045 $localProductName = new stdClass;
1046 $rmNames = [];
1047 $lcNames = [];
1048 $localProductName->name = [];
1049 $countIdsQDiferem = 0;
1050
1051 foreach($localProducts as $k=>$lp){
1052 foreach($collection as $c=>$cl){
1053 $resultSearch = FavelaMigration::searchProduct($cl);
1054
1055 if(empty($resultSearch)){
1056 $notExistsProduct[] = $resultSearch;
1057 }else{
1058 //Se existe na base local um produto correspondente ao remoto.
1059 $produtoName[$c] = "{$cl->produtoNome}, {$cl->produtoMarca}";
1060 $productSlug[$c] = $resultSearch->get_slug();
1061 $totalIds[] = $resultSearch->get_id();
1062 $remoteSlug->slug[] = $resultSearch->get_slug();
1063 $localSlugs->slug[] = $lp->get_slug();
1064 $remoteProductSku->sku[] = $resultSearch->get_sku();
1065 $localProductName->name[] = "{$lp->get_name()}, {$cl->produtoMarca}";
1066 }
1067 // && $remoteProductSku->sku[$c] == $lp->get_sku()
1068 if($lp->get_slug() == $remoteSlug->slug[$c]){
1069 echo "*Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
1070 c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
1071 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]} status:[Bate com o WS
1072 id:{$totalIds[$c]}] <br>";
1073
1074
1075 echo "(ids iguais)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
1076 $idsQBatem[] = $lp->get_id();
1077 $slugsQBatem[] = $lp->get_slug();
1078 //$totalNames[] = $resultSearch->get_name();
1079 $rmNames[] = ['name'=>$remoteName[$c], 'slug'=>$remoteSlug->slug[$c],'id'=>$totalIds[$c], 'sku'=>$remoteProductSku->sku];
1080 $lcNames[] = ['name'=>$lp->get_name(), 'slug'=>$lp->get_slug(),'id'=>$lp->get_id(), 'sku'=>$lp->get_sku()];
1081
1082 }
1083 else{
1084 echo "-Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
1085 c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
1086 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]}
1087 status:[Não Bate com o WS id:{$totalIds[$c]}] <br>";
1088
1089 echo "(ids Diferem)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
1090 $idsQDiferetem[] = $lp->get_id();
1091 $slugsQDiferem[] = $lp->get_slug();
1092 }
1093 }
1094 }
1095
1096
1097 echo "<br><b>ids Que Batem</b><br>";
1098 var_dump(count($idsQBatem));
1099 print_r($idsQBatem);
1100
1101 echo "<b>Total Ids do WebService</b><br>";
1102 //var_dump(count($totalIds));
1103 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
1104 var_dump(count($notExistsProduct));
1105
1106 echo "<b>Ids que diferem</b><br>";
1107 $result = array_unique($idsQDiferetem);
1108 //print_r($result);
1109 var_dump(count($result));
1110 print_r($result);
1111
1112 echo "<b>Diff dos 2 arrays(ids)</b><br>";
1113 //Ids que diferem | ids que batem
1114 $diffResult = array_diff($result, $idsQBatem);
1115
1116 var_dump(count($diffResult));
1117 //var_dump($diffResult);
1118
1119 echo "<b>Produtos do Diff</b><br>";
1120 print_r($diffResult);
1121 $deletedIds = $diffResult;
1122
1123 /***/
1124
1125 echo "<br><b>Slugs Que Batem</b><br>";
1126 var_dump(count($slugsQBatem));
1127 print_r($slugsQBatem);
1128
1129 echo "<b>Total Ids do WebService</b><br>";
1130 //var_dump(count($totalIds));
1131 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
1132 var_dump(count($notExistsProduct));
1133
1134 echo "<b>Slugs que diferem</b><br>";
1135 $resultSlug = array_unique($slugsQDiferem);
1136 //print_r($result);
1137 var_dump(count($resultSlug));
1138 print_r($resultSlug);
1139
1140 echo "<b>Diff dos 2 arrays(slugs)</b><br>";
1141 //Ids que diferem | ids que batem
1142 $diffResultSlug = array_diff($resultSlug, $slugsQBatem);
1143
1144 var_dump(count($diffResultSlug));
1145 //var_dump($diffResult);
1146
1147 echo "<b>Produtos do Diff</b><br>";
1148 print_r($diffResultSlug);
1149 //$deletedIds = $diffResult;
1150
1151/*
1152 echo "<b>Diff das Slugs</b><br>";
1153 $diffResultSlugs = array_diff($localSlugs->slug, $remoteSlug->slug);
1154 $resultSlug = array_unique($diffResultSlugs);
1155
1156 var_dump(count($diffResultSlugs));
1157 //print_r($diffResultSlugs);
1158 echo "<b>Slug processado excluido os Repetidos</b><br>";
1159 var_dump(count($resultSlug));
1160 //var_dump($resultSlug);
1161 //var_dump($diffResultSlugs);
1162
1163
1164 echo " <b>Diff dos Nomes(locais/remotos)</b><br>";
1165 $diffResultNames = array_diff($totalNames, $remoteName);
1166 var_dump(count($diffResultNames));
1167 //print_r($diffResultNames);
1168 echo "<b>Total de nomes que Batem</b><br>";
1169 var_dump(count($totalNames));
1170
1171 echo "<b>Total de nomes do Ws</b><br>";
1172 var_dump(count($remoteName));
1173
1174 echo "<b>Remote Info Produtcs{names}</b><br>";
1175 var_dump(count($rmNames));
1176 //print_r($rmNames);
1177
1178 echo "<b>Local Info Produtcs{names}</b><br>";
1179 var_dump(count($lcNames));
1180 //print_r($lcNames);
1181 //print_r($diffResultNames);
1182*/
1183 if(isset($deletedIds)){
1184 $productNameDelIds = [];
1185 foreach($deletedIds as $d => $pDelete){
1186 $product = wc_get_product($pDelete);
1187 $productNameDelIds[] = ['name'=>$product->get_name(), 'id'=>$product->get_id(), 'sku'=>$product->get_sku()];
1188 //echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDelete} | nome: {$productNameDelIds[$x]}]<br>";
1189 //wh_deleteProduct($pDelete);
1190 //$product = wc_get_product($pDelete);
1191 //$product->delete();
1192 //$result = 'trash' === $product->get_status();
1193 /*
1194 if (!$result)
1195 {
1196 //return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
1197 }
1198 $x++;*/
1199 }
1200 }
1201
1202 //var_dump($productNameDelIds);
1203
1204 //$u = 0;
1205 foreach($collection as $ck=>$coll){
1206 //stristr($string, 'earth') === FALSE
1207 foreach($productNameDelIds as $pk=>$pDeIds){
1208 //var_dump($pDeIds);
1209 if(is_string($pDeIds['name'])){
1210 $pname = explode(",", $pDeIds['name']);
1211 if(preg_match("/{$pname[0]}/i", $coll->produtoNome)){
1212 echo "Existe na base [{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']} | collection-k:{$ck} | <br>";
1213 //unset($pname[0]);
1214 unset($productNameDelIds[$pk]);
1215
1216 }else{
1217 if((count($collection)-1) == $ck){
1218 echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDeIds['id']} | nome: {$pname[0]}] collection-k:{$ck} <br>";
1219 //wh_deleteProduct($pDelete);
1220 $product = wc_get_product($pDeIds['id']);
1221 $product->delete();
1222 echo "Não Existe na base [{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']} | collection-k:{$ck} |<br>";
1223 }
1224 }
1225
1226 }
1227
1228 }
1229
1230 }
1231
1232
1233
1234
1235
1236
1237 //61
1238 //FavelaMigration::init($prodPosition=61);
1239 //186
1240 /*
1241 $bate = 0;
1242 foreach($collection as $k=> $coll){
1243
1244 //FavelaMigration::init($prodPosition=185);
1245 //echo "no loop: {$i}";
1246 //$productsOp[] = FavelaMigration::init($i);
1247
1248 $productTeste = $coll;
1249 $resultSearch = FavelaMigration::searchProduct($productTeste);
1250 if(empty($resultSearch)){
1251 echo "<h4>Produto não existe na base Local</h4>";
1252
1253 }else{
1254 $totalIds[] = $resultSearch->get_id();
1255 //echo "<h4>Produto existe na base Local</h2>";
1256 //var_dump($resultSearch);
1257 }
1258
1259 $produtoName = "{$coll->produtoNome}, {$coll->produtoMarca}";
1260
1261 foreach($totalIds as $t=>$tIds){
1262 if($localProducts[$t]->get_id() == $tIds){
1263 echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$k]->get_id()} ({$k}) Produto(Remoto)Nome:$produtoName [Bate com o WS (id:{$tIds})] Bate: [{$bate}]<br>";
1264 $bate++;
1265 //echo "(ids iguais) k: {$k} | t: [{$t}] : ids remoto: " . ($tIds) . " ids local: {$localProducts[$t]->get_id()} <br>";
1266 echo "(ids iguais)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
1267 //unset($lp);
1268 //$listVerify['produtoBate'] = $localProducts[$prodPosition];
1269 //$listNoExists = $lp;
1270 }else{
1271
1272 //echo "*Produto(Local) Nome:{$localProducts[$k]->get_name()}, id:{$localProducts[$i]->get_id()}[c:{$i}] ({$i}) Produto(Remoto)Nome:$produtoName [Não Bate com o WS (id:{$totalIds[0]})]<br>";
1273
1274 //unset($localProducts);
1275 echo "(ids diferentes)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
1276 }
1277 }
1278
1279 //echo "<h4>Total de produtos Locais</h4>";
1280
1281
1282 }*/
1283
1284 //print_r($listVerify);
1285 //print_r($totalIds);
1286
1287
1288 //return $listVerify;
1289
1290
1291
1292 //echo "<h4>Produtos Operacionais</h4>";
1293 //print_r($productsOp);
1294 //var_dump($productsOp["produtoBate"]);
1295}
1296
1297class MigrationRules {
1298
1299 private static $lproduct, $rproduct, $collection,
1300 $postId, $prodPosition, $productTeste, $remoteAttr;
1301
1302 private static $tamanhoUpdated = false;
1303 private static $isUpdated = false;
1304
1305 static function filterVariations($post_id,$meta_key,$meta_value) {
1306 $query = new \WP_Query( array(
1307 'post_parent' => $post_id,
1308 'post_status' => 'publish',
1309 'post_type' => 'product_variation',
1310 'posts_per_page' => -1,
1311 'meta_query' => array( array(
1312 'key' => $meta_key,
1313 'value' => $meta_value,
1314 ) ),
1315 ) );
1316 $result = array();
1317 if($query->have_posts()){
1318 while ($query->have_posts()) {
1319 $query->next_post();
1320 $result[] = $query->post;
1321 }
1322 wp_reset_postdata();
1323 }
1324 wp_reset_query();
1325
1326 return $result;
1327 }
1328/*
1329*
1330
1331**/
1332 static function _filterVariations($post_id,array $properties) {
1333 $query = new \WP_Query( array(
1334 'post_parent' => $post_id,
1335 'post_status' => 'publish',
1336 'post_type' => 'product_variation',
1337 'posts_per_page' => -1,
1338 'meta_query' => array(
1339 'relation' => 'AND',
1340 'cor_clause' => array(
1341 'key' => $properties['cor_key'],
1342 'value' => $properties['cor_value'],
1343 ),
1344 'tamanho_clause' => array(
1345 'key' => $properties['tamanho_key'],
1346 'value' => $properties['tamanho_value'],
1347 ),
1348 ),
1349 ) );
1350 $result = array();
1351 if($query->have_posts()){
1352 while ($query->have_posts()) {
1353 $query->next_post();
1354 $result[] = $query->post;
1355 }
1356 wp_reset_postdata();
1357 }
1358 wp_reset_query();
1359
1360 return $result;
1361 }
1362
1363 static function storeStock($listCorT, $x){
1364 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
1365
1366 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
1367 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
1368 } else{
1369 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
1370 }
1371 echo "Attr com problema<br>";
1372 var_dump($listCorT->produtoCor);
1373
1374 echo "{Cor:[{$listCorT->produtoCor}], Tamanho:[{$listCorT->produtoTamanho}] Será persistido} | (x:{$x},total:{$rtotal}) | <br>";
1375 $variation_data = [
1376 'attributes' => [
1377 'cor' => $listCorT->produtoCor,
1378 'tamanho' => $listCorT->produtoTamanho,
1379 ],
1380 'sku' => MigrationRules::getProductTeste()->produtoId,
1381 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1382 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1383 'stock_qty' => $_stockRemote
1384 ];
1385 // The function to be run
1386 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1387 }
1388
1389 static function updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts){
1390 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
1391 $totalL = self::getTotalLocalProducts();
1392 $diffProducts = $rtotal-$totalL;
1393
1394 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
1395 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
1396 } else{
1397 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
1398 }
1399
1400 $pcor = strtolower(tirarAcentos($listCorT->produtoCor));
1401 $acor = strtolower(tirarAcentos($attrCor));
1402
1403 $corFragment = explode(" ", $pcor);
1404
1405 if(isset($corFragment[0])){
1406 $pcor = $corFragment[0];
1407 }
1408
1409 if(isset($corFragment[1])){
1410 $pcor = $corFragment[0] . "-" . $corFragment[1];
1411 }
1412
1413
1414 $rTamanho = strtolower(tirarAcentos($listCorT->produtoTamanho));
1415 $atTamanho = strtolower(tirarAcentos($attrTamanho));
1416
1417 if($pcor == $acor){
1418 //atualiza
1419 echo "produtoCor:[{$pcor}] são iguais AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1420 //se o tamanho do produto for igual
1421 if($rTamanho == $attrTamanho){
1422 //atualiza
1423 echo "produtoTamanho:[{$rTamanho}] são iguais attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1424
1425 //se o estoque remoto for igual ao estoque local (Não atualiza)
1426 if($_stockRemote == $attrStock){
1427 //não atualiza
1428 echo "produtoQtdeEstoque:[{$_stockRemote}] são iguais{NÃO ATUALIZA} attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1429 echo "<hr><hr>";
1430 //self::$isUpdated = true;
1431 }
1432
1433 //se estoque remoto for maior que o estoque local (Atualiza)
1434 if($_stockRemote > $attrStock){
1435 //atualiza
1436 //var_dump(self::$isUpdated);
1437
1438 echo "condition:(<i>produto tem cor e tamanho iguais e estoque local menor do que o estoque remoto</i>:)
1439 ,<br> produtoQtdeEstoque(Remoto):[{$_stockRemote}] {ATUALIZA} -> attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} > {{$attrStock}}] <br>";
1440 $result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$rTamanho);
1441
1442 $variation_data = [
1443 'attributes' => [
1444 'cor' => $listCorT->produtoCor,
1445 'tamanho' => $listCorT->produtoTamanho,
1446 ],
1447 'ID' => $cproducts,
1448 'sku' => MigrationRules::getProductTeste()->produtoId,
1449 'update' => true,
1450 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1451 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1452 'stock_qty' => $_stockRemote
1453 ];
1454 // The function to be run
1455 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1456 //self::$isUpdated = true;
1457
1458
1459 }
1460 if($_stockRemote < $attrStock){//se for diferente, atualiza com base no valor do estoque remoto
1461 //atualiza
1462 echo "produtoQtdeEstoque(Remoto):[{$_stockRemote}] {Menor do que Estoque Local - Ação: Incrementa Sobre o Stock Local o Estoque Remoto} -> attrStock(Estoque Local):[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} < {{$attrStock}}] <br>";
1463 echo "<hr><hr>";
1464 $localStk = (int)get_post_meta($cproducts, '_stock', true );
1465 //var_dump($localStk);
1466
1467 $variation_data = [
1468 'attributes' => [
1469 'cor' => $listCorT->produtoCor,
1470 'tamanho' => $listCorT->produtoTamanho,
1471 ],
1472 'ID' => $cproducts,
1473 'sku' => MigrationRules::getProductTeste()->produtoId,
1474 'update' => true,
1475 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1476 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1477 'stock_qty' => $_stockRemote + $localStk
1478 ];
1479 // The function to be run
1480 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1481 //self::$isUpdated = true;
1482
1483 }
1484 }elseif(($totalL)-1 == $c && $totalL < $rtotal){//se tamanhos são diferentes
1485 // [se a quantidade de produtos com cores iguais e tamanhos diferentes
1486 // _remotos_ forem maior que a quantidade de produtos locais (insere ou atualiza)
1487 echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1488 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1489 ['cor_key'=>'attribute_pa_cor',
1490 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1491 ]);
1492
1493 //var_dump($result);
1494
1495 if(empty($result)){
1496 //var_dump($result);
1497 // The variation data
1498 echo "{Tamanho remoto não existe - Tamanho [{$rTamanho}] Será persistido} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1499 $variation_data = [
1500 'attributes' => [
1501 'cor' => $listCorT->produtoCor,
1502 'tamanho' => $listCorT->produtoTamanho,
1503 ],
1504 'sku' => MigrationRules::getProductTeste()->produtoId,
1505 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1506 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1507 'stock_qty' => $_stockRemote
1508 ];
1509 // The function to be run
1510 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1511 }
1512 else{
1513
1514 echo "{Tamanho remoto existe na base [{$rTamanho}] Não Será atualizada} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | {$result[0]->ID} | STock:{$_stockRemote}<br>";
1515 /*$variation_data = [
1516 'attributes' => [
1517 'cor' => $listCorT->produtoCor,
1518 'tamanho' => $listCorT->produtoTamanho,
1519 ],
1520 'ID' => $cproducts,
1521 'sku' => MigrationRules::getProductTeste()->produtoId,
1522 'update' => true,
1523 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1524 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1525 'stock_qty' => $_stockRemote
1526 ];
1527 */
1528 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1529
1530
1531 }
1532 }
1533 //se a quantidade do estoque for igual
1534 //var_dump(substr($listCorT->produtoQtdeEstoque,0,1));
1535
1536 }else{//atualiza $c (contador do loop das variacoes remotas)
1537 $totalL = self::getTotalLocalProducts();
1538 $diffProducts = $rtotal-$totalL;
1539 echo "#produtoCor:[{$pcor},{$rTamanho}] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total:{$rtotal}, diffP:{$diffProducts}) - variable_id:[$cproducts] | {Cor remota não existe em cores locais}<br>";
1540 //se total de variacoes locais é menor que o total de variacoes remotas
1541 //insere a variacao remota até a quantidade de variacoes locais ficar = a quantidade de variacoes
1542 //remotas
1543 //enquanto 29 <= 52 { execulta }
1544 // $c < $rtotal && $z <= $rtotal && { $z = $c; store(color); $z++;}
1545 //$z = $c;
1546 //30 == $c
1547 //se o contador de produtos locais ficar com o mesmo valor do total de produtos locais tornarem iguais
1548 //e a quantidade de produtos locais for menor que o total de produtos remotos persiste o produto remoto
1549 if(($totalL)-1 == $c && $totalL < $rtotal){
1550 //if($z <= $rtotal){
1551 //$pID = MigrationRules::getPostId();
1552 //$result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_cor',$pcor);
1553 //$resultT = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$listCorT->produtoTamanho);
1554 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1555 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1556 ['cor_key'=>'attribute_pa_cor',
1557 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1558 ]);
1559
1560 echo "-produtoCor:[{$pcor}|[$rTamanho]] são diferentes AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c}[Último Produto Local],total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor remota não existe em cores locais} |<br>";
1561
1562 //var_dump($result);
1563 if(empty($result)){
1564 //var_dump($result);
1565 // The variation data
1566 echo "{Cor remota não existe - Cor [{$pcor}] Será persistida} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1567 $variation_data = [
1568 'attributes' => [
1569 'cor' => $listCorT->produtoCor,
1570 'tamanho' => $listCorT->produtoTamanho,
1571 ],
1572 'sku' => MigrationRules::getProductTeste()->produtoId,
1573 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1574 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1575 'stock_qty' => $_stockRemote
1576 ];
1577 // The function to be run
1578 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1579 //$z++;
1580 }
1581 else{
1582 echo "*produtoCor:[{$pcor}|[$rTamanho]] existe como variacao local na base AttrCor:[{$acor},{$atTamanho}] (x:{$x}, c:{$c},total(R):{$rtotal},total(L):($totalL), diffP:{$diffProducts}) - variable_id:[$cproducts]|father:$pID | {Cor/Tamanho remota existe em cores/tamanhos locais(Operacão: Não atualiza)} |<br>";
1583 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1584 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1585 ['cor_key'=>'attribute_pa_cor',
1586 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1587 ]);
1588 //var_dump($result[0]->ID);
1589
1590 //if(empty($result)){
1591 //var_dump($result);
1592 // The variation data
1593 echo "{Variaçao de tamanho Existe para a cor:{$pcor} ->{Tamanho:{$listCorT->produtoTamanho}} - Variação de cor:[{$pcor}] Não Será Criada, pois já existe} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1594 $variation_data = [
1595 'attributes' => [
1596 'cor' => $listCorT->produtoCor,
1597 'tamanho' => $listCorT->produtoTamanho,
1598 ],
1599 'sku' => MigrationRules::getProductTeste()->produtoId,
1600 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1601 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1602 'stock_qty' => $_stockRemote
1603 ];
1604 // The function to be run
1605 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1606
1607 #
1608 //echo "{Cor remota existe - Cor [{$pcor}] Será Atualizada} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1609 /*
1610 $variation_data = [
1611 'attributes' => [
1612 'cor' => $listCorT->produtoCor,
1613 'tamanho' => $listCorT->produtoTamanho,
1614 ],
1615 'ID' => $cproducts,
1616 'sku' => MigrationRules::getProductTeste()->produtoId,
1617 'update' => true,
1618 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1619 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1620 'stock_qty' => $_stockRemote
1621 ];
1622 // The function to be run
1623 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1624 */
1625 }
1626
1627
1628 }else{
1629 //echo ">produtoCor:[{$pcor}] são diferentes AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts] | <br>";
1630 }
1631
1632 }
1633 //exit;
1634 }
1635
1636 static function setTotalLocalProducts($lproduct){
1637 self::$lproduct = $lproduct;
1638 }
1639
1640 static function setTotalRemoteProducts($rproduct){
1641 self::$rproduct = $rproduct;
1642 }
1643
1644
1645 static function getTotalLocalProducts(){
1646 return self::$lproduct;
1647 }
1648
1649 static function getTotalRemoteProducts(){
1650 return self::$rproduct;
1651 }
1652
1653 static function setCollection($collection){
1654 self::$collection = $collection;
1655 }
1656
1657 static function getCollection(){
1658 return self::$collection;
1659 }
1660
1661
1662 static function setPostId($postId){
1663 self::$postId = $postId;
1664 }
1665
1666 static function getPostId(){
1667 return self::$postId;
1668 }
1669
1670 static function setProdPosition($prodPosition){
1671 self::$prodPosition = $prodPosition;
1672 }
1673
1674 static function getProdPosition(){
1675 return self::$prodPosition;
1676 }
1677
1678 static function setProductTeste($productTeste){
1679 self::$productTeste = $productTeste;
1680 }
1681
1682 static function getProductTeste(){
1683 return self::$productTeste;
1684 }
1685
1686 static function setRemoteAttr($remoteAttr){
1687 self::$remoteAttr = $remoteAttr;
1688 }
1689
1690 static function getRemoteAttr(){
1691 return self::$remoteAttr;
1692 }
1693
1694}
1695
1696class FavelaMigration {
1697
1698 static function listAllVariableProducts($post_id){
1699 //cria uma instancia do produto
1700 $product = wc_get_product($post_id);
1701
1702 //pega todas as variacoes do produto (só os ids)
1703 if(!empty($product)){
1704 $current_products = $product->get_children();
1705 return(count($current_products));
1706 }
1707
1708 }
1709
1710 static function getAllVariableProduct($post_id){
1711 //cria uma instancia do produto
1712 $product = wc_get_product($post_id);
1713 if(!empty($product)){
1714 $current_products = $product->get_children();
1715 return $current_products;
1716 }
1717 }
1718
1719 static function getAllRemoteVariableProduct(stdClass $collection){
1720 return(count($collection->listaCorTamanho));
1721 }
1722
1723 static function getAllRemoteVariableProductNames(stdClass $collection){
1724 foreach($collection->listaCorTamanho as $k=>$coll){
1725 echo "{$coll->produtoCor},{$coll->produtoTamanho} -({$k})<br>";
1726 }
1727 }
1728
1729
1730 static function getAttributesForProduct(stdClass $product){
1731 foreach($product->listaCorTamanho as $p=>$prop){
1732 $cores[] = $prop->produtoCor;
1733 $tamanho[] = $prop->produtoTamanho;
1734 $stock[] = $prop->produtoQtdeEstoque;
1735 }
1736
1737 return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1738 }
1739
1740 static function _getAttributesForProduct(stdClass $product){
1741 //echo "<h1>Objeto Remoto como stdClass: </h1>";
1742 //var_dump($product->listaCorTamanho);
1743 $c = 0;
1744 foreach($product->listaCorTamanho as $p=>$prop){
1745 //$object = $object[$k];
1746 foreach($prop as $k=>$value){
1747 //$attributeMeta[] = $prop->$k;
1748 //$object[] = ["{$k}"=>[$prop->$k]];
1749 //echo "p:[{$p}] k:[{$k}] count:[{$c}] value:[{$value}]<br>";
1750 $attribute = substr($k,7);//produto{AttrName}elimina produto da str
1751 if("QtdeEstoque" != $attribute && "CorHex" != $attribute && "CorId" != $attribute){
1752 $object[$attribute][] = $product->listaCorTamanho[$p]->$k;
1753 }
1754
1755 }
1756 //echo "<h3>{$product->listaCorTamanho[$p]->$attribute} [{$attribute}]</h3>";
1757 $c++;
1758 }
1759
1760 //var_dump($object);
1761
1762 return $object;
1763 //return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1764 }
1765
1766 static function getAllAttributes($post_id){
1767 //exibe os atributos do produto
1768 $prodAttrGlobal = get_post_meta($post_id, '_product_attributes', true );
1769 echo "<h2>Atributos do produto</h2>";
1770 var_dump($prodAttrGlobal);
1771 }
1772
1773 static function getAllAttrForTaxonomy($tax,$post_id){
1774 echo "<h2>termos dos atributos dos produtos(pa_tamanho)tax:{$tax}| id:{$post_id}</h2>";
1775 $result = wc_get_product_terms($post_id, $tax, 'names');
1776 var_dump($result);
1777 }
1778
1779 static function updateVariableProduct(stdClass $productTeste, array $current_products){
1780 //counters
1781 MigrationRules::setTotalLocalProducts(count($current_products));
1782 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1783
1784 $x = 0; $c=0;
1785 //loop (produto remoto / produtos variavies)
1786 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1787 foreach($current_products as $c=>$cproducts){
1788 $attrCor = get_post_meta($cproducts, 'attribute_pa_cor', true );
1789 var_dump($attrCor);
1790 $attrTamanho = get_post_meta($cproducts, 'attribute_pa_tamanho', true );
1791 $attrStock = get_post_meta($cproducts, '_stock', true );
1792 //atualiza estoque
1793 MigrationRules::updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts);
1794 $x++;//no loop das variacoes locais ($current_products)
1795 }
1796 $c++;//no loop das variacoes remotas ($productTest)
1797 }
1798 }
1799
1800
1801 static function storeVariableProduct(stdClass $productTeste){
1802 //counters
1803 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1804 $c=0;
1805 //loop (produto remoto / produtos variavies)
1806 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1807 MigrationRules::storeStock($listCorT, $c);
1808 $c++;//no loop das variacoes remotas ($productTest)
1809 }
1810 }
1811
1812 static function searchProduct($productTeste){
1813 $result = get_wc_product_by_title($productTeste->produtoNome, $productTeste->produtoMarca);
1814 return $result;
1815 }
1816
1817 static function getAllLocalProducts(){
1818 // Get 10 most recent product IDs in date descending order.
1819 $query = new WC_Product_Query( array(
1820 'limit' => 209,
1821 'orderby' => 'date',
1822 'order' => 'ASC',
1823 ));
1824
1825 //echo "query aqui";
1826 //var_dump($query);
1827 $products = $query->get_products();
1828 //var_dump($products);
1829 return $products;
1830 }
1831
1832 static function init($prodPosition){
1833 //recebe uma coleção remota
1834 $collection = getProdutosForWikiWs();
1835 $productTeste = $collection[$prodPosition];
1836 //se colecao for vazia sai do funcao
1837 if(empty($productTeste)){
1838 return;
1839 }
1840
1841 //Busca com base no {titulo}, {nomeDaMarca} na base da loja
1842 //caso exista um produto local com o mesmo nome de um produto remoto.
1843 $resultSearch = self::searchProduct($productTeste);
1844
1845 if(empty($resultSearch)){
1846 echo "<h4>Produto não existe na base Local</h4>";
1847 $pRemotosQNaoExistemLocal[] = $productTeste->produtoNome;
1848 }else{
1849 $totalIds[] = $resultSearch->get_id();
1850 echo "<h4>Produto existe na base Local</h2>";
1851 //var_dump($resultSearch);
1852 }
1853
1854 $pRemotos = self::getAllRemoteVariableProduct($productTeste);
1855 echo "<h2>Total de produtos Variáveis Remotos: {updated}<i>[{$pRemotos}]</i></h2>";
1856 //todos os nomes das variáveis remotas
1857 self::getAllRemoteVariableProductNames($productTeste);
1858
1859 //busca os produtos locais baseados no sku = WebService.produtoTest.id
1860 $post_id = wc_get_product_id_by_sku($productTeste->produtoId);
1861
1862 //caso
1863 /*if(!empty($post_id)){
1864 update_post_meta($post_id, '_sku', $productTeste->produtoId, true);
1865 echo "<h2>SKU do produto Manipulado</h2><br>";
1866 var_dump($post_id);
1867 }*/
1868 //var_dump($produtoTeste);
1869 //pega os atributosdo produto remoto (taxonomias e termos)
1870 //$remoteAttributes = self::getAttributesForProduct($productTeste);
1871 $remoteAttributes = self::_getAttributesForProduct($productTeste);
1872 echo "<h1>Array de atributos remotos construido:</h1>";
1873 var_dump($remoteAttributes);
1874
1875 if($post_id != 0){
1876 update_product_variation( array(
1877 'ID' => $post_id,
1878 'author' => '', // optional
1879 'title' => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
1880 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1881 'excerpt' => $productTeste->produtoDescricao,
1882 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1883 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1884 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1885 'manager_stock' => '0',
1886 'category' => $productTeste->produtoCat,
1887 // Set a minimal stock quantity
1888 'image_id' => '', // optional
1889 'gallery_ids' => array(), // optional
1890 'sku' => $productTeste->produtoId, // optional
1891 'tax_class' => '', // optional
1892 'weight' => $productTeste->produtoPeso, // optional
1893 'width' => $productTeste->produtoDimensaoL,
1894 'length' => $productTeste->produtoDimensaoC,
1895 // For NEW attributes/values use NAMES (not slugs)
1896 'attributes' => [
1897 'Cor' => $remoteAttributes['Cor'],
1898 'Tamanho' => $remoteAttributes['Tamanho']
1899 ],
1900 ));
1901 }else{
1902 //var_dump($produtoTeste);
1903 $post_id = update_product_variation( array(
1904 'author' => '', // optional
1905 'title' => "{$productTeste->produtoNome}, {$productTeste->produtoMarca}",
1906 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1907 'excerpt' => $productTeste->produtoDescricao,
1908 'category' => $productTeste->produtoCat,
1909 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1910 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1911 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1912 'manager_stock' => '0',
1913 // Set a minimal stock quantity
1914 'image_id' => '', // optional
1915 'gallery_ids' => array(), // optional
1916 'sku' => $productTeste->produtoId, // optional
1917 'tax_class' => '', // optional
1918 'weight' => $productTeste->produtoPeso, // optional
1919 'width' => $productTeste->produtoDimensaoL,
1920 'length' => $productTeste->produtoDimensaoC,
1921 // For NEW attributes/values use NAMES (not slugs)
1922 'attributes' => ['Cor' => $remoteAttributes['Cor'],
1923 'Tamanho' => $remoteAttributes['Tamanho']]
1924 ) );
1925 }
1926 //exit;
1927
1928 //lista todos os produtos variáveis.
1929 echo "<h1>Total de Variações Locais</h1>";
1930 var_dump(self::listAllVariableProducts($post_id));
1931
1932 //exibe todos os attributos
1933 self::getAllAttributes($post_id);
1934
1935 //exibe todos os termos (por taxonomia)
1936 self::getAllAttrForTaxonomy($tax='pa_cor',$post_id);
1937
1938 //retorna um array contendo todos os ids de produtos variáveis
1939 $current_products = self::getAllVariableProduct($post_id);
1940 //atualiza a loja com base nas informacoes dos produtos variaveis do WS
1941 MigrationRules::setCollection($collection);
1942 MigrationRules::setPostId($post_id);
1943 MigrationRules::setProdPosition($prodPosition);
1944 MigrationRules::setProductTeste($productTeste);
1945 MigrationRules::setRemoteAttr($remoteAttributes);
1946
1947 //post_id, $collection, prodposition, productTeste, remoteAttr
1948 if(empty($current_products)){
1949 self::storeVariableProduct($productTeste);
1950 }
1951 else{
1952 self::updateVariableProduct($productTeste,$current_products);
1953 }
1954
1955
1956 }
1957}
1958
1959function createTerms($post_id, $attributes_data){
1960 if( sizeof($attributes_data) > 0 ){
1961 $attributes = array(); // Initializing
1962
1963 // Loop through defined attribute data
1964 foreach( $attributes_data as $key => $attribute_array ) {
1965 if( isset($attribute_array['name']) && isset($attribute_array['options']) ){
1966 // Clean attribute name to get the taxonomy
1967 $taxonomy = 'pa_' . wc_sanitize_taxonomy_name( $attribute_array['name'] );
1968
1969 $option_term_ids = array(); // Initializing
1970
1971 // Loop through defined attribute data options (terms values)
1972 foreach( $attribute_array['options'] as $option ){
1973 if( term_exists( $option, $taxonomy ) ){
1974 // Save the possible option value for the attribute which will be used for variation later
1975 wp_set_object_terms($post_id, $option, $taxonomy, true );
1976 // Get the term ID
1977 $option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1978 }else{
1979 //wp_set_object_terms($post_id, $option, $taxonomy, true );
1980 //$option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1981 //var_dump($option_term_ids);
1982 }
1983 }
1984 }
1985
1986 // Loop through defined attribute data
1987 $attributes[$taxonomy] = array(
1988 'name' => $taxonomy,
1989 'value' => $option_term_ids, // Need to be term IDs
1990 'position' => $key + 1,
1991 'is_visible' => $attribute_array['visible'],
1992 'is_variation' => $attribute_array['variation'],
1993 'is_taxonomy' => '1'
1994 );
1995 }
1996 // Save the meta entry for product attributes
1997 update_post_meta( $post_id, '_product_attributes', $attributes);
1998
1999 }
2000}
2001
2002function create_product_attribute( $label_name ){
2003 global $wpdb;
2004
2005 $slug = sanitize_title( $label_name );
2006
2007 if ( strlen( $slug ) >= 28 ) {
2008 return new WP_Error( 'invalid_product_attribute_slug_too_long', sprintf( __( 'Name "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
2009 } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
2010 return new WP_Error( 'invalid_product_attribute_slug_reserved_name', sprintf( __( 'Name "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
2011 } elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
2012 return new WP_Error( 'invalid_product_attribute_slug_already_exists', sprintf( __( 'Name "%s" is already in use. Change it, please.', 'woocommerce' ), $label_name ), array( 'status' => 400 ) );
2013 }
2014
2015 $data = array(
2016 'attribute_label' => $label_name,
2017 'attribute_name' => $slug,
2018 'attribute_type' => 'select',
2019 'attribute_orderby' => 'menu_order',
2020 'attribute_public' => 0, // Enable archives ==> true (or 1)
2021 );
2022
2023 $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );
2024
2025 if ( is_wp_error( $results ) ) {
2026 return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
2027 }
2028
2029 $id = $wpdb->insert_id;
2030
2031 do_action('woocommerce_attribute_added', $id, $data);
2032
2033 wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
2034
2035 delete_transient('wc_attribute_taxonomies');
2036}
2037
2038/**
2039 * Save a new product attribute from his name (slug).
2040 *
2041 * @since 3.0.0
2042 * @param string $name | The product attribute name (slug).
2043 * @param string $label | The product attribute label (name).
2044 */
2045function save_product_attribute_from_name( $name, $label='', $set=true ){
2046 if( ! function_exists ('get_attribute_id_from_name') ) return;
2047
2048 global $wpdb;
2049
2050 $label = $label == '' ? ucfirst($name) : $label;
2051 $attribute_id = get_attribute_id_from_name( $name );
2052
2053 if( empty($attribute_id) ){
2054 $attribute_id = NULL;
2055 } else {
2056 $set = false;
2057 }
2058 $args = array(
2059 'attribute_id' => $attribute_id,
2060 'attribute_name' => $name,
2061 'attribute_label' => $label,
2062 'attribute_type' => 'select',
2063 'attribute_orderby' => 'menu_order',
2064 'attribute_public' => 0,
2065 );
2066
2067 if( empty($attribute_id) ) {
2068 $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
2069 set_transient( 'wc_attribute_taxonomies', false );
2070 }
2071
2072 if( $set ){
2073 $attributes = wc_get_attribute_taxonomies();
2074 $args['attribute_id'] = get_attribute_id_from_name( $name );
2075 $attributes[] = (object) $args;
2076 //print_r($attributes);
2077 set_transient( 'wc_attribute_taxonomies', $attributes );
2078 } else {
2079 return;
2080 }
2081}
2082
2083/**
2084 * Get the product attribute ID from the name.
2085 *
2086 * @since 3.0.0
2087 * @param string $name | The name (slug).
2088 */
2089function get_attribute_id_from_name( $name ){
2090 global $wpdb;
2091 $attribute_id = $wpdb->get_col("SELECT attribute_id
2092 FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
2093 WHERE attribute_name LIKE '$name'");
2094 return reset($attribute_id);
2095}
2096
2097/**
2098 * Create a new variable product (with new attributes if they are).
2099 * (Needed functions:
2100 *
2101 * @since 3.0.0
2102 * @param array $data | The data to insert in the product.
2103 */
2104
2105function create_product_variation( $data ){
2106 if( ! function_exists ('save_product_attribute_from_name') ) return;
2107
2108 $postname = sanitize_title( $data['title'] );
2109 $author = empty( $data['author'] ) ? '1' : $data['author'];
2110
2111 $post_data = array(
2112 'post_author' => $author,
2113 'post_name' => $postname,
2114 'post_title' => $data['title'],
2115 'post_content' => $data['content'],
2116 'post_excerpt' => $data['excerpt'],
2117 'post_status' => 'publish',
2118 'ping_status' => 'closed',
2119 'post_type' => 'product_variation',
2120 'post_parent' => $data['parent_id'],
2121 'guid' => home_url( '/product/'.$postname.'/' ),
2122 );
2123
2124 // Creating the product (post data)
2125 //$product_id = wp_insert_post( );
2126 $result = wp_insert_post( $post_data );
2127
2128 if ( $result && ! is_wp_error( $result ) ) {
2129 $product_id = $result;
2130 // Do something else
2131 var_dump($result);
2132 echo "sucesso";
2133 }else{
2134 echo "erro ao gravar produto variavel";
2135 var_dump($result);
2136 }
2137 // Get an instance of the WC_Product_Variable object and save it
2138 $product = new WC_Product_Variation( $product_id );
2139
2140 ## ---------------------- Other optional data ---------------------- ##
2141 ## (see WC_Product and WC_Product_Variable setters methods)
2142
2143 // THE PRICES (No prices yet as we need to create product variations)
2144
2145 // IMAGES GALLERY
2146 // Prices
2147 if( empty( $data['sale_price'] ) ){
2148 $product->set_price( $data['regular_price'] );
2149 } else {
2150 $product->set_price($data['sale_price'] );
2151 $product->set_sale_price($data['sale_price'] );
2152 }
2153 $variation->set_regular_price($data['regular_price'] );
2154
2155 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
2156 $product->set_gallery_image_ids( $data['gallery_ids'] );
2157
2158 // SKU/*
2159// if( ! empty( $data['sku'] ) )
2160 // $product->set_sku( $data['sku'] );
2161
2162
2163 // STOCK (stock will be managed in variations)
2164 $product->set_stock_quantity($data['stock']); // Set a minimal stock quantity
2165 if($data['manager_stock'] == '0'){
2166 $product->set_manage_stock(false);
2167 }else{
2168 $product->set_manage_stock(true);
2169 }
2170
2171 $product->set_stock_status('');
2172
2173 // Tax class
2174 if( empty( $data['tax_class'] ) )
2175 $product->set_tax_class( $data['tax_class'] );
2176
2177 // WEIGHT
2178 if( ! empty($data['weight']) )
2179 $product->set_weight(''); // weight (reseting)
2180 else
2181 $product->set_weight($data['weight']);
2182
2183 $product->validate_props(); // Check validation
2184
2185 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
2186
2187 $product_attributes = array();
2188
2189 foreach( $data['attributes'] as $key => $terms ){
2190 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
2191 $attr_label = ucfirst($key); // attribute label name
2192 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
2193
2194 // NEW Attributes: Register and save them
2195 if( ! taxonomy_exists( $taxonomy ) )
2196
2197 var_dump(save_product_attribute_from_name( $attr_name, $attr_label ));
2198
2199 $product_attributes[$taxonomy] = array (
2200 'name' => $taxonomy,
2201 'value' => '',
2202 'position' => '',
2203 'is_visible' => 0,
2204 'is_variation' => 1,
2205 'is_taxonomy' => 1
2206 );
2207
2208 foreach( $terms as $value ){
2209 $term_name = ucfirst($value);
2210 $term_slug = sanitize_title($value);
2211
2212 // Check if the Term name exist and if not we create it.
2213 if( ! term_exists( $value, $taxonomy ) )
2214 wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
2215
2216 // Set attribute values
2217 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
2218 }
2219 }
2220 update_post_meta( $product_id, '_product_attributes', $product_attributes );
2221
2222 $product->save(); // Save the data
2223}
2224
2225function get_product_category($catname){
2226 if($catname == ''){
2227 $catname = "CAMISAS";
2228 }else{
2229 $catnamesub = $catname;
2230 $slug = $catnamesub;
2231 //var_dump($slug);
2232 $productCategory = get_term_by( 'name', $slug, 'product_cat' );
2233
2234 //echo "termo Id";
2235 //var_dump($productCategory->term_id);
2236 if($productCategory){
2237 $cat_id = get_term_by('id',$productCategory->term_id , 'product_cat' );
2238 }else{
2239 return false;
2240 }
2241 //$cat_id = get_category($productCategory->term_id);
2242 //echo "cat_id";
2243 //var_dump($cat_id);
2244 }
2245
2246 if(empty($cat_id)) {
2247 //echo "insere um termo se não existir a categoria<br>";
2248 //var_dump($cat_id);
2249 $arg = array( 'description' => $slug, 'parent' => 0 );
2250 $cat_id = wp_insert_term($slug, "product_cat", $arg);
2251 //echo "id inserido da categoria criada<br>";
2252 //var_dump($cat_id);
2253 return $cat_id['term_id'];
2254 }else{
2255 //var_dump("retornando resultado existindo uma categoria correspondente");
2256 return $cat_id->term_id;
2257 }
2258}
2259/**
2260 * Update a new variable product (with new attributes if they are).
2261 * (Needed functions:
2262 *
2263 * @since 3.0.0
2264 * @param array $data | The data to insert in the product.
2265 */
2266function update_product_variation($data){
2267 if( ! function_exists ('save_product_attribute_from_name') ) return;
2268
2269 $category_id = get_product_category($data['category']);
2270 $postname = sanitize_title( $data['title'] );
2271 $author = empty( $data['author'] ) ? '1' : $data['author'];
2272
2273 if(empty($data['excerpt'])){
2274 $data['excerpt'] = $postname;
2275 }
2276
2277
2278 if(empty($data['ID'])){
2279
2280 $post_data = array(
2281 'post_author' => $author,
2282 'post_name' => $postname,
2283 'post_title' => $data['title'],
2284 'post_content' => $data['content'],
2285 'post_excerpt' => $data['excerpt'],
2286 'post_status' => 'publish',
2287 'ping_status' => 'closed',
2288 'post_type' => 'product',
2289 'guid' => home_url( '/product/'.$postname.'/') ,
2290 'tax_input' => ['product_cat' => $category_id]
2291 );
2292
2293 $product_id = wp_insert_post( $post_data );
2294 //wp_set_post_terms($product_id, get_term()->slug,'product_cat',true);
2295 }else{
2296
2297 if(!isset($data['insert_variable_product_unique'])){
2298 $post_data = array(
2299 'ID' => $data['ID'],
2300 'post_author' => $author,
2301 'post_name' => $postname,
2302 'post_title' => $data['title'],
2303 'post_content' => $data['content'],
2304 'post_excerpt' => $data['excerpt'],
2305 'post_status' => 'publish',
2306 'ping_status' => 'closed',
2307 'post_type' => 'product',
2308 'guid' => home_url( '/product/'.$postname.'/' ),
2309 'tax_input' => ['product_cat'=>$category_id]
2310 );
2311 $product_id = wp_update_post( $post_data );
2312 }
2313
2314 }
2315
2316 $product = new WC_Product_Variable( $product_id );
2317 $product->save();
2318
2319 ## ---------------------- Other optional data ---------------------- ##
2320 ## (see WC_Product and WC_Product_Variable setters methods)
2321
2322 //THE PRICES (No prices yet as we need to create product variations)
2323 //IMAGES GALLERY
2324 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
2325 $product->set_gallery_image_ids( $data['gallery_ids'] );
2326
2327 //SKU
2328 if( ! empty( $data['sku'] ) )
2329 $product->set_sku( $data['sku'] );
2330
2331 // STOCK (stock will be managed in variations)
2332 $product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
2333 if($data['manager_stock'] == '0'){
2334 $product->set_manage_stock(false);
2335 }else{
2336 $product->set_manage_stock(true);
2337 }
2338
2339 $product->set_stock_status('');
2340
2341 // Tax class
2342 if( empty( $data['tax_class'] ) )
2343 $product->set_tax_class( $data['tax_class'] );
2344
2345 // WEIGHT
2346 if( ! empty($data['weight']) )
2347 $product->set_weight(''); // weight (reseting)
2348 else
2349 $product->set_weight($data['weight']);
2350
2351 //length
2352 if( ! empty($data['length']) )
2353 $product->set_length(''); // length (reseting)
2354 else
2355 $product->set_length($data['length']);
2356
2357 $product->validate_props(); // Check validation
2358
2359 //WIDTH
2360 if( ! empty($data['width']) )
2361 $product->set_width(""); // weight (reseting)
2362else
2363 $product->set_width($data['width']);
2364
2365 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
2366
2367 $product_attributes = array();
2368 echo "Atributes da persistência do Objeto (não da variação)";
2369 var_dump($data['attributes']);
2370
2371 foreach( $data['attributes'] as $key => $terms ){
2372 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
2373 $attr_label = ucfirst($key); // attribute label name
2374 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
2375
2376 // NEW Attributes: Register and save them
2377 if( ! taxonomy_exists( $taxonomy ) )
2378 echo "salvando taxonomia: {$attr_name}, {$attr_label} <br>";
2379 var_dump(save_product_attribute_from_name( $attr_name, $attr_label ));
2380 //$slug = 'pa_' . strtolower($attribute->name);
2381 $attribute_id = wc_create_attribute( array(
2382 'name' => $taxonomy,
2383 'slug' => $attr_name,
2384 'type' => 'product',
2385 'order_by' => 'menu_order',
2386 'has_archives' => false,
2387 ) );
2388
2389 var_dump($attribute_id);
2390 //Register it as a wordpress taxonomy for just this session. Later on this will be loaded from the woocommerce taxonomy table.
2391 /*register_taxonomy(
2392 $taxonomy,
2393 apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy, array( 'product' ) ),
2394 apply_filters( 'woocommerce_taxonomy_args_' . $taxonomy, array(
2395 'labels' => array(
2396 'name' => $attr_label,
2397 ),
2398 'hierarchical' => true,
2399 'show_ui' => false,
2400 'query_var' => true,
2401 'rewrite' => false,
2402 ) )
2403 );*/
2404
2405
2406 $product_attributes[$taxonomy] = array (
2407 'name' => $taxonomy,
2408 'value' => '',
2409 'position' => '',
2410 'is_visible' => 0,
2411 'is_variation' => 1,
2412 'is_taxonomy' => 1
2413 );
2414
2415 foreach( $terms as $value ){
2416 $term_name = ucfirst($value);
2417 $term_slug = sanitize_title($value);
2418
2419 // Check if the Term name exist and if not we create it.
2420 if( ! term_exists( $value, $taxonomy ) )
2421 echo "salvando termo: term_name:{$term_name} | tax:{$taxonomy} | slug:{$term_slug}<br>";
2422 var_dump(wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) )); // Create the term
2423
2424 // Set attribute values
2425 if(isset($data['insert_variable_product_unique'])){
2426 echo "setando valores dos atributos: id:{$data['ID']}(atualizando), tax:{$taxonomy}, term_name:{$term_name}<br>";
2427 var_dump(wp_set_post_terms( $data['ID'], $term_name, $taxonomy, true ));
2428 }else{
2429 echo "setando valores dos atributos: id:{$product_id}(inserindo), tax:{$taxonomy}, term_name:{$term_name}<br>";
2430 var_dump(wp_set_post_terms( $product_id, $term_name, $taxonomy, true ));
2431 }
2432
2433 }
2434 }
2435 //print_r($product);
2436 if(isset($data['insert_variable_product_unique'])){
2437 echo "atualizando: product Attrb: {$product_attributes}<br>";
2438 update_post_meta( $data['ID'], '_product_attributes', $product_attributes );
2439 }else{
2440 echo "inserindo: product Attrb:<br>";
2441 var_dump($product_attributes);
2442 update_post_meta( $product_id, '_product_attributes', $product_attributes );
2443 }
2444 //var_dump($product);
2445 //exit;
2446 $product->save(); // Save the data
2447 return $product_id;
2448}
2449/*
2450*
2451$parent_id = 746; // Or get the variable product id dynamically
2452
2453// The variation data
2454$variation_data = array(
2455 'attributes' => array(
2456 'size' => 'M',
2457 'color' => 'Green',
2458 ),
2459 'sku' => '',
2460 'regular_price' => '22.00',
2461 'sale_price' => '',
2462 'stock_qty' => 10,
2463);
2464
2465// The function to be run
2466create_product_variation( $parent_id, $variation_data );
2467*/
2468/**
2469 * Create a product variation for a defined variable product ID.
2470 *
2471 * @since 3.0.0
2472 * @param int $product_id | Post ID of the product parent variable product.
2473 * @param array $variation_data | The data to insert in the product.
2474 */
2475
2476function _create_product_variation( $product_id, $variation_data ){
2477 // Get the Variable product object (parent)
2478 $product = wc_get_product($product_id);
2479
2480 // Creating the product variation
2481 if(empty($variation_data['update'])){
2482 //var_dump($variation_data);
2483 $variation_post = array(
2484 'post_title' => MigrationRules::getProductTeste()->produtoNome,
2485 'post_name' => 'product-'. MigrationRules::getPostId() .'-variation',
2486 'post_status' => 'publish',
2487 'post_parent' => MigrationRules::getPostId(),
2488 'post_type' => 'product_variation',
2489 'guid' => site_url() . "/" . MigrationRules::getPostId()
2490 );
2491
2492 $variation_id = wp_insert_post( $variation_post );
2493 }else{
2494
2495 $variation_post = array(
2496 'ID' => $variation_data['ID'],
2497 'post_title' => $product->get_name(),
2498 'post_name' => 'product-'.$product_id.'-variation',
2499 'post_status' => 'publish',
2500 'post_parent' => $product_id,
2501 'post_type' => 'product_variation',
2502 'guid' => $product->get_permalink()
2503 );
2504
2505 $variation_id = wp_update_post( $variation_post );
2506 }
2507
2508
2509
2510 // Get an instance of the WC_Product_Variation object
2511 $variation = new WC_Product_Variation( $variation_id );
2512 //var_dump($variation_id);
2513 //exit;
2514 echo "Registrando taxonomia<br>";
2515 var_dump($variation_data['attributes']);
2516
2517 foreach ($variation_data['attributes'] as $attribute => $term_name )
2518 {
2519
2520 $taxonomy = 'pa_'.$attribute; // The attribute taxonomy
2521
2522 echo "taxonomia problemática: {$taxonomy}<br>";
2523
2524 // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
2525 if( ! taxonomy_exists( $taxonomy ) ){
2526 echo "Registrando taxonomia : {$attribute}<br>";
2527 register_taxonomy(
2528 $taxonomy,
2529 'product_variation',
2530 array(
2531 'hierarchical' => false,
2532 'label' => ucfirst( $attribute ),
2533 'query_var' => true,
2534 'rewrite' => array( 'slug' => sanitize_title($attribute) ), // The base slug
2535 )
2536 );
2537 }
2538
2539 $ntax = ucfirst( $attribute );
2540 echo "taxonomia com ucfirst: {$ntax}<br>";
2541 echo "nome do termo";
2542 var_dump($term_name);
2543
2544 // Check if the Term name exist and if not we create it.
2545 if( ! term_exists( $term_name, $taxonomy ) )
2546 echo "TERMO INSERIDO {$term_name}<br> ";
2547 var_dump(wp_insert_term( $term_name, $taxonomy )); // Create the term
2548
2549 $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug
2550
2551 // Get the post Terms names from the parent variable product.
2552 $post_term_names = wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
2553
2554 // Check if the post term exist and if not we set it in the parent variable product.
2555 if( ! in_array( $term_name, $post_term_names ) )
2556 echo "wp_set_post_terms: nome do slug {$term_slug} | productId:{$product_id} | term_name:{$term_name} | tax:{$taxonomy}<br>";
2557 var_dump(wp_set_post_terms( $product_id, $term_name, $taxonomy, true ));
2558
2559 //var_dump($term_slug);
2560 // Set/save the attribute data in the product variation
2561 echo "update_post_meta: variation_id: [{$variation_id}] - " . 'attribute_'.$taxonomy . "<br>";
2562 var_dump(update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug, true));
2563 }
2564
2565 ## Set/save all other data
2566
2567
2568 // SKU
2569 //if( ! empty( $variation_data['sku'] ) )
2570 // $variation->set_sku( $variation_data['sku'] );
2571
2572 // Prices
2573
2574 if( empty( $variation_data['sale_price'] ) ){
2575
2576 $variation->set_price( $variation_data['regular_price'] );
2577 } else {
2578
2579 $variation->set_price( $variation_data['sale_price'] );
2580 $variation->set_sale_price( $variation_data['sale_price'] );
2581 }
2582 $variation->set_regular_price( $variation_data['regular_price'] );
2583
2584 // Stock
2585 var_dump($variation_data['stock_qty']);
2586 if( ! empty($variation_data['stock_qty']) ){
2587 $variation->set_stock_quantity( $variation_data['stock_qty'] );
2588 $variation->set_manage_stock(true);
2589 $variation->set_stock_status('');
2590 } else {
2591 //$variation->set_manage_stock(true);
2592 $variation->set_manage_stock(false);
2593 $variation->set_stock_status('outofstock');
2594 }
2595
2596 if($variation_data['stock_qty'] == 0){
2597 $variation->set_manage_stock(false);
2598 $variation->set_stock_status('outofstock');
2599 }
2600 $variation->set_weight(''); // weight (reseting)
2601 //var_dump( $variation_data['ID']);
2602 $variation->save(); // Save the data
2603 //var_dump($variation->get_stock_quantity());
2604 //exit;
2605}
2606
2607function tirarAcentos($string){
2608 return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$string);
2609}
2610
2611/**
2612 * Method to delete Woo Product
2613 *
2614 * @param int $id the product ID.
2615 * @param bool $force true to permanently delete product, false to move to trash.
2616 * @return \WP_Error|boolean
2617 */
2618function wh_deleteProduct($id, $force = FALSE)
2619{
2620 $product = wc_get_product($id);
2621
2622 if(empty($product))
2623 return new WP_Error(999, sprintf(__('No %s is associated with #%d', 'woocommerce'), 'product', $id));
2624
2625 // If we're forcing, then delete permanently.
2626 if ($force)
2627 {
2628 if ($product->is_type('variable'))
2629 {
2630 foreach ($product->get_children() as $child_id)
2631 {
2632 $child = wc_get_product($child_id);
2633 $child->delete(true);
2634 }
2635 }
2636 elseif ($product->is_type('grouped'))
2637 {
2638 foreach ($product->get_children() as $child_id)
2639 {
2640 $child = wc_get_product($child_id);
2641 $child->set_parent_id(0);
2642 $child->save();
2643 }
2644 }
2645
2646 $product->delete(true);
2647 $result = $product->get_id() > 0 ? false : true;
2648 }
2649 else
2650 {
2651 $product->delete();
2652 $result = 'trash' === $product->get_status();
2653 }
2654
2655 if (!$result)
2656 {
2657 return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
2658 }
2659
2660 // Delete parent product transients.
2661 if ($parent_id = wp_get_post_parent_id($id))
2662 {
2663 wc_delete_product_transients($parent_id);
2664 }
2665 return true;
2666}
2667
2668/**
2669 * Add a widget to the dashboard.
2670 *
2671 * This function is hooked into the 'wp_dashboard_setup' action below.
2672 */
2673function wporg_add_dashboard_widgets() {
2674 wp_add_dashboard_widget(
2675 'wporg_dashboard_widget', // Widget slug.
2676 esc_html__( 'Wiki Importer', 'wporg' ), // Title.
2677 'wporg_dashboard_widget_render' // Display function.
2678 );
2679}
2680add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );
2681
2682/**
2683 * Create the function to output the content of our Dashboard Widget.
2684 */
2685function wporg_dashboard_widget_render() {
2686 // Display whatever you want to show.
2687
2688 $html = '<h2>Clique <span style="color:#0099FF" id="importData"><b>aqui</b></span> para importar Dados do ERP Wiki</h2>
2689 <p id="link_produtos">Visualizar Produtos -> <a href="edit.php?post_type=product">aqui</a> </p>
2690 <div id="importBlock">
2691 <img id="importLogo" width="450" height="368" src="https://lindabrand.com.br/wp-content/uploads/importLogo.png"/>
2692 </div>';
2693
2694 $html .= '<script>
2695 jQuery("#link_produtos").hide();
2696 jQuery("#importData").click(function(){
2697
2698 jQuery.ajax({
2699 type: "GET",
2700 url: "admin.php?action=executeWikiImport",
2701 beforeSend: function(){
2702 jQuery("#importLogo").hide();
2703 var img = jQuery("<img />", {
2704 id: "importGif",
2705 src: "https://lindabrand.com.br/wp-content/uploads/import.gif",
2706 width: "420px",
2707 height: "368",
2708 alt: "import"
2709 });
2710
2711 img.appendTo(jQuery("#importBlock"));
2712 },
2713 success: function(){
2714 alert("Dados Importados com sucesso");
2715 jQuery("#importGif").hide();
2716 jQuery("#importLogo").show();
2717 jQuery("#link_produtos").show();
2718 }
2719 });
2720 });
2721
2722 </script>';
2723
2724 echo $html;
2725}
2726
2727
2728
2729//add_action( 'importInitializer', 'executeWikiImport', 10,0);
2730//add_action("after_setup_theme",function(){
2731// do_action('importInitializer');
2732//});
2733
2734
2735add_action( 'admin_init', 'executeWikiImport' );
2736function executeWikiImport(){
2737 if(isset($_GET['action']) && $_GET['action']=="executeWikiImport"){
2738 initMigration();
2739 //initMigration();
2740 //create curl resource
2741 //$ch = curl_init();
2742 //curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2743 //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2744 //$output = curl_exec($ch);
2745 //curl_close($ch);
2746 }
2747}
2748
2749
2750add_action( 'woocommerce_thankyou', 'MyPersistRemoteObject3', 20, 2 );
2751function MyPersistRemoteObject3($order_id){
2752
2753 $ch = curl_init();
2754 curl_setopt_array($ch, array(
2755 CURLOPT_URL => "https://lindabrand.com.br/wp-json/wc/v3/orders/" . $order_id . "/?consumer_key=ck_9e747cfe973b52e14180a7c0c84aac41c8e960ec&consumer_secret=cs_225e4823dd0664b95f6030600dfebf8209ded416",
2756 CURLOPT_RETURNTRANSFER => true,
2757 CURLOPT_ENCODING => "",
2758 CURLOPT_MAXREDIRS => 10,
2759 CURLOPT_TIMEOUT => 30,
2760 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2761 CURLOPT_CUSTOMREQUEST => "GET",
2762 CURLOPT_SSL_VERIFYPEER=> false,
2763
2764 CURLOPT_HTTPHEADER => array(
2765 "Authorization: Basic *****************",
2766 "Cache-Control: no-cache"
2767 ),
2768 ));
2769
2770 $result = curl_exec($ch);
2771
2772 $result = curl_exec($ch);
2773
2774 $jsonResult = json_decode($result);
2775 foreach($jsonResult->meta_data as $k=>$meta){
2776 if($meta->key == "Tipo de pagamento" && $meta->value == "Boleto"){
2777 $bolVencimento = new stdClass;
2778 $bolVencimento->key = "Boleto Vencimento";
2779 $order = new WC_Order($order_id);
2780 $order_date = $order->order_date;
2781 $date = new DateTime($order_date);
2782 $date->modify("+3 day");
2783 $bolVencimento->value = $date->format("d-m-Y");
2784 $jsonResult->meta_data[] = $bolVencimento;
2785 }
2786 }
2787
2788 $replaced_result = substr_replace(json_encode($jsonResult), '"empresa":460, "guid":"9351c4b5-8c8a-4657-8244-56cb46e5e5d8",', 12,0);
2789
2790 //print_r($replaced_result);
2791 //echo " ";
2792 //print_r(base64_encode($replaced_result));
2793/* $opts = [
2794 'http' => [
2795 'method' => 'GET'
2796 ]
2797 ];*/
2798
2799 //$context = stream_context_create($opts);
2800 //$result = file_get_contents('http://app.wikisistemas.com.br:8086/EcommerceExternoWebservice.asmx/RecebePedidoWooCommerce?json=' . base64_encode($replaced_result), false, $context);
2801 //var_dump($result);
2802
2803 //
2804 //print_r($replaced_result);
2805 $ch2 = curl_init();
2806 curl_setopt_array($ch2, array(
2807 CURLOPT_URL => 'http://52.6.107.225/script.php?pedido=' . base64_encode($replaced_result),
2808 CURLOPT_RETURNTRANSFER => true,
2809 CURLOPT_ENCODING => "",
2810 CURLOPT_MAXREDIRS => 10,
2811 CURLOPT_TIMEOUT => 30,
2812 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2813 CURLOPT_CUSTOMREQUEST => "GET",
2814 CURLOPT_SSL_VERIFYPEER=> false,
2815
2816 CURLOPT_HTTPHEADER => array(
2817 "Authorization: Basic *****************",
2818 "Cache-Control: no-cache"
2819 ),
2820 ));
2821
2822 $result2 = curl_exec($ch2);
2823 //echo "retorno do WS<br>";
2824 //var_dump($result2);
2825
2826 //echo "pedido base64<br>";
2827 //var_dump($replaced_result);
2828
2829
2830 }
2831
2832
2833 add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
2834function grey_out_variations_when_out_of_stock( $grey_out, $variation ){
2835if ( ! $variation->is_in_stock() ){
2836 return false;
2837 }else{
2838 return true;
2839 }
2840}
2841
2842