· 4 years ago · Apr 06, 2021, 09:34 PM
1<?php
2set_time_limit(120);
3include "json.php";
4ini_set('memory_limit', '1500M');
5
6/**
7 *
8 * The framework's functions and definitions
9 *
10 */
11
12/**
13 * ------------------------------------------------------------------------------------------------
14 * Define constants.
15 * ------------------------------------------------------------------------------------------------
16 */
17define( 'WOODMART_THEME_DIR', get_template_directory_uri() );
18define( 'WOODMART_THEMEROOT', get_template_directory() );
19define( 'WOODMART_IMAGES', WOODMART_THEME_DIR . '/images' );
20define( 'WOODMART_SCRIPTS', WOODMART_THEME_DIR . '/js' );
21define( 'WOODMART_STYLES', WOODMART_THEME_DIR . '/css' );
22define( 'WOODMART_FRAMEWORK', '/inc' );
23define( 'WOODMART_DUMMY', WOODMART_THEME_DIR . '/inc/dummy-content' );
24define( 'WOODMART_CLASSES', WOODMART_THEMEROOT . '/inc/classes' );
25define( 'WOODMART_CONFIGS', WOODMART_THEMEROOT . '/inc/configs' );
26define( 'WOODMART_HEADER_BUILDER', WOODMART_THEME_DIR . '/inc/header-builder' );
27define( 'WOODMART_ASSETS', WOODMART_THEME_DIR . '/inc/admin/assets' );
28define( 'WOODMART_ASSETS_IMAGES', WOODMART_ASSETS . '/images' );
29define( 'WOODMART_API_URL', 'https://xtemos.com/licenses/api/' );
30define( 'WOODMART_DEMO_URL', 'https://woodmart.xtemos.com/' );
31define( 'WOODMART_PLUGINS_URL', WOODMART_DEMO_URL . 'plugins/');
32define( 'WOODMART_DUMMY_URL', WOODMART_DEMO_URL . 'dummy-content/');
33define( 'WOODMART_SLUG', 'woodmart' );
34define( 'WOODMART_CORE_VERSION', '1.0.18' );
35
36
37/**
38 * ------------------------------------------------------------------------------------------------
39 * Load all CORE Classes and files
40 * ------------------------------------------------------------------------------------------------
41 */
42
43if( ! function_exists( 'woodmart_autoload' ) ) {
44 function woodmart_autoload($className) {
45 $className = ltrim($className, '\\');
46 $fileName = '';
47 $namespace = '';
48 if ($lastNsPos = strripos($className, '\\')) {
49 $namespace = substr($className, 0, $lastNsPos);
50 $className = substr($className, $lastNsPos + 1);
51 $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
52 }
53 $className = str_replace('WOODMART_', '', $className);
54 $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
55 $fileName = WOODMART_CLASSES . DIRECTORY_SEPARATOR . $fileName;
56 if( file_exists( $fileName )) {
57 require $fileName;
58 }
59 }
60
61 spl_autoload_register('woodmart_autoload');
62}
63
64$woodmart_theme = new WOODMART_Theme();
65
66/**
67 * ------------------------------------------------------------------------------------------------
68 * Enqueue styles
69 * ------------------------------------------------------------------------------------------------
70 */
71if( ! function_exists( 'woodmart_enqueue_styles' ) ) {
72 add_action( 'wp_enqueue_scripts', 'woodmart_enqueue_styles', 10000 );
73
74 function woodmart_enqueue_styles() {
75 $version = woodmart_get_theme_info( 'Version' );
76 $minified = woodmart_get_opt( 'minified_css' ) ? '.min' : '';
77 $is_rtl = is_rtl() ? '-rtl' : '';
78 $style_url = WOODMART_THEME_DIR . '/style' . $minified . '.css';
79 if ( woodmart_woocommerce_installed() && is_rtl() ) {
80 $style_url = WOODMART_STYLES . '/style-rtl' . $minified . '.css';
81 } elseif ( ! woodmart_woocommerce_installed() ) {
82 $style_url = WOODMART_STYLES . '/base' . $is_rtl . $minified . '.css';
83 }
84
85 // Custom CSS generated from the dashboard
86
87 $file = get_option('woodmart-generated-css-file');
88 if( ! empty( $file ) && ! empty( $file['url'] ) ) {
89 $style_url = $file['url'];
90 }
91
92 wp_deregister_style( 'dokan-fontawesome' );
93 wp_dequeue_style( 'dokan-fontawesome' );
94
95 wp_deregister_style( 'font-awesome' );
96 wp_dequeue_style( 'font-awesome' );
97
98 wp_dequeue_style( 'vc_pageable_owl-carousel-css' );
99 wp_dequeue_style( 'vc_pageable_owl-carousel-css-theme' );
100
101 if ( ! woodmart_get_opt( 'disable_font_awesome_theme_css' ) ) {
102 wp_enqueue_style('font-awesome-css', WOODMART_STYLES . '/font-awesome.min.css', array(), $version);
103 }
104
105 wp_enqueue_style( 'bootstrap', WOODMART_STYLES . '/bootstrap.min.css', array(), $version );
106 wp_enqueue_style( 'woodmart-style', $style_url, array( 'bootstrap' ), $version );
107
108 wp_enqueue_style( 'js_composer_front', false, array(), $version );
109
110 // load typekit fonts
111 $typekit_id = woodmart_get_opt( 'typekit_id' );
112
113 if ( $typekit_id ) {
114 wp_enqueue_style( 'woodmart-typekit', 'https://use.typekit.net/' . esc_attr ( $typekit_id ) . '.css', array(), $version );
115 }
116
117 remove_action('wp_head', 'print_emoji_detection_script', 7);
118 remove_action('wp_print_styles', 'print_emoji_styles');
119
120 wp_register_style( 'woodmart-inline-css', false );
121 }
122}
123
124/**
125 * ------------------------------------------------------------------------------------------------
126 * Enqueue scripts
127 * ------------------------------------------------------------------------------------------------
128 */
129
130if( ! function_exists( 'woodmart_enqueue_scripts' ) ) {
131 add_action( 'wp_enqueue_scripts', 'woodmart_enqueue_scripts', 10000 );
132
133 function woodmart_enqueue_scripts() {
134
135 $version = woodmart_get_theme_info( 'Version' );
136 /*
137 * Adds JavaScript to pages with the comment form to support
138 * sites with threaded comments (when in use).
139 */
140 if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
141 wp_enqueue_script( 'comment-reply', false, array(), $version );
142 }
143 if( ! woodmart_woocommerce_installed() ) {
144 wp_register_script( 'js-cookie', woodmart_get_script_url( 'js.cookie' ), array( 'jquery' ), $version, true );
145 }
146
147 wp_dequeue_script( 'flexslider' );
148 wp_dequeue_script( 'photoswipe-ui-default' );
149 wp_dequeue_script( 'prettyPhoto-init' );
150 wp_dequeue_script( 'prettyPhoto' );
151 wp_dequeue_style( 'photoswipe-default-skin' );
152 if( woodmart_get_opt( 'image_action' ) != 'zoom' ) {
153 wp_dequeue_script( 'zoom' );
154 }
155
156 wp_enqueue_script( 'wpb_composer_front_js', false, array(), $version );
157 wp_enqueue_script( 'imagesloaded', false, array(), $version );
158
159 if( woodmart_get_opt( 'combined_js' ) ) {
160 wp_enqueue_script( 'isotope', woodmart_get_script_url( 'isotope.pkgd' ), array(), $version, true );
161 wp_enqueue_script( 'woodmart-theme', WOODMART_SCRIPTS . '/theme.min.js', array( 'jquery', 'js-cookie' ), $version, true );
162 } else {
163 wp_enqueue_script( 'woodmart-owl-carousel', woodmart_get_script_url( 'owl.carousel' ), array(), $version, true );
164 wp_enqueue_script( 'woodmart-tooltips', woodmart_get_script_url( 'jquery.tooltips' ), array(), $version, true );
165 wp_enqueue_script( 'woodmart-magnific-popup', woodmart_get_script_url( 'jquery.magnific-popup' ), array(), $version, true );
166 wp_enqueue_script( 'woodmart-device', woodmart_get_script_url( 'device' ), array( 'jquery' ), $version, true );
167 wp_enqueue_script( 'woodmart-waypoints', woodmart_get_script_url( 'waypoints' ), array( 'jquery' ), $version, true );
168
169 if ( woodmart_get_opt( 'disable_nanoscroller' ) != 'disable' ) {
170 wp_enqueue_script( 'woodmart-nanoscroller', woodmart_get_script_url( 'jquery.nanoscroller' ), array(), $version, true );
171 }
172
173 $minified = woodmart_get_opt( 'minified_js' ) ? '.min' : '';
174 $base = ! woodmart_woocommerce_installed() ? '-base' : '';
175 wp_enqueue_script( 'woodmart-theme', WOODMART_SCRIPTS . '/functions' . $base . $minified . '.js', array( 'js-cookie' ), $version, true );
176 if ( woodmart_get_opt( 'ajax_shop' ) && woodmart_woocommerce_installed() && ( is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy() ) ) {
177 wp_enqueue_script( 'woodmart-pjax', woodmart_get_script_url( 'jquery.pjax' ), array(), $version, true );
178 }
179 }
180 wp_add_inline_script( 'woodmart-theme', woodmart_settings_js(), 'after' );
181
182 wp_register_script( 'woodmart-panr-parallax', woodmart_get_script_url( 'panr-parallax' ), array(), $version, true );
183 wp_register_script( 'woodmart-photoswipe', woodmart_get_script_url( 'photoswipe-bundle' ), array(), $version, true );
184 wp_register_script( 'woodmart-slick', woodmart_get_script_url( 'slick' ), array(), $version, true );
185 wp_register_script( 'woodmart-countdown', woodmart_get_script_url( 'countdown' ), array(), $version, true );
186 wp_register_script( 'woodmart-packery-mode', woodmart_get_script_url( 'packery-mode.pkgd' ), array(), $version, true );
187 wp_register_script( 'woodmart-vivus', woodmart_get_script_url( 'vivus' ), array(), $version, true );
188 wp_register_script( 'woodmart-threesixty', woodmart_get_script_url( 'threesixty' ), array(), $version, true );
189 wp_register_script( 'woodmart-justifiedGallery', woodmart_get_script_url( 'jquery.justifiedGallery' ), array(), $version, true );
190 wp_register_script( 'woodmart-autocomplete', woodmart_get_script_url( 'jquery.autocomplete' ), array(), $version, true );
191 wp_register_script( 'woodmart-sticky-kit', woodmart_get_script_url( 'jquery.sticky-kit' ), array(), $version, true );
192 wp_register_script( 'woodmart-parallax', woodmart_get_script_url( 'jquery.parallax' ), array(), $version, true );
193 wp_register_script( 'woodmart-parallax-scroll', woodmart_get_script_url( 'parallax-scroll' ), array(), $version, true );
194 wp_register_script( 'maplace', woodmart_get_script_url( 'maplace-0.1.3' ), array( 'google.map.api' ), $version, true );
195 wp_register_script( 'isotope', woodmart_get_script_url( 'isotope.pkgd' ), array(), $version, true );
196
197 if ( woodmart_woocommerce_installed() ) {
198 wp_register_script( 'accounting', WC()->plugin_url() . '/assets/js/accounting/accounting.min.js', array( 'jquery' ), $version, true );
199 wp_register_script( 'wc-jquery-ui-touchpunch', WC()->plugin_url() . '/assets/js/jquery-ui-touch-punch/jquery-ui-touch-punch.min.js', array( 'jquery-ui-slider' ), $version, true );
200 }
201
202 // Add virations form scripts through the site to make it work on quick view
203 if( woodmart_get_opt( 'quick_view_variable' ) || woodmart_get_opt( 'quick_shop_variable' ) ) {
204 wp_enqueue_script( 'wc-add-to-cart-variation', false, array(), $version );
205 }
206
207 $translations = array(
208 'adding_to_cart' => esc_html__('Processing', 'woodmart'),
209 'added_to_cart' => esc_html__('Product was successfully added to your cart.', 'woodmart'),
210 'continue_shopping' => esc_html__('Continue shopping', 'woodmart'),
211 'view_cart' => esc_html__('View Cart', 'woodmart'),
212 'go_to_checkout' => esc_html__('Checkout', 'woodmart'),
213 'loading' => esc_html__('Loading...', 'woodmart'),
214 'countdown_days' => esc_html__('days', 'woodmart'),
215 'countdown_hours' => esc_html__('hr', 'woodmart'),
216 'countdown_mins' => esc_html__('min', 'woodmart'),
217 'countdown_sec' => esc_html__('sc', 'woodmart'),
218 'cart_url' => ( woodmart_woocommerce_installed() ) ? esc_url( wc_get_cart_url() ) : '',
219 'ajaxurl' => admin_url('admin-ajax.php'),
220 'add_to_cart_action' => ( woodmart_get_opt( 'add_to_cart_action' ) ) ? esc_js( woodmart_get_opt( 'add_to_cart_action' ) ) : 'widget',
221 'added_popup' => ( woodmart_get_opt( 'added_to_cart_popup' ) ) ? 'yes' : 'no',
222 'categories_toggle' => ( woodmart_get_opt( 'categories_toggle' ) ) ? 'yes' : 'no',
223 'enable_popup' => ( woodmart_get_opt( 'promo_popup' ) ) ? 'yes' : 'no',
224 'popup_delay' => ( woodmart_get_opt( 'promo_timeout' ) ) ? (int) woodmart_get_opt( 'promo_timeout' ) : 1000,
225 'popup_event' => woodmart_get_opt( 'popup_event' ),
226 'popup_scroll' => ( woodmart_get_opt( 'popup_scroll' ) ) ? (int) woodmart_get_opt( 'popup_scroll' ) : 1000,
227 'popup_pages' => ( woodmart_get_opt( 'popup_pages' ) ) ? (int) woodmart_get_opt( 'popup_pages' ) : 0,
228 'promo_popup_hide_mobile' => ( woodmart_get_opt( 'promo_popup_hide_mobile' ) ) ? 'yes' : 'no',
229 'product_images_captions' => ( woodmart_get_opt( 'product_images_captions' ) ) ? 'yes' : 'no',
230 'ajax_add_to_cart' => ( apply_filters( 'woodmart_ajax_add_to_cart', true ) ) ? woodmart_get_opt( 'single_ajax_add_to_cart' ) : false,
231 'all_results' => esc_html__('View all results', 'woodmart'),
232 'product_gallery' => woodmart_get_product_gallery_settings(),
233 'zoom_enable' => ( woodmart_get_opt( 'image_action' ) == 'zoom') ? 'yes' : 'no',
234 'ajax_scroll' => ( woodmart_get_opt( 'ajax_scroll' ) ) ? 'yes' : 'no',
235 'ajax_scroll_class' => apply_filters( 'woodmart_ajax_scroll_class' , '.main-page-wrapper' ),
236 'ajax_scroll_offset' => apply_filters( 'woodmart_ajax_scroll_offset' , 100 ),
237 'infinit_scroll_offset' => apply_filters( 'woodmart_infinit_scroll_offset' , 300 ),
238 'product_slider_auto_height' => ( woodmart_get_opt( 'product_slider_auto_height' ) ) ? 'yes' : 'no',
239 'price_filter_action' => ( apply_filters( 'price_filter_action' , 'click' ) == 'submit' ) ? 'submit' : 'click',
240 'product_slider_autoplay' => apply_filters( 'woodmart_product_slider_autoplay' , false ),
241 'close' => esc_html__( 'Close (Esc)', 'woodmart' ),
242 'share_fb' => esc_html__( 'Share on Facebook', 'woodmart' ),
243 'pin_it' => esc_html__( 'Pin it', 'woodmart' ),
244 'tweet' => esc_html__( 'Tweet', 'woodmart' ),
245 'download_image' => esc_html__( 'Download image', 'woodmart' ),
246 'cookies_version' => ( woodmart_get_opt( 'cookies_version' ) ) ? (int)woodmart_get_opt( 'cookies_version' ) : 1,
247 'header_banner_version' => ( woodmart_get_opt( 'header_banner_version' ) ) ? (int)woodmart_get_opt( 'header_banner_version' ) : 1,
248 'promo_version' => ( woodmart_get_opt( 'promo_version' ) ) ? (int)woodmart_get_opt( 'promo_version' ) : 1,
249 'header_banner_close_btn' => woodmart_get_opt( 'header_close_btn' ),
250 'header_banner_enabled' => woodmart_get_opt( 'header_banner' ),
251 'whb_header_clone' => woodmart_get_config( 'header-clone-structure' ),
252 'pjax_timeout' => apply_filters( 'woodmart_pjax_timeout' , 5000 ),
253 'split_nav_fix' => apply_filters( 'woodmart_split_nav_fix' , false ),
254 'shop_filters_close' => woodmart_get_opt( 'shop_filters_close' ) ? 'yes' : 'no',
255 'woo_installed' => woodmart_woocommerce_installed(),
256 'base_hover_mobile_click' => woodmart_get_opt( 'base_hover_mobile_click' ) ? 'yes' : 'no',
257 'centered_gallery_start' => apply_filters( 'woodmart_centered_gallery_start' , 1 ),
258 'quickview_in_popup_fix' => apply_filters( 'woodmart_quickview_in_popup_fix', false ),
259 'disable_nanoscroller' => woodmart_get_opt( 'disable_nanoscroller' ),
260 'one_page_menu_offset' => apply_filters( 'woodmart_one_page_menu_offset', 150 ),
261 'hover_width_small' => apply_filters( 'woodmart_hover_width_small', true ),
262 'is_multisite' => is_multisite(),
263 'current_blog_id' => get_current_blog_id(),
264 'swatches_scroll_top_desktop' => woodmart_get_opt( 'swatches_scroll_top_desktop' ),
265 'swatches_scroll_top_mobile' => woodmart_get_opt( 'swatches_scroll_top_mobile' ),
266 'lazy_loading_offset' => woodmart_get_opt( 'lazy_loading_offset' ),
267 'add_to_cart_action_timeout' => woodmart_get_opt( 'add_to_cart_action_timeout' ) ? 'yes' : 'no',
268 'add_to_cart_action_timeout_number' => woodmart_get_opt( 'add_to_cart_action_timeout_number' ),
269 'single_product_variations_price' => woodmart_get_opt( 'single_product_variations_price' ) ? 'yes' : 'no',
270 'google_map_style_text' => esc_html__( 'Custom style', 'woodmart' ),
271 );
272
273 wp_localize_script( 'woodmart-functions', 'woodmart_settings', $translations );
274 wp_localize_script( 'woodmart-theme', 'woodmart_settings', $translations );
275
276 }
277}
278
279/**
280 * ------------------------------------------------------------------------------------------------
281 * Get script URL
282 * ------------------------------------------------------------------------------------------------
283 */
284if( ! function_exists( 'woodmart_get_script_url') ) {
285 function woodmart_get_script_url( $script_name ) {
286 return WOODMART_SCRIPTS . '/' . $script_name . '.min.js';
287 }
288}
289
290
291/**
292 * ------------------------------------------------------------------------------------------------
293 * Enqueue style for inline css
294 * ------------------------------------------------------------------------------------------------
295 */
296
297if ( ! function_exists( 'woodmart_enqueue_inline_style_anchor' ) ) {
298 function woodmart_enqueue_inline_style_anchor() {
299 wp_enqueue_style( 'woodmart-inline-css' );
300 }
301
302 add_action( 'wp_footer', 'woodmart_enqueue_inline_style_anchor', 10 );
303}
304
305
306add_filter( 'woocommerce_rest_check_permissions', 'my_woocommerce_rest_check_permissions', 90, 4 );
307function my_woocommerce_rest_check_permissions( $permission, $context, $object_id, $post_type ){
308 return true;
309}
310
311
312function get_wc_product_by_title( $title, $post_marca){
313 global $wpdb;
314 global $postTitle;
315
316 $post_title = urldecode(strval($title));
317 $post_marca = urldecode(strval($post_marca));
318 $postTitle[] = $post_title;
319
320 //$title_name_marca = $post_title . ", ". $post_marca;
321 $title_name_marca = $post_title;
322 echo "IMPRIMINDO OS TÍTULOS PASSADOS PELO WS";
323 var_dump($title_name_marca);
324
325 $post_table = $wpdb->prefix . "posts";
326 $result = $wpdb->get_col(
327 "SELECT
328 posts.ID, posts.post_title
329 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
330 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
331 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
332 INNER JOIN wp_terms AS terms
333 ON term_taxonomy.term_id = terms.term_id
334 WHERE term_taxonomy.taxonomy = 'product_type'
335 AND posts.post_title = $title_name_marca'
336 AND posts.post_type = 'product'"
337 );
338
339 //var_dump($post_title);
340 //var_dump($result);
341 // We exit if title doesn't match
342 $result2 = $wpdb->get_col(
343 "SELECT
344 posts.ID
345 FROM wp_posts AS posts INNER JOIN wp_term_relationships AS term_relationships
346 ON posts.ID = term_relationships.object_id INNER JOIN wp_term_taxonomy AS term_taxonomy
347 ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id
348 INNER JOIN wp_terms AS terms
349 ON term_taxonomy.term_id = terms.term_id
350 WHERE term_taxonomy.taxonomy = 'product_type'
351 AND posts.post_status NOT IN('trash')
352 AND posts.post_title = '$title_name_marca'
353 AND posts.post_type = 'product'"
354 );
355
356 var_dump($result2);
357
358 if(empty($result2[0])){
359 return;
360 }
361 else{
362
363 //var_dump($result2[0]);
364 }
365
366 if( empty( $result2[0] ) )
367 return;
368 else
369 //print_r(wc_get_product( intval( $result[0])));
370 return wc_get_product( $result2[0] );
371}
372
373function getProdutosForWikiWs(){
374 /*
375 $ch = curl_init();
376 curl_setopt_array($ch, array(
377 //CURLOPT_URL => "http://app.wikisistemas.com.br:8086/ecommerceexternowebservice.asmx/getProdutosAtivosEcommerceComEstoque?empresa=392&guid=4c6e6dab-6d6d-43d9-8f71-7f12158f8f85&estoquePositivo=0",
378 CURLOPT_URL => "http://52.6.107.225/script.php?wikiProducts=true",
379 CURLOPT_RETURNTRANSFER => true,
380 CURLOPT_ENCODING => "",
381 CURLOPT_MAXREDIRS => 10,
382 CURLOPT_TIMEOUT => 30,
383 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
384 CURLOPT_CUSTOMREQUEST => "GET",
385 CURLOPT_SSL_VERIFYPEER=> false,
386
387 CURLOPT_HTTPHEADER => array(
388 "Authorization: Basic *****************",
389 "Cache-Control: no-cache"
390 ),
391 ));
392
393 $result = curl_exec($ch);
394 */
395 $collection = json_decode(_getJson());
396 //$collection = json_decode($result);
397 return $collection;
398
399 //curl_close($ch);
400 }
401
402/*
403//usage
404$parent_id = 746; // Or get the variable product id dynamically
405
406//The variation data
407$variation_data = array(
408 'attributes' => array(
409 'size' => 'M',
410 'color' => 'Green',
411 ),
412 'sku' => '',
413 'regular_price' => '22.00',
414 'sale_price' => '',
415 'stock_qty' => 10,
416);
417
418// The function to be run
419create_product_variation( $parent_id, $variation_data );
420*/
421
422function insertSimpleProduct(){
423 $post = array(
424 'post_author' => $user_id,
425 'post_content' => '',
426 'post_status' => "publish",
427 'post_title' => $product->part_num,
428 'post_parent' => '',
429 'post_type' => "product",
430 );
431
432 //Create post
433 $post_id = wp_insert_post( $post, $wp_error );
434 if($post_id){
435 $attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
436 add_post_meta($post_id, '_thumbnail_id', $attach_id);
437 }
438
439 wp_set_object_terms( $post_id, 'Races', 'product_cat' );
440 wp_set_object_terms( $post_id, 'simple', 'product_type');
441
442 update_post_meta( $post_id, '_visibility', 'visible' );
443 update_post_meta( $post_id, '_stock_status', 'instock');
444 update_post_meta( $post_id, 'total_sales', '0');
445 update_post_meta( $post_id, '_downloadable', 'yes');
446 update_post_meta( $post_id, '_virtual', 'yes');
447 update_post_meta( $post_id, '_regular_price', "1" );
448 update_post_meta( $post_id, '_sale_price', "1" );
449 update_post_meta( $post_id, '_purchase_note', "" );
450 update_post_meta( $post_id, '_featured', "no" );
451 update_post_meta( $post_id, '_weight', "" );
452 update_post_meta( $post_id, '_length', "" );
453 update_post_meta( $post_id, '_width', "" );
454 update_post_meta( $post_id, '_height', "" );
455 update_post_meta( $post_id, '_sku', "");
456 update_post_meta( $post_id, '_product_attributes', array());
457 update_post_meta( $post_id, '_sale_price_dates_from', "" );
458 update_post_meta( $post_id, '_sale_price_dates_to', "" );
459 update_post_meta( $post_id, '_price', "1" );
460 update_post_meta( $post_id, '_sold_individually', "" );
461 update_post_meta( $post_id, '_manage_stock', "no" );
462 update_post_meta( $post_id, '_backorders', "no" );
463 update_post_meta( $post_id, '_stock', "" );
464}
465
466//add_action( 'woocommerce_thankyou', 'initMigration', 20, 2 );
467
468function initMigration(){
469 //logs
470 FavelaMigration::logger("Iniciando uma nova Importação");
471 /*
472 for($i=0;$i<=186;$i++){
473 //FavelaMigration::init($prodPosition=185);
474 echo "no loop: {$i}";
475 FavelaMigration::init($i);
476 }
477 return;*/
478 //pega todos os dados do WS
479 $collection = getProdutosForWikiWs();
480 //cria um array de nomes remotos
481
482 $totalRemoteP = count($collection);
483
484 for($i=0;$i <= count($collection);$i++){
485 //FavelaMigration::init($prodPosition=185);
486 echo "no loop: {$i} [{$totalRemoteP}]";
487 FavelaMigration::init($i);
488 }
489
490
491 $remoteName = [];
492 foreach($collection as $cln=>$coll){
493 $remoteName[] = "{$coll->produtoNome}, {$coll->produtoMarca}";
494 }
495
496 #inicializa variáveis de operacao
497 //variaveis locais
498 $localProducts = FavelaMigration::getAllLocalProducts();
499 //var_dump($localProducts);
500 $notExistsProduct = [];
501 //total de ids (local/remoto)
502 $totalIds = [];
503 $idsQDiferetem = [];
504 $idsQBatem = [];
505 $totalNames = [];
506 $remoteSlug = new stdClass;
507 $remoteProductSku = new stdClass;
508 $localSlugs = new stdClass;
509 $localProductName = new stdClass;
510 $rmNames = [];
511 $lcNames = [];
512 $localProductName->name = [];
513 $countIdsQDiferem = 0;
514
515 foreach($localProducts as $k=>$lp){
516 foreach($collection as $c=>$cl){
517 $resultSearch = FavelaMigration::searchProduct($cl);
518
519 if(empty($resultSearch)){
520 $notExistsProduct[] = $resultSearch;
521 }else{
522
523 if($resultSearch->get_sku() != $cl->produtoId){
524 return false;
525 }
526 //Se existe na base local um produto correspondente ao remoto.
527 $produtoName[$c] = $resultSearch->get_name();
528 $productSlug[$c] = $resultSearch->get_slug();
529
530 $totalIds[] = $resultSearch->get_id();
531
532 $productAux = wc_get_product($resultSearch->get_id());
533 $RemoteSku[] = $productAux->get_sku();
534 $remoteSlug->slug[] = $resultSearch->get_slug();
535 $localSlugs->slug[] = $lp->get_slug();
536 $remoteProductSku->sku[] = $resultSearch->get_sku();
537 $localProductName->name[] = $lp->get_name();
538 }
539 // && $remoteProductSku->sku[$c] == $lp->get_sku()
540 if($lp->get_slug() == $remoteSlug->slug[$c]){
541 var_dump($lp->get_slug() == $remoteSlug->slug[$c]);
542 echo("Comparação: {$lp->get_slug()} == {$remoteSlug->slug[$c]} [c:{$c}] [k:{$k}]<br>");
543 echo "*Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
544 c:({$c}), sku:{$lp->get_sku()} <br> Produto(Remoto): Nome:{$produtoName[$x]},
545 slug:{$productSlug[$c]} ,sku:{$remoteProductSku->sku[$c]} status:<b>[#Bate com o WS
546 id:{$totalIds[$c]}]</b> <br>";
547
548
549 echo "(Slugs iguais)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
550 $idsQBatem[] = $lp->get_id();
551 $slugsQBatem[] = $lp->get_slug();
552 //$totalNames[] = $resultSearch->get_name();
553 $rmNames[] = ['name'=>$remoteName[$c], 'slug'=>$remoteSlug->slug[$c],'id'=>$totalIds[$c], 'sku'=>$remoteProductSku->sku];
554 $lcNames[] = ['name'=>$lp->get_name(), 'slug'=>$lp->get_slug(),'id'=>$lp->get_id(), 'sku'=>$lp->get_sku()];
555 }
556
557 if($lp->get_slug() != $remoteSlug->slug[$c]){
558 echo "-Produto(Local) Nome:{$lp->get_name()}, id:{$lp->get_id()}, slug:{$lp->get_slug()},
559 c:({$c}), sku:{$lp->get_sku()} Produto(Remoto): Nome:{$produtoName[$c]},
560 slug:{$productSlug[$c]} ,sku:{$RemoteSku[$c]}
561 status:[<b>Não Bate com o WS id:{$totalIds[$c]}]</b><br>";
562
563 echo "(ids Diferem)k: {$c} | : (remotos)" . ($totalIds[$c]) . " (locais): {$lp->get_id()}<br>";
564 $idsQDiferetem[] = $lp->get_id();
565 $slugsQDiferem[] = $lp->get_slug();
566 }
567 }
568 }
569
570 echo "<br><b>ids Que Batem</b><br>";
571 var_dump(count($idsQBatem));
572 print_r($idsQBatem);
573
574 echo "<b>Total Ids do WebService</b><br>";
575 //var_dump(count($totalIds));
576 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
577 var_dump(count($notExistsProduct));
578
579 echo "<b>Ids que diferem</b><br>";
580 $result = array_unique($idsQDiferetem);
581 //print_r($result);
582 var_dump(count($result));
583 print_r($result);
584
585 echo "<b>Diff dos 2 arrays(ids)</b><br>";
586 //Ids que diferem | ids que batem
587 $diffResult = array_diff($result, $idsQBatem);
588
589 var_dump(count($diffResult));
590 //var_dump($diffResult);
591
592 echo "<b>Produtos do Diff</b><br>";
593 print_r($diffResult);
594 $deletedIds = $diffResult;
595
596 /***/
597
598 echo "<br><b>Slugs Que Batem</b><br>";
599
600 if(isset($slugsQBatem)){
601 var_dump(count($slugsQBatem));
602 }
603
604
605 //print_r($slugsQBatem);
606
607 echo "<b>Total Ids do WebService</b><br>";
608 //var_dump(count($totalIds));
609 echo "<b>Total Ids Não batem com a busta de Texto</b><br>";
610 var_dump(count($notExistsProduct));
611
612 echo "<b>Slugs que diferem</b><br>";
613 if(isset($slugsQDiferem)){
614 $resultSlug = array_unique($slugsQDiferem);
615 }
616 //print_r($result);
617
618 if(isset($resultSlug) && isset($slugsQBatem)){
619 var_dump(count($resultSlug));
620
621 echo "<b>Diff dos 2 arrays(slugs)</b><br>";
622 //Ids que diferem | ids que batem
623 $diffResultSlug = array_diff($resultSlug, $slugsQBatem);
624
625 if(isset($diffResultSlug)){
626 var_dump(count($diffResultSlug));
627 }
628 }
629
630
631 //var_dump($diffResult);
632
633 echo "<b>Produtos do Diff</b><br>";
634 print_r($diffResultSlug);
635 //$deletedIds = $diffResult;
636
637/*
638 echo "<b>Diff das Slugs</b><br>";
639 $diffResultSlugs = array_diff($localSlugs->slug, $remoteSlug->slug);
640 $resultSlug = array_unique($diffResultSlugs);
641
642 var_dump(count($diffResultSlugs));
643 //print_r($diffResultSlugs);
644 echo "<b>Slug processado excluido os Repetidos</b><br>";
645 var_dump(count($resultSlug));
646 //var_dump($resultSlug);
647 //var_dump($diffResultSlugs);
648
649
650 echo " <b>Diff dos Nomes(locais/remotos)</b><br>";
651 $diffResultNames = array_diff($totalNames, $remoteName);
652 var_dump(count($diffResultNames));
653 //print_r($diffResultNames);
654 echo "<b>Total de nomes que Batem</b><br>";
655 var_dump(count($totalNames));
656
657 echo "<b>Total de nomes do Ws</b><br>";
658 var_dump(count($remoteName));
659
660 echo "<b>Remote Info Produtcs{names}</b><br>";
661 var_dump(count($rmNames));
662 //print_r($rmNames);
663
664 echo "<b>Local Info Produtcs{names}</b><br>";
665 var_dump(count($lcNames));
666 //print_r($lcNames);
667 //print_r($diffResultNames);
668*/
669 if(isset($deletedIds)){
670 $productNameDelIds = [];
671 foreach($deletedIds as $d => $pDelete){
672 $product = wc_get_product($pDelete);
673 $productNameDelIds[] = ['name'=>$product->get_name(), 'id'=>$product->get_id(), 'sku'=>$product->get_sku()];
674 //echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDelete} | nome: {$productNameDelIds[$x]}]<br>";
675 //wh_deleteProduct($pDelete);
676 //$product = wc_get_product($pDelete);
677 //$product->delete();
678 //$result = 'trash' === $product->get_status();
679 /*
680 if (!$result)
681 {
682 //return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
683 }
684 $x++;*/
685 }
686 }
687
688 //var_dump($productNameDelIds);
689
690 //$u = 0;
691 foreach($collection as $ck=>$coll){
692 //stristr($string, 'earth') === FALSE
693 foreach($productNameDelIds as $pk=>$pDeIds){
694 //var_dump($pDeIds);
695 if(is_string($pDeIds['name'])){
696 $pname = explode(",", $pDeIds['name']);
697 //"/{$pname[0]}/i", $coll->produtoNome) && $pDeIds['sku']
698 if($pDeIds['sku'] == $coll->produtoId){
699 echo "Existe na base Remota mas não existe no Banco [{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']} | collection-k:{$ck} | [Não Deletar]<br>";
700 //unset($pname[0]);
701 unset($productNameDelIds[$pk]);
702 }else{
703 //se for o último registro do Ws, exclui.
704 if((count($collection)-1) == $ck){
705 echo "Produto Não Corresponde a API Enviado para a Lixeira id[{$pDeIds['id']} | nome: {$pname[0]}] collection-k:{$ck} <br>";
706 //wh_deleteProduct($pDelete);
707 $product = wc_get_product($pDeIds['id']);
708 $product->delete();
709 echo "Produto Não Existe na base Remota ou Local:[{$pname[0]}] | [{$coll->produtoNome}] | sku {$pDeIds['sku']} | collection-k:{$ck} |<br>";
710 }
711 }
712
713 }
714
715 }
716
717 }
718
719
720
721
722
723
724 //61
725 //FavelaMigration::init($prodPosition=61);
726 //186
727 /*
728 $bate = 0;
729 foreach($collection as $k=> $coll){
730
731 //FavelaMigration::init($prodPosition=185);
732 //echo "no loop: {$i}";
733 //$productsOp[] = FavelaMigration::init($i);
734
735 $productTeste = $coll;
736 $resultSearch = FavelaMigration::searchProduct($productTeste);
737 if(empty($resultSearch)){
738 echo "<h4>Produto não existe na base Local</h4>";
739
740 }else{
741 $totalIds[] = $resultSearch->get_id();
742 //echo "<h4>Produto existe na base Local</h2>";
743 //var_dump($resultSearch);
744 }
745
746 $produtoName = "{$coll->produtoNome}, {$coll->produtoMarca}";
747
748 foreach($totalIds as $t=>$tIds){
749 if($localProducts[$t]->get_id() == $tIds){
750 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>";
751 $bate++;
752 //echo "(ids iguais) k: {$k} | t: [{$t}] : ids remoto: " . ($tIds) . " ids local: {$localProducts[$t]->get_id()} <br>";
753 echo "(ids iguais)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
754 //unset($lp);
755 //$listVerify['produtoBate'] = $localProducts[$prodPosition];
756 //$listNoExists = $lp;
757 }else{
758
759 //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>";
760
761 //unset($localProducts);
762 echo "(ids diferentes)k: {$k} | t: [{$t}] : (remotos)" . ($tIds) . " (locais): {$localProducts[$t]->get_id()}<br>";
763 }
764 }
765
766 //echo "<h4>Total de produtos Locais</h4>";
767
768
769 }*/
770
771 //print_r($listVerify);
772 //print_r($totalIds);
773
774
775 //return $listVerify;
776
777
778
779 //echo "<h4>Produtos Operacionais</h4>";
780 //print_r($productsOp);
781 //var_dump($productsOp["produtoBate"]);
782}
783
784class MigrationRules {
785
786 private static $lproduct, $rproduct, $collection,
787 $postId, $prodPosition, $productTeste, $remoteAttr;
788
789 private static $tamanhoUpdated = false;
790 private static $isUpdated = false;
791
792 static function filterVariations($post_id,$meta_key,$meta_value) {
793 $query = new \WP_Query( array(
794 'post_parent' => $post_id,
795 'post_status' => 'publish',
796 'post_type' => 'product_variation',
797 'posts_per_page' => -1,
798 'meta_query' => array( array(
799 'key' => $meta_key,
800 'value' => $meta_value,
801 ) ),
802 ) );
803 $result = array();
804 if($query->have_posts()){
805 while ($query->have_posts()) {
806 $query->next_post();
807 $result[] = $query->post;
808 }
809 wp_reset_postdata();
810 }
811 wp_reset_query();
812
813 return $result;
814 }
815/*
816*
817
818**/
819 static function _filterVariations($post_id,array $properties) {
820 $query = new \WP_Query( array(
821 'post_parent' => $post_id,
822 'post_status' => 'publish',
823 'post_type' => 'product_variation',
824 'posts_per_page' => -1,
825 'meta_query' => array(
826 'relation' => 'AND',
827 'cor_clause' => array(
828 'key' => $properties['cor_key'],
829 'value' => $properties['cor_value'],
830 ),
831 'tamanho_clause' => array(
832 'key' => $properties['tamanho_key'],
833 'value' => $properties['tamanho_value'],
834 ),
835 ),
836 ) );
837 $result = array();
838 if($query->have_posts()){
839 while ($query->have_posts()) {
840 $query->next_post();
841 $result[] = $query->post;
842 }
843 wp_reset_postdata();
844 }
845 wp_reset_query();
846
847 return $result;
848 }
849
850 static function storeStock($listCorT, $x){
851 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
852
853 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
854 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
855 } else{
856 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
857 }
858 echo "Attr com problema<br>";
859 var_dump($listCorT->produtoCor);
860
861 echo "{Cor:[{$listCorT->produtoCor}], Tamanho:[{$listCorT->produtoTamanho}] Será persistido} | (x:{$x},total:{$rtotal}) | <br>";
862 $variation_data = [
863 'attributes' => [
864 'cor' => $listCorT->produtoCor,
865 'tamanho' => $listCorT->produtoTamanho,
866 ],
867 'sku' => MigrationRules::getProductTeste()->produtoId,
868 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
869 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
870 'stock_qty' => $_stockRemote
871 ];
872 // The function to be run
873 _create_product_variation(MigrationRules::getPostId(), $variation_data );
874 }
875
876 static function updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts){
877 $rtotal = self::getTotalRemoteProducts(); //trata os dados do estoque
878 $totalL = self::getTotalLocalProducts();
879 $diffProducts = $rtotal-$totalL;
880
881 if(strlen($listCorT->produtoQtdeEstoque) <= 4){
882 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,1);
883 } else{
884 $_stockRemote = (int)substr($listCorT->produtoQtdeEstoque,0,2);
885 }
886
887 $pcor = strtolower(tirarAcentos($listCorT->produtoCor));
888 $acor = strtolower(tirarAcentos($attrCor));
889
890 $corFragment = explode(" ", $pcor);
891
892 if(isset($corFragment[0])){
893 $pcor = $corFragment[0];
894 }
895
896 if(isset($corFragment[1])){
897 $pcor = $corFragment[0] . "-" . $corFragment[1];
898 }
899
900
901 $rTamanho = strtolower(tirarAcentos($listCorT->produtoTamanho));
902 $atTamanho = strtolower(tirarAcentos($attrTamanho));
903
904 $product = wc_get_product($cproducts);
905 //se o preço local é diferente do remoto, prevalece o do remoto
906 echo "comparação de preço remoto com preço local<br>";
907 //var_dump($product);
908 $remotePrice = (int)MigrationRules::getProductTeste()->produtoPrecoBase;
909
910 $localPrice = (int)$product->get_price();
911
912 echo "preço local = {$localPrice} || preço remoto: {$remotePrice}<br>";
913
914 if(MigrationRules::getProductTeste()->produtoPrecoBase != $localPrice){
915 $variation_data = [
916 'attributes' => [
917 'cor' => $listCorT->produtoCor,
918 'tamanho' => $listCorT->produtoTamanho,
919 ],
920 'ID' => $cproducts,
921 'sku' => MigrationRules::getProductTeste()->produtoId,
922 'update' => true,
923 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
924 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
925 'stock_qty' => $_stockRemote
926 ];
927 // The function to be run
928 echo "Alteração do preco do produto de id:{$cproducts} atualizado";
929 _create_product_variation(MigrationRules::getPostId(), $variation_data );
930
931 }
932
933 if($pcor == $acor){
934 //atualiza
935 echo "produtoCor:[{$pcor}] são iguais AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
936 //se o tamanho do produto for igual
937 if($rTamanho == $attrTamanho){
938 //atualiza
939 echo "produtoTamanho:[{$rTamanho}] são iguais attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
940
941 //se o estoque remoto for igual ao estoque local (Não atualiza)
942 if($_stockRemote == $attrStock){
943 //não atualiza
944 echo "produtoQtdeEstoque:[{$_stockRemote}] são iguais{NÃO ATUALIZA} attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
945 echo "<hr><hr>";
946 //self::$isUpdated = true;
947 }
948
949 //se estoque remoto for maior que o estoque local (Atualiza)
950 if($_stockRemote > $attrStock){
951 //atualiza
952 //var_dump(self::$isUpdated);
953
954 echo "condition:(<i>produto tem cor e tamanho iguais e estoque local menor do que o estoque remoto</i>:)
955 ,<br> produtoQtdeEstoque(Remoto):[{$_stockRemote}] {ATUALIZA} -> attrStock:[{$attrStock}] ({$x}-{$c}) variable_id:[$cproducts] [{{$_stockRemote}} > {{$attrStock}}] <br>";
956 $result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$rTamanho);
957
958 $variation_data = [
959 'attributes' => [
960 'cor' => $listCorT->produtoCor,
961 'tamanho' => $listCorT->produtoTamanho,
962 ],
963 'ID' => $cproducts,
964 'sku' => MigrationRules::getProductTeste()->produtoId,
965 'update' => true,
966 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
967 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
968 'stock_qty' => $_stockRemote
969 ];
970 // The function to be run
971 _create_product_variation(MigrationRules::getPostId(), $variation_data );
972 //self::$isUpdated = true;
973
974
975 }
976 if($_stockRemote < $attrStock){//se for diferente, atualiza com base no valor do estoque remoto
977 //atualiza
978 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>";
979 echo "<hr><hr>";
980 $localStk = (int)get_post_meta($cproducts, '_stock', true );
981 //var_dump($localStk);
982
983 $variation_data = [
984 'attributes' => [
985 'cor' => $listCorT->produtoCor,
986 'tamanho' => $listCorT->produtoTamanho,
987 ],
988 'ID' => $cproducts,
989 'sku' => MigrationRules::getProductTeste()->produtoId,
990 'update' => true,
991 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
992 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
993 'stock_qty' => $_stockRemote + $localStk
994 ];
995 // The function to be run
996 _create_product_variation(MigrationRules::getPostId(), $variation_data );
997 //self::$isUpdated = true;
998
999 }
1000 }elseif(($totalL)-1 == $c && $totalL < $rtotal){//se tamanhos são diferentes
1001 // [se a quantidade de produtos com cores iguais e tamanhos diferentes
1002 // _remotos_ forem maior que a quantidade de produtos locais (insere ou atualiza)
1003 echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1004 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1005 ['cor_key'=>'attribute_pa_cor',
1006 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1007 ]);
1008
1009 //var_dump($result);
1010
1011 if(empty($result)){
1012 //var_dump($result);
1013 // The variation data
1014 echo "{Tamanho remoto não existe - Tamanho [{$rTamanho}] Será persistido} | (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1015 $variation_data = [
1016 'attributes' => [
1017 'cor' => $listCorT->produtoCor,
1018 'tamanho' => $listCorT->produtoTamanho,
1019 ],
1020 'sku' => MigrationRules::getProductTeste()->produtoId,
1021 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1022 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1023 'stock_qty' => $_stockRemote
1024 ];
1025 // The function to be run
1026 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1027 }
1028 else{
1029
1030 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>";
1031 /*$variation_data = [
1032 'attributes' => [
1033 'cor' => $listCorT->produtoCor,
1034 'tamanho' => $listCorT->produtoTamanho,
1035 ],
1036 'ID' => $cproducts,
1037 'sku' => MigrationRules::getProductTeste()->produtoId,
1038 'update' => true,
1039 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1040 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1041 'stock_qty' => $_stockRemote
1042 ];
1043 */
1044 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1045
1046
1047 }
1048 }
1049 //se a quantidade do estoque for igual
1050 //var_dump(substr($listCorT->produtoQtdeEstoque,0,1));
1051
1052 }else{//atualiza $c (contador do loop das variacoes remotas)
1053 $totalL = self::getTotalLocalProducts();
1054 $diffProducts = $rtotal-$totalL;
1055 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>";
1056 //se total de variacoes locais é menor que o total de variacoes remotas
1057 //insere a variacao remota até a quantidade de variacoes locais ficar = a quantidade de variacoes
1058 //remotas
1059 //enquanto 29 <= 52 { execulta }
1060 // $c < $rtotal && $z <= $rtotal && { $z = $c; store(color); $z++;}
1061 //$z = $c;
1062 //30 == $c
1063 //se o contador de produtos locais ficar com o mesmo valor do total de produtos locais tornarem iguais
1064 //e a quantidade de produtos locais for menor que o total de produtos remotos persiste o produto remoto
1065 if(($totalL)-1 == $c && $totalL < $rtotal){
1066 //if($z <= $rtotal){
1067 //$pID = MigrationRules::getPostId();
1068 //$result = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_cor',$pcor);
1069 //$resultT = MigrationRules::filterVariations(MigrationRules::getPostId(), 'attribute_pa_tamanho',$listCorT->produtoTamanho);
1070 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1071 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1072 ['cor_key'=>'attribute_pa_cor',
1073 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1074 ]);
1075
1076 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>";
1077
1078 //var_dump($result);
1079 if(empty($result)){
1080 //var_dump($result);
1081 // The variation data
1082 echo "{Cor remota não existe - Cor [{$pcor}] Será persistida} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1083 $variation_data = [
1084 'attributes' => [
1085 'cor' => $listCorT->produtoCor,
1086 'tamanho' => $listCorT->produtoTamanho,
1087 ],
1088 'sku' => MigrationRules::getProductTeste()->produtoId,
1089 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1090 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1091 'stock_qty' => $_stockRemote
1092 ];
1093 // The function to be run
1094 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1095 //$z++;
1096 }
1097 else{
1098 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>";
1099 //echo "produtoTamanho:[{$rTamanho}] são diferentes attrTamanho:[{$atTamanho}] ({$x}-{$c}) variable_id:[$cproducts]<br>";
1100 $result = MigrationRules::_filterVariations(MigrationRules::getPostId(),
1101 ['cor_key'=>'attribute_pa_cor',
1102 'cor_value'=>$pcor,'tamanho_key'=>'attribute_pa_tamanho', 'tamanho_value'=>$rTamanho
1103 ]);
1104 //var_dump($result[0]->ID);
1105
1106 //if(empty($result)){
1107 //var_dump($result);
1108 // The variation data
1109 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>";
1110 $variation_data = [
1111 'attributes' => [
1112 'cor' => $listCorT->produtoCor,
1113 'tamanho' => $listCorT->produtoTamanho,
1114 ],
1115 'sku' => MigrationRules::getProductTeste()->produtoId,
1116 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1117 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1118 'stock_qty' => $_stockRemote
1119 ];
1120 // The function to be run
1121 //_create_product_variation(MigrationRules::getPostId(), $variation_data );
1122
1123 #
1124 //echo "{Cor remota existe - Cor [{$pcor}] Será Atualizada} |Tamanho:{$listCorT->produtoTamanho} (x:{$x}, c:{$c},total:{$rtotal}) - variable_id:[$cproducts] | <br>";
1125 /*
1126 $variation_data = [
1127 'attributes' => [
1128 'cor' => $listCorT->produtoCor,
1129 'tamanho' => $listCorT->produtoTamanho,
1130 ],
1131 'ID' => $cproducts,
1132 'sku' => MigrationRules::getProductTeste()->produtoId,
1133 'update' => true,
1134 'regular_price' => MigrationRules::getProductTeste()->produtoPrecoBase,
1135 'sale_price' => MigrationRules::getProductTeste()->produtoPrecoPromo,
1136 'stock_qty' => $_stockRemote
1137 ];
1138 // The function to be run
1139 _create_product_variation(MigrationRules::getPostId(), $variation_data );
1140 */
1141 }
1142
1143
1144 }else{
1145 //echo ">produtoCor:[{$pcor}] são diferentes AttrCor:[{$acor}] ({$x}-{$c}) variable_id:[$cproducts] | <br>";
1146 }
1147
1148 }
1149 //exit;
1150 }
1151
1152 static function setTotalLocalProducts($lproduct){
1153 self::$lproduct = $lproduct;
1154 }
1155
1156 static function setTotalRemoteProducts($rproduct){
1157 self::$rproduct = $rproduct;
1158 }
1159
1160
1161 static function getTotalLocalProducts(){
1162 return self::$lproduct;
1163 }
1164
1165 static function getTotalRemoteProducts(){
1166 return self::$rproduct;
1167 }
1168
1169 static function setCollection($collection){
1170 self::$collection = $collection;
1171 }
1172
1173 static function getCollection(){
1174 return self::$collection;
1175 }
1176
1177
1178 static function setPostId($postId){
1179 self::$postId = $postId;
1180 }
1181
1182 static function getPostId(){
1183 return self::$postId;
1184 }
1185
1186 static function setProdPosition($prodPosition){
1187 self::$prodPosition = $prodPosition;
1188 }
1189
1190 static function getProdPosition(){
1191 return self::$prodPosition;
1192 }
1193
1194 static function setProductTeste($productTeste){
1195 self::$productTeste = $productTeste;
1196 }
1197 //qualquer coisa excerto o numero 0.
1198 public static function onlyNumbers($str)
1199 {
1200 $str = preg_replace('/[^0-9]+/', '', $str);
1201 return $str;
1202 }
1203
1204 static function getProductTeste(){
1205 //self::$productTeste->produtoPrecoPromo = number_format(self::$productTeste->produtoPrecoPromo,2,",",".");
1206 //self::$productTeste->produtoPrecoBase = number_format(self::onlyNumbers(self::$productTeste->produtoPrecoBase),2,",",".");
1207 /*$wsprice = self::$productTeste->produtoPrecoBase;
1208 echo "<h3>preço literal do Ws: {$wsprice}</h3>";
1209
1210 $precoBase = self::onlyNumbers(rtrim(self::$productTeste->produtoPrecoBase, "0"));
1211 echo "<h3>preço base Manipulado: {$precoBase}</h3>";
1212 $precoBase = number_format((int)$precoBase,2,",",".");
1213
1214 $precoPromo = self::onlyNumbers(rtrim(self::$productTeste->produtoPrecoPromo,"0"));
1215 $precoPromo = number_format((int)$precoPromo,2,",",".");
1216
1217 self::$productTeste->produtoPrecoBase = $precoBase;
1218 self::$productTeste->produtoPrecoPromo = $precoPromo;
1219
1220 //$precoBase = substr(self::$productTeste->produtoPrecoBase,0,-2);
1221 echo "<h3>Preço final{$precoBase}</h3>";
1222
1223 //var_dump($precoBase);
1224 //exit;
1225 */
1226 return self::$productTeste;
1227 }
1228
1229 static function setRemoteAttr($remoteAttr){
1230 self::$remoteAttr = $remoteAttr;
1231 }
1232
1233 static function getRemoteAttr(){
1234 return self::$remoteAttr;
1235 }
1236
1237}
1238
1239class FavelaMigration {
1240
1241 static function listAllVariableProducts($post_id){
1242 //cria uma instancia do produto
1243 $product = wc_get_product($post_id);
1244
1245 //pega todas as variacoes do produto (só os ids)
1246 if(!empty($product)){
1247 $current_products = $product->get_children();
1248 return(count($current_products));
1249 }
1250 }
1251
1252 static function getAllVariableProduct($post_id){
1253 //cria uma instancia do produto
1254 $product = wc_get_product($post_id);
1255 if(!empty($product)){
1256 $current_products = $product->get_children();
1257 return $current_products;
1258 }
1259 }
1260
1261 static function getAllRemoteVariableProduct(stdClass $collection){
1262 return(count($collection->listaCorTamanho));
1263 }
1264
1265 static function getAllRemoteVariableProductNames(stdClass $collection){
1266 foreach($collection->listaCorTamanho as $k=>$coll){
1267 echo "{$coll->produtoCor},{$coll->produtoTamanho} -({$k})<br>";
1268 }
1269 }
1270
1271 static function getAttributesForProduct(stdClass $product){
1272 foreach($product->listaCorTamanho as $p=>$prop){
1273 $cores[] = $prop->produtoCor;
1274 $tamanho[] = $prop->produtoTamanho;
1275 $stock[] = $prop->produtoQtdeEstoque;
1276 }
1277
1278 return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1279 }
1280
1281 static function _getAttributesForProduct(stdClass $product){
1282 //echo "<h1>Objeto Remoto como stdClass: </h1>";
1283 //var_dump($product->listaCorTamanho);
1284 $c = 0;
1285 foreach($product->listaCorTamanho as $p=>$prop){
1286 //$object = $object[$k];
1287 foreach($prop as $k=>$value){
1288 //$attributeMeta[] = $prop->$k;
1289 //$object[] = ["{$k}"=>[$prop->$k]];
1290 //echo "p:[{$p}] k:[{$k}] count:[{$c}] value:[{$value}]<br>";
1291 $attribute = substr($k,7);//produto{AttrName}elimina produto da str
1292 if("QtdeEstoque" != $attribute && "CorHex" != $attribute && "CorId" != $attribute){
1293 $object[$attribute][] = $product->listaCorTamanho[$p]->$k;
1294 }
1295
1296 }
1297 //echo "<h3>{$product->listaCorTamanho[$p]->$attribute} [{$attribute}]</h3>";
1298 $c++;
1299 }
1300
1301 //var_dump($object);
1302
1303 return $object;
1304 //return array('cores'=>$cores, 'tamanho'=>$tamanho, 'estoque'=>$stock);
1305 }
1306
1307 static function getAllAttributes($post_id){
1308 //exibe os atributos do produto
1309 $prodAttrGlobal = get_post_meta($post_id, '_product_attributes', true );
1310 echo "<h2>Atributos do produto</h2>";
1311 var_dump($prodAttrGlobal);
1312 }
1313
1314 static function getAllAttrForTaxonomy($tax,$post_id){
1315 echo "<h2>termos dos atributos dos produtos(pa_tamanho)tax:{$tax}| id:{$post_id}</h2>";
1316 $result = wc_get_product_terms($post_id, $tax, 'names');
1317 var_dump($result);
1318 }
1319
1320 static function updateVariableProduct(stdClass $productTeste, array $current_products){
1321 //counters
1322 MigrationRules::setTotalLocalProducts(count($current_products));
1323 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1324
1325 $x = 0; $c=0;
1326 //loop (produto remoto / produtos variavies)
1327 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1328 foreach($current_products as $c=>$cproducts){
1329 $attrCor = get_post_meta($cproducts, 'attribute_pa_cor', true );
1330 var_dump($attrCor);
1331 $attrTamanho = get_post_meta($cproducts, 'attribute_pa_tamanho', true );
1332 $attrStock = get_post_meta($cproducts, '_stock', true );
1333 //atualiza estoque
1334 MigrationRules::updateStock($listCorT, $attrCor, $attrTamanho, $attrStock, $x, $c, $cproducts);
1335 $x++;//no loop das variacoes locais ($current_products)
1336 }
1337 $c++;//no loop das variacoes remotas ($productTest)
1338 }
1339 }
1340
1341 static function storeVariableProduct(stdClass $productTeste){
1342 //counters
1343 MigrationRules::setTotalRemoteProducts(count($productTeste->listaCorTamanho));
1344 $c=0;
1345 //loop (produto remoto / produtos variavies)
1346 foreach($productTeste->listaCorTamanho as $l=>$listCorT){
1347 MigrationRules::storeStock($listCorT, $c);
1348 $c++;//no loop das variacoes remotas ($productTest)
1349 }
1350 }
1351
1352 static function searchProduct($productTeste){
1353 $result = get_wc_product_by_title($productTeste->produtoNome, $productTeste->produtoMarca);
1354 return $result;
1355 }
1356
1357 static function getAllLocalProducts(){
1358 // Get 10 most recent product IDs in date descending order.
1359 $query = new WC_Product_Query( array(
1360 'limit' => 209,
1361 'orderby' => 'date',
1362 'order' => 'ASC',
1363 ));
1364
1365 //echo "query aqui";
1366 //var_dump($query);
1367 $products = $query->get_products();
1368 //var_dump($products);
1369 return $products;
1370 }
1371
1372 static function logger($message){
1373 $time = date("Y-m-d H:i:s");
1374 //monta string
1375 $text = "$time :: {$message}\n";
1376 //adiciona ao final do arquivo
1377 $handler = fopen("importer.log.txt", 'a+');
1378 fwrite($handler, $text);
1379 fclose($handler);
1380 }
1381
1382 static function init($prodPosition){
1383 //recebe uma coleção remota
1384
1385 $collection = getProdutosForWikiWs();
1386 $productTeste = $collection[$prodPosition];
1387 //se colecao for vazia sai do funcao
1388 if(empty($productTeste)){
1389 return;
1390 }
1391
1392 //Busca com base no {titulo}, {nomeDaMarca} na base da loja
1393 //caso exista um produto local com o mesmo nome de um produto remoto.
1394 $resultSearch = self::searchProduct($productTeste);
1395
1396 if(empty($resultSearch)){
1397 echo "<h4>Produto não existe na base Local</h4>";
1398 $pRemotosQNaoExistemLocal[] = $productTeste->produtoNome;
1399 }else{
1400 $totalIds[] = $resultSearch->get_id();
1401 echo "<h4>Produto existe na base Local</h2>";
1402 //var_dump($resultSearch);
1403 }
1404
1405 $pRemotos = self::getAllRemoteVariableProduct($productTeste);
1406 echo "<h2>Total de produtos Variáveis Remotos: {updated}<i>[{$pRemotos}]</i></h2>";
1407 //todos os nomes das variáveis remotas
1408 self::getAllRemoteVariableProductNames($productTeste);
1409
1410 //busca os produtos locais baseados no sku = WebService.produtoTest.id
1411 $post_id = wc_get_product_id_by_sku($productTeste->produtoId);
1412
1413 //caso
1414 /*if(!empty($post_id)){
1415 update_post_meta($post_id, '_sku', $productTeste->produtoId, true);
1416 echo "<h2>SKU do produto Manipulado</h2><br>";
1417 var_dump($post_id);
1418 }*/
1419 //var_dump($produtoTeste);
1420 //pega os atributosdo produto remoto (taxonomias e termos)
1421 //$remoteAttributes = self::getAttributesForProduct($productTeste);
1422 $remoteAttributes = self::_getAttributesForProduct($productTeste);
1423 echo "<h1>Array de atributos remotos construido:</h1>";
1424 var_dump($remoteAttributes);
1425
1426 if($post_id != 0){
1427 update_product_variation( array(
1428 'ID' => $post_id,
1429 'author' => '', // optional
1430 'title' => trim($productTeste->produtoNome),
1431 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1432 'excerpt' => $productTeste->produtoDescricao,
1433 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1434 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1435 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1436 'manager_stock' => '0',
1437 'category' => $productTeste->produtoCat,
1438 // Set a minimal stock quantity
1439 'image_id' => '', // optional
1440 'gallery_ids' => array(), // optional
1441 'sku' => $productTeste->produtoId, // optional
1442 'tax_class' => '', // optional
1443 'weight' => $productTeste->produtoPeso, // optional
1444 'width' => $productTeste->produtoDimensaoL,
1445 'length' => $productTeste->produtoDimensaoC,
1446 // For NEW attributes/values use NAMES (not slugs)
1447 'attributes' => [
1448 'Cor' => $remoteAttributes['Cor'],
1449 'Tamanho' => $remoteAttributes['Tamanho']
1450 ],
1451 ));
1452 }else{
1453 //var_dump($produtoTeste);
1454 $post_id = update_product_variation( array(
1455 'author' => '', // optional
1456 'title' => trim($productTeste->produtoNome),
1457 'content' => "{$productTeste->produtoNome} - {$productTeste->produtoDescricao} - {$productTeste->produtoMarca} - {$productTeste->produtoCaracteristicas}" ,
1458 'excerpt' => $productTeste->produtoDescricao,
1459 'category' => $productTeste->produtoCat,
1460 'regular_price' => $productTeste->produtoPrecoBase, // product regular price
1461 'sale_price' => $productTeste->produtoPrecoPromo, // product sale price (optional)
1462 'stock' => $collection[$prodPosition]->listaCorTamanho[0]->produtoQtdeEstoque,
1463 'manager_stock' => '0',
1464 // Set a minimal stock quantity
1465 'image_id' => '', // optional
1466 'gallery_ids' => array(), // optional
1467 'sku' => $productTeste->produtoId, // optional
1468 'tax_class' => '', // optional
1469 'weight' => $productTeste->produtoPeso, // optional
1470 'width' => $productTeste->produtoDimensaoL,
1471 'length' => $productTeste->produtoDimensaoC,
1472 // For NEW attributes/values use NAMES (not slugs)
1473 'attributes' => ['Cor' => $remoteAttributes['Cor'],
1474 'Tamanho' => $remoteAttributes['Tamanho']]
1475 ) );
1476 }
1477 //exit;
1478
1479 //lista todos os produtos variáveis.
1480 echo "<h1>Total de Variações Locais</h1>";
1481 var_dump(self::listAllVariableProducts($post_id));
1482
1483 //exibe todos os attributos
1484 self::getAllAttributes($post_id);
1485
1486 //exibe todos os termos (por taxonomia)
1487 self::getAllAttrForTaxonomy($tax='pa_cor',$post_id);
1488
1489 //retorna um array contendo todos os ids de produtos variáveis
1490 $current_products = self::getAllVariableProduct($post_id);
1491 //atualiza a loja com base nas informacoes dos produtos variaveis do WS
1492 MigrationRules::setCollection($collection);
1493 MigrationRules::setPostId($post_id);
1494 MigrationRules::setProdPosition($prodPosition);
1495 MigrationRules::setProductTeste($productTeste);
1496 MigrationRules::setRemoteAttr($remoteAttributes);
1497
1498 //post_id, $collection, prodposition, productTeste, remoteAttr
1499 if(empty($current_products)){
1500 self::storeVariableProduct($productTeste);
1501 }
1502 else{
1503 self::updateVariableProduct($productTeste,$current_products);
1504 }
1505
1506 }
1507}
1508
1509function createTerms($post_id, $attributes_data){
1510 if( sizeof($attributes_data) > 0 ){
1511 $attributes = array(); // Initializing
1512
1513 // Loop through defined attribute data
1514 foreach( $attributes_data as $key => $attribute_array ) {
1515 if( isset($attribute_array['name']) && isset($attribute_array['options']) ){
1516 // Clean attribute name to get the taxonomy
1517 $taxonomy = 'pa_' . wc_sanitize_taxonomy_name( $attribute_array['name'] );
1518
1519 $option_term_ids = array(); // Initializing
1520
1521 // Loop through defined attribute data options (terms values)
1522 foreach( $attribute_array['options'] as $option ){
1523 if( term_exists( $option, $taxonomy ) ){
1524 // Save the possible option value for the attribute which will be used for variation later
1525 wp_set_object_terms($post_id, $option, $taxonomy, true );
1526 // Get the term ID
1527 $option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1528 }else{
1529 //wp_set_object_terms($post_id, $option, $taxonomy, true );
1530 //$option_term_ids[] = get_term_by( 'name', $option, $taxonomy )->term_id;
1531 //var_dump($option_term_ids);
1532 }
1533 }
1534 }
1535
1536 // Loop through defined attribute data
1537 $attributes[$taxonomy] = array(
1538 'name' => $taxonomy,
1539 'value' => $option_term_ids, // Need to be term IDs
1540 'position' => $key + 1,
1541 'is_visible' => $attribute_array['visible'],
1542 'is_variation' => $attribute_array['variation'],
1543 'is_taxonomy' => '1'
1544 );
1545 }
1546 // Save the meta entry for product attributes
1547 update_post_meta( $post_id, '_product_attributes', $attributes);
1548
1549 }
1550}
1551
1552function create_product_attribute( $label_name ){
1553 global $wpdb;
1554
1555 $slug = sanitize_title( $label_name );
1556
1557 if ( strlen( $slug ) >= 28 ) {
1558 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 ) );
1559 } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
1560 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 ) );
1561 } elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
1562 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 ) );
1563 }
1564
1565 $data = array(
1566 'attribute_label' => $label_name,
1567 'attribute_name' => $slug,
1568 'attribute_type' => 'select',
1569 'attribute_orderby' => 'menu_order',
1570 'attribute_public' => 0, // Enable archives ==> true (or 1)
1571 );
1572
1573 $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );
1574
1575 if ( is_wp_error( $results ) ) {
1576 return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
1577 }
1578
1579 $id = $wpdb->insert_id;
1580
1581 do_action('woocommerce_attribute_added', $id, $data);
1582
1583 wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );
1584
1585 delete_transient('wc_attribute_taxonomies');
1586}
1587
1588/**
1589 * Save a new product attribute from his name (slug).
1590 *
1591 * @since 3.0.0
1592 * @param string $name | The product attribute name (slug).
1593 * @param string $label | The product attribute label (name).
1594 */
1595function save_product_attribute_from_name( $name, $label='', $set=true ){
1596 if( ! function_exists ('get_attribute_id_from_name') ) return;
1597
1598 global $wpdb;
1599
1600 $label = $label == '' ? ucfirst($name) : $label;
1601 $attribute_id = get_attribute_id_from_name( $name );
1602
1603 if( empty($attribute_id) ){
1604 $attribute_id = NULL;
1605 } else {
1606 $set = false;
1607 }
1608 $args = array(
1609 'attribute_id' => $attribute_id,
1610 'attribute_name' => $name,
1611 'attribute_label' => $label,
1612 'attribute_type' => 'select',
1613 'attribute_orderby' => 'menu_order',
1614 'attribute_public' => 0,
1615 );
1616
1617 if( empty($attribute_id) ) {
1618 $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
1619 set_transient( 'wc_attribute_taxonomies', false );
1620 }
1621
1622 if( $set ){
1623 $attributes = wc_get_attribute_taxonomies();
1624 $args['attribute_id'] = get_attribute_id_from_name( $name );
1625 $attributes[] = (object) $args;
1626 //print_r($attributes);
1627 set_transient( 'wc_attribute_taxonomies', $attributes );
1628 } else {
1629 return;
1630 }
1631}
1632
1633/**
1634 * Get the product attribute ID from the name.
1635 *
1636 * @since 3.0.0
1637 * @param string $name | The name (slug).
1638 */
1639function get_attribute_id_from_name( $name ){
1640 global $wpdb;
1641 $attribute_id = $wpdb->get_col("SELECT attribute_id
1642 FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
1643 WHERE attribute_name LIKE '$name'");
1644 return reset($attribute_id);
1645}
1646
1647/**
1648 * Create a new variable product (with new attributes if they are).
1649 * (Needed functions:
1650 *
1651 * @since 3.0.0
1652 * @param array $data | The data to insert in the product.
1653 */
1654
1655function create_product_variation( $data ){
1656 if( ! function_exists ('save_product_attribute_from_name') ) return;
1657
1658 $postname = sanitize_title( $data['title'] );
1659 $author = empty( $data['author'] ) ? '1' : $data['author'];
1660
1661 $post_data = array(
1662 'post_author' => $author,
1663 'post_name' => $postname,
1664 'post_title' => $data['title'],
1665 'post_content' => $data['content'],
1666 'post_excerpt' => $data['excerpt'],
1667 'post_status' => 'publish',
1668 'ping_status' => 'closed',
1669 'post_type' => 'product_variation',
1670 'post_parent' => $data['parent_id'],
1671 'guid' => home_url( '/product/'.$postname.'/' ),
1672 );
1673
1674 // Creating the product (post data)
1675 //$product_id = wp_insert_post( );
1676 $result = wp_insert_post( $post_data );
1677
1678 if ( $result && ! is_wp_error( $result ) ) {
1679 $product_id = $result;
1680 // Do something else
1681 var_dump($result);
1682 echo "sucesso";
1683 }else{
1684 echo "erro ao gravar produto variavel";
1685 var_dump($result);
1686 }
1687 // Get an instance of the WC_Product_Variable object and save it
1688 $product = new WC_Product_Variation( $product_id );
1689
1690 ## ---------------------- Other optional data ---------------------- ##
1691 ## (see WC_Product and WC_Product_Variable setters methods)
1692
1693 // THE PRICES (No prices yet as we need to create product variations)
1694
1695 // IMAGES GALLERY
1696 // Prices
1697 if( empty( $data['sale_price'] ) ){
1698 $product->set_price( $data['regular_price'] );
1699 } else {
1700 $product->set_price($data['sale_price'] );
1701 $product->set_sale_price($data['sale_price'] );
1702 }
1703 $variation->set_regular_price($data['regular_price'] );
1704
1705 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
1706 $product->set_gallery_image_ids( $data['gallery_ids'] );
1707
1708 // SKU/*
1709// if( ! empty( $data['sku'] ) )
1710 // $product->set_sku( $data['sku'] );
1711
1712
1713 // STOCK (stock will be managed in variations)
1714 $product->set_stock_quantity($data['stock']); // Set a minimal stock quantity
1715 if($data['manager_stock'] == '0'){
1716 $product->set_manage_stock(false);
1717 }else{
1718 $product->set_manage_stock(true);
1719 }
1720
1721 $product->set_stock_status('');
1722
1723 // Tax class
1724 if( empty( $data['tax_class'] ) )
1725 $product->set_tax_class( $data['tax_class'] );
1726
1727 // WEIGHT
1728 if( ! empty($data['weight']) )
1729 $product->set_weight(''); // weight (reseting)
1730 else
1731 $product->set_weight($data['weight']);
1732
1733 $product->validate_props(); // Check validation
1734
1735 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
1736
1737 $product_attributes = array();
1738
1739 foreach( $data['attributes'] as $key => $terms ){
1740 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
1741 $attr_label = ucfirst($key); // attribute label name
1742 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
1743
1744 // NEW Attributes: Register and save them
1745 if( ! taxonomy_exists( $taxonomy ) )
1746
1747 var_dump(save_product_attribute_from_name( $attr_name, $attr_label ));
1748
1749 $product_attributes[$taxonomy] = array (
1750 'name' => $taxonomy,
1751 'value' => '',
1752 'position' => '',
1753 'is_visible' => 0,
1754 'is_variation' => 1,
1755 'is_taxonomy' => 1
1756 );
1757
1758 foreach( $terms as $value ){
1759 $term_name = ucfirst($value);
1760 $term_slug = sanitize_title($value);
1761
1762 // Check if the Term name exist and if not we create it.
1763 if( ! term_exists( $value, $taxonomy ) )
1764 wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
1765
1766 // Set attribute values
1767 wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
1768 }
1769 }
1770
1771 update_post_meta( $product_id, '_product_attributes', $product_attributes );
1772 $product->save(); // Save the data
1773}
1774
1775function get_product_category($catname){
1776 if($catname == ''){
1777 $catname = "CAMISAS";
1778 }else{
1779 $catnamesub = $catname;
1780 $slug = $catnamesub;
1781 //var_dump($slug);
1782 $productCategory = get_term_by( 'name', $slug, 'product_cat' );
1783
1784 //echo "termo Id";
1785 //var_dump($productCategory->term_id);
1786 if($productCategory){
1787 $cat_id = get_term_by('id',$productCategory->term_id , 'product_cat' );
1788 }else{
1789 return false;
1790 }
1791 //$cat_id = get_category($productCategory->term_id);
1792 //echo "cat_id";
1793 //var_dump($cat_id);
1794 }
1795
1796 if(empty($cat_id)) {
1797 //echo "insere um termo se não existir a categoria<br>";
1798 //var_dump($cat_id);
1799 $arg = array( 'description' => $slug, 'parent' => 0 );
1800 $cat_id = wp_insert_term($slug, "product_cat", $arg);
1801 //echo "id inserido da categoria criada<br>";
1802 //var_dump($cat_id);
1803 return $cat_id['term_id'];
1804 }else{
1805 //var_dump("retornando resultado existindo uma categoria correspondente");
1806 return $cat_id->term_id;
1807 }
1808}
1809/**
1810 * Update a new variable product (with new attributes if they are).
1811 * (Needed functions:
1812 *
1813 * @since 3.0.0
1814 * @param array $data | The data to insert in the product.
1815 */
1816function update_product_variation($data){
1817 if( ! function_exists ('save_product_attribute_from_name') ) return;
1818
1819 $category_id = get_product_category($data['category']);
1820 $postname = sanitize_title( $data['title'] );
1821 $author = empty( $data['author'] ) ? '1' : $data['author'];
1822
1823 if(empty($data['excerpt'])){
1824 $data['excerpt'] = $postname;
1825 }
1826
1827
1828 if(empty($data['ID'])){
1829
1830 $post_data = array(
1831 'post_author' => $author,
1832 'post_name' => $postname,
1833 'post_title' => $data['title'],
1834 'post_content' => $data['content'],
1835 'post_excerpt' => $data['excerpt'],
1836 'post_status' => 'publish',
1837 'ping_status' => 'closed',
1838 'post_type' => 'product',
1839 'guid' => home_url( '/product/'.$postname.'/') ,
1840 'tax_input' => ['product_cat' => $category_id]
1841 );
1842
1843 $product_id = wp_insert_post( $post_data );
1844 //wp_set_post_terms($product_id, get_term()->slug,'product_cat',true);
1845 }else{
1846
1847 if(!isset($data['insert_variable_product_unique'])){
1848 $post_data = array(
1849 'ID' => $data['ID'],
1850 'post_name' => $postname,
1851 'post_title' => $data['title'],
1852 'ping_status' => 'closed',
1853 'post_type' => 'product',
1854 'guid' => home_url( '/product/'.$postname.'/' )
1855 );
1856 $product_id = wp_update_post( $post_data );
1857 }
1858
1859 }
1860
1861 $product = new WC_Product_Variable( $product_id );
1862 $product->save();
1863
1864 ## ---------------------- Other optional data ---------------------- ##
1865 ## (see WC_Product and WC_Product_Variable setters methods)
1866
1867 //THE PRICES (No prices yet as we need to create product variations)
1868 //IMAGES GALLERY
1869 if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
1870 $product->set_gallery_image_ids( $data['gallery_ids'] );
1871
1872 //SKU
1873 if( ! empty( $data['sku'] ) )
1874 $product->set_sku( $data['sku'] );
1875
1876 // STOCK (stock will be managed in variations)
1877 $product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
1878 if($data['manager_stock'] == '0'){
1879 $product->set_manage_stock(false);
1880 }else{
1881 $product->set_manage_stock(true);
1882 }
1883
1884 $product->set_stock_status('');
1885
1886 // Tax class
1887 if( empty( $data['tax_class'] ) )
1888 $product->set_tax_class( $data['tax_class'] );
1889
1890 // WEIGHT
1891 if( ! empty($data['weight']) )
1892 $product->set_weight(''); // weight (reseting)
1893 else
1894 $product->set_weight($data['weight']);
1895
1896 //length
1897 if( ! empty($data['length']) )
1898 $product->set_length(''); // length (reseting)
1899 else
1900 $product->set_length($data['length']);
1901
1902 $product->validate_props(); // Check validation
1903
1904 //WIDTH
1905 if( ! empty($data['width']) )
1906 $product->set_width(""); // weight (reseting)
1907else
1908 $product->set_width($data['width']);
1909
1910 ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
1911
1912 $product_attributes = array();
1913 echo "Atributes da persistência do Objeto (não da variação)";
1914 var_dump($data['attributes']);
1915
1916 foreach( $data['attributes'] as $key => $terms ){
1917 $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
1918 $attr_label = ucfirst($key); // attribute label name
1919 $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
1920
1921 // NEW Attributes: Register and save them
1922 if( ! taxonomy_exists( $taxonomy ) )
1923 echo "salvando taxonomia: name:{$attr_name}, label:{$attr_label}, tax:{$taxonomy} <br>";
1924 var_dump(save_product_attribute_from_name( $attr_name, $attr_label ));
1925 //$slug = 'pa_' . strtolower($attribute->name);
1926 $attribute_id = wc_create_attribute( array(
1927 'name' => $attr_label,
1928 'slug' => $attr_name,
1929 'type' => 'product',
1930 'order_by' => 'menu_order',
1931 'has_archives' => false,
1932 ) );
1933
1934 var_dump($attribute_id);
1935 //Register it as a wordpress taxonomy for just this session. Later on this will be loaded from the woocommerce taxonomy table.
1936 /*register_taxonomy(
1937 $taxonomy,
1938 apply_filters( 'woocommerce_taxonomy_objects_' . $taxonomy, array( 'product' ) ),
1939 apply_filters( 'woocommerce_taxonomy_args_' . $taxonomy, array(
1940 'labels' => array(
1941 'name' => $attr_label,
1942 ),
1943 'hierarchical' => true,
1944 'show_ui' => false,
1945 'query_var' => true,
1946 'rewrite' => false,
1947 ) )
1948 );*/
1949
1950
1951 $product_attributes[$taxonomy] = array (
1952 'name' => $taxonomy,
1953 'value' => '',
1954 'position' => '',
1955 'is_visible' => 0,
1956 'is_variation' => 1,
1957 'is_taxonomy' => 1
1958 );
1959
1960 foreach( $terms as $value ){
1961 $term_name = ucfirst($value);
1962 $term_slug = sanitize_title($value);
1963
1964 // Check if the Term name exist and if not we create it.
1965 if( ! term_exists( $value, $taxonomy ) )
1966 echo "salvando termo: term_name:{$term_name} | tax:{$taxonomy} | slug:{$term_slug}<br>";
1967 var_dump(wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) )); // Create the term
1968
1969 // Set attribute values
1970 if(isset($data['insert_variable_product_unique'])){
1971 echo "setando valores dos atributos: id:{$data['ID']}(atualizando), tax:{$taxonomy}, term_name:{$term_name}<br>";
1972 var_dump(wp_set_post_terms( $data['ID'], $term_name, $taxonomy, true ));
1973 }else{
1974 echo "setando valores dos atributos: id:{$product_id}(inserindo), tax:{$taxonomy}, term_name:{$term_name}<br>";
1975 var_dump(wp_set_post_terms( $product_id, $term_name, $taxonomy, true ));
1976 }
1977
1978 }
1979 }
1980 //print_r($product);
1981 if(isset($data['insert_variable_product_unique'])){
1982 echo "atualizando: product Attrb: {$product_attributes}<br>";
1983 update_post_meta( $data['ID'], '_product_attributes', $product_attributes );
1984 }else{
1985 echo "inserindo: product Attrb:<br>";
1986 var_dump($product_attributes);
1987 update_post_meta( $product_id, '_product_attributes', $product_attributes );
1988 }
1989 //var_dump($product);
1990 //exit;
1991 $product->save(); // Save the data
1992 return $product_id;
1993}
1994/*
1995*
1996$parent_id = 746; // Or get the variable product id dynamically
1997
1998// The variation data
1999$variation_data = array(
2000 'attributes' => array(
2001 'size' => 'M',
2002 'color' => 'Green',
2003 ),
2004 'sku' => '',
2005 'regular_price' => '22.00',
2006 'sale_price' => '',
2007 'stock_qty' => 10,
2008);
2009
2010// The function to be run
2011create_product_variation( $parent_id, $variation_data );
2012*/
2013/**
2014 * Create a product variation for a defined variable product ID.
2015 *
2016 * @since 3.0.0
2017 * @param int $product_id | Post ID of the product parent variable product.
2018 * @param array $variation_data | The data to insert in the product.
2019 */
2020
2021function _create_product_variation( $product_id, $variation_data ){
2022 // Get the Variable product object (parent)
2023 $product = wc_get_product($product_id);
2024
2025 // Creating the product variation
2026 if(empty($variation_data['update'])){
2027 //var_dump($variation_data);
2028 $variation_post = array(
2029 'post_title' => MigrationRules::getProductTeste()->produtoNome,
2030 'post_name' => 'product-'. MigrationRules::getPostId() .'-variation',
2031 'post_status' => 'publish',
2032 'post_parent' => MigrationRules::getPostId(),
2033 'post_type' => 'product_variation',
2034 'guid' => site_url() . "/" . MigrationRules::getPostId()
2035 );
2036
2037 $variation_id = wp_insert_post( $variation_post );
2038 }else{
2039
2040 $variation_post = array(
2041 'ID' => $variation_data['ID'],
2042 'post_title' => $product->get_name(),
2043 'post_name' => 'product-'.$product_id.'-variation',
2044 'post_status' => 'publish',
2045 'post_parent' => $product_id,
2046 'post_type' => 'product_variation',
2047 'guid' => $product->get_permalink()
2048 );
2049
2050 $variation_id = wp_update_post( $variation_post );
2051 }
2052
2053
2054
2055 // Get an instance of the WC_Product_Variation object
2056 $variation = new WC_Product_Variation( $variation_id );
2057 //var_dump($variation_id);
2058 //exit;
2059 echo "Registrando taxonomia<br>";
2060 var_dump($variation_data['attributes']);
2061
2062 foreach ($variation_data['attributes'] as $attribute => $term_name )
2063 {
2064
2065 $taxonomy = 'pa_'.$attribute; // The attribute taxonomy
2066
2067 echo "taxonomia problemática: {$taxonomy}<br>";
2068
2069 // If taxonomy doesn't exists we create it (Thanks to Carl F. Corneil)
2070 if( ! taxonomy_exists( $taxonomy ) ){
2071 echo "Registrando taxonomia : {$attribute}<br>";
2072 register_taxonomy(
2073 $taxonomy,
2074 'product_variation',
2075 array(
2076 'hierarchical' => false,
2077 'label' => ucfirst( $attribute ),
2078 'query_var' => true,
2079 'rewrite' => array( 'slug' => sanitize_title($attribute) ), // The base slug
2080 )
2081 );
2082 }
2083
2084 $ntax = ucfirst( $attribute );
2085 echo "taxonomia com ucfirst: {$ntax}<br>";
2086 echo "nome do termo";
2087 var_dump($term_name);
2088
2089 // Check if the Term name exist and if not we create it.
2090 if( ! term_exists( $term_name, $taxonomy ) )
2091 echo "TERMO INSERIDO {$term_name}<br> ";
2092 var_dump(wp_insert_term( $term_name, $taxonomy )); // Create the term
2093
2094 $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get the term slug
2095
2096 // Get the post Terms names from the parent variable product.
2097 $post_term_names = wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
2098
2099 // Check if the post term exist and if not we set it in the parent variable product.
2100 if( ! in_array( $term_name, $post_term_names ) )
2101 echo "wp_set_post_terms: nome do slug {$term_slug} | productId:{$product_id} | term_name:{$term_name} | tax:{$taxonomy}<br>";
2102 var_dump(wp_set_post_terms( $product_id, $term_name, $taxonomy, true ));
2103
2104 //var_dump($term_slug);
2105 // Set/save the attribute data in the product variation
2106 echo "update_post_meta: variation_id: [{$variation_id}] - " . 'attribute_'.$taxonomy . "<br>";
2107 var_dump(update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug, true));
2108 }
2109
2110 ## Set/save all other data
2111
2112
2113 // SKU
2114 //if( ! empty( $variation_data['sku'] ) )
2115 // $variation->set_sku( $variation_data['sku'] );
2116
2117 // Prices
2118// Prices
2119echo "<h4>valores do preço promocional</h4><br>";
2120var_dump($variation_data['sale_price'] == "0,00");
2121var_dump($variation_data['sale_price']);
2122
2123if( empty( $variation_data['sale_price'] ) ){
2124
2125 $variation->set_price( $variation_data['regular_price'] );
2126} else {
2127 if(!$variation_data['sale_price'] == "0,00"){
2128 $variation->set_sale_price( $variation_data['sale_price']);
2129 }
2130 $variation->set_price($variation_data['regular_price']);
2131}
2132$variation->set_regular_price( $variation_data['regular_price'] );
2133
2134 // Stock
2135 var_dump($variation_data['stock_qty']);
2136 if( ! empty($variation_data['stock_qty']) ){
2137 $variation->set_stock_quantity( $variation_data['stock_qty'] );
2138 $variation->set_manage_stock(true);
2139 $variation->set_stock_status('');
2140 } else {
2141 //$variation->set_manage_stock(true);
2142 $variation->set_manage_stock(false);
2143 $variation->set_stock_status('outofstock');
2144 }
2145
2146 if($variation_data['stock_qty'] == 0){
2147 $variation->set_manage_stock(false);
2148 $variation->set_stock_status('outofstock');
2149 }
2150 $variation->set_weight(''); // weight (reseting)
2151 //var_dump( $variation_data['ID']);
2152 $variation->save(); // Save the data
2153 //var_dump($variation->get_stock_quantity());
2154 //exit;
2155}
2156
2157function tirarAcentos($string){
2158 return preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/"),explode(" ","a A e E i I o O u U n N"),$string);
2159}
2160
2161/**
2162 * Method to delete Woo Product
2163 *
2164 * @param int $id the product ID.
2165 * @param bool $force true to permanently delete product, false to move to trash.
2166 * @return \WP_Error|boolean
2167 */
2168function wh_deleteProduct($id, $force = FALSE)
2169{
2170 $product = wc_get_product($id);
2171
2172 if(empty($product))
2173 return new WP_Error(999, sprintf(__('No %s is associated with #%d', 'woocommerce'), 'product', $id));
2174
2175 // If we're forcing, then delete permanently.
2176 if ($force)
2177 {
2178 if ($product->is_type('variable'))
2179 {
2180 foreach ($product->get_children() as $child_id)
2181 {
2182 $child = wc_get_product($child_id);
2183 $child->delete(true);
2184 }
2185 }
2186 elseif ($product->is_type('grouped'))
2187 {
2188 foreach ($product->get_children() as $child_id)
2189 {
2190 $child = wc_get_product($child_id);
2191 $child->set_parent_id(0);
2192 $child->save();
2193 }
2194 }
2195
2196 $product->delete(true);
2197 $result = $product->get_id() > 0 ? false : true;
2198 }
2199 else
2200 {
2201 $product->delete();
2202 $result = 'trash' === $product->get_status();
2203 }
2204
2205 if (!$result)
2206 {
2207 return new WP_Error(999, sprintf(__('This %s cannot be deleted', 'woocommerce'), 'product'));
2208 }
2209
2210 // Delete parent product transients.
2211 if ($parent_id = wp_get_post_parent_id($id))
2212 {
2213 wc_delete_product_transients($parent_id);
2214 }
2215 return true;
2216}
2217
2218/**
2219 * Add a widget to the dashboard.
2220 *
2221 * This function is hooked into the 'wp_dashboard_setup' action below.
2222 */
2223function wporg_add_dashboard_widgets() {
2224 wp_add_dashboard_widget(
2225 'wporg_dashboard_widget', // Widget slug.
2226 esc_html__( 'Wiki Importer', 'wporg' ), // Title.
2227 'wporg_dashboard_widget_render' // Display function.
2228 );
2229}
2230add_action( 'wp_dashboard_setup', 'wporg_add_dashboard_widgets' );
2231
2232/**
2233 * Create the function to output the content of our Dashboard Widget.
2234 */
2235function wporg_dashboard_widget_render() {
2236 // Display whatever you want to show.
2237
2238 $html = '<h2>Clique <span style="color:#0099FF" id="importData"><b>aqui</b></span> para importar Dados do ERP Wiki</h2>
2239 <p id="link_produtos">Visualizar Produtos -> <a href="edit.php?post_type=product">aqui</a> </p>
2240 <div id="importBlock">
2241 <img id="importLogo" width="450" height="368" src="https://lindabrand.com.br/wp-content/uploads/importLogo.png"/>
2242 </div>';
2243
2244 $html .= '<script>
2245 jQuery("#link_produtos").hide();
2246 jQuery("#importData").click(function(){
2247
2248 jQuery.ajax({
2249 type: "GET",
2250 url: "admin.php?action=executeWikiImport",
2251 beforeSend: function(){
2252 jQuery("#importLogo").hide();
2253 var img = jQuery("<img />", {
2254 id: "importGif",
2255 src: "https://lindabrand.com.br/wp-content/uploads/import.gif",
2256 width: "420px",
2257 height: "368",
2258 alt: "import"
2259 });
2260
2261 img.appendTo(jQuery("#importBlock"));
2262 },
2263 success: function(){
2264 alert("Dados Importados com sucesso");
2265 jQuery("#importGif").hide();
2266 jQuery("#importLogo").show();
2267 jQuery("#link_produtos").show();
2268 }
2269 });
2270 });
2271
2272 </script>';
2273
2274 echo $html;
2275}
2276
2277
2278
2279//add_action( 'importInitializer', 'executeWikiImport', 10,0);
2280//add_action("after_setup_theme",function(){
2281// do_action('importInitializer');
2282//});
2283
2284add_action( 'init', 'executeWikiImportHome' );
2285function executeWikiImportHome(){
2286 if(isset($_GET['action']) && $_GET['action']=="executeWikiImport"){
2287 initMigration();
2288 //initMigration();
2289 //create curl resource
2290 //$ch = curl_init();
2291 //curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2292 //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2293 //$output = curl_exec($ch);
2294 //curl_close($ch);
2295 }
2296}
2297
2298add_action( 'admin_init', 'executeWikiImport' );
2299function executeWikiImport(){
2300 if(isset($_GET['action']) && $_GET['action']=="executeWikiImport"){
2301 initMigration();
2302 //initMigration();
2303 //create curl resource
2304 //$ch = curl_init();
2305 //curl_setopt($ch, CURLOPT_URL, "http://localhost/favelachick/checkout/order-received/19606/?key=wc_order_1TMRfz22JXnYf");
2306 //curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
2307 //$output = curl_exec($ch);
2308 //curl_close($ch);
2309 }
2310}
2311
2312
2313add_action('woocommerce_thankyou', 'MyPersistRemoteObject3', 20, 2 );
2314function MyPersistRemoteObject3($order_id){
2315
2316 $ch = curl_init();
2317 curl_setopt_array($ch, array(
2318 CURLOPT_URL => "https://lindabrand.com.br/wp-json/wc/v3/orders/" . $order_id . "/?consumer_key=ck_9e747cfe973b52e14180a7c0c84aac41c8e960ec&consumer_secret=cs_225e4823dd0664b95f6030600dfebf8209ded416",
2319 CURLOPT_RETURNTRANSFER => true,
2320 CURLOPT_ENCODING => "",
2321 CURLOPT_MAXREDIRS => 10,
2322 CURLOPT_TIMEOUT => 30,
2323 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2324 CURLOPT_CUSTOMREQUEST => "GET",
2325 CURLOPT_SSL_VERIFYPEER=> false,
2326
2327 CURLOPT_HTTPHEADER => array(
2328 "Authorization: Basic *****************",
2329 "Cache-Control: no-cache"
2330 ),
2331 ));
2332
2333 $result = curl_exec($ch);
2334
2335 $jsonResult = json_decode($result);
2336 foreach($jsonResult->meta_data as $k=>$meta){
2337 if($meta->key == "Tipo de pagamento" && $meta->value == "Boleto"){
2338 $bolVencimento = new stdClass;
2339 $bolVencimento->key = "Boleto Vencimento";
2340 $order = new WC_Order($order_id);
2341 $order_date = $order->order_date;
2342 $date = new DateTime($order_date);
2343 $date->modify("+3 day");
2344 $bolVencimento->value = $date->format("d-m-Y");
2345 $jsonResult->meta_data[] = $bolVencimento;
2346 }
2347 }
2348
2349 $replaced_result = substr_replace(json_encode($jsonResult), '"empresa":460, "guid":"9351c4b5-8c8a-4657-8244-56cb46e5e5d8",', 12,0);
2350
2351 //print_r($replaced_result);
2352 //echo " ";
2353 //print_r(base64_encode($replaced_result));
2354/* $opts = [
2355 'http' => [
2356 'method' => 'GET'
2357 ]
2358 ];*/
2359
2360 //$context = stream_context_create($opts);
2361 //$result = file_get_contents('http://app.wikisistemas.com.br:8086/EcommerceExternoWebservice.asmx/RecebePedidoWooCommerce?json=' . base64_encode($replaced_result), false, $context);
2362 //var_dump($result);
2363
2364 //
2365 //print_r($replaced_result);
2366 $ch2 = curl_init();
2367 curl_setopt_array($ch2, array(
2368 CURLOPT_URL => 'http://52.6.107.225/script.php?pedido=' . base64_encode($replaced_result),
2369 CURLOPT_RETURNTRANSFER => true,
2370 CURLOPT_ENCODING => "",
2371 CURLOPT_MAXREDIRS => 10,
2372 CURLOPT_TIMEOUT => 30,
2373 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
2374 CURLOPT_CUSTOMREQUEST => "GET",
2375 CURLOPT_SSL_VERIFYPEER=> false,
2376
2377 CURLOPT_HTTPHEADER => array(
2378 "Authorization: Basic *****************",
2379 "Cache-Control: no-cache"
2380 ),
2381 ));
2382
2383 $result2 = curl_exec($ch2);
2384 //echo "retorno do WS<br>";
2385 //var_dump($result2);
2386
2387 //echo "pedido base64<br>";
2388 //var_dump($replaced_result);
2389
2390
2391 }
2392
2393
2394 add_filter( 'woocommerce_variation_is_active', 'grey_out_variations_when_out_of_stock', 10, 2 );
2395function grey_out_variations_when_out_of_stock( $grey_out, $variation ){
2396if ( ! $variation->is_in_stock() ){
2397 return false;
2398 }else{
2399 return true;
2400 }
2401}
2402
2403////*/5 * * * * /opt/bitnami/php/bin/php ~/apps/wordpress/htdocs/cron-importer.php