The WooCommerce product class handles individual product data.
Author: WooThemes
Inheritance: extends WC_Product
 function test_varation_save_attributes()
 {
     // Create a variable product with a color attribute.
     $product = new WC_Product_Variable();
     $attribute = new WC_Product_Attribute();
     $attribute->set_id(0);
     $attribute->set_name('color');
     $attribute->set_options(explode(WC_DELIMITER, 'green | red'));
     $attribute->set_visible(true);
     $attribute->set_variation(true);
     $product->set_attributes(array($attribute));
     $product->save();
     // Create a new variation with the color 'green'.
     $variation = new WC_Product_Variation();
     $variation->set_parent_id($product->get_id());
     $variation->set_attributes(array('color' => 'green'));
     $variation->set_status('private');
     $variation->save();
     // Now update some value unrelated to attributes.
     $variation = wc_get_product($variation->get_id());
     $variation->set_status('publish');
     $variation->save();
     // Load up the updated variation and verify that the saved state is correct.
     $loaded_variation = wc_get_product($variation->get_id());
     $this->assertEquals('publish', $loaded_variation->get_status('edit'));
     $_attribute = $loaded_variation->get_attributes('edit');
     $this->assertEquals('green', $_attribute['color']);
 }
 /**
  * Bulk edit
  * @param integer $post_id
  * @param WC_Product $product
  */
 public function bulk_edit_save($post_id, $product)
 {
     $old_regular_price = $product->regular_price;
     $old_sale_price = $product->sale_price;
     // Save fields
     if (!empty($_REQUEST['change_weight']) && isset($_REQUEST['_weight'])) {
         update_post_meta($post_id, '_weight', wc_clean(stripslashes($_REQUEST['_weight'])));
     }
     if (!empty($_REQUEST['change_dimensions'])) {
         if (isset($_REQUEST['_length'])) {
             update_post_meta($post_id, '_length', wc_clean(stripslashes($_REQUEST['_length'])));
         }
         if (isset($_REQUEST['_width'])) {
             update_post_meta($post_id, '_width', wc_clean(stripslashes($_REQUEST['_width'])));
         }
         if (isset($_REQUEST['_height'])) {
             update_post_meta($post_id, '_height', wc_clean(stripslashes($_REQUEST['_height'])));
         }
     }
     if (!empty($_REQUEST['_tax_status'])) {
         update_post_meta($post_id, '_tax_status', wc_clean($_REQUEST['_tax_status']));
     }
     if (!empty($_REQUEST['_tax_class'])) {
         $tax_class = wc_clean($_REQUEST['_tax_class']);
         if ('standard' == $tax_class) {
             $tax_class = '';
         }
         update_post_meta($post_id, '_tax_class', $tax_class);
     }
     if (!empty($_REQUEST['_stock_status'])) {
         $stock_status = wc_clean($_REQUEST['_stock_status']);
         if ($product->is_type('variable')) {
             foreach ($product->get_children() as $child_id) {
                 if ('yes' !== get_post_meta($child_id, '_manage_stock', true)) {
                     wc_update_product_stock_status($child_id, $stock_status);
                 }
             }
             WC_Product_Variable::sync_stock_status($post_id);
         } else {
             wc_update_product_stock_status($post_id, $stock_status);
         }
     }
     if (!empty($_REQUEST['_shipping_class'])) {
         $shipping_class = '_no_shipping_class' == $_REQUEST['_shipping_class'] ? '' : wc_clean($_REQUEST['_shipping_class']);
         wp_set_object_terms($post_id, $shipping_class, 'product_shipping_class');
     }
     if (!empty($_REQUEST['_visibility'])) {
         if (update_post_meta($post_id, '_visibility', wc_clean($_REQUEST['_visibility']))) {
             do_action('woocommerce_product_set_visibility', $post_id, wc_clean($_REQUEST['_visibility']));
         }
     }
     if (!empty($_REQUEST['_featured'])) {
         if (update_post_meta($post_id, '_featured', stripslashes($_REQUEST['_featured']))) {
             delete_transient('wc_featured_products');
         }
     }
     // Sold Individually
     if (!empty($_REQUEST['_sold_individually'])) {
         if ($_REQUEST['_sold_individually'] == 'yes') {
             update_post_meta($post_id, '_sold_individually', 'yes');
         } else {
             update_post_meta($post_id, '_sold_individually', '');
         }
     }
     // Handle price - remove dates and set to lowest
     if ($product->is_type('simple') || $product->is_type('external')) {
         $price_changed = false;
         if (!empty($_REQUEST['change_regular_price'])) {
             $change_regular_price = absint($_REQUEST['change_regular_price']);
             $regular_price = esc_attr(stripslashes($_REQUEST['_regular_price']));
             switch ($change_regular_price) {
                 case 1:
                     $new_price = $regular_price;
                     break;
                 case 2:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = $old_regular_price + round($old_regular_price * $percent, wc_get_price_decimals());
                     } else {
                         $new_price = $old_regular_price + $regular_price;
                     }
                     break;
                 case 3:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = max(0, $old_regular_price - round($old_regular_price * $percent, wc_get_price_decimals()));
                     } else {
                         $new_price = max(0, $old_regular_price - $regular_price);
                     }
                     break;
                 default:
                     break;
             }
             if (isset($new_price) && $new_price != $old_regular_price) {
                 $price_changed = true;
                 $new_price = round($new_price, wc_get_price_decimals());
                 update_post_meta($post_id, '_regular_price', $new_price);
                 $product->regular_price = $new_price;
             }
         }
         if (!empty($_REQUEST['change_sale_price'])) {
             $change_sale_price = absint($_REQUEST['change_sale_price']);
             $sale_price = esc_attr(stripslashes($_REQUEST['_sale_price']));
             switch ($change_sale_price) {
                 case 1:
                     $new_price = $sale_price;
                     break;
                 case 2:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = $old_sale_price + $old_sale_price * $percent;
                     } else {
                         $new_price = $old_sale_price + $sale_price;
                     }
                     break;
                 case 3:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = max(0, $old_sale_price - $old_sale_price * $percent);
                     } else {
                         $new_price = max(0, $old_sale_price - $sale_price);
                     }
                     break;
                 case 4:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = max(0, $product->regular_price - $product->regular_price * $percent);
                     } else {
                         $new_price = max(0, $product->regular_price - $sale_price);
                     }
                     break;
                 default:
                     break;
             }
             if (isset($new_price) && $new_price != $old_sale_price) {
                 $price_changed = true;
                 $new_price = !empty($new_price) || '0' === $new_price ? round($new_price, wc_get_price_decimals()) : '';
                 update_post_meta($post_id, '_sale_price', $new_price);
                 $product->sale_price = $new_price;
             }
         }
         if ($price_changed) {
             update_post_meta($post_id, '_sale_price_dates_from', '');
             update_post_meta($post_id, '_sale_price_dates_to', '');
             if ($product->regular_price < $product->sale_price) {
                 $product->sale_price = '';
                 update_post_meta($post_id, '_sale_price', '');
             }
             if ($product->sale_price) {
                 update_post_meta($post_id, '_price', $product->sale_price);
             } else {
                 update_post_meta($post_id, '_price', $product->regular_price);
             }
         }
     }
     // Handle stock
     if (!$product->is_type('grouped')) {
         if (!empty($_REQUEST['change_stock'])) {
             update_post_meta($post_id, '_manage_stock', 'yes');
             wc_update_product_stock($post_id, wc_stock_amount($_REQUEST['_stock']));
         }
         if (!empty($_REQUEST['_manage_stock'])) {
             if ($_REQUEST['_manage_stock'] == 'yes') {
                 update_post_meta($post_id, '_manage_stock', 'yes');
             } else {
                 update_post_meta($post_id, '_manage_stock', 'no');
                 wc_update_product_stock($post_id, 0);
             }
         }
         if (!empty($_REQUEST['_backorders'])) {
             update_post_meta($post_id, '_backorders', wc_clean($_REQUEST['_backorders']));
         }
     }
     do_action('woocommerce_product_bulk_edit_save', $product);
 }
 /**
  * Use it to avoid repeated get_child calls for the same variation.
  *
  * @param  int                   $variation_id
  * @param  WC_Product_Variable   $product
  * @return WC_Product_Variation
  */
 function get_variation($variation_id, $product)
 {
     if (isset($this->variations_cache[$variation_id])) {
         return $this->variations_cache[$variation_id];
     }
     $variation = $product->get_child($variation_id, array('parent_id' => $product->id, 'parent' => $product));
     $this->variations_cache[$variation_id] = $variation;
     return $variation;
 }
 /**
  * Create a variable registration product object.
  *
  * @access public
  * @param mixed $product
  */
 public function __construct($product)
 {
     parent::__construct($product);
     $this->parent_product_type = $this->product_type;
     $this->product_type = 'registrations';
     add_filter('woocommerce_add_to_cart_handler', array(&$this, 'add_to_cart_handler'), 10, 2);
 }
 public function __get($key)
 {
     if ('variable_tour' == $key) {
         $value = get_post_meta($this->id, '_' . $key, true);
         return $this->variable_tour = $value ? $value : 'no';
     } else {
         return parent::__get($key);
     }
 }
Exemple #6
0
 /**
  * Handle variation duplicate
  *
  * @return boolean false if the from product contains no variatoins
  */
 public function duplicate()
 {
     $fromVariation = $this->from->get_available_variations();
     if (empty($fromVariation)) {
         return false;
     }
     if ($this->to->id === $this->from->id) {
         /*
          * In such a case just add the duplicate meta key
          */
         foreach ($fromVariation as $variation) {
             if (!metadata_exists('post', $variation['variation_id'], self::DUPLICATE_KEY)) {
                 update_post_meta($variation['variation_id'], self::DUPLICATE_KEY, $variation['variation_id']);
             }
         }
     } else {
         /* This could be a very long operation */
         set_time_limit(0);
         foreach ($fromVariation as $variation) {
             /*
              * First we check if the "to" product contains the duplicate meta
              * key to find out if we have to update or insert
              */
             $posts = get_posts(array('meta_key' => self::DUPLICATE_KEY, 'meta_value' => $variation['variation_id'], 'post_type' => 'product_variation', 'post_parent' => $this->to->id));
             switch (count($posts)) {
                 case 1:
                     // update
                     $this->update(wc_get_product($variation['variation_id']), $posts[0], $variation);
                     break;
                 case 0:
                     // insert
                     $this->insert(wc_get_product($variation['variation_id']), $variation);
                     break;
                 default:
                     // we can not handle, something wrong here
                     break;
             }
         }
         /* Restore original timeout */
         set_time_limit(ini_get('max_execution_time'));
     }
 }
 /**
  * Add woo attributes to a custom field with the same name
  *
  * @param $custom_fields
  * @param $post_id
  *
  * @return mixed
  */
 public function filter_custom_fields($custom_fields, $post_id)
 {
     if (!isset($custom_fields)) {
         $custom_fields = array();
     }
     // Get the product correponding to this post
     $product = wc_get_product($post_id);
     if (false === $product) {
         // Not a product
         return $custom_fields;
     }
     switch ($product->get_type()) {
         case self::PRODUCT_TYPE_VARIABLE:
             $product_variable = new WC_Product_Variable($product);
             foreach ($product_variable->get_available_variations() as $variation_array) {
                 foreach ($variation_array['attributes'] as $attribute_name => $attribute_value) {
                     if (!isset($custom_fields[$attribute_name])) {
                         $custom_fields[$attribute_name] = array();
                     }
                     if (!in_array($attribute_value, $custom_fields[$attribute_name], true)) {
                         array_push($custom_fields[$attribute_name], $attribute_value);
                     }
                 }
             }
             break;
         default:
             foreach ($product->get_attributes() as $attribute) {
                 //$terms = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) );
                 // Remove the eventual 'pa_' prefix from the global attribute name
                 $attribute_name = $attribute['name'];
                 if (substr($attribute_name, 0, 3) === 'pa_') {
                     $attribute_name = substr($attribute_name, 3, strlen($attribute_name));
                 }
                 $custom_fields[$attribute_name] = explode(',', $product->get_attribute($attribute['name']));
             }
             break;
     }
     return $custom_fields;
 }
function wcva_return_displaytype_number($product, $post)
{
    $displaytypenumber = 0;
    $product = get_product($post->ID);
    $_coloredvariables = get_post_meta($product->id, '_coloredvariables', true);
    $displaytype = "none";
    if ($product->product_type == 'variable') {
        $product = new WC_Product_Variable($post->ID);
        $attributes = $product->get_variation_attributes();
    }
    if (!empty($attributes) && sizeof($attributes) > 0) {
        foreach ($attributes as $key => $values) {
            if (isset($_coloredvariables[$key]['display_type'])) {
                $displaytype = $_coloredvariables[$key]['display_type'];
            }
            if ($displaytype == "colororimage" || $displaytype == "radio") {
                $displaytypenumber++;
            }
        }
    }
    return $displaytypenumber;
}
 /**
  * Maybe display pricing table or anchor to display pricing table in modal
  * 
  * @access public
  * @return void
  */
 public function product_page_pricing_table()
 {
     if ($this->opt['settings']['display_table'] == 'hide' && (!isset($this->opt['settings']['display_offers']) || $this->opt['settings']['display_offers'] == 'hide')) {
         return;
     }
     global $product;
     if (!$product) {
         return;
     }
     // Load required classes
     require_once RP_WCDPD_PLUGIN_PATH . 'includes/classes/Pricing.php';
     $selected_rule = null;
     // Iterate over pricing rules and use the first one that has this product in conditions (or does not have if condition "not in list")
     if (isset($this->opt['pricing']['sets']) && count($this->opt['pricing']['sets'])) {
         foreach ($this->opt['pricing']['sets'] as $rule_key => $rule) {
             if ($rule['method'] == 'quantity' && ($validated_rule = RP_WCDPD_Pricing::validate_rule($rule))) {
                 if ($validated_rule['selection_method'] == 'all' && $this->user_matches_rule($validated_rule)) {
                     $selected_rule = $validated_rule;
                     break;
                 }
                 if ($validated_rule['selection_method'] == 'categories_include' && count(array_intersect($this->get_product_categories($product->id), $validated_rule['categories'])) > 0 && $this->user_matches_rule($validated_rule)) {
                     $selected_rule = $validated_rule;
                     break;
                 }
                 if ($validated_rule['selection_method'] == 'categories_exclude' && count(array_intersect($this->get_product_categories($product->id), $validated_rule['categories'])) == 0 && $this->user_matches_rule($validated_rule)) {
                     $selected_rule = $validated_rule;
                     break;
                 }
                 if ($validated_rule['selection_method'] == 'products_include' && in_array($product->id, $validated_rule['products']) && $this->user_matches_rule($validated_rule)) {
                     $selected_rule = $validated_rule;
                     break;
                 }
                 if ($validated_rule['selection_method'] == 'products_exclude' && !in_array($product->id, $validated_rule['products']) && $this->user_matches_rule($validated_rule)) {
                     $selected_rule = $validated_rule;
                     break;
                 }
             }
         }
     }
     if (is_array($selected_rule)) {
         // Quantity
         if ($selected_rule['method'] == 'quantity' && in_array($this->opt['settings']['display_table'], array('modal', 'inline')) && isset($selected_rule['pricing'])) {
             if ($product->product_type == 'variable') {
                 $product_variations = $product->get_available_variations();
             }
             // For variable products only - check if prices differ for different variations
             $multiprice_variable_product = false;
             if ($product->product_type == 'variable' && !empty($product_variations)) {
                 $last_product_variation = array_slice($product_variations, -1);
                 $last_product_variation_object = new WC_Product_Variable($last_product_variation[0]['variation_id']);
                 $last_product_variation_price = $last_product_variation_object->get_price();
                 foreach ($product_variations as $variation) {
                     $variation_object = new WC_Product_Variable($variation['variation_id']);
                     if ($variation_object->get_price() != $last_product_variation_price) {
                         $multiprice_variable_product = true;
                     }
                 }
             }
             if ($multiprice_variable_product) {
                 $variation_table_data = array();
                 foreach ($product_variations as $variation) {
                     $variation_product = new WC_Product_Variation($variation['variation_id']);
                     $variation_table_data[$variation['variation_id']] = $this->pricing_table_calculate_adjusted_prices($selected_rule['pricing'], $variation_product->get_price());
                 }
                 require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/frontend/table-variable.php';
             } else {
                 if ($product->product_type == 'variable' && !empty($product_variations)) {
                     $variation_product = new WC_Product_Variation($last_product_variation[0]['variation_id']);
                     $table_data = $this->pricing_table_calculate_adjusted_prices($selected_rule['pricing'], $variation_product->get_price());
                 } else {
                     $table_data = $this->pricing_table_calculate_adjusted_prices($selected_rule['pricing'], $product->get_price());
                 }
                 require_once RP_WCDPD_PLUGIN_PATH . 'includes/views/frontend/table-' . $this->opt['settings']['display_table'] . '-' . $this->opt['settings']['pricing_table_style'] . '.php';
             }
         }
     }
 }
 /**
  * Checks if the store manager has requested the current product be limited to one purchase
  * per customer, and if so, checks whether the customer already has an active subscription to
  * the product.
  *
  * @access public
  * @return bool
  */
 function is_purchasable()
 {
     $purchasable = parent::is_purchasable();
     if (true === $purchasable && 'yes' == $this->limit_subscriptions) {
         if (WC_Subscriptions_Manager::user_has_subscription(0, $this->id, 'active')) {
             $purchasable = false;
         }
     }
     return apply_filters('woocommerce_subscription_is_purchasable', $purchasable, $this);
 }
 public function fixVariableStockStatus()
 {
     // get all parent variations
     $args = array('post_type' => 'product', 'posts_per_page' => -1, 'tax_query' => array(array('taxonomy' => 'product_type', 'field' => 'slug', 'terms' => array('variable'))));
     $query = new WP_Query($args);
     $parent_variations = $query->posts;
     // loop products
     foreach ($parent_variations as $post) {
         // $this->fixVariableStockStatusForProduct( $post->ID );
         WC_Product_Variable::sync_stock_status($post->ID);
     }
 }
 /**
  * Checks if the store manager has requested the current product be limited to one purchase
  * per customer, and if so, checks whether the customer already has an active subscription to
  * the product.
  *
  * @access public
  * @return bool
  */
 function is_purchasable()
 {
     $purchasable = parent::is_purchasable();
     if (true === $purchasable && false === WC_Subscriptions_Product::is_purchasable($purchasable, $this)) {
         $purchasable = false;
     }
     return apply_filters('woocommerce_subscription_is_purchasable', $purchasable, $this);
 }
 /**
  * Sync variable product prices with the children lowest/highest price per
  * unit.
  *
  * Code based on WC_Product_Variable version 2.0.0
  * @see WC_Product_Variable::variable_product_sync()
  * @see WC_Price_Calculator_Product::variable_product_unsync()
  *
  * @since 3.0
  * @param WC_Product_Variable $product the variable product
  * @param WC_Price_Calculator_Settings $settings the calculator settings
  */
 public static function variable_product_sync($product, $settings)
 {
     // save the original values so we can restore the product
     $product->wcmpc_min_variation_price = $product->min_variation_price;
     $product->wcmpc_min_variation_regular_price = $product->min_variation_regular_price;
     $product->wcmpc_min_variation_sale_price = $product->min_variation_sale_price;
     $product->wcmpc_max_variation_price = $product->max_variation_price;
     $product->wcmpc_max_variation_regular_price = $product->max_variation_regular_price;
     $product->wcmpc_max_variation_sale_price = $product->max_variation_sale_price;
     $product->wcmpc_price = $product->price;
     $product->min_variation_price = $product->min_variation_regular_price = $product->min_variation_sale_price = $product->max_variation_price = $product->max_variation_regular_price = $product->max_variation_sale_price = '';
     foreach ($product->get_children() as $variation_product_id) {
         $variation_product = apply_filters('wc_measurement_price_calculator_variable_product_sync', SV_WC_Plugin_Compatibility::wc_get_product($variation_product_id), $product);
         $child_price = $variation_product->price;
         $child_regular_price = $variation_product->regular_price;
         $child_sale_price = $variation_product->sale_price;
         // get the product measurement
         $measurement = self::get_product_measurement($variation_product, $settings);
         $measurement->set_unit($settings->get_pricing_unit());
         if ('' === $child_price && '' === $child_regular_price || !$measurement->get_value()) {
             continue;
         }
         // convert to price per unit
         if ('' !== $child_price) {
             $child_price /= $measurement->get_value();
         }
         // Regular prices
         if ($child_regular_price !== '') {
             // convert to price per unit
             $child_regular_price /= $measurement->get_value();
             if (!is_numeric($product->min_variation_regular_price) || $child_regular_price < $product->min_variation_regular_price) {
                 $product->min_variation_regular_price = $child_regular_price;
             }
             if (!is_numeric($product->max_variation_regular_price) || $child_regular_price > $product->max_variation_regular_price) {
                 $product->max_variation_regular_price = $child_regular_price;
             }
         }
         // Sale prices
         if ($child_sale_price !== '') {
             // convert to price per unit
             $child_sale_price /= $measurement->get_value();
             if ($child_price == $child_sale_price) {
                 if (!is_numeric($product->min_variation_sale_price) || $child_sale_price < $product->min_variation_sale_price) {
                     $product->min_variation_sale_price = $child_sale_price;
                 }
                 if (!is_numeric($product->max_variation_sale_price) || $child_sale_price > $product->max_variation_sale_price) {
                     $product->max_variation_sale_price = $child_sale_price;
                 }
             }
         }
         // Actual prices
         if ($child_price !== '') {
             if ($child_price > $product->max_variation_price) {
                 $product->max_variation_price = $child_price;
             }
             if ($product->min_variation_price === '' || $child_price < $product->min_variation_price) {
                 $product->min_variation_price = $child_price;
             }
         }
     }
     // as seen in WC_Product_Variable::get_price_html()
     $product->price = $product->min_variation_price;
 }
        }
        /* update _price with sale price */
        $rows = $wpdb->get_results($wpdb->prepare("SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_value !='' AND meta_key = %s", $pre_meta_key . '_sale_price'));
        foreach ($rows as $row) {
            update_post_meta($row->post_id, $pre_meta_key . '_price', $row->meta_value);
        }
    }
}
/* rename options regions */
delete_option('_oga_wppbc_countries_groups');
add_option('wc_price_based_country_regions', $regions);
/* sync variable products */
require_once WC()->plugin_path() . '/includes/class-wc-product-variable.php';
$rows = $wpdb->get_results($wpdb->prepare("SELECT distinct post_parent FROM {$wpdb->posts} where post_type = %s", 'product_variation'));
foreach ($rows as $row) {
    WC_Product_Variable::sync($row->post_parent);
}
/* rename and update test options */
add_option('wc_price_based_country_test_mode', get_option('wc_price_based_country_debug_mode'));
delete_option('wc_price_based_country_debug_mode');
$test_ip = get_option('wc_price_based_country_debug_ip');
if ($test_ip) {
    $country = WC_Geolocation::geolocate_ip($test_ip);
    add_option('wc_price_based_country_test_country', $country['country']);
}
delete_option('wc_price_based_country_debug_ip');
/* unschedule geoip donwload */
if (wp_next_scheduled('wcpbc_update_geoip')) {
    wp_clear_scheduled_hook('wcpbc_update_geoip');
}
delete_option('wc_price_based_country_update_geoip');
Exemple #15
0
 function woocomposer_list_shortcode($atts)
 {
     global $woocommerce;
     $img_position = $img_size = $img_border = $border_size = $border_radius = $border_color = $title_font = $price_font = $price_color = $rating_color = $rating_font = $shortcode = '';
     extract(shortcode_atts(array("img_position" => "", "shortcode" => "", "img_size" => "", "img_border" => "", "border_size" => "", "border_radius" => "", "border_color" => "", "title_color" => "", "title_font" => "", "price_font" => "", "price_color" => "", "rating_color" => "", "rating_font" => ""), $atts));
     $output = $on_sale = $style = $title_style = $pricing_style = $rating_style = '';
     if ($img_size !== "") {
         $style .= 'width:' . $img_size . 'px; height:' . $img_size . 'px;';
     }
     if ($title_color !== "") {
         $title_style .= 'color:' . $title_color . ';';
     }
     if ($title_font !== "") {
         $title_style .= 'font-size:' . $title_font . 'px;';
     }
     if ($img_border !== '') {
         $style .= 'border-style:' . $img_border . ';';
         if ($border_size !== '') {
             $style .= 'border-width:' . $border_size . 'px;';
         }
         if ($border_color !== '') {
             $style .= 'border-color:' . $border_color . ';';
         }
         if ($border_radius !== '') {
             $style .= 'border-radius:' . $border_radius . 'px;';
         }
     }
     if ($price_font !== "") {
         $pricing_style .= 'font-size:' . $price_font . 'px;';
     }
     if ($price_color !== "") {
         $pricing_style .= 'color:' . $price_color . ';';
     }
     if ($rating_color !== "") {
         $rating_style .= 'color:' . $rating_color . ';';
     }
     if ($rating_font !== "") {
         $rating_style .= 'font-size:' . $rating_font . 'px;';
     }
     $post_count = '12';
     $output .= '<div class="woocomposer_list woocommerce">';
     /* $output .= do_shortcode($content); */
     $pattern = get_shortcode_regex();
     if ($shortcode !== '') {
         $new_shortcode = rawurldecode(base64_decode(strip_tags($shortcode)));
     }
     preg_match_all("/" . $pattern . "/", $new_shortcode, $matches);
     $shortcode_str = str_replace('"', '', str_replace(" ", "&", trim($matches[3][0])));
     $short_atts = parse_str($shortcode_str);
     //explode("&",$shortcode_str);
     if (isset($matches[2][0])) {
         $display_type = $matches[2][0];
     } else {
         $display_type = '';
     }
     if (!isset($columns)) {
         $columns = '4';
     }
     if (isset($per_page)) {
         $post_count = $per_page;
     }
     if (isset($number)) {
         $post_count = $number;
     }
     if (!isset($order)) {
         $order = 'ASC';
     }
     if (!isset($orderby)) {
         $orderby = 'date';
     }
     if (!isset($category)) {
         $category = '';
     }
     if (!isset($ids)) {
         $ids = '';
     }
     if ($ids) {
         $ids = explode(',', $ids);
         $ids = array_map('trim', $ids);
     }
     if ($columns == "2") {
         $columns = 6;
     } elseif ($columns == "3") {
         $columns = 4;
     } elseif ($columns == "4") {
         $columns = 3;
     }
     $meta_query = '';
     if ($display_type == "recent_products") {
         $meta_query = WC()->query->get_meta_query();
     }
     if ($display_type == "featured_products") {
         $meta_query = array(array('key' => '_visibility', 'value' => array('catalog', 'visible'), 'compare' => 'IN'), array('key' => '_featured', 'value' => 'yes'));
     }
     if ($display_type == "top_rated_products") {
         add_filter('posts_clauses', array(WC()->query, 'order_by_rating_post_clauses'));
         $meta_query = WC()->query->get_meta_query();
     }
     $args = array('post_type' => 'product', 'post_status' => 'publish', 'ignore_sticky_posts' => 1, 'posts_per_page' => $post_count, 'orderby' => $orderby, 'order' => $order, 'meta_query' => $meta_query);
     if ($display_type == "sale_products") {
         $product_ids_on_sale = woocommerce_get_product_ids_on_sale();
         $meta_query = array();
         $meta_query[] = $woocommerce->query->visibility_meta_query();
         $meta_query[] = $woocommerce->query->stock_status_meta_query();
         $args['meta_query'] = $meta_query;
         $args['post__in'] = $product_ids_on_sale;
     }
     if ($display_type == "best_selling_products") {
         $args['meta_key'] = 'total_sales';
         $args['orderby'] = 'meta_value_num';
         $args['meta_query'] = array(array('key' => '_visibility', 'value' => array('catalog', 'visible'), 'compare' => 'IN'));
     }
     if ($display_type == "product_category") {
         $args['tax_query'] = array(array('taxonomy' => 'product_cat', 'terms' => array(esc_attr($category)), 'field' => 'slug', 'operator' => 'IN'));
     }
     if ($display_type == "product_categories") {
         $args['tax_query'] = array(array('taxonomy' => 'product_cat', 'terms' => $ids, 'field' => 'term_id', 'operator' => 'IN'));
     }
     $query = new WP_Query($args);
     $output .= '<ul class="wcmp-product-list wcmp-img-' . $img_position . ' ' . $order . '">';
     if ($query->have_posts()) {
         while ($query->have_posts()) {
             $query->the_post();
             $product_id = get_the_ID();
             $post = get_post($product_id);
             $product_title = get_the_title();
             $product = new WC_Product($product_id);
             $attachment_ids = $product->get_gallery_attachment_ids();
             $price = $product->get_price_html();
             $rating = $product->get_rating_html();
             $product_var = new WC_Product_Variable($product_id);
             $available_variations = $product_var->get_available_variations();
             $output .= '<li>';
             $output .= '<a href="' . get_permalink($product_id) . '">';
             $product_img = wp_get_attachment_image_src(get_post_thumbnail_id($product_id), 'full');
             $output .= '<img style="' . $style . '" src="' . $product_img[0] . '"/>';
             $output .= '<span style="' . $title_style . '">' . $product_title . '</span>';
             $output .= '</a>';
             if ($display_type == "top_rated_products") {
                 $output .= '<div style="' . $rating_style . '">' . $rating . '</div>';
             }
             $output .= '<span class="amount" style="' . $pricing_style . '">' . $price . '</span>';
             $output .= '</li>';
         }
     }
     $output .= "\n" . '</ul>';
     $output .= "\n" . '</div>';
     if ($display_type == "top_rated_products") {
         remove_filter('posts_clauses', array(WC()->query, 'order_by_rating_post_clauses'));
     }
     wp_reset_postdata();
     return $output;
 }
 /**
  * set_stock_status function.
  */
 public function set_stock_status($status)
 {
     $status = 'outofstock' === $status ? 'outofstock' : 'instock';
     // Sanity check
     if (true === $this->managing_stock()) {
         if (!$this->backorders_allowed() && $this->get_stock_quantity() <= get_option('woocommerce_notify_no_stock_amount')) {
             $status = 'outofstock';
         }
     } elseif ('parent' === $this->managing_stock()) {
         if (!$this->parent->backorders_allowed() && $this->parent->get_stock_quantity() <= get_option('woocommerce_notify_no_stock_amount')) {
             $status = 'outofstock';
         }
     }
     if (update_post_meta($this->variation_id, '_stock_status', $status)) {
         do_action('woocommerce_variation_set_stock_status', $this->variation_id, $status);
         if (true === $this->managing_stock()) {
             WC_Product_Variable::sync_stock_status($this->id);
         }
     }
 }
 /**
  * Edit a product
  *
  * @since 2.2
  * @param int $id the product ID
  * @param array $data
  * @return array
  */
 public function edit_product($id, $data)
 {
     try {
         if (!isset($data['product'])) {
             throw new WC_API_Exception('woocommerce_api_missing_product_data', sprintf(__('No %1$s data specified to edit %1$s', 'woocommerce'), 'product'), 400);
         }
         $data = $data['product'];
         $id = $this->validate_request($id, 'product', 'edit');
         if (is_wp_error($id)) {
             return $id;
         }
         $product = wc_get_product($id);
         $data = apply_filters('woocommerce_api_edit_product_data', $data, $this);
         // Product title.
         if (isset($data['title'])) {
             $product->set_name(wc_clean($data['title']));
         }
         // Product name (slug).
         if (isset($data['name'])) {
             $product->set_slug(wc_clean($data['name']));
         }
         // Product status.
         if (isset($data['status'])) {
             $product->set_status(wc_clean($data['status']));
         }
         // Product short description.
         if (isset($data['short_description'])) {
             // Enable short description html tags.
             $post_excerpt = isset($data['enable_html_short_description']) && true === $data['enable_html_short_description'] ? $data['short_description'] : wc_clean($data['short_description']);
             $product->set_short_description($post_excerpt);
         }
         // Product description.
         if (isset($data['description'])) {
             // Enable description html tags.
             $post_content = isset($data['enable_html_description']) && true === $data['enable_html_description'] ? $data['description'] : wc_clean($data['description']);
             $product->set_description($post_content);
         }
         // Validate the product type.
         if (isset($data['type']) && !in_array(wc_clean($data['type']), array_keys(wc_get_product_types()))) {
             throw new WC_API_Exception('woocommerce_api_invalid_product_type', sprintf(__('Invalid product type - the product type must be any of these: %s', 'woocommerce'), implode(', ', array_keys(wc_get_product_types()))), 400);
         }
         // Check for featured/gallery images, upload it and set it.
         if (isset($data['images'])) {
             $product = $this->save_product_images($product, $data['images']);
         }
         // Save product meta fields.
         $product = $this->save_product_meta($product, $data);
         // Save variations.
         if ($product->is_type('variable')) {
             if (isset($data['variations']) && is_array($data['variations'])) {
                 $this->save_variations($product, $data);
             } else {
                 // Just sync variations.
                 $product = WC_Product_Variable::sync($product, false);
             }
         }
         $product->save();
         do_action('woocommerce_api_edit_product', $id, $data);
         // Clear cache/transients.
         wc_delete_product_transients($id);
         return $this->get_product($id);
     } catch (WC_Data_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     } catch (WC_API_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }
Exemple #18
0
 private function get_product_from_post($post_id)
 {
     $woocommerce_ver_below_2_1 = false;
     if (version_compare(WOOCOMMERCE_VERSION, '2.1', '<')) {
         $woocommerce_ver_below_2_1 = true;
     }
     if ($woocommerce_ver_below_2_1) {
         $product = new WC_Product_Simple($post_id);
     } else {
         $product = new WC_Product($post_id);
     }
     //$post_categories = wp_get_post_categories( $post_id );
     //$categories = get_the_category();
     try {
         $thumbnail = $product->get_image();
         if ($thumbnail) {
             if (preg_match('/data-lazy-src="([^\\"]+)"/s', $thumbnail, $match)) {
                 $thumbnail = $match[1];
             } else {
                 if (preg_match('/data-lazy-original="([^\\"]+)"/s', $thumbnail, $match)) {
                     $thumbnail = $match[1];
                 } else {
                     if (preg_match('/lazy-src="([^\\"]+)"/s', $thumbnail, $match)) {
                         // Animate Lazy Load Wordpress Plugin
                         $thumbnail = $match[1];
                     } else {
                         if (preg_match('/data-echo="([^\\"]+)"/s', $thumbnail, $match)) {
                             $thumbnail = $match[1];
                         } else {
                             preg_match('/<img(.*)src(.*)=(.*)"(.*)"/U', $thumbnail, $result);
                             $thumbnail = array_pop($result);
                         }
                     }
                 }
             }
         }
     } catch (Exception $e) {
         $err_msg = "exception raised in thumbnails";
         self::send_error_report($err_msg);
         $thumbnail = '';
     }
     // handling scheduled sale price update
     if (!$woocommerce_ver_below_2_1) {
         $sale_price_dates_from = get_post_meta($post_id, '_sale_price_dates_from', true);
         $sale_price_dates_to = get_post_meta($post_id, '_sale_price_dates_to', true);
         if ($sale_price_dates_from || $sale_price_dates_to) {
             self::schedule_sale_price_update($post_id, null);
         }
         if ($sale_price_dates_from) {
             self::schedule_sale_price_update($post_id, $sale_price_dates_from);
         }
         if ($sale_price_dates_to) {
             self::schedule_sale_price_update($post_id, $sale_price_dates_to);
         }
     }
     $product_tags = array();
     foreach (wp_get_post_terms($post_id, 'product_tag') as $tag) {
         $product_tags[] = $tag->name;
     }
     $product_brands = array();
     if (taxonomy_exists('product_brand')) {
         foreach (wp_get_post_terms($post_id, 'product_brand') as $brand) {
             $product_brands[] = $brand->name;
         }
     }
     $taxonomies = array();
     try {
         $all_taxonomies = get_option('wcis_taxonomies');
         if (is_array($all_taxonomies)) {
             foreach ($all_taxonomies as $taxonomy) {
                 if (taxonomy_exists($taxonomy) && !array_key_exists($taxonomy, $taxonomies)) {
                     foreach (wp_get_post_terms($post_id, $taxonomy) as $taxonomy_value) {
                         if (!array_key_exists($taxonomy, $taxonomies)) {
                             $taxonomies[$taxonomy] = array();
                         }
                         $taxonomies[$taxonomy][] = $taxonomy_value->name;
                     }
                 }
             }
         }
     } catch (Exception $e) {
     }
     $acf_fields = array();
     try {
         if (class_exists('acf') && function_exists('get_field')) {
             $all_acf_fields = get_option('wcis_acf_fields');
             if (is_array($all_acf_fields)) {
                 foreach ($all_acf_fields as $acf_field_name) {
                     $acf_field_value = get_field($acf_field_name, $post_id);
                     if ($acf_field_value) {
                         $acf_fields[$acf_field_name] = $acf_field_value;
                     }
                 }
             }
         }
     } catch (Exception $e) {
     }
     $send_product = array('product_id' => $product->id, 'currency' => get_woocommerce_currency(), 'price' => $product->get_price(), 'url' => get_permalink($product->id), 'thumbnail_url' => $thumbnail, 'action' => 'insert', 'description' => $product->get_post_data()->post_content, 'short_description' => $product->get_post_data()->post_excerpt, 'name' => $product->get_title(), 'sku' => $product->get_sku(), 'categories' => $product->get_categories(), 'tag' => $product_tags, 'store_id' => get_current_blog_id(), 'identifier' => (string) $product->id, 'product_brand' => $product_brands, 'taxonomies' => $taxonomies, 'acf_fields' => $acf_fields, 'sellable' => $product->is_purchasable(), 'visibility' => $product->is_visible(), 'stock_quantity' => $product->get_stock_quantity(), 'is_managing_stock' => $product->managing_stock(), 'is_backorders_allowed' => $product->backorders_allowed(), 'is_purchasable' => $product->is_purchasable(), 'is_in_stock' => $product->is_in_stock(), 'product_status' => get_post_status($post_id));
     try {
         $variable = new WC_Product_Variable($post_id);
         $variations = $variable->get_available_variations();
         $variations_sku = '';
         if (!empty($variations)) {
             foreach ($variations as $variation) {
                 if ($product->get_sku() != $variation['sku']) {
                     $variations_sku .= $variation['sku'] . ' ';
                 }
             }
         }
         $send_product['variations_sku'] = $variations_sku;
         $all_attributes = $product->get_attributes();
         $attributes = array();
         if (!empty($all_attributes)) {
             foreach ($all_attributes as $attr_mame => $value) {
                 if ($all_attributes[$attr_mame]['is_taxonomy']) {
                     if (!$woocommerce_ver_below_2_1) {
                         $attributes[$attr_mame] = wc_get_product_terms($post_id, $attr_mame, array('fields' => 'names'));
                     } else {
                         $attributes[$attr_mame] = woocommerce_get_product_terms($post_id, $attr_mame, 'names');
                     }
                 } else {
                     $attributes[$attr_mame] = $product->get_attribute($attr_mame);
                 }
             }
         }
         $send_product['attributes'] = $attributes;
         $send_product['total_variable_stock'] = $variable->get_total_stock();
         try {
             if (version_compare(WOOCOMMERCE_VERSION, '2.2', '>=')) {
                 if (function_exists('wc_get_product')) {
                     $original_product = wc_get_product($product->id);
                     if (is_object($original_product)) {
                         $send_product['visibility'] = $original_product->is_visible();
                         $send_product['product_type'] = $original_product->product_type;
                     }
                 }
             } else {
                 if (function_exists('get_product')) {
                     $original_product = get_product($product->id);
                     if (is_object($original_product)) {
                         $send_product['visibility'] = $original_product->is_visible();
                         $send_product['product_type'] = $original_product->product_type;
                     }
                 }
             }
         } catch (Exception $e) {
         }
     } catch (Exception $e) {
         $err_msg = "exception raised in attributes";
         self::send_error_report($err_msg);
     }
     if (!$woocommerce_ver_below_2_1) {
         try {
             $send_product['price_compare_at_price'] = $product->get_regular_price();
             $send_product['price_min'] = $variable->get_variation_price('min');
             $send_product['price_max'] = $variable->get_variation_price('max');
             $send_product['price_min_compare_at_price'] = $variable->get_variation_regular_price('min');
             $send_product['price_max_compare_at_price'] = $variable->get_variation_regular_price('max');
         } catch (Exception $e) {
             $send_product['price_compare_at_price'] = null;
             $send_product['price_min'] = null;
             $send_product['price_max'] = null;
             $send_product['price_min_compare_at_price'] = null;
             $send_product['price_max_compare_at_price'] = null;
         }
     } else {
         $send_product['price_compare_at_price'] = null;
         $send_product['price_min'] = null;
         $send_product['price_max'] = null;
         $send_product['price_min_compare_at_price'] = null;
         $send_product['price_max_compare_at_price'] = null;
     }
     $send_product['description'] = self::content_filter_shortcode_with_content($send_product['description']);
     $send_product['short_description'] = self::content_filter_shortcode_with_content($send_product['short_description']);
     $send_product['description'] = self::content_filter_shortcode($send_product['description']);
     $send_product['short_description'] = self::content_filter_shortcode($send_product['short_description']);
     try {
         if (defined('ICL_SITEPRESS_VERSION') && is_plugin_active('woocommerce-multilingual/wpml-woocommerce.php') && function_exists('wpml_get_language_information')) {
             if (version_compare(ICL_SITEPRESS_VERSION, '3.2', '>=')) {
                 $language_info = apply_filters('wpml_post_language_details', NULL, $post_id);
             } else {
                 $language_info = wpml_get_language_information($post_id);
             }
             if ($language_info && is_array($language_info) && array_key_exists('locale', $language_info)) {
                 // WP_Error could be returned from wpml_get_language_information(...)
                 $send_product['lang'] = $language_info['locale'];
             }
         }
     } catch (Exception $e) {
     }
     return $send_product;
 }
    /**
     * Registered callback function for the WordPress Importer
     *
     * Manages the three separate stages of the CSV import process
     */
    public function dispatch()
    {
        global $woocommerce, $wpdb;
        if (!empty($_POST['delimiter'])) {
            $this->delimiter = stripslashes(trim($_POST['delimiter']));
        }
        if (!$this->delimiter) {
            $this->delimiter = ',';
        }
        if (!empty($_POST['merge_empty_cells'])) {
            $this->merge_empty_cells = 1;
        } else {
            $this->merge_empty_cells = 0;
        }
        $step = empty($_GET['step']) ? 0 : (int) $_GET['step'];
        switch ($step) {
            case 0:
                $this->header();
                $this->greet();
                break;
            case 1:
                $this->header();
                check_admin_referer('import-upload');
                if ($this->handle_upload()) {
                    $this->import_options();
                } else {
                    _e('Error with handle_upload!', 'wc_csv_import');
                }
                break;
            case 2:
                $this->header();
                check_admin_referer('import-woocommerce');
                $this->id = (int) $_POST['import_id'];
                if ($this->file_url_import_enabled) {
                    $this->file_url = esc_attr($_POST['import_url']);
                }
                if ($this->id) {
                    $file = get_attached_file($this->id);
                } else {
                    if ($this->file_url_import_enabled) {
                        $file = ABSPATH . $this->file_url;
                    }
                }
                $file = str_replace("\\", "/", $file);
                if ($file) {
                    ?>
					<table id="import-progress" class="widefat_importer widefat">
						<thead>
							<tr>
								<th class="status">&nbsp;</th>
								<th class="row"><?php 
                    _e('Row', 'wc_csv_import');
                    ?>
</th>
								<th><?php 
                    _e('SKU', 'wc_csv_import');
                    ?>
</th>
								<th><?php 
                    _e('Product', 'wc_csv_import');
                    ?>
</th>
								<th class="reason"><?php 
                    _e('Status Msg', 'wc_csv_import');
                    ?>
</th>
							</tr>
						</thead>
						<tfoot>
							<tr class="importer-loading">
								<td colspan="5"></td>
							</tr>
						</tfoot>
						<tbody></tbody>
					</table>
					<script type="text/javascript">
						jQuery(document).ready(function($) {

							if ( ! window.console ) { window.console = function(){}; }

							var processed_terms = [];
							var processed_posts = [];
							var post_orphans    = [];
							var attachments     = [];
							var upsell_skus     = [];
							var crosssell_skus  = [];
							var i               = 1;
							var done_count      = 0;

							function import_rows( start_pos, end_pos ) {

								var data = {
									action: 	'woocommerce_csv_import_request',
									file:       '<?php 
                    echo addslashes($file);
                    ?>
',
									mapping:    '<?php 
                    echo json_encode($_POST['map_to']);
                    ?>
',
									delimiter:  '<?php 
                    echo $this->delimiter;
                    ?>
',
									merge_empty_cells: '<?php 
                    echo $this->merge_empty_cells;
                    ?>
',
									start_pos:  start_pos,
									end_pos:    end_pos,
								};

								return $.ajax({
									url:        '<?php 
                    echo add_query_arg(array('import_page' => $this->import_page, 'step' => '3', 'merge' => !empty($_GET['merge']) ? '1' : '0'), admin_url('admin-ajax.php'));
                    ?>
',
									data:       data,
									type:       'POST',
									success:    function( response ) {
										console.log( response );
										if ( response ) {

											try {
												// Get the valid JSON only from the returned string
												if ( response.indexOf("<!--WC_START-->") >= 0 )
													response = response.split("<!--WC_START-->")[1]; // Strip off before after WC_START

												if ( response.indexOf("<!--WC_END-->") >= 0 )
													response = response.split("<!--WC_END-->")[0]; // Strip off anything after WC_END

												// Parse
												var results = $.parseJSON( response );

												if ( results.error ) {

													$('#import-progress tbody').append( '<tr id="row-' + i + '" class="error"><td class="status" colspan="5">' + results.error + '</td></tr>' );

													i++;

												} else if ( results.import_results && $( results.import_results ).size() > 0 ) {

													$.each( results.processed_terms, function( index, value ) {
														processed_terms.push( value );
													});

													$.each( results.processed_posts, function( index, value ) {
														processed_posts.push( value );
													});

													$.each( results.post_orphans, function( index, value ) {
														post_orphans.push( value );
													});

													$.each( results.attachments, function( index, value ) {
														attachments.push( value );
													});

													upsell_skus    = jQuery.extend( {}, upsell_skus, results.upsell_skus );
													crosssell_skus = jQuery.extend( {}, crosssell_skus, results.crosssell_skus );

													$( results.import_results ).each(function( index, row ) {
														$('#import-progress tbody').append( '<tr id="row-' + i + '" class="' + row['status'] + '"><td><mark class="result" title="' + row['status'] + '">' + row['status'] + '</mark></td><td class="row">' + i + '</td><td>' + row['sku'] + '</td><td>' + row['post_id'] + ' - ' + row['post_title'] + '</td><td class="reason">' + row['reason'] + '</td></tr>' );

														i++;
													});
												}

											} catch(err) {}

										} else {
											$('#import-progress tbody').append( '<tr class="error"><td class="status" colspan="5">' + '<?php 
                    _e('AJAX Error', 'wc_csv_import');
                    ?>
' + '</td></tr>' );
										}

										var w = $(window);
										var row = $( "#row-" + ( i - 1 ) );

										if ( row.length ) {
										    w.scrollTop( row.offset().top - (w.height()/2) );
										}

										done_count++;

										$('body').trigger( 'woocommerce_csv_import_request_complete' );
									}
								});
							}

							var rows = [];

							<?php 
                    $limit = apply_filters('woocommerce_csv_import_limit_per_request', 10);
                    $enc = mb_detect_encoding($file, 'UTF-8, ISO-8859-1', true);
                    if ($enc) {
                        setlocale(LC_ALL, 'en_US.' . $enc);
                    }
                    @ini_set('auto_detect_line_endings', true);
                    $count = 0;
                    $previous_position = 0;
                    $position = 0;
                    $import_count = 0;
                    // Get CSV positions
                    if (($handle = fopen($file, "r")) !== FALSE) {
                        while (($postmeta = fgetcsv($handle, 0, $this->delimiter)) !== FALSE) {
                            $count++;
                            if ($count >= $limit) {
                                $previous_position = $position;
                                $position = ftell($handle);
                                $count = 0;
                                $import_count++;
                                // Import rows between $previous_position $position
                                ?>
rows.push( [ <?php 
                                echo $previous_position;
                                ?>
, <?php 
                                echo $position;
                                ?>
 ] ); <?php 
                            }
                        }
                        // Remainder
                        if ($count > 0) {
                            ?>
rows.push( [ <?php 
                            echo $position;
                            ?>
, '' ] ); <?php 
                            $import_count++;
                        }
                        fclose($handle);
                    }
                    ?>

							var data = rows.shift();
							var regen_count = 0;
							import_rows( data[0], data[1] );

							$('body').on( 'woocommerce_csv_import_request_complete', function() {
								if ( done_count == <?php 
                    echo $import_count;
                    ?>
 ) {

									if ( attachments.length ) {

										$('#import-progress tbody').append( '<tr class="regenerating"><td colspan="5"><div class="progress"></div></td></tr>' );

										index = 0;

										$.each( attachments, function( i, value ) {
											regenerate_thumbnail( value );
											index ++;
											if ( index == attachments.length ) {
												import_done();
											}
										});

									} else {
										import_done();
									}

								} else {
									// Call next request
									data = rows.shift();
									import_rows( data[0], data[1] );
								}
							} );

							// Regenerate a specified image via AJAX
							function regenerate_thumbnail( id ) {
								$.ajax({
									type: 'POST',
									url: ajaxurl,
									data: { action: "woocommerce_csv_import_regenerate_thumbnail", id: id },
									success: function( response ) {
										if ( response !== Object( response ) || ( typeof response.success === "undefined" && typeof response.error === "undefined" ) ) {
											response = new Object;
											response.success = false;
											response.error = "<?php 
                    printf(esc_js(__('The resize request was abnormally terminated (ID %s). This is likely due to the image exceeding available memory or some other type of fatal error.', 'wc_csv_import')), '" + id + "');
                    ?>
";
										}

										regen_count ++;

										$('#import-progress tbody .regenerating .progress').css( 'width', ( ( regen_count / attachments.length ) * 100 ) + '%' ).html( regen_count + ' / ' + attachments.length + ' <?php 
                    echo esc_js(__('thumbnails regenerated', 'wc_csv_import'));
                    ?>
' );

										if ( ! response.success ) {
											$('#import-progress tbody').append( '<tr><td colspan="5">' + response.error + '</td></tr>' );
										}
									},
									error: function( response ) {
										$('#import-progress tbody').append( '<tr><td colspan="5">' + response.error + '</td></tr>' );
									}
								});
							}

							function import_done() {
								var data = {
									action: 'woocommerce_csv_import_request',
									file: '<?php 
                    echo $file;
                    ?>
',
									processed_terms: processed_terms,
									processed_posts: processed_posts,
									post_orphans: post_orphans,
									upsell_skus: upsell_skus,
									crosssell_skus: crosssell_skus
								};

								$.ajax({
									url: '<?php 
                    echo add_query_arg(array('import_page' => $this->import_page, 'step' => '4', 'merge' => !empty($_GET['merge']) ? 1 : 0), admin_url('admin-ajax.php'));
                    ?>
',
									data:       data,
									type:       'POST',
									success:    function( response ) {
										console.log( response );
										$('#import-progress tbody').append( '<tr class="complete"><td colspan="5">' + response + '</td></tr>' );
										$('.importer-loading').hide();
									}
								});
							}
						});
					</script>
					<?php 
                } else {
                    echo '<p class="error">' . __('Error finding uploaded file!', 'wc_csv_import') . '</p>';
                }
                break;
            case 3:
                // Check access - cannot use nonce here as it will expire after multiple requests
                if (!current_user_can('manage_woocommerce')) {
                    die;
                }
                add_filter('http_request_timeout', array($this, 'bump_request_timeout'));
                if (function_exists('gc_enable')) {
                    gc_enable();
                }
                @set_time_limit(0);
                @ob_flush();
                @flush();
                $wpdb->hide_errors();
                $file = stripslashes($_POST['file']);
                $mapping = json_decode(stripslashes($_POST['mapping']), true);
                $start_pos = isset($_POST['start_pos']) ? absint($_POST['start_pos']) : 0;
                $end_pos = isset($_POST['end_pos']) ? absint($_POST['end_pos']) : '';
                $position = $this->import_start($file, $mapping, $start_pos, $end_pos);
                $this->import();
                $this->import_end();
                $results = array();
                $results['import_results'] = $this->import_results;
                $results['processed_terms'] = $this->processed_terms;
                $results['processed_posts'] = $this->processed_posts;
                $results['post_orphans'] = $this->post_orphans;
                $results['attachments'] = $this->attachments;
                $results['upsell_skus'] = $this->upsell_skus;
                $results['crosssell_skus'] = $this->crosssell_skus;
                echo "<!--WC_START-->";
                echo json_encode($results);
                echo "<!--WC_END-->";
                exit;
                break;
            case 4:
                // Check access - cannot use nonce here as it will expire after multiple requests
                if (!current_user_can('manage_woocommerce')) {
                    die;
                }
                add_filter('http_request_timeout', array($this, 'bump_request_timeout'));
                if (function_exists('gc_enable')) {
                    gc_enable();
                }
                @set_time_limit(0);
                @ob_flush();
                @flush();
                $wpdb->hide_errors();
                $this->processed_terms = isset($_POST['processed_terms']) ? $_POST['processed_terms'] : array();
                $this->processed_posts = isset($_POST['processed_posts']) ? $_POST['processed_posts'] : array();
                $this->post_orphans = isset($_POST['post_orphans']) ? $_POST['post_orphans'] : array();
                $this->crosssell_skus = isset($_POST['crosssell_skus']) ? array_filter((array) $_POST['crosssell_skus']) : array();
                $this->upsell_skus = isset($_POST['upsell_skus']) ? array_filter((array) $_POST['upsell_skus']) : array();
                _e('Cleaning up...', 'wc_csv_import') . ' ';
                wp_defer_term_counting(true);
                wp_defer_comment_counting(true);
                _e('Clearing transients...', 'wc_csv_import') . ' ';
                echo 'Reticulating Splines...' . ' ';
                // Easter egg
                // reset transients for products
                if (function_exists('wc_delete_product_transients')) {
                    wc_delete_product_transients();
                } else {
                    $woocommerce->clear_product_transients();
                }
                delete_transient('wc_attribute_taxonomies');
                $wpdb->query("DELETE FROM `{$wpdb->options}` WHERE `option_name` LIKE ('_transient_wc_product_type_%')");
                _e('Backfilling parents...', 'wc_csv_import') . ' ';
                $this->backfill_parents();
                if (!empty($this->upsell_skus)) {
                    _e('Linking upsells...', 'wc_csv_import') . ' ';
                    foreach ($this->upsell_skus as $post_id => $skus) {
                        $this->link_product_skus('upsell', $post_id, $skus);
                    }
                }
                if (!empty($this->crosssell_skus)) {
                    _e('Linking crosssells...', 'wc_csv_import') . ' ';
                    foreach ($this->crosssell_skus as $post_id => $skus) {
                        $this->link_product_skus('crosssell', $post_id, $skus);
                    }
                }
                if ('woocommerce_variation_csv' == $this->import_page && !empty($this->processed_posts)) {
                    _e('Syncing variations...', 'wc_csv_import') . ' ';
                    $synced = array();
                    foreach ($this->processed_posts as $post_id) {
                        $parent = wp_get_post_parent_id($post_id);
                        if (!in_array($parent, $synced)) {
                            WC_Product_Variable::sync($parent);
                            $synced[] = $parent;
                        }
                    }
                }
                // SUCCESS
                _e('Finished. Import complete.', 'wc_csv_import');
                $this->import_end();
                exit;
                break;
        }
        $this->footer();
    }
 /**
  * Checks if the store manager has requested the current product be limited to one purchase
  * per customer, and if so, checks whether the customer already has an active subscription to
  * the product.
  *
  * @access public
  * @return bool
  */
 function is_purchasable()
 {
     $purchasable = parent::is_purchasable();
     if (true === $purchasable && 'no' != $this->limit_subscriptions && is_user_logged_in() && ('active' == $this->limit_subscriptions && WC_Subscriptions_Manager::user_has_subscription(0, $this->id, 'on-hold') || WC_Subscriptions_Manager::user_has_subscription(0, $this->id, $this->limit_subscriptions)) && false === strpos($_SERVER['REQUEST_URI'], 'order-received')) {
         // we can't use is_order_received_page() becuase get_cart_from_session() is called before the query vars are setup
         $purchasable = false;
     }
     return apply_filters('woocommerce_subscription_is_purchasable', $purchasable, $this);
 }
 /**
  * Update post meta fields.
  *
  * @param WP_Post $post
  * @param WP_REST_Request $request
  * @return bool|WP_Error
  */
 protected function update_post_meta_fields($post, $request)
 {
     try {
         $product = wc_get_product($post);
         // Check for featured/gallery images, upload it and set it.
         if (isset($request['images'])) {
             $this->save_product_images($product->id, $request['images']);
         }
         // Save product meta fields.
         $this->save_product_meta($product, $request);
         // Save variations.
         if ($product->is_type('variable')) {
             if (isset($request['variations']) && is_array($request['variations'])) {
                 $this->save_variations_data($product, $request);
             } else {
                 // Just sync variations.
                 WC_Product_Variable::sync($product->id);
                 WC_Product_Variable::sync_stock_status($product->id);
             }
         }
         return true;
     } catch (WC_REST_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }
 /**
  * Bulk edit variations via AJAX
  */
 public static function bulk_edit_variations()
 {
     ob_start();
     check_ajax_referer('bulk-edit-variations', 'security');
     // Check permissions again and make sure we have what we need
     if (!current_user_can('edit_products') || empty($_POST['product_id']) || empty($_POST['bulk_action'])) {
         die(-1);
     }
     global $wpdb;
     $product_id = absint($_POST['product_id']);
     $bulk_action = wc_clean($_POST['bulk_action']);
     $data = !empty($_POST['data']) ? array_map('wc_clean', $_POST['data']) : array();
     $variations = array();
     if (apply_filters('woocommerce_bulk_edit_variations_need_children', !in_array($bulk_action, array('variable_weight', 'variable_length', 'variable_width', 'variable_height')))) {
         $variations = get_posts(array('post_parent' => $product_id, 'posts_per_page' => -1, 'post_type' => 'product_variation', 'fields' => 'ids', 'post_status' => array('publish', 'private')));
     }
     switch ($bulk_action) {
         case 'toggle_enabled':
             foreach ($variations as $variation_id) {
                 $post_status = get_post_status($variation_id);
                 $new_status = 'private' === $post_status ? 'publish' : 'private';
                 $wpdb->update($wpdb->posts, array('post_status' => $new_status), array('ID' => $variation_id));
             }
             break;
         case 'toggle_downloadable':
             foreach ($variations as $variation_id) {
                 $_downloadable = get_post_meta($variation_id, '_downloadable', true);
                 $is_downloadable = 'no' === $_downloadable ? 'yes' : 'no';
                 update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable));
             }
             break;
         case 'toggle_virtual':
             foreach ($variations as $variation_id) {
                 $_virtual = get_post_meta($variation_id, '_virtual', true);
                 $is_virtual = 'no' === $_virtual ? 'yes' : 'no';
                 update_post_meta($variation_id, '_virtual', wc_clean($is_virtual));
             }
             break;
         case 'toggle_manage_stock':
             foreach ($variations as $variation_id) {
                 $_manage_stock = get_post_meta($variation_id, '_manage_stock', true);
                 $is_manage_stock = 'no' === $_manage_stock ? 'yes' : 'no';
                 update_post_meta($variation_id, '_manage_stock', wc_clean($is_manage_stock));
             }
             break;
         case 'variable_regular_price':
         case 'variable_sale_price':
             if (empty($data['value'])) {
                 break;
             }
             $field = str_replace('variable', '', $bulk_action);
             foreach ($variations as $variation_id) {
                 // Price fields
                 $regular_price = '_regular_price' === $field ? $data['value'] : get_post_meta($variation_id, '_regular_price', true);
                 $sale_price = '_sale_price' === $field ? $data['value'] : get_post_meta($variation_id, '_sale_price', true);
                 // Date fields
                 $date_from = get_post_meta($variation_id, '_sale_price_dates_from', true);
                 $date_to = get_post_meta($variation_id, '_sale_price_dates_to', true);
                 $date_from = !empty($date_from) ? date('Y-m-d', $date_from) : '';
                 $date_to = !empty($date_to) ? date('Y-m-d', $date_to) : '';
                 _wc_save_product_price($variation_id, $regular_price, $sale_price, $date_from, $date_to);
             }
             break;
         case 'variable_stock':
             if (empty($data['value'])) {
                 break;
             }
             $value = wc_clean($data['value']);
             foreach ($variations as $variation_id) {
                 if ('yes' === get_post_meta($variation_id, '_manage_stock', true)) {
                     wc_update_product_stock($variation_id, wc_stock_amount($value));
                 } else {
                     delete_post_meta($variation_id, '_stock');
                 }
             }
             break;
         case 'variable_weight':
         case 'variable_length':
         case 'variable_width':
         case 'variable_height':
             if (empty($data['value'])) {
                 break;
             }
             $value = wc_clean($data['value']);
             $field = str_replace('variable', '', $bulk_action);
             $wpdb->query($wpdb->prepare("\n\t\t\t\t\tUPDATE {$wpdb->postmeta} AS postmeta\n\t\t\t\t\tINNER JOIN {$wpdb->posts} AS posts ON posts.post_parent = %d\n\t\t\t\t\tSET postmeta.meta_value = %s\n\t\t\t\t\tWHERE postmeta.meta_key = '%s'\n\t\t\t\t\tAND postmeta.post_id = posts.ID\n\t\t\t\t ", $product_id, $value, $field));
             break;
         case 'variable_download_limit':
         case 'variable_download_expiry':
             if (empty($data['value'])) {
                 break;
             }
             $value = wc_clean($data['value']);
             $field = str_replace('variable', '', $bulk_action);
             foreach ($variations as $variation_id) {
                 if ('yes' === get_post_meta($variation_id, '_downloadable', true)) {
                     update_post_meta($variation_id, $field, $value);
                 } else {
                     update_post_meta($variation_id, $field, '');
                 }
             }
             break;
         case 'delete_all':
             if (isset($data['allowed']) && 'true' === $data['allowed']) {
                 foreach ($variations as $variation_id) {
                     wp_delete_post($variation_id);
                 }
             }
             break;
         case 'variable_regular_price_increase':
         case 'variable_regular_price_decrease':
         case 'variable_sale_price_increase':
         case 'variable_sale_price_decrease':
             if (empty($data['value'])) {
                 break;
             }
             $field = str_replace(array('variable', '_increase', '_decrease'), '', $bulk_action);
             $operator = 'increase' === substr($bulk_action, -8) ? +1 : -1;
             foreach ($variations as $variation_id) {
                 // Price fields
                 $regular_price = get_post_meta($variation_id, '_regular_price', true);
                 $sale_price = get_post_meta($variation_id, '_sale_price', true);
                 // Date fields
                 $date_from = get_post_meta($variation_id, '_sale_price_dates_from', true);
                 $date_to = get_post_meta($variation_id, '_sale_price_dates_to', true);
                 $date_from = !empty($date_from) ? date('Y-m-d', $date_from) : '';
                 $date_to = !empty($date_to) ? date('Y-m-d', $date_to) : '';
                 if ('%' === substr($data['value'], -1)) {
                     $percent = wc_format_decimal(substr($data['value'], 0, -1));
                     if ('_regular_price' === $field) {
                         $regular_price += $regular_price / 100 * $percent * $operator;
                     } else {
                         $sale_price += $sale_price / 100 * $percent * $operator;
                     }
                 } else {
                     if ('_regular_price' === $field) {
                         $regular_price += $data['value'];
                     } else {
                         $sale_price += $data['value'];
                     }
                 }
                 _wc_save_product_price($variation_id, $regular_price, $sale_price, $date_from, $date_to);
             }
             break;
         case 'variable_sale_schedule':
             if (!isset($data['date_from']) && !isset($data['date_to'])) {
                 break;
             }
             foreach ($variations as $variation_id) {
                 // Price fields
                 $regular_price = get_post_meta($variation_id, '_regular_price', true);
                 $sale_price = get_post_meta($variation_id, '_sale_price', true);
                 // Date fields
                 $date_from = get_post_meta($variation_id, '_sale_price_dates_from', true);
                 $date_to = get_post_meta($variation_id, '_sale_price_dates_to', true);
                 if ('false' === $data['date_from']) {
                     $date_from = !empty($date_from) ? date('Y-m-d', $date_from) : '';
                 } else {
                     $date_from = $data['date_from'];
                 }
                 if ('false' === $data['date_to']) {
                     $date_to = !empty($date_to) ? date('Y-m-d', $date_to) : '';
                 } else {
                     $date_to = $data['date_to'];
                 }
                 _wc_save_product_price($variation_id, $regular_price, $sale_price, $date_from, $date_to);
             }
             break;
         default:
             do_action('woocommerce_bulk_edit_variations_default', $bulk_action, $data, $product_id, $variations);
             break;
     }
     do_action('woocommerce_bulk_edit_variations', $bulk_action, $data, $product_id, $variations);
     // Sync and update transients
     WC_Product_Variable::sync($product_id);
     wc_delete_product_transients($product_id);
     die;
 }
 /**
  * Set stock level of the product variation.
  * @param int  $amount
  * @param bool $force_variation_stock If true, the variation's stock will be updated and not the parents.
  * @return int
  * @todo Need to return 0 if is_null? Or something. Should not be just return.
  */
 function set_stock($amount = null, $force_variation_stock = false)
 {
     if (is_null($amount)) {
         return;
     }
     if ($amount === '' && $force_variation_stock) {
         // If amount is an empty string, stock management is being turned off at variation level
         $this->variation_has_stock = false;
         $this->stock = '';
         unset($this->manage_stock);
         // Update meta
         update_post_meta($this->variation_id, '_stock', '');
         // Refresh parent prices
         WC_Product_Variable::sync($this->id);
     } elseif ($this->variation_has_stock || $force_variation_stock) {
         // Update stock amount
         $this->stock = intval($amount);
         $this->variation_has_stock = true;
         $this->manage_stock = 'yes';
         // Update meta
         update_post_meta($this->variation_id, '_stock', $this->stock);
         // Clear total stock transient
         delete_transient('wc_product_total_stock_' . $this->id);
         // Check parents out of stock attribute
         if (!$this->is_in_stock()) {
             // Check parent
             $parent_product = get_product($this->id);
             // Only continue if the parent has backorders off and all children are stock managed and out of stock
             if (!$parent_product->backorders_allowed() && $parent_product->get_total_stock() <= get_option('woocommerce_notify_no_stock_amount')) {
                 $all_managed = true;
                 if (sizeof($parent_product->get_children()) > 0) {
                     foreach ($parent_product->get_children() as $child_id) {
                         $stock = get_post_meta($child_id, '_stock', true);
                         if ($stock == '') {
                             $all_managed = false;
                             break;
                         }
                     }
                 }
                 if ($all_managed) {
                     $this->set_stock_status('outofstock');
                 }
             }
         } elseif ($this->is_in_stock()) {
             $this->set_stock_status('instock');
         }
         // Refresh parent prices
         WC_Product_Variable::sync($this->id);
         // Trigger action
         do_action('woocommerce_product_set_stock', $this);
         return $this->get_stock_quantity();
     } else {
         return parent::set_stock($amount);
     }
 }
Exemple #24
0
function dokan_save_variations($post_id)
{
    global $woocommerce, $wpdb;
    $attributes = (array) maybe_unserialize(get_post_meta($post_id, '_product_attributes', true));
    if (isset($_POST['variable_sku'])) {
        $variable_post_id = $_POST['variable_post_id'];
        $variable_sku = $_POST['variable_sku'];
        $variable_mrp_var = $_POST['_mrp_var'];
        $variable_regular_price = $_POST['variable_regular_price'];
        $variable_sale_price = $_POST['variable_sale_price'];
        $upload_image_id = $_POST['upload_image_id'];
        $variable_download_limit = $_POST['variable_download_limit'];
        $variable_download_expiry = $_POST['variable_download_expiry'];
        $variable_shipping_class = $_POST['variable_shipping_class'];
        $variable_tax_class = isset($_POST['variable_tax_class']) ? $_POST['variable_tax_class'] : array();
        $variable_menu_order = $_POST['variation_menu_order'];
        $variable_sale_price_dates_from = $_POST['variable_sale_price_dates_from'];
        $variable_sale_price_dates_to = $_POST['variable_sale_price_dates_to'];
        $variable_weight = isset($_POST['variable_weight']) ? $_POST['variable_weight'] : array();
        $variable_length = isset($_POST['variable_length']) ? $_POST['variable_length'] : array();
        $variable_width = isset($_POST['variable_width']) ? $_POST['variable_width'] : array();
        $variable_height = isset($_POST['variable_height']) ? $_POST['variable_height'] : array();
        $variable_stock = isset($_POST['variable_stock']) ? $_POST['variable_stock'] : array();
        $variable_enabled = isset($_POST['variable_enabled']) ? $_POST['variable_enabled'] : array();
        $variable_is_virtual = isset($_POST['variable_is_virtual']) ? $_POST['variable_is_virtual'] : array();
        $variable_is_downloadable = isset($_POST['variable_is_downloadable']) ? $_POST['variable_is_downloadable'] : array();
        $max_loop = max(array_keys($_POST['variable_post_id']));
        for ($i = 0; $i <= $max_loop; $i++) {
            if (!isset($variable_post_id[$i])) {
                continue;
            }
            $variation_id = absint($variable_post_id[$i]);
            // Virtal/Downloadable
            $is_virtual = isset($variable_is_virtual[$i]) ? 'yes' : 'no';
            $is_downloadable = isset($variable_is_downloadable[$i]) ? 'yes' : 'no';
            $manage_stock = isset($variable_stock[$i]) ? 'yes' : 'no';
            // Enabled or disabled
            $post_status = isset($variable_enabled[$i]) ? 'publish' : 'private';
            // Generate a useful post title
            $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), absint($variation_id), esc_html(get_the_title($post_id)));
            // Update or Add post
            if (!$variation_id) {
                $variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $post_id, 'post_type' => 'product_variation', 'menu_order' => $variable_menu_order[$i]);
                $variation_id = wp_insert_post($variation);
                do_action('woocommerce_create_product_variation', $variation_id);
            } else {
                $wpdb->update($wpdb->posts, array('post_status' => $post_status, 'post_title' => $variation_post_title, 'menu_order' => $variable_menu_order[$i]), array('ID' => $variation_id));
                do_action('woocommerce_update_product_variation', $variation_id);
            }
            // Update post meta
            update_post_meta($variation_id, '_sku', wc_clean($variable_sku[$i]));
            update_post_meta($variation_id, '_thumbnail_id', absint($upload_image_id[$i]));
            update_post_meta($variation_id, '_virtual', wc_clean($is_virtual));
            update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable));
            update_post_meta($variation_id, '_manage_stock', wc_clean($manage_stock));
            if (isset($variable_weight[$i])) {
                update_post_meta($variation_id, '_weight', $variable_weight[$i] === '' ? '' : wc_format_decimal($variable_weight[$i]));
            }
            if (isset($variable_length[$i])) {
                update_post_meta($variation_id, '_length', $variable_length[$i] === '' ? '' : wc_format_decimal($variable_length[$i]));
            }
            if (isset($variable_width[$i])) {
                update_post_meta($variation_id, '_width', $variable_width[$i] === '' ? '' : wc_format_decimal($variable_width[$i]));
            }
            if (isset($variable_height[$i])) {
                update_post_meta($variation_id, '_height', $variable_height[$i] === '' ? '' : wc_format_decimal($variable_height[$i]));
            }
            // Stock handling
            if (isset($variable_stock[$i])) {
                wc_update_product_stock($variation_id, wc_clean($variable_stock[$i]));
            }
            // Price handling
            $mrp = wc_format_decimal($variable_mrp_var[$i]);
            $regular_price = wc_format_decimal($variable_regular_price[$i]);
            $sale_price = $variable_sale_price[$i] === '' ? '' : wc_format_decimal($variable_sale_price[$i]);
            $date_from = wc_clean($variable_sale_price_dates_from[$i]);
            $date_to = wc_clean($variable_sale_price_dates_to[$i]);
            update_post_meta($variation_id, '_regular_price', $regular_price);
            update_post_meta($variation_id, '_sale_price', $sale_price);
            update_post_meta($variation_id, '_list_price_mrp', $mrp);
            // Save Dates
            if ($date_from) {
                update_post_meta($variation_id, '_sale_price_dates_from', strtotime($date_from));
            } else {
                update_post_meta($variation_id, '_sale_price_dates_from', '');
            }
            if ($date_to) {
                update_post_meta($variation_id, '_sale_price_dates_to', strtotime($date_to));
            } else {
                update_post_meta($variation_id, '_sale_price_dates_to', '');
            }
            if ($date_to && !$date_from) {
                update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
            }
            // Update price if on sale
            if ($sale_price != '' && $date_to == '' && $date_from == '') {
                update_post_meta($variation_id, '_price', $sale_price);
            } else {
                update_post_meta($variation_id, '_price', $regular_price);
            }
            if ($sale_price != '' && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) {
                update_post_meta($variation_id, '_price', $sale_price);
            }
            if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
                update_post_meta($variation_id, '_price', $regular_price);
                update_post_meta($variation_id, '_sale_price_dates_from', '');
                update_post_meta($variation_id, '_sale_price_dates_to', '');
            }
            if (isset($variable_tax_class[$i]) && $variable_tax_class[$i] !== 'parent') {
                update_post_meta($variation_id, '_tax_class', wc_clean($variable_tax_class[$i]));
            } else {
                delete_post_meta($variation_id, '_tax_class');
            }
            if ($is_downloadable == 'yes') {
                update_post_meta($variation_id, '_download_limit', wc_clean($variable_download_limit[$i]));
                update_post_meta($variation_id, '_download_expiry', wc_clean($variable_download_expiry[$i]));
                $files = array();
                $file_names = isset($_POST['_wc_variation_file_names'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_names'][$variation_id]) : array();
                $file_urls = isset($_POST['_wc_variation_file_urls'][$variation_id]) ? array_map('esc_url_raw', array_map('trim', $_POST['_wc_variation_file_urls'][$variation_id])) : array();
                $file_url_size = sizeof($file_urls);
                for ($ii = 0; $ii < $file_url_size; $ii++) {
                    if (!empty($file_urls[$ii])) {
                        $files[md5($file_urls[$ii])] = array('name' => $file_names[$ii], 'file' => $file_urls[$ii]);
                    }
                }
                // grant permission to any newly added files on any existing orders for this product prior to saving
                do_action('woocommerce_process_product_file_download_paths', $post_id, $variation_id, $files);
                update_post_meta($variation_id, '_downloadable_files', $files);
            } else {
                update_post_meta($variation_id, '_download_limit', '');
                update_post_meta($variation_id, '_download_expiry', '');
                update_post_meta($variation_id, '_downloadable_files', '');
            }
            // Save shipping class
            $variable_shipping_class[$i] = !empty($variable_shipping_class[$i]) ? (int) $variable_shipping_class[$i] : '';
            wp_set_object_terms($variation_id, $variable_shipping_class[$i], 'product_shipping_class');
            // Remove old taxonomies attributes so data is kept up to date
            if ($variation_id) {
                $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND post_id = %d;", $variation_id));
                wp_cache_delete($variation_id, 'post_meta');
            }
            // Update taxonomies
            foreach ($attributes as $attribute) {
                if ($attribute['is_variation']) {
                    // Don't use wc_clean as it destroys sanitized characters
                    if (isset($_POST['attribute_' . sanitize_title($attribute['name'])][$i])) {
                        $value = sanitize_title(trim(stripslashes($_POST['attribute_' . sanitize_title($attribute['name'])][$i])));
                    } else {
                        $value = '';
                    }
                    update_post_meta($variation_id, 'attribute_' . sanitize_title($attribute['name']), $value);
                }
            }
            do_action('woocommerce_save_product_variation', $variation_id, $i);
        }
    }
    // Update parent if variable so price sorting works and stays in sync with the cheapest child
    WC_Product_Variable::sync($post_id);
    // Update default attribute options setting
    $default_attributes = array();
    foreach ($attributes as $attribute) {
        if ($attribute['is_variation']) {
            // Don't use wc_clean as it destroys sanitized characters
            if (isset($_POST['default_attribute_' . sanitize_title($attribute['name'])])) {
                $value = sanitize_title(trim(stripslashes($_POST['default_attribute_' . sanitize_title($attribute['name'])])));
            } else {
                $value = '';
            }
            if ($value) {
                $default_attributes[sanitize_title($attribute['name'])] = $value;
            }
        }
    }
    update_post_meta($post_id, '_default_attributes', $default_attributes);
}
 /**
  * Bulk edit variations via AJAX
  */
 public static function bulk_edit_variations()
 {
     ob_start();
     check_ajax_referer('bulk-edit-variations', 'security');
     // Check permissions again and make sure we have what we need
     if (!current_user_can('edit_products') || empty($_POST['product_id']) || empty($_POST['bulk_action'])) {
         die(-1);
     }
     $product_id = absint($_POST['product_id']);
     $bulk_action = wc_clean($_POST['bulk_action']);
     $data = !empty($_POST['data']) ? array_map('wc_clean', $_POST['data']) : array();
     $variations = array();
     if (apply_filters('woocommerce_bulk_edit_variations_need_children', true)) {
         $variations = get_posts(array('post_parent' => $product_id, 'posts_per_page' => -1, 'post_type' => 'product_variation', 'fields' => 'ids', 'post_status' => array('publish', 'private')));
     }
     if (method_exists(__CLASS__, "variation_bulk_action_{$bulk_action}")) {
         call_user_func(array(__CLASS__, "variation_bulk_action_{$bulk_action}"), $variations, $data);
     } else {
         do_action('woocommerce_bulk_edit_variations_default', $bulk_action, $data, $product_id, $variations);
     }
     do_action('woocommerce_bulk_edit_variations', $bulk_action, $data, $product_id, $variations);
     // Sync and update transients
     WC_Product_Variable::sync($product_id);
     wc_delete_product_transients($product_id);
     die;
 }
 public function get_product_variations($prod_id)
 {
     // verify we are in woocommerce product
     if (function_exists('get_product')) {
         $product = new WC_Product_Variable($prod_id);
         // WC_Product
         if (isset($product->id) && (int) $product->id > 0) {
             return $product->get_children();
         }
     }
     return array();
 }
 /**
  * Save meta box data
  *
  * @deprecated 2.4.0 Deprecated in favor to WC_AJAX::save_variations()
  */
 public static function save_variations($post_id, $post)
 {
     global $wpdb;
     $attributes = (array) maybe_unserialize(get_post_meta($post_id, '_product_attributes', true));
     if (isset($_POST['variable_sku'])) {
         $variable_post_id = $_POST['variable_post_id'];
         $variable_sku = $_POST['variable_sku'];
         $variable_regular_price = $_POST['variable_regular_price'];
         $variable_sale_price = $_POST['variable_sale_price'];
         $upload_image_id = $_POST['upload_image_id'];
         $variable_download_limit = $_POST['variable_download_limit'];
         $variable_download_expiry = $_POST['variable_download_expiry'];
         $variable_shipping_class = $_POST['variable_shipping_class'];
         $variable_tax_class = isset($_POST['variable_tax_class']) ? $_POST['variable_tax_class'] : array();
         $variable_menu_order = $_POST['variation_menu_order'];
         $variable_sale_price_dates_from = $_POST['variable_sale_price_dates_from'];
         $variable_sale_price_dates_to = $_POST['variable_sale_price_dates_to'];
         $variable_weight = isset($_POST['variable_weight']) ? $_POST['variable_weight'] : array();
         $variable_length = isset($_POST['variable_length']) ? $_POST['variable_length'] : array();
         $variable_width = isset($_POST['variable_width']) ? $_POST['variable_width'] : array();
         $variable_height = isset($_POST['variable_height']) ? $_POST['variable_height'] : array();
         $variable_enabled = isset($_POST['variable_enabled']) ? $_POST['variable_enabled'] : array();
         $variable_is_virtual = isset($_POST['variable_is_virtual']) ? $_POST['variable_is_virtual'] : array();
         $variable_is_downloadable = isset($_POST['variable_is_downloadable']) ? $_POST['variable_is_downloadable'] : array();
         $variable_manage_stock = isset($_POST['variable_manage_stock']) ? $_POST['variable_manage_stock'] : array();
         $variable_stock = isset($_POST['variable_stock']) ? $_POST['variable_stock'] : array();
         $variable_backorders = isset($_POST['variable_backorders']) ? $_POST['variable_backorders'] : array();
         $variable_stock_status = isset($_POST['variable_stock_status']) ? $_POST['variable_stock_status'] : array();
         $variable_description = isset($_POST['variable_description']) ? $_POST['variable_description'] : array();
         $max_loop = max(array_keys($_POST['variable_post_id']));
         for ($i = 0; $i <= $max_loop; $i++) {
             if (!isset($variable_post_id[$i])) {
                 continue;
             }
             $variation_id = absint($variable_post_id[$i]);
             // Checkboxes
             $is_virtual = isset($variable_is_virtual[$i]) ? 'yes' : 'no';
             $is_downloadable = isset($variable_is_downloadable[$i]) ? 'yes' : 'no';
             $post_status = isset($variable_enabled[$i]) ? 'publish' : 'private';
             $manage_stock = isset($variable_manage_stock[$i]) ? 'yes' : 'no';
             // Generate a useful post title
             $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), absint($variation_id), esc_html(get_the_title($post_id)));
             // Update or Add post
             if (!$variation_id) {
                 $variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $post_id, 'post_type' => 'product_variation', 'menu_order' => $variable_menu_order[$i]);
                 $variation_id = wp_insert_post($variation);
                 do_action('woocommerce_create_product_variation', $variation_id);
             } else {
                 $wpdb->update($wpdb->posts, array('post_status' => $post_status, 'post_title' => $variation_post_title, 'menu_order' => $variable_menu_order[$i]), array('ID' => $variation_id));
                 do_action('woocommerce_update_product_variation', $variation_id);
             }
             // Only continue if we have a variation ID
             if (!$variation_id) {
                 continue;
             }
             // Unique SKU
             $sku = get_post_meta($variation_id, '_sku', true);
             $new_sku = wc_clean(stripslashes($variable_sku[$i]));
             if ('' == $new_sku) {
                 update_post_meta($variation_id, '_sku', '');
             } elseif ($new_sku !== $sku) {
                 if (!empty($new_sku)) {
                     $unique_sku = wc_product_has_unique_sku($variation_id, $new_sku);
                     if (!$unique_sku) {
                         WC_Admin_Meta_Boxes::add_error(__('Variation SKU must be unique.', 'woocommerce'));
                     } else {
                         update_post_meta($variation_id, '_sku', $new_sku);
                     }
                 } else {
                     update_post_meta($variation_id, '_sku', '');
                 }
             }
             // Update post meta
             update_post_meta($variation_id, '_thumbnail_id', absint($upload_image_id[$i]));
             update_post_meta($variation_id, '_virtual', wc_clean($is_virtual));
             update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable));
             if (isset($variable_weight[$i])) {
                 update_post_meta($variation_id, '_weight', '' === $variable_weight[$i] ? '' : wc_format_decimal($variable_weight[$i]));
             }
             if (isset($variable_length[$i])) {
                 update_post_meta($variation_id, '_length', '' === $variable_length[$i] ? '' : wc_format_decimal($variable_length[$i]));
             }
             if (isset($variable_width[$i])) {
                 update_post_meta($variation_id, '_width', '' === $variable_width[$i] ? '' : wc_format_decimal($variable_width[$i]));
             }
             if (isset($variable_height[$i])) {
                 update_post_meta($variation_id, '_height', '' === $variable_height[$i] ? '' : wc_format_decimal($variable_height[$i]));
             }
             // Stock handling
             update_post_meta($variation_id, '_manage_stock', $manage_stock);
             // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level
             if (!empty($variable_stock_status[$i])) {
                 wc_update_product_stock_status($variation_id, $variable_stock_status[$i]);
             }
             if ('yes' === $manage_stock) {
                 update_post_meta($variation_id, '_backorders', wc_clean($variable_backorders[$i]));
                 wc_update_product_stock($variation_id, wc_stock_amount($variable_stock[$i]));
             } else {
                 delete_post_meta($variation_id, '_backorders');
                 delete_post_meta($variation_id, '_stock');
             }
             // Price handling
             $regular_price = wc_format_decimal($variable_regular_price[$i]);
             $sale_price = $variable_sale_price[$i] === '' ? '' : wc_format_decimal($variable_sale_price[$i]);
             $date_from = wc_clean($variable_sale_price_dates_from[$i]);
             $date_to = wc_clean($variable_sale_price_dates_to[$i]);
             update_post_meta($variation_id, '_regular_price', $regular_price);
             update_post_meta($variation_id, '_sale_price', $sale_price);
             // Save Dates
             update_post_meta($variation_id, '_sale_price_dates_from', $date_from ? strtotime($date_from) : '');
             update_post_meta($variation_id, '_sale_price_dates_to', $date_to ? strtotime($date_to) : '');
             if ($date_to && !$date_from) {
                 update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
             }
             // Update price if on sale
             if ('' !== $sale_price && '' === $date_to && '' === $date_from) {
                 update_post_meta($variation_id, '_price', $sale_price);
             } else {
                 update_post_meta($variation_id, '_price', $regular_price);
             }
             if ('' !== $sale_price && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) {
                 update_post_meta($variation_id, '_price', $sale_price);
             }
             if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
                 update_post_meta($variation_id, '_price', $regular_price);
                 update_post_meta($variation_id, '_sale_price_dates_from', '');
                 update_post_meta($variation_id, '_sale_price_dates_to', '');
             }
             if (isset($variable_tax_class[$i]) && $variable_tax_class[$i] !== 'parent') {
                 update_post_meta($variation_id, '_tax_class', wc_clean($variable_tax_class[$i]));
             } else {
                 delete_post_meta($variation_id, '_tax_class');
             }
             if ('yes' == $is_downloadable) {
                 update_post_meta($variation_id, '_download_limit', wc_clean($variable_download_limit[$i]));
                 update_post_meta($variation_id, '_download_expiry', wc_clean($variable_download_expiry[$i]));
                 $files = array();
                 $file_names = isset($_POST['_wc_variation_file_names'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_names'][$variation_id]) : array();
                 $file_urls = isset($_POST['_wc_variation_file_urls'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_urls'][$variation_id]) : array();
                 $file_url_size = sizeof($file_urls);
                 $allowed_file_types = get_allowed_mime_types();
                 for ($ii = 0; $ii < $file_url_size; $ii++) {
                     if (!empty($file_urls[$ii])) {
                         // Find type and file URL
                         if (0 === strpos($file_urls[$ii], 'http')) {
                             $file_is = 'absolute';
                             $file_url = esc_url_raw($file_urls[$ii]);
                         } elseif ('[' === substr($file_urls[$ii], 0, 1) && ']' === substr($file_urls[$ii], -1)) {
                             $file_is = 'shortcode';
                             $file_url = wc_clean($file_urls[$ii]);
                         } else {
                             $file_is = 'relative';
                             $file_url = wc_clean($file_urls[$ii]);
                         }
                         $file_name = wc_clean($file_names[$ii]);
                         $file_hash = md5($file_url);
                         // Validate the file extension
                         if (in_array($file_is, array('absolute', 'relative'))) {
                             $file_type = wp_check_filetype(strtok($file_url, '?'));
                             $parsed_url = parse_url($file_url, PHP_URL_PATH);
                             $extension = pathinfo($parsed_url, PATHINFO_EXTENSION);
                             if (!empty($extension) && !in_array($file_type['type'], $allowed_file_types)) {
                                 WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not have an allowed file type. Allowed types include: %s', 'woocommerce'), '<code>' . basename($file_url) . '</code>', '<code>' . implode(', ', array_keys($allowed_file_types)) . '</code>'));
                                 continue;
                             }
                         }
                         // Validate the file exists
                         if ('relative' === $file_is && !apply_filters('woocommerce_downloadable_file_exists', file_exists($file_url), $file_url)) {
                             WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not exist on the server.', 'woocommerce'), '<code>' . $file_url . '</code>'));
                             continue;
                         }
                         $files[$file_hash] = array('name' => $file_name, 'file' => $file_url);
                     }
                 }
                 // grant permission to any newly added files on any existing orders for this product prior to saving
                 do_action('woocommerce_process_product_file_download_paths', $post_id, $variation_id, $files);
                 update_post_meta($variation_id, '_downloadable_files', $files);
             } else {
                 update_post_meta($variation_id, '_download_limit', '');
                 update_post_meta($variation_id, '_download_expiry', '');
                 update_post_meta($variation_id, '_downloadable_files', '');
             }
             update_post_meta($variation_id, '_variation_description', wp_kses_post($variable_description[$i]));
             // Save shipping class
             $variable_shipping_class[$i] = !empty($variable_shipping_class[$i]) ? (int) $variable_shipping_class[$i] : '';
             wp_set_object_terms($variation_id, $variable_shipping_class[$i], 'product_shipping_class');
             // Update Attributes
             $updated_attribute_keys = array();
             foreach ($attributes as $attribute) {
                 if ($attribute['is_variation']) {
                     $attribute_key = 'attribute_' . sanitize_title($attribute['name']);
                     $updated_attribute_keys[] = $attribute_key;
                     if ($attribute['is_taxonomy']) {
                         // Don't use wc_clean as it destroys sanitized characters
                         $value = isset($_POST[$attribute_key][$i]) ? sanitize_title(stripslashes($_POST[$attribute_key][$i])) : '';
                     } else {
                         $value = isset($_POST[$attribute_key][$i]) ? wc_clean(stripslashes($_POST[$attribute_key][$i])) : '';
                     }
                     update_post_meta($variation_id, $attribute_key, $value);
                 }
             }
             // Remove old taxonomies attributes so data is kept up to date - first get attribute key names
             $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id));
             foreach ($delete_attribute_keys as $key) {
                 delete_post_meta($variation_id, $key);
             }
             do_action('woocommerce_save_product_variation', $variation_id, $i);
         }
     }
     // Update parent if variable so price sorting works and stays in sync with the cheapest child
     WC_Product_Variable::sync($post_id);
     // Update default attribute options setting
     $default_attributes = array();
     foreach ($attributes as $attribute) {
         if ($attribute['is_variation']) {
             // Don't use wc_clean as it destroys sanitized characters
             if (isset($_POST['default_attribute_' . sanitize_title($attribute['name'])])) {
                 $value = sanitize_title(trim(stripslashes($_POST['default_attribute_' . sanitize_title($attribute['name'])])));
             } else {
                 $value = '';
             }
             if ($value) {
                 $default_attributes[sanitize_title($attribute['name'])] = $value;
             }
         }
     }
     update_post_meta($post_id, '_default_attributes', $default_attributes);
 }
 /**
  * Update post meta fields.
  *
  * @param WP_Post         $post    Post data.
  * @param WP_REST_Request $request Request data.
  * @return bool|WP_Error
  */
 protected function update_post_meta_fields($post, $request)
 {
     $product = wc_get_product($post);
     // Check for featured/gallery images, upload it and set it.
     if (isset($request['images'])) {
         $product = $this->save_product_images($product, $request['images']);
     }
     // Save product meta fields.
     $product = $this->save_product_meta($product, $request);
     // Save variations.
     if ($product->is_type('variable')) {
         if (isset($request['variations']) && is_array($request['variations'])) {
             $this->save_variations_data($product, $request);
         } else {
             // Just sync variations.
             $product = WC_Product_Variable::sync($product, false);
         }
     }
     $product->save();
     return true;
 }
 /**
  * Save variations
  *
  * @since 2.2
  * @param int $id
  * @param array $data
  * @return bool
  */
 protected function save_variations($id, $data)
 {
     global $wpdb;
     $variations = $data['variations'];
     $attributes = (array) maybe_unserialize(get_post_meta($id, '_product_attributes', true));
     foreach ($variations as $menu_order => $variation) {
         $variation_id = isset($variation['id']) ? absint($variation['id']) : 0;
         // Generate a useful post title
         $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), $variation_id, esc_html(get_the_title($id)));
         // Update or Add post
         if (!$variation_id) {
             $post_status = isset($variation['visible']) && false === $variation['visible'] ? 'private' : 'publish';
             $new_variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $id, 'post_type' => 'product_variation', 'menu_order' => $menu_order);
             $variation_id = wp_insert_post($new_variation);
             do_action('woocommerce_create_product_variation', $variation_id);
         } else {
             $update_variation = array('post_title' => $variation_post_title, 'menu_order' => $menu_order);
             if (isset($variation['visible'])) {
                 $post_status = false === $variation['visible'] ? 'private' : 'publish';
                 $update_variation['post_status'] = $post_status;
             }
             $wpdb->update($wpdb->posts, $update_variation, array('ID' => $variation_id));
             do_action('woocommerce_update_product_variation', $variation_id);
         }
         // Stop with we don't have a variation ID
         if (is_wp_error($variation_id)) {
             throw new WC_API_Exception('woocommerce_api_cannot_save_product_variation', $variation_id->get_error_message(), 400);
         }
         // SKU
         if (isset($variation['sku'])) {
             $sku = get_post_meta($variation_id, '_sku', true);
             $new_sku = wc_clean($variation['sku']);
             if ('' == $new_sku) {
                 update_post_meta($variation_id, '_sku', '');
             } elseif ($new_sku !== $sku) {
                 if (!empty($new_sku)) {
                     $unique_sku = wc_product_has_unique_sku($variation_id, $new_sku);
                     if (!$unique_sku) {
                         throw new WC_API_Exception('woocommerce_api_product_sku_already_exists', __('The SKU already exists on another product', 'woocommerce'), 400);
                     } else {
                         update_post_meta($variation_id, '_sku', $new_sku);
                     }
                 } else {
                     update_post_meta($variation_id, '_sku', '');
                 }
             }
         }
         // Thumbnail
         if (isset($variation['image']) && is_array($variation['image'])) {
             $image = current($variation['image']);
             if ($image && is_array($image)) {
                 if (isset($image['position']) && isset($image['src']) && $image['position'] == 0) {
                     $upload = $this->upload_product_image(wc_clean($image['src']));
                     if (is_wp_error($upload)) {
                         throw new WC_API_Exception('woocommerce_api_cannot_upload_product_image', $upload->get_error_message(), 400);
                     }
                     $attachment_id = $this->set_product_image_as_attachment($upload, $id);
                     update_post_meta($variation_id, '_thumbnail_id', $attachment_id);
                 }
             } else {
                 delete_post_meta($variation_id, '_thumbnail_id');
             }
         }
         // Virtual variation
         if (isset($variation['virtual'])) {
             $is_virtual = true === $variation['virtual'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_virtual', $is_virtual);
         }
         // Downloadable variation
         if (isset($variation['downloadable'])) {
             $is_downloadable = true === $variation['downloadable'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_downloadable', $is_downloadable);
         } else {
             $is_downloadable = get_post_meta($variation_id, '_downloadable', true);
         }
         // Shipping data
         $this->save_product_shipping_data($variation_id, $variation);
         // Stock handling
         if (isset($variation['managing_stock'])) {
             $managing_stock = true === $variation['managing_stock'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_manage_stock', $managing_stock);
         } else {
             $managing_stock = get_post_meta($variation_id, '_manage_stock', true);
         }
         // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level
         if (isset($variation['in_stock'])) {
             $stock_status = true === $variation['in_stock'] ? 'instock' : 'outofstock';
             wc_update_product_stock_status($variation_id, $stock_status);
         }
         if ('yes' === $managing_stock) {
             if (isset($variation['backorders'])) {
                 if ('notify' == $variation['backorders']) {
                     $backorders = 'notify';
                 } else {
                     $backorders = true === $variation['backorders'] ? 'yes' : 'no';
                 }
             } else {
                 $backorders = 'no';
             }
             update_post_meta($variation_id, '_backorders', $backorders);
             if (isset($variation['stock_quantity'])) {
                 wc_update_product_stock($variation_id, wc_stock_amount($variation['stock_quantity']));
             } else {
                 if (isset($data['inventory_delta'])) {
                     $stock_quantity = wc_stock_amount(get_post_meta($variation_id, '_stock', true));
                     $stock_quantity += wc_stock_amount($data['inventory_delta']);
                     wc_update_product_stock($variation_id, wc_stock_amount($stock_quantity));
                 }
             }
         } else {
             delete_post_meta($variation_id, '_backorders');
             delete_post_meta($variation_id, '_stock');
         }
         // Regular Price
         if (isset($variation['regular_price'])) {
             $regular_price = '' === $variation['regular_price'] ? '' : wc_format_decimal($variation['regular_price']);
             update_post_meta($variation_id, '_regular_price', $regular_price);
         } else {
             $regular_price = get_post_meta($variation_id, '_regular_price', true);
         }
         // Sale Price
         if (isset($variation['sale_price'])) {
             $sale_price = '' === $variation['sale_price'] ? '' : wc_format_decimal($variation['sale_price']);
             update_post_meta($variation_id, '_sale_price', $sale_price);
         } else {
             $sale_price = get_post_meta($variation_id, '_sale_price', true);
         }
         $date_from = isset($variation['sale_price_dates_from']) ? strtotime($variation['sale_price_dates_from']) : get_post_meta($variation_id, '_sale_price_dates_from', true);
         $date_to = isset($variation['sale_price_dates_to']) ? strtotime($variation['sale_price_dates_to']) : get_post_meta($variation_id, '_sale_price_dates_to', true);
         // Save Dates
         if ($date_from) {
             update_post_meta($variation_id, '_sale_price_dates_from', $date_from);
         } else {
             update_post_meta($variation_id, '_sale_price_dates_from', '');
         }
         if ($date_to) {
             update_post_meta($variation_id, '_sale_price_dates_to', $date_to);
         } else {
             update_post_meta($variation_id, '_sale_price_dates_to', '');
         }
         if ($date_to && !$date_from) {
             update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
         }
         // Update price if on sale
         if ('' != $sale_price && '' == $date_to && '' == $date_from) {
             update_post_meta($variation_id, '_price', $sale_price);
         } else {
             update_post_meta($variation_id, '_price', $regular_price);
         }
         if ('' != $sale_price && $date_from && $date_from < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($variation_id, '_price', $sale_price);
         }
         if ($date_to && $date_to < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($variation_id, '_price', $regular_price);
             update_post_meta($variation_id, '_sale_price_dates_from', '');
             update_post_meta($variation_id, '_sale_price_dates_to', '');
         }
         // Tax class
         if (isset($variation['tax_class'])) {
             if ($variation['tax_class'] !== 'parent') {
                 update_post_meta($variation_id, '_tax_class', wc_clean($variation['tax_class']));
             } else {
                 delete_post_meta($variation_id, '_tax_class');
             }
         }
         // Downloads
         if ('yes' == $is_downloadable) {
             // Downloadable files
             if (isset($variation['downloads']) && is_array($variation['downloads'])) {
                 $this->save_downloadable_files($id, $variation['downloads'], $variation_id);
             }
             // Download limit
             if (isset($variation['download_limit'])) {
                 $download_limit = absint($variation['download_limit']);
                 update_post_meta($variation_id, '_download_limit', !$download_limit ? '' : $download_limit);
             }
             // Download expiry
             if (isset($variation['download_expiry'])) {
                 $download_expiry = absint($variation['download_expiry']);
                 update_post_meta($variation_id, '_download_expiry', !$download_expiry ? '' : $download_expiry);
             }
         } else {
             update_post_meta($variation_id, '_download_limit', '');
             update_post_meta($variation_id, '_download_expiry', '');
             update_post_meta($variation_id, '_downloadable_files', '');
         }
         // Update taxonomies
         if (isset($variation['attributes'])) {
             $updated_attribute_keys = array();
             foreach ($variation['attributes'] as $attribute_key => $attribute) {
                 if (!isset($attribute['name'])) {
                     continue;
                 }
                 $_attribute = array();
                 if (isset($attribute['slug'])) {
                     $taxonomy = $this->get_attribute_taxonomy_by_slug($attribute['slug']);
                 }
                 if (!$taxonomy) {
                     $taxonomy = sanitize_title($attribute['name']);
                 }
                 if (isset($attributes[$taxonomy])) {
                     $_attribute = $attributes[$taxonomy];
                 }
                 if (isset($_attribute['is_variation']) && $_attribute['is_variation']) {
                     $_attribute_key = 'attribute_' . sanitize_title($_attribute['name']);
                     $updated_attribute_keys[] = $_attribute_key;
                     if (isset($_attribute['is_taxonomy']) && $_attribute['is_taxonomy']) {
                         // Don't use wc_clean as it destroys sanitized characters
                         $_attribute_value = isset($attribute['option']) ? sanitize_title(stripslashes($attribute['option'])) : '';
                     } else {
                         $_attribute_value = isset($attribute['option']) ? wc_clean(stripslashes($attribute['option'])) : '';
                     }
                     update_post_meta($variation_id, $_attribute_key, $_attribute_value);
                 }
             }
             // Remove old taxonomies attributes so data is kept up to date - first get attribute key names
             $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id));
             foreach ($delete_attribute_keys as $key) {
                 delete_post_meta($variation_id, $key);
             }
         }
         do_action('woocommerce_api_save_product_variation', $variation_id, $menu_order, $variation);
     }
     // Update parent if variable so price sorting works and stays in sync with the cheapest child
     WC_Product_Variable::sync($id);
     // Update default attributes options setting
     if (isset($data['default_attribute'])) {
         $data['default_attributes'] = $data['default_attribute'];
     }
     if (isset($data['default_attributes']) && is_array($data['default_attributes'])) {
         $default_attributes = array();
         foreach ($data['default_attributes'] as $default_attr_key => $default_attr) {
             if (!isset($default_attr['name'])) {
                 continue;
             }
             $taxonomy = sanitize_title($default_attr['name']);
             if (isset($default_attr['slug'])) {
                 $taxonomy = $this->get_attribute_taxonomy_by_slug($default_attr['slug']);
             }
             if (isset($attributes[$taxonomy])) {
                 $_attribute = $attributes[$taxonomy];
                 if ($_attribute['is_variation']) {
                     $value = '';
                     if (isset($default_attr['option'])) {
                         if ($_attribute['is_taxonomy']) {
                             // Don't use wc_clean as it destroys sanitized characters
                             $value = sanitize_title(trim(stripslashes($default_attr['option'])));
                         } else {
                             $value = wc_clean(trim(stripslashes($default_attr['option'])));
                         }
                     }
                     if ($value) {
                         $default_attributes[$taxonomy] = $value;
                     }
                 }
             }
         }
         update_post_meta($id, '_default_attributes', $default_attributes);
     }
     return true;
 }
function idwc_payment_vars($item, $status, $order_id, $qty_num)
{
    $order = new WC_Order($order_id);
    if (isset($item['product_id'])) {
        $product_id = $item['product_id'];
    }
    if (isset($item['variation_id'])) {
        $variation_id = $item['variation_id'];
    }
    if (isset($product_id)) {
        $project_id = get_post_meta($product_id, '_wc_project_pairing', true);
        if (isset($project_id)) {
            $product = new WC_Product_Variable($product_id);
            if (!empty($product)) {
                $variations = $product->get_available_variations();
                $v_array = array();
                foreach ($variations as $variant) {
                    $v_array[] = $variant['variation_id'];
                }
                $level = array_search($variation_id, $v_array) + 1;
            }
            $first_name = get_post_meta($order_id, '_billing_first_name', true);
            $last_name = get_post_meta($order_id, '_billing_last_name', true);
            $email = get_post_meta($order_id, '_billing_email', true);
            $address = get_post_meta($order_id, '_billing_address_1', true);
            $city = get_post_meta($order_id, '_billing_city', true);
            $state = get_post_meta($order_id, '_billing_state', true);
            $zip = get_post_meta($order_id, '_billing_postcode', true);
            $country = get_post_meta($order_id, '_billing_country', true);
            $transaction_id = get_post_meta($order_id, '_order_key', true);
            $price = get_post_meta($variation_id, '_price', true);
            $date = $order->order_date;
            $vars = array('id' => null, 'first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, 'address' => $address, 'state' => $state, 'city' => $city, 'zip' => $zip, 'country' => $country, 'product_id' => $project_id, 'transaction_id' => $transaction_id . '-v' . $variation_id . '-' . $qty_num, 'preapproval_key' => '', 'product_level' => $level, 'prod_price' => $price, 'status' => $status, 'created_at' => $date);
        }
    }
    return isset($vars) ? $vars : array();
}