Jump to content

Need Assistance in How PHP Code is Acquiring Shipping Cost from UPS


pghtech

Recommended Posts

I am using CubeCart (v4) for my e-commerce site. 

 

I have attached the code below for three .php files, one of which is the actual shopping cart .php file that uses the other two (UPS and Calc) .php files to acquire shipping cost from UPS. 

 

QUESTION:

Can someone point out the flow, of how the Cart.inc.php file is sending the calculated (total weight) of all products to UPS through the use of the other two files (calc.php and UPS.php) to acquire shipping cost from UPS.

 

PROBLEM and GOAL:

It passes the total 'actual weight' value to UPS to acquire shipping cost for any of the shipping options you have enabled in CubeCart.  The problem is that CubeCart does not support 'Dimensional weight' which is what UPS uses to calculate any "AIR" shipping cost (i.e. Next Day Air, 2nd Day Air).  Dimensional weight is the cubic weight (length x width x height) of each package.  UPS only uses 'actual weight' for calculating "Ground" shipping cost.

 

What happens is that CubeCart uses the total 'actual weight' of all products in the shopping cart to acquire shipping cost for both ground and AIR shipping cost. Therefore, ground shipping cost is correct, while AIR shipping cost are lower since actual weight for the products I sell is lower than cubic weight of the package. 

 

I have completed the ability to input the package dimensions of each product, and have it calculate and store the cubic weight of each package and finally calculate the 'total' cubic weight of the contents in the shopping cart.  If I could just figure out how the cart.inc.php file passes the value of the 'actual weight' through the other two files (UPS.php and Calc.php) to acquire shipping cost, I could possibly figure out a way to use the 'actual weight' for acquiring shipping cost for ground, and the 'cubic weight' for acquiring shipping cost for all AIR shipping options.

 

 

Shopping Cart

Cart.inc.php

<?php
/*
+--------------------------------------------------------------------------
|   CubeCart 4
|   ========================================
|	CubeCart is a registered trade mark of Devellion Limited
|   Copyright Devellion Limited 2006. All rights reserved.
|   Devellion Limited,
|   5 Bridge Street,
|   Bishops Stortford,
|   HERTFORDSHIRE.
|   CM23 2JU
|   UNITED KINGDOM
|   http://www.devellion.com
|	UK Private Limited Company No. 5323904
|   ========================================
|   Web: http://www.cubecart.com
|   Email: info (at) cubecart (dot) com
|	License Type: CubeCart is NOT Open Source Software and Limitations Apply 
|   Licence Info: http://www.cubecart.com/site/faq/license.php
+--------------------------------------------------------------------------
|	cart.inc.php
|   ========================================
|	Core Checkout & Cart Pages	
+--------------------------------------------------------------------------
*/

if(!defined('CC_INI_SET')) die("Access Denied");

session_start(); // required for PayPal Pro

// include lang file

$lang1 = getLang("includes".CC_DS."content".CC_DS."reg.inc.php");
$lang2 = getLang("includes".CC_DS."content".CC_DS."cart.inc.php");

$lang = array_merge($lang1, $lang2);

require_once("classes".CC_DS."cart".CC_DS."shoppingCart.php");
$cart = new cart();

// check the user is logged on
if($_GET['_a']=="step2" && empty($cc_session->ccUserData['customer_id'])) {
httpredir("index.php?_g=co&_a=step1");
}
// if user is logged in an act = cart jump ahead to step2
else if($_GET['_a']=="cart" && $cc_session->ccUserData['customer_id']>0) {
#	$basket = $cart->cartContents($cc_session->ccUserData['basket']);
#	if (!empty($basket)) {
	httpredir("index.php?_g=co&_a=step2");
#	}
}
/* start mod: Shipping Estimates - http://cubecart.expandingbrain.com */
if ($config['shipAddressLock'] && !empty($_GET['editDel'])) {
/* not permitted to have different delivery address - change invoice instead */
httpredir('index.php?_a=profile&f=step2');
}
/* end mod: Shipping Estimates - by Estelle */


$basket = $cart->cartContents($cc_session->ccUserData['basket']);

// Flexible Taxes, by Estelle Winterflood
$config_tax_mod = fetchDbConfig("Multiple_Tax_Mod");

if(isset($_GET['remlast'])) {
$cart->unsetVar("invArray");
$cart->removeLastItem();
$refresh = TRUE;
}
if (isset($_GET['remCode'])) {
$cart->removeCoupon($_GET['remCode']);
// lose the post vars
$refresh = TRUE;

}

if (isset($_POST['coupon']) && !empty($_POST['coupon']) && !isset($basket['code'])){

$cart->addCoupon($_POST['coupon']);
// lose post vars
$refresh = TRUE;

}
if(isset($_POST['shipKey']) && $_POST['shipKey']>0) {

$cart->setVar($_POST['shipKey'],"shipKey");
// lose post vars
$refresh = TRUE;

}
/* start mod: Shipping Estimates - http://cubecart.expandingbrain.com */
if (!empty($_POST['shipAddress'])) {
$cart->setVar($_POST['shipAddress'], "shipAddress");
$refresh = TRUE;
} 
/* end mod: Shipping Estimates - by Estelle */


if(isset($_POST['delInf'])) {

// start: Flexible Taxes, by Estelle Winterflood
if (isset($_POST['which_field'])){
	$delivery = $_POST['delInf'];
	if ($_POST['which_field']=="T"){
		unset($delivery['county_sel']);
	} elseif ($_POST['which_field']=="S") {
		$delivery['county'] = $delivery['county_sel'];
		unset($delivery['county_sel']);
	}
	$_POST['delInf'] = $delivery;
}

$cart->setVar($_POST['delInf'],"delInf");
$refresh = TRUE;

}

if(isset($_GET['remove'])) {

$cart->unsetVar("invArray");
$cart->remove($_GET['remove']);
$refresh = true;
} 

if (isset($_POST['quan'])) {
$cart->unsetVar('invArray');
foreach ($_POST['quan'] as $key => $value) {
	$cart->update($key, $value);
}
$refresh = true;
} 
if(isset($_GET['mode']) && $_GET['mode'] == "emptyCart") {
## Empty the cart
$cart->emptyCart();
$refresh = true;
}

if(isset($_POST['productCode']) && !empty($_POST['productCode'])) {
$cart->addByCode($_POST['productCode']);

$refresh = TRUE;
}

if ($refresh) {
$excludeGetVars = array("editDel" => 1, "remCode" => 1, "mode" => 1, "remove" => 1, "remlast" => 1);
httpredir(currentpage($excludeGetVars));
}

$view_cart = new XTemplate ("content".CC_DS."cart.tpl");
$view_cart->assign("LANG_CART",$lang['cart']['cart']);
$view_cart->assign("LANG_CHECKOUT", $lang['cart']['checkout']);
$view_cart->assign("LANG_PAYMENT", $lang['cart']['payment']);
$view_cart->assign("LANG_COMPLETE", $lang['cart']['complete']);
$view_cart->assign("LANG_ADD_PRODCODE",$lang['cart']['add_more']);
$view_cart->assign("LANG_ADD", $lang['cart']['add']);
$view_cart->assign("LANG_QTY",$lang['cart']['qty']);
$view_cart->assign("LANG_PRODUCT",$lang['cart']['product']);
$view_cart->assign("LANG_CODE",$lang['cart']['code']);
$view_cart->assign("LANG_STOCK",$lang['cart']['stock']);
$view_cart->assign("LANG_PRICE",$lang['cart']['price']);
$view_cart->assign("LANG_LINE_PRICE",$lang['cart']['line_price']);
$view_cart->assign("LANG_DELETE",$lang['cart']['delete']);
$view_cart->assign("LANG_REMOVE_ITEM",$lang['cart']['remove']);

if ($_GET['_a'] == 'cart') {

$view_cart->assign("CONT_VAL","index.php?_g=co&_a=step1");
$view_cart->assign("LANG_CHECKOUT_BTN",$lang['cart']['checkout_btn']);
$view_cart->assign("LANG_VIEW_CART",$lang['cart']['view_cart']);
$view_cart->assign("CLASS_CART","class='txtcartProgressCurrent'");
$view_cart->assign("CLASS_STEP2","");

$view_cart->assign("BSKT_LI","class='item_activeRT'");
$view_cart->assign("BSKT_SPAN","class='item_activeLT'");
$view_cart->assign("CHKT_LI","");
$view_cart->assign("CHKT_SPAN","");
$view_cart->assign("PYMT_LI","");
$view_cart->assign("PYMT_SPAN","");
$view_cart->assign("CMPT_LI","");
$view_cart->assign("CMPT_SPAN","");

} else if ($_GET['_a'] == 'step2' && !empty($basket['conts'])) {

#	if (empty($basket)) httpredir('?_g=co&_a=cart');

// Place Order Link
$view_cart->assign("CONT_VAL", "index.php?_g=co&_a=step3");
$view_cart->assign("CONT_VAL", ($_GET['editDel'] == 1) ? "javascript:submitDoc('cart');" : "index.php?_g=co&_a=step3");

$view_cart->assign("BSKT_LI","");
$view_cart->assign("BSKT_SPAN","");
$view_cart->assign("CHKT_LI","class='item_activeRT'");
$view_cart->assign("CHKT_SPAN","class='item_activeLT'");
$view_cart->assign("PYMT_LI","");
$view_cart->assign("PYMT_SPAN","");
$view_cart->assign("CMPT_LI","");
$view_cart->assign("CMPT_SPAN","");

$view_cart->assign("CLASS_CART","");
$view_cart->assign("CLASS_STEP2","class='txtcartProgressCurrent'");
$view_cart->assign("LANG_VIEW_CART",$lang['cart']['place_order_title']);

$view_cart->assign("LANG_INVOICE_ADDRESS",$lang['cart']['invoice_address']);
$view_cart->assign("LANG_DELIVERY_ADDRESS",$lang['cart']['delivery_address']);

$view_cart->assign("TXT_TITLE",$lang['cart']['title']);
$view_cart->assign("LANG_TITLE_DESC",$lang['reg']['title_desc']);

$view_cart->assign("TXT_FIRST_NAME",$lang['cart']['first_name']);
$view_cart->assign("TXT_LAST_NAME",$lang['cart']['last_name']);
$view_cart->assign("TXT_COMPANY_NAME",$lang['cart']['company_name']);
$view_cart->assign("TXT_ADD_1",$lang['cart']['address1']);
$view_cart->assign("TXT_ADD_2",$lang['cart']['address2']);
$view_cart->assign("TXT_TOWN",$lang['cart']['town']);
$view_cart->assign("TXT_COUNTY",$lang['cart']['county']);
$view_cart->assign("TXT_POSTCODE",$lang['cart']['postcode']);
$view_cart->assign("TXT_COUNTRY",$lang['cart']['country']);

// PayPal EC make payment button
if (isset($_SESSION['token']) && isset($_SESSION['payer_id'])) {
	$lang = getLang("includes".CC_DS."content".CC_DS."gateway.inc.php");
	$view_cart->assign("LANG_CHECKOUT_BTN",$lang['gateway']['continue']);
} else {
	$view_cart->assign("LANG_CHECKOUT_BTN",$lang['cart']['place_order']);
}

// stick in delivery details
if (!isset($basket['delInf']) || $config['shipAddressLock']) {
	$iniDeliv['title']			= $cc_session->ccUserData['title'];
	$iniDeliv['firstName']		= $cc_session->ccUserData['firstName'];
	$iniDeliv['lastName']		= $cc_session->ccUserData['lastName'];
	$iniDeliv['companyName']	= $cc_session->ccUserData['companyName'];
	$iniDeliv['add_1']			= $cc_session->ccUserData['add_1'];
	$iniDeliv['add_2']			= $cc_session->ccUserData['add_2'];
	$iniDeliv['town']			= $cc_session->ccUserData['town'];
	$iniDeliv['county']			= $cc_session->ccUserData['county'];
	$iniDeliv['postcode']		= $cc_session->ccUserData['postcode'];
	$iniDeliv['country']		= $cc_session->ccUserData['country'];
	$basket = $cart->setVar($iniDeliv, 'delInf');
}


// stick in delivery details
$view_cart->assign("VAL_DEL_TITLE", $basket['delInf']['title']);
$view_cart->assign("VAL_DEL_FIRST_NAME",$basket['delInf']['firstName']);
$view_cart->assign("VAL_DEL_LAST_NAME",$basket['delInf']['lastName']);
$view_cart->assign("VAL_DEL_COMPANY_NAME",$basket['delInf']['companyName']);
$view_cart->assign("VAL_DEL_ADD_1",$basket['delInf']['add_1']);
$view_cart->assign("VAL_DEL_ADD_2",$basket['delInf']['add_2']);
$view_cart->assign("VAL_DEL_TOWN",$basket['delInf']['town']);
$view_cart->assign("VAL_DEL_COUNTY",$basket['delInf']['county']);
$view_cart->assign("VAL_DEL_POSTCODE",$basket['delInf']['postcode']);
$view_cart->assign("VAL_DEL_COUNTRY",getCountryFormat($basket['delInf']['country'],"id","printable_name"));

// stick in invoice details
$view_cart->assign("VAL_TITLE",$cc_session->ccUserData['title']);
$view_cart->assign("VAL_FIRST_NAME",$cc_session->ccUserData['firstName']);
$view_cart->assign("VAL_LAST_NAME",$cc_session->ccUserData['lastName']);
$view_cart->assign("VAL_COMPANY_NAME",$cc_session->ccUserData['companyName']);
$view_cart->assign("VAL_ADD_1",$cc_session->ccUserData['add_1']);
$view_cart->assign("VAL_ADD_2",$cc_session->ccUserData['add_2']);
$view_cart->assign("VAL_TOWN",$cc_session->ccUserData['town']);
$view_cart->assign("VAL_COUNTY",$cc_session->ccUserData['county']);
$view_cart->assign("VAL_POSTCODE",$cc_session->ccUserData['postcode']);
$view_cart->assign("VAL_COUNTRY",getCountryFormat($cc_session->ccUserData['country'],"id","printable_name"));

$view_cart->assign("LANG_CHANGE_INV_ADD",$lang['cart']['edit_invoice_address']);
$view_cart->assign("VAL_BACK_TO", $_GET['_a']);

// start: Flexible Taxes, by Estelle Winterflood
// counties selector

if (isset($_GET['editDel']) && $_GET['editDel'] == true && !$config['shipAddressLock']) {
	$jsScript = jsGeoLocationExtended('country', 'county_sel', $lang['cart']['na'], 'divCountySelect', 'divCountyText', 'county', 'which_field');
	$counties = $db->select("SELECT * FROM  ".$glob['dbprefix']."CubeCart_iso_counties WHERE countryId = '".$basket['delInf']['country']."';");

	if (is_array($counties)){
		$view_cart->assign("VAL_COUNTY_SEL_STYLE", "style='display:block;'");
		$view_cart->assign("VAL_COUNTY_TXT_STYLE", "style='display:none;'");
		$view_cart->assign("VAL_COUNTY_WHICH_FIELD", "S");
	} else {
		$view_cart->assign("VAL_COUNTY_SEL_STYLE", "style='display:none;'");
		$view_cart->assign("VAL_COUNTY_TXT_STYLE", "style='display:block;'");
		$view_cart->assign("VAL_COUNTY_WHICH_FIELD", 'T');
	}
	$view_cart->assign('JS_COUNTY_OPTIONS', '<script type="text/javascript">'.$jsScript.'</script>');

	for ($i=0; $i<count($counties); $i++) {
		if ($counties[$i]['name'] == $basket['delInf']['county']){
			$view_cart->assign('COUNTY_SELECTED', 'selected="selected"');
		} else {
			$view_cart->assign('COUNTY_SELECTED', '');
		}

		$countyName = $counties[$i]['name'];
		if (strlen($countyName)>20) $countyName = substr($countyName ,0, 20).'…';

		$view_cart->assign('VAL_DEL_COUNTY_NAME', $countyName);
		$view_cart->parse('view_cart.cart_true.edit_delivery.county_opts');
	}

	// end: Flexible Taxes
	$cache		= new cache('glob.countries');
	$countries	= $cache->readCache();

	if (!$cache->cacheStatus) {
		$countries = $db->select("SELECT id, printable_name FROM ".$glob['dbprefix']."CubeCart_iso_countries ORDER BY printable_name");
		$cache->writeCache($countries);
	} 

	for ($i=0; $i<count($countries); $i++) {
		if ($countries[$i]['id'] == $basket['delInf']['country']) {
			$view_cart->assign('COUNTRY_SELECTED', 'selected="selected"');
		} else {
			$view_cart->assign('COUNTRY_SELECTED', '');
		}
		$view_cart->assign("VAL_DEL_COUNTRY_ID",$countries[$i]['id']);
		$countryName = $countries[$i]['printable_name'];

		if (strlen($countryName)>20) {
			$countryName = substr($countryName,0,20)."…";
		}

		$view_cart->assign('VAL_DEL_COUNTRY_NAME', $countryName);
		$view_cart->parse('view_cart.cart_true.edit_delivery.country_opts');
	}
	$view_cart->parse('view_cart.cart_true.edit_delivery');
} else {
	if (!$config['shipAddressLock']) {
		$view_cart->assign('LANG_CHANGE_DEL_ADD', $lang['cart']['edit_delivery_address']);
		$view_cart->parse('view_cart.cart_true.fixed_delivery.edit_btn');
	}
	$view_cart->parse("view_cart.cart_true.fixed_delivery");
}
}

## See if there are contents in the basket array
if ($basket['conts']) {

$tax = 0;
$taxCustomer = 0;
$taxZone = array();

// $config['priceTaxDelInv'] 0 = devivery address
// $config['priceTaxDelInv'] 1 = invoice address
//$countyDel = $db->select("SELECT `id` FROM ".$glob['dbprefix']."CubeCart_iso_counties WHERE `abbrev` = ".$db->MySQLSafe($basket['delInf']['county'])." AND `countryId` = ".$db->MySQLSafe($basket['delInf']['country']));
$countyDel = $db->select("SELECT `id` FROM ".$glob['dbprefix']."CubeCart_iso_counties WHERE (`abbrev` = ".$db->MySQLSafe($basket['delInf']['county'])." OR `name` = ".$db->MySQLSafe($basket['delInf']['county']).") AND `countryId` = ".$db->MySQLSafe($basket['delInf']['country']));

$countyInv = $db->select("SELECT `id` FROM ".$glob['dbprefix']."CubeCart_iso_counties WHERE `name` = ".$db->mySQLSafe($cc_session->ccUserData['county'])." AND `countryId` = ".$db->MySQLSafe($cc_session->ccUserData['country']));


if($config['priceTaxDelInv']==0 || $config['shipAddressLock'] == 1) {
	// calculate tax on delivery address
	$taxZone['countyId'] = $countyDel[0]['id'];

	$taxZone['countryId'] = $basket['delInf']['country'];

} elseif($config['priceTaxDelInv']==1) {
	// calculate tax on invoice address
	$taxZone['countyId'] = $countyInv[0]['id'];
	$taxZone['countryId'] = $cc_session->ccUserData['country'];
}

if ($taxZone['countryId']==$config['taxCountry']) {
	if ($config['taxCounty']==0) {
		// tax customer
		$taxCustomer = 1;
	} else if ($taxZone['countyId']==$config['taxCounty']) {
		// tax customer
		$taxCustomer = 1;
	}
}

// start: Flexible Taxes, by Estelle Winterflood
if ($config_tax_mod['status']) {
	// get specific entries for this state, and also entries for this whole country (ie. county_id=0)
	$query = "SELECT d.name AS name, taxName AS type_name, type_id, country_id, county_id, abbrev, tax_percent, goods, shipping, display FROM ".$glob['dbprefix']."CubeCart_taxes AS t, ".$glob['dbprefix']."CubeCart_tax_rates AS r LEFT JOIN ".$glob['dbprefix']."CubeCart_tax_details AS d ON r.details_id=d.id LEFT JOIN ".$glob['dbprefix']."CubeCart_iso_counties AS c ON c.id=county_id WHERE r.type_id=t.id AND d.status='1' AND r.active='1' AND country_id='".$taxZone['countryId']."' AND (county_id='0' OR (county_id = '".$taxZone['countyId']."'))";

	// "Testing" mode info display
	if ($config_tax_mod['debug']) {
		echo "<div style=\"border: 1px solid grey; background: white; text: black; margin-bottom: 1em; padding: 0.5em 1em; font-family: verdana; font-size: 11px;\">";
		echo "<p>This information is being printed because the taxes is in "Testing Configuration" mode.<br/>Please use this information to ensure you have your taxes configured correctly, then set the Flexible Taxes mod to "Live Store" mode.</p>";
		echo "<p><strong>Customer Delivery Location:</strong><br/>";
		if (empty($basket['delInf']['county'])) {
			$state_id = "n/a";
		} else {
			$state_id = $taxZone['countyId'];
		}
		echo "Country id [".$taxZone['countryId']."] State/County/Zone ID [".$state_id."]</p>";
	}

	$taxes_config = $db->select($query);

	$taxes = array();

	// is there any possibility of taxing this delivery address?
	if (is_array($taxes_config)){
		if ($config_tax_mod['debug'])
			echo "<p><strong>Taxes which affect this customer:</strong><br/>";

		for ($i=0; $i<count($taxes_config); $i++){
			$tax_config = $taxes_config[$i];

			// "Testing" mode info display
			if ($config_tax_mod['debug']) {
				if ($tax_config['abbrev']=="") {
					$state_abbrev = "--all--";
				} else {
					$state_abbrev = $tax_config['abbrev'];
				}
				echo "Tax [".$tax_config['name']."] Class [".$tax_config['type_name']."] Country ID [".$tax_config['country_id']."] State/County/Zone [".$state_abbrev."] Rate [".number_format($tax_config['tax_percent'],2)." %]<br/>";
			}

			// Prepare array to hold tax name/display/amount
			// The tax_config array may contain multiple occurances
			// of the same tax if there are multiple tax classes
			$setup = FALSE;
			for ($j=0; $j<count($taxes); $j++){
				if ($taxes[$j]['name'] == $tax_config['name'])
					$setup = true;
			}
			if (!$setup){
				$idx = count($taxes);
				$taxes[$idx]['name'] = $tax_config['name'];
				$taxes[$idx]['display'] = $tax_config['display'].":";
				$taxes[$idx]['amount'] = 0;
			}
		}

		$taxCustomer = 1;

		if ($config_tax_mod['debug'])
			echo "</p>";
	}
	// "Testing" mode info display
	elseif ($config_tax_mod['debug']) {
		echo "<p><strong>No taxes active/enabled for this location.</strong></p>";
	}
}

// end: Flexible Taxes

$totalWeight	= "";
$i				= 0;
$subTotal		= 0;
$shipCost		= 0;
$grandTotal		= 0;
$discount		= 0;

##########################
## START PRODUCTS LOOP  ##
##########################

## Start discounts
if ($basket['discount_percent']>0) {
	$discount_percent	= $basket['discount_percent'];

} else if ($basket['discount_price']>0) {
	$discount_remainder = $basket['discount_price'];
}

foreach($basket['conts'] as $key => $value){

	$i++;
	$linePrice		= 0;	// line price for basket
	$optionsCost	= 0;	// product options cost
	$plainOpts		= '';	// options as plain text


	// fetch shipping by category module
	$module = fetchDbConfig("Per_Category");
	$shipByCat = $module['status'];

	$extraJoin = "";

	if ($shipByCat==1) {
		$extraJoin = "INNER JOIN ".$glob['dbprefix']."CubeCart_category AS C ON I.cat_id = C.cat_id";
	}

	## Check for custom basket data e.g Gift Certificates
	if ($basket['conts'][$key]['custom'] == 1) {

		$gc = fetchDbConfig('gift_certs');

		$product[0]['productId']	= 0;
		$product[0]['productCode']	= $gc['productCode'];
		$product[0]['quantity']		= $basket['conts'][$key]['quantity'];
		$product[0]['price']		= $basket['conts'][$key]['gcInfo']['amount'];
		$product[0]['name']			= $lang['cart']['gift_cert'];
		$product[0]['image']		= $GLOBALS['rootRel'].'images/general/giftcert.gif';
		$product[0]['cat_id']		= 0;
		$product[0]['sale_price']	= 0;
		$product[0]['stock_level']	= 0;
		$product[0]['useStockLevel']= 0;
		$product[0]['digital']		= (strtolower($basket['conts'][$key]['gcInfo']['delivery']) == 'm') ? false : true;
		$product[0]['prodWeight']	= ($gc['delivery']=="e") ? 0 : $gc['weight'];
		$product[0]['taxType']		= $gc['taxType'];
		$product[0]['tax_inclusive']= ($gc['tax']) ? true : false;
		$product[0]['giftCert']		= true;

		// START PSEUDO PRODUCT OPTS
		$view_cart->assign("VAL_OPT_NAME",$lang['cart']['gift_cert_recip_name']);
		$view_cart->assign("VAL_OPT_VALUE",$basket['conts'][$key]['gcInfo']['recipName']);

		$plainOpts .= $lang['cart']['gift_cert_recip_name']." - ".$basket['conts'][$key]['gcInfo']['recipName']."\r\n";
		$view_cart->parse("view_cart.cart_true.repeat_cart_contents.options");

		$view_cart->assign("VAL_OPT_NAME",$lang['cart']['gift_cert_recip_email']);
		$view_cart->assign("VAL_OPT_VALUE",$basket['conts'][$key]['gcInfo']['recipEmail']);

		$plainOpts .= $lang['cart']['gift_cert_recip_email']." - ".$basket['conts'][$key]['gcInfo']['recipEmail']."\r\n";
		$view_cart->parse("view_cart.cart_true.repeat_cart_contents.options");

		$view_cart->assign("VAL_OPT_NAME",$lang['cart']['gift_cert_recip_message']);

		$gcMessage = $basket['conts'][$key]['gcInfo']['message'];

		if (strlen($gcMessage) > 30) $gcMessage = substr($gcMessage, 0, 30).'…';

		$view_cart->assign("VAL_OPT_VALUE", $gcMessage);

		$plainOpts .= $lang['cart']['gift_cert_recip_message']." - ".$basket['conts'][$key]['gcInfo']['message']."\r\n";
		$view_cart->parse("view_cart.cart_true.repeat_cart_contents.options");

		$view_cart->assign("VAL_OPT_NAME",$lang['cart']['gift_cert_delivery']);
		$view_cart->assign("VAL_OPT_VALUE",$lang['cart']['delivery_method_'.$basket['conts'][$key]['gcInfo']['delivery']]);

		$plainOpts .= $lang['cart']['gift_cert_delivery']." - ".$lang['cart']['delivery_method_'.$basket['conts'][$key]['gcInfo']['delivery']]."\r\n";
		$view_cart->parse("view_cart.cart_true.repeat_cart_contents.options");

		// END PSEUDO PRODUCT OPTS
	} else {

		$productId	= $cart->getProductId($key);
		$product	= $db->select("SELECT * FROM ".$glob['dbprefix']."CubeCart_inventory AS I INNER JOIN ".$glob['dbprefix']."CubeCart_taxes AS T ON T.id = taxType ".$extraJoin." WHERE I.productId=".$db->mySQLSafe($productId));

		// FIX FOR DELETED TAX BANDS PRE 3.0.5
		if (!$product) {
			$product = $db->select("SELECT * FROM ".$glob['dbprefix']."CubeCart_inventory WHERE productId=".$db->mySQLSafe($productId));
			$product[0]['percent'] = 0;
		}
		if (($val = prodAltLang($product[0]['productId'])) == TRUE) {
			$product[0]['name'] = $val['name'];
		}
	}

	$view_cart->assign("TD_CART_CLASS",cellColor($i, 'tdcartEven', 'tdcartOdd'));
	$view_cart->assign("VAL_PRODUCT_ID",$productId);
	$view_cart->assign("VAL_CURRENT_STEP",$_GET['_a']);
	$view_cart->assign("VAL_PRODUCT_KEY", md5($key));

	if ($product[0]['giftCert'] === true) {
		$view_cart->assign('VAL_IMG_SRC', imgPath($product[0]['image'], false, ''));
	} else {
		if (file_exists(imgPath($product[0]['image'], true, 'root')) && !empty($product[0]['image'])) {
			$view_cart->assign('VAL_IMG_SRC', imgPath($product[0]["image"], true, 'rel'));
		} else {
			$view_cart->assign('VAL_IMG_SRC', 'skins/'. SKIN_FOLDER . '/styleImages/thumb_nophoto.gif');
		}
	}

	## Only calculate shipping IF the product is tangible
	if (!$product[0]['digital']) {
		$orderTangible = true;
	}

	$view_cart->assign("VAL_PRODUCT_NAME", validHTML($product[0]["name"]));
	$view_cart->assign("VAL_PRODUCT_CODE", $product[0]["productCode"]);  


 

 

CONTINUES BELOW:

 

Link to comment
Share on other sites

## Build the product options
	$optionKeys = $cart->getOptions($key);

	if (!empty($optionKeys)) {
		$options = explode('|', $optionKeys);

		foreach ($options as $value) {
			## Split on separator
			$value_data		= explode('@', $value);
			## Get Option Data
			$option_name	= false;
			$option_value	= false;
			$option_top		= $db->select(sprintf("SELECT T.* FROM %1\$sCubeCart_options_top AS T WHERE T.option_id = %2\$s", $glob['dbprefix'], $value_data[0]));
			if ($option_top) {
				$option_name	= $option_top[0]['option_name'];
				if ($option_top[0]['option_type'] == 0) {
					$option		= $db->select(sprintf("SELECT M.*, B.* FROM %1\$sCubeCart_options_mid AS M, %1\$sCubeCart_options_bot AS B WHERE M.value_id = B.value_id AND B.assign_id = %2\$d", $glob['dbprefix'], $value_data[1]));
					if ($option) {
						$option_price	= $option[0]['option_price'];
						$option_symbol	= $option[0]['option_symbol'];
						$option_value	= $option[0]['value_name'];
					}
				} else {
					$option			= $db->select(sprintf("SELECT B.* FROM %1\$sCubeCart_options_bot AS B WHERE B.option_id = %2\$d AND B.product = %3\$d LIMIT 1", $glob['dbprefix'], $value_data[0], $productId));	
					if ($option) {
						$option_price	= $option[0]['option_price'];
						$option_symbol	= $option[0]['option_symbol'];
						$option_value	= $value_data[1];
					}
				}
			}
			if (!empty($option_value) && !empty($option_name)) {
				## Assign values
				$view_cart->assign('VAL_OPT_NAME', validHTML($option_name));
				$view_cart->assign('VAL_OPT_VALUE', htmlentities(strip_tags($option_value), ENT_QUOTES, 'UTF-8'));

				$plainOpts .= $option_name.' - '.$option_value."\r\n";

				if ($option_price > 0) {
					if ($option_symbol == "+") {
						$optionsCost = $optionsCost + $option_price;
					} else if ($option_symbol == "-") {
						$optionsCost = $optionsCost - $option_price;
					} else if ($option_symbol == "~") {
						$optionsCost = 0;
					}
				}
				$view_cart->parse('view_cart.cart_true.repeat_cart_contents.options');
			}
		}
	}

	if ($product[0]['useStockLevel'] && $config['stockLevel']){
		$view_cart->assign('VAL_INSTOCK', $product[0]['stock_level']);
	} else {
		$view_cart->assign('VAL_INSTOCK', '∞');
	}

	if (($config['outofstockPurchase']) && ($product[0]["stock_level"]<$cart->cartArray['conts'][$key]["quantity"]) && ($product[0]['useStockLevel'])) {
		$view_cart->assign("VAL_STOCK_WARN",$lang['cart']['stock_warn']);

		$quantity = $cart->cartArray['conts'][$key]["quantity"];
		$view_cart->parse("view_cart.repeat_cart_contents.stock_warn");

	} else if ((!$config['outofstockPurchase']) && ($product[0]["stock_level"]<$cart->cartArray['conts'][$key]["quantity"]) && ($product[0]['useStockLevel'])) {

		$view_cart->assign("VAL_STOCK_WARN",$lang['cart']['amount_capped']." ".$product[0]["stock_level"].".");
		$quantity = $product[0]["stock_level"];
		$basket = $cart->update($key, $quantity);
		$view_cart->parse("view_cart.cart_true.repeat_cart_contents.stock_warn");
	} else {
		$quantity = $cart->cartArray['conts'][$key]["quantity"];
	}
	$view_cart->assign("VAL_QUANTITY", $quantity);

	if ($basket['conts'][$key]['custom']==1 || !salePrice($product[0]['price'], $product[0]['sale_price'])) {
		$price = $product[0]['price'];
	} else {
		$price = salePrice($product[0]['price'], $product[0]['sale_price']);
	}

	$price = ($price+$optionsCost < 0) ? 0 : $price+($optionsCost);

	if (!$basket['conts'][$key]['custom']) {
		$altCheckoutInv[$i]['taxType']	= $product[0]['taxType'];
		$altCheckoutInv[$i]['name']		= $product[0]['name'];
		$altCheckoutInv[$i]['options']	= $plainOpts;
		$altCheckoutInv[$i]['quantity'] = $quantity;

		if($product[0]['tax_inclusive'] == true) {
			$altCheckoutInv[$i]['price'] = sprintf("%.2f",$price / (($product[0]['percent'] / 100) +1));
			$altCheckoutInv[$i]['priceIncTax']	= sprintf("%.2f",$price);
		} else {
			$altCheckoutInv[$i]['price']	= sprintf("%.2f",$price);
		}

		## Private data 
		$altCheckoutInv[$i]['private_data']['digital']		= $product[0]['digital'];
		$altCheckoutInv[$i]['private_data']['productcode']	= $product[0]['productCode'];
		$altCheckoutInv[$i]['private_data']['productid']	= $productId;
	} else {
		## Alternative checkout can only be used for tangible goods right now
		$customWarn = true;
	}

	$linePrice = $price * $quantity;

	// set live vars for order inv and its the last step
	$basket = $cart->setVar($productId,"productId","invArray",$i);
	$basket = $cart->setVar($product[0]['name'],"name","invArray",$i);
	$basket = $cart->setVar($product[0]['productCode'],"productCode","invArray",$i);
	$basket = $cart->setVar($plainOpts, "prodOptions", "invArray", $i);
	$basket = $cart->setVar(sprintf("%.2f",$linePrice),"price","invArray",$i);
	$basket = $cart->setVar($quantity,"quantity","invArray",$i);
	$basket = $cart->setVar($product[0]['digital'],"digital","invArray",$i);

	if ($basket['conts'][$key]['custom'] == 1) {
		$basket = $cart->setVar(serialize($basket['conts'][$key]['gcInfo']),"custom","invArray",$i);
		$view_cart->parse("view_cart.cart_true.repeat_cart_contents.quanDisabled");
	} else {
		$view_cart->parse("view_cart.cart_true.repeat_cart_contents.quanEnabled");
	}

	$view_cart->assign("VAL_IND_PRICE", priceFormat($price, true));
	$view_cart->assign("VAL_LINE_PRICE", priceFormat($linePrice, true));

	if ($shipByCat) {
		## Calculate the line category shipping price
		require CC_ROOT_DIR.CC_DS."modules".CC_DS."shipping".CC_DS."Per_Category".CC_DS."line.inc.php";
	}

	## Apply discounts
	$itemDiscount = 0;
	if (isset($discount_percent) && $discount_percent > 0 && !$product[0]['giftCert']) {
		## Percentile discounts
		$itemDiscount	= $linePrice*($discount_percent/100);
		$totalDiscount	+= $linePrice*($discount_percent/100);

	} else if (isset($discount_remainder) && $discount_remainder > 0 && !$product[0]['giftCert']) {
		## Fixed value discounts
		if ($discount_remainder <= $linePrice) {
			$discount			= $discount_remainder;
			$discount_remainder	= 0;
		} else if ($discount_remainder > $linePrice) {
			$discount			= $linePrice;
			$discount_remainder = $discount_remainder - $discount;
		}

		if ($discount > 0) {
			$totalDiscount	+= $discount;
			$itemDiscount	= $discount;
			$discount		= 0;
		}
	}
	$linePrice -= $itemDiscount;

	## Calculate weight
	//if ($product[0]['prodWeight']>0 && !$product[0]['digital']) {
	if ($product[0]['prodWeight']>0) {
		$totalWeight = ($product[0]['prodWeight'] * $quantity) + $totalWeight;
		$totalcubicWeight = ($product[0]['cubicWeight'] * $quantity) + $totalcubicWeight;
	}

	## Calculate tax
	if ($taxCustomer) {
		// start: Flexible Taxes, by Estelle Winterflood
		// calculate Tax on Goods
		if ($config_tax_mod['status']) {
			for ($j=0; is_array($taxes_config) && $j<count($taxes_config); $j++) {
				$tax_config = $taxes_config[$j];
				if ($tax_config['type_id'] == $product[0]['taxType']) {
					// tax on goods
					if ($tax_config['goods']) {

						$lineTax = getTax($linePrice, ($product[0]['tax_inclusive']) ? false : true, $tax_config['tax_percent']);

						for ($k=0; $k<count($taxes); $k++){
							if ($taxes[$k]['name'] == $tax_config['name']){
								// "Testing" mode info display
								if ($config_tax_mod['debug']) {
									if (!isset($debug)) $debug = '';
									$debug .= "Item ".$i." [".$product[0]['name']."] [".$product[0]['taxName']."] [".$quantity." x ".priceFormat($price, true)."] --- Tax [".$taxes[$k]['name']."] [".$tax_config['type_name']."] [".number_format($tax_config['tax_percent'],2)." %] --- ".priceFormat($lineTax,TRUE)."<br/>";
								}
								$taxes[$k]['amount'] += $lineTax;
							}
						}
					}
				}
			}
			## end: Flexible Taxes
		} else if (!$config['priceIncTax']) {
			$tax += getTax($linePrice, ($product[0]['tax_inclusive']) ? false : true, $product[0]['percent']);
		}
	}
	$subTotal += $linePrice;
	$view_cart->parse("view_cart.cart_true.repeat_cart_contents");
}

## Deduct the total discount from the subtotal - Fixes bug report #705
//$subTotal -= $totalDiscount;

## Work out discount on price if any - OLD CODE, left for reference
/*
if ($basket['discount_percent']>0) {
	if ($basket['discount_percent'] > 100) $basket['discount_percent'] = 100;
	$totalDiscount	= ($basket['discount_percent']/100) * $subTotal;
	$subTotal		= $subTotal - $totalDiscount;

} else if ($basket['discount_price']>0) {
	if (isset($discountRemainder) && $discountRemainder>0) { 
		$lineDiscount = $discountRemainder; 
	} else if (!isset($discountRemainder)) { 
		$lineDiscount = $basket['discount_price']; 
	}
	if ($lineDiscount<$linePrice) {
		$discount = $lineDiscount;
	} else {
		$discount = $linePrice;
		$discountRemainder = $lineDiscount - $discount;
	}

	$totalDiscount	= $discount;
	$subTotal -= $totalDiscount;

} else {
	$discount = 0;
}
*/

// start: Flexible Taxes, by Estelle Winterflood
if ($config_tax_mod['status'] && is_array($taxes_config)){
	if ($config_tax_mod['debug'])
		echo "<p><strong>Tax applied to goods:</strong><br/>".$debug."</p>";
}
// end: Flexible Taxes

	/* start mod: Shipping Estimates - http://cubecart.expandingbrain.com */
$se_mod = fetchDbConfig("Shipping_Estimates");
if ($se_mod && $se_mod['status_cc4']) {
	$se_template_parse = "view_cart.cart_true.shipping_estimates";
	include 'modules'.CC_DS.'3rdparty'.CC_DS.'Shipping_Estimates'.CC_DS.'cart1.inc.php';
}

/* calculate shipping */
/*if ($_GET['_a'] == 'step2' && $orderTangible) {*/
if ($se_mod && $se_mod['status_cc4'] && $_GET['_a'] == 'cart' && $orderTangible && !isset($basket['delInf']) && $se_mod['postcode']) {

	$shippingPrice = $lang['cart']['se_enter_location'];
	$shippingPrice = '<select class="textbox" style="width: 150px" id="shipping-select"><option>'.$shippingPrice.'</option></select>';

} else if ((($se_mod['status_cc4'] && isset($basket['delInf'])) || $_GET['_a'] == 'step2') && $orderTangible) {
/* end mod: Shipping Estimates - by Estelle */

	$shippingModules = $db->select("SELECT DISTINCT `folder` FROM ".$glob['dbprefix']."CubeCart_Modules WHERE module='shipping' AND status = 1");

	$noItems 	= $cart->noItems();
	$sum		= 0;

	if (is_array($shippingModules) && !empty($shippingModules)) {
		// if selected key has not been set, set it
		if (!isset($basket['shipKey'])) $basket = $cart->setVar(1, 'shipKey');

		foreach ($shippingModules as $shippingModule) {
			$shippingCalcPath = 'modules'.CC_DS.'shipping'.CC_DS.$shippingModule['folder'].CC_DS.'calc.php';
			if (file_exists($shippingCalcPath)) {
				include($shippingCalcPath);
			}
		}

		#:convict:# Shipping cost from lowest to highest >>
		$Shipping = array();
		foreach ($shipArray as $shipMethod) {
			if (!empty($shipMethod) && is_array($shipMethod)) {
				foreach ($shipMethod as $shipDetails) {
					$Shipping[] = $shipDetails;
				}
			}
		}
		function cmp($a, $b) { $b=floatval($b['value']); $a=floatval($a['value']); return $a<$b ? -1 : ($a>$b ? 1 : 0); }
		usort($Shipping, "cmp");
		$shipKey = 0;
		foreach ($Shipping as $shipDetails) {
			$shipKey++;
			if ($shipKey == $basket['shipKey']) {
				$selected = ' selected="selected"';

				$basket = $cart->setVar($shipDetails['method'], 'shipMethod');
				$basket = $cart->setVar(sprintf("%.2f", $shipDetails['value']), 'shipCost');

				$shippingTaxId		= $shipDetails['taxId'];
				$shippingTaxAmount	= $shipDetails['taxAmount'];
			} else {
				$selected = '';
			}
			$shippingPrice[] = '<option value="'.$shipKey.'"'.$selected.'>'.$shipDetails['desc'].'</option>';
		}

		if (is_array($shippingPrice)) {
			$shippingPrice = '<select class="textbox" style="width: 150px" id="shipping-select" name="shipKey" onchange="submitDoc(\'cart\');">'.implode("\n", $shippingPrice).'</select>';
		}
		/* start mod: Shipping Estimates - http://cubecart.expandingbrain.com */
		if ($se_mod && $se_mod['status_cc4'] && $_GET['_a'] == 'cart') {
			$basket = $cart->unsetVar("delInf");
		}
		if ($se_mod && $se_mod['status_cc4'] && $_GET['_a'] == 'cart' && empty($shippingPrice)) {
			$shippingPrice = $lang['cart']['se_not_available'];
			$shippingPrice = '<select class="textbox" style="width: 150px" id="shipping-select"><option>'.$shippingPrice.'</option></select>';
			$shipKey = 1;  /* pretend there are shipping options to allow view cart */
		}
		if (!$shipKey && !empty($_GET['editDel'])) {
			$shipKey = 1;  /* pretend there are shipping options to allow address edit */
		}
		/* end mod: Shipping Estimates - by Estelle */


		## if no shipping method is available go to error page
		if (!$shipKey) httpredir('index.php?_g=co&_a=error&code=10001');

		## if shipping key is greater than those available set to 1, and redirect
		if ($basket['shipKey']>$shipKey) {
			$cart->setVar(1, 'shipKey');
			$basket = $cart->setVar(0.00, 'shipCost');
		/* start mod: Shipping Estimates - http://cubecart.expandingbrain.com */
		/*httpredir('index.php?_g=co&_a=step2') or die('help');*/
		httpredir('index.php?_g=co&_a=cart') or die('help');
		/* end mod: Shipping Estimates - by Estelle */

		}

	} else {
		$shippingPrice .= priceFormat(0, true);
		$basket = $cart->setVar($lang['cart']['free_shipping'], 'shipMethod');
		$basket = $cart->setVar(0.00, 'shipCost');
	}
} else {
	$shippingPrice = $lang['cart']['na'];
	## set shipping cost to 0.00 just incase
		$basket = $cart->setVar(0.00, 'shipCost');
}



## If the voucher is a gift certificate, we'll let them use it to discount shipping
if ($basket['code_is_purchased'] && $totalDiscount < $basket['discount_price']) {
	$shippingCost = (is_numeric($shippingPrice)) ? $shippingPrice : $basket['shipCost'];

	if ($discount_remainder <= $basket['shipCost']) {
		$shippingCost	-= $discount_remainder;
		$totalDiscount	= $basket['discount_price'];
		$basket			= $cart->setVar(sprintf('%.2f', $shippingCost), 'shipCost');

	} else if ($discount_remainder > $basket['shipCost']) {
		$totalDiscount += $basket['shipCost'];
		$basket			= $cart->setVar(0.00, 'shipCost');
	}
}

// start: Flexible Taxes, by Estelle Winterflood
// calculate tax on shipping
if ($config_tax_mod['status'] && $taxCustomer) {

	if ($config_tax_mod['debug'] && is_array($taxes_config))
		echo "<p><strong>Tax applied to shipping & handling:</strong><br/>";

	for ($i=0; is_array($taxes_config) && $i<count($taxes_config); $i++){
		$tax_config = $taxes_config[$i];
		if ($tax_config['type_id'] == $shippingTaxId){
			// tax on shipping

			if ($tax_config['shipping']) {

				$lineTax = getTax($basket['shipCost'], true, $tax_config['tax_percent']);
				for ($j=0; $j<count($taxes); $j++){
					if ($taxes[$j]['name'] == $tax_config['name']){
						// "Testing" mode info display
						if ($config_tax_mod['debug']) {
							echo "Method [".$folder."] [".$tax_config['type_name']."] [".priceFormat($basket['shipCost'], true)."] --- Tax [".$taxes[$j]['name']."] [".$tax_config['type_name']."] [".number_format($tax_config['tax_percent'],2)." %] --- ".priceFormat($lineTax,TRUE)."<br />";
						}
						$taxes[$j]['amount'] += $lineTax;
					}
				}
			}
		}
	}
	if ($config_tax_mod['debug'] && is_array($taxes_config))

	echo "</p>";
}

## claculate basic tax on shipping
elseif($taxCustomer==1){
	$tax += $shippingTaxAmount;
}
if ($config_tax_mod['status']){
	## "Testing" mode info display
	if ($config_tax_mod['debug']) {
		echo "</div>";
	}
}
## end: Flexible Taxes

$view_cart->assign("LANG_SHIPPING", $lang['cart']['shipping']);

$view_cart->assign("VAL_SHIPPING", $shippingPrice);

// start: Flexible Taxes, by Estelle Winterflood
// display taxes
if ($config_tax_mod['status']){
	if (count($taxes)==0){
		$view_cart->assign("LANG_TAX",$lang['cart']['tax']);
		$view_cart->assign("VAL_TAX",$lang['cart']['na']);
	} else {
		// any additional taxes
		for ($i=1; $i<count($taxes); $i++) {
			$view_cart->assign("LANG_TAX",$taxes[$i]['display']);
			$view_cart->assign("VAL_TAX",priceFormat($taxes[$i]['amount'],TRUE));
			$view_cart->parse("view_cart.cart_true.repeat_more_taxes");
		}

		// first tax
		$view_cart->assign("LANG_TAX",$taxes[0]['display']);
		$view_cart->assign("VAL_TAX",priceFormat($taxes[0]['amount'],TRUE));
	}

	// tax registration number(s)
	$reg_number = $db->select("SELECT reg_number FROM ".$glob['dbprefix']."CubeCart_tax_details;");
	$reg_string = "";
	for ($i=0; is_array($reg_number) && $i<count($reg_number); $i++) {
		if (strlen($reg_string) && $reg_number[$i]['reg_number']!="") 
		{
			$reg_string .= "<br/>";
		}
		$reg_string .= $reg_number[$i]['reg_number'];
	}
	$view_cart->assign("VAL_TAX_REG",$reg_string);
	// end: Flexible Taxes
} else {
	$view_cart->assign("LANG_TAX",$lang['cart']['tax']);
	if($tax>0) {
		$view_cart->assign("VAL_TAX",priceFormat($tax,TRUE));
	} else {
		$view_cart->assign("VAL_TAX",$lang['cart']['na']);
	}
}

## Work out if the Gift Certificate has any discount left
if ($basket['code_is_purchased'] == true && $totalDiscount <= $basket['discount_price']) {
	$couponRemainder = $basket['discount_price'] - $totalDiscount;
	$basket	= $cart->setVar(sprintf("%.2f", $couponRemainder),"code_remainder");

	## Update coupon so that it can be used again with remainder, if there is any	
	if ($couponRemainder > 0) {
		$giftRecord['discount_price'] = $db->mySQLSafe(sprintf("%.2f", $couponRemainder));
	} else {
		$giftRecord = array(
			'discount_price'	=> 0,
			'allowed_uses'		=> 0,
			'count'				=> 1,
		);
	}
	$basket	= $cart->setVar(sprintf("%.2f",$couponRemainder),"code_remainder");

	$where	= 'code = '.$db->mySQLSafe($basket['code']);
	$update	= $db->update($glob['dbprefix'].'CubeCart_Coupons', $giftRecord, $where);
}

$basket = $cart->setVar($totalDiscount, "discount");
$view_cart->assign("LANG_DISCOUNT",$lang['cart']['discount']);
// set discount to return value if null
if(empty($basket['discount']) || !isset($basket['discount'])) { 
	$basket['discount'] = 0; 
} 
$view_cart->assign("VAL_DISCOUNT", priceFormat($basket['discount'], true));

$view_cart->assign("LANG_SUBTOTAL", $lang['cart']['subtotal']);
$view_cart->assign("VAL_SUBTOTAL", priceFormat($subTotal, true));

if($totalWeight>0){
	$view_cart->assign("LANG_BASKET_WEIGHT",$lang['cart']['basket_weight']);
	$view_cart->assign("VAL_BASKET_WEIGHT",$totalWeight.$config['weightUnit']);
	$view_cart->assign("VAL_BASKET_CUBICWEIGHT",$totalcubicWeight.$config['weightUnit']);
}

// start: Flexible Taxes, by Estelle Winterflood
// grand total
if ($config_tax_mod['status']) {
	$tax = 0;
	for ($i=0; is_array($taxes) && $i<count($taxes); $i++) {
		$tax += $taxes[$i]['amount'];
	}
	$grandTotal = $subTotal + $tax + $basket['shipCost'];
}
// end: Flexible Taxes
else {
	$grandTotal = $subTotal + $tax + $basket['shipCost'];
}


$view_cart->assign("LANG_CART_TOTAL",$lang['cart']['cart_total']);
$view_cart->assign("VAL_CART_TOTAL",priceFormat($grandTotal, true));

if (isset($basket['codeResult'])) {
	if (!$basket['codeResult']) {
		# add remove link
		$view_cart->assign("LANG_CODE_REMOVE",$lang['cart']['coupon_remove']);
		$view_cart->assign("VAL_OLD_CODE",base64_encode($basket['code']));
		$view_cart->assign("VAL_CURRENT_PAGE",currentPage());
		$view_cart->parse("view_cart.cart_true.coupon_code_result.remove");
	}
	$view_cart->assign("LANG_CODE_RESULT",$lang['cart']['coupon_result_'.$basket['codeResult']]);
	$view_cart->parse("view_cart.cart_true.coupon_code_result");

}

if (!isset($basket['codeResult']) || $basket['codeResult']>0) {
	$view_cart->assign("LANG_GOT_CODE", $lang['cart']['got_code']);
	$view_cart->assign("LANG_ENTER_CODE", $lang['cart']['enter_code']);
	$view_cart->parse("view_cart.cart_true.enter_coupon_code");
	$basket = $cart->unsetVar("codeResult");
}

// build array of price vars in session data
$basket = $cart->setVar(sprintf("%.2f",$subTotal),"subTotal");
$basket = $cart->setVar(sprintf("%.2f",$tax),"tax");
$basket = $cart->setVar(sprintf("%.2f",$grandTotal),"grandTotal");
// start: Flexible Taxes, by Estelle Winterflood
// leave "tax" in session data as the total tax
// define a new array to hold the individual tax names/amounts
if ($config_tax_mod['status']) {
	for ($i=1; $i<=count($taxes); $i++) {
		$basket = $cart->setVar($taxes[$i-1]['display'],'tax'.$i.'_disp');
		$basket = $cart->setVar(sprintf("%.2f",$taxes[$i-1]['amount']),'tax'.$i.'_amt');
	}

}
// end: Flexible Taxes	

$view_cart->assign("LANG_UPDATE_CART_DESC",$lang['cart']['if_changed_quan']);

$view_cart->assign("LANG_UPDATE_CART",$lang['cart']['update_cart']);

$view_cart->assign("LANG_CHECKOUT",$lang['cart']['checkout']);
// see if passports are enabled
$altCheckout = $db->select("SELECT `folder`, `default` FROM `".$glob['dbprefix']."CubeCart_Modules` WHERE `module`='altCheckout' AND `status` = 1");

// stop alt checkout if they have aleady chosen PayPal... mission	
if($grandTotal>0 && !isset($_SESSION['token']) && !isset($_SESSION['payer_id']) && $altCheckout) {

	$noAltCheckouts = count($altCheckout);

	if($noAltCheckouts == 1 && $altCheckout[0]['folder']=="PayPal_Pro") { unset($customWarn); }

	if ($customWarn) {
		$view_cart->assign("LANG_CUSTOM_WARN",$lang['cart']['custom_warn']);
		$view_cart->parse("view_cart.cart_true.alt_checkout.custom_warn");	
	}
	$view_cart->assign("LANG_ALTERNATIVE_CHECKOUT",$lang['cart']['alternative']);

	## Get alt checkout shipping
	$query = "SELECT `name`, `byprice`, `low`, `high`, `price` FROM ".$glob['dbprefix']."CubeCart_alt_shipping a LEFT JOIN ".$glob['dbprefix']."CubeCart_alt_shipping_prices b ON a.id = b.alt_ship_id ORDER BY `order`, `low`, `high` ASC";
	$altShipping = $db->select($query);

	if ($altShipping) {
		$n=0;
		for($i=0;$i<count($altShipping);$i++) {
			if($altShipping[$i]['byprice']==1 && $subTotal>=$altShipping[$i]['low'] && $subTotal<=$altShipping[$i]['high']){
				$altShippingPrices[$n]['name'] = $altShipping[$i]['name'];
				$altShippingPrices[$n]['price'] = $altShipping[$i]['price'];
				$n++;
			} elseif($altShipping[$i]['byprice']==0 && $totalWeight>=$altShipping[$i]['low'] && $totalWeight<=$altShipping[$i]['high']) {
				$altShippingPrices[$n]['name'] = $altShipping[$i]['name'];
				$altShippingPrices[$n]['price'] = $altShipping[$i]['price'];
				$n++;
			}
		}
	}

	if (!isset($customWarn) || $customWarn != true) {
		## build checkout buttons
		for ($i=0;$i<count($altCheckout);$i++) {
			require("modules".CC_DS."altCheckout".CC_DS.$altCheckout[$i]['folder'].CC_DS."button.php");
			## get module config
			$altCheckoutConf = fetchDbConfig($altCheckout[$i]['folder']);
			if($altCheckoutConf['mode']!=="USDPO") {
				## Run class and functions
				$altCheckoutButton = new $altCheckout[$i]['folder']();
				$buttonCode = $altCheckoutButton->buildIt($altCheckout[$i]['folder']);
				$view_cart->assign("IMG_CHECKOUT_ALT",$buttonCode);
				$view_cart->parse("view_cart.cart_true.alt_checkout.loop_button");
				## set include path right again - this fixes things, for some reason
				ini_set('include_path', ini_get('include_path').CC_PS.CC_ROOT_DIR);
			}
		}
	}
	$view_cart->parse("view_cart.cart_true.alt_checkout");	
}
$view_cart->assign("VAL_FORM_ACTION", currentPage());
$view_cart->parse("view_cart.cart_true");
} else {

$view_cart->assign("CONT_VAL","index.php?_g=co&_a=step1");
$view_cart->assign("LANG_CHECKOUT_BTN",$lang['cart']['checkout_btn']);
$view_cart->assign("LANG_VIEW_CART",$lang['cart']['view_cart']);
$view_cart->assign("CLASS_CART","class='txtcartProgressCurrent'");
$view_cart->assign("CLASS_STEP2","");

$view_cart->assign("LANG_CART_EMPTY", $lang['cart']['cart_empty']);
$view_cart->parse("view_cart.cart_false");

} 
$view_cart->parse("view_cart");
$page_content = $view_cart->text("view_cart");
?>

 

 

UPS.PHP

 

<?php
/*

Copyright (c) 2000, Jason Costomiris
All rights reserved.

Props to shawnblue@radiotakeover.com for the original idea which I have cannibalized herein.  You go boy.

Don't be scared, it's just a BSD-ish license.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by Jason Costomiris.
4. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/


  class Ups {

    function upsProduct($prod){
       /*

     1DM == Next Day Air Early AM
     1DA == Next Day Air
     1DP == Next Day Air Saver
     2DM == 2nd Day Air Early AM
     2DA == 2nd Day Air
     3DS == 3 Day Select
     GND == Ground
     STD == Canada Standard
     XPR == Worldwide Express
     XDM == Worldwide Express Plus
     XPD == Worldwide Expedited
      
    */
      $this->upsProductCode = $prod;
    }
    
    function origin($postal, $country){
      $this->originPostalCode = $postal;
      $this->originCountryCode = $country;
    }

    function dest($postal, $country){
      $this->destPostalCode = $postal;
          $this->destCountryCode = $country;
    }

    function rate($foo){
      switch(strtoupper($foo)){
        case "RDP":
          $this->rateCode = "Regular+Daily+Pickup";
          break;
        case "OCA":
          $this->rateCode = "On+Call+Air";
          break;
        case "OTP":
          $this->rateCode = "One+Time+Pickup";
          break;
        case "LC":
          $this->rateCode = "Letter+Center";
          break;
        case "CC":
          $this->rateCode = "Customer+Counter";
          break;
      }
    }

    function container($foo){
          switch(strtoupper($foo)){
        case "CP":            // Customer Packaging
          $this->containerCode = "00";
          break;
        case "ULE":        // UPS Letter Envelope
          $this->containerCode = "01";        
          break;
        case "UT":            // UPS Tube
          $this->containerCode = "03";
          break;
        case "UEB":            // UPS Express Box
          $this->containerCode = "21";
          break;
        case "UW25":        // UPS Worldwide 25 kilo
          $this->containerCode = "24";
          break;
        case "UW10":        // UPS Worldwide 10 kilo
          $this->containerCode = "25";
          break;
      }
    }
    
    function weight($foo){
      $this->packageWeight = $foo;
    }

    function rescom($foo){
          switch(strtoupper($foo)){
        case "RES":            // Residential Address
          $this->resComCode = "1";
          break;
        case "COM":            // Commercial Address
          $this->resComCode = "0";
          break;
          }
    }

function getQuote(){

	global $config;

	$upsAction = "3"; // You want 3.  Don't change unless you are sure.
	$url = join("&",
		array("http://www.ups.com/using/services/rave/qcostcgi.cgi?accept_UPS_license_agreement=yes",
			"10_action=$upsAction",
			"13_product=$this->upsProductCode",
			"14_origCountry=$this->originCountryCode",
			"15_origPostal=$this->originPostalCode",
			"19_destPostal=$this->destPostalCode",
			"22_destCountry=$this->destCountryCode",
			"23_weight=$this->packageWeight",
			"47_rate_chart=$this->rateCode",
			"48_container=$this->containerCode",
			"49_residential=$this->resComCode"
		)
	);

	if (function_exists('curl_init')) {

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		if($config['proxy']==1){
  			curl_setopt ($ch, CURLOPT_PROXY, $config['proxyHost'].":".$config['proxyPort']); 
  		}

		$data = curl_exec($ch);

		if (!empty($data)) {				
			$dataline = explode("\n", $data);
			foreach ($dataline as $result) {
				if (strstr($result, 'Origin postal code must have five digits')) {
					echo 'Origin postal code must have five digits to use UPS. Please update this in the module settings.';
					exit;
				} else if (strstr($result, 'Unsupported country specified')) {
					echo 'Unsupported country specified to use UPS. Please update this in the general settings.';
					exit;
				}
				$result = explode('%', $result);
				$errcode = substr($result[0], -1);
				switch($errcode){
					case 3:
						$returnval = $result[8];
						break;
					case 4:
						$returnval = $result[8];
						break;
					case 5:
						$returnval = $result[1];
						break;
					case 6:
						$returnval = $result[1];
						break;
				}
			}
		}
	} else {
		$fp = fopen($url, 'r');
		while(!feof($fp)) {
			$result = fgets($fp, 500);
			if (strstr($result, 'Origin postal code must have five digits')) {
				echo 'Origin postal code must have five digits to use UPS. Please update this in the module settings.';
				exit;
			} else if (strstr($result, 'Unsupported country specified')) {
				echo 'Unsupported country specified to use UPS. Please update this in the general settings.';
				exit;
			}
			$result = explode('%', $result);
			$errcode = substr($result[0], -1);
			switch($errcode){
				case 3:
					$returnval = $result[8];
					break;
				case 4:
					$returnval = $result[8];
					break;
				case 5:
					$returnval = $result[1];
					break;
				case 6:
					$returnval = $result[1];
					break;
			}
		}
		fclose($fp);
	}
	return (!$returnval) ? 'error' : $returnval;
}
}

?>

 

 

CALC.PHP

 

<?php
/*
+--------------------------------------------------------------------------
|   CubeCart 4
|   ========================================
|	CubeCart is a Trade Mark of Devellion Limited
|   Copyright Devellion Limited 2006. All rights reserved.
|   Devellion Limited,
|   5 Bridge Street,
|   Bishops Stortford,
|   HERTFORDSHIRE.
|   CM23 2JU
|   UNITED KINGDOM
|   http://www.devellion.com
|	UK Private Limited Company No. 5323904
|   ========================================
|   Web: http://www.cubecart.com
|   Email: info (at) cubecart (dot) com
|	License Type: CubeCart is NOT Open Source Software and Limitations Apply 
|   Licence Info: http://www.cubecart.com/site/faq/license.php
+--------------------------------------------------------------------------
|	calc.inc.php
|   ========================================
|	Calculate UPS Quotes
+--------------------------------------------------------------------------
*/
function UPS()
{
global $totalWeight,$basket,$config,$lang;

$moduleName = "UPS";

$module = fetchDbConfig($moduleName);

$taxVal = taxRate($module['tax']);

if ($module['status']) {
	require 'ups.php';
	$i=0;
	foreach ($module as $key => $value) {
		if (preg_match('#product#', $key) && $value) {
			$productCode = substr($key,7,3);

			$rate = new Ups;
			$rate->upsProduct($productCode);					# See upsProduct() function for codes
			$rate->origin($module['postcode'], getCountryFormat($config['siteCountry'],"id","iso"));				# Use ISO country codes!
			$rate->dest($basket['delInf']['postcode'], getCountryFormat($basket['delInf']['country'],"id","iso"));	# Use ISO country codes!
			if (!isset($module['rate'])) $module['rate']="CC";

			$rate->rate(strtoupper($module['rate']));			# See the rate() function for codes
			$rate->container(strtoupper($module['container']));	# See the container() function for codes
			$rate->weight($totalWeight);

			if (!isset($module['rescom'])) $module['rescom']="RES";
			$rate->rescom(strtoupper($module['rescom']));		# See the rescom() function for codes

			switch ($productCode) {
				case "1DM":
					$desc = $lang['front']['misc_nextDayEarlyAm'];
					break;
				case "1DA":
					$desc = $lang['front']['misc_nextDayAir'];
					break;
				case "1DP":
					$desc = $lang['front']['misc_nextDayAirSaver'];
					break;
				case "2DM":
					$desc = $lang['front']['misc_2ndDayEarlyAm'];
					break;
				case "2DA":
					$desc = $lang['front']['misc_2ndDayAir'];
					break;
				case "3DS":
					$desc = $lang['front']['misc_3daySelect'];
					break;
				case "GND":
					$desc = $lang['front']['misc_ground'];
					break;
				case "STD":
					$desc = $lang['front']['misc_canadaStandard'];
					break;
				case "XPR":
					$desc = $lang['front']['misc_worldwideExpress'];
					break;
				case "XDM":
					$desc = $lang['front']['misc_worldwideExpressPlus'];
					break;
				case "XPD":
					$desc = $lang['front']['misc_worldwideExpedited'];
					break;
			}

			$quote = $rate->getQuote();

			if($quote>0)
			{
				$quote = $module['handling'] + $quote;


				if($taxVal>0)
				{

					$shippingTax = ($taxVal / 100) * $quote;

				}

				$out[$i]['method'] = "UPS ".$desc;
				$out[$i]['desc'] = priceFormat($quote,true)." (UPS ".$desc.")";
				$out[$i]['value'] = $quote;
				$out[$i]['taxId'] = $module['tax'];
				$out[$i]['taxAmount'] = $shippingTax;

				$i++;
			}

		}

	}

}

return $out;
}
$shipArray[] = UPS();
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.