Пример #1
0
 function getQuote()
 {
     global $wpdb;
     $weight = wpsc_cart_weight_total();
     $layers = get_option('weight_rate_layers');
     if ($layers != '') {
         krsort($layers);
         foreach ($layers as $key => $shipping) {
             if ($weight >= (double) $key) {
                 return array("Weight Rate" => $shipping);
             }
         }
         return array("Weight Rate" => array_shift($layers));
     }
 }
Пример #2
0
 function getQuote()
 {
     global $wpdb, $wpec_ash;
     if (!is_object($wpec_ash)) {
         $wpec_ash = new ASH();
     }
     // Arguments array for various functions to use
     $args = array();
     // Final rate table
     $rate_table = array();
     // Get the ups settings from the ups account info page (Shipping tab)
     $wpsc_ups_settings = get_option("wpsc_ups_settings", array());
     // Get the wordpress shopping cart options
     $wpsc_options = get_option("wpsc_options");
     // API Auth settings //
     $args['username'] = array_key_exists('upsaccount', $wpsc_ups_settings) ? $wpsc_ups_settings['upsusername'] : "";
     $args['password'] = array_key_exists('upspassword', $wpsc_ups_settings) ? $wpsc_ups_settings['upspassword'] : "";
     $args['api_id'] = array_key_exists('upsid', $wpsc_ups_settings) ? $wpsc_ups_settings['upsid'] : "";
     $args['account_number'] = array_key_exists('upsaccount', $wpsc_ups_settings) ? $wpsc_ups_settings['upsaccount'] : "";
     $args['negotiated_rates'] = array_key_exists('ups_negotiated_rates', $wpsc_ups_settings) ? $wpsc_ups_settings['ups_negotiated_rates'] : "";
     $args['residential'] = $wpsc_ups_settings['49_residential'];
     $args["singular_shipping"] = array_key_exists("singular_shipping", $wpsc_ups_settings) ? $wpsc_ups_settings["singular_shipping"] : "0";
     $args['insured_shipment'] = array_key_exists("insured_shipment", $wpsc_ups_settings) ? $wpsc_ups_settings["insured_shipment"] : "0";
     // What kind of pickup service do you use ?
     $args['DropoffType'] = $wpsc_ups_settings['DropoffType'];
     $args['packaging'] = $wpsc_ups_settings['48_container'];
     // Preferred Currency to display
     $currency_data = $wpdb->get_row($wpdb->prepare("SELECT `code`\n                                         FROM `" . WPSC_TABLE_CURRENCY_LIST . "`\n                                         WHERE `isocode`= %s\n                                         LIMIT 1", get_option('currency_type')), ARRAY_A);
     if ($currency_data) {
         $args['currency'] = $currency_data['code'];
     } else {
         $args['currency'] = "USD";
     }
     // Shipping billing / account address
     $origin_region_data = $wpdb->get_results($wpdb->prepare("SELECT `" . WPSC_TABLE_REGION_TAX . "`.* FROM `" . WPSC_TABLE_REGION_TAX . "`\n                                WHERE `" . WPSC_TABLE_REGION_TAX . "`.`id` = %d ", get_option('base_region')), ARRAY_A);
     $args['shipr_state'] = is_array($origin_region_data) ? $origin_region_data[0]['code'] : "";
     $args['shipr_city'] = get_option('base_city');
     $args['shipr_ccode'] = get_option('base_country');
     $args['shipr_pcode'] = get_option('base_zipcode');
     // Physical Shipping address being shipped from
     $args['shipf_state'] = $args['shipr_state'];
     $args['shipf_city'] = $args['shipr_city'];
     $args['shipf_ccode'] = $args['shipr_ccode'];
     $args['shipf_pcode'] = $args['shipr_pcode'];
     // Get the total weight from the shopping cart
     $args['units'] = "LBS";
     $args['weight'] = wpsc_cart_weight_total();
     // Destination zip code
     $args['dest_ccode'] = wpsc_get_customer_meta('shipping_country');
     if ($args['dest_ccode'] == "UK") {
         // So, UPS is a little off the times
         $args['dest_ccode'] = "GB";
     }
     // If ths zip code is provided via a form post use it!
     $args['dest_pcode'] = (string) wpsc_get_customer_meta('shipping_zip');
     if (isset($_POST['zipcode']) && ($_POST['zipcode'] != __("Your Zipcode", 'wpsc') && $_POST['zipcode'] != "YOURZIPCODE")) {
         $args['dest_pcode'] = esc_attr($_POST['zipcode']);
     }
     if (in_array($args['dest_pcode'], array(__('Your Zipcode', 'wpsc'), 'YOURZIPCODE'))) {
         $args['dest_pcode'] = '';
     }
     wpsc_update_customer_meta('shipping_zip', $args['dest_pcode']);
     if (empty($args['dest_pcode'])) {
         // We cannot get a quote without a zip code so might as well return!
         return array();
     }
     // If the region code is provided via a form post use it!
     if (isset($_POST['region']) && !empty($_POST['region'])) {
         $query = $wpdb->prepare("SELECT `" . WPSC_TABLE_REGION_TAX . "`.* FROM `" . WPSC_TABLE_REGION_TAX . "`\n                                WHERE `" . WPSC_TABLE_REGION_TAX . "`.`id` = %d", $_POST['region']);
         $dest_region_data = $wpdb->get_results($query, ARRAY_A);
         $args['dest_state'] = is_array($dest_region_data) ? $dest_region_data[0]['code'] : "";
         wpsc_update_customer_meta('ups_state', $args['dest_state']);
     } else {
         if ($dest_state = wpsc_get_customer_meta('ups_state')) {
             // Well, we have a zip code in the session and no new one provided
             $args['dest_state'] = $dest_state;
         } else {
             $args['dest_state'] = "";
         }
     }
     $shipping_cache_check['state'] = $args['dest_state'];
     $shipping_cache_check['zipcode'] = $args['dest_pcode'];
     $shipping_cache_check['weight'] = $args['weight'];
     $session_cache_check = wpsc_get_customer_meta('ups_shipping_cache_check');
     if (!is_array($session_cache_check)) {
         $session_cache_check = array();
     }
     $session_cache = wpsc_get_customer_meta('ups_shipping_cache');
     if (!is_array($session_cache)) {
         $session_cache = array();
     }
     if (!(bool) $args["singular_shipping"]) {
         // This is where shipping breaks out of UPS if weight is higher than 150 LBS
         if ($weight > 150) {
             wpsc_delete_customer_meta('quote_shipping_method');
             $shipping_quotes[TXT_WPSC_OVER_UPS_WEIGHT] = 0;
             $session_cache_check['weight'] = $args['weight'];
             $session_cache[$this->internal_name] = $shipping_quotes;
             wpsc_update_customer_meta('quote_shipping_method', $this->internal_name);
             wpsc_update_customer_meta('ups_shipping_cache_check', $session_cache_check);
             wpsc_update_customer_meta('ups_shipping_cache', $session_cache);
             return array($shipping_quotes);
         }
     }
     // We do not want to spam UPS (and slow down our process) if we already
     // have a shipping quote!
     if ($session_cache_check === $shipping_cache_check && !empty($session_cache[$this->internal_name])) {
         $rate_table = $session_cache[$this->internal_name];
         return $rate_table;
     } else {
         global $wpsc_cart;
         $args["cart_total"] = $wpsc_cart->calculate_subtotal(true);
         // Build the XML request
         $request = $this->_buildRateRequest($args);
         // Now that we have the message to send ... Send it!
         $raw_quote = $this->_makeRateRequest($request);
         // Now we have the UPS response .. unfortunately its not ready
         // to be viewed by normal humans ...
         $quotes = $this->_parseQuote($raw_quote);
         // If we actually have rates back from UPS we can use em!
         if ($quotes != false) {
             $rate_table = $this->_formatTable($quotes, $args['currency']);
         } else {
             if ($wpsc_ups_settings['upsenvironment'] == '1') {
                 echo "<strong>:: GetQuote ::DEBUG OUTPUT::</strong><br />";
                 echo "Arguments sent to UPS";
                 print_r($args);
                 echo "<hr />";
                 print $request;
                 echo "<hr />";
                 echo "Response from UPS";
                 echo $raw_quote;
                 echo "</strong>:: GetQuote ::End DEBUG OUTPUT::";
             }
         }
     }
     $wpec_ash->cache_results($this->internal_name, $args["dest_ccode"], $args["dest_state"], $args["dest_pcode"], $rate_table, $this->shipment);
     // return the final formatted array !
     return $rate_table;
 }
Пример #3
0
 function getQuote()
 {
     global $wpdb, $wpec_ash, $wpsc_cart, $wpec_ash_tools;
     // Arguments array for various functions to use
     $args = array();
     $args['dest_ccode'] = wpsc_get_customer_meta('shippingcountry');
     // Get the ups settings from the ups account info page (Shipping tab)
     $wpsc_ups_settings = get_option('wpsc_ups_settings', array());
     //Disable International Shipping. Default: Enabled, as it currently is.
     $args['intl_rate'] = isset($wpsc_ups_settings['intl_rate']) && !empty($wpsc_ups_settings['intl_rate']) ? FALSE : TRUE;
     if (!$args['intl_rate'] && $args['dest_ccode'] != get_option('base_country')) {
         return array();
     }
     // Destination zip code
     $args['dest_pcode'] = (string) wpsc_get_customer_meta('shippingpostcode');
     if (!is_object($wpec_ash_tools)) {
         $wpec_ash_tools = new ASHTools();
     }
     if (empty($args['dest_pcode']) && $wpec_ash_tools->needs_post_code($args['dest_ccode'])) {
         // We cannot get a quote without a zip code so might as well return!
         return array();
     }
     // Get the total weight from the shopping cart
     $args['weight'] = wpsc_cart_weight_total();
     if (empty($args['weight'])) {
         return array();
     }
     $args['dest_state'] = '';
     $wpsc_country = new WPSC_Country(wpsc_get_customer_meta('shippingcountry'));
     if ($wpsc_country->has_regions()) {
         $wpsc_region = $wpsc_country->get_region(wpsc_get_customer_meta('shippingregion'));
         if (is_a($wpsc_region, 'WPSC_Region')) {
             $args['dest_state'] = $wpsc_region->get_code();
         }
     }
     if (empty($args['dest_state'])) {
         $args['dest_state'] = wpsc_get_customer_meta('shippingstate');
     }
     if (!is_object($wpec_ash)) {
         $wpec_ash = new ASH();
     }
     $shipping_cache_check['state'] = $args['dest_state'];
     //The destination is needed for cached shipment check.
     $shipping_cache_check['country'] = $args['dest_ccode'];
     $shipping_cache_check['zipcode'] = $args['dest_pcode'];
     $this->shipment = $wpec_ash->get_shipment();
     $this->shipment->set_destination($this->internal_name, $shipping_cache_check);
     //Set this shipment's destination.
     $this->shipment->rates_expire = date('Y-m-d');
     $args['shipper'] = $this->internal_name;
     $args['singular_shipping'] = array_key_exists('singular_shipping', $wpsc_ups_settings) ? $wpsc_ups_settings['singular_shipping'] : '0';
     if ($args['weight'] > 150 && !(bool) $args['singular_shipping']) {
         // This is where shipping breaks out of UPS if weight is higher than 150 LBS
         $over_weight_txt = apply_filters('wpsc_shipment_over_weight', __('Your order exceeds the standard shipping weight limit. Please contact us to quote other shipping alternatives.', 'wpsc'), $args);
         $shipping_quotes[$over_weight_txt] = 0;
         // yes, a constant.
         $wpec_ash->cache_results($this->internal_name, array($shipping_quotes), $this->shipment);
         //Update shipment cache.
         return array($shipping_quotes);
     }
     $cache = $wpec_ash->check_cache($this->internal_name, $this->shipment);
     //And now, we're ready to check cache.
     // We do not want to spam UPS (and slow down our process) if we already
     // have a shipping quote!
     if (count($cache['rate_table']) >= 1) {
         return $cache['rate_table'];
     }
     // Final rate table
     $rate_table = array();
     // API Auth settings //
     $args['username'] = array_key_exists('upsaccount', $wpsc_ups_settings) ? $wpsc_ups_settings['upsusername'] : '';
     $args['password'] = array_key_exists('upspassword', $wpsc_ups_settings) ? $wpsc_ups_settings['upspassword'] : '';
     $args['api_id'] = array_key_exists('upsid', $wpsc_ups_settings) ? $wpsc_ups_settings['upsid'] : '';
     $args['account_number'] = array_key_exists('upsaccount', $wpsc_ups_settings) ? $wpsc_ups_settings['upsaccount'] : '';
     $args['negotiated_rates'] = array_key_exists('ups_negotiated_rates', $wpsc_ups_settings) ? $wpsc_ups_settings['ups_negotiated_rates'] : '';
     $args['residential'] = $wpsc_ups_settings['49_residential'];
     $args['insured_shipment'] = array_key_exists('insured_shipment', $wpsc_ups_settings) ? $wpsc_ups_settings['insured_shipment'] : '0';
     // What kind of pickup service do you use ?
     $args['DropoffType'] = $wpsc_ups_settings['DropoffType'];
     $args['packaging'] = $wpsc_ups_settings['48_container'];
     // Preferred Currency to display
     $currency_data = WPSC_Countries::get_currency_code(get_option('currency_type'));
     if (!empty($currency_data)) {
         $args['currency'] = $currency_data;
     } else {
         $args['currency'] = 'USD';
     }
     // Shipping billing / account address
     $region = new WPSC_Region(get_option('base_country'), get_option('base_region'));
     $args['shipr_state'] = $region->get_code();
     $args['shipr_city'] = get_option('base_city');
     $args['shipr_ccode'] = get_option('base_country');
     $args['shipr_pcode'] = get_option('base_zipcode');
     // Physical Shipping address being shipped from
     $args['shipf_state'] = $args['shipr_state'];
     $args['shipf_city'] = $args['shipr_city'];
     $args['shipf_ccode'] = $args['shipr_ccode'];
     $args['shipf_pcode'] = $args['shipr_pcode'];
     $args['units'] = 'LBS';
     $args['cart_total'] = $wpsc_cart->calculate_subtotal(true);
     $args = apply_filters('wpsc_shipment_data', $args, $this->shipment);
     if (isset($args['stop'])) {
         //Do not get rates.
         return array();
     }
     // Build the XML request
     $request = $this->_buildRateRequest($args);
     // Now that we have the message to send ... Send it!
     $raw_quote = $this->_makeRateRequest($request);
     // Now we have the UPS response .. unfortunately its not ready
     // to be viewed by normal humans ...
     $quotes = $this->_parseQuote($raw_quote);
     // If we actually have rates back from UPS we can use em!
     if ($quotes != false) {
         $rate_table = apply_filters('wpsc_rates_table', $this->_formatTable($quotes, $args['currency']), $args, $this->shipment);
     } else {
         if (isset($wpsc_ups_settings['upsenvironment'])) {
             echo '<strong>:: GetQuote ::DEBUG OUTPUT::</strong><br />';
             echo 'Arguments sent to UPS';
             print_r($args);
             echo '<hr />';
             print $request;
             echo '<hr />';
             echo 'Response from UPS';
             echo $raw_quote;
             echo '</strong>:: GetQuote ::End DEBUG OUTPUT::';
         }
     }
     $wpec_ash->cache_results($this->internal_name, $rate_table, $this->shipment);
     // return the final formatted array !
     return $rate_table;
 }
Пример #4
0
    /**
     * General entry point for WPEC external shipping calculator
     * This function expects no arguments but requires POST data
     * and configuration from the plugin settings
     * @return array $rate_table List of rates in "Service"=>"Rate" format
     */
    function getQuote()
    {
        global $wpdb, $wpec_ash, $wpec_ash_tools, $wpsc_cart;
        $data = array();
        //************** These values are common to all entry points **************
        //*** User/Customer Entered Values ***\\
        //*** Set up the destination country ***\
        $data["dest_country"] = wpsc_get_customer_meta('shipping_country');
        $settings = get_option('wpec_usps');
        //Disable International Shipping. Default: Enabled as it currently is.
        $data['intl_rate'] = isset($settings['intl_rate']) && !empty($settings['intl_rate']) ? FALSE : TRUE;
        if (!$data['intl_rate'] && $data['dest_country'] != get_option('base_country')) {
            return array();
        }
        // If ths zip code is provided via a form post use it!
        $data["dest_zipcode"] = (string) wpsc_get_customer_meta('shippingpostcode');
        if (!is_object($wpec_ash_tools)) {
            $wpec_ash_tools = new ASHTools();
        }
        if (empty($data["dest_zipcode"]) && $wpec_ash_tools->needs_post_code($data["dest_country"])) {
            // We cannot get a quote without a zip code so might as well return!
            return array();
        }
        //*** Grab Total Weight from the shipment object for simple shipping
        $data["weight"] = wpsc_cart_weight_total();
        if (empty($data["weight"])) {
            return array();
        }
        // If the region code is provided via a form post use it!
        if (isset($_POST['region']) && !empty($_POST['region'])) {
            $data['dest_state'] = wpsc_get_region(sanitize_text_field($_POST['region']));
        } else {
            if ($dest_state = wpsc_get_customer_meta('shipping_state')) {
                // Well, we have a zip code in the session and no new one provided
                $data['dest_state'] = $dest_state;
            } else {
                $data['dest_state'] = "";
            }
        }
        $data["dest_country"] = $wpec_ash_tools->get_full_country($data["dest_country"]);
        $data["dest_country"] = $this->_update_country($data["dest_country"]);
        if (!is_object($wpec_ash)) {
            $wpec_ash = new ASH();
        }
        $shipping_cache_check['state'] = $data['dest_state'];
        $shipping_cache_check['country'] = $data['dest_country'];
        $shipping_cache_check['zipcode'] = $data["dest_zipcode"];
        $this->shipment = $wpec_ash->get_shipment();
        $this->shipment->set_destination($this->internal_name, $shipping_cache_check);
        $this->shipment->rates_expire = date('Y-m-d');
        //Date will be checked against the cached date.
        $data['shipper'] = $this->internal_name;
        $data["adv_rate"] = !empty($settings["adv_rate"]) ? $settings["adv_rate"] : FALSE;
        // Use advanced shipping for Domestic Rates ? Not available
        if ($data["weight"] > 70 && !(bool) $data["adv_rate"]) {
            //USPS has a weight limit: https://www.usps.com/send/can-you-mail-it.htm?#3.
            $over_weight_txt = apply_filters('wpsc_shipment_over_weight', __('Your order exceeds the standard shipping weight limit.
													Please contact us to quote other shipping alternatives.', 'wp-e-commerce'), $data);
            $shipping_quotes[$over_weight_txt] = 0;
            // yes, a constant.
            $wpec_ash->cache_results($this->internal_name, array($shipping_quotes), $this->shipment);
            return array($shipping_quotes);
        }
        // Check to see if the cached shipment is still accurate, if not we need new rate
        $cache = $wpec_ash->check_cache($this->internal_name, $this->shipment);
        // We do not want to spam USPS (and slow down our process) if we already
        // have a shipping quote!
        if (count($cache["rate_table"]) >= 1) {
            //$cache['rate_table'] could be array(0).
            return $cache["rate_table"];
        }
        //*** WPEC Configuration values ***\\
        $this->use_test_env = !isset($settings["test_server"]) ? false : (bool) $settings['test_server'];
        $data["fcl_type"] = !empty($settings["fcl_type"]) ? $settings["fcl_type"] : "PARCEL";
        $data["mail_type"] = !empty($settings["intl_pkg"]) ? $settings["intl_pkg"] : "Package";
        $data["base_zipcode"] = get_option("base_zipcode");
        $data["services"] = !empty($settings["services"]) ? $settings["services"] : array("STANDARD POST", "PRIORITY", "PRIORITY EXPRESS", "FIRST CLASS");
        foreach ($data["services"] as $id => $service) {
            if ($service == 'PARCEL') {
                $data["services"][$id] = 'STANDARD POST';
            }
            if ($service == 'EXPRESS') {
                $data["services"][$id] = 'PRIORITY EXPRESS';
            }
        }
        $data["user_id"] = $settings["id"];
        $data["value"] = $wpsc_cart->calculate_subtotal(true);
        //Required by $this->_build_intl_shipment.
        $data = apply_filters('wpsc_shipment_data', $data, $this->shipment);
        if (isset($data['stop'])) {
            //Do not get rates.
            return array();
        }
        //************ GET THE RATE ************\\
        $rate_table = apply_filters('wpsc_rates_table', $this->_run_quote($data), $data, $this->shipment);
        //Avoid trying getting rates again and again when the stored zip code is incorrect.
        //************ CACHE the Results ************\\
        $wpec_ash->cache_results($this->internal_name, $rate_table, $this->shipment);
        return $rate_table;
    }
Пример #5
0
 /**
  * returns shipping quotes using this shipping module.
  *
  * @return array collection of rates applicable.
  */
 function getQuote()
 {
     global $wpsc_cart;
     $weight = wpsc_cart_weight_total();
     if (is_object($wpsc_cart)) {
         $cart_total = $wpsc_cart->calculate_subtotal(true);
     }
     $layers = get_option('weight_rate_layers');
     if ($layers != '') {
         krsort($layers);
         foreach ($layers as $key => $shipping) {
             if ($weight >= (double) $key) {
                 if (stristr($shipping, '%')) {
                     // Shipping should be a % of the cart total
                     $shipping = str_replace('%', '', $shipping);
                     $shipping_amount = $cart_total * ($shipping / 100);
                     return array(__("Weight Rate", 'wp-e-commerce') => (double) $shipping_amount);
                 } else {
                     return array(__("Weight Rate", 'wp-e-commerce') => $shipping);
                 }
             }
         }
         $shipping = array_shift($layers);
         if (stristr($shipping, '%')) {
             $shipping = str_replace('%', '', $shipping);
             $shipping_amount = $cart_total * ($shipping / 100);
         } else {
             $shipping_amount = $shipping;
         }
         return array(__("Weight Rate", 'wp-e-commerce') => (double) $shipping_amount);
     }
 }
Пример #6
0
 function getQuote()
 {
     global $wpdb, $wpsc_usps_quote;
     if (isset($wpsc_usps_quote) && count($wpsc_usps_quote) > 0) {
         return $wpsc_usps_quote;
     }
     if (isset($_POST['zipcode'])) {
         $zipcode = $_POST['zipcode'];
         $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
     } else {
         if (isset($_SESSION['wpsc_zipcode'])) {
             $zipcode = $_SESSION['wpsc_zipcode'];
         } else {
             $zipcode = get_option('base_zipcode');
         }
     }
     $dest = $_SESSION['wpsc_delivery_country'];
     $weight = wpsc_cart_weight_total();
     $pound = floor($weight);
     $ounce = ($weight - $pound) * 16;
     $machinable = 'true';
     if ($ounce > 13 || $pound > 1) {
         $serv = get_option('usps_services');
         $serv = str_replace('FIRST CLASS, ', '', $serv);
         $serv = str_replace('FIRST CLASS', '', $serv);
         define('MODULE_SHIPPING_USPS_TYPES', $serv);
     } else {
         define('MODULE_SHIPPING_USPS_TYPES', get_option('usps_services'));
     }
     if ($dest == 'US' && 'US' == get_option('base_country')) {
         $request = '<RateV3Request USERID="' . get_option('uspsid') . '" PASSWORD="******">';
         $allowed_types = explode(", ", MODULE_SHIPPING_USPS_TYPES);
         $types = array("FIRST CLASS" => 0, "PRIORITY" => 0, "PRIORITY_MAIL" => 0, "PRIORITY_SMALL" => 0, "PRIORITY_REGULAR" => 0, "PRIORITY_LARGE" => 0, "EXPRESS" => 0, "EXPRESS_REGULAR" => 0, "PARCEL POST" => 0, "MEDIA" => 0, "LIBRARY" => 0);
         while (list($key, $value) = each($types)) {
             if (!in_array($key, $allowed_types)) {
                 continue;
             }
             // FIRST CLASS
             if ($key == 'FIRST CLASS') {
                 if ($ounce > 3.5) {
                     $FirstClassMailType = '<FirstClassMailType>FLAT</FirstClassMailType>';
                 } else {
                     $FirstClassMailType = '<FirstClassMailType>LETTER</FirstClassMailType>';
                 }
             } else {
                 $FirstClassMailType = '';
             }
             //PRIORITY
             if ($key == 'PRIORITY') {
                 $container = 'FLAT RATE ENVELOPE';
             }
             if ($key == 'PRIORITY_LARGE') {
                 $key = 'PRIORITY';
                 $container = 'LG FLAT RATE BOX';
             }
             if ($key == 'PRIORITY_SMALL') {
                 $key = 'PRIORITY';
                 $container = 'SM FLAT RATE BOX';
             }
             if ($key == 'PRIORITY_REGULAR') {
                 $key = 'PRIORITY';
                 $container = 'MD FLAT RATE BOX';
             }
             if ($key == 'PRIORITY_MAIL') {
                 $key = 'PRIORITY';
                 $container = '';
                 $size = 'REGULAR';
             }
             // EXPRESS
             if ($key == 'EXPRESS') {
                 $container = 'FLAT RATE ENVELOPE';
             }
             if ($key == 'EXPRESS_REGULAR') {
                 $key = 'EXPRESS';
                 $container = '';
                 $size = 'REGULAR';
             }
             if ($key == 'PARCEL POST') {
                 $container = 'REGULAR';
                 $machinable = 'false';
                 $size = 'REGULAR';
             }
             if ($key == 'MEDIA') {
                 $size = 'REGULAR';
             }
             if ($key == 'LIBRARY') {
                 $size = 'REGULAR';
             }
             $pound = round($pound, 2);
             $ounce = round($ounce, 2);
             $request .= '<Package ID="1">' . '<Service>' . $key . '</Service>' . $FirstClassMailType . '<ZipOrigination>' . get_option("base_zipcode") . '</ZipOrigination>' . '<ZipDestination>' . $zipcode . '</ZipDestination>' . '<Pounds>' . $pound . '</Pounds>' . '<Ounces>' . $ounce . '</Ounces>' . '<Container>' . $container . '</Container>' . '<Size>' . $size . '</Size>' . '<Machinable>' . $machinable . '</Machinable>' . '</Package>';
             if ($transit) {
                 $transitreq = 'USERID="' . MODULE_SHIPPING_USPS_USERID . '" PASSWORD="******">' . '<OriginZip>' . STORE_ORIGIN_ZIP . '</OriginZip>' . '<DestinationZip>' . $dest_zip . '</DestinationZip>';
                 switch ($key) {
                     case 'EXPRESS':
                         $transreq[$key] = 'API=ExpressMail&XML=' . urlencode('<ExpressMailRequest ' . $transitreq . '</ExpressMailRequest>');
                         break;
                     case 'PRIORITY':
                         $transreq[$key] = 'API=PriorityMail&XML=' . urlencode('<PriorityMailRequest ' . $transitreq . '</PriorityMailRequest>');
                         break;
                     case 'PARCEL':
                         $transreq[$key] = 'API=StandardB&XML=' . urlencode('<StandardBRequest ' . $transitreq . '</StandardBRequest>');
                         break;
                     default:
                         $transreq[$key] = '';
                         break;
                 }
             }
             $services_count++;
         }
         $request .= '</RateV3Request>';
         //'</RateRequest>'; //Changed by Greg Deeth April 30, 2008
         $request = 'API=RateV3&XML=' . urlencode($request);
     } else {
         $dest = $wpdb->get_var("SELECT country FROM " . WPSC_TABLE_CURRENCY_LIST . " WHERE isocode='" . $dest . "'");
         if ($dest == 'U.K.') {
             $dest = 'Great Britain and Northern Ireland';
         }
         $pound = round($pound, 2);
         $ounce = round($ounce, 2);
         $request = '<IntlRateRequest USERID="' . get_option('uspsid') . '" PASSWORD="******">' . '<Package ID="0">' . '<Pounds>' . $pound . '</Pounds>' . '<Ounces>' . $ounce . '</Ounces>' . '<MailType>Package</MailType>' . '<Country>' . $dest . '</Country>' . '</Package>' . '</IntlRateRequest>';
         $request = 'API=IntlRate&XML=' . urlencode($request);
     }
     $usps_server = 'production.shippingapis.com';
     $api_dll = 'shippingAPI.dll';
     if (get_option('usps_test_server') == '1') {
         $url = 'http://testing.shippingapis.com/ShippingAPITest.dll?' . $request;
     } else {
         $url = 'http://' . $usps_server . '/' . $api_dll . '?' . $request;
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
     curl_setopt($ch, CURLOPT_VERBOSE, 1);
     @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($ch, CURLOPT_TIMEOUT, 120);
     curl_setopt($ch, CURLOPT_USERAGENT, 'wp-e-commerce');
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $body = curl_exec($ch);
     curl_close($ch);
     $rates = array();
     $response = array();
     while (true) {
         if ($start = strpos($body, '<Package ID=')) {
             $body = substr($body, $start);
             $end = strpos($body, '</Package>');
             $response[] = substr($body, 0, $end + 10);
             $body = substr($body, $end + 9);
         } else {
             break;
         }
     }
     $rates = array();
     if ($dest == get_option('base_country')) {
         if (sizeof($response) == '1') {
             if (ereg('<Error>', $response[0])) {
                 $number = ereg('<Number>(.*)</Number>', $response[0], $regs);
                 $number = $regs[1];
                 $description = ereg('<Description>(.*)</Description>', $response[0], $regs);
                 $description = $regs[1];
             }
         }
         $n = sizeof($response);
         for ($i = 0; $i < $n; $i++) {
             if (strpos($response[$i], '<Rate>')) {
                 $service = ereg('<MailService>(.*)</MailService>', $response[$i], $regs);
                 $service = $regs[1];
                 $service = str_replace('&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt;', '<sup>&reg;</sup>', $service);
                 $service = str_replace('&amp;lt;sup&amp;gt;&amp;amp;trade;&amp;lt;/sup&amp;gt;', '<sup>&trade;</sup>', $service);
                 $postage = ereg('<Rate>(.*)</Rate>', $response[$i], $regs);
                 $postage = $regs[1];
                 $postage = $postage + get_option('usps_extra_cost');
                 if ($postage <= 0) {
                     continue;
                 }
                 $rates += array($service => $postage);
                 if ($transit) {
                     switch ($service) {
                         case 'EXPRESS':
                             $time = ereg('<MonFriCommitment>(.*)</MonFriCommitment>', $transresp[$service], $tregs);
                             $time = $tregs[1];
                             if ($time == '' || $time == 'No Data') {
                                 $time = 'Estimated 1 - 2 ' . 'Days';
                             } else {
                                 $time = 'Tomorrow by ' . $time;
                             }
                             break;
                         case 'PRIORITY':
                             $time = ereg('<Days>(.*)</Days>', $transresp[$service], $tregs);
                             $time = $tregs[1];
                             if ($time == '' || $time == 'No Data') {
                                 $time = 'Estimated 1 - 3 ' . 'Days';
                             } elseif ($time == '1') {
                                 $time .= ' ' . 'Day';
                             } else {
                                 $time .= ' ' . 'Days';
                             }
                             break;
                         case 'PARCEL':
                             $time = ereg('<Days>(.*)</Days>', $transresp[$service], $tregs);
                             $time = $tregs[1];
                             if ($time == '' || $time == 'No Data') {
                                 $time = 'Estimated 2 - 9 ' . 'Days';
                             } elseif ($time == '1') {
                                 $time .= ' ' . 'Day';
                             } else {
                                 $time .= ' ' . 'Days';
                             }
                             break;
                         case 'First-Class Mail':
                             $time = 'Estimated 1 - 5 ' . 'Days';
                             break;
                         case 'MEDIA':
                             $time = 'Estimated 2 - 9 ' . 'Days';
                             break;
                         case 'BPM':
                             $time = 'Estimated 2 - 9 ' . 'Days';
                             break;
                         default:
                             $time = '';
                             break;
                     }
                     if ($time != '') {
                         $transittime[$service] = ': ' . $time . '';
                     }
                 }
             }
         }
         $wpsc_usps_quote = $rates;
     } else {
         if (ereg('<Error>', $response[0])) {
             $number = ereg('<Number>(.*)</Number>', $response[0], $regs);
             $number = $regs[1];
             $description = ereg('<Description>(.*)</Description>', $response[0], $regs);
             $description = $regs[1];
         } else {
             $body = $response[0];
             $services = array();
             while (true) {
                 if ($start = strpos($body, '<Service ID=')) {
                     $body = substr($body, $start);
                     $end = strpos($body, '</Service>');
                     $services[] = substr($body, 0, $end + 10);
                     $body = substr($body, $end + 9);
                 } else {
                     break;
                 }
             }
             //$allowed_types = Array( 'EXPRESS MAIL INT' => "Express Mail International (EMS)", 'EXPRESS MAIL INT FLAT RATE ENV' => "Express Mail International (EMS) Flat-Rate Envelope", 'PRIORITY MAIL INT' => "Priority Mail International", 'PRIORITY MAIL INT FLAT RATE ENV' => "Priority Mail International Flat-Rate Envelope", 'PRIORITY MAIL INT FLAT RATE BOX' => "Priority Mail International Flat-Rate Box", 'FIRST-CLASS MAIL INT' => "First Class Mail International Letters" );
             $allowed_types = array('Global Express Guaranteed' => 'Global Express Guaranteed&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; (GXG)**', 'Global Express Non-Doc Rect' => 'Global Express Guaranteed&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; Non-Document Rectangular', 'Global Express Non-Doc Non-Rect' => 'Global Express Guaranteed&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; Non-Document Non-Rectangular', 'Global Express Envelopes' => 'USPS GXG&amp;lt;sup&amp;gt;&amp;amp;trade;&amp;lt;/sup&amp;gt; Envelopes**', 'Express Mail Int' => 'Express Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International', 'Express Mail Int Flat Rate Env' => 'Express Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Flat Rate Envelope', 'Express Mail Int Legal' => 'Express Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Legal Flat Rate Envelope', 'Priority Mail International' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International', 'Priority Mail Int Flat Rate Lrg Box' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Large Flat Rate Box', 'Priority Mail Int Flat Rate Med Box' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Medium Flat Rate Box', 'Priority Mail Int Flat Rate Small Box' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Small Flat Rate Box**', 'Priority Mail Int DVD' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International DVD Flat Rate Box**', 'Priority Mail Int Lrg Video' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Large Video Flat Rate Box**', 'Priority Mail Int Flat Rate Env' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Flat Rate Envelope**', 'Priority Mail Int Legal Flat Rate Env' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Legal Flat Rate Envelope**', 'Priority Mail Int Padded Flat Rate Env' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Padded Flat Rate Envelope**', 'Priority Mail Int Gift Card Flat Rate Env' => 'Priority Mail&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; International Gift Card Flat Rate Envelope**', 'Priority Mail International Small Flat Rate Envelope' => 'Priority Mail International&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; Small Flat Rate Envelope**', 'Priority Mail International Window Flat Rate Envelope' => 'Priority Mail International&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; Window Flat Rate Envelope**', 'First-Class Mail International Package' => 'First-Class Mail International&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; Package**', 'First-Class Mail International Large Envelope' => 'First-Class Mail International&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt; Large Envelope**');
             $size = sizeof($services);
             for ($i = 0, $n = $size; $i < $n; $i++) {
                 if (strpos($services[$i], '<Postage>')) {
                     $service = ereg('<SvcDescription>(.*)</SvcDescription>', $services[$i], $regs);
                     $service = $regs[1];
                     $postage = ereg('<Postage>(.*)</Postage>', $services[$i], $regs);
                     $postage = $regs[1];
                     $time = ereg('<SvcCommitments>(.*)</SvcCommitments>', $services[$i], $tregs);
                     $time = $tregs[1];
                     $time = preg_replace('/Weeks$/', 'Weeks', $time);
                     $time = preg_replace('/Days$/', 'Days', $time);
                     $time = preg_replace('/Day$/', 'Day', $time);
                     if (!in_array($service, $allowed_types) || $postage < 0) {
                         continue;
                     }
                     $postage = $postage + get_option('usps_extra_cost');
                     $service = str_replace('&amp;lt;sup&amp;gt;&amp;amp;reg;&amp;lt;/sup&amp;gt;', '<sup>&reg;</sup>', $service);
                     $service = str_replace('&amp;lt;sup&amp;gt;&amp;amp;trade;&amp;lt;/sup&amp;gt;', '<sup>&trade;</sup>', $service);
                     $rates += array($service => $postage);
                     if ($time != '') {
                         $transittime[$service] = ' (' . $time . ')';
                     }
                 }
             }
         }
     }
     $uspsQuote = $rates;
     $wpsc_usps_quote = $rates;
     return $uspsQuote;
 }
Пример #7
0
 /** 
  * Contact Bring Fraktguide API to get shipping quotes and return as array
  *
  * @return array[string]float|array|false Associative array containing shipping option and price
  */
 function getQuote()
 {
     global $wpdb, $wpsc_cart;
     if ($this->base_country != 'NO' || strlen($this->base_zipcode) != 4 || !count($wpsc_cart->cart_items)) {
         return;
     }
     $dest = $wpsc_cart->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 != 'NO') {
         // Return empty set of quotes if destination country is not Norway
         return array();
     }
     if ($dest == 'NO' && strlen($destzipcode) != 4) {
         // Invalid Norwegian Post Code entered, so just return an empty set of quotes
         return array();
     }
     if ($this->validate_postcode($destzipcode) == false) {
         // Invalid Norwegian Post Code entered, so just return an empty set of quotes
         return array();
     }
     $options = get_option($this->getInternalName() . '_options');
     $prod = "";
     $vol = "";
     foreach ($this->services as $code => $value) {
         if ($options['services'][$code] == 1) {
             $prod .= '&product=' . $code;
         }
     }
     if ($options['use_cod'] == 1) {
         // Add Collect on Delivery
         $prod .= '&additional=postoppkrav';
     }
     // Calculate the total cart dimensions by adding the volume of each product then calculating the cubed root
     $volume = 0;
     $volumeitemtotal = 0;
     $volumetotal = 0;
     $packagenum = 0;
     $weight = "";
     foreach ($wpsc_cart->cart_items as $key => $cart_item) {
         $product_meta = get_post_meta($cart_item->product_id, '_wpsc_product_metadata');
         $meta = $product_meta[0]['dimensions'];
         if ($meta && is_array($meta)) {
             $productVolume = 1;
             foreach (array('width', 'height', 'length') as $dimension) {
                 switch ($meta["{$dimension}_unit"]) {
                     // we need the units in cm
                     case 'cm':
                         // keep cm
                         $productVolume = $productVolume * floatval($meta[$dimension]);
                         break;
                     case 'meter':
                         // convert from m to cm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 100);
                         break;
                     case 'in':
                         // convert from in to cm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 2.54);
                         break;
                 }
             }
             $volume += floatval($productVolume);
         }
         if ($options['quote_method'] == 'items') {
             $volume = $volume / 1000;
             for ($i = 0; $i < $cart_item->quantity; $i++) {
                 $vol .= "&volume{$packagenum}={$volume}";
                 // convert weight from pound to gram
                 $gram = $cart_item->weight * 453.59237;
                 $weight .= "&weightInGrams{$packagenum}={$gram}";
                 $packagenum++;
             }
         } else {
             // convert volume from cubic cm to cubic dm
             $volumeitemtotal = $volume * $cart_item->quantity / 1000;
             $volumetotal = $volumetotal + $volumeitemtotal;
         }
     }
     if ($options['quote_method'] == 'total') {
         $totalweight = floatval(wpsc_cart_weight_total() * 453.59237);
         $weight = "&weightInGrams={$totalweight}";
         if ($volumetotal > 0) {
             $vol = "&volume={$volumetotal}";
         }
     }
     $base_url = "http://fraktguide.bring.no/fraktguide/products/price.xml?from={$this->base_zipcode}&to={$destzipcode}";
     $bring_url = $base_url . $prod . $weight . $vol;
     /*
     all.xml?weightInGrams=1500&from=7600&to=1407
     &length=30&width=40&height=40&volume=33&date=2009-2-3
     */
     $response = wp_remote_get($bring_url, $this->header_options);
     if (is_wp_error($response)) {
         $error_string = $response->get_error_message();
         return false;
     }
     if (200 != $response['response']['code']) {
         return false;
     }
     $body = trim($response['body']);
     $xml = new SimpleXMLElement($body);
     $pricearray = array();
     foreach ($xml->Product as $product) {
         $prodID = (string) $product->ProductId;
         if ($options['price_vat'] == 'with') {
             // Get price with VAT
             $price = floatval($product->Price->PackagePriceWithoutAdditionalServices->AmountWithVAT);
         } else {
             // Get price without VAT
             $price = floatval($product->Price->PackagePriceWithoutAdditionalServices->AmountWithoutVAT);
         }
         if ($options['use_cod'] == 1) {
             // Get price for Collect on Delivery
             if ($options['price_vat'] == 'with') {
                 // Get price for CoD with VAT
                 $cod = floatval($product->Price->AdditionalServicePrices->AdditionalService->AdditionalServicePrice->AmountWithVAT);
             } else {
                 // Get price for CoD without VAT
                 $cod = floatval($product->Price->AdditionalServicePrices->AdditionalService->AdditionalServicePrice->AmountWithoutVAT);
             }
             $totalprice = $price + $cod;
         } else {
             $totalprice = $price;
         }
         if ($options['use_handlingfee'] == true) {
             $handlingfee = floatval($options['handlingfee']);
             $finalprice = $totalprice + $handlingfee;
         } else {
             $finalprice = $totalprice;
         }
         $pricearray[$prodID] = $finalprice;
     }
     asort($pricearray);
     // Return an array of options for the user to choose
     // The first option is the default
     foreach ($pricearray as $key => $val) {
         if ($options['use_handlingfee'] == true) {
             $handlingFee = wpsc_currency_display($handlingfee, array('display_as_html' => false));
             $shippingString = __('%s - (including handling fee &agrave; %s)', 'bfg');
             $ProductName = sprintf($shippingString, $this->services[$key], $handlingFee);
         } else {
             $ProductName = $this->services[$key];
         }
         $shippingArray[strval($ProductName)] = floatval($val);
     }
     /** 
      * Return shipping options and prices
      */
     return $shippingArray;
 }
Пример #8
0
 function getQuote()
 {
     global $wpdb, $wpsc_cart;
     if ($this->base_country != 'AU' || strlen($this->base_zipcode) != 4 || !count($wpsc_cart->cart_items)) {
         return;
     }
     $dest = $_SESSION['wpsc_delivery_country'];
     // Weight is in pounds but needs to be in grams
     $weight = floatval(wpsc_cart_weight_total() * 453.59237);
     $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 == '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();
     }
     //Calculate the total cart dimensions by adding the volume of each product then calculating the cubed root
     $volume = 0;
     foreach ((array) $wpsc_cart->cart_items as $cart_item) {
         $meta = get_product_meta($cart_item->product_id, 'dimensions');
         if ($meta && is_array($meta)) {
             $productVolume = 1;
             foreach (array('width', 'height', 'length') as $dimension) {
                 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;
     $width = 100;
     $length = 100;
     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;
     }
     // API Documentation: http://drc.edeliver.com.au/
     $url = "http://drc.edeliver.com.au/ratecalc.asp?Pickup_Postcode={$this->base_zipcode}&Destination_Postcode={$destzipcode}&Quantity=1&Weight={$weight}&Height={$height}&Width={$width}&Length={$length}&Country={$dest}";
     $log = '';
     $methods = array();
     foreach ($this->services as $code => $service) {
         if (!$this->settings['services'][$code]) {
             continue;
         }
         $fullURL = "{$url}&Service_Type={$code}";
         $response = wp_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) {
             list($key, $value) = explode('=', $line);
             $key = trim($key);
             $value = trim($value);
             switch ($key) {
                 case 'charge':
                     $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];
     }
     if ($this->debug) {
         error_log('WP e-Commerce Australia Post shipping quotes for ' . site_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;
 }
Пример #9
0
 function getQuote()
 {
     global $wpdb;
     $dest = $_SESSION['delivery_country'];
     $wpsc_ups_settings = get_option("wpsc_ups_settings");
     $weight = wpsc_cart_weight_total();
     if (isset($_POST['zipcode'])) {
         $zipcode = $_POST['zipcode'];
         $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
     } else {
         if (isset($_SESSION['wpsc_zipcode'])) {
             $zipcode = $_SESSION['wpsc_zipcode'];
         }
     }
     if ($_GET['debug'] == 'true') {
         echo '<pre>' . print_r($wpsc_ups_settings, true) . '</pre>';
     }
     $shipping_cache_check['zipcode'] = $zipcode;
     $shipping_cache_check['weight'] = $weight;
     //$_SESSION['wpsc_shipping_cache_check']
     //this is where shipping breaks out of UPS if weight is higher than 150 LBS
     if ($weight > 150) {
         unset($_SESSION['quote_shipping_method']);
         $shipping_quotes[TXT_WPSC_OVER_UPS_WEIGHT] = 0;
         $_SESSION['wpsc_shipping_cache_check']['weight'] = $weight;
         $_SESSION['wpsc_shipping_cache'][$this->internal_name] = $shipping_quotes;
         $_SESSION['quote_shipping_method'] = $this->internal_name;
         return array($shipping_quotes);
     }
     //$shipping_cache_check = null;
     if ($_SESSION['wpsc_shipping_cache_check'] === $shipping_cache_check && $_SESSION['wpsc_shipping_cache'][$this->internal_name] != null) {
         $shipping_list = $_SESSION['wpsc_shipping_cache'][$this->internal_name];
     } else {
         $services = $this->getMethod($_SESSION['wpsc_delivery_country']);
         $ch = curl_init();
         $service_keys = array_keys($services);
         $key = $service_keys[0];
         $Url = join("&", array("http://www.ups.com/using/services/rave/qcostcgi.cgi?accept_UPS_license_agreement=yes", "10_action=4", "13_product=" . $key, "14_origCountry=" . get_option('base_country'), "15_origPostal=" . get_option('base_zipcode'), "19_destPostal=" . $zipcode, "22_destCountry=" . $_SESSION['wpsc_delivery_country'], "23_weight=" . $weight, "47_rate_chart=Regular Daily Pickup", "48_container={$wpsc_ups_settings['48_container']}", "49_residential={$wpsc_ups_settings['49_residential']}", "document=01", "billToUPS=no"));
         curl_setopt($ch, CURLOPT_URL, $Url);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         $raw_results = curl_exec($ch);
         curl_close($ch);
         $raw_results = str_replace('UPSOnLine', '', $raw_results);
         $results = explode("\n", $raw_results);
         $shipping_list = array();
         foreach ($results as $result) {
             $result = explode("%", $result);
             if ($services[$result[1]] != '') {
                 if ($result[1] == 'XPR' && $pre == 'XPR' || $result[1] == 'XDM' && $pre == 'XDM' || $result[1] == '1DP' && $pre == '1DP' || $result[1] == '1DM' && $pre == '1DM' || $result[1] == '1DA' && $pre == '1DA' || $result[1] == '2DA' && $pre == '2DA') {
                     $shipping_list += array($services[$result[1] . "L"] => $result[8]);
                 } else {
                     if ($result[1] == 'GND' && $pre == 'GND') {
                         $shipping_list += array($services[$result[1] . "RES"] => $result[8]);
                     } else {
                         $shipping_list += array($services[$result[1]] => $result[8]);
                     }
                 }
                 $pre = $result[1];
             }
         }
         $_SESSION['wpsc_shipping_cache_check']['zipcode'] = $zipcode;
         $_SESSION['wpsc_shipping_cache_check']['weight'] = $weight;
         $_SESSION['wpsc_shipping_cache'][$this->internal_name] = $shipping_list;
     }
     $shipping_list = array_reverse($shipping_list);
     //exit();
     return $shipping_list;
 }
Пример #10
0
 function getQuote()
 {
     global $wpdb, $wpsc_usps_quote;
     if (isset($wpsc_usps_quote) && count($wpsc_usps_quote) > 0) {
         return $wpsc_usps_quote;
     }
     if (isset($_POST['zipcode'])) {
         $zipcode = $_POST['zipcode'];
         $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
     } else {
         if (isset($_SESSION['wpsc_zipcode'])) {
             $zipcode = $_SESSION['wpsc_zipcode'];
         } else {
             $zipcode = get_option('base_zipcode');
         }
     }
     $dest = $_SESSION['wpsc_delivery_country'];
     $weight = wpsc_cart_weight_total();
     $pound = floor($weight);
     $ounce = ($weight - $pound) * 16;
     $machinable = 'true';
     if ($ounce > 13 || $pound > 1) {
         define('MODULE_SHIPPING_USPS_TYPES', "PRIORITY, EXPRESS, PARCEL POST");
     } else {
         define('MODULE_SHIPPING_USPS_TYPES', "FIRST CLASS, PRIORITY, EXPRESS, PARCEL POST");
     }
     if ($dest == 'US' && 'US' == get_option('base_country')) {
         $request = '<RateV3Request USERID="' . get_option('uspsid') . '" PASSWORD="******">';
         $allowed_types = explode(", ", MODULE_SHIPPING_USPS_TYPES);
         $types = array("FIRST CLASS" => 0, "PRIORITY" => 0, "EXPRESS" => 0, "PARCEL POST" => 0);
         while (list($key, $value) = each($types)) {
             if (!in_array($key, $allowed_types)) {
                 continue;
             }
             if ($key == 'FIRST CLASS') {
                 $FirstClassMailType = '<FirstClassMailType>LETTER</FirstClassMailType>';
             } else {
                 $FirstClassMailType = '';
             }
             if ($key == 'PRIORITY') {
                 $container = 'FLAT RATE ENVELOPE';
             }
             if ($key == 'EXPRESS') {
                 $container = 'FLAT RATE ENVELOPE';
             }
             if ($key == 'PARCEL POST') {
                 $container = 'REGULAR';
                 $machinable = 'false';
                 $size = 'REGULAR';
             }
             $pound = round($pound, 2);
             $ounce = round($ounce, 2);
             $request .= '<Package ID="1">' . '<Service>' . $key . '</Service>' . $FirstClassMailType . '<ZipOrigination>' . get_option("base_zipcode") . '</ZipOrigination>' . '<ZipDestination>' . $zipcode . '</ZipDestination>' . '<Pounds>' . $pound . '</Pounds>' . '<Ounces>' . $ounce . '</Ounces>' . '<Container>' . $container . '</Container>' . '<Size>' . $size . '</Size>' . '<Machinable>' . $machinable . '</Machinable>' . '</Package>';
             if ($transit) {
                 $transitreq = 'USERID="' . MODULE_SHIPPING_USPS_USERID . '" PASSWORD="******">' . '<OriginZip>' . STORE_ORIGIN_ZIP . '</OriginZip>' . '<DestinationZip>' . $dest_zip . '</DestinationZip>';
                 switch ($key) {
                     case 'EXPRESS':
                         $transreq[$key] = 'API=ExpressMail&XML=' . urlencode('<ExpressMailRequest ' . $transitreq . '</ExpressMailRequest>');
                         break;
                     case 'PRIORITY':
                         $transreq[$key] = 'API=PriorityMail&XML=' . urlencode('<PriorityMailRequest ' . $transitreq . '</PriorityMailRequest>');
                         break;
                     case 'PARCEL':
                         $transreq[$key] = 'API=StandardB&XML=' . urlencode('<StandardBRequest ' . $transitreq . '</StandardBRequest>');
                         break;
                     default:
                         $transreq[$key] = '';
                         break;
                 }
             }
             $services_count++;
         }
         $request .= '</RateV3Request>';
         //'</RateRequest>'; //Changed by Greg Deeth April 30, 2008
         //exit($request);
         $request = 'API=RateV3&XML=' . urlencode($request);
     } else {
         $dest = $wpdb->get_var("SELECT country FROM " . WPSC_TABLE_CURRENCY_LIST . " WHERE isocode='" . $dest . "'");
         if ($dest == 'U.K.') {
             $dest = 'Great Britain and Northern Ireland';
         }
         $pound = round($pound, 2);
         $ounce = round($ounce, 2);
         $request = '<IntlRateRequest USERID="' . get_option('uspsid') . '" PASSWORD="******">' . '<Package ID="0">' . '<Pounds>' . $pound . '</Pounds>' . '<Ounces>' . $ounce . '</Ounces>' . '<MailType>Package</MailType>' . '<Country>' . $dest . '</Country>' . '</Package>' . '</IntlRateRequest>';
         $request = 'API=IntlRate&XML=' . urlencode($request);
     }
     $usps_server = 'production.shippingapis.com';
     $api_dll = 'shippingAPI.dll';
     if (get_option('usps_test_server') == '1') {
         $url = 'http://testing.shippingapis.com/ShippingAPITest.dll?' . $request;
     } else {
         $url = 'http://' . $usps_server . '/' . $api_dll . '?' . $request;
     }
     //exit('URL '.$url);
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
     curl_setopt($ch, CURLOPT_VERBOSE, 1);
     @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($ch, CURLOPT_TIMEOUT, 120);
     curl_setopt($ch, CURLOPT_USERAGENT, 'wp-e-commerce');
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $body = curl_exec($ch);
     //exit('Response:<pre>'.print_r($body, true).'</pre>'.$url);
     curl_close($ch);
     //exit($body);
     $rates = array();
     $response = array();
     while (true) {
         if ($start = strpos($body, '<Package ID=')) {
             $body = substr($body, $start);
             $end = strpos($body, '</Package>');
             $response[] = substr($body, 0, $end + 10);
             $body = substr($body, $end + 9);
         } else {
             break;
         }
     }
     $rates = array();
     if ($dest == get_option('base_country')) {
         if (sizeof($response) == '1') {
             if (ereg('<Error>', $response[0])) {
                 $number = ereg('<Number>(.*)</Number>', $response[0], $regs);
                 $number = $regs[1];
                 $description = ereg('<Description>(.*)</Description>', $response[0], $regs);
                 $description = $regs[1];
                 //return array('error' => $number . ' - ' . $description);
             }
         }
         $n = sizeof($response);
         for ($i = 0; $i < $n; $i++) {
             if (strpos($response[$i], '<Rate>')) {
                 $service = ereg('<MailService>(.*)</MailService>', $response[$i], $regs);
                 $service = $regs[1];
                 $postage = ereg('<Rate>(.*)</Rate>', $response[$i], $regs);
                 $postage = $regs[1];
                 if ($postage <= 0) {
                     continue;
                 }
                 $rates += array($service => $postage);
                 if ($transit) {
                     switch ($service) {
                         case 'EXPRESS':
                             $time = ereg('<MonFriCommitment>(.*)</MonFriCommitment>', $transresp[$service], $tregs);
                             $time = $tregs[1];
                             if ($time == '' || $time == 'No Data') {
                                 $time = 'Estimated 1 - 2 ' . 'Days';
                             } else {
                                 $time = 'Tomorrow by ' . $time;
                             }
                             break;
                         case 'PRIORITY':
                             $time = ereg('<Days>(.*)</Days>', $transresp[$service], $tregs);
                             $time = $tregs[1];
                             if ($time == '' || $time == 'No Data') {
                                 $time = 'Estimated 1 - 3 ' . 'Days';
                             } elseif ($time == '1') {
                                 $time .= ' ' . 'Day';
                             } else {
                                 $time .= ' ' . 'Days';
                             }
                             break;
                         case 'PARCEL':
                             $time = ereg('<Days>(.*)</Days>', $transresp[$service], $tregs);
                             $time = $tregs[1];
                             if ($time == '' || $time == 'No Data') {
                                 $time = 'Estimated 2 - 9 ' . 'Days';
                             } elseif ($time == '1') {
                                 $time .= ' ' . 'Day';
                             } else {
                                 $time .= ' ' . 'Days';
                             }
                             break;
                         case 'First-Class Mail':
                             $time = 'Estimated 1 - 5 ' . 'Days';
                             break;
                         case 'MEDIA':
                             $time = 'Estimated 2 - 9 ' . 'Days';
                             break;
                         case 'BPM':
                             $time = 'Estimated 2 - 9 ' . 'Days';
                             break;
                         default:
                             $time = '';
                             break;
                     }
                     if ($time != '') {
                         $transittime[$service] = ': ' . $time . '';
                     }
                 }
             }
         }
         $wpsc_usps_quote = $rates;
         //return $rates;
     } else {
         if (ereg('<Error>', $response[0])) {
             $number = ereg('<Number>(.*)</Number>', $response[0], $regs);
             $number = $regs[1];
             $description = ereg('<Description>(.*)</Description>', $response[0], $regs);
             $description = $regs[1];
             //return array('error' => $number . ' - ' . $description);
         } else {
             $body = $response[0];
             $services = array();
             while (true) {
                 if ($start = strpos($body, '<Service ID=')) {
                     $body = substr($body, $start);
                     $end = strpos($body, '</Service>');
                     $services[] = substr($body, 0, $end + 10);
                     $body = substr($body, $end + 9);
                 } else {
                     break;
                 }
             }
             $allowed_types = array('EXPRESS MAIL INT' => "Express Mail International (EMS)", 'EXPRESS MAIL INT FLAT RATE ENV' => "Express Mail International (EMS) Flat-Rate Envelope", 'PRIORITY MAIL INT' => "Priority Mail International", 'PRIORITY MAIL INT FLAT RATE ENV' => "Priority Mail International Flat-Rate Envelope", 'PRIORITY MAIL INT FLAT RATE BOX' => "Priority Mail International Flat-Rate Box", 'FIRST-CLASS MAIL INT' => "First Class Mail International Letters");
             //foreach( explode(", ", MODULE_SHIPPING_USPS_TYPES_INTL) as $value ) $allowed_types[$value] = $this->intl_types[$value];
             $size = sizeof($services);
             for ($i = 0, $n = $size; $i < $n; $i++) {
                 if (strpos($services[$i], '<Postage>')) {
                     $service = ereg('<SvcDescription>(.*)</SvcDescription>', $services[$i], $regs);
                     $service = $regs[1];
                     $postage = ereg('<Postage>(.*)</Postage>', $services[$i], $regs);
                     $postage = $regs[1];
                     $time = ereg('<SvcCommitments>(.*)</SvcCommitments>', $services[$i], $tregs);
                     $time = $tregs[1];
                     $time = preg_replace('/Weeks$/', 'Weeks', $time);
                     $time = preg_replace('/Days$/', 'Days', $time);
                     $time = preg_replace('/Day$/', 'Day', $time);
                     if (!in_array($service, $allowed_types) || $postage < 0) {
                         continue;
                     }
                     $rates += array($service => $postage);
                     if ($time != '') {
                         $transittime[$service] = ' (' . $time . ')';
                     }
                 }
             }
             //$uspsQuote=$rates;
         }
     }
     $uspsQuote = $rates;
     $wpsc_usps_quote = $rates;
     //exit('<pre>'.print_r($uspsQuote,true).'</pre>');
     return $uspsQuote;
 }
Пример #11
0
 function getQuote()
 {
     global $wpdb;
     // Arguments array for various functions to use
     $args = array();
     // Final rate table
     $rate_table = array();
     // Get the ups settings from the ups account info page (Shipping tab)
     $wpsc_ups_settings = get_option("wpsc_ups_settings");
     // Get the wordpress shopping cart options
     $wpsc_options = get_option("wpsc_options");
     // API Auth settings //
     $args['username'] = $wpsc_ups_settings['upsusername'];
     $args['password'] = $wpsc_ups_settings['upspassword'];
     $args['api_id'] = $wpsc_ups_settings['upsid'];
     // What kind of pickup service do you use ?
     $args['pickup_type'] = "01";
     $args['packaging'] = $wpsc_ups_settings['48_container'];
     // Preferred Currency to display
     $currency_data = $wpdb->get_row("SELECT `code`\n                                             FROM `" . WPSC_TABLE_CURRENCY_LIST . "`\n                                             WHERE `isocode`='" . $wpsc_options['currency_type'] . "'\n                                             LIMIT 1", ARRAY_A);
     if ($currency_data) {
         $args['currency'] = $currency_data['code'];
     } else {
         $args['currency'] = "USD";
     }
     // Shipping billing / account address
     $args['shipr_ccode'] = get_option('base_country');
     $args['shipr_pcode'] = get_option('base_zipcode');
     // Physical Shipping addres being shipped from
     $args['shipf_ccode'] = get_option('base_country');
     $args['shipf_pcode'] = get_option('base_zipcode');
     // Get the total weight from the shopping cart
     $args['units'] = "LBS";
     $args['weight'] = wpsc_cart_weight_total();
     // Destination zip code
     $args['dest_ccode'] = $_SESSION['wpsc_delivery_country'];
     if ($args['dest_ccode'] == "UK") {
         // So, UPS is a little off the times
         $args['dest_ccode'] = "GB";
     }
     // If ths zip code is provided via a form post use it!
     if (isset($_POST['zipcode'])) {
         $args['dest_pcode'] = $_POST['zipcode'];
         $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
     } else {
         if (isset($_SESSION['wpsc_zipcode'])) {
             // Well, we have a zip code in the session and no new one provided
             $args['dest_pcode'] = $_SESSION['wpsc_zipcode'];
         } else {
             // We cannot get a quote without a zip code so might as well return!
             return array();
         }
     }
     $shipping_cache_check['zipcode'] = $args['dest_pcode'];
     $shipping_cache_check['weight'] = $args['weight'];
     // This is where shipping breaks out of UPS if weight is higher than 150 LBS
     if ($weight > 150) {
         unset($_SESSION['quote_shipping_method']);
         $shipping_quotes[TXT_WPSC_OVER_UPS_WEIGHT] = 0;
         $_SESSION['wpsc_shipping_cache_check']['weight'] = $args['weight'];
         $_SESSION['wpsc_shipping_cache'][$this->internal_name] = $shipping_quotes;
         $_SESSION['quote_shipping_method'] = $this->internal_name;
         return array($shipping_quotes);
     }
     // We do not want to spam UPS (and slow down our process) if we already
     // have a shipping quote!
     if ($_SESSION['wpsc_shipping_cache_check'] === $shipping_cache_check && $_SESSION['wpsc_shipping_cache'][$this->internal_name] != null) {
         $rate_table = $_SESSION['wpsc_shipping_cache'][$this->internal_name];
     } else {
         // Build the XML request
         $request = $this->_buildRateRequest($args);
         // Now that we have the message to send ... Send it!
         $raw_quote = $this->_makeRateRequest($request);
         // Now we have the UPS response .. unfortunately its not ready
         // to be viewed by normal humans ...
         $quotes = $this->_parseQuote($raw_quote);
         // If we actually have rates back from UPS we can use em!
         if ($quotes != false) {
             $rate_table = $this->_formatTable($quotes, $args['currency']);
         }
     }
     // return the final formatted array !
     $_SESSION['wpsc_shipping_cache_check']['zipcode'] = $args['dest_pcode'];
     $_SESSION['wpsc_shipping_cache_check']['weight'] = $args['weight'];
     $_SESSION['wpsc_shipping_cache'][$this->internal_name] = $rate_table;
     return $rate_table;
 }