private function save_variation_meta($id, $data)
 {
     $product_meta = get_product_meta($id, 'product_metadata', true);
     if (!is_array($product_meta)) {
         $product_meta = array();
     }
     $product_meta = $this->merge_meta_deep($product_meta, $data['product_metadata']);
     // convert to pound to maintain backward compat with shipping modules
     if (isset($data['product_metadata']['weight']) || isset($data['product_metadata']['weight_unit'])) {
         $product_meta['weight'] = wpsc_convert_weight($product_meta['weight'], $product_meta['weight_unit'], 'pound', true);
     }
     update_product_meta($id, 'product_metadata', $product_meta);
     if (isset($data['price'])) {
         update_product_meta($id, 'price', wpsc_string_to_float($data['price']));
     }
     if (isset($data['sale_price'])) {
         $sale_price = wpsc_string_to_float($data['sale_price']);
         if (is_numeric($sale_price)) {
             update_product_meta($id, 'special_price', wpsc_string_to_float($data['sale_price']));
         } else {
             update_product_meta($id, 'special_price', '');
         }
     }
     if (isset($data['sku'])) {
         update_product_meta($id, 'sku', $data['sku']);
     }
     if (isset($data['stock'])) {
         if (is_numeric($data['stock'])) {
             update_product_meta($id, 'stock', (int) $data['stock']);
         } else {
             update_product_meta($id, 'stock', '');
         }
     }
 }
Exemple #2
0
 function wpsc_the_product_weight($product_id = null)
 {
     global $wp_query;
     if (!$product_id) {
         $product_id = $wp_query->post->ID;
     }
     $product_data = get_post_meta($product_id, '_wpsc_product_metadata', true);
     $weight = $product_data['weight'];
     $weight_unit = $product_data['weight_unit'];
     if ($weight && $weight_unit) {
         $output = wpsc_convert_weight($weight, 'pound', $weight_unit);
         switch ($weight_unit) {
             case 'pound':
                 $weight_unit = __(' lbs.', 'wpsc');
                 break;
             case 'ounce':
                 $weight_unit = __(' oz.', 'wpsc');
                 break;
             case 'gram':
                 $weight_unit = __(' g', 'wpsc');
                 break;
             case 'kilograms':
             case 'kilogram':
                 $weight_unit = __(' kgs.', 'wpsc');
                 break;
         }
         $output .= ' ' . $weight_unit;
         echo $output;
     }
 }
/**
 * Weight column in Manage Products page
 *
 * @since 3.8.9
 * @access private
 *
 * @param  object  $post    Post object
 * @param  int     $post_id Post ID
 * @param  boolean $has_variations Whether the product has variations
 *
 * @uses esc_html_e()                Safe HTML with translation
 * @uses get_post_meta()             Gets post meta given key and post_id
 * @uses maybe_unserialize()         Unserialize value only if it was serialized.
 * @uses wpsc_convert_weight()       Does weight conversions
 * @uses esc_html()                  Makes sure things are safe
 * @uses wpsc_weight_unit_display()  Gets weight unit for display
 */
function _wpsc_manage_products_column_weight($post, $post_id, $has_variations)
{
    if ($has_variations) {
        esc_html_e('N/A', 'wpsc');
        return;
    }
    $product_data = array();
    $product_data['meta'] = array();
    $product_data['meta'] = get_post_meta($post->ID, '');
    foreach ($product_data['meta'] as $meta_name => $meta_value) {
        $product_data['meta'][$meta_name] = maybe_unserialize(array_pop($meta_value));
    }
    $product_data['transformed'] = array();
    if (!isset($product_data['meta']['_wpsc_product_metadata']['weight'])) {
        $product_data['meta']['_wpsc_product_metadata']['weight'] = "";
    }
    if (!isset($product_data['meta']['_wpsc_product_metadata']['weight_unit'])) {
        $product_data['meta']['_wpsc_product_metadata']['weight_unit'] = "";
    }
    $product_data['transformed']['weight'] = wpsc_convert_weight($product_data['meta']['_wpsc_product_metadata']['weight'], "pound", $product_data['meta']['_wpsc_product_metadata']['weight_unit']);
    $weight = $product_data['transformed']['weight'];
    if ($weight == '') {
        $weight = '0';
    }
    $unit = $product_data['meta']['_wpsc_product_metadata']['weight_unit'];
    echo $weight . wpsc_weight_unit_display($unit);
    echo '<div id="inline_' . $post->ID . '_weight" class="hidden">' . esc_html($weight) . '</div>';
}
function wpsc_convert_weights($weight, $unit)
{
    _wpsc_deprecated_function(__FUNCTION__, '3.8', 'wpsc_convert_weight');
    if (is_array($weight)) {
        $weight = $weight['weight'];
    }
    return wpsc_convert_weight($weight, $unit, 'gram', true);
}
/**
* wpsc_sanitise_product_forms function
*
* @return array - Sanitised product details
*/
function wpsc_sanitise_product_forms($post_data = null)
{
    if (empty($post_data)) {
        $post_data =& $_POST;
    }
    $post_data['name'] = isset($post_data['post_title']) ? $post_data['post_title'] : '';
    $post_data['title'] = $post_data['name'];
    $post_data['description'] = isset($post_data['content']) ? $post_data['content'] : '';
    $post_data['additional_description'] = isset($post_data['additional_description']) ? $post_data['additional_description'] : '';
    $post_data['post_status'] = 'draft';
    if (isset($post_data['publish'])) {
        $post_data['post_status'] = 'publish';
    } else {
        if (isset($post_data['unpublish'])) {
            $post_data['post_status'] = 'draft';
        }
    }
    $post_data['meta']['_wpsc_price'] = (double) str_replace(',', '', $post_data['meta']['_wpsc_price']);
    $post_data['meta']['_wpsc_special_price'] = (double) str_replace(',', '', $post_data['meta']['_wpsc_special_price']);
    $post_data['meta']['_wpsc_sku'] = $post_data['meta']['_wpsc_sku'];
    if (!isset($post_data['meta']['_wpsc_is_donation'])) {
        $post_data['meta']['_wpsc_is_donation'] = '';
    }
    $post_data['meta']['_wpsc_is_donation'] = (int) (bool) $post_data['meta']['_wpsc_is_donation'];
    $post_data['meta']['_wpsc_stock'] = (int) $post_data['meta']['_wpsc_stock'];
    if (!isset($post_data['meta']['_wpsc_limited_stock'])) {
        $post_data['meta']['_wpsc_limited_stock'] = '';
    }
    if ((bool) $post_data['meta']['_wpsc_limited_stock'] != true) {
        $post_data['meta']['_wpsc_stock'] = false;
    }
    unset($post_data['meta']['_wpsc_limited_stock']);
    if (!isset($post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'])) {
        $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'] = '';
    }
    if (!isset($post_data['quantity_limited'])) {
        $post_data['quantity_limited'] = '';
    }
    if (!isset($post_data['special'])) {
        $post_data['special'] = '';
    }
    if (!isset($post_data['meta']['_wpsc_product_metadata']['no_shipping'])) {
        $post_data['meta']['_wpsc_product_metadata']['no_shipping'] = '';
    }
    $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'];
    $post_data['meta']['_wpsc_product_metadata']['quantity_limited'] = (int) (bool) $post_data['quantity_limited'];
    $post_data['meta']['_wpsc_product_metadata']['special'] = (int) (bool) $post_data['special'];
    $post_data['meta']['_wpsc_product_metadata']['no_shipping'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['no_shipping'];
    // Product Weight
    if (!isset($post_data['meta']['_wpsc_product_metadata']['display_weight_as'])) {
        $post_data['meta']['_wpsc_product_metadata']['display_weight_as'] = '';
    }
    if (!isset($post_data['meta']['_wpsc_product_metadata']['display_weight_as'])) {
        $post_data['meta']['_wpsc_product_metadata']['display_weight_as'] = '';
    }
    $weight = wpsc_convert_weight($post_data['meta']['_wpsc_product_metadata']['weight'], $post_data['meta']['_wpsc_product_metadata']['weight_unit'], "pound", true);
    $post_data['meta']['_wpsc_product_metadata']['weight'] = (double) $weight;
    $post_data['meta']['_wpsc_product_metadata']['display_weight_as'] = $post_data['meta']['_wpsc_product_metadata']['weight_unit'];
    $post_data['files'] = $_FILES;
    return $post_data;
}
Exemple #6
0
 function getQuote()
 {
     global $wpdb, $wpsc_cart;
     if ($this->base_country != 'FR' || strlen($this->base_zipcode) != 5 || !count($wpsc_cart->cart_items)) {
         return;
     }
     $dest = $_SESSION['wpsc_delivery_country'];
     $destzipcode = '';
     if (isset($_POST['zipcode'])) {
         $destzipcode = $_POST['zipcode'];
         $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
     } else {
         if (isset($_SESSION['wpsc_zipcode'])) {
             $destzipcode = $_SESSION['wpsc_zipcode'];
         }
     }
     //echo '*****'.$dest;
     if ($dest == 'FR' && strlen($destzipcode) != 5) {
         return array();
     }
     /*
     3 possible scenarios:
     1. Cart consists of only item(s) that have "disregard shipping" ticked.
     In this case, WPEC doesn't mention shipping at all during checkout, and this shipping module probably won't be executed at all.
     Just in case it does get queried, we should still override the quoted price(s) to $0.00 so the customer is able to get free shipping.
     2. Cart consists of only item(s) where "disregard shipping" isn't ticked (ie. all item(s) attract shipping charges).
     In this case, we should query the quote as per normal.
     3. Cart consists of one or more "disregard shipping" product(s), and one or more other products that attract shipping charges.
     In this case, we should query the quote, only taking into account the product(s) that attract shipping charges.
     Products with "disregard shipping" ticked shouldn't have their weight or dimensions included in the quote.
     */
     // Weight is in grams
     $weight = wpsc_convert_weight($wpsc_cart->calculate_total_weight(true), 'pound', 'gram');
     // Calculate the total cart dimensions by adding the volume of each product then calculating the cubed root
     $volume = 0;
     // Total number of item(s) in the cart
     $numItems = count($wpsc_cart->cart_items);
     if ($numItems == 0) {
         // The customer's cart is empty. This probably shouldn't occur, but just in case!
         return array();
     }
     // Total number of item(s) that don't attract shipping charges.
     $numItemsWithDisregardShippingTicked = 0;
     foreach ($wpsc_cart->cart_items as $cart_item) {
         if (!$cart_item->uses_shipping) {
             // The "Disregard Shipping for this product" option is ticked for this item.
             // Don't include it in the shipping quote.
             $numItemsWithDisregardShippingTicked++;
             continue;
         }
         // If we are here then this item attracts shipping charges.
         $meta = get_product_meta($cart_item->product_id, 'product_metadata', true);
         $meta = $meta['dimensions'];
         if ($meta && is_array($meta)) {
             $productVolume = 1;
             foreach (array('width', 'height', 'length') as $dimension) {
                 // Cubi square of the dimension to get the volume of the box it will be squared later
                 switch ($meta["{$dimension}_unit"]) {
                     // we need the units in mm
                     case 'cm':
                         // convert from cm to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 10);
                         break;
                     case 'meter':
                         // convert from m to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 1000);
                         break;
                     case 'in':
                         // convert from in to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 25.4);
                         break;
                 }
             }
             $volume += floatval($productVolume);
         }
     }
     // Calculate the cubic root of the total volume, rounding up
     $cuberoot = ceil(pow($volume, 1 / 3));
     // Use default dimensions of 100mm if the volume is zero
     $height = 100;
     // Mettre dans les options, todo
     $width = 100;
     $length = 100;
     if ($cuberoot > 0) {
         $height = $width = $length = $cuberoot;
     }
     if ($length < 100) {
         $length = 100;
     }
     if ($width < 100) {
         $width = 100;
     }
     $shippingPriceNeedsToBeZero = false;
     if ($numItemsWithDisregardShippingTicked == $numItems) {
         // The cart consists of entirely "disregard shipping" products, so the shipping quote(s) should be $0.00
         // Set the weight to 1 gram so that we can obtain valid Australia Post quotes (which we will then ignore the quoted price of)
         $weight = 1;
         $shippingPriceNeedsToBeZero = true;
     }
     //API :
     $wpcb_livraison_options = get_option('wpcb_livraison');
     $post_data['wpcb_livraison_options'] = $wpcb_livraison_options;
     //peut-etre faut il les serializer ?
     $wpcb_general = get_option('wpcb_general');
     $post_data['apiKey'] = $wpcb_general['apiKey'];
     $post_data['emailapiKey'] = $wpcb_general['emailapiKey'];
     $response = wp_remote_post('http://wpcb.fr/api/wpcb/valid.php', array('body' => $post_data));
     $valid = unserialize($response['body']);
     if ($valid[0]) {
         //Cle API valid, on peut aller chercher des tarifs speciaux // Pas necessaire car déjà vérifier après... à réfléchir
         // Ajouter ici les services en fonction de l'admin :
         $services = array();
         if ($wpcb_livraison_options['ENLEVEMENT']) {
             $services[] = 'ENLEVEMENT';
         }
         if ($wpcb_livraison_options['COLIS']) {
             $services[] = 'COLIS';
         }
         if ($wpcb_livraison_options['LETTREPRIORITAIRE']) {
             $services[] = 'LETTREPRIORITAIRE';
         }
         if ($wpcb_livraison_options['LETTREVERTE']) {
             $services[] = 'LETTREVERTE';
         }
         if ($wpcb_livraison_options['CHRONOPOST']) {
             $services[] = 'CHRONOPOST';
         }
         if ($wpcb_livraison_options['ENVELOPPEDOCUMENT']) {
             $services[] = 'ENVELOPPEDOCUMENT';
         }
         if ($wpcb_livraison_options['ENVELOPPEDOCUMENTUE']) {
             $services[] = 'ENVELOPPEDOCUMENTUE';
         }
         if ($wpcb_livraison_options['ENVELOPPEDOCUMENTOMRDM']) {
             $services[] = 'ENVELOPPEDOCUMENTOMRDM';
         }
         //		echo '***';
         //		print_r($services);
         //		echo '///';
         $post_data['services'] = $services;
         $post_data['Weight'] = $weight;
         $post_data['Country'] = $dest;
         $response = wp_remote_post('http://wpcb.fr/api/wpcb/livraison/getQuote.php', array('body' => $post_data));
         // Validation de la clé a l'intérieur
         //			echo '£££'.$response['body'].'£££';
         $response = unserialize($response['body']);
         //			echo '%%%';
         //			print_r($response);
         //			echo '%%%';
         if ($response['valid']) {
             foreach ($services as $dummy => $service) {
                 //					echo '<<<'.$service.'^^^';
                 $name = $service . '_name';
                 $methods[$service]['name'] = $wpcb_livraison_options[$name];
                 // A mettre dans les options ex : LETTREMAX_name
                 $methods[$service]['charge'] = $response[$service]['charge'];
                 // Ne coute rien
                 $methods[$service]['err_msg'] = $response[$service]['err_msg'];
             }
         } else {
             // non valid apikey
             //echo 'non valid key';
             //print_r($response);
         }
     } else {
         //non valid api Key
     }
     //print_r($methods);
     // Allow another WordPress plugin to override the quoted method(s)/amount(s)
     $methods = apply_filters('wpcb_livraison_methods', $methods, $this->base_zipcode, $destzipcode, $dest, $weight);
     $quotedMethods = array();
     // Debug :
     //$text = sprintf('Poids : %1$d grammes',$params['Weight']);
     //$quotedMethods[$text] = 1;
     //echo '****';
     //print_r($methods);
     //echo '****';
     if ($methods) {
         foreach ($methods as $key => $data) {
             // Only include methods with an OK response
             if ($data['err_msg'] == 'OK') {
                 // Only include methods that are checked in the admin :
                 //if (!$this->settings['services'][$code]) continue;
                 $text = $data['name'];
                 $quotedMethods[$text] = $data['charge'];
             }
         }
     }
     //print_r($quotedMethods);
     return $quotedMethods;
 }
Exemple #7
0
/**
 * wpsc_ajax_ie_save save changes made using inline edit
 *
 * @public
 *
 * @3.8
 * @returns nothing
 */
function wpsc_ajax_ie_save()
{
    $product_post_type = get_post_type_object('wpsc-product');
    if (!current_user_can($product_post_type->cap->edit_posts)) {
        echo '({"error":"' . __('Error: you don\'t have required permissions to edit this product', 'wpsc') . '", "id": "' . $_POST['id'] . '"})';
        die;
    }
    $product = array('ID' => $_POST['id'], 'post_title' => $_POST['title']);
    $id = wp_update_post($product);
    if ($id > 0) {
        //need parent meta to know which weight unit we are using
        $post = get_post($id);
        $parent_meta = get_product_meta($post->post_parent, 'product_metadata', true);
        $product_meta = get_product_meta($product['ID'], 'product_metadata', true);
        if (is_numeric($_POST['weight']) || empty($_POST['weight'])) {
            $product_meta['weight'] = wpsc_convert_weight($_POST['weight'], $parent_meta['weight_unit'], 'pound', true);
            $product_meta['weight_unit'] = $parent_meta['weight_unit'];
        }
        update_product_meta($product['ID'], 'product_metadata', $product_meta);
        update_product_meta($product['ID'], 'price', (double) $_POST['price']);
        update_product_meta($product['ID'], 'special_price', (double) $_POST['special_price']);
        update_product_meta($product['ID'], 'sku', $_POST['sku']);
        if (!is_numeric($_POST['stock'])) {
            update_product_meta($product['ID'], 'stock', '');
        } else {
            update_product_meta($product['ID'], 'stock', absint($_POST['stock']));
        }
        $post = get_post($id);
        $meta = get_product_meta($id, 'product_metadata', true);
        $price = get_product_meta($id, 'price', true);
        $special_price = get_product_meta($id, 'special_price', true);
        $sku = get_product_meta($id, 'sku', true);
        $sku = $sku ? $sku : __('N/A', 'wpsc');
        $stock = get_product_meta($id, 'stock', true);
        $stock = $stock === '' ? __('N/A', 'wpsc') : $stock;
        $results = array('id' => $id, 'title' => $post->post_title, 'weight' => wpsc_convert_weight($meta['weight'], 'pound', $parent_meta['weight_unit']), 'price' => wpsc_currency_display($price), 'special_price' => wpsc_currency_display($special_price), 'sku' => $sku, 'stock' => $stock);
        echo '(' . json_encode($results) . ')';
        die;
    } else {
        echo '({"error":"' . __('Error updating product', 'wpsc') . '", "id": "' . $_POST['id'] . '"})';
    }
    die;
}
function wpsc_convert_variation_combinations()
{
    global $wpdb, $user_ID, $current_version_number;
    $wpsc_update = WPSC_Update::get_instance();
    remove_filter('get_terms', 'wpsc_get_terms_category_sort_filter');
    if (!($offset = get_transient('wpsc_update_variation_comb_offset'))) {
        $offset = 0;
    }
    $limit = 150;
    wp_defer_term_counting(true);
    $sql = "SELECT * FROM {$wpdb->posts} WHERE post_type = 'wpsc-product' AND post_parent = 0 LIMIT %d, %d";
    $total = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'wpsc-product' AND post_parent = 0");
    $progress = new WPSC_Update_Progress($total);
    while (true) {
        // get the posts
        // I use a direct SQL query here because the get_posts function sometimes does not function for a reason that is not clear.
        $posts = $wpdb->get_results($wpdb->prepare($sql, $offset, $limit));
        $i = $offset;
        if (empty($posts)) {
            break;
        }
        foreach ((array) $posts as $post) {
            if (!($child_products = get_transient('wpsc_update_current_child_products'))) {
                $child_products = array();
            }
            $wpsc_update->check_timeout();
            $base_product_terms = array();
            //create a post template
            $child_product_template = array('post_author' => $user_ID, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_title' => $post->post_title, 'post_status' => 'inherit', 'post_type' => "wpsc-product", 'post_name' => $post->post_title, 'post_parent' => $post->ID);
            // select the original product ID
            $original_id = get_post_meta($post->ID, '_wpsc_original_id', true);
            $parent_stock = get_post_meta($post->ID, '_wpsc_stock', true);
            // select the variation set associations
            $variation_set_associations = $wpdb->get_col("SELECT `variation_id` FROM " . WPSC_TABLE_VARIATION_ASSOC . " WHERE `associated_id` = '{$original_id}'");
            // select the variation associations if the count of variation sets is greater than zero
            if ($original_id > 0 && count($variation_set_associations) > 0) {
                $variation_associations = $wpdb->get_col("SELECT `value_id` FROM " . WPSC_TABLE_VARIATION_VALUES_ASSOC . " WHERE `product_id` = '{$original_id}' AND `variation_id` IN(" . implode(", ", $variation_set_associations) . ") AND `visible` IN ('1')");
            } else {
                // otherwise, we have no active variations, skip to the next product
                $i++;
                $progress->update($i);
                set_transient('wpsc_update_variation_comb_offset', $i, 604800);
                continue;
            }
            $variation_set_id_sql = "SELECT meta_value FROM " . WPSC_TABLE_META . " WHERE object_type='wpsc_variation_set' AND object_id IN (" . implode(',', $variation_set_associations) . ") AND meta_key = 'variation_set_id'";
            $variation_set_terms = $wpdb->get_col($variation_set_id_sql);
            $variation_associations_sql = "SELECT meta_value FROM " . WPSC_TABLE_META . " WHERE object_type='wpsc_variation' AND object_id IN (" . implode(',', $variation_associations) . ") AND meta_key = 'variation_id'";
            $variation_associations_terms = $wpdb->get_col($variation_associations_sql);
            $base_product_terms = array_merge($base_product_terms, $variation_set_terms, $variation_associations_terms);
            // Now that we have the term IDs, we need to retrieve the slugs, as wp_set_object_terms will not use IDs in the way we want
            // If we pass IDs into wp_set_object_terms, it creates terms using the ID as the name.
            $parent_product_terms = get_terms('wpsc-variation', array('hide_empty' => 0, 'include' => implode(",", $base_product_terms), 'orderby' => 'parent'));
            $base_product_term_slugs = array();
            foreach ($parent_product_terms as $parent_product_term) {
                $base_product_term_slugs[] = $parent_product_term->slug;
            }
            wp_set_object_terms($post->ID, $base_product_term_slugs, 'wpsc-variation');
            // select all variation "products"
            $variation_items = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_VARIATION_PROPERTIES . " WHERE `product_id` = '{$original_id}'");
            foreach ((array) $variation_items as $variation_item) {
                $wpsc_update->check_timeout();
                // initialize the requisite arrays to empty
                $variation_ids = array();
                $term_data = array('ids' => array(), 'slugs' => array(), 'names' => array());
                // make a temporary copy of the product teplate
                $product_values = $child_product_template;
                // select all values this "product" is associated with, then loop through them, getting the term id of the variation using the value ID
                $variation_associations_combinations = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_VARIATION_COMBINATIONS . " WHERE `priceandstock_id` = '{$variation_item->id}'");
                foreach ((array) $variation_associations_combinations as $association) {
                    $variation_id = (int) wpsc_get_meta($association->value_id, 'variation_id', 'wpsc_variation');
                    // discard any values that are null, as they break the selecting of the terms
                    if ($variation_id > 0 && in_array($association->value_id, $variation_associations)) {
                        $variation_ids[] = $variation_id;
                    }
                }
                // if we have more than zero remaining terms, get the term data, then loop through it to convert it to a more useful set of arrays.
                if (count($variation_ids) > 0 && count($variation_set_associations) == count($variation_ids)) {
                    $combination_terms = get_terms('wpsc-variation', array('hide_empty' => 0, 'include' => implode(",", $variation_ids)));
                    foreach ($combination_terms as $term) {
                        $term_data['ids'][] = $term->term_id;
                        $term_data['slugs'][] = $term->slug;
                        $term_data['names'][] = $term->name;
                    }
                    $product_values['post_title'] .= " (" . implode(", ", $term_data['names']) . ")";
                    $product_values['post_name'] = sanitize_title($product_values['post_title']);
                    $selected_post = get_posts(array('name' => $product_values['post_name'], 'post_parent' => $post->ID, 'post_type' => "wpsc-product", 'post_status' => 'all', 'suppress_filters' => true));
                    $selected_post = array_shift($selected_post);
                    $key = md5($post->ID . ':' . count($term_data['ids']) . ':' . implode(',', $term_data['ids']));
                    $child_product_id = false;
                    if (!empty($child_products[$key])) {
                        $child_product_id = $child_products[$key];
                    }
                    $post_data = array();
                    $post_data['_wpsc_price'] = (double) $variation_item->price;
                    $post_data['_wpsc_stock'] = (double) $variation_item->stock;
                    if (!is_numeric($parent_stock)) {
                        $post_data['_wpsc_stock'] = false;
                    }
                    $post_data['_wpsc_original_variation_id'] = (double) $variation_item->id;
                    // Product Weight
                    $post_data['_wpsc_product_metadata']['weight'] = wpsc_convert_weight($variation_item->weight, $variation_item->weight_unit, "pound", true);
                    $post_data['_wpsc_product_metadata']['display_weight_as'] = $variation_item->weight_unit;
                    $post_data['_wpsc_product_metadata']['weight_unit'] = $variation_item->weight_unit;
                    // Parts of the code (eg wpsc_product_variation_price_from() make the assumption that these meta keys exist
                    $post_data['_wpsc_special_price'] = 0;
                    $post_data['_wpsc_sku'] = '';
                    $already_exists = true;
                    if (!empty($selected_post) && $selected_post->ID != $child_product_id) {
                        $child_product_id = $selected_post->ID;
                    } elseif (empty($child_product_id)) {
                        $child_product_id = wp_insert_post($product_values);
                        $already_exists = false;
                    }
                    if ($child_product_id > 0) {
                        foreach ($post_data as $meta_key => $meta_value) {
                            // prefix all meta keys with _wpsc_
                            update_post_meta($child_product_id, $meta_key, $meta_value);
                        }
                        wp_set_object_terms($child_product_id, $term_data['slugs'], 'wpsc-variation');
                        if (!$already_exists) {
                            $child_products[$key] = $child_product_id;
                            set_transient('wpsc_update_current_child_products', $child_products, 604800);
                        }
                    }
                    unset($term_data);
                }
            }
            $i++;
            $progress->update($i);
            set_transient('wpsc_update_variation_comb_offset', $i, 604800);
            delete_transient('wpsc_update_current_child_products');
        }
        $offset += $limit;
    }
    delete_option("wpsc-variation_children");
    _get_term_hierarchy('wpsc-variation');
    delete_option("wpsc_product_category_children");
    _get_term_hierarchy('wpsc_product_category');
}
/**
 * wpsc_save_quickedit_box function
 * Saves input for the various meta in the quick edit boxes
 *
 * @todo UI
 * @todo Data validation / sanitization / security
 * @todo AJAX should probably return weight unit
 * @return $post_id (int) Post ID
 */
function wpsc_save_quickedit_box($post_id)
{
    global $current_screen, $doaction;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || empty($current_screen) || $current_screen->id != 'edit-wpsc-product') {
        return;
    }
    $bulk = isset($doaction) && $doaction == 'edit';
    $custom_fields = array('weight' => 'product_metadata', 'stock' => 'stock', 'price' => 'price', 'sale_price' => 'special_price', 'sku' => 'sku');
    $args = array('post_parent' => $post_id, 'post_type' => 'wpsc-product', 'post_status' => 'inherit');
    $children = get_children($args);
    $is_parent = (bool) $children;
    foreach ($custom_fields as $post_key => $meta_key) {
        $overideVariant = isset($_REQUEST[$post_key . '_variant']) && $_REQUEST[$post_key . '_variant'] == 'on';
        // don't update if we're bulk updating and the field is left blank, or if the product has children and the field is one of those fields defined below (unles overridden)
        if (!isset($_REQUEST[$post_key]) || $bulk && empty($_REQUEST[$post_key]) || $is_parent && in_array($post_key, array('weight', 'stock', 'price', 'special_price')) && !$overideVariant) {
            continue;
        }
        if ($is_parent && count($children) > 0) {
            $products = $children;
        } else {
            $products = array($post_id);
        }
        foreach ($products as $product) {
            $value = $_REQUEST[$post_key];
            if ($is_parent) {
                $post_id = $product->ID;
            } else {
                $post_id = $product;
            }
            switch ($post_key) {
                case 'weight':
                    $product_meta = get_post_meta($post_id, '_wpsc_product_metadata', true);
                    if (!is_array($product_meta)) {
                        $product_meta = array();
                    }
                    // draft products don't have product metadata set yet
                    $weight_unit = isset($product_meta["weight_unit"]) ? $product_meta["weight_unit"] : 'pound';
                    $weight = wpsc_convert_weight($value, $weight_unit, "pound", true);
                    if (isset($product_meta["weight"])) {
                        unset($product_meta["weight"]);
                    }
                    $product_meta["weight"] = $weight;
                    $value = $product_meta;
                    break;
                case 'stock':
                    if (!is_numeric($value)) {
                        $value = '';
                    }
                    break;
                case 'sku':
                    if ($value == __('N/A', 'wpsc')) {
                        $value = '';
                    }
                    break;
            }
            update_post_meta($post_id, "_wpsc_{$meta_key}", $value);
        }
    }
    return $post_id;
}
Exemple #10
0
 function getQuote()
 {
     global $wpdb, $wpsc_cart, $CodeEnseigne, $CodeMarque, $Pays, $ClePrivee;
     $wpcb_livraison_options = get_option('wpcb_livraison');
     if ($this->base_country != 'FR' || strlen($this->base_zipcode) != 5 || !count($wpsc_cart->cart_items)) {
         return;
     }
     $dest = $_SESSION['wpsc_delivery_country'];
     $destzipcode = '';
     if (isset($_POST['zipcode'])) {
         $destzipcode = $_POST['zipcode'];
         $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
     } else {
         if (isset($_SESSION['wpsc_zipcode'])) {
             $destzipcode = $_SESSION['wpsc_zipcode'];
         }
     }
     if ($dest == 'FR' && strlen($destzipcode) != 5) {
         return array();
     }
     // Weight is in grams
     $weight = wpsc_convert_weight($wpsc_cart->calculate_total_weight(true), 'pound', 'gram');
     // Calculate the total cart dimensions by adding the volume of each product then calculating the cubed root
     $volume = 0;
     // Total number of item(s) in the cart
     $numItems = count($wpsc_cart->cart_items);
     if ($numItems == 0) {
         // The customer's cart is empty. This probably shouldn't occur, but just in case!
         return array();
     }
     // Total number of item(s) that don't attract shipping charges.
     $numItemsWithDisregardShippingTicked = 0;
     foreach ($wpsc_cart->cart_items as $cart_item) {
         if (!$cart_item->uses_shipping) {
             // The "Disregard Shipping for this product" option is ticked for this item.
             // Don't include it in the shipping quote.
             $numItemsWithDisregardShippingTicked++;
             continue;
         }
         // If we are here then this item attracts shipping charges.
         $meta = get_product_meta($cart_item->product_id, 'product_metadata', true);
         $meta = $meta['dimensions'];
         if ($meta && is_array($meta)) {
             $productVolume = 1;
             foreach (array('width', 'height', 'length') as $dimension) {
                 // Cubi square of the dimension to get the volume of the box it will be squared later
                 switch ($meta["{$dimension}_unit"]) {
                     // we need the units in mm
                     case 'cm':
                         // convert from cm to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 10);
                         break;
                     case 'meter':
                         // convert from m to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 1000);
                         break;
                     case 'in':
                         // convert from in to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 25.4);
                         break;
                 }
             }
             $volume += floatval($productVolume);
         }
     }
     // Calculate the cubic root of the total volume, rounding up
     $cuberoot = ceil(pow($volume, 1 / 3));
     // Use default dimensions of 100mm if the volume is zero
     $height = 100;
     // Mettre dans les options, todo
     $width = 100;
     $length = 100;
     if ($cuberoot > 0) {
         $height = $width = $length = $cuberoot;
     }
     if ($length < 100) {
         $length = 100;
     }
     if ($width < 100) {
         $width = 100;
     }
     // todo : calculer la longueur déroulée.
     // todo : forcer la taille par un custom field dans le produit
     $shippingPriceNeedsToBeZero = false;
     if ($numItemsWithDisregardShippingTicked == $numItems) {
         // The cart consists of entirely "disregard shipping" products, so the shipping quote(s) should be $0.00
         // Set the weight to 1 gram so that we can obtain valid Australia Post quotes (which we will then ignore the quoted price of)
         $weight = 1;
         $shippingPriceNeedsToBeZero = true;
     }
     $params = array('Pickup_Postcode' => $this->base_zipcode, 'Destination_Postcode' => $destzipcode, 'Quantity' => 1, 'Weight' => $weight, 'Height' => $height, 'Width' => $width, 'Length' => $length, 'Country' => $dest);
     // Tableaux des destinations COLIS :
     $dest_colis_fr = array('FR');
     // to do ajouter les tableaux pour les autres pays
     // Param API
     if ($wpcb_livraison_options['mr_ComptePro']) {
         $ComptePro = true;
         $CodeEnseigne = $wpcb_livraison_options['mr_CodeEnseigne'];
         //'BDTESTMR';
         $ClePrivee = $wpcb_livraison_options['mr_ClePrivee'];
         //'TesT_MondiaL_RelaY';
         $CodeMarque = $wpcb_livraison_options['mr_CodeMarque'];
         //'11';
         // to do
         $Tarif['500']['HT'] = 3.6;
         $Tarif['500']['TTC'] = $Tarif['500']['HT'] * 1.196;
         $PoidsMax[0] = 500;
         //en gramme
         $Tarif['1000']['HT'] = 4.1;
         $Tarif['1000']['TTC'] = $Tarif['1000']['HT'] * 1.196;
         $PoidsMax[1] = 1000;
         //en gramme
         $Tarif['2000']['HT'] = 4.72;
         $Tarif['2000']['TTC'] = $Tarif['2000']['HT'] * 1.196;
         $PoidsMax[2] = 2000;
         //en gramme
         $Tarif['3000']['HT'] = 5.31;
         $Tarif['3000']['TTC'] = $Tarif['3000']['HT'] * 1.196;
         $PoidsMax[3] = 3000;
         //en gramme
         $Tarif['5000']['HT'] = 6.4;
         $Tarif['5000']['TTC'] = $Tarif['5000']['HT'] * 1.196;
         $PoidsMax[4] = 5000;
         //en gramme
         $Tarif['7000']['HT'] = 8.19;
         $Tarif['7000']['TTC'] = $Tarif['7000']['HT'] * 1.196;
         $PoidsMax[5] = 7000;
         //en gramme
         $Tarif['10000']['HT'] = 10.12;
         $Tarif['10000']['TTC'] = $Tarif['10000']['HT'] * 1.196;
         $PoidsMax[6] = 10000;
         //en gramme
         $Tarif['15000']['HT'] = 12.12;
         $Tarif['15000']['TTC'] = $Tarif['15000']['HT'] * 1.196;
         $PoidsMax[7] = 15000;
         //en gramme
         $Tarif['20000']['HT'] = 15.01;
         $Tarif['20000']['TTC'] = $Tarif['20000']['HT'] * 1.196;
         $PoidsMax[8] = 20000;
         //en gramme
         //print_r($Tarif);
     } else {
         $ComptePro = false;
         $Tarif['500'] = 4.3;
         $PoidsMax['500'] = 500;
         //en gramme
         $Tarif['1000'] = 4.9;
         $PoidsMax['1000'] = 1000;
         //en gramme
         $Tarif['2000'] = 5.65;
         $PoidsMax['2000'] = 2000;
         //en gramme
         $Tarif['3000'] = 6.35;
         $PoidsMax['3000'] = 3000;
         //en gramme
         $Tarif['5000'] = 7.65;
         $PoidsMax['5000'] = 5000;
         //en gramme
         $Tarif['7000'] = 9.800000000000001;
         $PoidsMax['7000'] = 7000;
         //en gramme
         $Tarif['10000'] = 12.1;
         $PoidsMax['10000'] = 10000;
         //en gramme
         $Tarif['15000'] = 14.5;
         $PoidsMax['15000'] = 15000;
         //en gramme
         $Tarif['20000'] = 17.95;
         $PoidsMax['20000'] = 20000;
         //en gramme
     }
     // Adresse
     $CP = $destzipcode;
     $Pays = $params['Country'];
     $Ville = '';
     // colis :
     // Utilisation de l'api "home-made" (uniquement a destination de france métropolitaine)
     if (in_array($params['Country'], $dest_colis_fr)) {
         // Tarifs à  destination de la france :
         //Table tarifaire colis France Métropolitaine et Monaco
         // Check if custom field before
         if ($ComptePro) {
             require_once 'lib/nusoap.php';
             $client = new nusoap_client("http://www.mondialrelay.fr/WebService/Web_Services.asmx?WSDL", true);
             $client->soap_defencoding = 'utf-8';
             $Action = '24R';
             // todo
             if ($params['Weight'] >= 0 && $params['Weight'] <= 500) {
                 $MaxWeight = 500;
             } elseif ($params['Weight'] > 500 && $params['Weight'] <= 1000) {
                 $MaxWeight = 1000;
             } elseif ($params['Weight'] > 1000 && $params['Weight'] <= 2000) {
                 $MaxWeight = 2000;
             } elseif ($params['Weight'] > 2000 && $params['Weight'] <= 3000) {
                 $MaxWeight = 3000;
             } elseif ($params['Weight'] > 3000 && $params['Weight'] <= 5000) {
                 $MaxWeight = 5000;
             } elseif ($params['Weight'] > 5000 && $params['Weight'] <= 7000) {
                 $MaxWeight = 7000;
             } elseif ($params['Weight'] > 7000 && $params['Weight'] <= 10000) {
                 $MaxWeight = 10000;
             } elseif ($params['Weight'] > 10000 && $params['Weight'] <= 15000) {
                 $MaxWeight = 15000;
             } elseif ($params['Weight'] > 15000 && $params['Weight'] <= 20000) {
                 $MaxWeight = 20000;
             } else {
                 $MaxWeight = false;
             }
             if ($MaxWeight) {
                 // API Mondial Relay :
                 // Produits :
                 $Taille = '';
                 //Facultatif pour l'api
                 $Poids = '';
                 //Facultatif pour l'api
                 $paramsAPI = array('Enseigne' => $CodeEnseigne, 'Pays' => $Pays, 'Ville' => $Ville, 'CP' => $CP, 'Taille' => $Taille, 'Poids' => $Poids, 'Action' => $Action, 'Security' => strtoupper(md5($CodeEnseigne . $Pays . $Ville . $CP . $Taille . $Poids . $Action . $ClePrivee)));
                 $result = $client->call('WSI2_RecherchePointRelais', $paramsAPI, 'http://www.mondialrelay.fr/webservice/', 'http://www.mondialrelay.fr/webservice/WSI2_RecherchePointRelais');
                 if ($client->fault) {
                     $methods['MONDIALRELAY']['err_msg'] = 'Fault (Expect - The request contains an invalid SOAP body)';
                 } else {
                     $err = $client->getError();
                     if ($err) {
                         $methods[$service_mondialrelay]['err_msg'] = 'Fault (Expect - The request contains an invalid SOAP body) :' . $err;
                     } else {
                         $PRs = array('PR01', 'PR02', 'PR03', 'PR04', 'PR05');
                         // add here if you want to show more
                         foreach ($PRs as $PR) {
                             $Num = $result['WSI2_RecherchePointRelaisResult'][$PR]['Num'];
                             $LgAdr1 = $result['WSI2_RecherchePointRelaisResult'][$PR]['LgAdr1'];
                             $LgAdr3 = $result['WSI2_RecherchePointRelaisResult'][$PR]['LgAdr3'];
                             $CPRelais = $result['WSI2_RecherchePointRelaisResult'][$PR]['CP'];
                             $VilleRelais = $result['WSI2_RecherchePointRelaisResult'][$PR]['Ville'];
                             $MapLink = 'http://www.mondialrelay.com/public/permanent/details_relais.aspx?ens=' . $CodeEnseigne . $CodeMarque . '&num=' . $Num . '&pays=' . $Pays . '&crc=' . strtoupper(md5('<' . $CodeEnseigne . $CodeMarque . '>' . $Num . $Pays . '<' . $ClePrivee . '>'));
                             $service_mondialrelay = 'MONDIAL_RELAY_' . $Num;
                             // On ajoute ici le numéro pour differencier des diffentes méthodes de livraison
                             $methods[$service_mondialrelay]['name'] = 'MONDIAL RELAY (Relais : <a href=' . $MapLink . ' target=%22_blank%22>' . $Num . '</a> ' . $LgAdr1 . ', ' . $LgAdr3 . ', ' . $CPRelais . ' ' . $VilleRelais . ')';
                             $methods[$service_mondialrelay]['err_msg'] = 'OK';
                             $methods[$service_mondialrelay]['charge'] = $Tarif[$MaxWeight]['TTC'];
                             // TTC todo add taxe
                         }
                     }
                 }
             } else {
                 $methods[$service_mondialrelay]['err_msg'] = 'Poids non trouvé';
             }
         } else {
             // Compte Particulier France
             $service_mondialrelay = 'MONDIAL_RELAY_0';
             if ($params['Weight'] >= 0 && $params['Weight'] <= 1000) {
                 $Type = 'XS';
             } elseif ($params['Weight'] > 1000 && $params['Weight'] <= 3000) {
                 $Type = 'S';
             } elseif ($params['Weight'] > 3000 && $params['Weight'] <= 5000) {
                 $Type = 'M';
             } elseif ($params['Weight'] > 5000 && $params['Weight'] <= 10000) {
                 $Type = 'L';
             } elseif ($params['Weight'] > 10000 && $params['Weight'] <= 20000) {
                 $Type = 'XL';
             } else {
                 $Type = false;
             }
             if ($Type) {
                 $methods[$service_mondialrelay]['name'] = 'MONDIAL RELAY (Nous choisirons le Relais de livraison au plus proche de chez vous !)';
                 $methods[$service_mondialrelay]['err_msg'] = 'OK';
                 $methods[$service_mondialrelay]['charge'] = $Tarif[$Type];
             } else {
                 $methods[$service_mondialrelay]['err_msg'] = 'Poids inconnu';
             }
         }
         //Fin du compte particulier France
     } else {
         // Tarif internationaux //todo
         $methods[$service_mondialrelay]['name'] = 'Mondial Relay International';
         // Je ne connais pas les tarifs
         $methods[$service_mondialrelay]['err_msg'] = 'Todo';
     }
     // Fin de international
     // **********************************************************************************
     //print_r($methods);
     // Allow another WordPress plugin to override the quoted method(s)/amount(s)
     //$methods = apply_filters('wpsc_mondialrelay_methods', $methods, $this->base_zipcode, $destzipcode, $dest, $weight);
     $quotedMethods = array();
     foreach ($methods as $code => $data) {
         // Only include methods with an OK response
         if ($data['err_msg'] != 'OK') {
             continue;
         }
         $text = $data['name'];
         $quotedMethods[$text] = $data['charge'];
     }
     return $quotedMethods;
 }
/**
 * wpsc_save_quickedit_box function
 * Saves input for the various meta in the quick edit boxes
 *
 * @todo UI
 * @todo Data validation / sanitization / security
 * @todo AJAX should probably return weight unit
 * @return $post_id (int) Post ID
 */
function wpsc_save_quickedit_box($post_id)
{
    global $current_screen;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || empty($current_screen) || $current_screen->id != 'edit-wpsc-product' || !defined('DOING_AJAX') || !DOING_AJAX) {
        return;
    }
    $is_parent = (bool) wpsc_product_has_children($post_id);
    $product_meta = get_post_meta($post_id, '_wpsc_product_metadata', true);
    $weight_unit = $product_meta["weight_unit"];
    $weight = wpsc_convert_weight($_POST["weight"], $weight_unit, "pound", true);
    if (isset($product_meta["weight"])) {
        unset($product_meta["weight"]);
    }
    $product_meta["weight"] = $weight;
    if (!$is_parent) {
        update_post_meta($post_id, '_wpsc_product_metadata', $product_meta);
        if (is_numeric($_POST['stock'])) {
            update_post_meta($post_id, '_wpsc_stock', $_POST['stock']);
        } else {
            update_post_meta($post_id, '_wpsc_stock', '');
        }
        update_post_meta($post_id, '_wpsc_price', $_POST['price']);
        update_post_meta($post_id, '_wpsc_special_price', $_POST['sale_price']);
    }
    if ($_POST['sku'] == __('N/A', 'wpsc')) {
        update_post_meta($post_id, '_wpsc_sku', '');
    } else {
        update_post_meta($post_id, '_wpsc_sku', $_POST['sku']);
    }
    return $post_id;
}
Exemple #12
0
function wpsc_convert_variation_combinations()
{
    global $wpdb, $user_ID, $current_version_number;
    // get the posts
    // I use a direct SQL query here because the get_posts function sometimes does not function for a reason that is not clear.
    $posts = $wpdb->get_results("SELECT * FROM `{$wpdb->posts}` WHERE `post_type` IN('wpsc-product')");
    $posts = get_posts(array('post_type' => 'wpsc-product', 'post_status' => 'all', 'numberposts' => -1));
    foreach ((array) $posts as $post) {
        $base_product_terms = array();
        //create a post template
        $child_product_template = array('post_author' => $user_ID, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_title' => $post->post_title, 'post_status' => 'inherit', 'post_type' => "wpsc-product", 'post_name' => sanitize_title($post->post_title), 'post_parent' => $post->ID);
        // select the original product ID
        $original_id = get_post_meta($post->ID, '_wpsc_original_id', true);
        $parent_stock = get_post_meta($post->ID, '_wpsc_stock', true);
        // select the variation set associations
        $variation_set_associations = $wpdb->get_col("SELECT `variation_id` FROM " . WPSC_TABLE_VARIATION_ASSOC . " WHERE `associated_id` = '{$original_id}'");
        // select the variation associations if the count of variation sets is greater than zero
        if ($original_id > 0 && count($variation_set_associations) > 0) {
            $variation_associations = $wpdb->get_col("SELECT `value_id` FROM " . WPSC_TABLE_VARIATION_VALUES_ASSOC . " WHERE `product_id` = '{$original_id}' AND `variation_id` IN(" . implode(", ", $variation_set_associations) . ") AND `visible` IN ('1')");
        } else {
            // otherwise, we have no active variations, skip to the next product
            continue;
        }
        foreach ($variation_set_associations as $variation_set_id) {
            $base_product_terms[] = wpsc_get_meta($variation_set_id, 'variation_set_id', 'wpsc_variation_set');
        }
        foreach ($variation_associations as $variation_association_id) {
            $base_product_terms[] = wpsc_get_meta($variation_association_id, 'variation_id', 'wpsc_variation');
        }
        // Now that we have the term IDs, we need to retrieve the slugs, as wp_set_object_terms will not use IDs in the way we want
        // If we pass IDs into wp_set_object_terms, it creates terms using the ID as the name.
        $parent_product_terms = get_terms('wpsc-variation', array('hide_empty' => 0, 'include' => implode(",", $base_product_terms), 'orderby' => 'parent'));
        $base_product_term_slugs = array();
        foreach ($parent_product_terms as $parent_product_term) {
            $base_product_term_slugs[] = $parent_product_term->slug;
        }
        wp_set_object_terms($post->ID, $base_product_term_slugs, 'wpsc-variation');
        // select all variation "products"
        $variation_items = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_VARIATION_PROPERTIES . " WHERE `product_id` = '{$original_id}'");
        foreach ((array) $variation_items as $variation_item) {
            // initialize the requisite arrays to empty
            $variation_ids = array();
            $term_data = array();
            // make a temporary copy of the product teplate
            $product_values = $child_product_template;
            // select all values this "product" is associated with, then loop through them, getting the term id of the variation using the value ID
            $variation_associations_combinations = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_VARIATION_COMBINATIONS . " WHERE `priceandstock_id` = '{$variation_item->id}'");
            foreach ((array) $variation_associations_combinations as $association) {
                $variation_id = (int) wpsc_get_meta($association->value_id, 'variation_id', 'wpsc_variation');
                // discard any values that are null, as they break the selecting of the terms
                if ($variation_id > 0 && in_array($association->value_id, $variation_associations)) {
                    $variation_ids[] = $variation_id;
                }
            }
            // if we have more than zero remaining terms, get the term data, then loop through it to convert it to a more useful set of arrays.
            if (count($variation_ids) > 0 && count($variation_set_associations) == count($variation_ids)) {
                $combination_terms = get_terms('wpsc-variation', array('hide_empty' => 0, 'include' => implode(",", $variation_ids), 'orderby' => 'parent'));
                foreach ($combination_terms as $term) {
                    $term_data['ids'][] = $term->term_id;
                    $term_data['slugs'][] = $term->slug;
                    $term_data['names'][] = $term->name;
                }
                $product_values['post_title'] .= " (" . implode(", ", $term_data['names']) . ")";
                $product_values['post_name'] = sanitize_title($product_values['post_title']);
                $selected_post = get_posts(array('name' => $product_values['post_name'], 'post_parent' => $post->ID, 'post_type' => "wpsc-product", 'post_status' => 'all', 'suppress_filters' => true));
                $selected_post = array_shift($selected_post);
                $child_product_id = wpsc_get_child_object_in_terms($post->ID, $term_data['ids'], 'wpsc-variation');
                $post_data = array();
                $post_data['_wpsc_price'] = (double) $variation_item->price;
                $post_data['_wpsc_stock'] = (double) $variation_item->stock;
                if (!is_numeric($parent_stock)) {
                    $post_data['_wpsc_stock'] = false;
                }
                $post_data['_wpsc_original_variation_id'] = (double) $variation_item->id;
                // Product Weight
                $post_data['_wpsc_product_metadata']['weight'] = wpsc_convert_weight($variation_item->weight, $variation_item->weight_unit, "pound", true);
                $post_data['_wpsc_product_metadata']['display_weight_as'] = $variation_item->weight_unit;
                $post_data['_wpsc_product_metadata']['weight_unit'] = $variation_item->weight_unit;
                //file
                if ($child_product_id == false) {
                    if ($selected_post != null) {
                        $child_product_id = $selected_post->ID;
                    } else {
                        $child_product_id = wp_update_post($product_values);
                    }
                } else {
                    // sometimes there have been problems saving the variations, this gets the correct product ID
                    if ($selected_post != null && $selected_post->ID != $child_product_id) {
                        $child_product_id = $selected_post->ID;
                    }
                }
                if ($child_product_id > 0) {
                    foreach ($post_data as $meta_key => $meta_value) {
                        // prefix all meta keys with _wpsc_
                        update_post_meta($child_product_id, $meta_key, $meta_value);
                    }
                    wp_set_object_terms($child_product_id, $term_data['slugs'], 'wpsc-variation');
                }
                unset($term_data);
            }
        }
    }
    delete_option("wpsc-variation_children");
    _get_term_hierarchy('wpsc-variation');
    delete_option("wpsc_product_category_children");
    _get_term_hierarchy('wpsc_product_category');
}
Exemple #13
0
/**
* wpsc_sanitise_product_forms function 
* 
* @return array - Sanitised product details
*/
function wpsc_sanitise_product_forms($post_data = null)
{
    if (empty($post_data)) {
        $post_data =& $_POST;
    }
    $product = get_post(absint($post_data['post_ID']));
    $post_data['name'] = isset($post_data['post_title']) ? $post_data['post_title'] : '';
    $post_data['title'] = $post_data['name'];
    $post_data['description'] = isset($post_data['content']) ? $post_data['content'] : '';
    $post_data['additional_description'] = isset($post_data['additional_description']) ? $post_data['additional_description'] : '';
    if ($product != null) {
        $post_data['post_status'] = $product->post_status;
    } else {
        $post_data['post_status'] = 'draft';
    }
    if (isset($post_data['save']) && $product->post_status == 'inherit' && ($product->post_parent == 0 || $product->post_parent == $product->ID)) {
        $post_data['post_status'] = 'draft';
    } else {
        if (isset($post_data['publish'])) {
            $post_data['post_status'] = 'publish';
        } else {
            if (isset($post_data['unpublish'])) {
                $post_data['post_status'] = 'draft';
            }
        }
    }
    $post_meta['meta'] = (array) $_POST['meta'];
    $post_data['meta']['_wpsc_price'] = (double) str_replace(',', '', $post_data['meta']['_wpsc_price']);
    $post_data['meta']['_wpsc_special_price'] = (double) str_replace(',', '', $post_data['meta']['_wpsc_special_price']);
    $post_data['meta']['_wpsc_sku'] = $post_data['meta']['_wpsc_sku'];
    if (!isset($post_data['meta']['_wpsc_is_donation'])) {
        $post_data['meta']['_wpsc_is_donation'] = '';
    }
    $post_data['meta']['_wpsc_is_donation'] = (int) (bool) $post_data['meta']['_wpsc_is_donation'];
    $post_data['meta']['_wpsc_stock'] = (int) $post_data['meta']['_wpsc_stock'];
    if (!isset($post_data['meta']['_wpsc_limited_stock'])) {
        $post_data['meta']['_wpsc_limited_stock'] = '';
    }
    if ((bool) $post_data['meta']['_wpsc_limited_stock'] != true) {
        $post_data['meta']['_wpsc_stock'] = false;
    }
    unset($post_data['meta']['_wpsc_limited_stock']);
    if (!isset($post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'])) {
        $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'] = '';
    }
    if (!isset($post_data['quantity_limited'])) {
        $post_data['quantity_limited'] = '';
    }
    if (!isset($post_data['special'])) {
        $post_data['special'] = '';
    }
    if (!isset($post_data['meta']['_wpsc_product_metadata']['no_shipping'])) {
        $post_data['meta']['_wpsc_product_metadata']['no_shipping'] = '';
    }
    $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'];
    $post_data['meta']['_wpsc_product_metadata']['quantity_limited'] = (int) (bool) $post_data['quantity_limited'];
    $post_data['meta']['_wpsc_product_metadata']['special'] = (int) (bool) $post_data['special'];
    $post_data['meta']['_wpsc_product_metadata']['no_shipping'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['no_shipping'];
    // Product Weight
    if (!isset($post_data['meta']['_wpsc_product_metadata']['display_weight_as'])) {
        $post_data['meta']['_wpsc_product_metadata']['display_weight_as'] = '';
    }
    if (!isset($post_data['meta']['_wpsc_product_metadata']['display_weight_as'])) {
        $post_data['meta']['_wpsc_product_metadata']['display_weight_as'] = '';
    }
    $weight = wpsc_convert_weight($post_data['meta']['_wpsc_product_metadata']['weight'], $post_data['meta']['_wpsc_product_metadata']['weight_unit'], "pound", true);
    $post_data['meta']['_wpsc_product_metadata']['weight'] = (double) $weight;
    $post_data['meta']['_wpsc_product_metadata']['display_weight_as'] = $post_data['meta']['_wpsc_product_metadata']['weight_unit'];
    // table rate price
    $post_data['meta']['_wpsc_product_metadata']['table_rate_price'] = $post_data['table_rate_price'];
    // if table_rate_price is unticked, wipe the table rate prices
    if (!isset($post_data['table_rate_price']['state'])) {
        $post_data['table_rate_price']['state'] = '';
    }
    if ($post_data['table_rate_price']['state'] != 1) {
        $post_data['meta']['_wpsc_product_metadata']['table_rate_price']['quantity'] = null;
        $post_data['meta']['_wpsc_product_metadata']['table_rate_price']['table_price'] = null;
    }
    foreach ((array) $post_data['meta']['_wpsc_product_metadata']['table_rate_price']['table_price'] as $key => $value) {
        if (empty($value)) {
            unset($post_data['meta']['_wpsc_product_metadata']['table_rate_price']['table_price'][$key]);
            unset($post_data['meta']['_wpsc_product_metadata']['table_rate_price']['quantity'][$key]);
        }
    }
    $post_data['meta']['_wpsc_product_metadata']['shipping']['local'] = (double) $post_data['meta']['_wpsc_product_metadata']['shipping']['local'];
    $post_data['meta']['_wpsc_product_metadata']['shipping']['international'] = (double) $post_data['meta']['_wpsc_product_metadata']['shipping']['international'];
    // Advanced Options
    $post_data['meta']['_wpsc_product_metadata']['engraved'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['engraved'];
    $post_data['meta']['_wpsc_product_metadata']['can_have_uploaded_image'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['can_have_uploaded_image'];
    if (!isset($post_data['meta']['_wpsc_product_metadata']['google_prohibited'])) {
        $post_data['meta']['_wpsc_product_metadata']['google_prohibited'] = '';
    }
    $post_data['meta']['_wpsc_product_metadata']['google_prohibited'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['google_prohibited'];
    $post_data['meta']['_wpsc_product_metadata']['external_link'] = (string) $post_data['meta']['_wpsc_product_metadata']['external_link'];
    $post_data['meta']['_wpsc_product_metadata']['external_link_text'] = (string) $post_data['meta']['_wpsc_product_metadata']['external_link_text'];
    $post_data['meta']['_wpsc_product_metadata']['external_link_target'] = (string) $post_data['meta']['_wpsc_product_metadata']['external_link_target'];
    $post_data['meta']['_wpsc_product_metadata']['enable_comments'] = $post_data['meta']['_wpsc_product_metadata']['enable_comments'];
    $post_data['meta']['_wpsc_product_metadata']['merchant_notes'] = $post_data['meta']['_wpsc_product_metadata']['merchant_notes'];
    $post_data['files'] = $_FILES;
    return $post_data;
}
Exemple #14
0
function update_record_metadata($update_column, &$wpsc_product_metadata, $params, $action_name)
{
    foreach ($wpsc_product_metadata as $key => $value) {
        switch ($update_column) {
            case 'weight':
                if (isset($params['unit']) && !empty($params['unit'])) {
                    $wpsc_product_metadata[$key]['weight_unit'] = $params['unit'];
                }
                $wpsc_product_metadata[$key]['display_weight_as'] = $params['unit'];
                eval('$wpsc_product_metadata[$key][weight] = perform_action($action_name,$wpsc_product_metadata[$key][weight], $params);');
                // insert the product weight in pound unit since wp-e-commerce does the same.
                $wpsc_product_metadata[$key][weight] = wpsc_convert_weight($wpsc_product_metadata[$key][weight], $wpsc_product_metadata[$key]['weight_unit'], "pound", true);
                break;
            case 'height':
                if (isset($params['unit']) && !empty($params['unit'])) {
                    $wpsc_product_metadata[$key]['dimensions']['height_unit'] = $params['unit'];
                }
                eval('$wpsc_product_metadata[$key][dimensions][height] = perform_action($action_name,$wpsc_product_metadata[$key][dimensions][height], $params);');
                break;
            case 'width':
                if (isset($params['unit']) && !empty($params['unit'])) {
                    $wpsc_product_metadata[$key]['dimensions']['width_unit'] = $params['unit'];
                }
                eval('$wpsc_product_metadata[$key][dimensions][width] = perform_action($action_name,$wpsc_product_metadata[$key][dimensions][width], $params);');
                break;
            case 'length':
                if (isset($params['unit']) && !empty($params['unit'])) {
                    $wpsc_product_metadata[$key]['dimensions']['length_unit'] = $params['unit'];
                }
                eval('$wpsc_product_metadata[$key][dimensions][length] = perform_action($action_name,$wpsc_product_metadata[$key][dimensions][length], $params);');
                break;
            case 'local':
                eval('$wpsc_product_metadata[$key][shipping][local] = perform_action($action_name,$wpsc_product_metadata[$key][shipping][local], $params);');
                break;
            case 'international':
                eval('$wpsc_product_metadata[$key][shipping][international] = perform_action($action_name,$wpsc_product_metadata[$key][shipping][international], $params);');
                break;
            case 'no_shipping':
                eval('$wpsc_product_metadata[$key][no_shipping] = perform_action($action_name,$wpsc_product_metadata[$key][no_shipping], $params);');
                break;
            case 'quantity_limited':
                eval('$wpsc_product_metadata[$key][quantity_limited] = perform_action($action_name,$wpsc_product_metadata[$key][quantity_limited], $params);');
                break;
            case 'unpublish_when_none_left':
                eval('$wpsc_product_metadata[$key][unpublish_when_none_left] = perform_action($action_name,$wpsc_product_metadata[$key][unpublish_when_none_left], $params);');
                break;
        }
    }
}
function data_for_insert_update($post)
{
    global $result, $wpdb, $user_ID;
    require_once WP_PLUGIN_DIR . '/wp-e-commerce/wpsc-admin/includes/product-functions.php';
    $_POST = $post;
    // Fix: PHP 5.4
    $selected_object = json_decode($_POST['selected']);
    $edited_object = json_decode($_POST['edited']);
    $objectArray = array();
    if (is_array($edited_object)) {
        foreach ($edited_object as $obj) {
            array_push($objectArray, $obj);
        }
    }
    if (is_array($selected_object)) {
        foreach ($selected_object as $obj) {
            if (!in_array($obj, $objectArray)) {
                array_push($objectArray, $obj);
            }
        }
    }
    $insertCnt = 1;
    $updateCnt = 1;
    $result['updated'] = 0;
    $result['inserted'] = 0;
    $result['productId'] = array();
    if (is_array($objectArray)) {
        foreach ($objectArray as $obj) {
            if (isset($obj->id) && $obj->id != '') {
                $post = get_post($obj->id);
            }
            // Default $post Array used only to INSERT new post & get postId which will be used as productId.
            // FOR wp_insert_post FUNCTION
            $post = array('ID' => $obj->id, 'menu_order' => isset($post->menu_order) ? $post->menu_order : 0, 'comment_status' => isset($post->comment_status) ? $post->comment_status : 'closed', 'ping_status' => isset($post->ping_status) ? $post->ping_status : 'closed', 'pinged' => isset($post->pinged) ? $post->pinged : '', 'post_author' => isset($post->post_author) ? $post->post_author : $user_ID, 'post_category' => '', 'post_content' => $obj->post_content, 'post_date' => isset($post->post_date) ? $post->post_date : '', 'post_date_gmt' => isset($post->post_date_gmt) ? $post->post_date_gmt : '', 'post_excerpt' => $obj->post_excerpt, 'post_name' => isset($post->post_name) ? $post->post_name : '', 'post_parent' => $obj->post_parent, 'post_password' => isset($post->post_password) ? $post->post_password : '', 'post_title' => $obj->post_title, 'post_status' => $obj->post_status, 'post_type' => 'wpsc-product', 'to_ping' => isset($post->to_ping) ? $post->to_ping : '', 'post_content_filtered' => isset($post->post_content_filtered) ? $post->post_content_filtered : '');
            //Default $data Array
            //FOR wpsc_pre_update FUNCTION & FOR wpsc_admin_submit_product FUNCTION
            $data = array('post_author' => $user_ID, 'post_date' => date('Y-m-d H:i:s'), 'post_date_gmt' => gmdate('Y-m-d H:i:s'), 'post_content' => $obj->post_content, 'post_title' => $obj->post_title, 'post_excerpt' => $obj->post_excerpt, 'post_status' => $obj->post_status, 'post_type' => 'wpsc-product', 'comment_status' => 'closed', 'ping_status' => 'closed', 'post_password' => '', 'post_name' => '', 'to_ping' => '', 'pinged' => '', 'post_modified' => date('Y-m-d H:i:s'), 'post_modified_gmt' => gmdate('Y-m-d H:i:s'), 'post_parent' => $obj->post_parent, 'menu_order' => 0, 'guid' => '', 'post_content_filtered' => '');
            // 'tax_input' 	   => Array (
            // 												'product_tag' 			=> 1, 						  // product_tag
            // 												'wpsc_product_category' => Array (0 => $obj->category ), // product category
            // 												'wpsc-variation' 		=> Array (0 => 0 ) 			  // product variation
            // 											),
            //FOR wpsc_pre_update FUNCTION & FOR wpsc_admin_submit_product FUNCTION
            //(not passed as an argument but used in the function)
            $wpsc_product_metadeta = array('wpec_taxes_taxable_amount' => '', 'external_link' => '', 'external_link_text' => '', 'external_link_target' => '', 'weight' => $obj->weight, 'weight_unit' => $obj->weight_unit, 'display_weight_as' => $obj->weight_unit, 'dimensions' => array('height' => $obj->height, 'height_unit' => $obj->height_unit, 'width' => $obj->width, 'width_unit' => $obj->width_unit, 'length' => $obj->length, 'length_unit' => $obj->length_unit), 'shipping' => array('local' => $obj->local, 'international' => $obj->international), 'no_shipping' => $obj->no_shipping, 'merchant_notes' => '', 'engraved' => 0, 'can_have_uploaded_image' => 0, 'enable_comments' => '');
            if (!empty($_POST['isWPSC3814']) && $_POST['isWPSC3814'] == '1') {
                $wpsc_product_metadeta['dimensions'] = array('height' => $obj->height, 'width' => $obj->width, 'length' => $obj->length);
                $wpsc_product_metadeta['dimension_unit'] = $obj->dimension_unit;
            } else {
                $wpsc_product_metadeta['dimensions'] = array('height' => $obj->height, 'height_unit' => $obj->height_unit, 'width' => $obj->width, 'width_unit' => $obj->width_unit, 'length' => $obj->length, 'length_unit' => $obj->length_unit);
            }
            $_POST = array('original_publish' => $obj->post_status, 'publish' => $obj->post_status, 'meta' => array('_wpsc_price' => $obj->_wpsc_price, '_wpsc_special_price' => $obj->_wpsc_special_price, '_wpsc_sku' => $obj->_wpsc_sku, '_wpsc_stock' => $obj->_wpsc_stock, '_wpsc_product_metadata' => $wpsc_product_metadeta), 'table_rate_price' => array('quantity' => array(0 => ''), 'table_price' => array(0 => '')), 'ID' => '', 'product_id' => '', 'post_title' => $obj->post_title, 'content' => $obj->post_content, 'additional_description' => $obj->post_excerpt);
            if ($obj->id == '') {
                $result['inserted'] = 1;
                $product_id = wp_insert_post($post);
                $guid = site_url() . '/?post_type=wpsc-product&p=' . $product_id;
                $data['guid'] = $guid;
                $_POST['product_id'] = $product_id;
                $_POST['ID'] = $product_id;
                $data_value = wpsc_pre_update($data, $_POST);
                $inserted_product_id = wpsc_admin_submit_product($product_id, $data);
                $product_meta = $_POST['meta'];
                if ($product_meta != null) {
                    foreach ((array) $product_meta as $key => $value) {
                        $bool = update_post_meta($inserted_product_id, $key, $value, $prev_value = '');
                        if ($bool == true) {
                            $success = true;
                        }
                    }
                }
                if (isset($inserted_product_id) && $inserted_product_id != 0 || $success == true) {
                    $result['result'] = true;
                }
                array_push($result['productId'], $inserted_product_id);
                if ($result['result']) {
                    $result['insertCnt'] = $insertCnt++;
                }
            } else {
                if (in_array($obj, $edited_object)) {
                    $result['updated'] = 1;
                    // setting a flag to check on whether updated or inserted.
                    //this will update the current product since we are already
                    //passing the id while forming the $post array
                    $product_id = wp_insert_post($post);
                    $_POST['product_id'] = $product_id;
                    $_POST['ID'] = $product_id;
                    // insert the product weight in pound unit since wp-e-commerce does the same.
                    $_POST['meta']['_wpsc_product_metadata']['weight'] = wpsc_convert_weight($_POST['meta']['_wpsc_product_metadata']['weight'], $_POST['meta']['_wpsc_product_metadata']['weight_unit'], "pound", true);
                    // get the actual array of post meta from the database and overwrite it with the new values
                    // so that the keys of the array will be maintained and will get the proper serialized value.
                    // helpful files: processing.functions.php, display-items.page.php, display-items-functions.php
                    $product_meta_values = get_post_meta($product_id, '_wpsc_product_metadata', true);
                    $_POST['meta']['_wpsc_product_metadata'] = array_merge((array) $product_meta_values, $_POST['meta']['_wpsc_product_metadata']);
                    $product_meta = $_POST['meta'];
                    if ($product_meta != null) {
                        foreach ((array) $product_meta as $key => $value) {
                            $bool = update_post_meta($product_id, $key, $value, $prev_value = '');
                            if ($bool == true) {
                                $success = true;
                            }
                        }
                    }
                    if ($product_id == $obj->id || $success == true) {
                        $result['result'] = 1;
                        $result['updateCnt'] = $updateCnt++;
                    }
                }
            }
        }
    }
    return $result;
}
/**
 * Save Product Quick Edit Box
 *
 * Saves input for the various meta in the quick edit boxes.
 *
 * @todo  UI.
 * @todo  Data validation / sanitization / security.
 * @todo  AJAX should probably return weight unit.
 *
 * @return  int  $post_id  Post ID.
 */
function wpsc_save_quickedit_box($post_id)
{
    global $doaction;
    // Only save product if saving (not autosaving) via AJAX.
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || !defined('DOING_AJAX') || !DOING_AJAX || get_post_type($post_id) != 'wpsc-product') {
        return;
    }
    $bulk = isset($doaction) && $doaction == 'edit';
    // Map post field to meta key.
    $custom_fields = array('weight' => 'product_metadata', 'stock' => 'stock', 'price' => 'price', 'sale_price' => 'special_price', 'sku' => 'sku');
    // Get product variations (if any).
    $children = get_children(array('post_parent' => $post_id, 'post_type' => 'wpsc-product', 'post_status' => 'inherit'));
    $is_parent = (bool) $children;
    foreach ($custom_fields as $post_key => $meta_key) {
        // Don't update if field is not set or we're bulk updating and the field is left blank.
        if (!isset($_REQUEST[$post_key]) || $bulk && empty($_REQUEST[$post_key])) {
            continue;
        }
        // Don't update if the product has variations and the field is one of the defined custom fields (unless overridden).
        $override_variant = isset($_REQUEST[$post_key . '_variant']) && $_REQUEST[$post_key . '_variant'] == 'on';
        if ($is_parent && !$override_variant && in_array($post_key, array_keys($custom_fields))) {
            continue;
        }
        // Select single product or variation IDs.
        if ($is_parent && count($children) > 0) {
            $products = wp_list_pluck($children, 'ID');
        } else {
            $products = array($post_id);
        }
        foreach ($products as $post_id) {
            $value = $_REQUEST[$post_key];
            // Validate custom field values
            switch ($post_key) {
                case 'weight':
                    $product_meta = get_post_meta($post_id, '_wpsc_product_metadata', true);
                    if (!is_array($product_meta)) {
                        $product_meta = array();
                    }
                    // Draft products don't have product metadata set yet
                    $weight_unit = isset($product_meta['weight_unit']) ? $product_meta['weight_unit'] : 'pound';
                    $weight = wpsc_convert_weight($value, $weight_unit, 'pound', true);
                    if (isset($product_meta['weight'])) {
                        unset($product_meta['weight']);
                    }
                    $product_meta['weight'] = $weight;
                    $value = $product_meta;
                    break;
                case 'stock':
                    if (!is_numeric($value)) {
                        $value = '';
                    }
                    break;
                case 'sku':
                    if ($value == __('N/A', 'wp-e-commerce')) {
                        $value = '';
                    } else {
                        $value = sanitize_text_field($value);
                    }
                    break;
                default:
                    $value = sanitize_text_field($value);
            }
            update_post_meta($post_id, "_wpsc_{$meta_key}", $value);
        }
    }
    return $post_id;
}
 function getQuote()
 {
     global $wpdb, $wpsc_cart;
     if ($this->base_country != 'AU' || strlen($this->base_zipcode) != 4 || !count($wpsc_cart->cart_items)) {
         return;
     }
     $dest = wpsc_get_customer_meta('shipping_country');
     $destzipcode = (string) wpsc_get_customer_meta('shipping_zip');
     if (isset($_POST['zipcode'])) {
         $destzipcode = sanitize_text_field($_POST['zipcode']);
         wpsc_update_customer_meta('shipping_zip', $destzipcode);
     }
     if ($dest == 'AU' && strlen($destzipcode) != 4) {
         // Invalid Australian Post Code entered, so just return an empty set of quotes instead of wasting time contactin the Aus Post API
         return array();
     }
     /*
     3 possible scenarios:
     
     1.
     Cart consists of only item(s) that have "disregard shipping" ticked.
     
     In this case, WPEC doesn't mention shipping at all during checkout, and this shipping module probably won't be executed at all.
     
     Just in case it does get queried, we should still query the Australia Post API for valid shipping estimates,
     and then override the quoted price(s) to $0.00 so the customer is able to get free shipping.
     
     
     2.
     Cart consists of only item(s) where "disregard shipping" isn't ticked (ie. all item(s) attract shipping charges).
     
     In this case, we should query the Australia Post API as per normal.
     
     
     3.
     Cart consists of one or more "disregard shipping" product(s), and one or more other products that attract shipping charges.
     
     In this case, we should query the Aus Post API, only taking into account the product(s) that attract shipping charges.
     Products with "disregard shipping" ticked shouldn't have their weight or dimensions included in the quote.
     */
     // Obtain the total combined weight for all items(s) in the cart (excluding items that have the "Disregard Shipping for this product" option ticked)
     // Weight is in grams
     $weight = wpsc_convert_weight($wpsc_cart->calculate_total_weight(true), 'pound', 'gram');
     // Calculate the total cart dimensions by adding the volume of each product then calculating the cubed root
     $volume = 0;
     // Total number of item(s) in the cart
     $numItems = count($wpsc_cart->cart_items);
     if ($numItems == 0) {
         // The customer's cart is empty. This probably shouldn't occur, but just in case!
         return array();
     }
     // Total number of item(s) that don't attract shipping charges.
     $numItemsWithDisregardShippingTicked = 0;
     foreach ($wpsc_cart->cart_items as $cart_item) {
         if (!$cart_item->uses_shipping) {
             // The "Disregard Shipping for this product" option is ticked for this item.
             // Don't include it in the shipping quote.
             $numItemsWithDisregardShippingTicked++;
             continue;
         }
         // If we are here then this item attracts shipping charges.
         $meta = get_product_meta($cart_item->product_id, 'product_metadata', true);
         $unit = $meta['dimension_unit'];
         $meta = $meta['dimensions'];
         if ($meta && is_array($meta)) {
             $productVolume = 1;
             foreach (array('width', 'height', 'length') as $dimension) {
                 // default dimension to 100mm
                 if (empty($meta[$dimension])) {
                     $meta[$dimension] = 100;
                     $unit = 'mm';
                 }
                 switch ($unit) {
                     // we need the units in mm
                     case 'cm':
                         // convert from cm to mm
                         $meta[$dimension] *= 10;
                         break;
                     case 'meter':
                         // convert from m to mm
                         $meta[$dimension] *= 1000;
                         break;
                     case 'in':
                         // convert from in to mm
                         $meta[$dimension] *= 25.4;
                         break;
                 }
                 $productVolume *= $meta[$dimension];
             }
             $volume += floatval($productVolume) * $cart_item->quantity;
         }
     }
     // If there's only one item in the cart, its dimensions will be used
     // But if there are multiple items, cubic root of total volume will be used instead
     if ($wpsc_cart->get_total_shipping_quantity() == 1) {
         $height = $meta['height'];
         $width = $meta['width'];
         $length = $meta['length'];
     } else {
         // Calculate the cubic root of the total volume, rounding up
         $cuberoot = ceil(pow($volume, 1 / 3));
         if ($cuberoot > 0) {
             $height = $width = $length = $cuberoot;
         }
     }
     // As per http://auspost.com.au/personal/parcel-dimensions.html: if the parcel is box-shaped, both its length and width must be at least 15cm.
     if ($length < 150) {
         $length = 150;
     }
     if ($width < 150) {
         $width = 150;
     }
     // By default we should use Australia Post's quoted rate(s)
     $shippingPriceNeedsToBeZero = false;
     if ($numItemsWithDisregardShippingTicked == $numItems) {
         // The cart consists of entirely "disregard shipping" products, so the shipping quote(s) should be $0.00
         // Set the weight to 1 gram so that we can obtain valid Australia Post quotes (which we will then ignore the quoted price of)
         $weight = 1;
         $shippingPriceNeedsToBeZero = true;
     }
     // API Documentation: http://drc.edeliver.com.au/
     $url = "http://drc.edeliver.com.au/ratecalc.asp";
     $params = array('Pickup_Postcode' => $this->base_zipcode, 'Destination_Postcode' => $destzipcode, 'Quantity' => 1, 'Weight' => $weight, 'Height' => $height, 'Width' => $width, 'Length' => $length, 'Country' => $dest);
     // URL encode the parameters to prevent issues where postcodes contain spaces (eg London postcodes)
     $params = array_map('urlencode', $params);
     $url = add_query_arg($params, $url);
     $log = '';
     $methods = array();
     foreach ($this->services as $code => $service) {
         if (!$this->settings['services'][$code]) {
             continue;
         }
         $fullURL = esc_url_raw(add_query_arg('Service_Type', $code, $url));
         // This cache key should be unique for a cart with these contents and destination
         // Needs to be less than 45 characters (as per http://core.trac.wordpress.org/ticket/15058)
         $cacheKey = 'wpec_apq_' . md5($fullURL);
         // See if this Australia Post quote is cached
         $cachedResult = get_transient($cacheKey);
         if (false === $cachedResult) {
             // Quote isn't cached -> query the Australia Post API and then cache the result for 10 minutes
             $response = wp_safe_remote_get($fullURL);
             // Silently ignore any API server errors
             if (is_wp_error($response) || $response['response']['code'] != '200' || empty($response['body'])) {
                 continue;
             }
             if ($this->debug) {
                 $log .= "  {$fullURL}\n    " . $response['body'] . "\n";
             }
             $lines = explode("\n", $response['body']);
             foreach ($lines as $line) {
                 if (empty($line)) {
                     continue;
                 }
                 list($key, $value) = explode('=', $line);
                 $key = trim($key);
                 $value = trim($value);
                 switch ($key) {
                     case 'charge':
                         if ($shippingPriceNeedsToBeZero) {
                             // All shipping prices quoted should be zero
                             $methods[$code]['charge'] = 0.0;
                             $log .= "  NB: the price for the above quote has been overridden to \$0.00\n\n";
                         } else {
                             // Use the Australia Post quoted price
                             $methods[$code]['charge'] = floatval($value);
                         }
                         break;
                     case 'days':
                         $methods[$code]['days'] = floatval($value);
                         break;
                     case 'err_msg':
                         $methods[$code]['err_msg'] = trim($value);
                         break;
                 }
             }
             $methods[$code]['name'] = $this->services[$code];
             // Cache this quote for 10 minutes
             set_transient($cacheKey, $methods[$code], 600);
         } else {
             // This quote is cached so use that result instead
             $methods[$code] = $cachedResult;
         }
     }
     if ($this->debug && strlen($log)) {
         error_log('WP eCommerce Australia Post shipping quotes for ' . home_url() . ":\n----------\n{$log}----------");
     }
     // Allow another WordPress plugin to override the quoted method(s)/amount(s)
     $methods = apply_filters('wpsc_australia_post_methods', $methods, $this->base_zipcode, $destzipcode, $dest, $weight);
     $quotedMethods = array();
     foreach ($methods as $code => $data) {
         // Only include methods with an OK response
         if ($data['err_msg'] != 'OK') {
             continue;
         }
         if ($data['days']) {
             // If the estimated number of days is specified, so include it in the quote
             $text = sprintf(_n('%1$s (estimated delivery time: %2$d business day)', '%1$s (estimated delivery time: %2$d business days)', $data['days'], 'wpsc'), $data['name'], $data['days']);
         } else {
             // No time estimate
             $text = $data['name'];
         }
         $quotedMethods[$text] = $data['charge'];
     }
     return $quotedMethods;
 }
Exemple #18
0
/**
 * Spits out the current products details in a table row for manage products page and variations on edit product page.
 * @access public
 *
 * @since 3.8
 * @param $product (Object), $parent_product (Int) Note: I believe parent_product is unused
 */
function wpsc_product_row(&$product, $parent_product = null)
{
    global $mode, $current_user, $wpsc_products;
    //is this good practice? <*****@*****.**>
    static $rowclass, $object_terms_cache = array();
    // store terms associated with variants inside a cache array. This only requires 1 DB query.
    if (empty($object_terms_cache)) {
        $ids = wp_list_pluck($wpsc_products, 'ID');
        $object_terms = wp_get_object_terms($ids, 'wpsc-variation', array('fields' => 'all_with_object_id'));
        foreach ($object_terms as $term) {
            if (!array_key_exists($term->object_id, $object_terms_cache)) {
                $object_terms_cache[$term->object_id] = array();
            }
            $object_terms_cache[$term->object_id][$term->parent] = $term->name;
        }
    }
    $global_product = $product;
    setup_postdata($product);
    $product_post_type_object = get_post_type_object('wpsc-product');
    $current_user_can_edit_this_product = current_user_can($product_post_type_object->cap->edit_post, $product->ID);
    $rowclass = 'alternate' == $rowclass ? '' : 'alternate';
    $post_owner = $current_user->ID == $product->post_author ? 'self' : 'other';
    $edit_link = get_edit_post_link($product->ID);
    if (isset($object_terms_cache[$product->ID])) {
        ksort($object_terms_cache[$product->ID]);
        $title = implode(', ', $object_terms_cache[$product->ID]);
    } else {
        $title = get_the_title($product->ID);
    }
    if (empty($title)) {
        $title = __('(no title)', 'wpsc');
    }
    ?>

	<tr id='post-<?php 
    echo $product->ID;
    ?>
' class='<?php 
    echo trim($rowclass . ' author-' . $post_owner . ' status-' . $product->post_status);
    ?>
 iedit <?php 
    if (get_option('wpsc_sort_by') == 'dragndrop') {
        echo 'product-edit';
    }
    ?>
' valign="top">
	<?php 
    $posts_columns = get_column_headers('wpsc-product_variants');
    if (empty($posts_columns)) {
        $posts_columns = array('image' => '', 'title' => __('Name', 'wpsc'), 'weight' => __('Weight', 'wpsc'), 'stock' => __('Stock', 'wpsc'), 'price' => __('Price', 'wpsc'), 'sale_price' => __('Sale Price', 'wpsc'), 'SKU' => __('SKU', 'wpsc'), 'hidden_alerts' => '');
    }
    foreach ($posts_columns as $column_name => $column_display_name) {
        $attributes = "class=\"{$column_name} column-{$column_name}\"";
        switch ($column_name) {
            case 'date':
                /* !date case */
                if ('0000-00-00 00:00:00' == $product->post_date && 'date' == $column_name) {
                    $t_time = $h_time = __('Unpublished', 'wpsc');
                    $time_diff = 0;
                } else {
                    $t_time = get_the_time(__('Y/m/d g:i:s A', 'wpsc'));
                    $m_time = $product->post_date;
                    $time = get_post_time('G', true, $post);
                    $time_diff = time() - $time;
                    if ($time_diff > 0 && $time_diff < 24 * 60 * 60) {
                        $h_time = sprintf(__('%s ago', 'wpsc'), human_time_diff($time));
                    } else {
                        $h_time = mysql2date(__('Y/m/d', 'wpsc'), $m_time);
                    }
                }
                echo '<td ' . $attributes . '>';
                if ('excerpt' == $mode) {
                    echo apply_filters('post_date_column_time', $t_time, $post, $column_name, $mode);
                } else {
                    echo '<abbr title="' . $t_time . '">' . apply_filters('post_date_column_time', $h_time, $post, $column_name, $mode) . '</abbr>';
                }
                echo '<br />';
                if ('publish' == $product->post_status) {
                    _e('Published', 'wpsc');
                } elseif ('future' == $product->post_status) {
                    if ($time_diff > 0) {
                        echo '<strong class="attention">' . __('Missed schedule', 'wpsc') . '</strong>';
                    } else {
                        _e('Scheduled', 'wpsc');
                    }
                } else {
                    _e('Last Modified', 'wpsc');
                }
                echo '</td>';
                break;
            case 'title':
                /* !title case */
                $attributes = 'class="post-title column-title"';
                $edit_link = wp_nonce_url($edit_link, 'edit-product_' . $product->ID);
                ?>
		<td <?php 
                echo $attributes;
                ?>
>
			<strong>
			<?php 
                if ($current_user_can_edit_this_product && $product->post_status != 'trash') {
                    ?>
				<span><a class="row-title" href="<?php 
                    echo $edit_link;
                    ?>
" title="<?php 
                    echo esc_attr(sprintf(__('Edit &#8220;%s&#8221;', 'wpsc'), $title));
                    ?>
"><?php 
                    echo $title;
                    ?>
</a></span>
				<?php 
                    if ($parent_product) {
                        ?>
					<a href="<?php 
                        echo $edit_link;
                        ?>
" title="<?php 
                        echo esc_attr(sprintf(__('Edit &#8220;%s&#8221;', 'wpsc'), $title));
                        ?>
"><?php 
                        echo $title;
                        ?>
</a>

				<?php 
                    }
                    ?>
			<?php 
                } else {
                    echo $title;
                }
                _post_states($product);
                $product_alert = apply_filters('wpsc_product_alert', array(false, ''), $product);
                if (!empty($product_alert['messages'])) {
                    $product_alert['messages'] = implode("\n", (array) $product_alert['messages']);
                }
                if ($product_alert['state'] === true) {
                    ?>
				<img alt='<?php 
                    echo $product_alert['messages'];
                    ?>
' title='<?php 
                    echo $product_alert['messages'];
                    ?>
' class='product-alert-image' src='<?php 
                    echo WPSC_CORE_IMAGES_URL;
                    ?>
/product-alert.jpg' alt='' />
				<?php 
                }
                // If a product alert has stuff to display, show it.
                // Can be used to add extra icons etc
                if (!empty($product_alert['display'])) {
                    echo $product_alert['display'];
                }
                ?>
			</strong>
			<?php 
                $has_var = '';
                if (!$parent_product && wpsc_product_has_children($product->ID)) {
                    $has_var = 'wpsc_has_variation';
                }
                $actions = array();
                if ($current_user_can_edit_this_product && 'trash' != $product->post_status) {
                    $actions['edit'] = '<a class="edit-product" href="' . $edit_link . '" title="' . esc_attr(__('Edit this product', 'wpsc')) . '">' . __('Edit', 'wpsc') . '</a>';
                    //commenting this out for now as we are trying new variation ui quick edit boxes are open by default so we dont need this link.
                    //$actions['quick_edit'] = "<a class='wpsc_editinline ".$has_var."' title='".esc_attr(__('Quick Edit', 'wpsc'))."' href='#'>".__('Quick Edit', 'wpsc')."</a>";
                }
                $actions = apply_filters('post_row_actions', $actions, $product);
                $action_count = count($actions);
                $i = 0;
                echo '<div class="row-actions">';
                foreach ($actions as $action => $link) {
                    ++$i;
                    $i == $action_count ? $sep = '' : ($sep = ' | ');
                    echo "<span class='{$action}'>{$link}{$sep}</span>";
                }
                echo '</div>';
                ?>
		</td>
		<?php 
                break;
            case 'image':
                /* !image case */
                ?>
			<td class="product-image ">
			<?php 
                $attachment_args = array('post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $product->ID, 'orderby' => 'menu_order', 'order' => 'ASC');
                if (isset($product->ID) && has_post_thumbnail($product->ID)) {
                    echo get_the_post_thumbnail($product->ID, 'admin-product-thumbnails');
                } else {
                    $image_url = WPSC_CORE_IMAGES_URL . "/no-image-uploaded.gif";
                    ?>
					<img title='Drag to a new position' src='<?php 
                    echo $image_url;
                    ?>
' alt='<?php 
                    echo $title;
                    ?>
' width='38' height='38' />
				<?php 
                }
                ?>
			</td>
			<?php 
                break;
            case 'price':
                /* !price case */
                $price = get_product_meta($product->ID, 'price', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<?php 
                echo wpsc_currency_display($price);
                ?>
					<input type="text" class="wpsc_ie_field wpsc_ie_price" value="<?php 
                echo $price;
                ?>
">
					<a href="<?php 
                echo $edit_link;
                ?>
/#wpsc_downloads">Variant Download Files</a>
				</td>
			<?php 
                break;
            case 'weight':
                $product_data['meta'] = array();
                $product_data['meta'] = get_post_meta($product->ID, '');
                foreach ($product_data['meta'] as $meta_name => $meta_value) {
                    $product_data['meta'][$meta_name] = maybe_unserialize(array_pop($meta_value));
                }
                $product_data['transformed'] = array();
                if (!isset($product_data['meta']['_wpsc_product_metadata']['weight'])) {
                    $product_data['meta']['_wpsc_product_metadata']['weight'] = "";
                }
                if (!isset($product_data['meta']['_wpsc_product_metadata']['weight_unit'])) {
                    $product_data['meta']['_wpsc_product_metadata']['weight_unit'] = "";
                }
                $product_data['transformed']['weight'] = wpsc_convert_weight($product_data['meta']['_wpsc_product_metadata']['weight'], "pound", $product_data['meta']['_wpsc_product_metadata']['weight_unit'], false);
                $weight = $product_data['transformed']['weight'];
                if ($weight == '') {
                    $weight = '0';
                }
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo $weight;
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_weight" value="<?php 
                echo $weight;
                ?>
">
					<a href="<?php 
                echo $edit_link;
                ?>
/#wpsc_tax">Set Variant Tax</a>
				</td>
			<?php 
                break;
            case 'stock':
                $stock = get_post_meta($product->ID, '_wpsc_stock', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo $stock ? $stock : __('N/A', 'wpsc');
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_stock" value="<?php 
                echo $stock;
                ?>
">
					<a href="<?php 
                echo $edit_link;
                ?>
/#wpsc_shipping">Set Variant Shipping</a>
				</td>
	<?php 
                break;
            case 'categories':
                /* !categories case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><?php 
                $categories = get_the_product_category($product->ID);
                if (!empty($categories)) {
                    $out = array();
                    foreach ($categories as $c) {
                        $out[] = "<a href='admin.php?page=wpsc-edit-products&amp;category={$c->slug}'> " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'category', 'display')) . "</a>";
                    }
                    echo join(', ', $out);
                } else {
                    _e('Uncategorized', 'wpsc');
                }
                ?>
</td>
		<?php 
                break;
            case 'tags':
                /* !tags case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><?php 
                $tags = get_the_tags($product->ID);
                if (!empty($tags)) {
                    $out = array();
                    foreach ($tags as $c) {
                        $out[] = "<a href='edit.php?tag={$c->slug}'> " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'post_tag', 'display')) . "</a>";
                    }
                    echo join(', ', $out);
                } else {
                    _e('No Tags', 'wpsc');
                }
                ?>
</td>
		<?php 
                break;
            case 'SKU':
                $sku = get_post_meta($product->ID, '_wpsc_sku', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo $sku ? $sku : __('N/A', 'wpsc');
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_sku" value="<?php 
                echo $sku;
                ?>
">
										<input type="hidden" class="wpsc_ie_id wpsc_ie_field" value="<?php 
                echo $product->ID;
                ?>
">
					<div class="wpsc_inline_actions"><input type="button" class="button-primary wpsc_ie_save" value="Save"><img src="<?php 
                echo admin_url('images/wpspin_light.gif');
                ?>
" class="loading_indicator"><br/></div>
				</td>
			<?php 
                break;
            case 'sale_price':
                $sale_price = get_post_meta($product->ID, '_wpsc_special_price', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo wpsc_currency_display($sale_price);
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_special_price" value="<?php 
                echo $sale_price;
                ?>
">
				</td>
			<?php 
                break;
            case 'comments':
                /* !comments case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><div class="post-com-count-wrapper">
		<?php 
                $pending_phrase = sprintf(__('%s pending', 'wpsc'), number_format($pending_comments));
                if ($pending_comments) {
                    echo '<strong>';
                }
                comments_number("<a href='edit-comments.php?p={$product->ID}' title='{$pending_phrase}' class='post-com-count'><span class='comment-count'>" . _x('0', 'comment count', 'wpsc') . '</span></a>', "<a href='edit-comments.php?p={$product->ID}' title='{$pending_phrase}' class='post-com-count'><span class='comment-count'>" . _x('1', 'comment count', 'wpsc') . '</span></a>', "<a href='edit-comments.php?p={$product->ID}' title='{$pending_phrase}' class='post-com-count'><span class='comment-count'>" . _x('%', 'comment count', 'wpsc') . '</span></a>');
                if ($pending_comments) {
                    echo '</strong>';
                }
                ?>
		</div></td>
		<?php 
                break;
            case 'author':
                /* !author case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><a href="edit.php?author=<?php 
                the_author_meta('ID');
                ?>
"><?php 
                the_author();
                ?>
</a></td>
		<?php 
                break;
            case 'control_view':
                /* !control view case */
                ?>
		<td><a href="<?php 
                the_permalink();
                ?>
" rel="permalink" class="view"><?php 
                _e('View', 'wpsc');
                ?>
</a></td>
		<?php 
                break;
            case 'control_edit':
                /* !control edit case */
                ?>
		<td><?php 
                if ($current_user_can_edit_this_product) {
                    echo "<a href='{$edit_link}' class='edit'>" . __('Edit', 'wpsc') . "</a>";
                }
                ?>
</td>
		<?php 
                break;
            case 'control_delete':
                /* !control delete case */
                ?>
		<td><?php 
                if ($current_user_can_edit_this_product) {
                    echo "<a href='" . wp_nonce_url("post.php?action=delete&amp;post={$id}", 'delete-post_' . $product->ID) . "' class='delete'>" . __('Delete', 'wpsc') . "</a>";
                }
                ?>
</td>
		<?php 
                break;
            case 'featured':
                /* !control featured case */
                ?>
			<td><?php 
                do_action('manage_posts_featured_column', $product->ID);
                ?>
</td>
		<?php 
                break;
            default:
                /* !default case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><?php 
                do_action('manage_posts_custom_column', $column_name, $product->ID);
                ?>
</td>
		<?php 
                break;
        }
    }
    ?>
	</tr>
<?php 
    $product = $global_product;
}
/**
 * Weight column in Manage Products page
 *
 * @since 3.8.9
 * @access private
 * @param  object  $post    Post object
 * @param  int     $post_id Post ID
 * @param  boolean $has_variations Whether the product has variations
 */
function _wpsc_manage_products_column_weight($post, $post_id, $has_variations)
{
    if ($has_variations) {
        esc_html_e('N/A', 'wpsc');
        return;
    }
    $product_data = array();
    $product_data['meta'] = array();
    $product_data['meta'] = get_post_meta($post->ID, '');
    foreach ($product_data['meta'] as $meta_name => $meta_value) {
        $product_data['meta'][$meta_name] = maybe_unserialize(array_pop($meta_value));
    }
    $product_data['transformed'] = array();
    if (!isset($product_data['meta']['_wpsc_product_metadata']['weight'])) {
        $product_data['meta']['_wpsc_product_metadata']['weight'] = "";
    }
    if (!isset($product_data['meta']['_wpsc_product_metadata']['weight_unit'])) {
        $product_data['meta']['_wpsc_product_metadata']['weight_unit'] = "";
    }
    $product_data['transformed']['weight'] = wpsc_convert_weight($product_data['meta']['_wpsc_product_metadata']['weight'], "pound", $product_data['meta']['_wpsc_product_metadata']['weight_unit']);
    $weight = $product_data['transformed']['weight'];
    if ($weight == '') {
        $weight = '0';
    }
    $unit = $product_data['meta']['_wpsc_product_metadata']['weight_unit'];
    switch ($unit) {
        case "pound":
            $unit = __(" lbs.", "wpsc");
            break;
        case "ounce":
            $unit = __(" oz.", "wpsc");
            break;
        case "gram":
            $unit = __(" g", "wpsc");
            break;
        case "kilograms":
        case "kilogram":
            $unit = __(" kgs.", "wpsc");
            break;
    }
    echo $weight . $unit;
    echo '<div id="inline_' . $post->ID . '_weight" class="hidden">' . $weight . '</div>';
}
 /**
  * Shipwire requires dimensions to be in inches and pounds.  This handles the conversion process, if one is required.
  * @param int $product_id
  * @since 3.8.9
  * @return array $dimensions
  */
 public static function get_dimensions($product_id)
 {
     $product_meta = get_post_meta($product_id, '_wpsc_product_metadata', true);
     $original_dimensions = $product_meta['dimensions'];
     $dimensions = array();
     $dimensions['weight'] = 'pound' == $original_dimensions['weight_unit'] ? $original_dimensions['weight'] : wpsc_convert_weight($original_dimensions['weight'], $original_dimensions['weight_unit']);
     $dimensions['length'] = 'in' == $original_dimensions['length_unit'] ? $original_dimensions['length'] : self::convert_dimensions($original_dimensions['length'], $original_dimensions['length_unit']);
     $dimensions['width'] = 'in' == $original_dimensions['width_unit'] ? $original_dimensions['width'] : self::convert_dimensions($original_dimensions['width'], $original_dimensions['width_unit']);
     $dimensions['height'] = 'in' == $original_dimensions['height_unit'] ? $original_dimensions['height'] : self::convert_dimensions($original_dimensions['height'], $original_dimensions['height_unit']);
     return $dimensions;
 }
/**
 * Weight of current or specified purchase
 *
 * @since 3.8.14
 *
 *
 * @param string $id
 * @return float $weight in '$out_unit' of shipment
 */
function wpsc_purchlogs_get_weight($id = '', $out_unit = 'pound')
{
    global $purchlogitem;
    $weight = 0.0;
    $items_count = 0;
    if (empty($id) || !empty($purchlogitem) && $id == $purchlogitem->purchlogid) {
        $thepurchlogitem = $purchlogitem;
    } else {
        $thepurchlogitem = new wpsc_purchaselogs_items($id);
    }
    /**
     * Filter wpsc_purchlogs_before_get_weight
     *
     * Allow the weight to be overridden, can be used to persistantly save weight and recall it rather than recalculate
     *
     * @since 3.8.14
     *
     * @param  float  $weight, purchase calculation will not continue if value is returned
     * @param  string weight unit to use for return value
     * @param  object wpsc_purchaselogs_items purchase log item being used
     * @param  int    purchase log item id
     * @return float  $weight
     */
    $weight_override = apply_filters('wpsc_purchlogs_before_get_weight', false, $out_unit, $thepurchlogitem, $thepurchlogitem->purchlogid);
    if ($weight_override !== false) {
        return $weight_override;
    }
    // if there isn't a purchase log item we are done
    if (empty($thepurchlogitem)) {
        return false;
    }
    foreach ((array) $thepurchlogitem->allcartcontent as $cartitem) {
        $product_meta = get_product_meta($cartitem->prodid, 'product_metadata', true);
        if (!empty($product_meta['weight']) && !empty($product_meta['weight_unit'])) {
            $converted_weight = wpsc_convert_weight($product_meta['weight'], $product_meta['weight_unit'], $out_unit, true);
            $weight += $converted_weight * $cartitem->quantity;
            $items_count += $cartitem->quantity;
        }
    }
    /**
     * Filter wpsc_purchlogs_get_weight
     *
     * Allow the weight to be overridden
     *
     * @since 3.8.14
     *
     * @param  float  $weight                 calculated cart weight
     * @param  object wpsc_purchaselogs_items purchase log item being used
     * @param  int    purchase log item id
     * @param  int    $items_count            how many items are in the cart, useful for
     *                                        cases where packaging weight changes as more items are
     *                                        added
     */
    $weight = apply_filters('wpsc_purchlogs_get_weight', $weight, $thepurchlogitem, $thepurchlogitem->purchlogid, $items_count);
    return $weight;
}
/**
 * wpsc_additional_column_data.
 *
 * @access public
 * @param (array) $column
 * @return void
 * @todo Need to check titles / alt tags ( I don't think thumbnails have any in this code )
 * @desc Switch function to generate columns the right way...no more UI hacking!
 *
 */
function wpsc_additional_column_data($column)
{
    global $post;
    $is_parent = (bool) wpsc_product_has_children($post->ID);
    switch ($column) {
        case 'image':
            $attached_images = get_posts(array('post_type' => 'attachment', 'numberposts' => 1, 'post_parent' => $post->ID, 'orderby' => 'menu_order', 'order' => 'ASC'));
            if (isset($post->ID) && has_post_thumbnail($post->ID)) {
                echo get_the_post_thumbnail($post->ID, 'admin-product-thumbnails');
            } else {
                if (!empty($attached_images)) {
                    $attached_image = $attached_images[0];
                    $src = wp_get_attachment_url($attached_image->ID);
                    ?>
                    <div style='width:38px; height:38px; overflow:hidden;'>
                        <img src='<?php 
                    echo $src;
                    ?>
' alt='<?php 
                    _e('Drag to a new position', 'wpsc');
                    ?>
' width='38' height='38' />
                    </div>
                <?php 
                } else {
                    $image_url = WPSC_CORE_IMAGES_URL . "/no-image-uploaded.gif";
                    ?>
                      <img src='<?php 
                    echo $image_url;
                    ?>
' alt='<?php 
                    _e('Drag to a new position', 'wpsc');
                    ?>
' width='38' height='38' />
                <?php 
                }
            }
            break;
        case 'weight':
            if ($is_parent) {
                _e('N/A', 'wpsc');
            } else {
                $product_data['meta'] = array();
                $product_data['meta'] = get_post_meta($post->ID, '');
                foreach ($product_data['meta'] as $meta_name => $meta_value) {
                    $product_data['meta'][$meta_name] = maybe_unserialize(array_pop($meta_value));
                }
                $product_data['transformed'] = array();
                if (!isset($product_data['meta']['_wpsc_product_metadata']['weight'])) {
                    $product_data['meta']['_wpsc_product_metadata']['weight'] = "";
                }
                if (!isset($product_data['meta']['_wpsc_product_metadata']['weight_unit'])) {
                    $product_data['meta']['_wpsc_product_metadata']['weight_unit'] = "";
                }
                $product_data['transformed']['weight'] = wpsc_convert_weight($product_data['meta']['_wpsc_product_metadata']['weight'], "pound", $product_data['meta']['_wpsc_product_metadata']['weight_unit']);
                $weight = $product_data['transformed']['weight'];
                if ($weight == '') {
                    $weight = '0';
                }
                $unit = $product_data['meta']['_wpsc_product_metadata']['weight_unit'];
                switch ($unit) {
                    case "pound":
                        $unit = __(" lbs.", "wpsc");
                        break;
                    case "ounce":
                        $unit = __(" oz.", "wpsc");
                        break;
                    case "gram":
                        $unit = __(" g", "wpsc");
                        break;
                    case "kilograms":
                    case "kilogram":
                        $unit = __(" kgs.", "wpsc");
                        break;
                }
                echo $weight . $unit;
                echo '<div id="inline_' . $post->ID . '_weight" class="hidden">' . $weight . '</div>';
            }
            break;
        case 'stock':
            $stock = get_post_meta($post->ID, '_wpsc_stock', true);
            if ($stock == '') {
                $stock = __('N/A', 'wpsc');
            }
            if (!$is_parent) {
                echo $stock;
                echo '<div id="inline_' . $post->ID . '_stock" class="hidden">' . $stock . '</div>';
            } else {
                echo '~' . wpsc_variations_stock_remaining($post->ID);
            }
            break;
        case 'price':
            $price = get_post_meta($post->ID, '_wpsc_price', true);
            $has_var = '1';
            if (!$is_parent) {
                echo wpsc_currency_display($price);
                echo '<div id="inline_' . $post->ID . '_price" class="hidden">' . trim($price) . '</div>';
                $has_var = '0';
            } else {
                echo wpsc_product_variation_price_available($post->ID) . '+';
            }
            echo '<input type="hidden" value="' . $has_var . '" id="inline_' . $post->ID . '_has_var" />';
            break;
        case 'sale_price':
            $price = get_post_meta($post->ID, '_wpsc_special_price', true);
            if (!$is_parent) {
                echo wpsc_currency_display($price);
                echo '<div id="inline_' . $post->ID . '_sale_price" class="hidden">' . $price . '</div>';
            } else {
                echo wpsc_product_variation_price_available($post->ID) . '+';
            }
            break;
        case 'SKU':
            $sku = get_post_meta($post->ID, '_wpsc_sku', true);
            if ($sku == '') {
                $sku = __('N/A', 'wpsc');
            }
            echo $sku;
            echo '<div id="inline_' . $post->ID . '_sku" class="hidden">' . $sku . '</div>';
            break;
        case 'cats':
            $categories = get_the_product_category($post->ID);
            if (!empty($categories)) {
                $out = array();
                foreach ($categories as $c) {
                    $out[] = "<a href='?post_type=wpsc-product&amp;wpsc_product_category={$c->slug}'> " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'category', 'display')) . "</a>";
                }
                echo join(', ', $out);
            } else {
                _e('Uncategorized', 'wpsc');
            }
            break;
        case 'featured':
            $featured_product_url = wp_nonce_url("index.php?wpsc_admin_action=update_featured_product&amp;product_id={$post->ID}", 'feature_product_' . $post->ID);
            ?>
	<a class="wpsc_featured_product_toggle featured_toggle_<?php 
            echo $post->ID;
            ?>
" href='<?php 
            echo $featured_product_url;
            ?>
' >
            <?php 
            if (in_array($post->ID, (array) get_option('sticky_products'))) {
                ?>
                <img class='gold-star' src='<?php 
                echo WPSC_CORE_IMAGES_URL;
                ?>
/gold-star.gif' alt='<?php 
                _e('Unmark as Featured', 'wpsc');
                ?>
' title='<?php 
                _e('Unmark as Featured', 'wpsc');
                ?>
' />
            <?php 
            } else {
                ?>
                <img class='grey-star' src='<?php 
                echo WPSC_CORE_IMAGES_URL;
                ?>
/grey-star.gif' alt='<?php 
                _e('Mark as Featured', 'wpsc');
                ?>
' title='<?php 
                _e('Mark as Featured', 'wpsc');
                ?>
' />
            <?php 
            }
            ?>
	</a>
        <?php 
            break;
        case 'hidden_alerts':
            $product_alert = apply_filters('wpsc_product_alert', array(false, ''), $post);
            if (!empty($product_alert['messages'])) {
                $product_alert['messages'] = implode("\n", (array) $product_alert['messages']);
            }
            if ($product_alert['state'] === true) {
                ?>
                            <img alt='<?php 
                echo $product_alert['messages'];
                ?>
' title='<?php 
                echo $product_alert['messages'];
                ?>
' class='product-alert-image' src='<?php 
                echo WPSC_CORE_IMAGES_URL;
                ?>
/product-alert.jpg' alt='' />
                        <?php 
            }
            // If a product alert has stuff to display, show it.
            // Can be used to add extra icons etc
            if (!empty($product_alert['display'])) {
                echo $product_alert['display'];
            }
            break;
    }
}