Ejemplo n.º 1
0
 public function SetPanelSettings()
 {
     // Show "All prices are in [currency code]"
     $currency = GetCurrencyById($GLOBALS['CurrentCurrency']);
     if (is_array($currency) && $currency['currencycode']) {
         $GLOBALS['AllPricesAreInCurrency'] = sprintf(GetLang('AllPricesAreInCurrency'), isc_html_escape($currency['currencyname']), isc_html_escape($currency['currencycode']));
     }
     if (GetConfig('DebugMode') == 1) {
         $end_time = microtime_float();
         $GLOBALS['ScriptTime'] = number_format($end_time - ISC_START_TIME, 4);
         $GLOBALS['QueryCount'] = $GLOBALS['ISC_CLASS_DB']->NumQueries;
         if (function_exists('memory_get_peak_usage')) {
             $GLOBALS['MemoryPeak'] = "Memory usage peaked at " . NiceSize(memory_get_peak_usage(true));
         } else {
             $GLOBALS['MemoryPeak'] = '';
         }
         if (isset($_REQUEST['debug'])) {
             $GLOBALS['QueryList'] = "<ol class='QueryList' style='font-size: 13px;'>\n";
             foreach ($GLOBALS['ISC_CLASS_DB']->QueryList as $query) {
                 $GLOBALS['QueryList'] .= "<li style='line-height: 1.4; margin-bottom: 4px;'>" . isc_html_escape($query['Query']) . " &mdash; <em>" . number_format($query['ExecutionTime'], 4) . "seconds</em></li>\n";
             }
             $GLOBALS['QueryList'] .= "</ol>";
         }
         $GLOBALS['DebugDetails'] = "<p>Page built in " . $GLOBALS['ScriptTime'] . "s with " . $GLOBALS['QueryCount'] . " queries. " . $GLOBALS['MemoryPeak'] . "</p>";
     } else {
         $GLOBALS['DebugDetails'] = '';
     }
     // Do we have any live chat service code to show in the footer
     $modules = GetConfig('LiveChatModules');
     if (!empty($modules)) {
         $liveChatClass = GetClass('ISC_LIVECHAT');
         $GLOBALS['LiveChatFooterCode'] = $liveChatClass->GetPageTrackingCode('footer');
     }
     // Load our whitelabel file for the front end
     require_once ISC_BASE_PATH . '/includes/whitelabel.php';
     // Load the configuration file for this template
     $poweredBy = 0;
     require_once ISC_BASE_PATH . '/templates/' . GetConfig('template') . '/config.php';
     if (isset($GLOBALS['TPL_CFG']['PoweredBy'])) {
         if (!isset($GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$GLOBALS['TPL_CFG']['PoweredBy']])) {
             $GLOBALS['TPL_CFG']['PoweredBy'] = 0;
         }
         $poweredBy = $GLOBALS['TPL_CFG']['PoweredBy'];
     }
     // Showing the powered by?
     $GLOBALS['PoweredBy'] = '';
     if ($GLOBALS['ISC_CFG']['DisableFrontEndPoweredBy'] == false && isset($GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$poweredBy])) {
         $GLOBALS['PoweredBy'] = $GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$poweredBy];
     }
 }
Ejemplo n.º 2
0
	public function __construct($templateId = 0)
	{
		$templateId = (int)$templateId;

		if (!$templateId) {
			return;
		}

		$query = '
			SELECT
				*
			FROM
				[|PREFIX|]ebay_listing_template
			WHERE
				id = ' . (int)$templateId;

		$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
		if (!($row = $GLOBALS['ISC_CLASS_DB']->Fetch($res))) {
			throw new Exception('Template ' . $templateId . ' not found.');
		}

		// get prices
		$query = 'SELECT * FROM [|PREFIX|]ebay_listing_prices WHERE ebay_listing_template_id = ' . $templateId;
		$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
		$prices = array();
		while ($priceRow = $GLOBALS['ISC_CLASS_DB']->Fetch($res)) {
			$prices[$priceRow['price_type']] = $priceRow;
		}

		// get shipping
		$query = '
			SELECT
				es.*
			FROM
				[|PREFIX|]ebay_shipping es
			WHERE
				es.ebay_listing_template_id = ' . $templateId . '
			ORDER BY
				es.id';
		$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
		$shippingSettings = array();
		while ($shippingRow = $GLOBALS['ISC_CLASS_DB']->Fetch($res)) {
			$shippingSettings[$shippingRow['area']] = $shippingRow;
		}

		// get shipping services
		$query = '
			SELECT
				ess.*,
				es.area,
				es.ebay_listing_template_id
			FROM
				[|PREFIX|]ebay_shipping_serv ess
				LEFT JOIN [|PREFIX|]ebay_shipping es ON es.id = ess.ebay_shipping_id
			WHERE
				es.ebay_listing_template_id = ' . $templateId . '
			ORDER BY
				ess.id';
		$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
		$shippingServices = array();
		while ($shippingRow = $GLOBALS['ISC_CLASS_DB']->Fetch($res)) {
			// only support one location at this stage
			$shipToLocations = unserialize($shippingRow['ship_to_locations']);
			$shipToLocation = '';
			if (!empty($shipToLocations)) {
				$shipToLocation = $shipToLocations[0];
			}
			$shippingRow['ship_to_location'] = $shipToLocation;
			$shippingRow['ship_to_locations'] = $shipToLocations;
			$shippingServices[$shippingRow['area']][$shippingRow['name']] = $shippingRow;
		}

		$this->_siteId = $row['site_id'];
		$this->_siteCode = GetClass('ISC_ADMIN_EBAY')->getSiteCodeFromSiteId($this->_siteId);

		// set the currency
		$currencyId = GetClass('ISC_ADMIN_EBAY')->getCurrencyFromSiteId($this->_siteId);
		if (!$currencyId) {
			throw new Exception('Currency for site not found');
		}
		$this->_currency = GetCurrencyById($currencyId);

		$this->_templateId = $templateId;
		$this->_templateName = $row['name'];
		$this->_defaultTemplate = (bool)$row['is_default'];
		$this->_privateListing = (bool)$row['is_private'];

		$this->_quantityToSell = $row['quantities'];
		$this->_useProductImage = (bool)$row['use_prod_image'];
		$this->_lotSize = $row['lot_size'];
		$this->_acceptBestOffers = (bool)$row['accept_best_offer'];

		$this->_sellingMethod = $row['listing_type'];
		$this->_listingDuration = $row['listing_duration'];

		$this->_itemLocationCountry = $row['item_country'];
		$this->_itemLocationZip = $row['item_zip'];
		$this->_itemLocationCityState = $row['item_city'];

		$this->_paymentMethods = unserialize($row['payment_method']);
		$this->_payPalEmailAddress = $row['paypal_email'];

		foreach ($prices as $price) {
			switch ($price['price_type']) {
				case ISC_ADMIN_EBAY::RESERVE_PRICE_TYPE:
					$this->_reservePriceOptions = $price;
					break;
				case ISC_ADMIN_EBAY::STARTING_PRICE_TYPE:
					$this->_startPriceOptions = $price;
					break;
				case ISC_ADMIN_EBAY::BUY_PRICE_TYPE:
					$this->_buyItNowPriceOptions = $price;
					break;
			}
		}

		// set category info
		$this->_primaryCategoryOptions = unserialize($row['primary_category_options']);
		$this->_secondaryCategoryOptions = unserialize($row['secondary_category_options']);
		$this->_primaryCategoryId = $row['primary_category_id'];
		$this->_secondaryCategoryId = $row['secondary_category_id'];
		$this->_secondaryCategoryName = $row['secondary_category_name'];
		$this->_primaryStoreCategoryId = $row['store_category1_id'];
		$this->_primaryStoreCategoryName = $row['store_category1_name'];
		$this->_secondaryStoreCategoryId = $row['store_category2_id'];
		$this->_secondaryStoreCategoryName = $row['store_category2_name'];

		// checkout and return info
		$this->_checkoutInstructions = $row['payment_instruction'];
		$this->_acceptReturns = (bool)$row['accept_return'];
		$this->_returnOfferedAs = $row['return_offer_as'];
		$this->_returnsPeriod = $row['return_period'];
		$this->_returnCostPaidBy = $row['return_cost_by'];
		$this->_additionalPolicyInfo = $row['return_policy_description'];

		// counter
		$this->_counterStyle = $row['counter_style'];

		$this->_galleryOption = $row['gallery_opt'];
		$this->_featuredGalleryDuration = $row['featured_gallery_duration'];

		// listing features/enhancements
		$this->_listingFeatures = unserialize($row['listing_opt']);

		// sales tax - US only
		$this->_useSalesTax = (bool)$row['use_salestax'];
		$this->_salesTaxState = $row['sales_tax_states'];
		$this->_salesTaxPercent = $row['salestax_percent'];
		$this->_salesTaxIncludesShipping = (int)$row['salestax_inc_shipping'];

		// shipping
		$this->_shippingSettings = $shippingSettings;
		$this->_shippingServices = $shippingServices;
		$this->_useDomesticShipping = (bool)$row['use_domestic_shipping'];
		$this->_useInternationalShipping = (bool)$row['use_international_shipping'];
		$this->_handlingTime = (int)$row['handling_time'];

		// option to specify this when listing has been removed and will be allowed always
		$this->_allowCategoryMapping = true;
	}
Ejemplo n.º 3
0
	protected function _ConstructPostData($postData)
	{
		$transactionid	= $this->GetCombinedOrderId();

		switch ($postData['cctype']) {
			case 'VISA':
				$cctype = '6';
				break;
			case 'MC':
				$cctype = '5';
				break;
			case 'AMEX':
				$cctype = '2';
				break;
			case 'DINERS':
				$cctype = '3';
				break;
			case 'JCB':
				$cctype = '1';
				break;
			default:
				$cctype = '0';
				break;
		}

		$timestamp = strftime("%Y%d%m%H%M%S000000%z");

		// A list of currencies that if is the store default, we don't need to convert to
		// cents
		$simpleCurrencies = array(
			'GRD',
			'ITL',
			'JPY'
		);
		$currency = GetCurrencyById($this->GetBaseCurrency());
		if(in_array($currency['currencycode'], $simpleCurrencies)) {
			$amount = $this->GetGatewayAmount();
		}
		else {
			$amount = number_format($this->GetGatewayAmount()*100,0,'','');
		}

		if($this->GetValue('fraudguard')) {
			$txnType = 21;
			$this->_testTransactionURI = '/antifraud_test/payment';
			$this->_liveTransactionURI = '/antifraud/payment';
		}
		else {
			$txnType = 0;
		}

		$amount = number_format($this->GetGatewayAmount()*100, 0, '', '');
		$currency = 'AUD';
		$expiryDate = str_pad($postData['ccexpm'], 2, '0', STR_PAD_LEFT).'/'.str_pad($postData['ccexpy'], 2, '0', STR_PAD_LEFT);
		$billingDetails = $this->GetBillingDetails();

		$xml = new SimpleXMLElement('<SecurePayMessage />');

		$messageInfo = $xml->addChild('MessageInfo');
		$messageInfo->addChild('messageID', md5($transactionid));
		$messageInfo->addChild('messageTimestamp', $timestamp);
		$messageInfo->addChild('timeoutValue', 60);
		$messageInfo->addChild('apiVersion', 'xml-4.2');

		$merchantInfo = $xml->addChild('MerchantInfo');
		$merchantInfo->addChild('merchantID', $this->GetValue('merchantid'));
		$merchantInfo->addChild('password', $this->GetValue('password'));

		$xml->addChild('RequestType', 'Payment');

		$payment = $xml->addChild('Payment');

		$txnList = $payment->addChild('TxnList');
		$txnList->addAttribute('count', 1);

		$txn = $xml->addChild('Txn');
		$txn->addAttribute('ID', 1);
		$txn->addChild('txnType', $txnType);
		$txn->addChild('txnSource', 23);
		$txn->addChild('amount', $amount);
		$txn->addChild('currency', $currency);
		$txn->addChild('purchaseOrderNo', $transactionid);

		$cardInfo = $txn->addChild('CreditCardInfo');
		$cardInfo->addChild('cardNumber', $postData['ccno']);
		$cardInfo->addChild('expiryDate', $expiryDate);
		$cardInfo->addChild('cardType', $cctype);
		if($this->CardTypeRequiresCVV2($postData['cctype'])) {
			$cardInfo->addChild('cvv', $postData['cccvd']);
		}

		$buyerInfo = $txn->addChild('BuyerInfo');
		$buyerInfo->addChild('firstName', $billingDetails['ordbillfirstname']);
		$buyerInfo->addChild('lastName', $billingDetails['ordbilllastname']);
		$buyerInfo->addChild('ipcode', $billingDetails['ordbillzip']);
		$buyerInfo->addChild('town', $billingDetails['ordbillsuburb']);
		$buyerInfo->addChild('billingCountry', $billingDetails['ordbillcountrycode']);
		$buyerInfo->addChild('emailAddress', $billingDetails['ordbillemail']);
		$buyerInfo->addChild('ip', $this->GetIpAddress());

		return $xml->asXML();
	}
Ejemplo n.º 4
0
 /**
  * Calculate the order details and populate the necessary session fields so we can call CreateOrder()
  *
  * @return void
  **/
 public function CalculateOrder()
 {
     $GLOBALS['ISC_CLASS_CART'] = GetClass('ISC_CART');
     //$GLOBALS['ISC_CLASS_CART'] not declared earlier, Added by Simha
     if ($GLOBALS['ISC_CLASS_CART']->api->AllProductsInCartAreIntangible()) {
         $all_digital_downloads = 1;
     } else {
         $all_digital_downloads = 0;
     }
     $GLOBALS['ISC_CLASS_CHECKOUT'] = GetClass('ISC_CHECKOUT');
     $orderSummary = $GLOBALS['ISC_CLASS_CHECKOUT']->CalculateOrderSummary();
     $this->module->DebugLog($orderSummary);
     $product_array = $GLOBALS['ISC_CLASS_CART']->api->GetProductsInCart(true);
     $itemTotal = 0;
     foreach ($product_array as $k => $product) {
         $comptotal = 0;
         /// Baskaran
         /*
         $compitem = $product['compitem'];
         @$compproductid = $product['complementary']['comp_productid'];
         @$compmainproductid = $product['complementary']['comp_mainproductid'];
         $mainproductid = $product['product_id'];
         
         if($compitem == 1 and $mainproductid == $compmainproductid) {
             $compprice = $product['complementary']['comp_original_price'];
             $comptotal += $compprice;
         }
         /// Code Ends 
         */
         //if .. else added by Simha to consider the discount price in order total
         /* To add complementary product to Google checkout -- Baskaran*/
         if ($product['compitem'] == 1) {
             for ($y = 0; $y < count($product['complementary']); $y++) {
                 if ($product['product_id'] == $product['complementary'][$y]['comp_mainproductid']) {
                     $compprodname = $product['complementary'][$y]['comp_product_name'];
                     $compprodprice = $product['complementary'][$y]['comp_original_price'];
                     $compqty = $product['complementary'][$y]['quantity'];
                     $comptotal += $compprodprice * $compqty;
                 }
             }
         }
         if (isset($product['discount_price']) && $product['discount_price'] < $product['product_price']) {
             $curprice = $product['discount_price'];
         } else {
             $curprice = $product['product_price'];
         }
         $itemTotal += $curprice * $product['quantity'] + $comptotal;
         # $comptotal added to add the complementary amount to the table -- Baskaran
     }
     if (isset($this->response->data[$this->response->root]['order-adjustment']['shipping']['merchant-calculated-shipping-adjustment'])) {
         $shipping = $this->response->data[$this->response->root]['order-adjustment']['shipping']['merchant-calculated-shipping-adjustment'];
     } else {
         $shipping = array('shipping-cost' => array('VALUE' => 0), 'shipping-name' => array('VALUE' => ''));
     }
     $shippingCost = $shipping['shipping-cost']['VALUE'];
     $vendorIds = $GLOBALS['ISC_CLASS_CART']->api->GetCartVendorIds();
     $vendorIds = array_shift($vendorIds);
     //array_pop replaced by array_shift to consider only the first vendor after merging vendors
     $_SESSION['CHECKOUT']['PENDING_DATA']['VENDORS'][$vendorIds . '_0'] = array();
     // The cost of shipping
     $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['COST'] = $shippingCost;
     // The handling cost
     $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['HANDLING'] = 0;
     // The name of the tax being applied
     $_SESSION['CHECKOUT']['PENDING_DATA']['TAX_NAME'] = $orderSummary['taxName'];
     // The dollar value of the tax being applied
     $_SESSION['CHECKOUT']['PENDING_DATA']['VENDORS'][$vendorIds . '_0']['TAX_COST'] = $orderSummary['taxCost'];
     $_SESSION['CHECKOUT']['PENDING_DATA']['TAX_COST'] = $orderSummary['taxCost'];
     // The rate the tax is being applied at as a percentage (0-100)
     $_SESSION['CHECKOUT']['PENDING_DATA']['TAX_RATE'] = $orderSummary['taxRate'];
     // Is the tax already being included in the price of the products 0/1
     $_SESSION['CHECKOUT']['PENDING_DATA']['TAX_INCLUDED'] = $orderSummary['taxIncluded'];
     $orderTotal = $itemTotal + $shippingCost;
     if (!$orderSummary['taxIncluded'] && !(GetConfig('TaxTypeSelected') == 2)) {
         $orderTotal += $orderSummary['taxCost'];
     }
     // The total of the order including items, shipping, handling and tax
     $_SESSION['CHECKOUT']['PENDING_DATA']['VENDORS'][$vendorIds . '_0']['ORDER_TOTAL'] = $orderTotal;
     $_SESSION['CHECKOUT']['PENDING_DATA']['VENDORS'][$vendorIds . '_0']['ITEM_TOTAL'] = $itemTotal;
     $_SESSION['CHECKOUT']['PENDING_DATA']['ORDER_TOTAL'] = $orderTotal;
     //$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, 'response details '.print_r($this->response, true));
     // The shipping address array
     $_SESSION['CHECKOUT']['SHIPPING_ADDRESS'] = $this->GetAddressFromResponse($this->response->data[$this->response->root]['buyer-shipping-address']);
     // The billing address array
     $_SESSION['CHECKOUT']['BILLING_ADDRESS'] = $this->GetAddressFromResponse($this->response->data[$this->response->root]['buyer-billing-address']);
     // The english name of the provider
     $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['PROVIDER'] = $shipping['shipping-name']['VALUE'];
     // The id of the provider
     $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['MODULE'] = $this->GetShippingProviderModuleByName($shipping['shipping-name']['VALUE']);
     $shippingZoneId = GetShippingZoneIdByAddress($_SESSION['CHECKOUT']['SHIPPING_ADDRESS']);
     $shippingZone = GetShippingZoneById($shippingZoneId);
     // The amount of store credit being applied to the order
     $creditDiscount = 0;
     // The name of the gift certificates being applied
     $giftCertificates = '';
     $giftCertificateDiscount = 0;
     // The total amount of all the gift certs being applied
     $_SESSION['CHECKOUT']['PENDING_DATA']['GIFTCERTIFICATE_AMOUNT'] = $giftCertificateDiscount;
     // The amount being sent to the checkout gateway (order total - gift certifcate discounts - store credit discounts)
     $_SESSION['CHECKOUT']['PENDING_DATA']['GATEWAY_AMOUNT'] = $orderTotal - $creditDiscount - $giftCertificateDiscount;
     //$GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, 'checkout before creating the pending order '.print_r($_SESSION['CHECKOUT'], true));
     // Now that we're here, we have everything we need to create the pending order.
     // Create it and store it. We hard code the geoip information since google will be
     // making the request
     $selectedCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);
     $pendingOrder = array('customertoken' => '', 'customerid' => 0, 'itemtotal' => $orderSummary['itemTotal'], 'shippingcost' => $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['COST'], 'handlingcost' => $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['HANDLING'], 'taxname' => $_SESSION['CHECKOUT']['PENDING_DATA']['TAX_NAME'], 'taxcost' => $_SESSION['CHECKOUT']['PENDING_DATA']['VENDORS'][$vendorIds . '_0']['TAX_COST'], 'taxrate' => $_SESSION['CHECKOUT']['PENDING_DATA']['TAX_RATE'], 'totalincludestax' => $_SESSION['CHECKOUT']['PENDING_DATA']['TAX_INCLUDED'], 'totalcost' => $_SESSION['CHECKOUT']['PENDING_DATA']['ORDER_TOTAL'], 'shippingaddress' => $_SESSION['CHECKOUT']['SHIPPING_ADDRESS'], 'billingaddress' => $_SESSION['CHECKOUT']['BILLING_ADDRESS'], 'shippingprovider' => $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['PROVIDER'], 'shippingmodule' => $_SESSION['CHECKOUT']['SHIPPING'][$vendorIds . '_0']['MODULE'], 'paymentmethod' => 'checkout_googlecheckout', 'isdigitalorder' => (int) $all_digital_downloads, 'storecreditamount' => $creditDiscount, 'giftcertificateamount' => $_SESSION['CHECKOUT']['PENDING_DATA']['GIFTCERTIFICATE_AMOUNT'], 'giftcertificates' => $giftCertificates, 'gatewayamount' => $_SESSION['CHECKOUT']['PENDING_DATA']['GATEWAY_AMOUNT'], 'currencyid' => $selectedCurrency['currencyid'], 'currencyexchangerate' => $selectedCurrency['currencyexchangerate'], 'ordshippingzoneid' => $shippingZoneId, 'ordshippingzone' => $shippingZone['zonename']);
     return $pendingOrder;
 }
Ejemplo n.º 5
0
/**
 * Format the price
 *
 * Function will format the price based on the currency record that is provided. The default currency record will be the
 * one stored in the current session
 *
 * @access public
 * @param float $price The price to format
 * @param array $currency The currency record. Default is the one stored within the currency session
 * @return string The formatted price
 */
function FormatPrice($price, $strip_decimals=false, $add_token=true, $strip_thousandsep=false, $currency=null, $includeCurrencyCode=false)
{
	// Because we're going to have prices come as floats, we're likely to have
	// precision issues. Round everything to 4 decimal places before formatting
	// a price, because that's the max internally storable in the DB anyway.
	// Better yet would be to store prices in cents, rather than dollars but
	// this is not feasible at the moment.
	$price = round($price, 4);

	if (is_null($currency)) {
		if(!isset($GLOBALS['CurrentCurrency'])) {
			$defaultCurrency = GetDefaultCurrency();
			$GLOBALS['CurrentCurrency'] = $defaultCurrency['currencyid'];
		}
		$currency = GetCurrencyById($GLOBALS['CurrentCurrency']);
	}

	if(!is_array($currency)) {
		$currency = GetCurrencyById($currency);
	}

	if(!isset($currency['currencyid'])) {
		$currency = GetDefaultCurrency();
	}

	if ($strip_thousandsep) {
		$currency['currencythousandstring'] = '';
	}

	$negative = false;
	if($price < 0) {
		$negative = true;
		$price = substr($price, 1);
	}

	$num = number_format($price, $currency['currencydecimalplace'], $currency['currencydecimalstring'], $currency['currencythousandstring']);
	// Do we strip decimal places? If so just return the whole number portion
	if ($strip_decimals) {
		$tmp = explode($currency['currencydecimalstring'], $num);
		$num = $tmp[0];
	}

	if ($add_token) {
		if (strtolower($currency['currencystringposition']) == "left") {
			$num = $currency['currencystring'] . $num;
		}
		else {
			$num = $num . $currency['currencystring'];
		}
	}

	if($includeCurrencyCode == true) {
		$num .= ' '.$currency['currencycode'];
	}

	if($negative) {
		$num = '-'.$num;
	}

	return $num;
}
Ejemplo n.º 6
0
/**
 * Save a particular currency in the current viewers session.
 *
 * @param int The currency ID to save in the session.
 * @return boolean True if successful,false if unsuccessful.
 */
function SaveCurrencyInSession($currencyId)
{
    $currency = GetCurrencyById($currencyId);
    if ($currency['currencyid']) {
        $_SESSION['CURRENCY'] = $currencyId;
        return true;
    }
    return false;
}
Ejemplo n.º 7
0
	/**
	* Gets specific details and available item conditions for a specific category
	*
	*/
	private function getCategoryFeaturesAction()
	{
		$categoryId = (int)$_POST['categoryId'];
		$siteId = (int)$_POST['siteId'];

		try {
			$categoryFeatures = ISC_ADMIN_EBAY_CATEGORIES::getCategoryFeatures($categoryId, $siteId);

			$categoryPath = ISC_ADMIN_EBAY_CATEGORIES::getFormattedCategoryPath($categoryId, $siteId);
			$categoryFeatures['path'] = $categoryPath;
		}
		catch (Exception $ex) {
			ISC_JSON::output('The category information could not be retrieved.', false);
		}

		$output = array(
			'categoryFeatures' => $categoryFeatures
		);

		// are we requesting features for the primary category?
		if (!empty($_POST['primaryCategory'])) {
			// include conditions
			if ($categoryFeatures['has_conditions']) {
				$conditions = array('-- Do Not Map --');
				$conditions += $categoryFeatures['conditions'];

				$this->template->assign('conditions', $conditions);
				$this->template->assign('conditionRequired', $categoryFeatures['conditions_required']);
				$output['conditionsHTML'] = $this->template->render('ebay.mapconditions.tpl');
			}

			// generate a list of features
			$this->template->assign('categoryOptions', $categoryFeatures);
			$currencyId = GetClass('ISC_ADMIN_EBAY')->getCurrencyFromSiteId($siteId);
			$currency = GetCurrencyById($currencyId);
			$this->template->assign('currency', $currency);
			$output['categoryFeaturesList'] = $this->template->render('ebay.template.featureslist.tpl');
		}

		ISC_JSON::output('', true, $output);
	}
Ejemplo n.º 8
0
	/**
	 * Create the pending order in the database with the customers selected payment details, etc.
	 *
	 * @return array An array containing information about what needs to be done next.
	 */
	public function SavePendingOrder()
	{
		$provider = null;
		$verifyPaymentProvider = true;
		$redirectToFinishOrder = false;
		$providerId = '';

		$pendingOrderResult = array();
		$creditUsed = 0;
		$giftCertificates = array();

		$orderTotal = $this->getQuote()->getGrandTotal();

		// store the discounted subtotal in the session for affiliate tracking
		$incTax = (getConfig('taxDefaultTaxDisplayOrders') == TAX_PRICES_DISPLAY_INCLUSIVE);
		$_SESSION['LAST_ORDER_DISCOUNTED_SUBTOTAL'] = $this->getQuote()->getDiscountedSubTotal($incTax);

		// Find out what currency we are using. We'll need this later to display their previous orders in the currency that they have selected
		$selectedCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);

		$giftCertificates = $this->getQuote()->getAppliedGiftCertificates();
		if(!empty($giftCertificates)) {
			$badCertificates = array();
			$remainingBalance = 0;
			$totalWithoutCertificates =
				$this->getQuote()->getGrandTotalWithoutGiftCertificates();
			$giftCertificateAmount =
				$this->getQuote()->getGiftCertificateTotal();
			getClass('ISC_GIFTCERTIFICATES')
				->giftCertificatesApplicableToOrder(
					$totalWithoutCertificates,
					$giftCertificates,
					$remainingBalance,
					$badCertificates);

			// One or more gift certificates were invalid so this order is now invalid
			if(!empty($badCertificates)) {
				$badCertificatesList = '<strong>'.GetLang('BadGiftCertificates').'</strong><ul>';
				foreach($badCertificates as $code => $reason) {
					if(is_array($reason) && $reason[0] == "expired") {
						$reason = sprintf(GetLang('BadGiftCertificateExpired'), CDate($reason[1]));
					}
					else {
						$reason = GetLang('BadGiftCertificate'.ucfirst($reason));
					}
					$badCertificatesList .= sprintf("<li>%s - %s", isc_html_escape($code), $reason);
				}
				$badCertificatesList .= "</ul>";
				$pendingOrderResult = array(
					'error' => GetLang('OrderContainedInvalidGiftCertificates'),
					'errorDetails' => $badCertificatesList
				);
				return $pendingOrderResult;
			}
			// This order was entirely paid for using gift certificates but the totals don't add up
			else if($totalWithoutCertificates == $giftCertificateAmount && $remainingBalance > 0) {
				$pendingOrderResult = array(
					'error' => GetLang('OrderTotalStillRemainingCertificates')
				);
				return $pendingOrderResult;
			}
			// Order was entirely paid for using gift certificates
			else if($totalWithoutCertificates == $giftCertificateAmount) {
				$providerId = 'giftcertificate';
				$verifyPaymentProvider = false;
				$redirectToFinishOrder = true;
			}
		}

		// If the order total is 0, then we just forward the user on to the "Thank You" page and set the payment provider to ''
		if($orderTotal == 0) {
			$providerId = '';
			$verifyPaymentProvider = false;
			$redirectToFinishOrder = true;
		}

		$selected_provider = '';
		if($verifyPaymentProvider) {
			$candidate = '';
			if (isset($_POST['checkout_provider']) && $_POST['checkout_provider'] != '') {
				$candidate = $_POST['checkout_provider'];
			} else if (isset($_POST['credit_checkout_provider']) && $_POST['credit_checkout_provider'] != '') {
				// used by paypal
				$candidate = $_POST['credit_checkout_provider'];
			}

			// Check if the chosen checkout method is valid
			$providers = GetCheckoutModulesThatCustomerHasAccessTo(true);
			foreach ($providers as $p) {
				if ($p['id'] == $candidate) {
					$selected_provider = $candidate;
				}
			}

			// If there's only one payment provider, then they're paying via that
			if($selected_provider == '' && count($providers) == 1) {
				$selected_provider = $providers[0]['object']->GetId();
			}

			// Are we using our store credit?
			$customer = getClass('ISC_CUSTOMER')->getCustomerDataByToken();
			if (isset($_POST['store_credit']) && $_POST['store_credit'] == 1
				&& $customer['custstorecredit'] > 0) {
					// User has not chosen a payment provider and can't afford this order using only store credit, throw back as error
					if ($selected_provider == '' && $customer['custstorecredit'] < $orderTotal) {
						return false;
					}
					// Otherwise we can use the store credit.
					// Subtract store credit from users account and send them to the finished page
					else {
						$onlyCredit = false;
						$updateExtra = '';
						// If we're only using store credit
						$creditToUse = $orderTotal;
						if ($customer['custstorecredit'] >= $creditToUse) {
							// Set the checkout provider
							$providerId = 'storecredit';
							$verifyPaymentProvider = false;
							$redirectToFinishOrder = true;
							$creditUsed = $creditToUse;
							$onlyCredit = true;
						}
						else {
							// Using all of our store credit to pay for this order and we owe more.
							$creditUsed = $customer['custstorecredit'];
						}
					}
			}
		}

		$orderStatus = ORDER_STATUS_INCOMPLETE;

		// Now with round 2, do we still need to verify the payment provider?
		if($verifyPaymentProvider) {
			// If there's more than one provider and one wasn't selected on the order confirmation screen then there's a problem
			if ((count($providers) == 0 ||
				(count($providers) > 1 && $selected_provider == '')) &&
					!isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
					return false;
			}

			// Is the payment provider selected actually valid?
			if (!GetModuleById('checkout', $provider, $selected_provider)) {
				return false;
			}
			$providerId = $provider->GetId();
		}

		if(isset($_COOKIE['SHOP_TOKEN'])) {
			$customerToken = $_COOKIE['SHOP_TOKEN'];
		}
		else {
			$customerToken = '';
		}

		$orderComments = '';
		if(isset($_REQUEST['ordercomments'])) {
			$orderComments = $_POST['ordercomments'];
		}

		// Set up the order to be created
		$this->getQuote()
			->setAppliedStoreCredit($creditUsed)
			->setCustomerMessage($orderComments);
			;

		$newOrder = array(
			'orderpaymentmodule' => $providerId,
			'ordcurrencyid' => $selectedCurrency['currencyid'],
			'ordcurrencyexchangerate' => $selectedCurrency['currencyexchangerate'],
			'ordipaddress' => getIp(),
			'ordstatus' => $orderStatus,
			'extraInfo' => array(),

			'quote' => $this->getQuote(),
		);


		// OK, we're successful down to here - do they want to create an account? If so then assign it to
		// a session so we can create the actual record on a successful order
		if(!empty($_SESSION['CHECKOUT']['CREATE_ACCOUNT']) ||
			!customerIsSignedIn() && getConfig('GuestCheckoutCreateAccounts')) {
				$createAccount = array(
					'addresses' => array()
				);
				if(!empty($_SESSION['CHECKOUT']['CREATE_ACCOUNT'])) {
					$createAccount['password'] = $_SESSION['CHECKOUT']['CREATE_ACCOUNT']['password'];
					$createAccount['customFormFields'] = $_SESSION['CHECKOUT']['CREATE_ACCOUNT']['customFields'];
				}
				else {
					$createAccount['autoCreated'] = 1;
				}

				// Handle saving of addresses for new customers
				foreach($this->getQuote()->getAllAddresses() as $address) {
					if($address->getSaveAddress()) {
						$customerAddress = $address->getAsArray();
						$customFields = $address->getCustomFields();
						if(!empty($customFields)) {
							$customerAddress['customFormFields'] = $customFields;

							// Shipping fields need to be mapped back to billing so they can be stored
							if($address->getType() == ISC_QUOTE_ADDRESS::TYPE_SHIPPING) {
								$newCustomFields = array();
								$map = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, array_keys($customFields));
								foreach($map as $oldId => $newId) {
									$newCustomFields[$newId] = $customFields[$oldId];
								}
								$customerAddress['customFormFields'] = $newCustomFields;
							}
						}

						$createAccount['addresses'][] = $customerAddress;
					}
				}

				$newOrder['extraInfo']['createAccount'] = $createAccount;
		}

		// Did they agree to signup to any mailing lists?
		if (isset($_POST['join_mailing_list'])) {
			$newOrder['extraInfo']['join_mailing_list'] = true;
		}

		if (isset($_POST['join_order_list'])) {
			$newOrder['extraInfo']['join_order_list'] = true;
		}

		if (isset($_POST['join_mailing_list']) || isset($_POST['join_order_list'])) {
			if (isset($_POST['mail_format_preference'])) {
				$newOrder['extraInfo']['mail_format_preference'] = (int)$_POST['mail_format_preference'];
			} else {
				$newOrder['extraInfo']['mail_format_preference'] = Interspire_EmailIntegration_Subscription::FORMAT_PREF_NONE;
			}
			$newOrder['extraInfo']['join_order_list'] = true;
		}


		if(isset($_POST['ordermessage'])) {
			$newOrder['ordermessage'] = $_POST['ordermessage'];
		} else {
			$newOrder['ordermessage'] = '';
		}

		$entity = new ISC_ENTITY_ORDER();
		$orderId = $entity->add($newOrder);

		// Failed to create the order
		if(!$orderId) {
			return false;
		}

		$order = getOrder($orderId);

		// Persist the pending order token as a cookie for 24 hours
		ISC_SetCookie("SHOP_ORDER_TOKEN", $order['ordtoken'], time() + (3600*24), true);
		$_COOKIE['SHOP_ORDER_TOKEN'] = $order['ordtoken'];

		// Redirecting to finish order page?
		if($redirectToFinishOrder) {
			return array(
				'redirectToFinishOrder' => true
			);
		}

		// Otherwise, the gateway want's to do something
		$orderData = LoadPendingOrdersByToken($order['ordtoken']);
		$provider->SetOrderData($orderData);

		// Is this an online payment provider? It would like to do something
		if($provider->GetPaymentType() == PAYMENT_PROVIDER_ONLINE || method_exists($provider, "ShowPaymentForm")) {
			// Call the checkout process for the selected provider
			if(method_exists($provider, "ShowPaymentForm")) {
				return array(
					'provider' => $provider,
					'showPaymentForm' => true
				);
			}
			else {
				return array(
					'provider' => $provider
				);
			}
		}
		// If an offline method, we throw them to the "Thank you for your order" page
		else {
			return array(
				'provider' => $provider
			);
		}
	}
Ejemplo n.º 9
0
/**
 * Format the price
 *
 * Function will format the price based on the currency record that is provided. The default currency record will be the
 * one stored in the current session
 *
 * @access public
 * @param float $price The price to format
 * @param array $currency The currency record. Default is the one stored within the currency session
 * @return string The formatted price
 */
function FormatPrice($price, $strip_decimals = false, $add_token = true, $strip_thousandsep = false, $currency = null, $includeCurrencyCode = false)
{
    if (is_null($currency)) {
        if (!isset($GLOBALS['CurrentCurrency'])) {
            $defaultCurrency = GetDefaultCurrency();
            $GLOBALS['CurrentCurrency'] = $defaultCurrency['currencyid'];
        }
        $currency = GetCurrencyById($GLOBALS['CurrentCurrency']);
    }
    if (!is_array($currency)) {
        $currency = GetCurrencyById($currency);
    }
    if (!isset($currency['currencyid'])) {
        $currency = GetDefaultCurrency();
    }
    if ($strip_thousandsep) {
        $currency['currencythousandstring'] = '';
    }
    $num = number_format($price, $currency['currencydecimalplace'], $currency['currencydecimalstring'], $currency['currencythousandstring']);
    // Do we strip decimal places? If so just return the whole number portion
    if ($strip_decimals) {
        $tmp = explode($currency['currencydecimalstring'], $num);
        $num = $tmp[0];
    }
    if ($add_token) {
        if (strtolower($currency['currencystringposition']) == "left") {
            $num = $currency['currencystring'] . $num;
        } else {
            $num = $num . $currency['currencystring'];
        }
    }
    if ($includeCurrencyCode == true) {
        $num .= ' ' . $currency['currencycode'];
    }
    return $num;
}
Ejemplo n.º 10
0
		public function SetPanelSettings()
		{
			$GLOBALS['FooterScripts'] = '';

			$GLOBALS['HideLogoutLink'] = 'display: none';
			if(CustomerIsSignedIn()) {
				$GLOBALS['HideLogoutLink'] = '';
			}

			if($_SERVER['REQUEST_METHOD'] == 'POST') {
				$baseURL = getConfig('ShopPathNormal');
			}
			else {
				$baseURL = getCurrentLocation();
			}

			if(strpos($baseURL, '?') === false) {
				$baseURL .= '?';
			}
			else {
				$baseURL .= '&';
			}

			$fullSiteLink = $baseURL.'fullSite=1';
			$GLOBALS['ISC_CLASS_TEMPLATE']->assign('FullSiteLink', $fullSiteLink);

			// Show Mobile Site link
			if(canViewMobileSite()) {
				$mobileSiteURL = preg_replace('/(&)?fullSite=\d*/i', '', $baseURL);
				$GLOBALS['MobileSiteURL'] = $mobileSiteURL.'fullSite=0';
				$GLOBALS['MobileSiteLink'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('MobileSiteLink');
			}

			// Show "All prices are in [currency code]"
			$currency = GetCurrencyById($GLOBALS['CurrentCurrency']);
			if(is_array($currency) && $currency['currencycode']) {
				$GLOBALS['AllPricesAreInCurrency'] = sprintf(GetLang('AllPricesAreInCurrency'), isc_html_escape($currency['currencyname']), isc_html_escape($currency['currencycode']));
			}

			if(GetConfig('DebugMode') == 1) {
				$end_time = microtime_float();
				$GLOBALS['ScriptTime'] = number_format($end_time - ISC_START_TIME, 4);
				$GLOBALS['QueryCount'] = $GLOBALS['ISC_CLASS_DB']->NumQueries;
				if (function_exists('memory_get_peak_usage')) {
					$GLOBALS['MemoryPeak'] = "Memory usage peaked at ".Store_Number::niceSize(memory_get_peak_usage(true));
				} else {
					$GLOBALS['MemoryPeak'] = '';
				}

				if (isset($_REQUEST['debug'])) {
					$GLOBALS['QueryList'] = "<ol class='QueryList' style='font-size: 13px;'>\n";
					foreach($GLOBALS['ISC_CLASS_DB']->QueryList as $query) {
						$GLOBALS['QueryList'] .= "<li style='line-height: 1.4; margin-bottom: 4px;'>".isc_html_escape($query['Query'])." &mdash; <em>".number_format($query['ExecutionTime'], 4)."seconds</em></li>\n";
					}
					$GLOBALS['QueryList'] .= "</ol>";
				}
				$GLOBALS['DebugDetails'] = "<p>Page built in ".$GLOBALS['ScriptTime']."s with ".$GLOBALS['QueryCount']." queries. ".$GLOBALS['MemoryPeak']."</p>";
			}
			else {
				$GLOBALS['DebugDetails'] = '';
			}

			// Do we have any live chat service code to show in the footer
			$modules = GetConfig('LiveChatModules');
			if(!empty($modules)) {
				$liveChatClass = GetClass('ISC_LIVECHAT');
				$GLOBALS['LiveChatFooterCode'] = $liveChatClass->GetPageTrackingCode('footer');
			}

			// Load our whitelabel file for the front end
			require_once ISC_BASE_PATH.'/includes/whitelabel.php';

			// Load the configuration file for this template
			$poweredBy = 0;
			require_once ISC_BASE_PATH.'/templates/'.GetConfig('template').'/config.php';
			if(isset($GLOBALS['TPL_CFG']['PoweredBy'])) {
				if(!isset($GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$GLOBALS['TPL_CFG']['PoweredBy']])) {
					$GLOBALS['TPL_CFG']['PoweredBy'] = 0;
				}
				$poweredBy = $GLOBALS['TPL_CFG']['PoweredBy'];
			}

			// Showing the powered by?
			$GLOBALS['PoweredBy'] = '';
			if($GLOBALS['ISC_CFG']['DisableFrontEndPoweredBy'] == false && isset($GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$poweredBy])) {
				$GLOBALS['PoweredBy'] = $GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$poweredBy];
			}

			if(empty($GLOBALS['OptimizerConversionScript']) && empty($GLOBALS['OptimizerTrackingScript']) && empty($GLOBALS['OptimizerControlScript'])) {
				$this->setGwoCookieCrossDomain();
			}

			$GLOBALS['SitemapURL_HTML'] = isc_html_escape(SitemapLink());
			$GLOBALS['SNIPPETS']['SitemapLink'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('SitemapLink');

			if (Interspire_TaskManager::hasTasks()) {
				// hasTasks is only implemented for Internal so this will (should) never run for Resque-based task manager
				$GLOBALS['FooterScripts'] .= Interspire_TaskManager::getTriggerHtml('json');
			}

			if (ISC_CATEGORY::areCategoryFlyoutsEnabled()) {
				// this needs to be output from php into the body since it's based on config vars
				// @todo use the stuff gaston is working on instead

				// bgiframe fixes some IE-related issues with CSS menus (like hovering over SELECT elements)
				$GLOBALS['FooterScripts'] .= '<script type="text/javascript" src="'
					. GetConfig('AppPath') . '/javascript/superfish/js/jquery.bgiframe.min.js?'
					. GetConfig('JSCacheToken') . '"></script>' . "\n";
				$GLOBALS['FooterScripts'] .= '<script type="text/javascript" src="'
					. GetConfig('AppPath') . '/javascript/superfish/js/superfish.js?'
					. GetConfig('JSCacheToken') . '"></script>' . "\n";
				$GLOBALS['FooterScripts'] .= '<script type="text/javascript">
	$(function(){
		if (typeof $.fn.superfish == "function") {
			$("ul.sf-menu").superfish({
				delay: ' . ((float)GetConfig('categoryFlyoutMouseOutDelay') * 1000) . ',
				dropShadows: ' . isc_json_encode(GetConfig('categoryFlyoutDropShadow')) . ',
				speed: "fast"
			})
			.find("ul")
			.bgIframe();
		}
	})
</script>
';
			}

			if (GetConfig('FastCartAction') == 'popup' && GetConfig('ShowCartSuggestions')) {
				$GLOBALS['SNIPPETS']['FastCartThickBoxJs'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('FastCartThickBoxJs');
			}
		}
Ejemplo n.º 11
0
	/**
	* Displays a template details form specific for an eBay site and selected category options
	*
	* @param int $siteId The eBay site to display a template for
	* @param array $categoryOptions The primary category options to customize the form
	* @param int $templateId Optional template Id to use to fill the form with
	* @return string The form HTML
	*/
	public function getTemplateForm($siteId, $categoryOptions, $templateId = 0)
	{
		// Load eBay XML cache
		$xmlContent = str_replace('xmlns=', 'ns=', $this->ReadCache($siteId));
		$getEbayDetailsXml = new SimpleXMLElement($xmlContent);

		$currencyId = $this->getCurrencyFromSiteId($siteId);
		$currency = GetCurrencyById($currencyId);

		$this->template->assign('currency', $currency);
		$this->template->assign('currencyToken', $currency['currencystring']);
		$this->template->assign('options', $categoryOptions);

		$this->template->assign('auctionDurations',  $this->getDurationOptions($categoryOptions['auction_durations']));
		$this->template->assign('fixedDurations',  $this->getDurationOptions($categoryOptions['fixed_durations']));

		$paymentMethods = $categoryOptions['payment_methods'];
		asort($paymentMethods);
		$this->template->assign('paymentMethods', $this->getPaymentMethodOptions($paymentMethods));

		// location details
		$this->template->assign('countries', GetCountryListAsIdValuePairs());

		// shipping details
		// Options for shipping services
		$shippingServiceObj = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ShippingServiceDetails');
		$shippingServices = $this->getShippingAsOptions($shippingServiceObj);

		// Options for handling time
		$handlingTimeObject = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/DispatchTimeMaxDetails');
		$handlingTimeArray = $this->convertEbayObjectToArray('DispatchTimeMax', 'Description', $handlingTimeObject);
		// remove the 0 days option as handling time is now required with ebay and 0 isnt valid
		unset($handlingTimeArray[0]);
		ksort($handlingTimeArray);
		$this->template->assign('handlingTimes', $handlingTimeArray);

		// Retrieving shipping cost type
		$this->template->assign('domesticShippingCostTypes', $shippingServices['Domestic']['ServiceTypes']);
		$this->template->assign('internationalShippingCostTypes', $shippingServices['International']['ServiceTypes']);

		// Shipping service Flat
		$domesticFlatServices = $shippingServices['Domestic']['Services']['Flat'];

		// is Pickup offered as a service? remove it from our service list and set it as a template var
		if (isset($domesticFlatServices['Other']['Pickup'])) {
			$this->template->assign('domesticPickupAllowed', true);
			unset($domesticFlatServices['Other']['Pickup']);
		}
		$this->template->assign('DomesticShippingServFlat', $domesticFlatServices);
		$this->template->assign('InternationalShippingServFlat', $shippingServices['International']['Services']['Flat']);

		// Shipping service Calculated
		if (!empty($shippingServices['Domestic']['Services']['Calculated'])) {
			$this->template->assign('DomesticShippingServCalculated', $shippingServices['Domestic']['Services']['Calculated']);
		}
		if (!empty($shippingServices['International']['Services']['Calculated'])) {
			$this->template->assign('InternationalShippingServCalculated', $shippingServices['International']['Services']['Calculated']);
		}

		// Shipping Service Package Details - only used for calculated shipping cost type
		$shippingPackageObj = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ShippingPackageDetails');
		$shippingPackageArr = $this->convertEbayObjectToArray('ShippingPackage', 'Description', $shippingPackageObj);
		$this->template->assign('DomesticShippingPackage', $shippingPackageArr);
		$this->template->assign('InternationalShippingPackage', $shippingPackageArr);

		// ship to locations
		$shippingLocationObj = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ShippingLocationDetails');
		$shippingLocationArr = $this->convertEbayObjectToArray('ShippingLocation', 'Description', $shippingLocationObj);
		asort($shippingLocationArr);
		$this->template->assign('ShipToLocations', $shippingLocationArr);

		// additional shipping details
		$salesTaxStatesObject = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/TaxJurisdiction');
		$salesTaxStatesArray = $this->convertEbayObjectToArray('JurisdictionID', 'JurisdictionName', $salesTaxStatesObject);
		$this->template->assign('hasSalesTaxStates', !empty($salesTaxStatesArray));
		asort($salesTaxStatesArray);
		$this->template->assign('salesTaxStates', $salesTaxStatesArray);

		// refund details
		$refundObject = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ReturnPolicyDetails/Refund');
		if ($refundObject) {
			$this->template->assign('refundOptions', $this->convertEbayObjectToArray('RefundOption', 'Description', $refundObject));
		}
		$this->template->assign('refundSupported', (bool)$refundObject);

		$returnsWithinObject = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ReturnPolicyDetails/ReturnsWithin');
		if ($returnsWithinObject) {
			$this->template->assign('returnsWithinOptions', $this->convertEbayObjectToArray('ReturnsWithinOption', 'Description', $returnsWithinObject));
		}
		$this->template->assign('returnsWithinSupported', (bool)$returnsWithinObject);

		$returnCostPaidByObject = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ReturnPolicyDetails/ShippingCostPaidBy');
		if ($returnCostPaidByObject) {
			$this->template->assign('returnCostPaidByOptions', $this->convertEbayObjectToArray('ShippingCostPaidByOption', 'Description', $returnCostPaidByObject));
		}
		$this->template->assign('returnCostPaidBySupported', (bool)$returnCostPaidByObject);

		$returnDescriptionObject = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ReturnPolicyDetails/Description');
		$this->template->assign('returnDescriptionSupported', (bool)$returnDescriptionObject);

		// hit counter
		$availableHitCounters = array ('NoHitCounter','HiddenStyle','BasicStyle','RetroStyle');
		$hitCounters = array();
		foreach ($availableHitCounters as $counter) {
			$hitCounters[$counter] = GetLang($counter);
		}
		$this->template->assign('hitCounters', $hitCounters);

		// Paid upgrade options

		// Gallery Style
		$availableGalleryOptions = array ('None', 'Gallery', 'Plus', 'Featured');
		$galleryOptions = array();
		foreach ($availableGalleryOptions as $galleryOption) {
			$galleryOptions[$galleryOption] = GetLang('EbayGallery' . $galleryOption);
		}
		$this->template->assign('galleryOptions', $galleryOptions);

		// Listing enhancement
		$listingFeaturesObject = $getEbayDetailsXml->xpath('/GeteBayDetailsResponse/ListingFeatureDetails');
		$supportedListingFeatures = array('BoldTitle','Border','FeaturedFirst','FeaturedPlus','GiftIcon','Highlight','HomePageFeatured','ProPack');
		$listingFeatures = array();
		if (isset($listingFeaturesObject[0])) {
			foreach ($listingFeaturesObject[0] as $featureCode => $availability) {
				//@ToDo add support for PowerSellerOnly and TopRatedSellerOnly options
				if (!in_array($featureCode, $supportedListingFeatures) || $availability != 'Enabled') {
					continue;
				}

				$listingFeatures[$featureCode] = GetLang($featureCode);
			}
		}
		$this->template->assign('listingFeatures', $listingFeatures);

		// any defaults we should set
		$this->template->assign('quantityOption', 'one');
		$this->template->assign('useItemPhoto', true);

		$this->template->assign('locationCountry', GetCountryIdByName(GetConfig('CompanyCountry')));
		$this->template->assign('locationZip', GetConfig('CompanyZip'));
		$this->template->assign('locationCityState', GetConfig('CompanyCity') . ', ' . GetConfig('CompanyState'));

		$this->template->assign('reservePriceOption', 'ProductPrice');
		$this->template->assign('reservePriceCustom', $categoryOptions['minimum_reserve_price']);
		$this->template->assign('startPriceOption', 'ProductPrice');
		$this->template->assign('startPriceCustom', 0.01);
		$this->template->assign('buyItNowPriceOption', 'ProductPrice');
		$this->template->assign('buyItNowPriceCalcPrice', 10);
		$this->template->assign('buyItNowPriceCustom', 0.01);
		$this->template->assign('fixedBuyItNowPriceOption', 'ProductPrice');
		$this->template->assign('fixedBuyItNowPriceCustom', 0.01);

		$this->template->assign('auctionDuration', 'Days_7');
		$this->template->assign('fixedDuration', 'Days_7');

		$this->template->assign('useDomesticShipping', false);
		$this->template->assign('useInternationalShipping', false);
		$this->template->assign('useSalesTax', false);

		$this->template->assign('hitCounter', 'BasicStyle');

		$this->template->assign('galleryOption', 'Gallery');

		$this->template->assign('domesticFlatCount', 0);
		$this->template->assign('domesticCalcCount', 0);
		$this->template->assign('internationalFlatCount', 0);
		$this->template->assign('internationalCalcCount', 0);

		// assign template specific variables
		if ($templateId) {
			$template = new ISC_ADMIN_EBAY_TEMPLATE($templateId);

			$this->template->assign('currency', $template->getCurrency());

			// quantity
			if ($template->getQuantityToSell() == 1) {
				$quantityOption = 'one';
			}
			else {
				$quantityOption = 'more';
				$this->template->assign('moreQuantity', $template->getQuantityToSell());
			}
			$this->template->assign('quantityOption', $quantityOption);

			// item photo
			$this->template->assign('useItemPhoto', $template->getUseItemPhoto());

			// lot size
			$this->template->assign('lotSize', $template->getLotSize());

			// location details
			$this->template->assign('locationCountry', GetCountryIdByISO2($template->getItemLocationCountry()));
			$this->template->assign('locationZip', $template->getItemLocationZip());
			$this->template->assign('locationCityState', $template->getItemLocationCityState());

			// selling method
			$this->template->assign('sellingMethod', $template->getSellingMethod());

			if ($template->getSellingMethod() == self::CHINESE_AUCTION_LISTING) {
				// reserve price
				$this->template->assign('useReservePrice', $template->getReservePriceUsed());
				$reservePriceOption = 'ProductPrice';
				if ($template->getReservePriceUsed()) {
					$reservePriceOption = $template->getReservePriceOption();

					if ($reservePriceOption == 'PriceExtra') {
						$this->template->assign('reservePriceCalcPrice', $template->getReservePriceCalcPrice());
						$this->template->assign('reservePriceCalcOption', $template->getReservePriceCalcOption());
						$this->template->assign('reservePriceCalcOperator', $template->getReservePriceCalcOperator());
					}
					elseif ($reservePriceOption == 'CustomPrice') {
						$this->template->assign('reservePriceCustom', $template->getReservePriceCustomPrice());
					}
				}
				$this->template->assign('reservePriceOption', $reservePriceOption);

				// start price
				$startPriceOption = $template->getStartPriceOption();

				if ($startPriceOption == 'PriceExtra') {
					$this->template->assign('startPriceCalcPrice', $template->getStartPriceCalcPrice());
					$this->template->assign('startPriceCalcOption', $template->getStartPriceCalcOption());
					$this->template->assign('startPriceCalcOperator', $template->getStartPriceCalcOperator());
				}
				elseif ($startPriceOption == 'CustomPrice') {
					$this->template->assign('startPriceCustom', $template->getStartPriceCustomPrice());
				}
				$this->template->assign('startPriceOption', $startPriceOption);


				// buy it now price
				$this->template->assign('useBuyItNowPrice', $template->getBuyItNowPriceUsed());
				$buyItNowPriceOption = 'ProductPrice';
				if ($template->getBuyItNowPriceUsed()) {
					$buyItNowPriceOption = $template->getBuyItNowPriceOption();

					if ($buyItNowPriceOption == 'PriceExtra') {
						$this->template->assign('buyItNowPriceCalcPrice', $template->getBuyItNowPriceCalcPrice());
						$this->template->assign('buyItNowPriceCalcOption', $template->getBuyItNowPriceCalcOption());
						$this->template->assign('buyItNowPriceCalcOperator', $template->getBuyItNowPriceCalcOperator());
					}
					elseif ($buyItNowPriceOption == 'CustomPrice') {
						$this->template->assign('buyItNowPriceCustom', $template->getBuyItNowPriceCustomPrice());
					}
				}
				$this->template->assign('buyItNowPriceOption', $buyItNowPriceOption);

				$this->template->assign('auctionDuration', $template->getListingDuration());
			}
			else {
				// Fixed Price Item
				$fixedBuyItNowPriceOption = $template->getStartPriceOption();
				if ($fixedBuyItNowPriceOption == 'PriceExtra') {
					$this->template->assign('fixedBuyItNowPriceCalcPrice', $template->getStartPriceCalcPrice());
					$this->template->assign('fixedBuyItNowPriceCalcOption', $template->getStartPriceCalcOption());
					$this->template->assign('fixedBuyItNowPriceCalcOperator', $template->getStartPriceCalcOperator());
				}
				elseif ($fixedBuyItNowPriceOption == 'CustomPrice') {
					$this->template->assign('fixedBuyItNowPriceCustom', $template->getStartPriceCustomPrice());
				}

				$this->template->assign('fixedBuyItNowPriceOption', $fixedBuyItNowPriceOption);

				$this->template->assign('fixedDuration', $template->getListingDuration());
			}

			// payment details
			$this->template->assign('selectedPaymentMethods', $template->getPaymentMethods());
			$this->template->assign('paypalEmailAddress', $template->getPayPalEmailAddress());

			// domestic shipping
			$this->template->assign('useDomesticShipping', $template->getUseDomesticShipping());
			if ($template->getUseDomesticShipping()) {
				$settings = $template->getDomesticShippingSettings();
				$shippingType = $settings['cost_type'];
				$this->template->assign('domesticShippingCostType', $shippingType);

				$services = $template->getDomesticShippingServices();

				// flat options
				if ($shippingType == 'Flat') {
					$this->template->assign('domesticFlatShippingServices', $services);
					$this->template->assign('domesticFlatCount', count($services));
				}
				// calculated options
				else {
					$service = current($services);

					$this->template->assign('domesticPackageType', $settings['package_type']);
					$this->template->assign('domesticCalculatedShippingServices', $services);
					$this->template->assign('domesticCalcCount', count($services));
				}

				$this->template->assign('domesticFreeShipping', $settings['is_free_shipping']);
				$this->template->assign('domesticGetItFast', $settings['get_it_fast']);
				$this->template->assign('domesticLocalPickup', $settings['offer_pickup']);
				$this->template->assign('domesticHandlingCost', $settings['handling_cost']);
			}

			// international shipping
			$this->template->assign('useInternationalShipping', $template->getUseInternationalShipping());
			if ($template->getUseInternationalShipping()) {
				$settings = $template->getInternationalShippingSettings();
				$shippingType = $settings['cost_type'];
				$this->template->assign('internationalShippingCostType', $shippingType);

				$services = $template->getInternationalShippingServices();

				// flat options
				if ($shippingType == 'Flat') {
					$this->template->assign('internationalFlatShippingServices', $services);
					$this->template->assign('internationalFlatCount', count($services));
				}
				// calculated options
				else {
					$service = current($services);

					$this->template->assign('internationalPackageType', $settings['package_type']);
					$this->template->assign('internationalCalculatedShippingServices', $services);
					$this->template->assign('internationalCalcCount', count($services));
				}

				$this->template->assign('internationalFreeShipping', $settings['is_free_shipping']);
				$this->template->assign('internationalHandlingCost', $settings['handling_cost']);
			}

			// other shipping
			$this->template->assign('handlingTime', $template->getHandlingTime());
			$this->template->assign('useSalesTax', $template->getUseSalesTax());
			$this->template->assign('salesTaxState', $template->getSalesTaxState());
			$this->template->assign('salesTaxPercent', $template->getSalesTaxPercent());
			$this->template->assign('salesTaxIncludesShipping', $template->getShippingIncludedInTax());

			// other details
			$this->template->assign('checkoutInstructions', $template->getCheckoutInstructions());
			$this->template->assign('acceptReturns', $template->getReturnsAccepted());
			$this->template->assign('returnOfferedAs', $template->getReturnOfferedAs());
			$this->template->assign('returnsPeriod', $template->getReturnsPeriod());
			$this->template->assign('returnCostPaidBy', $template->getReturnCostPaidBy());
			$this->template->assign('additionalPolicyInfo', $template->getAdditionalPolicyInfo());

			$this->template->assign('hitCounter', $template->getCounterStyle());

			$this->template->assign('galleryOption', $template->getGalleryType());

			$this->template->assign('selectedListingFeatures', $template->getListingFeatures());
		}

		return $this->template->render('ebay.template.form.details.tpl');
	}
Ejemplo n.º 12
0
 /**
  * Create the pending order in the database with the customers selected payment details, etc.
  *
  * @return array An array containing information about what needs to be done next.
  */
 public function SavePendingOrder()
 {
     $provider = null;
     $verifyPaymentProvider = true;
     $redirectToFinishOrder = false;
     $providerId = '';
     $pendingOrderResult = array();
     if (!isset($_SESSION['CHECKOUT']['PENDING_DATA'])) {
         return false;
     }
     // Did they agree to signup to any mailing lists?
     if (isset($_POST['join_mailing_list'])) {
         ISC_SetCookie("JOIN_MAILING_LIST", 1, time() + 3600 * 24 * 7);
     }
     if (isset($_POST['join_order_list'])) {
         ISC_SetCookie("JOIN_ORDER_LIST", 1, time() + 3600 * 24 * 7);
     }
     $orderTotal = $_SESSION['CHECKOUT']['PENDING_DATA']['ORDER_TOTAL'];
     $giftCertificateAmount = $_SESSION['CHECKOUT']['PENDING_DATA']['GIFTCERTIFICATE_AMOUNT'];
     $gatewayAmount = $_SESSION['CHECKOUT']['PENDING_DATA']['GATEWAY_AMOUNT'];
     $creditUsed = 0;
     $giftCertificates = array();
     // Find out what currency we are using. We'll need this later to display their previous orders in the currency that they have selected
     $selectedCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);
     if (isset($_SESSION['OFFERCART']['GIFTCERTIFICATES']) && is_array($_SESSION['OFFERCART']['GIFTCERTIFICATES'])) {
         $giftCertificates = $_SESSION['OFFERCART']['GIFTCERTIFICATES'];
         // Now we check that the gift certificates can actually be applied to the order
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $badCertificates = array();
         $remainingBalance = 0;
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->GiftCertificatesApplicableToOrder($orderTotal, $giftCertificates, $remainingBalance, $badCertificates);
         // One or more gift certificates were invalid so this order is now invalid
         if (count($badCertificates) > 0) {
             $badCertificatesList = '<strong>' . GetLang('BadGiftCertificates') . '</strong><ul>';
             foreach ($badCertificates as $code => $reason) {
                 if (is_array($reason) && $reason[0] == "expired") {
                     $reason = sprintf(GetLang('BadGiftCertificateExpired'), CDate($reason[1]));
                 } else {
                     $reason = GetLang('BadGiftCertificate' . ucfirst($reason));
                 }
                 $badCertificatesList .= sprintf("<li>%s - %s", isc_html_escape($code), $reason);
             }
             $badCertificatesList .= "</ul>";
             $pendingOrderResult = array('error' => GetLang('OrderContainedInvalidGiftCertificates'), 'errorDetails' => $badCertificatesList);
             return $pendingOrderResult;
         } else {
             if ($orderTotal == $giftCertificateAmount && $remainingBalance > 0) {
                 $pendingOrderResult = array('error' => GetLang('OrderTotalStillRemainingCertificates'));
                 return $pendingOrderResult;
             } else {
                 if ($orderTotal == $giftCertificateAmount) {
                     $providerId = 'giftcertificate';
                     $verifyPaymentProvider = false;
                     $redirectToFinishOrder = true;
                 }
             }
         }
     }
     // If the order total is 0, then we just forward the user on to the "Thank You" page and set the payment provider to ''
     if ($orderTotal == 0) {
         $providerId = '';
         $verifyPaymentProvider = false;
         $redirectToFinishOrder = true;
     }
     if ($verifyPaymentProvider) {
         if (isset($_POST['credit_checkout_provider']) && $_POST['credit_checkout_provider'] != "") {
             $_POST['checkout_provider'] = $_POST['credit_checkout_provider'];
         }
         $selected_provider = "";
         $providers = GetCheckoutModulesThatCustomerHasAccessTo(true);
         // If there's more than one, use the value they've chosen
         if (count($providers) > 1 && isset($_POST['checkout_provider']) || isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
             $selected_provider = $_POST['checkout_provider'];
         } else {
             if (count($providers) == 1) {
                 $selected_provider = $providers[0]['object']->GetId();
                 $_POST['checkout_provider'] = $selected_provider;
             } else {
                 $selected_provider = '';
             }
         }
         if (!isset($_POST['checkout_provider'])) {
             $_POST['checkout_provider'] = '';
         }
         // Are we using our store credit?
         $GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
         $customer = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerDataByToken();
         if (isset($_POST['store_credit']) && $_POST['store_credit'] == 1 && $customer['custstorecredit'] > 0) {
             // User has not chosen a payment provider and can't afford this order using only store credit, throw back as error
             if (!$_POST['checkout_provider'] && $customer['custstorecredit'] < $orderTotal) {
                 return false;
             } else {
                 $onlyCredit = false;
                 $updateExtra = '';
                 // If we're only using store credit
                 $creditToUse = $orderTotal - $giftCertificateAmount;
                 if ($customer['custstorecredit'] >= $creditToUse) {
                     // Set the checkout provider
                     $providerId = 'storecredit';
                     $verifyPaymentProvider = false;
                     $redirectToFinishOrder = true;
                     $creditUsed = $creditToUse;
                     $onlyCredit = true;
                 } else {
                     // Using all of our store credit to pay for this order and we owe more.
                     $creditUsed = $customer['custstorecredit'];
                     $gatewayAmount -= $creditUsed;
                 }
             }
         }
     }
     // Now with round 2, do we still need to verify the payment provider?
     if ($verifyPaymentProvider) {
         // If there's more than one provider and one wasn't selected on the order confirmation screen then there's a problem
         if ((count($providers) == 0 || count($providers) > 1 && !isset($_POST['checkout_provider'])) && !isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
             return false;
         }
         // Is the payment provider selected actually valid?
         if (!GetModuleById('checkout', $provider, $selected_provider)) {
             return false;
         }
         $providerId = $provider->GetId();
     }
     // Load up all of the data for the items in the cart
     $GLOBALS['ISC_CLASS_MAKEAOFFER'] = GetClass('ISC_MAKEAOFFER');
     $cartItems = $GLOBALS['ISC_CLASS_MAKEAOFFER']->api->GetProductsInCart();
     // OK, we're successful down to here - do they want to create an account?
     if (isset($_SESSION['CHECKOUT']['CREATE_ACCOUNT'])) {
         $accountDetails = $_SESSION['CHECKOUT']['ACCOUNT_DETAILS'];
         $token = GenerateCustomerToken();
         $customerData = array('email' => trim($accountDetails['email']), 'password' => $accountDetails['password'], 'firstname' => $accountDetails['firstname'], 'lastname' => $accountDetails['lastname'], 'company' => $accountDetails['company'], 'phone' => $accountDetails['phone'], 'token' => $token);
         //alandy modify.2011-5-20.
         /*$sql="select customerid from [|PREFIX|]customers where custconemail='".$accountDetails['email']."'";
         		$query=$GLOBALS['ISC_CLASS_DB']->Query($sql);
         		while($rs=$GLOBALS['ISC_CLASS_DB']->Fetch($query)){
         		    $GLOBALS['Hasemailflag']="yes";
         		      return array(
         				    'error' => GetLang('AccountInternalError')
         			    );
         			    
         	        }*/
         $cusquery = "SELECT customerid\n\t\t\t\tFROM [|PREFIX|]customers\n\t\t\t\tWHERE isguest = 1 AND LOWER(custconemail)='" . $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($customerData['email'])) . "'";
         $cusresult = $GLOBALS['ISC_CLASS_DB']->Query($cusquery);
         $cusrow = $GLOBALS['ISC_CLASS_DB']->Fetch($cusresult);
         $custId = $cusrow['customerid'];
         if ($custId == '') {
             // 20110613 johnny add ---- add flag for guest user email don't exist
             if ($_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
                 $customerData['isguest'] = 1;
             }
             $customerId = $GLOBALS['ISC_CLASS_CUSTOMER']->CreateCustomerAccount($customerData, false, $accountDetails['autoAccount']);
         } else {
             if (!$_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
                 $customerId = $GLOBALS['ISC_CLASS_CUSTOMER']->CreateCustomerAccount($customerData, true, $accountDetails['autoAccount']);
                 /* delet already exist guest account
                 			$entity = new ISC_ENTITY_CUSTOMER();
                 			$entity->delete($custId);
                 			*/
             } else {
                 $customerId = $custId;
                 // update guest account in customer table for guest user email exist
                 $GLOBALS['ISC_CLASS_DB']->Query("UPDATE [|PREFIX|]customers SET custconfirstname = '" . $customerData['firstname'] . "', custconlastname = '" . $customerData['lastname'] . "' WHERE customerid = {$customerId}");
             }
         }
         if (!$customerId) {
             return array('error' => GetLang('AccountInternalError'));
         }
         if (!$_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
             $GLOBALS['ISC_CLASS_CUSTOMER']->LoginCustomerById($customerId, true);
         }
         unset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']);
         unset($_SESSION['CHECKOUT']['ACCOUNT_DETAILS']);
         // Log the customer in
         @ob_end_clean();
     }
     if (isset($_COOKIE['SHOP_TOKEN'])) {
         $customerToken = $_COOKIE['SHOP_TOKEN'];
     } else {
         $customerToken = '';
     }
     $orderComments = '';
     if (isset($_REQUEST['ordercomments'])) {
         $orderComments = $_REQUEST['ordercomments'];
     }
     $checkoutSession = $_SESSION['CHECKOUT'];
     $pendingData = $checkoutSession['PENDING_DATA'];
     // Get a list of the vendors for all of the items in the cart, and loop through them
     // to build all of the pending orders
     $cartContent = $this->BreakdownCartByAddressVendorforshipping();
     //Changed to merging function by Simha
     $vendorOrderInfo = array();
     foreach ($cartContent as $vendorId => $addresses) {
         foreach ($addresses as $addressId => $products) {
             $allDigital = 1;
             $productArray = array();
             foreach ($products as $cartItemId => $product) {
                 // A physical product, mark as so
                 if ($product['data']['prodtype'] == PT_PHYSICAL) {
                     $allDigital = 0;
                 }
                 // Mark the quantity of this item
                 $productArray[$cartItemId] = $product['quantity'];
             }
             $vendorInfo = $pendingData['VENDORS'][$vendorId . '_' . $addressId];
             $vendorData = array('itemtotal' => $vendorInfo['ITEM_TOTAL'], 'taxcost' => $vendorInfo['TAX_COST'], 'taxname' => $vendorInfo['TAX_NAME'], 'taxrate' => $vendorInfo['TAX_RATE'], 'totalcost' => $vendorInfo['ORDER_TOTAL'], 'shippingcost' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['COST'], 'handlingcost' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['HANDLING'], 'shippingprovider' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['PROVIDER'], 'shippingmodule' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['MODULE'], 'isdigitalorder' => $allDigital, 'products' => $productArray);
             if ($addressId == 0) {
                 $addresses = $this->GetOrderShippingAddresses();
                 $vendorData['shippingaddress'] = $addresses[$addressId];
             } else {
                 $vendorData['shippingaddressid'] = $addressId;
             }
             // Shipping zones can be configured per vendor, so we need to be sure
             // to pass this along correctly too
             if (isset($vendorInfo['SHIPPING_ZONE'])) {
                 $shippingZone = GetShippingZoneById($vendorInfo['SHIPPING_ZONE']);
                 if (is_array($shippingZone)) {
                     $vendorData['ordshippingzoneid'] = $shippingZone['zoneid'];
                     $vendorData['ordshippingzone'] = $shippingZone['zonename'];
                 }
             }
             $vendorOrderInfo[$vendorId . '_' . $addressId] = $vendorData;
         }
     }
     // Set some defaults about the rest of the order
     $pendingOrder = array("customertoken" => $customerToken, 'paymentmethod' => $providerId, "storecreditamount" => $creditUsed, "giftcertificateamount" => $giftCertificateAmount, "giftcertificates" => $giftCertificates, "gatewayamount" => $gatewayAmount, 'totalincludestax' => $pendingData['TAX_INCLUDED'], "currencyid" => $selectedCurrency['currencyid'], "currencyexchangerate" => $selectedCurrency['currencyexchangerate'], 'ordercomments' => $orderComments, 'ipaddress' => GetIP(), 'vendorinfo' => $vendorOrderInfo);
     if (isset($customerId)) {
         $pendingOrder['customerid'] = $customerId;
     }
     // Determine the address ID we're using for billing
     if (is_array($_SESSION['CHECKOUT']['BILLING_ADDRESS'])) {
         $pendingOrder['billingaddress'] = $_SESSION['CHECKOUT']['BILLING_ADDRESS'];
     } else {
         $pendingOrder['billingaddressid'] = (int) $_SESSION['CHECKOUT']['BILLING_ADDRESS'];
     }
     if (isset($_POST['ordermessage'])) {
         $pendingOrder['ordermessage'] = $_POST['ordermessage'];
     } else {
         $pendingOrder['ordermessage'] = '';
     }
     /**
      * Save our custom fields. If we are creating a new account then split this up so the
      * account fields will go in the customers table and the rest will go in the orders table
      */
     if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['customer']) && isset($customerId) && isId($customerId)) {
         $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['customer']);
         if (isId($formSessionId)) {
             $updateData = array('customerid' => $customerId, 'email' => $customerData['email'], 'firstname' => $customerData['firstname'], 'lastname' => $customerData['lastname'], 'company' => $customerData['company'], 'phone' => $customerData['phone'], 'custformsessionid' => $formSessionId);
             $entity = new ISC_ENTITY_CUSTOMER();
             $entity->edit($updateData);
         }
     }
     /**
      * OK, now to store the custom address fields. Check here to see if we are not split
      * shipping (single order)
      */
     if (!isset($_SESSION['CHECKOUT']['IS_SPLIT_SHIPPING']) || !$_SESSION['CHECKOUT']['IS_SPLIT_SHIPPING']) {
         $pendingOrder['ordformsessionid'] = '';
         if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS'])) {
             /**
              * Save the billing
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && isset($pendingOrder['billingaddress']['saveAddress']) && $pendingOrder['billingaddress']['saveAddress']) {
                 $pendingOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']);
             }
             /**
              * Now for the shipping. Only save this once for all the shipping addresses
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'])) {
                 $shippSessId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping']);
                 foreach ($pendingOrder['vendorinfo'] as $vendorId => $vendorData) {
                     if (isset($vendorData['shippingaddress']['saveAddress']) && $vendorData['shippingaddress']['saveAddress']) {
                         $pendingOrder['vendorinfo'][$vendorId]['shippingaddress']['shipformsessionid'] = $shippSessId;
                     }
                 }
             }
             /**
              * Now the orders. This part is tricky because the billing and shipping information
              * have the same keys (same fields used in the frontend). We need to split them up
              * into separate billing and shipping information and then save it
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'])) {
                 /**
                  * We create a map first so we can map the shipping information to its proper field
                  * ID
                  */
                 $billingKeys = array_keys($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']);
                 $fieldAddressMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_BILLING, $billingKeys);
                 /**
                  * OK, we have the map, now to split up the custom fields
                  */
                 $orderSessData = array();
                 foreach ($fieldAddressMap as $fieldId => $newShippingFieldId) {
                     $orderSessData[$fieldId] = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'][$fieldId];
                     if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'][$fieldId])) {
                         $orderSessData[$newShippingFieldId] = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'][$fieldId];
                     }
                 }
                 $pendingOrder['ordformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($orderSessData);
             }
         }
         /**
          * This is for split shipping. Loop through each address to get their default custom
          * field data, combine it with the billing custom field data, create the form session
          * record and then save that ID for each address
          */
     } else {
         $shippingAddresses = $this->GetOrderShippingAddresses();
         $origFormSessionData = array();
         if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'])) {
             $origFormSessionData = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'];
         }
         foreach ($pendingOrder['vendorinfo'] as $vendorId => $vendorData) {
             $address = null;
             $orderSessData = array();
             if (array_key_exists($vendorData['shippingaddressid'], $shippingAddresses)) {
                 $address = $shippingAddresses[$vendorData['shippingaddressid']];
             }
             if (isset($address['shipformsessionid']) && isId($address['shipformsessionid'])) {
                 $shippingSessionData = $GLOBALS['ISC_CLASS_FORM']->getSavedSessionData($address['shipformsessionid']);
                 if (is_array($shippingSessionData)) {
                     /**
                      * Same deal with this save session data because the billing and shipping data
                      * use the same fields and therefore have the same keys
                      */
                     $billingKeys = array_keys($origFormSessionData);
                     $fieldAddressMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_BILLING, $billingKeys);
                     /**
                      * OK, we have the map, now to split up the custom fields
                      */
                     $orderSessData = array();
                     foreach ($fieldAddressMap as $fieldId => $newShippingFieldId) {
                         $orderSessData[$fieldId] = $origFormSessionData[$fieldId];
                         $orderSessData[$newShippingFieldId] = $shippingSessionData[$fieldId];
                     }
                 }
             }
             $newFormSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($orderSessData);
             if (isId($newFormSessionId)) {
                 $pendingOrder['vendorinfo'][$vendorId]['ordformsessionid'] = $newFormSessionId;
             }
         }
     }
     $pendingToken = CreateOrder($pendingOrder, $cartItems);
     // Try to add the record and if we can't then take them back to the shopping cart
     if (!$pendingToken) {
         return false;
     }
     // Persist the pending order token as a cookie for 24 hours
     ISC_SetCookie("SHOP_ORDER_TOKEN", $pendingToken, time() + 3600 * 24, true);
     $_COOKIE['SHOP_ORDER_TOKEN'] = $pendingToken;
     // Redirecting to finish order page?
     if ($redirectToFinishOrder) {
         return array('redirectToFinishOrder' => true);
     }
     $orderData = LoadPendingOrdersByToken($pendingToken);
     // Otherwise, the gateway want's to do something
     $provider->SetOrderData($orderData);
     // Is this an online payment provider? It would like to do something
     if ($provider->GetPaymentType() == PAYMENT_PROVIDER_ONLINE || method_exists($provider, "ShowPaymentForm")) {
         // Call the checkout process for the selected provider
         if (method_exists($provider, "ShowPaymentForm")) {
             return array('provider' => $provider, 'showPaymentForm' => true);
         } else {
             return array('provider' => $provider);
         }
     } else {
         return array('provider' => $provider);
     }
 }