Page MenuHomeIn-Portal Phabricator

in-commerce
No OneTemporary

File Metadata

Created
Wed, Feb 26, 11:03 PM

in-commerce

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: branches/5.1.x/units/gateways/gw_classes/paymentech.php
===================================================================
--- branches/5.1.x/units/gateways/gw_classes/paymentech.php (revision 13464)
+++ branches/5.1.x/units/gateways/gw_classes/paymentech.php (revision 13465)
@@ -1,311 +1,313 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
$class_name = 'kPaymentechGW'; // for automatic installation
class kPaymentechGW extends kGWBase
{
function InstallData()
{
$data = array(
'Gateway' => Array('Name' => 'Patmentech/Orbital', 'ClassName' => 'kPaymentechGW', 'ClassFile' => 'paymentech.php', 'RequireCCFields' => 1),
'ConfigFields' => Array(
'submit_url' => Array('Name' => 'Submit URL', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'user_account' => Array('Name' => 'Merchant ID', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'user_bin' => Array('Name' => 'BIN Number', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'shipping_control' => Array('Name' => 'Shipping Control', 'Type' => 'select', 'ValueList' => '3=la_CreditDirect,4=la_CreditPreAuthorize', 'Default' => '3'),
'deny_cvv' => Array('Name' => 'Decline the following CVV response codes (ex: N,P)', 'Type' => 'text', 'ValueList' => '', 'Default' => 'N,P,S'),
'deny_avs' => Array('Name' => 'Decline the following AVS response codes (ex: 1,3,R,5,6,G)', 'Type' => 'text', 'ValueList' => '', 'Default' => '1,2,3,4,R,5,6,7,8,A,C,D,E,F,G,Z'),
)
);
return $data;
}
function DirectPayment($item_data, $gw_params)
{
// if( $this->IsTestMode() ) $post_fields['x_test_request'] = 'True';
$data = array(
//sys default
'TzCode' => 705,
'CurrencyCode' => 840,
'CurrencyExponent' => 2,
'TxDateTime' => '', //gateway will set current timestamp
//merchant info
'MerchantID' => $gw_params['user_account'],
'BIN' => $gw_params['user_bin'],
//transaction
// A - Authorize Only // AC - Authorize & Capture // C - Prior Auth Capture
'MessageType' => $gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH ? 'A' : 'AC',
'Amount' => str_replace('.', '', sprintf('%.2f', $item_data['TotalAmount'])),
'AccountNum' => $item_data['PaymentAccount'], //card num
'Exp' => str_replace('/', '', $item_data['PaymentCCExpDate']), //expiration
'CardSecVal' => $item_data['PaymentCVV2'], //cvv2
//customer info
'AVSname' => $item_data['PaymentNameOnCard'],
'AVSaddress1' => $item_data['BillingAddress1'],
'AVSaddress2' => $item_data['BillingAddress2'],
'AVScity' => $item_data['BillingCity'],
'AVSstate' => $item_data['BillingState'],
'AVSzip' => $item_data['BillingZip'],
// order info
'OrderID' => $item_data['OrderNumber'],
'ECOrderNum' => $item_data['OrderNumber'],
'Comments' => 'Invoice #'.$item_data['OrderNumber'],
'ShippingRef' => '',
);
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
- $data['AVScountryCode'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $data['AVScountryCode'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
if ($data['AVScountryCode'] != 'US') {
$data['AVSstate'] = '';
}
$headers = Array(
'POST /AUTHORIZE HTTP/1.0',
'MIME-Version: 1.0',
'Content-type: application/PTI34',
'Content-transfer-encoding: text',
'Request-number: 1',
'Document-type: Request'
);
$xml = $this->PrepareXML($data);
$this->gw_responce = curl_post($gw_params['submit_url'], $xml, $headers);
$gw_responce = $this->parseGWResponce(null, $gw_params);
$this->CheckCVV_AVS($gw_params);
return ($this->parsed_responce['ProcStatus'] != 0 || $this->parsed_responce['ApprovalStatus'] != 1) ? false : true;
}
function CheckCVV_AVS($gw_params)
{
$cvv_reject = explode(',', $gw_params['deny_cvv']);
if (in_array(trim($this->parsed_responce['CVV2RespCode']), $cvv_reject)) {
$this->parsed_responce['ApprovalStatus'] = 0;
}
$avs_reject = explode(',', $gw_params['deny_avs']);
if (in_array(trim($this->parsed_responce['AVSRespCode']), $avs_reject)) {
$this->parsed_responce['ApprovalStatus'] = 0;
}
}
/**
* Perform SALE type transaction direct from php script wihtout redirecting to 3rd-party website
*
* @param Array $item_data
* @param Array $gw_params
* @return bool
*/
function Charge($item_data, $gw_params)
{
$gw_responce = unserialize( $item_data['GWResult1'] );
if( ( strtoupper($gw_responce['MessageType']) == 'A') )
{
$data = array(
//sys default
'TzCode' => 705,
'CurrencyCode' => 840,
'CurrencyExponent' => 2,
'TxDateTime' => '', //gateway will set current timestamp
//merchant info
'MerchantID' => $gw_params['user_account'],
'BIN' => $gw_params['user_bin'],
//transaction
// A - Authorize Only // AC - Authorize & Capture // C - Prior Auth Capture
'Amount' => str_replace('.', '', sprintf('%.2f', $item_data['TotalAmount'])),
'MessageType' => 'C',
'OrderID' => $gw_responce['OrderID'],
'TxRefNum' => $gw_responce['TxRefNum'],
);
$headers = Array(
'POST /AUTHORIZE HTTP/1.0',
'MIME-Version: 1.0',
'Content-type: application/PTI34',
'Content-transfer-encoding: text',
'Request-number: 1',
'Document-type: Request'
);
$xml = $this->PrepareXML($data);
$this->gw_responce = curl_post($gw_params['submit_url'], $xml, $headers);
$gw_responce = $this->parseGWResponce(null, $gw_params);
return ($gw_responce['ProcStatus'] != 0 || $gw_responce['ApprovalStatus'] != 1) ? false : true;
}
else
{
return true;
}
}
/**
* Parse previosly saved gw responce into associative array
*
* @param string $gw_responce
* @param Array $gw_params
* @return Array
*/
function parseGWResponce($gw_responce = null, $gw_params)
{
if( !isset($gw_responce) ) $gw_responce = $this->gw_responce;
$parser =& $this->Application->recallObject('kXMLHelper');
$parser->Clear();
$res = $parser->Parse($gw_responce);
$parsed = array();
$parsed['ProcStatus'] = $res->FindChildValue('ProcStatus');
$parsed['StatusMsg'] = $res->FindChildValue('StatusMsg');
$parsed['ApprovalStatus'] = $res->FindChildValue('ApprovalStatus');
$parsed['RespCode'] = $res->FindChildValue('RespCode');
$parsed['AuthCode'] = $res->FindChildValue('AuthCode');
$parsed['AVSRespCode'] = $res->FindChildValue('AVSRespCode');
$parsed['CVV2RespCode'] = $res->FindChildValue('CVV2RespCode');
$parsed['StatusMsg'] = $res->FindChildValue('StatusMsg');
$parsed['RespMsg'] = $res->FindChildValue('RespMsg');
$parsed['TxRefNum'] = $res->FindChildValue('TxRefNum');
$parsed['TxRefIdx'] = $res->FindChildValue('TxRefIdx');
$parsed['RespTime'] = $res->FindChildValue('RespTime');
$parsed['Amount'] = $res->FindChildValue('Amount');
$parsed['OrderID'] = $res->FindChildValue('OrderNumber');
$parsed['MessageType'] = $res->FindChildValue('CommonMandatoryResponse', 'MessageType');
$this->parsed_responce = $parsed;
return $parsed;
}
function getErrorMsg()
{
$code = $this->parsed_responce['ApprovalStatus'];
switch ($this->parsed_responce['ApprovalStatus']) {
case '0':
return 'The transaction has been declined';
case '1':
return 'The transaction has been approved';
default:
return 'An error has occured while processing the transaction ('.$this->parsed_responce['StatusMsg'].')';
}
}
function getGWResponce()
{
return serialize($this->parsed_responce);
}
function GetTestCCNumbers()
{
return array('4012888888881', '4055011111111111', '5454545454545454', '5405222222222226', '371449635398431',
'6011000995500000', '36438999960016', '3566002020140006');
}
function PrepareXML($data)
{
if ($data['MessageType'] == 'A' ||
$data['MessageType'] == 'AC') {
$xml = <<<END_XML
<?xml version="1.0" encoding="UTF-8"?>
<Request>
<AC>
<CommonData>
<CommonMandatory AuthOverrideInd="N" LangInd="00" CardHolderAttendanceInd="01" HcsTcsInd="T" TxCatg="7" MessageType="{$data['MessageType']}" Version="2" TzCode="{$data['TzCode']}">
<AccountNum AccountTypeInd="91">{$data['AccountNum']}</AccountNum>
<POSDetails POSEntryMode="01"/>
<MerchantID>{$data['MerchantID']}</MerchantID>
<TerminalID TermEntCapInd="05" CATInfoInd="06" TermLocInd="01" CardPresentInd="N" POSConditionCode="59" AttendedTermDataInd="01">001</TerminalID>
<BIN>{$data['BIN']}</BIN>
<OrderID>{$data['OrderID']}</OrderID>
<AmountDetails>
<Amount>{$data['Amount']}</Amount>
</AmountDetails>
<TxTypeCommon TxTypeID="G"/>
<Currency CurrencyCode="{$data['CurrencyCode']}" CurrencyExponent="{$data['CurrencyExponent']}"/>
<CardPresence>
<CardNP>
<Exp>{$data['Exp']}</Exp>
</CardNP>
</CardPresence>
<TxDateTime>{$data['TxDateTime']}</TxDateTime>
</CommonMandatory>
<CommonOptional>
<Comments>{$data['Comments']}</Comments>
<ShippingRef>{$data['ShippingRef']}</ShippingRef>
<CardSecVal>{$data['CardSecVal']}</CardSecVal>
<ECommerceData ECSecurityInd="07">
<ECOrderNum>{$data['ECOrderNum']}</ECOrderNum>
</ECommerceData>
</CommonOptional>
</CommonData>
<Auth>
<AuthMandatory FormatInd="H"/>
<AuthOptional>
<AVSextended>
<AVSname>{$data['AVSname']}</AVSname>
<AVSaddress1>{$data['AVSaddress1']}</AVSaddress1>
<AVSaddress2>{$data['AVSaddress2']}</AVSaddress2>
<AVScity>{$data['AVScity']}</AVScity>
<AVSstate>{$data['AVSstate']}</AVSstate>
<AVSzip>{$data['AVSzip']}</AVSzip>
</AVSextended>
</AuthOptional>
</Auth>
<Cap>
<CapMandatory>
<EntryDataSrc>02</EntryDataSrc>
</CapMandatory>
<CapOptional/>
</Cap>
</AC>
</Request>
END_XML;
}
elseif ($data['MessageType'] == 'C') {
$xml = <<<END_XML
<?xml version="1.0" encoding="UTF-8" ?>
<Request>
<AC>
<CommonData>
<CommonMandatory MessageType="{$data['MessageType']}">
<MerchantID>{$data['MerchantID']}</MerchantID>
<TerminalID>001</TerminalID>
<BIN>{$data['BIN']}</BIN>
<OrderID>{$data['OrderID']}</OrderID>
<AmountDetails>
<Amount>{$data['Amount']}</Amount>
</AmountDetails>
<TxDateTime>{$data['TxDateTime']}</TxDateTime>
</CommonMandatory>
<CommonOptional>
<TxRefNum>{$data['TxRefNum']}</TxRefNum>
</CommonOptional>
</CommonData>
</AC>
</Request>
END_XML;
}
return $xml;
}
}
\ No newline at end of file
Index: branches/5.1.x/units/gateways/gw_classes/paypal_direct.php
===================================================================
--- branches/5.1.x/units/gateways/gw_classes/paypal_direct.php (revision 13464)
+++ branches/5.1.x/units/gateways/gw_classes/paypal_direct.php (revision 13465)
@@ -1,229 +1,231 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
$class_name = 'kGWPaypalDirect'; // for automatic installation
class kGWPaypalDirect extends kGWBase
{
function InstallData()
{
$data = array(
'Gateway' => Array('Name' => 'PayPal Pro', 'ClassName' => 'kGWPaypalDirect', 'ClassFile' => 'paypal_direct.php', 'RequireCCFields' => 1),
'ConfigFields' => Array(
'submit_url' => Array('Name' => 'Submit URL', 'Type' => 'text', 'ValueList' => '', 'Default' => 'https://api-3t.paypal.com/nvp'),
'api_username' => Array('Name' => 'PayPal Pro API Username', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'api_password' => Array('Name' => 'PayPal Pro API Password', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'signature' => Array('Name' => 'PayPal Pro API Signature', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'shipping_control' => Array('Name' => 'Shipping Control', 'Type' => 'select', 'ValueList' => '3=la_CreditDirect', 'Default' => '3'),
)
);
return $data;
}
function DirectPayment($item_data, $gw_params)
{
$post_fields = Array();
// -- Login Information --
$post_fields['METHOD'] = 'DoDirectPayment';
$post_fields['VERSION'] = '52.0';
$post_fields['IPADDRESS'] = $_SERVER['REMOTE_ADDR'];
$post_fields['USER'] = $gw_params['api_username'];
$post_fields['PWD'] = $gw_params['api_password'];
$post_fields['SIGNATURE'] = $gw_params['signature'];
$post_fields['PAYMENTACTION'] = 'Sale';
$post_fields['AMT'] = sprintf('%.2f', $item_data['TotalAmount']);
switch ($item_data['PaymentCardType']) {
case 1:
$post_fields['CREDITCARDTYPE'] = 'Visa';
break;
case 2:
$post_fields['CREDITCARDTYPE'] = 'MasterCard';
break;
case 3:
$post_fields['CREDITCARDTYPE'] = 'Amex';
break;
case 4:
$post_fields['CREDITCARDTYPE'] = 'Discover';
break;
default:
$this->parsed_responce['responce_reason_text'] = 'Invalid Credit Card Type';
return false;
}
$post_fields['ACCT'] = $item_data['PaymentAccount'];
$date_parts = explode('/', $item_data['PaymentCCExpDate']);
$post_fields['EXPDATE'] = $date_parts[0].'20'.$date_parts[1];
$post_fields['CVV2'] = $item_data['PaymentCVV2'];
$names = explode(' ', $item_data['PaymentNameOnCard'], 2);
$post_fields['FIRSTNAME'] = getArrayValue($names, 0);
$post_fields['LASTNAME'] = getArrayValue($names, 1);
$post_fields['STREET'] = $item_data['BillingAddress1'];
$post_fields['STREET2'] = $item_data['BillingAddress2'];
$post_fields['CITY'] = $item_data['BillingCity'];
$post_fields['STATE'] = $item_data['BillingState'];
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
- $post_fields['COUNTRYCODE'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
+
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $post_fields['COUNTRYCODE'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$post_fields['ZIP'] = $item_data['BillingZip'];
$post_fields['INVNUM'] = $item_data['OrderNumber'];
$post_fields['CUSTOM'] = $item_data['PortalUserId'];
/*
$post_fields['x_encap_char'] = $gw_params['encapsulate_char'];
$post_fields['x_relay_response'] = 'False';
$post_fields['x_type'] = $gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH ? 'AUTH_ONLY' : 'AUTH_CAPTURE';
$post_fields['x_login'] = $gw_params['user_account'];
$post_fields['x_tran_key'] = $gw_params['transaction_key'];
if( $this->IsTestMode() ) $post_fields['x_test_request'] = 'True';
// -- Payment Details --
$names = explode(' ', $item_data['PaymentNameOnCard'], 2);
$post_fields['x_first_name'] = getArrayValue($names, 0);
$post_fields['x_last_name'] = getArrayValue($names, 1);
$post_fields['x_amount'] = sprintf('%.2f', $item_data['TotalAmount']);
$post_fields['x_company'] = $item_data['BillingCompany'];
$post_fields['x_card_num'] = $item_data['PaymentAccount'];
$post_fields['x_card_code'] = $item_data['PaymentCVV2'];
$post_fields['x_exp_date'] = $item_data['PaymentCCExpDate'];
$post_fields['x_address'] = $item_data['BillingAddress1'].' '.$item_data['BillingAddress2'];
$post_fields['x_city'] = $item_data['BillingCity'];
$post_fields['x_state'] = $item_data['BillingState'];
$post_fields['x_zip'] = $item_data['BillingZip'];
$recurring = getArrayValue($item_data, 'IsRecurringBilling') ? 'YES' : 'NO';
$post_fields['x_recurring_billing'] = $recurring;
$billing_email = $item_data['BillingEmail'];
if (!$billing_email) {
$billing_email = $this->Conn->GetOne(' SELECT Email FROM '.$this->Application->getUnitOption('u', 'TableName').'
WHERE PortalUserId = '.$this->Application->RecallVar('user_id'));
}
$post_fields['x_email'] = $billing_email;
$post_fields['x_phone'] = $item_data['BillingPhone'];
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
- $post_fields['x_country'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
+ $post_fields['x_country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$post_fields['x_cust_id'] = $item_data['PortalUserId'];
$post_fields['x_invoice_num'] = $item_data['OrderNumber'];
$post_fields['x_description'] = 'Invoice #'.$item_data['OrderNumber'];
$post_fields['x_email_customer'] = 'FALSE';
*/
// echo '<pre>';
// print_r($post_fields);
// exit;
$this->gw_responce = curl_post($gw_params['submit_url'], $post_fields);
// echo $this->gw_responce;
// exit;
$gw_responce = $this->parseGWResponce(null, $gw_params);
// gw_error_msg: $gw_response['responce_reason_text']
// gw_error_code: $gw_response['responce_reason_code']
// echo '<pre>';
// print_r($this->parsed_responce);
// exit;
return (isset($gw_responce['ACK']) && (substr($gw_responce['ACK'], 0, 7) == 'Success')) ? true : false;
}
/**
* Perform SALE type transaction direct from php script wihtout redirecting to 3rd-party website
*
* @param Array $item_data
* @param Array $gw_params
* @return bool
*/
/*
function Charge($item_data, $gw_params)
{
$gw_responce = unserialize( $item_data['GWResult1'] );
if( $item_data['PortalUserId'] != $gw_responce['customer_id'] ) return false;
if( ( strtolower($gw_responce['transaction_type']) == 'auth_only') )
{
$post_fields = Array();
// -- Login Information --
$post_fields['x_version'] = '3.1';
$post_fields['x_delim_data'] = 'True';
$post_fields['x_encap_char'] = $gw_params['encapsulate_char'];
$post_fields['x_relay_response'] = 'False';
$post_fields['x_type'] = 'PRIOR_AUTH_CAPTURE'; // $gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH ? 'PRIOR_AUTH_CAPTURE' : 'AUTH_CAPTURE'; // AUTH_CAPTURE not fully impletemnted/needed here
$post_fields['x_login'] = $gw_params['user_account'];
$post_fields['x_tran_key'] = $gw_params['transaction_key'];
$post_fields['x_trans_id'] = $gw_responce['transaction_id'];
if( $this->IsTestMode() ) $post_fields['x_test_request'] = 'True';
$this->gw_responce = curl_post($gw_params['submit_url'], $post_fields);
$gw_responce = $this->parseGWResponce(null, $gw_params);
// gw_error_msg: $gw_response['responce_reason_text']
// gw_error_code: $gw_response['responce_reason_code']
return (is_numeric($gw_responce['responce_code']) && $gw_responce['responce_code'] != 1 && !$this->IsTestMode()) ? false : true;
}
else
{
return true;
}
}
*/
/**
* Parse previosly saved gw responce into associative array
*
* @param string $gw_responce
* @param Array $gw_params
* @return Array
*/
function parseGWResponce($gw_responce = null, $gw_params)
{
if( !isset($gw_responce) ) $gw_responce = $this->gw_responce;
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendHTML('Curl Error #'.$GLOBALS['curl_errorno'].'; Error Message: '.$GLOBALS['curl_error']);
$this->Application->Debugger->appendHTML('Authorize.Net Responce:');
$this->Application->Debugger->dumpVars($gw_responce);
}
$a_responce = explode('&', $gw_responce);
$ret = Array();
foreach($a_responce as $field)
{
$pos = strpos($field, '=');
if ($pos) {
$ret[substr($field, 0, $pos)] = urldecode(substr($field, $pos + 1));
}
}
$this->parsed_responce = $ret;
// $ret['unparsed'] = $gw_responce;
return $ret;
}
function getGWResponce()
{
return serialize($this->parsed_responce);
}
function getErrorMsg()
{
return $this->parsed_responce['L_LONGMESSAGE0'];
}
function GetTestCCNumbers()
{
return array('370000000000002', '6011000000000012', '5424000000000015', '4007000000027', '4222222222222');
}
}
\ No newline at end of file
Index: branches/5.1.x/units/gateways/gw_classes/authorizenet.php
===================================================================
--- branches/5.1.x/units/gateways/gw_classes/authorizenet.php (revision 13464)
+++ branches/5.1.x/units/gateways/gw_classes/authorizenet.php (revision 13465)
@@ -1,168 +1,170 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
class kGWAuthorizeNet extends kGWBase
{
function DirectPayment($item_data, $gw_params)
{
$post_fields = Array();
// -- Login Information --
$post_fields['x_version'] = '3.1';
$post_fields['x_delim_data'] = 'True';
$post_fields['x_encap_char'] = $gw_params['encapsulate_char'];
$post_fields['x_relay_response'] = 'False';
$post_fields['x_type'] = $gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH ? 'AUTH_ONLY' : 'AUTH_CAPTURE';
$post_fields['x_login'] = $gw_params['user_account'];
$post_fields['x_tran_key'] = $gw_params['transaction_key'];
if( $this->IsTestMode() ) $post_fields['x_test_request'] = 'True';
// -- Payment Details --
$names = explode(' ', $item_data['PaymentNameOnCard'], 2);
$post_fields['x_first_name'] = getArrayValue($names, 0);
$post_fields['x_last_name'] = getArrayValue($names, 1);
$post_fields['x_amount'] = sprintf('%.2f', $item_data['TotalAmount']);
$post_fields['x_company'] = $item_data['BillingCompany'];
$post_fields['x_card_num'] = $item_data['PaymentAccount'];
$post_fields['x_card_code'] = $item_data['PaymentCVV2'];
$post_fields['x_exp_date'] = $item_data['PaymentCCExpDate'];
$post_fields['x_address'] = $item_data['BillingAddress1'].' '.$item_data['BillingAddress2'];
$post_fields['x_city'] = $item_data['BillingCity'];
$post_fields['x_state'] = $item_data['BillingState'];
$post_fields['x_zip'] = $item_data['BillingZip'];
$recurring = getArrayValue($item_data, 'IsRecurringBilling') ? 'YES' : 'NO';
$post_fields['x_recurring_billing'] = $recurring;
$billing_email = $item_data['BillingEmail'];
if (!$billing_email) {
$billing_email = $this->Conn->GetOne(' SELECT Email FROM '.$this->Application->getUnitOption('u', 'TableName').'
WHERE PortalUserId = '.$this->Application->RecallVar('user_id'));
}
$post_fields['x_email'] = $billing_email;
$post_fields['x_phone'] = $item_data['BillingPhone'];
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
- $post_fields['x_country'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $post_fields['x_country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$post_fields['x_cust_id'] = $item_data['PortalUserId'];
$post_fields['x_invoice_num'] = $item_data['OrderNumber'];
$post_fields['x_description'] = 'Invoice #'.$item_data['OrderNumber'];
$post_fields['x_email_customer'] = 'FALSE';
$this->gw_responce = curl_post($gw_params['submit_url'], $post_fields);
$gw_responce = $this->parseGWResponce(null, $gw_params);
// gw_error_msg: $gw_response['responce_reason_text']
// gw_error_code: $gw_response['responce_reason_code']
return (is_numeric($gw_responce['responce_code']) && $gw_responce['responce_code'] == 1) ? true : false;
}
/**
* Perform SALE type transaction direct from php script wihtout redirecting to 3rd-party website
*
* @param Array $item_data
* @param Array $gw_params
* @return bool
*/
function Charge($item_data, $gw_params)
{
$gw_responce = unserialize( $item_data['GWResult1'] );
if( ($item_data['PortalUserId'] != $gw_responce['customer_id']) && ($gw_repsponce['customer_id'] != -2 && !$this->Application->isAdmin)) return false;
if( ( strtolower($gw_responce['transaction_type']) == 'auth_only') )
{
$post_fields = Array();
// -- Login Information --
$post_fields['x_version'] = '3.1';
$post_fields['x_delim_data'] = 'True';
$post_fields['x_encap_char'] = $gw_params['encapsulate_char'];
$post_fields['x_relay_response'] = 'False';
$post_fields['x_type'] = 'PRIOR_AUTH_CAPTURE'; // $gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH ? 'PRIOR_AUTH_CAPTURE' : 'AUTH_CAPTURE'; // AUTH_CAPTURE not fully impletemnted/needed here
$post_fields['x_login'] = $gw_params['user_account'];
$post_fields['x_tran_key'] = $gw_params['transaction_key'];
$post_fields['x_trans_id'] = $gw_responce['transaction_id'];
if( $this->IsTestMode() ) $post_fields['x_test_request'] = 'True';
$this->gw_responce = curl_post($gw_params['submit_url'], $post_fields);
$gw_responce = $this->parseGWResponce(null, $gw_params);
// gw_error_msg: $gw_response['responce_reason_text']
// gw_error_code: $gw_response['responce_reason_code']
return (is_numeric($gw_responce['responce_code']) && $gw_responce['responce_code'] == 1) || $this->IsTestMode() ? true : false;
}
else
{
return true;
}
}
/**
* Parse previosly saved gw responce into associative array
*
* @param string $gw_responce
* @param Array $gw_params
* @return Array
*/
function parseGWResponce($gw_responce = null, $gw_params)
{
if( !isset($gw_responce) ) $gw_responce = $this->gw_responce;
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendHTML('Curl Error #'.$GLOBALS['curl_errorno'].'; Error Message: '.$GLOBALS['curl_error']);
$this->Application->Debugger->appendHTML('Authorize.Net Responce:');
$this->Application->Debugger->dumpVars($gw_responce);
}
$fields = Array('responce_code','responce_sub_code','responce_reason_code','responce_reason_text',
'approval_code','avs_result_code','transaction_id','invoice_number','description',
'amount','method','transaction_type','customer_id','first_name','last_name','company',
'address','city','state','zip','country','phone','fax','email');
$encapsulate_char = $gw_params['encapsulate_char'];
if($encapsulate_char)
{
$ec_length = strlen($encapsulate_char);
$gw_responce = substr($gw_responce, $ec_length, $ec_length * -1);
}
$gw_responce = explode($encapsulate_char.','.$encapsulate_char, $gw_responce);
$ret = Array();
foreach($fields as $field_index => $field_name)
{
$ret[$field_name] = $gw_responce[$field_index];
unset($gw_responce[$field_index]);
}
$this->parsed_responce = $ret;
return array_merge_recursive2($ret, $gw_responce); // returns unparsed fields with they original indexes together with parsed ones
}
function getGWResponce()
{
return serialize($this->parsed_responce);
}
function getErrorMsg()
{
return $this->parsed_responce['responce_reason_text'];
}
function GetTestCCNumbers()
{
return array('370000000000002', '6011000000000012', '5424000000000015', '4007000000027', '4222222222222');
}
}
\ No newline at end of file
Index: branches/5.1.x/units/gateways/gw_classes/google_checkout.php
===================================================================
--- branches/5.1.x/units/gateways/gw_classes/google_checkout.php (revision 13464)
+++ branches/5.1.x/units/gateways/gw_classes/google_checkout.php (revision 13465)
@@ -1,938 +1,931 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
$class_name = 'kGWGoogleCheckout'; // for automatic installation
class kGWGoogleCheckout extends kGWBase
{
var $gwParams = Array ();
function InstallData()
{
$data = array(
'Gateway' => Array('Name' => 'Google Checkout', 'ClassName' => 'kGWGoogleCheckout', 'ClassFile' => 'google_checkout.php', 'RequireCCFields' => 0),
'ConfigFields' => Array(
'submit_url' => Array('Name' => 'Submit URL', 'Type' => 'text', 'ValueList' => '', 'Default' => 'https://checkout.google.com/api/checkout/v2'),
'merchant_id' => Array('Name' => 'Google merchant ID', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'merchant_key' => Array('Name' => 'Google merchant key', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'shipping_control' => Array('Name' => 'Shipping Control', 'Type' => 'select', 'ValueList' => '3=la_CreditDirect,4=la_CreditPreAuthorize', 'Default' => 3),
)
);
return $data;
}
/**
* Returns payment form submit url
*
* @param Array $gw_params gateway params from payment type config
* @return string
*/
function getFormAction($gw_params)
{
return $gw_params['submit_url'].'/checkout/Merchant/'.$gw_params['merchant_id'];
}
/**
* Processed input data and convets it to fields understandable by gateway
*
* @param Array $item_data current order fields
* @param Array $tag_params additional params for gateway passed through tag
* @param Array $gw_params gateway params from payment type config
* @return Array
*/
function getHiddenFields($item_data, $tag_params, $gw_params)
{
$ret = Array();
$this->gwParams = $gw_params;
$cart_xml = $this->getCartXML($item_data);
$ret['cart'] = base64_encode($cart_xml);
$ret['signature'] = base64_encode( $this->CalcHmacSha1($cart_xml, $gw_params) );
return $ret;
}
function getCartXML($cart_fields)
{
// 1. prepare shopping cart content
$sql = 'SELECT *
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE oi.OrderId = '.$cart_fields['OrderId'];
$order_items = $this->Conn->Query($sql);
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
/* @var $ml_formatter kMultiLanguage */
$cart_xml = Array ();
foreach ($order_items as $order_item) {
$cart_xml[] = ' <item>
<item-name>'.htmlspecialchars($order_item['ProductName']).'</item-name>
<item-description>'.htmlspecialchars($order_item[$ml_formatter->LangFieldName('DescriptionExcerpt')]).'</item-description>'.
$this->getPriceXML('unit-price', $order_item['Price']).'
<quantity>'.$order_item['Quantity'].'</quantity>
</item>';
}
$cart_xml = '<items>'.implode("\n", $cart_xml).'</items>';
// 2. add order identification info (for google checkout notification)
$cart_xml .= ' <merchant-private-data>
<session_id>'.$this->Application->GetSID().'</session_id>
<order_id>'.$cart_fields['OrderId'].'</order_id>
</merchant-private-data>';
// 3. add all shipping types (with no costs)
$sql = 'SELECT Name
FROM '.TABLE_PREFIX.'ShippingType
WHERE Status = '.STATUS_ACTIVE;
$shipping_types = $this->Conn->GetCol($sql);
$shipping_xml = '';
foreach ($shipping_types as $shipping_name) {
$shipping_xml .= ' <merchant-calculated-shipping name="'.htmlspecialchars($shipping_name).'">
<price currency="USD">0.00</price>
</merchant-calculated-shipping>';
}
$use_ssl = substr($this->gwParams['submit_url'], 0, 8) == 'https://' ? true : null;
$shipping_url = $this->Application->BaseURL('/in-commerce/units/gateways/gw_classes/notify_scripts', $use_ssl).'google_checkout_shippings.php';
$shipping_xml = '<merchant-checkout-flow-support>
<shipping-methods>'.$shipping_xml.'</shipping-methods>
<merchant-calculations>
<merchant-calculations-url>'.$shipping_url.'</merchant-calculations-url>
</merchant-calculations>
</merchant-checkout-flow-support>';
$xml = '<checkout-shopping-cart xmlns="http://checkout.google.com/schema/2">
<shopping-cart>'.$cart_xml.'</shopping-cart>
<checkout-flow-support>'.$shipping_xml.'</checkout-flow-support>
</checkout-shopping-cart>';
return $xml;
}
/**
* Returns price formatted as xml tag
*
* @param string $tag_name
* @param float $price
* @return string
*/
function getPriceXML($tag_name, $price)
{
$currency = $this->Application->RecallVar('curr_iso');
return '<'.$tag_name.' currency="'.$currency.'">'.sprintf('%.2f', $price).'</'.$tag_name.'>';
}
/**
* Calculates the cart's hmac-sha1 signature, this allows google to verify
* that the cart hasn't been tampered by a third-party.
*
* {@link http://code.google.com/apis/checkout/developer/index.html#create_signature}
*
* @param string $data the cart's xml
* @return string the cart's signature (in binary format)
*/
function CalcHmacSha1($data, $gw_params) {
$key = $gw_params['merchant_key'];
$blocksize = 64;
$hashfunc = 'sha1';
if (mb_strlen($key) > $blocksize) {
$key = pack('H*', $hashfunc($key));
}
$key = str_pad($key, $blocksize, chr(0x00));
$ipad = str_repeat(chr(0x36), $blocksize);
$opad = str_repeat(chr(0x5c), $blocksize);
$hmac = pack(
'H*', $hashfunc(
($key^$opad).pack(
'H*', $hashfunc(
($key^$ipad).$data
)
)
)
);
return $hmac;
}
/**
* Returns XML request, that GoogleCheckout posts to notification / shipping calculation scripts
*
* @return string
*/
function getRequestXML()
{
$xml_data = $GLOBALS['HTTP_RAW_POST_DATA'];
if ($this->Application->isDebugMode()) {
$fp = fopen(FULL_PATH.'/xml_request.html', 'a');
fwrite($fp, '--- '.adodb_date('Y-m-d H:i:s').' ---'."\n".$xml_data);
fclose($fp);
}
return $xml_data;
// for debugging
/*return '<order-state-change-notification xmlns="http://checkout.google.com/schema/2"
serial-number="c821426e-7caa-4d51-9b2e-48ef7ecd6423">
<google-order-number>434532759516557</google-order-number>
<new-financial-order-state>CHARGEABLE</new-financial-order-state>
<new-fulfillment-order-state>NEW</new-fulfillment-order-state>
<previous-financial-order-state>REVIEWING</previous-financial-order-state>
<previous-fulfillment-order-state>NEW</previous-fulfillment-order-state>
<timestamp>2007-03-19T15:06:29.051Z</timestamp>
</order-state-change-notification>';*/
}
/**
* Processes notifications from google checkout
*
* @param Array $gw_params
* @return int
*/
function processNotification($gw_params)
{
// parse xml & get order_id from there, like sella pay
$this->gwParams = $gw_params;
$xml_helper =& $this->Application->recallObject('kXMLHelper');
/* @var $xml_helper kXMLHelper */
$root_node =& $xml_helper->Parse( $this->getRequestXML() );
/* @var $root_node kXMLNode */
$this->Application->XMLHeader();
define('DBG_SKIP_REPORTING', 1);
$order_approvable = false;
switch ($root_node->Name) {
case 'MERCHANT-CALCULATION-CALLBACK':
$xml_responce = $this->getShippingXML($root_node);
break;
case 'NEW-ORDER-NOTIFICATION':
case 'RISK-INFORMATION-NOTIFICATION':
case 'ORDER-STATE-CHANGE-NOTIFICATION':
// http://code.google.com/apis/checkout/developer/Google_Checkout_XML_API_Notification_API.html#new_order_notifications
list ($order_approvable, $xml_responce) = $this->getNotificationResponceXML($root_node);
break;
}
echo $xml_responce;
if ($this->Application->isDebugMode()) {
$fp = fopen(FULL_PATH.'/xml_responce.html', 'a');
fwrite($fp, '--- '.adodb_date('Y-m-d H:i:s').' ---'."\n".$xml_responce."\n");
fclose($fp);
}
return $order_approvable ? 1 : 0;
}
/**
* Processes notification
*
* @param kXMLNode $root_node
*/
function getNotificationResponceXML(&$root_node)
{
// we can get notification type by "$root_node->Name"
$order_approvable = false;
switch ($root_node->Name) {
case 'NEW-ORDER-NOTIFICATION':
$order_approvable = $this->processNewOrderNotification($root_node);
break;
case 'RISK-INFORMATION-NOTIFICATION':
$order_approvable = $this->processRiskInformationNotification($root_node);
break;
case 'ORDER-STATE-CHANGE-NOTIFICATION':
$order_approvable = $this->processOrderStateChangeNotification($root_node);
break;
}
// !!! globally set order id, so gw_responce.php will not fail in setting TransactionStatus
// 1. receive new order notification
// put address & payment type in our order using id found in merchant-private-data (Make order status: Incomplete)
// 2. receive risk information
// don't know what to do, just mark order some how (Make order status: Incomplete)
// 3. receive status change notification to CHARGEABLE (Make order status: Pending)
// only mark order status
// 4. admin approves order
// make api call, that changes order state (fulfillment-order-state) to PROCESSING or DELIVERED (see manual)
// 5. admin declines order
// make api call, that changes order state (fulfillment-order-state) to WILL_NOT_DELIVER
// Before you ship the items in an order, you should ensure that you have already received the new order notification for the order,
// the risk information notification for the order and an order state change notification informing you that the order's financial
// state has been updated to CHARGEABLE
return Array ($order_approvable, '<notification-acknowledgment xmlns="http://checkout.google.com/schema/2" serial-number="'.$root_node->Attributes['SERIAL-NUMBER'].'" />');
}
/**
* Returns shipping calculations and places part of shipping address into order (1st step)
*
* http://code.google.com/apis/checkout/developer/Google_Checkout_XML_API_Merchant_Calculations_API.html#Returning_Merchant_Calculation_Results
*
* @param kXMLNode $node
* @return string
*/
function getShippingXML(&$root_node)
{
// 1. extract data from xml
$search_nodes = Array (
'SHOPPING-CART:MERCHANT-PRIVATE-DATA',
'CALCULATE:ADDRESSES:ANONYMOUS-ADDRESS',
'CALCULATE:SHIPPING',
);
foreach ($search_nodes as $search_string) {
$found_node =& $root_node;
/* @var $found_node kXMLNode */
$search_string = explode(':', $search_string);
foreach ($search_string as $search_node) {
$found_node =& $found_node->FindChild($search_node);
}
$node_data = Array ();
$sub_node =& $found_node->firstChild;
/* @var $sub_node kXMLNode */
do {
if ($found_node->Name == 'SHIPPING') {
$node_data[] = $sub_node->Attributes['NAME'];
}
else {
$node_data[$sub_node->Name] = $sub_node->Data;
}
} while ( ($sub_node =& $sub_node->NextSibling()) );
switch ($found_node->Name) {
case 'MERCHANT-PRIVATE-DATA':
$order_id = $node_data['ORDER_ID'];
$session_id = $node_data['SESSION_ID'];
break;
case 'ANONYMOUS-ADDRESS':
$address_info = $node_data;
$address_id = $found_node->Attributes['ID'];
break;
case 'SHIPPING':
$process_shippings = $node_data;
break;
}
}
// 2. update shipping address in order
$order =& $this->Application->recallObject('ord', null, Array ('skip_autoload' => true));
/* @var $order OrdersItem */
$order->Load($order_id);
$shipping_address = Array (
'ShippingCity' => $address_info['CITY'],
'ShippingState' => $address_info['REGION'],
'ShippingZip' => $address_info['POSTAL-CODE'],
);
- $shipping_address['ShippingCountry'] = $this->getCountryISO($address_info['COUNTRY-CODE']);
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $shipping_address['ShippingCountry'] = $cs_helper->getCountryIso($address_info['COUNTRY-CODE'], true);
$order->SetDBFieldsFromHash($shipping_address);
$order->Update();
// 3. get shipping rates based on given address
$shipping_types_xml = '';
$shipping_types = $this->getOrderShippings($order);
// add available shipping types
foreach ($shipping_types as $shipping_type) {
$shipping_name = $shipping_type['ShippingName'];
$processable_shipping_index = array_search($shipping_name, $process_shippings);
if ($processable_shipping_index !== false) {
$shipping_types_xml .= '<result shipping-name="'.htmlspecialchars($shipping_name).'" address-id="'.$address_id.'">
<shipping-rate currency="USD">'.sprintf('%01.2f', $shipping_type['TotalCost']).'</shipping-rate>
<shippable>true</shippable>
</result>';
// remove available shipping type from processable list
unset($process_shippings[$processable_shipping_index]);
}
}
// add unavailable shipping types
foreach ($process_shippings as $shipping_name) {
$shipping_types_xml .= '<result shipping-name="'.htmlspecialchars($shipping_name).'" address-id="'.$address_id.'">
<shipping-rate currency="USD">0.00</shipping-rate>
<shippable>false</shippable>
</result>';
}
$shipping_types_xml = '<?xml version="1.0" encoding="UTF-8"?>
<merchant-calculation-results xmlns="http://checkout.google.com/schema/2">
<results>'.$shipping_types_xml.'</results>
</merchant-calculation-results>';
return $shipping_types_xml;
}
/**
* Places all information from google checkout into order (2nd step)
*
* @param kXMLNode $root_node
*/
function processNewOrderNotification(&$root_node)
{
// 1. extract data from xml
$search_nodes = Array (
'SHOPPING-CART:MERCHANT-PRIVATE-DATA',
'ORDER-ADJUSTMENT:SHIPPING:MERCHANT-CALCULATED-SHIPPING-ADJUSTMENT',
'BUYER-ID',
'GOOGLE-ORDER-NUMBER',
'BUYER-SHIPPING-ADDRESS',
'BUYER-BILLING-ADDRESS',
);
$user_address = Array ();
foreach ($search_nodes as $search_string) {
$found_node =& $root_node;
/* @var $found_node kXMLNode */
$search_string = explode(':', $search_string);
foreach ($search_string as $search_node) {
$found_node =& $found_node->FindChild($search_node);
}
$node_data = Array ();
if ($found_node->Children) {
$sub_node =& $found_node->firstChild;
/* @var $sub_node kXMLNode */
do {
$node_data[$sub_node->Name] = $sub_node->Data;
} while ( ($sub_node =& $sub_node->NextSibling()) );
}
switch ($found_node->Name) {
case 'MERCHANT-PRIVATE-DATA':
$order_id = $node_data['ORDER_ID'];
$session_id = $node_data['SESSION_ID'];
break;
case 'MERCHANT-CALCULATED-SHIPPING-ADJUSTMENT':
$shpipping_info = $node_data;
break;
case 'BUYER-ID':
$buyer_id = $found_node->Data;
break;
case 'GOOGLE-ORDER-NUMBER':
$google_order_number = $found_node->Data;
break;
case 'BUYER-SHIPPING-ADDRESS':
$user_address['Shipping'] = $node_data;
break;
case 'BUYER-BILLING-ADDRESS':
$user_address['Billing'] = $node_data;
break;
}
}
// 2. update shipping address in order
$order =& $this->Application->recallObject('ord', null, Array ('skip_autoload' => true));
/* @var $order OrdersItem */
$order->Load($order_id);
if (!$order->isLoaded()) {
return false;
}
// 2.1. this is 100% notification from google -> mark order with such payment type
$order->SetDBField('PaymentType', $this->Application->GetVar('payment_type_id'));
$this->parsed_responce = Array (
'GOOGLE-ORDER-NUMBER' => $google_order_number,
'BUYER-ID' => $buyer_id
);
// 2.2. save google checkout order information (maybe needed for future notification processing)
$order->SetDBField('GWResult1', serialize($this->parsed_responce));
$order->SetDBField('GoogleOrderNumber', $google_order_number);
// 2.3. set user-selected shipping type
$shipping_types = $this->getOrderShippings($order);
foreach ($shipping_types as $shipping_type) {
if ($shipping_type['ShippingName'] == $shpipping_info['SHIPPING-NAME']) {
$order->SetDBField('ShippingInfo', serialize(Array (1 => $shipping_type))); // minimal package number is 1
$order->SetDBField('ShippingCost', $shipping_type['TotalCost']); // set total shipping cost
break;
}
}
// 2.4. set full shipping & billing address
$address_mapping = Array (
'CONTACT-NAME' => 'To',
'COMPANY-NAME' => 'Company',
'EMAIL' => 'Email',
'PHONE' => 'Phone',
'FAX' => 'Fax',
'ADDRESS1' => 'Address1',
'ADDRESS2' => 'Address2',
'CITY' => 'City',
'REGION' => 'State',
'POSTAL-CODE' => 'Zip',
);
+
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
foreach ($user_address as $field_prefix => $address_details) {
foreach ($address_mapping as $src_field => $dst_field) {
$order->SetDBField($field_prefix.$dst_field, $address_details[$src_field]);
}
if (!$order->GetDBField($field_prefix.'Phone')) {
$order->SetDBField($field_prefix.'Phone', '-'); // required field
}
- $order->SetDBField($field_prefix.'Country', $this->getCountryISO($address_details['COUNTRY-CODE']));
+ $order->SetDBField( $field_prefix.'Country', $cs_helper->getCountryIso($address_details['COUNTRY-CODE'], true) );
}
$order->SetDBField('OnHold', 1);
$order->SetDBField('Status', ORDER_STATUS_PENDING);
$order->Update();
// unlink order, that GoogleCheckout used from shopping cart on site
$sql = 'DELETE
FROM '.TABLE_PREFIX.'SessionData
WHERE VariableName = "ord_id" AND VariableValue = '.$order->GetID();
$this->Conn->Query($sql);
// simulate visiting shipping screen
$sql = 'UPDATE '.TABLE_PREFIX.'OrderItems
SET PackageNum = 1
WHERE OrderId = '.$order->GetID();
$this->Conn->Query($sql);
return false;
}
/**
* Saves risk information in order record (3rd step)
*
* @param kXMLNode $root_node
*/
function processRiskInformationNotification(&$root_node)
{
// 1. extract data from xml
$search_nodes = Array (
'GOOGLE-ORDER-NUMBER',
'RISK-INFORMATION',
);
foreach ($search_nodes as $search_string) {
$found_node =& $root_node;
/* @var $found_node kXMLNode */
$search_string = explode(':', $search_string);
foreach ($search_string as $search_node) {
$found_node =& $found_node->FindChild($search_node);
}
$node_data = Array ();
if ($found_node->Children) {
$sub_node =& $found_node->firstChild;
/* @var $sub_node kXMLNode */
do {
$node_data[$sub_node->Name] = $sub_node->Data;
} while ( ($sub_node =& $sub_node->NextSibling()) );
}
switch ($found_node->Name) {
case 'GOOGLE-ORDER-NUMBER':
$google_order_number = $found_node->Data;
break;
case 'RISK-INFORMATION':
$risk_information = $node_data;
unset( $risk_information['BILLING-ADDRESS'] );
break;
}
}
// 2. update shipping address in order
$order =& $this->Application->recallObject('ord', null, Array ('skip_autoload' => true));
/* @var $order OrdersItem */
$order->Load($google_order_number, 'GoogleOrderNumber');
if (!$order->isLoaded()) {
return false;
}
// 2.1. save risk information in order
$this->parsed_responce = unserialize($order->GetDBField('GWResult1'));
$this->parsed_responce = array_merge_recursive($this->parsed_responce, $risk_information);
$order->SetDBField('GWResult1', serialize($this->parsed_responce));
$order->Update();
return false;
}
/**
* Perform PREAUTH/SALE type transaction direct from php script wihtout redirecting to 3rd-party website
*
* @param Array $item_data
* @param Array $gw_params
* @return bool
*/
function DirectPayment($item_data, $gw_params)
{
$this->gwParams = $gw_params;
if ($gw_params['shipping_control'] == SHIPPING_CONTROL_PREAUTH) {
// when shipping control is Pre-Authorize -> do nothing and charge when admin approves order
return true;
}
$this->_chargeOrder($item_data);
return false;
}
/**
* Issue charge-order api call
*
* @param Array $item_data
* @return bool
*/
function _chargeOrder($item_data)
{
$charge_xml = ' <charge-order xmlns="http://checkout.google.com/schema/2" google-order-number="'.$item_data['GoogleOrderNumber'].'">
<amount currency="USD">'.sprintf('%.2f', $item_data['TotalAmount']).'</amount>
</charge-order>';
$root_node =& $this->executeAPICommand($charge_xml);
$this->parsed_responce = unserialize($item_data['GWResult1']);
if ($root_node->Name == 'REQUEST-RECEIVED') {
$this->parsed_responce['FINANCIAL-ORDER-STATE'] = 'CHARGING';
return true;
}
return false;
}
/**
* Perform SALE type transaction direct from php script wihtout redirecting to 3rd-party website
*
* @param Array $item_data
* @param Array $gw_params
* @return bool
*/
function Charge($item_data, $gw_params)
{
$this->gwParams = $gw_params;
if ($gw_params['shipping_control'] == SHIPPING_CONTROL_DIRECT) {
// when shipping control is Direct Payment -> do nothing and auto-charge on notification received
return true;
}
$this->_chargeOrder($item_data);
$order =& $this->Application->recallObject('ord.-item', null, Array ('skip_autoload' => true));
/* @var $order OrdersItem */
$order->Load($item_data['OrderId']);
if (!$order->isLoaded()) {
return false;
}
$order->SetDBField('OnHold', 1);
$order->Update();
return false;
}
/**
* Executes API command for order and returns result
*
* @param string $command_xml
* @return kXMLNode
*/
function &executeAPICommand($command_xml)
{
$submit_url = $this->gwParams['submit_url'].'/request/Merchant/'.$this->gwParams['merchant_id'];
$curl_helper =& $this->Application->recallObject('CurlHelper');
/* @var $curl_helper kCurlHelper */
$xml_helper =& $this->Application->recallObject('kXMLHelper');
/* @var $xml_helper kXMLHelper */
$curl_helper->SetPostData($command_xml);
$auth_options = Array (
CURLOPT_USERPWD => $this->gwParams['merchant_id'].':'.$this->gwParams['merchant_key'],
);
$curl_helper->setOptions($auth_options);
$xml_responce = $curl_helper->Send($submit_url);
$root_node =& $xml_helper->Parse($xml_responce);
/* @var $root_node kXMLNode */
return $root_node;
}
/**
* Marks order as pending, when it's google status becomes CHARGEABLE (4th step)
*
* @param kXMLNode $root_node
*/
function processOrderStateChangeNotification(&$root_node)
{
// 1. extract data from xml
$search_nodes = Array (
'GOOGLE-ORDER-NUMBER',
'NEW-FINANCIAL-ORDER-STATE',
'PREVIOUS-FINANCIAL-ORDER-STATE',
);
$order_state = Array ();
foreach ($search_nodes as $search_string) {
$found_node =& $root_node;
/* @var $found_node kXMLNode */
$search_string = explode(':', $search_string);
foreach ($search_string as $search_node) {
$found_node =& $found_node->FindChild($search_node);
}
switch ($found_node->Name) {
case 'GOOGLE-ORDER-NUMBER':
$google_order_number = $found_node->Data;
break;
case 'NEW-FINANCIAL-ORDER-STATE':
$order_state['new'] = $found_node->Data;
break;
case 'PREVIOUS-FINANCIAL-ORDER-STATE':
$order_state['old'] = $found_node->Data;
break;
}
}
// 2. update shipping address in order
$order =& $this->Application->recallObject('ord', null, Array ('skip_autoload' => true));
/* @var $order OrdersItem */
$order->Load($google_order_number, 'GoogleOrderNumber');
if (!$order->isLoaded()) {
return false;
}
$state_changed = ($order_state['old'] != $order_state['new']);
if ($state_changed) {
$order_charged = ($order_state['new'] == 'CHARGED') && ($order->GetDBField('Status') == ORDER_STATUS_PENDING);
$this->parsed_responce = unserialize($order->GetDBField('GWResult1'));
$this->parsed_responce['FINANCIAL-ORDER-STATE'] = $order_state['new'];
$order->SetDBField('GWResult1', serialize($this->parsed_responce));
if ($order_charged) {
// when using Pre-Authorize
$order->SetDBField('OnHold', 0);
}
$order->Update();
if ($order_charged) {
// when using Pre-Authorize
$order_eh =& $this->Application->recallObject('ord_EventHandler');
/* @var $order_eh OrdersEventHandler */
$order_eh->SplitOrder( new kEvent('ord:OnMassOrderApprove'), $order);
}
}
// update order record in "google_checkout_notify.php" only when such state change happens
$order_chargeable = ($order_state['new'] == 'CHARGEABLE') && $state_changed;
if ($order_chargeable) {
if ($this->gwParams['shipping_control'] == SHIPPING_CONTROL_PREAUTH) {
$order->SetDBField('OnHold', 0);
$order->Update();
}
$process_xml = '<process-order xmlns="http://checkout.google.com/schema/2" google-order-number="'.$order->GetDBField('GoogleOrderNumber').'"/>';
$root_node =& $this->executeAPICommand($process_xml);
}
return $order_chargeable;
}
/**
- * Returns 3 symbols ISO code from 2 symbols ISO code
- *
- * @param string $country_code
- * @return string
- */
- function getCountryISO($country_code)
- {
- $sql = 'SELECT DestAbbr
- FROM '.TABLE_PREFIX.'StdDestinations
- WHERE DestAbbr2 = '.$this->Conn->qstr($country_code);
- return $this->Conn->GetOne($sql);
- }
-
- /**
* Retrieves shipping types available for given order
*
* @param OrdersItem $order
* @return Array
*/
function getOrderShippings(&$order)
{
$weight_sql = 'IF(oi.Weight IS NULL, 0, oi.Weight * oi.Quantity)';
$query = ' SELECT
SUM(oi.Quantity) AS TotalItems,
SUM('.$weight_sql.') AS TotalWeight,
SUM(oi.Price * oi.Quantity) AS TotalAmount,
SUM(oi.Quantity) - SUM(IF(p.MinQtyFreePromoShipping > 0 AND p.MinQtyFreePromoShipping <= oi.Quantity, oi.Quantity, 0)) AS TotalItemsPromo,
SUM('.$weight_sql.') - SUM(IF(p.MinQtyFreePromoShipping > 0 AND p.MinQtyFreePromoShipping <= oi.Quantity, '.$weight_sql.', 0)) AS TotalWeightPromo,
SUM(oi.Price * oi.Quantity) - SUM(IF(p.MinQtyFreePromoShipping > 0 AND p.MinQtyFreePromoShipping <= oi.Quantity, oi.Price * oi.Quantity, 0)) AS TotalAmountPromo
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON oi.ProductId = p.ProductId
WHERE oi.OrderId = '.$order->GetID().' AND p.Type = 1';
$shipping_totals = $this->Conn->GetRow($query);
$this->Application->recallObject('ShippingQuoteEngine');
$quote_engine_collector =& $this->Application->recallObject('ShippingQuoteCollector');
/* @var $quote_engine_collector ShippingQuoteCollector */
$shipping_quote_params = Array(
'dest_country' => $order->GetDBField('ShippingCountry'),
'dest_state' => $order->GetDBField('ShippingState'),
'dest_postal' => $order->GetDBField('ShippingZip'),
'dest_city' => $order->GetDBField('ShippingCity'),
'dest_addr1' => '',
'dest_addr2' => '',
'dest_name' => 'user-' . $order->GetDBField('PortalUserId'),
'packages' => Array(
Array(
'package_key' => 'package1',
'weight' => $shipping_totals['TotalWeight'],
'weight_unit' => 'KG',
'length' => '',
'width' => '',
'height' => '',
'dim_unit' => 'IN',
'packaging' => 'BOX',
'contents' => 'OTR',
'insurance' => '0'
),
),
'amount' => $shipping_totals['TotalAmount'],
'items' => $shipping_totals['TotalItems'],
'limit_types' => serialize(Array ('ANY')),
'promo_params' => Array (
'items' => $shipping_totals['TotalItemsPromo'],
'amount' => $shipping_totals['TotalAmountPromo'],
'weight' => $shipping_totals['TotalWeightPromo'],
),
);
return $quote_engine_collector->GetShippingQuotes($shipping_quote_params);
}
/**
* Returns gateway responce from last operation
*
* @return string
*/
function getGWResponce()
{
return serialize($this->parsed_responce);
}
/**
* Informs payment gateway, that order has been shipped
*
* http://code.google.com/apis/checkout/developer/Google_Checkout_XML_API_Order_Level_Shipping.html#Deliver_Order
*
* @param Array $item_data
* @param Array $gw_params
* @return bool
*/
function OrderShipped($item_data, $gw_params)
{
$this->gwParams = $gw_params;
$shipping_info = unserialize($item_data['ShippingInfo']);
if (getArrayValue($shipping_info, 'Code')) {
$traking_carrier = '<carrier>'.$item_data['Code'].'</carrier>';
}
if ($item_data['ShippingTracking']) {
$tracking_data = '<tracking-data>'.$traking_carrier.'
<tracking-number>'.$item_data['ShippingTracking'].'</tracking-number>
</tracking-data>';
}
$ship_xml = ' <deliver-order xmlns="http://checkout.google.com/schema/2" google-order-number="'.$item_data['GoogleOrderNumber'].'">
'.$traking_data.'
<send-email>true</send-email>
</deliver-order>';
$root_node =& $this->executeAPICommand($ship_xml);
}
/**
* Informs payment gateway, that order has been declined
*
* @param Array $item_data
* @param Array $gw_params
* @return bool
*/
function OrderDeclined($item_data, $gw_params)
{
}
}
\ No newline at end of file
Index: branches/5.1.x/units/gateways/gw_classes/worldpay.php
===================================================================
--- branches/5.1.x/units/gateways/gw_classes/worldpay.php (revision 13464)
+++ branches/5.1.x/units/gateways/gw_classes/worldpay.php (revision 13465)
@@ -1,110 +1,112 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
$class_name = 'kGWWorldPay'; // for automatic installation
class kGWWorldPay extends kGWBase
{
function InstallData()
{
$data = array(
'Gateway' => Array('Name' => 'Worldpay', 'ClassName' => 'kGWWorldPay', 'ClassFile' => 'worldpay.php', 'RequireCCFields' => 0),
'ConfigFields' => Array(
'submit_url' => Array('Name' => 'Submit URL', 'Type' => 'text', 'ValueList' => '', 'Default' => 'https://select.worldpay.com/wcc/purchase'),
'instId' => Array('Name' => 'Installation ID', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'callback_pw' => Array('Name' => 'Callback Password', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
)
);
return $data;
}
/**
* Returns payment form submit url
*
* @param Array $gw_params gateway params from payment type config
* @return string
*/
function getFormAction($gw_params)
{
return $gw_params['submit_url'];
}
/**
* Processed input data and convets it to fields understandable by gateway
*
* @param Array $item_data
* @param Array $tag_params additional params for gateway passed through tag
* @param Array $gw_params gateway params from payment type config
* @return Array
*/
function getHiddenFields($item_data, $tag_params, $gw_params)
{
$ret = Array();
$ret['instId'] = $gw_params['instId'];
$ret['cartId'] = $item_data['OrderNumber'];
if (!$this->IsTestMode()) {
$ret['amount'] = sprintf('%.2f', $item_data['TotalAmount']); // the total amount to be billed, in decimal form, without a currency symbol. (8 characters, decimal, 2 characters: Example: 99999999.99)
}
else {
$ret['testMode'] = 100; // 100 - success, 101 - failure
$ret['amount'] = 1;
}
$ret['currency'] = 'USD';
$ret['desc'] = 'Order #'.$item_data['OrderNumber'];
$ret['name'] = $item_data['BillingTo'];
$ret['address'] = $item_data['BillingAddress1'];
if ($item_data['BillingAddress2']) {
$ret['address'] .= '&#10;'.$item_data['BillingAddress2'];
}
$ret['postcode'] = $item_data['BillingZip'];
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
- $ret['country'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $ret['country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$ret['tel'] = $item_data['BillingPhone'];
$ret['fax'] = $item_data['BillingFax'];
$ret['email'] = $item_data['BillingEmail'];
$ret['fixContact'] = 1; // contact-info not editable ?
$return_params = Array ('pass' => 'm', 'sid' => $this->Application->GetSID(), 'admin' => 1);
$ret['MC_return_page'] = $this->Application->HREF($tag_params['return_template'], '', $return_params);
$ret['MC_cancel_return_page'] = $this->Application->HREF($tag_params['cancel_template'], '', $return_params);
$ret['MC_callback'] = $this->Application->BaseURL('/in-commerce').'gw_notify.php?sid='.$this->Application->GetSID().'&admin=1&order_id='.$item_data['OrderId'];
return $ret;
}
function processNotification($gw_params)
{
// http://support.worldpay.com/kb/integration_guides/junior/integration/help/appendicies/sjig_10100.html
// SubmitURL: https://select.worldpay.com/wcc/purchase
// for Notification to work do this in gateway Admin Console:
// Callback URL: <WPDISPLAY ITEM=MC_callback>
// Callback enabled? [x]
// Use callback response?[x]
$transaction_verified = ($this->Application->GetVar('callbackPW') == $gw_params['callback_pw']);
if (!$transaction_verified) {
return 0;
}
$transaction_status = $this->Application->GetVar('transStatus') == 'Y' ? 1 : 0;
echo curl_post($this->Application->GetVar($transaction_status ? 'MC_return_page' : 'MC_cancel_return_page'), '', null, 'GET');
return $transaction_status;
}
}
\ No newline at end of file
Index: branches/5.1.x/units/gateways/gw_classes/paypal.php
===================================================================
--- branches/5.1.x/units/gateways/gw_classes/paypal.php (revision 13464)
+++ branches/5.1.x/units/gateways/gw_classes/paypal.php (revision 13465)
@@ -1,256 +1,260 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
class kGWPayPal extends kGWBase
{
/**
* Returns payment form submit url
*
* @param Array $gw_params gateway params from payment type config
* @return string
*/
function getFormAction($gw_params)
{
return $gw_params['submit_url'];
}
/**
* Processed input data and convets it to fields understandable by gateway
*
* @param Array $item_data
* @param Array $tag_params additional params for gateway passed through tag
* @param Array $gw_params gateway params from payment type config
* @return Array
*/
function getHiddenFields($item_data, $tag_params, $gw_params)
{
$ret = Array();
$ret['item_name'] = 'Order #'.$item_data['OrderNumber'];
$ret['item_number'] = 'order:'.$item_data['OrderNumber'];
$selected_cur = $this->Application->RecallVar('curr_iso');
$available = explode(',', $gw_params['currency_code']);
$target = in_array($selected_cur, $available) ? $selected_cur : $available[0];
if( !$this->IsTestMode() )
{
$currency_iso = $gw_params['currency_code'];
$ret['amount'] = $this->ConvertCurrency($item_data['SubTotal'], $target);
$ret['shipping'] = $this->ConvertCurrency($item_data['ShippingCost'], $target);
$ret['tax'] = $this->ConvertCurrency($item_data['VAT'], $target);
}
else
{
$ret['amount'] = 1;
$ret['shipping'] = 0;
$ret['tax'] = 0;
}
$ret['quantity'] = 1;
$ret['cancel_return'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));
$ret['return'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
$ret['no_note'] = 1; // customer is not prompted for notes
$ret['no_shipping'] = 1; // customer is not prompted for shipping address
$ret['rm'] = 2; // return method - POST
$ret['currency_code'] = $target;
$ret['invoice'] = $item_data['OrderNumber'];
$ret['business'] = $gw_params['business_account'];
// prepopulated fields
$ret['address_override'] = 1; // override user's stored address
$ret['email'] = $item_data['BillingEmail'];
list($first_name, $last_name) = explode(' ', $item_data['BillingTo']);
$ret['first_name'] = $first_name;
$ret['last_name'] = $last_name;
$ret['address1'] = $item_data['BillingAddress1'];
$ret['address2'] = $item_data['BillingAddress2'];
$ret['city'] = $item_data['BillingCity'];
$ret['state'] = $item_data['BillingState'];
$ret['zip'] = $item_data['BillingZip'];
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
- $ret['country'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $ret['country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$ret['notify_url'] = $this->Application->BaseURL('/in-commerce').'gw_notify.php?sid='.$this->Application->GetSID().'&admin=1&order_id='.$item_data['OrderId'];
$ret['cmd'] = '_xclick'; // act as "Buy Now" PayPal button
return $ret;
}
function getSubscriptionFields($item_data, $tag_params, $gw_params)
{
$ret = Array();
$ret['item_name'] = $item_data['item_name'];
$ret['item_number'] = $item_data['item_number'];
$ret['a1'] = $item_data['a1'];
$ret['p1'] = $item_data['p1'];
$ret['t1'] = $item_data['t1'];
$ret['a2'] = $item_data['a2'];
$ret['p2'] = $item_data['p2'];
$ret['t2'] = $item_data['t2'];
$ret['p3'] = $item_data['p3'];
$ret['t3'] = $item_data['t3'];
$ret['src'] = $item_data['src'];
$ret['sra'] = $item_data['sra'];
$ret['srt'] = $item_data['srt'];
$ret['custom'] = $item_data['OrderId'];
$currency_iso = $gw_params['currency_code'];
$ret['a3'] = $this->ConvertCurrency($item_data['a3'], $currency_iso);;
$ret['tax'] = $this->ConvertCurrency($item_data['VAT'], $currency_iso);
if( $this->Application->isDebugMode() )
{
}
else
{
}
// $ret['quantity'] = 1;
$ret['cancel_return'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));
$ret['return'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
$ret['no_note'] = 1; // customer is not prompted for notes
$ret['no_shipping'] = 1; // customer is not prompted for shipping address
$ret['rm'] = 2; // return method - POST
$ret['currency_code'] = $gw_params['currency_code'];
$ret['invoice'] = $item_data['OrderNumber'];
$ret['business'] = $gw_params['business_account'];
// prepopulated fields
$ret['address_override'] = 1; // override user's stored address
$ret['email'] = $item_data['BillingEmail'];
list($first_name, $last_name) = explode(' ', $item_data['BillingTo']);
$ret['first_name'] = $first_name;
$ret['last_name'] = $last_name;
$ret['address1'] = $item_data['BillingAddress1'];
$ret['address2'] = $item_data['BillingAddress2'];
$ret['city'] = $item_data['BillingCity'];
$ret['state'] = $item_data['BillingState'];
$ret['zip'] = $item_data['BillingZip'];
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
- $ret['country'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $ret['country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$ret['notify_url'] = $this->Application->BaseURL('/in-commerce').'gw_notify.php?sid='.$this->Application->GetSID().'&admin=1&order_id='.$item_data['OrderId'].'&payment_type_id='.$tag_params['payment_type_id'];
$ret['cmd'] = '_xclick-subscriptions'; // act as "Buy Now" PayPal button
$real_ret = array();
foreach ($ret as $key => $val)
{
if ($val == '') continue;
$real_ret[$key] = $val;
}
return $real_ret;
}
function processNotification($gw_params)
{
$payment_status = $_POST['payment_status']; // save payment_status for later proceeding
$_POST['cmd'] = '_notify-validate';
// status, of that PayPal server really has sent such notification to us
$status_map = Array('INVALID' => 0, 'VERIFIED' => 1);
$n_status = curl_post($gw_params['submit_url'], $_POST); // INVALID, VERIFIED
$n_status = $status_map[$n_status];
$success = ($n_status == 1) && ($payment_status == 'Completed') ? 1:0 ; // 1:0 is on purpose, false will result an SQL error !
if (!$success) return;
$type = $_POST['txn_type'];
switch ($type)
{
case 'subscr_signup':
break;
case 'subscr_cancel':
break;
case 'subscr_failed':
break;
case 'subscr_payment':
$field_values = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'OrderItems WHERE OrderItemId = '.$_POST['item_number']);
$this->Application->HandleEvent($an_event, 'p:OnSubscriptionApprove', array('field_values' => $field_values));
$success = 0; //this will eliminate OnCompleteOrder in gw_notify!
$org_order = $this->Application->recallObject('ord.-original', 'ord', Array('skip_autoload' => true));
$org_order->Load($field_values['OrderId']);
$order = $this->Application->recallObject('ord.-paypal', 'ord');
$order->SetDBFieldsFromHash($org_order->FieldValues);
$order->SetDBField('SubTotal', $field_values['Price']);
$order->SetDBField('OriginalAmout', $field_values['Price']);
$order->SetDBField('OrderDate', adodb_mktime());
$order->UpdateFormattersSubFields();
$dup_item = false;
if ($org_order->GetDBField('Status') >= ORDER_STATUS_PROCESSED) {
$sql = 'SELECT MAX(SubNumber) FROM '.TABLE_PREFIX.'Orders WHERE Number = '.$org_order->GetDBField('Number');
$num = $this->Conn->GetOne($sql) + 1;
$order->SetDBField('SubNumber', $num);
$dup_item = true;
}
else {
$sql = 'SELECT MAX(Number) FROM '.TABLE_PREFIX.'Orders';
$num = $this->Conn->GetOne($sql) + 1;
$order->SetDBField('Number', $num);
$order->SetDBField('SubNumber', 0);
}
$order->SetDBField('PaymentType', $this->Application->GetVar('payment_type_id'));
$info = array(
'BillingTo' => $_POST['first_name'].' '.$_POST['last_name'],
'BillingCompany' => 'n/a (PayPal)',
'BillingPhone' => 'n/a (PayPal)',
'BillingFax' => '',
'BillingEmail' => $_POST['payer_email'],
'BillingAddress1' => 'n/a (PayPal)',
'BillingCity' => 'n/a (PayPal)',
'BillingState' => 'n/a (PayPal)',
'BillingZip' => 'n/a (PayPal)',
'BillingCountry' => '???',
);
$order->SetFieldsFromHash($info);
$order->SetDBField('Status', ORDER_STATUS_PROCESSED);
$order->Create();
if ($dup_item) {
$query = 'INSERT INTO '.TABLE_PREFIX.'OrderItems
(OrderId, ProductId, ProductName, Quantity, QuantityReserved, FlatPrice, Price, BackOrderFlag, Weight, ShippingTypeId, ItemData, OptionsSalt)
SELECT
'.$order->GetId().' AS OrderId, ProductId, ProductName, Quantity, QuantityReserved, FlatPrice, Price, BackOrderFlag, Weight, ShippingTypeId, ItemData, OptionsSalt
FROM '.TABLE_PREFIX.'OrderItems
WHERE OrderItemId = '.$field_values['OrderItemId'];
}
else {
$query = 'UPDATE '.TABLE_PREFIX.'OrderItems SET OrderId = %s WHERE OrderItemId = %s';
$query = sprintf($query, $order->GetId(), $field_values['OrderItemId']);
}
$this->Conn->Query($query);
break;
case 'subscr_eot':
break;
case 'subscr_modify':
break;
}
return $success;
}
}
\ No newline at end of file
Index: branches/5.1.x/units/gateways/gw_classes/multicards.php
===================================================================
--- branches/5.1.x/units/gateways/gw_classes/multicards.php (revision 13464)
+++ branches/5.1.x/units/gateways/gw_classes/multicards.php (revision 13465)
@@ -1,124 +1,122 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
$class_name = 'kMultiCardsGW'; // for automatic installation
class kMultiCardsGW extends kGWBase
{
function InstallData()
{
$data = array(
'Gateway' => Array('Name' => 'Multicards', 'ClassName' => 'kMultiCardsGW', 'ClassFile' => 'multicards.php', 'RequireCCFields' => 0),
'ConfigFields' => Array(
'submit_url' => Array('Name' => 'Submit URL', 'Type' => 'text', 'ValueList' => '', 'Default' => 'https://secure.multicards.com/cgi-bin/order2/processorder1.pl'),
'merchant_id' => Array('Name' => 'Merchant ID', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
'merchant_url_idx' => Array('Name' => 'Merchant Order Page Id', 'Type' => 'text', 'ValueList' => '', 'Default' => ''),
)
);
return $data;
}
/**
* Returns payment form submit url
*
* @param Array $gw_params gateway params from payment type config
* @return string
*/
function getFormAction($gw_params)
{
return $gw_params['submit_url'];
}
/**
* Processed input data and convets it to fields understandable by gateway
*
* @param Array $item_data
* @param Array $tag_params additional params for gateway passed through tag
* @param Array $gw_params gateway params from payment type config
* @return Array
*/
function getHiddenFields($item_data, $tag_params, $gw_params)
{
$ret = Array();
$ret['mer_id'] = $gw_params['merchant_id'];
$ret['mer_url_idx'] = $gw_params['merchant_url_idx'];
$ret['num_items'] = 100;
$ret['item1_price'] = $item_data['TotalAmount'];
$ret['item1_desc'] = 'Order #'.$item_data['OrderNumber'];
$ret['item1_qty'] = 1;
// $ret['cancel_return'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));
// $ret['return'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
// $ret['notify_url'] = $this->Application->BaseURL('/in-commerce').'gw_notify.php?sid='.$this->Application->GetSID().'&admin=1&order_id='.$item_data['OrderId'];
// $ret['cmd'] = '_xclick'; // act as "Buy Now" PayPal button
$ret['no_note'] = 1; // customer is not prompted for notes
$ret['no_shipping'] = 1; // customer is not prompted for shipping address
$ret['rm'] = 2; // return method - POST
$ret['currency_code'] = $target;
$ret['invoice'] = $item_data['OrderNumber'];
$ret['business'] = $gw_params['business_account'];
// prepopulated fields
$billing_email = $item_data['BillingEmail'];
if (!$billing_email) {
$billing_email = $this->Conn->GetOne(' SELECT Email FROM '.$this->Application->getUnitOption('u', 'TableName').'
WHERE PortalUserId = '.$this->Application->RecallVar('user_id'));
}
$ret['cust_email'] = $billing_email;
$ret['cust_name'] = $item_data['BillingTo'];
$ret['cust_company'] = $item_data['BillingCompany'];
$ret['cust_phone'] = $item_data['BillingPhone'];
$ret['cust_address1'] = $item_data['BillingAddress1'];
$ret['cust_address2'] = $item_data['BillingAddress2'];
$ret['cust_city'] = $item_data['BillingCity'];
$ret['cust_state'] = $item_data['BillingState'];
$ret['cust_zip'] = $item_data['BillingZip'] ? $item_data['BillingZip'] : '99999';
-// $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = %s';
-// $ret['country'] = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($item_data['BillingCountry']) ) );
$ret['cust_country'] = $item_data['BillingCountry'];
$ret['user1'] = $this->Application->GetSID().','.MD5($item_data['OrderId']);
$url = $this->Application->HREF($tag_params['return_template'], '', array('pass'=>'m'));
$ret['user2'] = $url;
return $ret;
}
function processNotification($gw_params)
{
$this->parsed_responce = $_POST;
list ($sid, $auth_code) = explode(',', $this->Application->GetVar('user1'));
$session =& $this->Application->recallObject('Session');
$session->SID = $sid;
$order_id = $this->Conn->GetOne('SELECT OrderId FROM '.TABLE_PREFIX.'Orders WHERE md5(OrderId) = '.$this->Conn->qstr($auth_code));
$this->Application->SetVar('ord_id', $order_id);
$order =& $this->Application->recallObject('ord');
$order->Load($order_id);
$url = $this->Application->GetVar('user2');
echo '<!--success--><a href="'.$url.'">'.$this->Application->Phrase('la_multicards_continue').'</a>';
return 1;
}
}
\ No newline at end of file
Index: branches/5.1.x/units/shipping_quote_engines/usps.php
===================================================================
--- branches/5.1.x/units/shipping_quote_engines/usps.php (revision 13464)
+++ branches/5.1.x/units/shipping_quote_engines/usps.php (revision 13465)
@@ -1,1193 +1,1189 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
define('MODULE_SHIPPING_USPS_TEXT_TITLE', 'United States Postal Service');
define('MODULE_SHIPPING_USPS_TEXT_DESCRIPTION', 'You will need to have registered an account with USPS. Click <a target="_blank" href="https://secure.shippingapis.com/registration/"><strong>HERE</strong></a> for registration details. USPS expects you to use pounds as weight measure for your products.');
define('MODULE_SHIPPING_USPS_TEXT_ERROR', 'An error occured with the USPS shipping calculations.<br>If you prefer to use USPS as your shipping method, please contact the store owner.');
define('MODULE_SHIPPING_USPS_TEXT_DAY', 'Day');
define('MODULE_SHIPPING_USPS_TEXT_DAYS', 'Days');
define('MODULE_SHIPPING_USPS_TEXT_WEEKS', 'Weeks');
define('MODULE_SHIPPING_USPS_STATUS', 'True'); // Do you want to offer USPS shipping?
define('MODULE_SHIPPING_USPS_SERVER', 'production'); // An account at USPS is needed to use the Production server // production othervise value may be 'test'
define('MODULE_SHIPPING_USPS_HANDLING', '0'); // Handling fee for this shipping method
define('MODULE_SHIPPING_USPS_TAX_CLASS', '0'); // Use the following tax class on the shipping fee
define('MODULE_SHIPPING_USPS_ZONE', '0'); // If a zone is selected, only enable this shipping method for that zone.
define('MODULE_SHIPPING_USPS_SORT_ORDER', '0'); // Sort order of display.
define('MODULE_SHIPPING_USPS_TYPES', 'PRIORITY, PARCEL'); // EXPRESS, FIRST CLASS, BMP, MEDIA 'Select the domestic services to be offered:
define('MODULE_SHIPPING_USPS_TYPES_INTL', 'EXPRESS MAIL INTERNATIONAL (EMS), EXPRESS MAIL INT, EXPRESS MAIL INT FLAT RATE ENV, PRIORITY MAIL INT, PRIORITY MAIL INT FLAT RATE ENV, PRIORITY MAILINT FLAT RATE BOX, FIRST-CLASS MAIL INT');// 'GLOBAL EXPRESS, GLOBAL EXPRESS NON-DOC RECT, GLOBAL EXPRESS NON-DOC NON-RECT, Select the international services to be offered:
define('MODULE_SHIPPING_USPS_OPTIONS', 'Display weight, Display transit time'); //
//configuration values for insurance
define('MODULE_SHIPPING_USPS_INS1', '1.65');// 'US/Canada insurance for totals $.01-$50.00
define('MODULE_SHIPPING_USPS_INS2', '2.05');// 'US/Canada insurance for totals $50.01-$100
define('MODULE_SHIPPING_USPS_INS3', '2.45');// 'US/Canada insurance for totals $100.01-$200
define('MODULE_SHIPPING_USPS_INS4', '4.60');// 'US/Canada insurance for totals $200.01-$300
define('MODULE_SHIPPING_USPS_INS5', '.90');// 'US/Canada insurance for every $100 over $300 (add)
define('MODULE_SHIPPING_USPS_INS6', '2.40');// 'International insurance for totals $.01-$50.00
define('MODULE_SHIPPING_USPS_INS7', '3.30');// 'International insurance for totals $50.01-$100
define('MODULE_SHIPPING_USPS_INS8', '4.20');// 'International insurance for totals $100.01-$200
define('MODULE_SHIPPING_USPS_INS9', '5.10');// 'International insurance for totals $200.01-$300
define('MODULE_SHIPPING_USPS_INS10', '.90');// 'International insurance for every $100 over $300 (add)
define('MODULE_SHIPPING_USPS_INSURE', 'True');// 'Insure packages shipped by USPS?
define('MODULE_SHIPPING_USPS_INSURE_TAX', 'True');// 'Insure tax on packages shipped by USPS?
define('USPS_LOG_FILE', WRITEABLE .'/user_files/usps.log');
class USPS extends ShippingQuoteEngine
{
var $countries, $pounds, $ounces, $insurance_cost = 0, $shipping_origin_country, $store_first_name, $store_last_name, $company_name, $store_name, $store_address1, $store_address2, $store_city, $store_state, $store_zip5, $store_zip4, $store_phone, $usps_userid;
var $order = Array();
var $types = Array();
var $intl_types = Array();
function USPS()
{
parent::kBase();
// EXPRESS, FIRST CLASS, PRIORITY, PARCEL, BMP, MEDIA
$this->types = Array(
'EXPRESS' => 'Express Mail',
'FIRST CLASS' => 'First Class Mail',
'PRIORITY' => 'Priority Mail',
'PARCEL' => 'Parcel Post',
'BPM' => 'Bound Printed Matter',
'MEDIA' => 'Media Mail'
);
$this->intl_types = Array(
// 'GLOBAL EXPRESS' => 'Global Express Guaranteed',
// 'GLOBAL EXPRESS NON-DOC RECT' => 'Global Express Guaranteed Non-Document Rectangular',
// 'GLOBAL EXPRESS NON-DOC NON-RECT' => 'Global Express Guaranteed Non-Document Non-Rectangular',
'EXPRESS MAIL INT' => 'Express Mail International (EMS)',
'EXPRESS MAIL INT FLAT RATE ENV' => 'Express Mail International (EMS) Flat Rate Envelope',
'PRIORITY MAIL INT' => 'Priority Mail International',
'PRIORITY MAIL INT FLAT RATE ENV' => 'Priority Mail International Flat Rate Envelope',
'PRIORITY MAIL INT FLAT RATE BOX' => 'Priority Mail International Flat Rate Box',
'FIRST-CLASS MAIL INT' => 'First-Class Mail International'
);
// get 2-symbol country code
$country = $this->Application->ConfigValue('Comm_Shipping_Country');
if ($country != '') {
- $db =& $this->Application->GetADODBConnection();
- $this->shipping_origin_country = $db->GetOne(
- 'SELECT DestAbbr2
- FROM '.TABLE_PREFIX.'StdDestinations
- WHERE
- DestAbbr = '.$db->qstr($country).'
- AND destType = 1
- '
- );
+ $this->shipping_origin_country = $this->GetUSPSCountry($country, '');
}
+
$contact_name = trim($this->_prepare_xml_param($this->Application->ConfigValue('Comm_Contacts_Name')));
$split_pos = strpos($contact_name, ' ');
if ($split_pos === false) {
$this->store_first_name = $contact_name;
$this->store_last_name = '';
} else {
$this->store_first_name = substr($contact_name, 0, $split_pos);
$this->store_last_name = trim(substr($contact_name, $split_pos));
}
$this->company_name = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_CompanyName'));
$this->store_name = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_StoreName'));
$this->store_address1 = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_Shipping_AddressLine1'));
$this->store_address2 = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_Shipping_AddressLine2'));
if ($this->store_address2 == '') {
$this->store_address2 = $this->store_address1;
$this->store_address1 = '';
}
$this->store_city = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_Shipping_City'));
$this->store_state = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_Shipping_State'));
$zip = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_Shipping_ZIP'));
$this->store_zip5 = substr($zip, 0, 5);
$this->store_zip4 = trim(substr($zip, 6), '-');
$this->store_phone = $this->_prepare_xml_param($this->Application->ConfigValue('Comm_Contacts_Phone'));
// get username and password fron config.
$a_params = $this->LoadParams();
$this->usps_userid = $a_params['AccountLogin'];
// Note by Erik: DO NOT CHANGE THIS ARRAY. It's values are sent to USPS service and any changes may impact class main functionality.
$this->countries = array(
'AF' => 'Afghanistan',
'AL' => 'Albania',
'DZ' => 'Algeria',
'AD' => 'Andorra',
'AO' => 'Angola',
'AI' => 'Anguilla',
'AG' => 'Antigua and Barbuda',
'AR' => 'Argentina',
'AM' => 'Armenia',
'AW' => 'Aruba',
'AU' => 'Australia',
'AT' => 'Austria',
'AZ' => 'Azerbaijan',
'BS' => 'Bahamas',
'BH' => 'Bahrain',
'BD' => 'Bangladesh',
'BB' => 'Barbados',
'BY' => 'Belarus',
'BE' => 'Belgium',
'BZ' => 'Belize',
'BJ' => 'Benin',
'BM' => 'Bermuda',
'BT' => 'Bhutan',
'BO' => 'Bolivia',
'BA' => 'Bosnia-Herzegovina',
'BW' => 'Botswana',
'BR' => 'Brazil',
'VG' => 'British Virgin Islands',
'BN' => 'Brunei Darussalam',
'BG' => 'Bulgaria',
'BF' => 'Burkina Faso',
'MM' => 'Burma',
'BI' => 'Burundi',
'KH' => 'Cambodia',
'CM' => 'Cameroon',
'CA' => 'Canada',
'CV' => 'Cape Verde',
'KY' => 'Cayman Islands',
'CF' => 'Central African Republic',
'TD' => 'Chad',
'CL' => 'Chile',
'CN' => 'China',
'CX' => 'Christmas Island (Australia)',
'CC' => 'Cocos Island (Australia)',
'CO' => 'Colombia',
'KM' => 'Comoros',
'CG' => 'Congo (Brazzaville),Republic of the',
'ZR' => 'Congo, Democratic Republic of the',
'CK' => 'Cook Islands (New Zealand)',
'CR' => 'Costa Rica',
'CI' => 'Cote d\'Ivoire (Ivory Coast)',
'HR' => 'Croatia',
'CU' => 'Cuba',
'CY' => 'Cyprus',
'CZ' => 'Czech Republic',
'DK' => 'Denmark',
'DJ' => 'Djibouti',
'DM' => 'Dominica',
'DO' => 'Dominican Republic',
'TP' => 'East Timor (Indonesia)',
'EC' => 'Ecuador',
'EG' => 'Egypt',
'SV' => 'El Salvador',
'GQ' => 'Equatorial Guinea',
'ER' => 'Eritrea',
'EE' => 'Estonia',
'ET' => 'Ethiopia',
'FK' => 'Falkland Islands',
'FO' => 'Faroe Islands',
'FJ' => 'Fiji',
'FI' => 'Finland',
'FR' => 'France',
'GF' => 'French Guiana',
'PF' => 'French Polynesia',
'GA' => 'Gabon',
'GM' => 'Gambia',
'GE' => 'Georgia, Republic of',
'DE' => 'Germany',
'GH' => 'Ghana',
'GI' => 'Gibraltar',
'GB' => 'Great Britain and Northern Ireland',
'GR' => 'Greece',
'GL' => 'Greenland',
'GD' => 'Grenada',
'GP' => 'Guadeloupe',
'GT' => 'Guatemala',
'GN' => 'Guinea',
'GW' => 'Guinea-Bissau',
'GY' => 'Guyana',
'HT' => 'Haiti',
'HN' => 'Honduras',
'HK' => 'Hong Kong',
'HU' => 'Hungary',
'IS' => 'Iceland',
'IN' => 'India',
'ID' => 'Indonesia',
'IR' => 'Iran',
'IQ' => 'Iraq',
'IE' => 'Ireland',
'IL' => 'Israel',
'IT' => 'Italy',
'JM' => 'Jamaica',
'JP' => 'Japan',
'JO' => 'Jordan',
'KZ' => 'Kazakhstan',
'KE' => 'Kenya',
'KI' => 'Kiribati',
'KW' => 'Kuwait',
'KG' => 'Kyrgyzstan',
'LA' => 'Laos',
'LV' => 'Latvia',
'LB' => 'Lebanon',
'LS' => 'Lesotho',
'LR' => 'Liberia',
'LY' => 'Libya',
'LI' => 'Liechtenstein',
'LT' => 'Lithuania',
'LU' => 'Luxembourg',
'MO' => 'Macao',
'MK' => 'Macedonia, Republic of',
'MG' => 'Madagascar',
'MW' => 'Malawi',
'MY' => 'Malaysia',
'MV' => 'Maldives',
'ML' => 'Mali',
'MT' => 'Malta',
'MQ' => 'Martinique',
'MR' => 'Mauritania',
'MU' => 'Mauritius',
'YT' => 'Mayotte (France)',
'MX' => 'Mexico',
'MD' => 'Moldova',
'MC' => 'Monaco (France)',
'MN' => 'Mongolia',
'MS' => 'Montserrat',
'MA' => 'Morocco',
'MZ' => 'Mozambique',
'NA' => 'Namibia',
'NR' => 'Nauru',
'NP' => 'Nepal',
'NL' => 'Netherlands',
'AN' => 'Netherlands Antilles',
'NC' => 'New Caledonia',
'NZ' => 'New Zealand',
'NI' => 'Nicaragua',
'NE' => 'Niger',
'NG' => 'Nigeria',
'KP' => 'North Korea (Korea, Democratic People\'s Republic of)',
'NO' => 'Norway',
'OM' => 'Oman',
'PK' => 'Pakistan',
'PA' => 'Panama',
'PG' => 'Papua New Guinea',
'PY' => 'Paraguay',
'PE' => 'Peru',
'PH' => 'Philippines',
'PN' => 'Pitcairn Island',
'PL' => 'Poland',
'PT' => 'Portugal',
'QA' => 'Qatar',
'RE' => 'Reunion',
'RO' => 'Romania',
'RU' => 'Russia',
'RW' => 'Rwanda',
'SH' => 'Saint Helena',
'KN' => 'Saint Kitts (St. Christopher and Nevis)',
'LC' => 'Saint Lucia',
'PM' => 'Saint Pierre and Miquelon',
'VC' => 'Saint Vincent and the Grenadines',
'SM' => 'San Marino',
'ST' => 'Sao Tome and Principe',
'SA' => 'Saudi Arabia',
'SN' => 'Senegal',
'YU' => 'Serbia-Montenegro',
'SC' => 'Seychelles',
'SL' => 'Sierra Leone',
'SG' => 'Singapore',
'SK' => 'Slovak Republic',
'SI' => 'Slovenia',
'SB' => 'Solomon Islands',
'SO' => 'Somalia',
'ZA' => 'South Africa',
'GS' => 'South Georgia (Falkland Islands)',
'KR' => 'South Korea (Korea, Republic of)',
'ES' => 'Spain',
'LK' => 'Sri Lanka',
'SD' => 'Sudan',
'SR' => 'Suriname',
'SZ' => 'Swaziland',
'SE' => 'Sweden',
'CH' => 'Switzerland',
'SY' => 'Syrian Arab Republic',
'TW' => 'Taiwan',
'TJ' => 'Tajikistan',
'TZ' => 'Tanzania',
'TH' => 'Thailand',
'TG' => 'Togo',
'TK' => 'Tokelau (Union) Group (Western Samoa)',
'TO' => 'Tonga',
'TT' => 'Trinidad and Tobago',
'TN' => 'Tunisia',
'TR' => 'Turkey',
'TM' => 'Turkmenistan',
'TC' => 'Turks and Caicos Islands',
'TV' => 'Tuvalu',
'UG' => 'Uganda',
'UA' => 'Ukraine',
'AE' => 'United Arab Emirates',
'UY' => 'Uruguay',
'UZ' => 'Uzbekistan',
'VU' => 'Vanuatu',
'VA' => 'Vatican City',
'VE' => 'Venezuela',
'VN' => 'Vietnam',
'WF' => 'Wallis and Futuna Islands',
'WS' => 'Western Samoa',
'YE' => 'Yemen',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe'
);
$this->countryinsure = array(
'AF' => 0,
'AL' => 0,
'DZ' => 2185,
'AD' => 5000,
'AO' => 0,
'AI' => 415,
'AG' => 60,
'AR' => 5000,
'AM' => 1350,
'AW' => 830,
'AU' => 3370,
'AT' => 5000,
'AZ' => 5000,
'BS' => 2795,
'BH' => 0,
'BD' => 5000,
'BB' => 220,
'BY' => 1323,
'BE' => 5000,
'BZ' => 1600,
'BJ' => 170,
'BM' => 440,
'BT' => 440,
'BO' => 0,
'BA' => 5000,
'BW' => 145,
'BR' => 5000,
'VG' => 165,
'BN' => 4405,
'BG' => 1030,
'BF' => 530,
'MM' => 4045,
'BI' => 790,
'KH' => 0,
'CM' => 5000,
'CA' => 675,
'CV' => 0,
'KY' => 0,
'CF' => 4405,
'TD' => 440,
'CL' => 0,
'CN' => 1130,
'CX' => 3370,
'CC' => 3370,
'CO' => 0,
'KM' => 690,
'CG' => 1685,
'ZR' => 0,
'CK' => 980,
'CR' => 0,
'CI' => 5000,
'HR' => 5000,
'CU' => 0,
'CY' => 5000,
'CZ' => 5000,
'DK' => 5000,
'DJ' => 880,
'DM' => 0,
'DO' => 0,
'TP' => 0,
'EC' => 0,
'EG' => 1685,
'SV' => 0,
'GQ' => 0,
'ER' => 0,
'EE' => 2020,
'ET' => 1000,
'FK' => 510,
'FO' => 5000,
'FJ' => 600,
'FI' => 5000,
'FR' => 5000,
'GF' => 5000,
'PF' => 1015,
'GA' => 485,
'GM' => 2575,
'GE' => 1350,
'DE' => 5000,
'GH' => 5000,
'GI' => 5000,
'GB' => 857,
'GR' => 5000,
'GL' => 5000,
'GD' => 350,
'GP' => 5000,
'GT' => 0,
'GN' => 875,
'GW' => 21,
'GY' => 10,
'HT' => 0,
'HN' => 0,
'HK' => 5000,
'HU' => 5000,
'IS' => 5000,
'IN' => 2265,
'ID' => 0,
'IR' => 0,
'IQ' => 0,
'IE' => 5000,
'IL' => 0,
'IT' => 5000,
'JM' => 0,
'JP' => 5000,
'JO' => 0,
'KZ' => 5000,
'KE' => 815,
'KI' => 0,
'KW' => 1765,
'KG' => 1350,
'LA' => 0,
'LV' => 1350,
'LB' => 440,
'LS' => 440,
'LR' => 440,
'LY' => 0,
'LI' => 5000,
'LT' => 5000,
'LU' => 5000,
'MO' => 4262,
'MK' => 2200,
'MG' => 675,
'MW' => 50,
'MY' => 1320,
'MV' => 0,
'ML' => 950,
'MT' => 5000,
'MQ' => 5000,
'MR' => 635,
'MU' => 270,
'YT' => 5000,
'MX' => 0,
'MD' => 1350,
'MC' => 5000,
'MN' => 440,
'MS' => 2200,
'MA' => 5000,
'MZ' => 0,
'NA' => 4405,
'NR' => 220,
'NP' => 0,
'NL' => 5000,
'AN' => 830,
'NC' => 1615,
'NZ' => 980,
'NI' => 440,
'NE' => 810,
'NG' => 205,
'KP' => 0,
'NO' => 0,
'OM' => 575,
'PK' => 270,
'PA' => 0,
'PG' => 445,
'PY' => 0,
'PE' => 0,
'PH' => 270,
'PN' => 0,
'PL' => 1350,
'PT' => 5000,
'QA' => 2515,
'RE' => 5000,
'RO' => 5000,
'RU' => 5000,
'RW' => 0,
'SH' => 170,
'KN' => 210,
'LC' => 400,
'PM' => 5000,
'VC' => 130,
'SM' => 5000,
'ST' => 440,
'SA' => 0,
'SN' => 865,
'YU' => 5000,
'SC' => 0,
'SL' => 0,
'SG' => 4580,
'SK' => 5000,
'SI' => 4400,
'SB' => 0,
'SO' => 440,
'ZA' => 1760,
'GS' => 510,
'KR' => 5000,
'ES' => 5000,
'LK' => 35,
'SD' => 0,
'SR' => 535,
'SZ' => 560,
'SE' => 5000,
'CH' => 5000,
'SY' => 3080,
'TW' => 1350,
'TJ' => 1350,
'TZ' => 230,
'TH' => 1350,
'TG' => 2190,
'TK' => 295,
'TO' => 515,
'TT' => 930,
'TN' => 2200,
'TR' => 880,
'TM' => 675,
'TC' => 0,
'TV' => 4715,
'UG' => 0,
'UA' => 5000,
'AE' => 5000,
'UY' => 0,
'UZ' => 5000,
'VU' => 0,
'VA' => 5000,
'VE' => 0,
'VN' => 0,
'WF' => 1615,
'WS' => 295,
'YE' => 0,
'ZM' => 540,
'ZW' => 600,
'US' => 5000
);
}
function SetInsurance()
{
$this->insurance_cost = 0;
// Insurance module by Kevin Shelton
// divide the value of the order among the packages based on the order total or subtotal depending on whether or not you have configured to insure tax
$shipping_weight = $this->order['ShippingWeight'];
$shipping_num_boxes = $this->order['ShippingNumBoxes'];
$costperpkg = $this->order['SubTotal'] / $shipping_num_boxes;
// retrieve the maximum allowed insurance for the destination country and if the package value exceeds it then set package value to the maximum allowed
$maxins = $this->countryinsure[$this->order['ShippingCountry']];
if ($costperpkg > $maxins) $costperpkg = $maxins;
// if insurance not allowed for destination or insurance is turned off add nothing to shipping cost
if (($maxins == 0) || (MODULE_SHIPPING_USPS_INSURE == 'False')) {
$insurance = 0;
}
// US and Canada share the same insurance calculation (though not the same maximum)
else if (($this->order['ShippingCountry'] == 'US') || ($this->order['ShippingCountry'] == 'CA'))
{
if ($costperpkg<=50) {
$insurance=MODULE_SHIPPING_USPS_INS1;
}
else if ($costperpkg<=100) {
$insurance=MODULE_SHIPPING_USPS_INS2;
}
else if ($costperpkg<=200) {
$insurance=MODULE_SHIPPING_USPS_INS3;
}
else if ($costperpkg<=300) {
$insurance=MODULE_SHIPPING_USPS_INS4;
}
else {
$insurance = MODULE_SHIPPING_USPS_INS4 + ((ceil($costperpkg/100) -3) * MODULE_SHIPPING_USPS_INS5);
}
}
// if insurance allowed and is not US or Canada then calculate international insurance
else {
if ($costperpkg<=50) {
$insurance=MODULE_SHIPPING_USPS_INS6;
}
else if ($costperpkg<=100) {
$insurance=MODULE_SHIPPING_USPS_INS7;
}
else if ($costperpkg<=200) {
$insurance=MODULE_SHIPPING_USPS_INS8;
}
else if ($costperpkg<=300) {
$insurance=MODULE_SHIPPING_USPS_INS9;
}
else {
$insurance = MODULE_SHIPPING_USPS_INS9 + ((ceil($costperpkg/100) - 3) * MODULE_SHIPPING_USPS_INS10);
}
}
// usps doesnt accept zero weight
$shipping_weight = ($shipping_weight < 0.1 ? 0.1 : $shipping_weight);
$shipping_pounds = floor ($shipping_weight);
$shipping_ounces = round(16 * ($shipping_weight - floor($shipping_weight)));
$this->_setWeight($shipping_pounds, $shipping_ounces);
// Added by Kevin Chen (kkchen@uci.edu); Fixes the Parcel Post Bug July 1, 2004
// Refer to http://www.usps.com/webtools/htm/Domestic-Rates.htm documentation
// Thanks Ryan
if($shipping_pounds > 35 || ($shipping_pounds == 0 && $shipping_ounces < 6)){
$this->_setMachinable('False');
}
else{
$this->_setMachinable('True');
}
$this->insurance_cost = $insurance;
// End Kevin Chen July 1, 2004
}
function _setService($service)
{
$this->service = $service;
}
function _setWeight($pounds, $ounces=0)
{
$this->pounds = $pounds;
$this->ounces = $ounces;
}
function _setContainer($container)
{
$this->container = $container;
}
function _setSize($size)
{
$this->size = $size;
}
function _setMachinable($machinable)
{
$this->machinable = $machinable;
}
function PhoneClean($phone)
{
$res = ereg_replace("[(]|[)]|[\-]|[ ]|[#]|[\.]|[a-z](.*)|[A-Z](.*)", "", $phone);
if ( strlen($res) > 10 ) $res = substr($res, 0, 10);
return $res != '' ? $res : $phone;
}
function GetQuote($method = '')
{
if ( isset($this->types[$method]) || in_array($method, $this->intl_types)) {
$this->_setService($method);
}
$this -> _setContainer('None');
$this -> _setSize('REGULAR');
$this -> SetInsurance(); // ???
if ($this->order['ShippingCountry'] == $this->shipping_origin_country) {
$request='<?xml version="1.0"?>';
// PASSWORD="'.$this->usps_password.'"
$request.= '<RateV3Request USERID="'.$this->usps_userid.'">';
$services_count = 0;
if (isset($this->service)) {
$this->types = array($this->service => $this->types[$this->service]);
}
$dest_zip = str_replace(' ', '', $this->order['ShippingZip']);
$dest_zip = substr($dest_zip, 0, 5);
reset($this->types);
$allowed_types = explode(", ", MODULE_SHIPPING_USPS_TYPES);
while (list($key, $value) = each($this->types))
{
if ( !in_array($key, $allowed_types) ) continue;
$request .= '<Package ID="'.$services_count.'">'.
'<Service>'.$key.'</Service>'.
'<ZipOrigination>'.$this->store_zip5.'</ZipOrigination>'.
'<ZipDestination>'.$dest_zip.'</ZipDestination>'.
'<Pounds>'.$this->pounds.'</Pounds>'.
'<Ounces>'.$this->ounces.'</Ounces>'.
'<Size>'.$this->size.'</Size>'.
'<Machinable>'.$this->machinable.'</Machinable>'.
'</Package>';
$services_count++;
}
$request .= '</RateV3Request>';
$api_query = 'RateV3';
}
else {
$request = '<IntlRateRequest USERID="'.$this->usps_userid.'">'.
'<Package ID="0">'.
'<Pounds>'.$this->pounds.'</Pounds>'.
'<Ounces>'.$this->ounces.'</Ounces>'.
'<MailType>Package</MailType>'.
'<Country>'.$this->countries[$this->order['ShippingCountry']].'</Country>'.
'</Package>'.
'</IntlRateRequest>';
$api_query = 'IntlRate';
}
$request = 'API='.$api_query.'&XML=' . urlencode($request);
$body = $this->PostQuery($request);
$body = str_replace(chr(146), '', $body); // for bad `
// check for errors
if (strpos($body, '<Error>') !== false) {
$errors = Array ();
preg_match_all('/<Number>(.*?)<\/Number>/s', $body, $error_numbers);
preg_match_all('/<Description>(.*?)<\/Description>/s', $body, $error_descriptions);
foreach ($error_numbers[1] as $index => $error_number) {
$errors[$index] = $error_descriptions[1][$index];
if ($this->Application->isDebugMode()) {
$errors[$index] .= ' (' . $error_number . ')';
}
}
$errors = array_unique($errors); // we may have same errors on many packages, so don't show duplicates
return Array('error' => implode('<br/>', $errors));
}
// parse response
$xml_helper =& $this->Application->recallObject('kXMLHelper');
/* @var $xml_helper kXMLHelper */
$root_node =& $xml_helper->Parse($body);
/* @var $root_node kXMLNode */
$rates = Array();
// Domestic shipping
if ($this->order['ShippingCountry'] == $this->shipping_origin_country) {
$i = 0;
$postage_node =& $root_node->FindChild('Package');
do {
// $parcel_node =& $postage_node->firstChild;
$service = $postage_node->FindChildValue('MailService');
if ( $service != '' ) {
$i++;
$rates[$i] = Array();
$rates[$i]['Title'] = $service;
$rates[$i]['Rate'] = $this->insurance_cost + $postage_node->FindChildValue('Rate');
}
}
while ( $postage_node =& $postage_node->NextSibling());
}
else {
// for International Rates !!!
$allowed_types = array();
foreach( explode(", ", MODULE_SHIPPING_USPS_TYPES_INTL) as $value ) {
$allowed_types[$value] = $this->intl_types[$value];
}
$i = 0;
$service_node =& $root_node->FindChild('Service');
do {
$service = trim($service_node->FindChildValue('SvcDescription'));
if( !in_array($service, $allowed_types) ) continue;
$i++;
if ( $service_node->FindChildValue('MaxWeight') >= $this->pounds ) {
$rates[$i] = Array();
$rates[$i]['Title'] = $service;
$rates[$i]['MaxDimensions'] = $service_node->FindChildValue('MaxDimensions');
$rates[$i]['MaxWeight'] = $service_node->FindChildValue('MaxWeight');
$rates[$i]['SvcCommitments'] = $service_node->FindChildValue('SvcCommitments');
$rates[$i]['Rate'] = $this->insurance_cost + $service_node->FindChildValue('Postage');
}
}
while ( $service_node =& $service_node->NextSibling());
}
// print_r($rates);
// die('here');
return $rates;
}
function PostOrder()
{
$request='';
$base_request = '';
$this->SetInsurance();
// $this->order['ShippingCountry'] = $this->GetUSPSCountry($this->order['ShippingCountry']);
// Domestic Order
if ($this->order['ShippingCountry'] == $this->shipping_origin_country) {
// $dest_zip = str_replace(' ', '', $this->order['ShippingZip5']);
$this->order['ShippingZip5'] = substr($this->order['ShippingZip5'], 0, 5);
$WeightInOunces = floor($this->pounds * 16 + $this->ounces);
$base_request ='
<Option>1</Option>
<ImageParameters></ImageParameters>
<FromName>'.$this->store_name.'</FromName>
<FromFirm>'.$this->company_name.'</FromFirm>
<FromAddress1>'.$this->store_address1.'</FromAddress1>
<FromAddress2>'.$this->store_address2.'</FromAddress2>
<FromCity>'.$this->store_city.'</FromCity>
<FromState>'.$this->store_state.'</FromState>
<FromZip5>'.$this->store_zip5.'</FromZip5>
<FromZip4>'.$this->store_zip4.'</FromZip4>
<ToName>'.$this->order['FirstName'].' '.$this->order['LastName'].'</ToName>
<ToFirm>'.$this->order['ShippingCompany'].'</ToFirm>
<ToAddress1>'.$this->order['ShippingAddress2'].'</ToAddress1>
<ToAddress2>'.$this->order['ShippingAddress1'].'</ToAddress2>
<ToCity>'.$this->order['ShippingCity'].'</ToCity>
<ToState>'.$this->order['ShippingState'].'</ToState>
<ToZip5>'.$this->order['ShippingZip5'].'</ToZip5>
<ToZip4>'.$this->order['ShippingZip4'].'</ToZip4>
<WeightInOunces>'.$WeightInOunces.'</WeightInOunces>
<ServiceType>'.$this->order['ShippingService'].'</ServiceType>
<ImageType>PDF</ImageType>
<LabelDate>'.date('m/d/Y',time()).'</LabelDate>
<CustomerRefNo></CustomerRefNo>
<AddressServiceRequested></AddressServiceRequested>
<SenderName></SenderName><SenderEMail></SenderEMail>
<RecipientName></RecipientName>
<RecipientEMail></RecipientEMail>
';
$api_query = 'DeliveryConfirmationV3';
$xml_request = 'DeliveryConfirmationV3.0Request';
}
else {
// International Order(s)
$shipping_service = strtolower($this->order['ShippingService']);
$base_request = '<Option/>
<ImageParameters/>
<FromFirstName>'.$this->store_first_name.'</FromFirstName>
<FromLastName>'.$this->store_last_name.'</FromLastName>
<FromFirm>'.$this->company_name.'</FromFirm>
<FromAddress1>'.$this->store_address1.'</FromAddress1>
<FromAddress2>'.$this->store_address2.'</FromAddress2>
<FromCity>'.$this->store_city.'</FromCity>
<FromState>'.$this->store_state.'</FromState>
<FromZip5>'.$this->store_zip5.'</FromZip5>
<FromPhone>'.$this->PhoneClean($this->store_phone).'</FromPhone>
<ToName>'.$this->order['FirstName'].' '.$this->order['LastName'].'</ToName>
<ToFirm>'.$this->order['ShippingCompany'].'</ToFirm>
<ToAddress1></ToAddress1>
<ToAddress2>'.$this->order['ShippingAddress2'].'</ToAddress2>
<ToAddress3>'.$this->order['ShippingAddress1'].'</ToAddress3>
<ToCity>'.$this->order['ShippingCity'].'</ToCity>';
if ( $this->order['ShippingProvince'] != '' ) {
$base_request.='
<ToProvince>'.$this->order['ShippingProvince'].'</ToProvince>';
}
$base_request.='
<ToCountry>'.$this->countries[$this->order['ShippingCountry']].'</ToCountry>
<ToPostalCode>'.$this->order['ShippingZip'].'</ToPostalCode>
<ToPOBoxFlag>N</ToPOBoxFlag>
<ToPhone>'.$this->PhoneClean($this->order['ShippingPhone']).'</ToPhone>
<ToFax>'.$this->PhoneClean($this->order['ShippingFax']).'</ToFax>
<ToEmail>'.$this->order['Email'].'</ToEmail>
<ShippingContents>';
// add items
foreach ( $this->order['Items'] as $k => $value ) {
$base_request.='
<ItemDetail>
<Description>Computer Parts</Description>
<Quantity>'.$value['Qty'].'</Quantity>
<Value>'.($value['Price'] * $value['Qty']).'</Value>
<NetPounds>'.$value['NetPounds'].'</NetPounds>
<NetOunces>'.$value['NetOunces'].'</NetOunces>
<HSTariffNumber>123456</HSTariffNumber>
<CountryOfOrigin>United States</CountryOfOrigin>
</ItemDetail>';
}
// end add items
$base_request.='
</ShippingContents>
<GrossPounds>'.$this->pounds.'</GrossPounds>
<GrossOunces>'.$this->ounces.'</GrossOunces>
<ContentType>MERCHANDISE</ContentType>
<Agreement>Y</Agreement>
<InvoiceNumber>'.$this->order['InvoiceNumber'].'</InvoiceNumber>
<ImageType>PDF</ImageType>
<ImageLayout>ALLINONEFILE</ImageLayout>
<LabelDate>'.date('m/d/Y',time()).'</LabelDate>
';
if (strpos($shipping_service, 'express') !== false) {
$xml_request = 'ExpressMailIntlRequest';
$api_query = 'ExpressMailIntl';
}
elseif (strpos($shipping_service, 'priority') !== false) {
$xml_request = 'PriorityMailIntlRequest';
$api_query = 'PriorityMailIntl';
}
else {
$xml_request = 'FirstClassMailIntlRequest';
$api_query = 'FirstClassMailIntl';
}
}
$request.= '<'.$xml_request.' USERID="'.$this->usps_userid.'">';
$request.= $base_request;
$request.= '</'.$xml_request.'>';
// die($request);
$request = 'API='.$api_query.'&XML='.urlencode($request);
$body = $this->PostQuery($request, 1);
// check for errors
if (strpos($body, '<Error>') !== false) {
$errors = Array ();
preg_match_all('/<Number>(.*?)<\/Number>/s', $body, $error_numbers);
preg_match_all('/<Description>(.*?)<\/Description>/s', $body, $error_descriptions);
foreach ($error_numbers[1] as $index => $error_number) {
$errors[$index] = Array ('error_number' => $error_number, 'error_description' => $error_descriptions[1][$index]);
}
// TODO: find a way to return other error messages in same package as well
return $errors[0];
}
// parse response
$xml_helper =& $this->Application->recallObject('kXMLHelper');
$root_node =& $xml_helper->Parse($body);
/* @var $root_node kXMLNode */
$Postage = 0;
$label_file = $TrackingNumber = $PostnetBarCode = '';
// Domestic shipping
if ($this->order['ShippingCountry'] == $this->shipping_origin_country ) {
$delivery_node =& $root_node->FindChild('DeliveryConfirmationV3.0Response');
do {
$TrackingNumber = $delivery_node->FindChildValue('DeliveryConfirmationNumber');
$PostnetBarCode = $delivery_node->FindChildValue('Postnet');
$DeliveryConfirmationLabel = base64_decode($delivery_node->FindChildValue('DeliveryConfirmationLabel'));
}
while ( $delivery_node =& $delivery_node->NextSibling());
}
else {
if (strpos($shipping_service, 'express') !== false) {
$node_title = 'ExpressMailIntlResponse';
}
elseif (strpos($shipping_service, 'priority') !== false) {
$node_title = 'PriorityMailIntlResponse';
}
else {
$node_title = 'FirstClassMailIntlResponse';
}
$delivery_node =& $root_node->FindChild($node_title);
$PostnetBarCode = $delivery_node->FindChildValue('BarcodeNumber');
$Postage = $delivery_node->FindChildValue('Postage');
$DeliveryConfirmationLabel = base64_decode($delivery_node->FindChildValue('LabelImage'));
}
if ( $TrackingNumber != '' ) {
$label_file = USPS_LABEL_FOLDER.$TrackingNumber.".pdf";
}
elseif ( $PostnetBarCode != '' ) {
$label_file = USPS_LABEL_FOLDER.$PostnetBarCode.".pdf";
}
if ( $label_file != '' ) {
if (!$handle = fopen($label_file, 'a')) echo "Cannot open file ($label_file)";
if ( @fwrite($handle, $DeliveryConfirmationLabel) === FALSE) echo "Cannot write to file ($label_file)";
}
return array('TrackingNumber' => $TrackingNumber, 'PostnetBarCode' => $PostnetBarCode, 'Postage' => $Postage);
}
- function GetUSPSCountry($country)
+ function GetUSPSCountry($country, $default = 'US')
{
- $country = $this->Application->Conn->GetOne('SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = '.$this->Application->Conn->qstr($country));
- if ( $country == '' ) $country = 'US';
- return $country;
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $country = $cs_helper->getCountryIso($country);
+
+ return $country == '' ? $default : $country;
}
function GetShippingQuotes($params = null)
{
$weights = Kg2Pounds($params['packages']['0']['weight']);
$weight = '';
$weight = $weights[0];
if ( $weights[1] != '' ) {
$weight.='.'.$weights[1];
}
$country = $this->GetUSPSCountry($params['dest_country']);
$this->order = Array();
$this->order['ShippingWeight'] = $weight;
$this->order['ShippingNumBoxes'] = 1;
$this->order['ShippingZip'] = $params['dest_postal'];
$this->order['SubTotal'] = $params['amount'];
$this->order['ShippingCountry'] = $country;
$shipping_types = Array();
$rates = $this->GetQuote();
if ( !isset($rates['error']) ) {
$this->Application->RemoveVar('usps_errors');
$i = 1;
foreach ($rates as $k => $rate ) {
$shipping_types['USPS_'.$i] = Array(
'ShippingId' => 'USPS_'.$i,
'TotalCost' => $rate['Rate'],
'ShippingName' => $rate['Title'],
'Type' => '1',
'CODFlat' => '0',
'CODPercent' => '0',
'PortalGroups' => ',15,',
'InsuranceFee' => '',
'COD' => '0',
'SelectedOnly' => '0',
'Code' => $rate['Title']
);
$i++;
}
}
else {
// for Front-End (shipping screen) and Admin (Shipping Tab on editing order)
$this->Application->StoreVar('usps_errors', $rates['error']);
}
$this->Application->StoreVar('current_usps_shipping_types', serialize($shipping_types));
return $shipping_types;
}
function TrackOrder($TrackingNumber='')
{
if ( $TrackingNumber != '' ) {
// http://testing.shippingapis.com/ShippingAPITest.dll?API=TrackV2&XML=<TrackFieldRequest USERID="402INTEC7634"><TrackID ID="EJ958083578US"></TrackID></TrackFieldRequest>
$request = '<TrackRequest USERID="'.$this->usps_userid.'"><TrackID ID="'.$TrackingNumber.'"></TrackID></TrackRequest>';
$api_query = 'TrackV2';
$request = 'API='.$api_query.'&XML='.urlencode($request);
$body = $this->PostQuery($request);
// check for errors
if (strpos($body, '<Error>') !== false) {
$errors = Array ();
preg_match_all('/<Number>(.*?)<\/Number>/s', $body, $error_numbers);
preg_match_all('/<Description>(.*?)<\/Description>/s', $body, $error_descriptions);
foreach ($error_numbers[1] as $index => $error_number) {
$errors[$index] = $error_descriptions[1][$index];
if ($this->Application->isDebugMode()) {
$errors[$index] .= ' (' . $error_number . ')';
}
}
$errors = array_unique($errors); // we may have same errors on many packages, so don't show duplicates
return Array('error' => implode('<br/>', $errors));
}
$xml_helper =& $this->Application->recallObject('kXMLHelper');
$root_node =& $xml_helper->Parse($body);
/* @var $root_node kXMLNode */
// Tracking Shipping
$delivery_node =& $root_node->FindChild('TrackInfo');
$TrackSummary = $delivery_node->FindChildValue('TrackSummary');
// echo ' TrackSummary ('.$TrackingNumber.') = '.$TrackSummary.'<br>';
return strpos($TrackSummary, 'delivered') !== false ? 1 : 0;
}
else
return false;
}
function ProcessTrackOrders()
{
$sql = sprintf('SELECT `OrderId`, `ShippingTracking` FROM %s WHERE `Status` > 3 AND `Delivered` = 0', TABLE_PREFIX.'Orders');
$orders = $this->Application->Conn->Query($sql);
foreach ( $orders as $k => $order ) {
// try to track order
if ( $order['ShippingTracking'] != '' && $this->TrackOrder($order['ShippingTracking']) ) {
$update_order = sprintf("UPDATE %s SET `Delivered` = 1 WHERE %s = %s",
TABLE_PREFIX.'Orders',
$this->Application->getUnitOption('ord', 'IDField'),
$order[$this->Application->getUnitOption('ord', 'IDField')]
);
$this->Application->Conn->Query($update_order);
}
}
}
function PostQuery($request, $secure=0)
{
switch (MODULE_SHIPPING_USPS_SERVER) {
case 'production':
$usps_server = $secure > 0 ? 'https://secure.shippingapis.com' : 'http://production.shippingapis.com' ;
$api_dll = 'ShippingAPI.dll';
break;
case 'test':
$usps_server = $secure > 0 ? 'https://secure.shippingapis.com' : 'http://testing.shippingapis.com';
$api_dll = 'ShippingAPITest.dll';
break;
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $usps_server.'/'.$api_dll.'?'.$request);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$body = curl_exec($curl);
curl_close($curl);
if (defined('USPS_LOG_FILE')) {
$filename = USPS_LOG_FILE;
if ( !$fp = fopen($filename, "a") ) echo("Failed opening file $filename");
}
$request_url = sprintf("Date %s : IP %s\n\nPost\n\n%s\n\nReplay\n\n%s\n\n",
date("m/d/Y H:i:s",time()),
$_SERVER['REMOTE_ADDR'],
$usps_server.'/'.$api_dll.'?'.urldecode($request),
$body
);
if (defined('USPS_LOG_FILE')) {
if (!fwrite($fp, $request_url)) echo("Failed writing to file $filename");
fclose($fp);
}
return $body;
}
function GetAvailableTypes()
{
return array();
$conn =& $this->Application->GetADODBConnection();
$types = $conn->Query('SELECT * FROM '.TABLE_PREFIX.'ShippingType');
$ret = array();
foreach ($types as $a_type) {
$a_type['_ClassName'] = get_class($this);
$a_type['_Id'] = 'CUST_'.$a_type['ShippingID'];
$a_type['_Name'] = '(Custom) '.$a_type['Name'];
$ret[] = $a_type;
}
return $ret;
}
function LoadParams()
{
$sql = 'SELECT Properties FROM '.$this->Application->getUnitOption('sqe', 'TableName').'
WHERE ClassName="USPS"';
$db =& $this->Application->GetADODBConnection();
return unserialize($db->GetOne($sql));
}
function _prepare_xml_param($value) {
return strip_tags($value);
}
}
\ No newline at end of file
Index: branches/5.1.x/units/shipping_quote_engines/intershipper.php
===================================================================
--- branches/5.1.x/units/shipping_quote_engines/intershipper.php (revision 13464)
+++ branches/5.1.x/units/shipping_quote_engines/intershipper.php (revision 13465)
@@ -1,502 +1,502 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class Intershipper extends ShippingQuoteEngine {
var $state = Array();
var $quote = Array();
var $quotes = Array();
var $package_id;
var $box_id;
var $shipment_id;
var $FlatSurcharge = 0;
var $PercentSurcharge = 0;
function _stripTags($params)
{
foreach ($params as $param_name => $param_value) {
if (is_array($param_value)) {
$params[$param_name] = $this->_stripTags($param_value);
}
else {
$params[$param_name] = strip_tags($param_value);
}
}
return $params;
}
function BuildUrl($params = null)
{
$params = $this->_stripTags($params);
$this->shipment_id = isset($params['shipment_id']) ? $params['shipment_id'] : $this->GenerateId();
$url = 'www.intershipper.com/Interface/Intershipper/XML/v2.0/HTTP.jsp';
$uri = 'Username='. $params['AccountLogin'].
'&Password='. $params['AccountPassword'].
'&Version='. '2.0.0.0'.
'&ShipmentID='. $this->shipment_id.
'&QueryID='. $this->shipment_id.
'&TotalCarriers='. count($params['carriers']);
$i = 0;
foreach($params['carriers'] as $carrier)
{
$i++;
$uri .= '&CarrierCode'.$i.'='. rawurlencode($carrier['name']).
'&CarrierAccount'.$i.'='. rawurlencode($carrier['account']).
'&CarrierInvoiced'.$i.'='. $carrier['invoiced'];
}
$uri .= '&TotalClasses='. count($params['classes']);
$i = 0;
foreach($params['classes'] as $class)
{
$i++;
$uri .= '&ClassCode'.$i.'='. $class;
}
$uri .= '&DeliveryType='. 'COM'.
'&ShipMethod='. $params['ShipMethod'].
'&OriginationName='. rawurlencode( $params['orig_name'] ).
'&OriginationAddress1='.rawurlencode( $params['orig_addr1'] ).
'&OriginationAddress2='.rawurlencode( $params['orig_addr2'] ).
'&OriginationCity='. rawurlencode( $params['orig_city'] ).
'&OriginationState='. rawurlencode( $params['orig_state'] ).
'&OriginationPostal='. rawurlencode( $params['orig_postal'] ).
'&OriginationCountry='. rawurlencode( $params['orig_country'] ).
'&DestinationName='. rawurlencode( $params['dest_name'] ).
'&DestinationAddress1='.rawurlencode( $params['dest_addr1'] ).
'&DestinationAddress2='.rawurlencode( $params['dest_addr2'] ).
'&DestinationCity='. rawurlencode( $params['dest_city'] ).
'&DestinationState='. rawurlencode( $params['dest_state'] ).
'&DestinationPostal='. rawurlencode( $params['dest_postal'] ).
'&DestinationCountry='. rawurlencode( $params['dest_country'] ).
'&Currency='. 'USD'.
'&TotalPackages='. count($params['packages']);
$i = 0;
foreach($params['packages'] as $package)
{
$i++;
$uri .= '&BoxID'.$i.'='. urlencode( $package['package_key'] ).
'&Weight'.$i.'='. $package['weight'].
'&WeightUnit'.$i.'='. $package['weight_unit'].
'&Length'.$i.'='. $package['length'].
'&Width'.$i.'='. $package['width'].
'&Height'.$i.'='. $package['height'].
'&DimensionalUnit'.$i.'='. $package['dim_unit'].
'&Packaging'.$i.'='. $package['packaging'].
'&Contents'.$i.'='. $package['contents'].
'&Insurance'.$i.'='. $package['insurance'];
}
return Array('url' => $url, 'uri' => $uri);
}
function MergeParams($custom_params)
{
$params = $this->LoadParams();
$db = $this->Application->GetADODBConnection();
$this->FlatSurcharge = $params['FlatSurcharge'];
$this->PercentSurcharge = $params['PercentSurcharge'];
if($custom_params['carriers'])
{
$params['carriers'] = $custom_params['carriers'];
}
else
{
$carrier_codes = Array('UPS', 'FDX', 'DHL', 'USP', 'ARB');
$i = 0;
foreach($carrier_codes as $carrier)
{
if(isset($params[$carrier.'Enabled']) && $params[$carrier.'Enabled'])
{
$i++;
$params['carriers'][$i]['name'] = $carrier;
$params['carriers'][$i]['account'] = $params[$carrier.'Account'];
$params['carriers'][$i]['invoiced'] = (int) $params[$carrier.'Invoiced'];
}
}
}
if($custom_params['classes'])
{
$params['classes'] = $custom_params['classes'];
}
else
{
$classes = Array('1DY', '2DY', '3DY', 'GND');
foreach($classes as $class)
{
if(isset($params[$class.'Enabled']) && $params[$class.'Enabled'])
{
$params['classes'][] = $class;
}
}
}
- if(isset($custom_params['orig_addr1']))
- {
+ if (isset($custom_params['orig_addr1'])) {
$params['orig_name'] = $custom_params['orig_name'];
$params['orig_addr1'] = $custom_params['orig_addr1'];
$params['orig_addr2'] = $custom_params['orig_addr2'];
$params['orig_city'] = $custom_params['orig_city'];
$params['orig_state'] = $custom_params['orig_state'];
$params['orig_postal'] = $custom_params['orig_postal'];
$params['orig_country'] = $custom_params['orig_country'];
}
- else
- {
+ else {
$params['orig_name'] = $this->Application->ConfigValue('Comm_StoreName');
$params['orig_addr1'] = $this->Application->ConfigValue('Comm_Shipping_AddressLine1');
$params['orig_addr2'] = $this->Application->ConfigValue('Comm_Shipping_AddressLine2');
$params['orig_city'] = $this->Application->ConfigValue('Comm_Shipping_City');
$params['orig_state'] = $this->Application->ConfigValue('Comm_Shipping_State');
$params['orig_postal'] = $this->Application->ConfigValue('Comm_Shipping_ZIP');
$params['orig_country'] = $this->Application->ConfigValue('Comm_Shipping_Country');
}
- if( mb_strlen($params['orig_country']) == 3)
- {
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = "'.$params['orig_country'].'"';
- $params['orig_country'] = $db->GetOne($sql);
+
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ if (strlen($params['orig_country']) == 3) {
+ // got 3symbol ISO code -> resolve to 2symbol ISO code
+ $params['orig_country'] = $cs_helper->getCountryIso( $params['orig_country'] );
}
- if( mb_strlen($params['orig_state']) != 2)
- {
- $sql = ' SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations
- WHERE DestName = "'.$params['orig_state'].'"';
- $params['orig_state'] = $db->GetOne($sql);
+
+ if (strlen($params['orig_state']) != 2) {
+ // got state name instead of ISO code -> resolve it to ISO code
+ $country_iso = $cs_helper->getCountryIso($params['orig_country'], true);
+ $params['orig_state'] = $cs_helper->getStateIso($params['orig_state'], $country_iso);
}
- if(isset($custom_params['ShipMethod']))
- {
- $params['ShipMethod'] = $custom_params['ShipMethod'];
+ if (isset($custom_params['ShipMethod'])) {
+ $params['ShipMethod'] = $custom_params['ShipMethod'];
}
$params['packages'] = $custom_params['packages'];
$params['dest_name'] = $custom_params['dest_name'];
$params['dest_addr1'] = $custom_params['dest_addr1'];
$params['dest_addr2'] = $custom_params['dest_addr2'];
$params['dest_city'] = $custom_params['dest_city'];
$params['dest_state'] = $custom_params['dest_state'];
$params['dest_postal'] = $custom_params['dest_postal'];
$params['dest_country'] = $custom_params['dest_country'];
- if( mb_strlen($params['dest_country']) == 3)
- {
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = "'.$params['dest_country'].'"';
- $params['dest_country'] = $db->GetOne($sql);
+
+ if (strlen($params['dest_country']) == 3) {
+ // got 3symbol ISO code -> resolve to 2symbol ISO code
+ $params['dest_country'] = $cs_helper->getCountryIso( $params['dest_country'] );
}
if(!$params['dest_city'] || !$params['dest_country'] ||
(($params['dest_country'] == 'US' || $params['dest_country'] == 'CA') && !$params['dest_state']) ||
!$params['dest_postal'] || !$params['packages'])
{
$valid = false;
}
else
{
$valid = true;
}
return $valid ? $params : false;
}
function GenerateId()
{
static $id;
if(!$id)
{
$id = rand(0, 1000000);
}
return $id;
}
function getShipmentId()
{
return $this->shipment_id;
}
function GetShippingQuotes($params = null)
{
if(!is_array($params)) $params = unserialize($params);
$params = $this->MergeParams($params);
// print_pre($params);
if($params == false)
{
trigger_error('Incorrect params given to <em>intershipper</em> engine', E_USER_WARNING);
return;
}
$target_url = $this->BuildUrl($params);
// print_r($target_url);
$depth = Array();
$xml_parser = xml_parser_create();
xml_set_element_handler( $xml_parser, Array(&$this, 'startElement'), Array(&$this, 'endElement') );
xml_set_character_data_handler( $xml_parser, Array(&$this, 'characterData') );
$newdata = curl_post($target_url['url'], $target_url['uri']);
$newdata = substr($newdata, strpos($newdata, '<'));
if (!xml_parse($xml_parser, $newdata, 1)) {
trigger_error(sprintf('XML error: %s at line %d'),
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser), E_USER_WARNING);
}
xml_parser_free($xml_parser);
return array_shift($this->quotes); // array_shift must be removed after!!!
}
function startElement(&$Parser, &$Elem, $Attr)
{
array_push($this->state, $Elem);
$states = implode(' ',$this->state);
//check what state we are in
if($states == 'SHIPMENT PACKAGE') {
$this->package_id = $Attr['ID'];
}
elseif($states == 'SHIPMENT PACKAGE QUOTE') {
$quote = Array('package_id' => $this->package_id, 'id' => $Attr['ID']);
}
}
function characterData($Parser, $Line)
{
$states = join (' ',$this->state);
switch($states)
{
case 'SHIPMENT ERROR':
trigger_error($error = $Line, E_USER_WARNING);
break;
case 'SHIPMENT SHIPMENTID':
$this->shipment_id = $Line;
break;
case 'SHIPMENT PACKAGE BOXID':
$this->box_id = $Line;
break;
case 'SHIPMENT PACKAGE QUOTE CARRIER NAME':
$this->quote['carrier_name'] = $Line;
break;
case 'SHIPMENT PACKAGE QUOTE CARRIER CODE':
$this->quote['carrier_code'] = $Line;
break;
case 'SHIPMENT PACKAGE QUOTE CLASS NAME':
$this->quote['class_name'] = $Line;
break;
case 'SHIPMENT PACKAGE QUOTE CLASS CODE':
$this->quote['class_code'] = $Line;
break;
case 'SHIPMENT PACKAGE QUOTE SERVICE NAME':
$this->quote['service_name'] = $Line;
break;
case 'SHIPMENT PACKAGE QUOTE SERVICE CODE':
$this->quote['service_code'] = $Line;
break;
case 'SHIPMENT PACKAGE QUOTE RATE AMOUNT':
$this->quote['amount'] = $Line / 100;
break;
default:
}
}
function endElement($Parser, $Elem)
{
$states = implode(' ',$this->state);
if ($states == 'SHIPMENT PACKAGE QUOTE') {
unset($this->quote['id']);
unset($this->quote['package_id']);
// the $key is a combo of the carrier_code and service_code
// this is the logical way to key each quote returned
$this->quote['amount'] = $this->quote['amount']*(1+$this->PercentSurcharge/100) + $this->FlatSurcharge;
$amount_plain = $this->quote['amount'] * 100;
$key = 'INTSH_'.$this->quote['carrier_code'].'_'.$this->quote['class_code'].'_'.$amount_plain;
$this->quote['ShippingId'] = $key;
$this->quote['ShippingName'] = $this->quote['carrier_code'].' - '.$this->quote['service_name'];
$this->quote['TotalCost'] = $this->quote['amount'];
$this->quotes[$this->box_id][$key] = $this->quote;
}
array_pop($this->state);
}
function LoadParams()
{
$sql = 'SELECT Properties, FlatSurcharge, PercentSurcharge FROM '.$this->Application->getUnitOption('sqe', 'TableName').'
WHERE Name="Intershipper.com"';
$db = $this->Application->GetADODBConnection();
$data = $db->GetRow($sql);
$params = unserialize(getArrayValue($data, 'Properties'));
return array_merge($params, array('FlatSurcharge' => $data['FlatSurcharge'], 'PercentSurcharge' => $data['PercentSurcharge']));
}
function GetAvailableTypes()
{
$params = $this->LoadParams();
$carrier_codes = Array('UPS', 'FDX', 'DHL', 'USP', 'ARB');
$classes = Array('1DY', '2DY', '3DY', 'GND');
$i = 0;
foreach($carrier_codes as $carrier)
{
if(isset($params[$carrier.'Enabled']) && $params[$carrier.'Enabled'])
{
foreach($classes as $class)
{
if(isset($params[$class.'Enabled']) && $params[$class.'Enabled'])
{
$a_type['_ClassName'] = get_class($this);
$a_type['_Id'] = 'INTSH_'.$carrier.'_'.$class;
$a_type['_Name'] = '(Intershipper)'.$carrier.' '.$class;
$ret[] = $a_type;
}
}
}
}
return $ret;
}
}
/*$params = Array(
'AccountLogin' => 'login',
'AccountPassword' => 'password',
'carriers' => Array(
Array(
'name' => 'UPS',
'account' => '',
'invoiced' => '0'
),
Array(
'name' => 'DHL',
'account' => '',
'invoiced' => '0'
),
Array(
'name' => 'FDX',
'account' => '',
'invoiced' => '0'
),
Array(
'name' => 'USP',
'account' => '',
'invoiced' => '0'
),
Array(
'name' => 'ARB',
'account' => '',
'invoiced' => '0'
),
),
'classes' => Array('1DY', '2DY', '3DY', 'GND'),
'ShipMethod' => 'DRP',
'orig_name' => 'John%20Smith',
'orig_addr1' => '2275%20Union%20Road',
'orig_city' => 'Cheektowaga',
'orig_state' => 'NY',
'orig_postal' => '14227',
'orig_country' => 'US',
// this section is required
'dest_name' => 'Vasya%20Pupkin',
'dest_addr1' => '175%20E.Hawthorn%20pkwy.',
'dest_city' => 'Vernon%20Hills',
'dest_state' => 'IL',
'dest_postal' => '60061',
'dest_country' => 'US',
// this section is required
'packages' => Array(
Array(
'package_key' => 'package1',
'weight' => '50',
'weight_unit' => 'LB',
'length' => '25',
'width' => '15',
'height' => '15',
'dim_unit' => 'IN',
'packaging' => 'BOX',
'contents' => 'OTR',
'insurance' => '0'
),
Array(
'package_key' => 'package2',
'weight' => '50',
'weight_unit' => 'LB',
'length' => '25',
'width' => '15',
'height' => '15',
'dim_unit' => 'IN',
'packaging' => 'BOX',
'contents' => 'OTR',
'insurance' => '0'
),
),
'shipment_id' => 1234;
);
*/
/*
Returns:
$quotes = Array(
'package1' =>
Array(
Array(
'id' => 'INTSH_FDX_2DY',
'type' => 'FDX',
..
'amount' => 24.24,
)
Array(
'type' => 'FDX',
..
'amount' => 24.24,
)
),
'package2' =>
Array(
Array(
'id' => 'INTSH_FDX_3DY',
'type' => 'FDX',
..
'amount' => 24.24,
)
Array(
'type' => 'FDX',
..
'amount' => 24.24,
)
),
)
*/
\ No newline at end of file
Index: branches/5.1.x/units/shipping_quote_engines/custom_shipping_quote_engine.php
===================================================================
--- branches/5.1.x/units/shipping_quote_engines/custom_shipping_quote_engine.php (revision 13464)
+++ branches/5.1.x/units/shipping_quote_engines/custom_shipping_quote_engine.php (revision 13465)
@@ -1,179 +1,183 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class CustomShippingQuoteEngine extends ShippingQuoteEngine {
function GetShippingQuotes($params)
{
$db =& $this->Application->GetADODBConnection();
$packages = $params['packages'];
$default_pack = array_shift($packages);
$query = $this->QueryShippingCost($params['dest_country'], $params['dest_state'], $params['dest_postal'], $default_pack['weight'], $params['items'], $params['amount'], $params['shipping_type'], $params['promo_params']);
$shipping_types = $db->Query($query, 'ShippingId');
if (!$this->Application->isAdminUser) {
$user_groups = explode(',', $this->Application->RecallVar('UserGroups'));
$filteres_shipping_types = array();
foreach ($shipping_types as $key=>$shipping_type) {
$shipping_type_groups = explode(',', trim($shipping_type['PortalGroups'], ','));
if (array_intersect($shipping_type_groups, $user_groups)) {
$filteres_shipping_types[$key] = $shipping_type;
}
}
$shipping_types = $filteres_shipping_types;
}
return $shipping_types;
}
- function QueryShippingCost($user_country_abbr, $user_state_abbr, $user_zip, $weight, $items, $amount, $shipping_type=null, $promo_params)
+ function QueryShippingCost($user_country, $user_state, $user_zip, $weight, $items, $amount, $shipping_type=null, $promo_params)
{
$db =& $this->Application->GetADODBConnection();
- $user_country_id = (int) $db->GetOne('SELECT DestId FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1 AND DestAbbr = '.$db->qstr($user_country_abbr));
- $user_state_id = (int) $db->GetOne('SELECT DestId FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=2 AND DestAbbr = '.$db->qstr($user_state_abbr));
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $user_country_id = $cs_helper->getCountryStateId($user_country, DESTINATION_TYPE_COUNTRY);
+ $user_state_id = $cs_helper->getCountryStateId($user_state, DESTINATION_TYPE_STATE);
+
$user_zip = (string) $user_zip;
$weight = (float) $weight;
$items = (int) $items;
$amount = (float) $amount;
$promo_weight = $promo_params['weight'];
$promo_amount = (float) $promo_params['amount'];
$promo_items = (float) $promo_params['items'];
if (isset($shipping_type)) $shipping_type = (int) $shipping_type;
$query = 'SELECT
CONCAT("CUST_", st.ShippingID) as ShippingId,
IF(st.Type = 4, st.BaseFee, '.# taking only base fee for handling
'IF (
st.IsFreePromoShipping = 1 AND
( (st.FreeShippingMinAmount != 0 AND st.FreeShippingMinAmount <= '.$amount.') OR
(st.Type = 1 AND '.$promo_weight.' = 0) OR
(st.Type = 2 AND '.$promo_items.' = 0) OR
(st.Type = 3 AND '.$promo_amount.' = 0)
), 0,
MIN(
IF(st.BaseFee IS NULL, 0, st.BaseFee) +
IF(st.CostType IN (1,3), IF(sc.Flat IS NULL, 0, sc.Flat), 0) +
IF(st.CostType IN (2,3),
IF(sc.PerUnit IS NULL, 0, sc.PerUnit)
*
( CASE st.Type
WHEN 1 THEN IF(st.IsFreePromoShipping = 1, '.$promo_weight.', '.$weight.')
WHEN 2 THEN IF(st.IsFreePromoShipping = 1, '.$promo_items.', '.$items.')
WHEN 3 THEN IF(st.IsFreePromoShipping = 1, '.$promo_amount.', '.$amount.')
ELSE 0 END ),
0)
)
)
) AS TotalCost,
st.Name as ShippingName,
st.Type as Type,
st.CODFlatSurcharge as CODFlat,
st.CODPercentSurcharge as CODPercent,
st.PortalGroups as PortalGroups,
IF (
st.InsuranceType = 1,
st.InsuranceFee,
st.InsuranceFee * '.$amount.' / 100
) AS InsuranceFee,
IF(sz.CODallowed IS NULL, 0, sz.CODallowed) AS COD,
st.Status = 2 as SelectedOnly,
st.Code
FROM '.TABLE_PREFIX.'ShippingType AS st '. #all shipping types
'LEFT JOIN '.TABLE_PREFIX.'ShippingBrackets AS sb '. #getting brackets by shipping type
'ON sb.ShippingTypeID = st.ShippingID '.
'LEFT JOIN '.TABLE_PREFIX.'ShippingZones AS sz '. #getting zones by shipping type
'ON sz.ShippingTypeID = st.ShippingID '.
'LEFT JOIN '.TABLE_PREFIX.'ShippingZonesDestinations AS szd '. #getting destinations by shipping type
'ON szd.ShippingZoneId = sz.ZoneID '.
'LEFT JOIN '.TABLE_PREFIX.'ShippingCosts AS sc '. #getting costs by bracket and zone
'ON sc.BracketId = sb.BracketId AND sc.ZoneID = sz.ZoneID '.
'WHERE
'.(isset($shipping_type) ? 'st.ShippingID = '.$shipping_type.' AND ' : '').'
(st.Status >= 1) '. # enabled (1) or Selected Only (2) shipping types
'AND
(
'.# handlign should require brackets/zones (st.Type = 4) # handling - does not required brackets
# OR
'(
( st.Type IN (1,2,3,4) ) '. # bracket dependant types
'AND
'.# Zone match
'( (sz.Type = 1 AND
(szd.StdDestId = '.$user_country_id.') '.# user country id
')
OR
(sz.Type = 2 AND
(szd.StdDestId = '.$user_state_id.') '.# user state id
')
OR
(sz.Type = 3 AND
(szd.StdDestId = '.$user_country_id.') '.# user country id
'AND
(szd.DestValue = '.$db->qstr($user_zip).') '.# user zip code
')
)
AND
'.# Bracket match
'( (st.Type = 1
AND
sb.Start <= IF(st.IsFreePromoShipping = 1, '.$promo_weight.', '.$weight.') AND (sb.End > IF(st.IsFreePromoShipping = 1, '.$promo_weight.', '.$weight.') OR sb.End = -1) '.# items total weight
')
OR
(st.Type = 2
AND
sb.Start <= IF(st.IsFreePromoShipping = 1, '.$promo_items.', '.$items.') AND (sb.End > IF(st.IsFreePromoShipping = 1, '.$promo_items.', '.$items.') OR sb.End = -1) '.# items total qty
')
OR
(st.Type = 3
AND
sb.Start <= IF(st.IsFreePromoShipping = 1, '.$promo_amount.', '.$amount.') AND (sb.End > IF(st.IsFreePromoShipping = 1, '.$promo_amount.', '.$amount.') OR sb.End = -1) '.# items total amount
')
OR
st.Type = 4 '.# handling - does not depend on brackets
')
AND
'.# Empty costs handling
'( (st.ZeroIfEmpty = 0 AND (sc.Flat IS NOT NULL OR sc.PerUnit IS NOT NULL) ) '.# if no shimpent on empty - flat or perunit should be filled in
'OR
(st.ZeroIfEmpty = 1) '. # zero on empty - is ok (nulls will be converted in SELECT part)
'OR
(st.Type = 4) '. # ignore costs for handling
')
)
)
GROUP BY st.ShippingId '. # getting minimal price (possible with closest address match) for every shipping type
'ORDER BY TotalCost asc';
return $query;
}
function GetAvailableTypes()
{
$conn =& $this->Application->GetADODBConnection();
$types = $conn->Query('SELECT * FROM '.TABLE_PREFIX.'ShippingType');
$ret = array();
foreach ($types as $a_type) {
$a_type['_ClassName'] = get_class($this);
$a_type['_Id'] = 'CUST_'.$a_type['ShippingID'];
$a_type['_Name'] = '(Custom) '.$a_type['Name'];
$ret[] = $a_type;
}
return $ret;
}
}
\ No newline at end of file
Index: branches/5.1.x/units/shipping_quote_engines/shipping_quote_engine_event_handler.php
===================================================================
--- branches/5.1.x/units/shipping_quote_engines/shipping_quote_engine_event_handler.php (revision 13464)
+++ branches/5.1.x/units/shipping_quote_engines/shipping_quote_engine_event_handler.php (revision 13465)
@@ -1,128 +1,131 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class ShippingQuoteEngineEventHandler extends kDBEventHandler {
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
if($object->GetDBField('AccountPassword') == '')
{
$sql = 'SELECT Properties FROM '.$object->TableName.'
WHERE EngineId = '.$object->GetDBField('EngineId');
$properties = unserialize( $this->Conn->GetOne($sql) );
$object->SetDBField('AccountPassword', $properties['AccountPassword']);
}
$properties = Array(
'AccountLogin' => $object->GetDBField('AccountLogin'),
'AccountPassword' => $object->GetDBField('AccountPassword'),
'UPSEnabled' => $object->GetDBField('UPSEnabled'),
'UPSAccount' => $object->GetDBField('UPSAccount'),
'UPSInvoiced' => $object->GetDBField('UPSInvoiced'),
'FDXEnabled' => $object->GetDBField('FDXEnabled'),
'FDXAccount' => $object->GetDBField('FDXAccount'),
'DHLEnabled' => $object->GetDBField('DHLEnabled'),
'DHLAccount' => $object->GetDBField('DHLAccount'),
'DHLInvoiced' => $object->GetDBField('DHLInvoiced'),
'USPEnabled' => $object->GetDBField('USPEnabled'),
'USPAccount' => $object->GetDBField('USPAccount'),
'USPInvoiced' => $object->GetDBField('USPInvoiced'),
'ARBEnabled' => $object->GetDBField('ARBEnabled'),
'ARBAccount' => $object->GetDBField('ARBAccount'),
'ARBInvoiced' => $object->GetDBField('ARBInvoiced'),
'1DYEnabled' => $object->GetDBField('1DYEnabled'),
'2DYEnabled' => $object->GetDBField('2DYEnabled'),
'3DYEnabled' => $object->GetDBField('3DYEnabled'),
'GNDEnabled' => $object->GetDBField('GNDEnabled'),
'ShipMethod' => $object->GetDBField('ShipMethod'),
);
$properties = serialize($properties);
$object->SetDBField('Properties', $properties);
$from_country = $this->Application->ConfigValue('Comm_Shipping_Country');
- if( mb_strlen($from_country) == 3)
- {
- $sql = 'SELECT DestAbbr2 FROM '.TABLE_PREFIX.'StdDestinations WHERE DestAbbr = "'.$from_country.'"';
- $from_country = $this->Conn->GetOne($sql);
+ if (strlen($from_country) == 3) {
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ // get 2symbol ISO code from 3symbol ISO code
+ $from_country = $cs_helper->getCountryIso($from_country);
}
+
if( !function_exists('curl_init') )
{
$object->FieldErrors['Status']['pseudo'] = 'curl_not_present';
$object->ErrorMsgs['curl_not_present'] = $this->Application->Phrase('la_error_EnableCurlFirst');
}
elseif( $object->GetDBField('Status') == 1 && (!$this->Application->ConfigValue('Comm_Shipping_City') || !$from_country ||
( ($from_country == 'US' || $from_country == 'CA') && !$this->Application->ConfigValue('Comm_Shipping_State') ) ||
!$this->Application->ConfigValue('Comm_Shipping_ZIP') ) )
{
$object->FieldErrors['Status']['pseudo'] = 'from_info_not_filled_in';
$object->ErrorMsgs['from_info_not_filled_in'] = $this->Application->Phrase('la_error_FillInShippingFromAddress');
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function iterateItems(&$event)
{
// $event->setEventParam('SkipProcessing', 1);
parent::iterateItems($event);
if($event->Name == 'OnMassApprove')
{
$event->status = erSUCCESS;
$event->redirect = true;
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnAfterItemLoad(&$event)
{
$object =& $event->getObject();
$properties = unserialize( $object->GetDBField('Properties') );
$object->SetDBFieldsFromHash($properties);
}
function OnAfterItemCreate(&$event)
{
$event->CallSubEvent('OnAnyChange');
}
function OnAfterItemUpdate(&$event)
{
$event->CallSubEvent('OnAnyChange');
}
function OnAfterItemDelete(&$event)
{
$event->CallSubEvent('OnAnyChange');
}
function OnAnyChange(&$event)
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Cache WHERE VarName LIKE "ShippingQuotes%"';
$this->Conn->Query($sql);
}
}
\ No newline at end of file
Index: branches/5.1.x/units/manufacturers/manufacturers_event_handler.php
===================================================================
--- branches/5.1.x/units/manufacturers/manufacturers_event_handler.php (revision 13464)
+++ branches/5.1.x/units/manufacturers/manufacturers_event_handler.php (revision 13465)
@@ -1,116 +1,123 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class ManufacturersEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnItemBuild' => Array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
if ($this->Application->isAdminUser) {
return ;
}
$category_id = $this->Application->GetVar('m_cat_id');
$parent_category_id = $event->getEventParam('parent_cat_id');
if ($parent_category_id) {
if ($parent_category_id != 'any' && $parent_category_id > 0) {
$category_id = $parent_category_id;
}
}
$sql = 'SELECT m.ManufacturerId, COUNT(p.ProductId)
FROM '.TABLE_PREFIX.'Manufacturers m
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ManufacturerId = m.ManufacturerId
LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON ci.ItemResourceId = p.ResourceId
LEFT JOIN '.TABLE_PREFIX.'Category c ON c.CategoryId = ci.CategoryId
WHERE (ci.PrimaryCat = 1) AND (p.Status = ' . STATUS_ACTIVE . ') AND (c.Status = ' . STATUS_ACTIVE . ') GROUP BY m.ManufacturerId';
// add category filter
$tree_indexes = $this->Application->getTreeIndex($category_id);
// if category_id is 0 returs false
if ($tree_indexes) {
$sql .= ' AND c.TreeLeft BETWEEN '.$tree_indexes['TreeLeft'].' AND '.$tree_indexes['TreeRight'];
}
$manufacturers = $this->Conn->GetCol($sql);
$object =& $event->getObject();
$object->addFilter('category_manufacturer_filter', $manufacturers ? '%1$s.ManufacturerId IN (' . implode(',', $manufacturers) . ')' : 'FALSE');
}
/**
* Prefill states dropdown with correct values
*
* @param kEvent $event
* @access public
*/
- function OnPrepareStates(&$event)
+ function OnAfterItemLoad(&$event)
{
- $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
- $cs_helper->PopulateStates($event, 'State', 'Country');
-
- $object =& $event->getObject();
+ parent::OnAfterItemLoad($event);
- if( $object->isRequired('Country') && $cs_helper->CountryHasStates( $object->GetDBField('Country') ) ) $object->setRequired('State', true);
- }
-
- function OnUpdate(&$event)
- {
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
- $cs_helper->CheckStateField($event, 'State', 'Country');
+ /* @var $cs_helper kCountryStatesHelper */
- parent::OnUpdate($event);
+ $cs_helper->PopulateStates($event, 'State', 'Country');
}
- function OnCreate(&$event)
+ /**
+ * Processes states
+ *
+ * @param kEvent $event
+ */
+ function OnBeforeItemUpdate(&$event)
{
+ parent::OnBeforeItemUpdate($event);
+
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
- $cs_helper->CheckStateField($event, 'State', 'Country');
+ /* @var $cs_helper kCountryStatesHelper */
- parent::OnCreate($event);
+ $cs_helper->CheckStateField($event, 'State', 'Country');
+ $cs_helper->PopulateStates($event, 'State', 'Country');
}
- function OnPreSave(&$event)
+ /**
+ * Processes states
+ *
+ * @param kEvent $event
+ */
+ function OnBeforeItemCreate(&$event)
{
+ parent::OnBeforeItemCreate($event);
+
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
- $cs_helper->CheckStateField($event, 'State', 'Country');
+ /* @var $cs_helper kCountryStatesHelper */
- parent::OnPreSave($event);
+ $cs_helper->CheckStateField($event, 'State', 'Country');
+ $cs_helper->PopulateStates($event, 'State', 'Country');
}
-
}
\ No newline at end of file
Index: branches/5.1.x/units/manufacturers/manufacturers_config.php
===================================================================
--- branches/5.1.x/units/manufacturers/manufacturers_config.php (revision 13464)
+++ branches/5.1.x/units/manufacturers/manufacturers_config.php (revision 13465)
@@ -1,148 +1,136 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array(
'Prefix' => 'manuf',
'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'),
'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'),
'EventHandlerClass' => Array('class'=>'ManufacturersEventHandler','file'=>'manufacturers_event_handler.php','build_event'=>'OnBuild'),
'TagProcessorClass' => Array('class'=>'ManufacturersTagProcessor','file'=>'manufacturers_tag_processor.php','build_event'=>'OnBuild'),
'AutoLoad' => true,
- 'Hooks' => Array(
- Array(
- 'Mode' => hAFTER,
- 'Conditional' => false,
- 'HookToPrefix' => 'manuf',
- 'HookToSpecial' => '',
- 'HookToEvent' => Array('OnAfterItemLoad', 'OnBeforeItemCreate', 'OnBeforeItemUpdate', 'OnUpdateAddress'),
- 'DoPrefix' => '',
- 'DoSpecial' => '',
- 'DoEvent' => 'OnPrepareStates',
- ),
- ),
+
'QueryString' => Array(
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'IDField' => 'ManufacturerId',
'StatusField' => Array(),
'TableName' => TABLE_PREFIX.'Manufacturers',
'TitlePresets' => Array(
'default' => Array( 'new_status_labels' => Array('manuf'=>'!la_title_AddingManufacturer!'),
'edit_status_labels' => Array('manuf'=>'!la_title_EditingManufacturer!'),
'new_titlefield' => Array('manuf'=>'!la_title_NewManufacturers!'),
),
'manuf_list'=>Array( 'prefixes' => Array('manuf_List'),
'format' => "!la_title_Manufacturers!",
),
'manuf_edit'=>Array( 'prefixes' => Array('manuf'),
'new_titlefield' => Array('manuf'=>'!la_title_NewManufacturer!'),
'format' => "#manuf_status# '#manuf_titlefield#' - !la_title_General!",
),
),
'PermSection' => Array('main' => 'in-commerce:manufacturers'),
'Sections' => Array(
'in-commerce:manufacturers' => Array(
'parent' => 'in-commerce',
'icon' => 'manufacturers',
'label' => 'la_tab_Manufacturers',
'url' => Array('t' => 'in-commerce/manufacturers/manufacturers_list', 'pass' => 'm'),
'permissions' => Array('view', 'add', 'edit', 'delete'),
'priority' => 4,
'type' => stTREE,
),
),
'TitleField' => 'Name', // field, used in bluebar when editing existing item
'ListSQLs' => Array( ''=>'SELECT * FROM %s',
), // key - special, value - list select sql
'ItemSQLs' => Array(''=>'SELECT * FROM %s',
),
'ListSortings' => Array(
'' => Array(
'Sorting' => Array('Name' => 'asc'),
)
),
'Fields' => Array (
'ManufacturerId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0,),
'Name' => Array('type' => 'string','not_null' => '1','default' => '', 'required'=>true,'max_len'=>255),
'Description' => Array('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => NULL),
'URL' => Array('type' => 'string','not_null' => '1','default' => '','max_len'=>255),
'Logo' => Array (
'type' => 'string',
'formatter' => 'kPictureFormatter',
'max_size' => MAX_UPLOAD_SIZE, 'upload_dir' => IMAGES_PATH.'manufacturers/',
'file_types' => '*.jpg;*.gif;*.png', 'files_description' => '!la_hint_ImageFiles!',
'multiple' => false,
'max_len' => 255, 'not_null' => 1, 'default' => ''
),
'IsPopular' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (0 => 'la_No', 1 => 'la_Yes'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 0),
'Email' => Array('type' => 'string', 'formatter'=>'kFormatter', 'regexp'=>'/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i', 'sample_value' => 'email@domain.com', 'default' => null, 'error_msgs' => Array('invalid_format'=>'!la_invalid_email!') ),
'Phone' => Array('type' => 'string','default' => null),
'Fax' => Array('type' => 'string', 'default' => null),
'Address1' => Array('type' => 'string','default' => null),
'Address2' => Array('type' => 'string', 'default' => null),
'City' => Array('type' => 'string','default' => null),
'State' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter', 'options' => Array(),
'default' => null
),
'Zip' => Array('type' => 'string', 'default' => null),
'Country' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter',
- 'options_sql' => ' SELECT %1$s
- FROM '.TABLE_PREFIX.'StdDestinations
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = '.TABLE_PREFIX.'StdDestinations.DestName
- WHERE DestType = 1
- ORDER BY l%2$s_Translation',
- 'option_key_field' => 'DestAbbr', 'option_title_field' => 'l%2$s_Translation', 'default' => null
+ 'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
+ FROM '.TABLE_PREFIX.'CountryStates
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
+ ORDER BY Name',
+ 'option_key_field' => 'IsoCode', 'option_title_field' => 'Name', 'default' => null
),
),
'Grids' => Array (
'Default' => Array (
'Icons' => Array (
'default' => 'icon16_item.png',
0 => 'icon16_disabled.png',
1 => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array (
'ManufacturerId' => Array ('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 60, ),
'Name' => Array ('title' => 'la_col_ManufacturerName', 'filter_block' => 'grid_like_filter', 'width' => 200, ),
'IsPopular' => Array ('title' => 'la_col_IsPopular', 'filter_block' => 'grid_options_filter', 'width' => 100, ),
'URL' => Array ('title' => 'la_col_URL', 'filter_block' => 'grid_like_filter', 'width' => 250, ),
),
),
),
'ConfigMapping' => Array (
'PerPage' => 'Comm_Perpage_Manufacturers',
'ShortListPerPage' => 'Comm_Perpage_Manufacturers_Short',
),
);
\ No newline at end of file
Index: branches/5.1.x/units/taxes/taxes_tag_processor.php
===================================================================
--- branches/5.1.x/units/taxes/taxes_tag_processor.php (revision 13464)
+++ branches/5.1.x/units/taxes/taxes_tag_processor.php (revision 13465)
@@ -1,471 +1,273 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class TaxesTagProcessor extends kDBTagProcessor
{
- /*
- function ShowDestinations($param)
- {
- $zone =& $this->Application->recallObject('tax');
- $zone->SetDBField('TaxZoneId', $zone->ID);
- $destination =& $this->Application->recallObject('taxdst');
-
- if(!$this->Application->GetVar('loaded'))
- {
- if ($zone->GetID() == 0)
- {
- $this->Application->DeleteVar('taxdst');
- }
- else
- {
- $sql = 'SELECT * FROM '.$destination->TableName.' WHERE TaxZoneId='.$zone->GetID();
- $res = $this->Conn->Query($sql);
- if (is_array($res)) foreach ($res as $dest_record)
- {
- $temp[$dest_record['TaxZoneDestId']]['TaxZoneDestId'] = $dest_record['TaxZoneDestId'];
- $temp[$dest_record['TaxZoneDestId']]['StdDestId'] = $dest_record['StdDestId'];
- $temp[$dest_record['TaxZoneDestId']]['DestValue'] = $dest_record['DestValue'];
- }
- $this->Application->SetVar('taxdst', $temp);
- }
- }
- $destination =& $this->Application->recallObject('taxdst');
-
- $hidden_clause = '<input type="hidden" name="loaded" value="1"><input type="hidden" name="zone_id" value="'.$zone->GetDBField('TaxZoneId').'">';
- switch ( $zone->GetDBField('Type') )
- {
- case 1:
+ function ShowCountries($params)
+ {
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
- $sql = 'SELECT * FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1';
- $res = $this->Conn->Query($sql, 'DestId');
+ $destination_table = $this->getDestinationsTable($params);
+ $selected_country_id = (int)$this->Application->GetVar('CountrySelector');
- $dropdown = '<select name="country">'."\n";
- foreach ($res as $record)
- {
- $dropdown .= '<option value="'.$record['DestId'].'">'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
- }
- $dropdown .= '</select>'."\n";
+ $name_field = 'l' . $this->Application->GetVar('m_lang') . '_Name';
+ $id_field = $this->Application->getUnitOption('country-state', 'IDField');
+ $table_name = $this->Application->getUnitOption('country-state', 'TableName');
- $form_params = Array();
- $form_params['dropdown'] = $dropdown;
- $form_params['block'] = $param['block'];
- $form_params['res'] = $res;
- $ret = $this->ShowDestionationForm($form_params);
- break;
- case 2:
-
- $country_sql = 'SELECT d1.* FROM '.TABLE_PREFIX.'StdDestinations d1,
- '.TABLE_PREFIX.'StdDestinations d2
- WHERE d1.DestType=1 AND d1.DestId=d2.DestParentId
- GROUP BY d1.DestId';
- if( !($current_country = $this->Application->GetVar('StatesCountry')) )
- {
- $current_country_sql = 'SELECT sd.DestParentId FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd
- ON zd.StdDestId = sd.DestId
- WHERE sd.DestType=2 AND zd.TaxZoneId='.$zone->GetDBField('TaxZoneId');
- if($zone->GetDBField('TaxZoneId'))
- {
- $current_country = $this->Conn->GetOne($current_country_sql);
- }
+ switch ($params['show']) {
+ case 'current':
+ // selected countries in current zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE cs.Type = ' . DESTINATION_TYPE_COUNTRY . ' AND zd.TaxZoneId = ' . $object->GetID() . '
+ ORDER BY cs.' . $name_field;
+ break;
- if(!$current_country)
- {
- $current_country_sql = 'SELECT DestId FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1';
- $current_country = $this->Conn->GetOne($current_country_sql);
- }
- }
- $states_sql = 'SELECT * FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=2 AND DestParentId='.$current_country;
- $countries = $this->Conn->Query($country_sql, 'DestId');
- $states = $this->Conn->Query($states_sql, 'DestId');
-
- if($countries)
- {
- $countries_dropdown = '<select name="StatesCountry" onchange="submit_event(\'tax\', \'OnCountryChange\')">'."\n";
- foreach ($countries as $record)
- {
- $countries_dropdown .= '<option value="'.$record['DestId'].'" ';
- if($record['DestId'] == $current_country)
- {
- $countries_dropdown .= 'selected';
- }
- $countries_dropdown .= '>'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
- }
- $countries_dropdown .= '</select>'."\n";
- }
+ case 'available':
+ // available countries in current zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE cs.Type = ' . DESTINATION_TYPE_COUNTRY . ' AND zd.TaxZoneId IS NULL
+ ORDER BY cs.' . $name_field;
+ break;
- if($states)
- {
- $states_dropdown = '<select name="state">'."\n";
- foreach ($states as $id => $record)
- {
- $states_dropdown .= '<option value="'.$record['DestId'].'">'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
+ case 'all':
+ // always preselect 1st country, when user haven't selected any
+ if (!$selected_country_id) {
+ $sql = 'SELECT StdDestId
+ FROM ' . $destination_table . '
+ WHERE TaxZoneId = ' . $object->GetID();
+ $selected_country_id = $this->Conn->GetOne($sql);
+
+ if ($selected_country_id) {
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
}
- $states_dropdown .= '</select>'."\n";
}
- $form_params = Array();
- $table = '<table border="0"><tr><td>'.$this->Application->Phrase('la_Country').': </td><td>'.$countries_dropdown.'</td></tr>';
- $table .= '<tr><td>'.$this->Application->Phrase('la_State').': </td><td>'.$states_dropdown.'</td></tr></table>';
- $form_params['dropdown'] = $table;
- $form_params['block'] = $param['block'];
- $form_params['res'] = $states;
- $ret = $this->ShowDestionationForm($form_params);
-
- break;
- case 3:
-
- if( !($current_country = $this->Application->GetVar('StatesCountry')) )
- {
- $current_country_sql = 'SELECT sd.DestParentId FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd
- ON zd.StdDestId = sd.DestId
- WHERE sd.DestType=2 AND zd.TaxZoneId='.$zone->GetDBField('TaxZoneId');
- if($zone->GetDBField('TaxZoneId'))
- {
- $current_country = $this->Conn->GetOne($current_country_sql);
- }
-
- if(!$current_country)
- {
- $current_country_sql = 'SELECT StdDestId FROM '.$destination->TableName.' WHERE TaxZoneId='.$zone->GetID();
- $current_country = $this->Conn->GetOne($current_country_sql);
- }
+ // all countries
+ $sql = 'SELECT ' . $name_field . ', ' . $id_field . '
+ FROM ' . $table_name . '
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
+ ORDER BY ' . $name_field;
+ break;
- if(!$current_country)
- {
- $current_country_sql = 'SELECT DestId FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1';
- $current_country = $this->Conn->GetOne($current_country_sql);
- }
+ case 'has_states':
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+ $has_states = $cs_helper->getCountriesWithStates();
- }
+ if ($selected_country_id && !array_key_exists($selected_country_id, $has_states)) {
+ list ($selected_country_id, ) = each($has_states);
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
+ }
+
+ // preselect country from 1st found state
+ if (!$selected_country_id) {
+ $sql = 'SELECT cs.StateCountryId
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE (cs.Type = ' . DESTINATION_TYPE_STATE . ') AND (zd.TaxZoneId = ' . $object->GetID() . ')';
+ $selected_country_id = $this->Conn->GetOne($sql);
- $country_sql = 'SELECT d1.* FROM '.TABLE_PREFIX.'StdDestinations d1
- WHERE d1.DestType=1
- GROUP BY d1.DestId';
- $countries = $this->Conn->Query($country_sql, 'DestId');
-
- if($countries)
- {
- $countries_dropdown = '<select name="StatesCountry" onchange="submit_event(\'tax\', \'OnCountryChange\')">'."\n";
- foreach ($countries as $record)
- {
- print "<br>";
- $countries_dropdown .= '<option value="'.$record['DestId'].'" ';
- if($record['DestId'] == $current_country)
- {
- $countries_dropdown .= 'selected';
- }
- $countries_dropdown .= '>'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
+ if ($selected_country_id) {
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
}
- $countries_dropdown .= '</select>'."\n";
- }
-
- $sql = 'SELECT DestValue FROM '.$this->Application->getUnitOption('taxdst', 'TableName').' WHERE NOT(DestValue IS NULL) AND DestValue<>"" AND StdDestId='.$current_country;
- $res = array_unique( $this->Conn->GetCol($sql) );
- $dropdown = '<input type="text" name="zip_input" id="zip_input" size="15">';
- if($res)
- {
- $dropdown .= ' or <select name="zip_dropdown">'."\n";
- $dropdown .= '<option value=""></option>';
- foreach ($res as $record)
- {
- $dropdown .= '<option value="'.$record.'">'.$record.'</option>'."\n";
+ else {
+ list ($selected_country_id, ) = each($has_states);
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
}
- $dropdown .= '</select>'."\n";
}
- $table = '<table border="0"><tr><td>'.$this->Application->Phrase('la_Country').': </td><td>'.$countries_dropdown.'</td></tr>';
- $table .= '<tr><td>'.$this->Application->Phrase('la_fld_ZIP').': </td><td>'.$dropdown.'</td></tr></table>';
-
- $form_params = Array();
- $form_params['dropdown'] = $table;
- $form_params['block'] = $param['block'];
- $form_params['res'] = $res;
- $ret = $this->ShowDestionationForm($form_params);
-
+ // gets only countries with states
+ $sql = 'SELECT ' . $name_field . ', ' . $id_field . '
+ FROM ' . $table_name . '
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . ' AND ' . $id_field . ' IN (' . implode(',', array_keys($has_states)) . ')
+ ORDER BY ' . $name_field;
break;
+
default:
+ trigger_error('Unknown "show" parameter value "' . $params['show'] . '" used.', E_USER_ERROR);
+ break;
}
- $ret .= $hidden_clause;
- return $ret;
- }
- */
- /*
- function ShowDestionationForm($param)
- {
- $add_button = '<input type="button" class="button" value="'.$this->Application->Phrase('la_btn_AddLocation').'" onclick="submit_event(\'tax\', \'OnAddLocation\')">';
-
- $main_processor =& $this->Application->RecallObject('m_TagProcessor');
- $oddevenparam['odd'] = 'table-color1';
- $oddevenparam['even'] = 'table-color2';
- $ret = '<tr class="'.$main_processor->Odd_Even($oddevenparam).'"><td></td><td>'.$param['dropdown'].'</td><td>'.$add_button.'</td></tr>';
-
- $dest_list = $this->Application->GetVar('taxdst');
- if (is_array($dest_list))
- {
-
-
- if (sizeof($dest_list)>0){
- $ret .= '<tr class="'.$main_processor->Odd_Even($oddevenparam).'"><td>&nbsp;</td><td>';
- $ret .= '<select multiple name="location_list" onchange="SelectToString(this)">';
- $hidden = '';
-
- foreach ($dest_list as $id => $destination)
- {
- $params = $destination;
- $params['id'] = $id;
- $hidden .= '<input type="hidden" id="taxdst['.$destination['TaxZoneDestId'].'][TaxZoneDestId]" name="taxdst['.$destination['TaxZoneDestId'].'][TaxZoneDestId]" value="'.$destination['TaxZoneDestId'].'">';
- if($destination['StdDestId'] && !$destination['DestValue'])
- {
- $params['destination_title'] = $param['res'][$destination['StdDestId']]['DestName'];
- $hidden .= '<input type="hidden" id="taxdst['.$destination['TaxZoneDestId'].'][StdDestId]" name="taxdst['.$destination['TaxZoneDestId'].'][StdDestId]" value="'.$destination['StdDestId'].'">';
- }
- else
- {
- $params['destination_title'] = $destination['DestValue'];
- $hidden .= '<input type="hidden" id="taxdst['.$destination['TaxZoneDestId'].'][DestValue]" name="taxdst['.$destination['TaxZoneDestId'].'][DestValue]" value="'.$destination['DestValue'].'">';
- }
+ $ret = '';
+ $countries = $this->Conn->GetCol($sql, $id_field);
- $params['name'] = $param['block'];
- $ret .= $main_processor->ParseBlock($params);
- }
- $ret .= '</select>';
+ $block_params = $this->prepareTagParams($params);
+ $block_params['name'] = $params['block'];
- $ret .= '</td><td><input type="button" class="button" value="'.$this->Application->Phrase('la_btn_RemoveLocations').'" onclick="remove_location('.$destination['TaxZoneDestId'].')">';
- $ret .= $hidden;
- $ret .= "&nbsp;</td></tr>";
- }else{
+ foreach ($countries as $country_id => $country_name) {
+ $block_params['id'] = $country_id;
+ $block_params['destination_title'] = $country_name;
+ $block_params['selected'] = $selected_country_id == $country_id ? ' selected="selected"' : '';
- }
+ $ret .= $this->Application->ParseBlock($block_params);
}
-// <input type="hidden" id="taxdst[<inp:m_param name="id"/>][TaxZoneDestId]" name="taxdst[<inp:m_param name="id"/>][TaxZoneDestId]" value="<inp:m_param name="id"/>">
return $ret;
}
- */
- function ShowCountries($param){
- $param = $this->prepareTagParams($param);
- $param['name'] = $param['block'];
+ function ShowStates($params)
+ {
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
+
+ $destination_table = $this->getDestinationsTable($params);
+
+ $name_field = 'l' . $this->Application->GetVar('m_lang') . '_Name';
+ $id_field = $this->Application->getUnitOption('country-state', 'IDField');
+ $table_name = $this->Application->getUnitOption('country-state', 'TableName');
- $destination = &$this->Application->recallObject('taxdst');
- $zone = &$this->Application->recallObject('tax');
+ $country_id = $this->Application->GetVar('CountrySelector');
- switch ($param['show']){
+ switch ($params['show']) {
case 'current':
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1 AND zd.TaxZoneId = '.$zone->GetDBField('TaxZoneId').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ // selected states for current country and zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE
+ cs.Type = ' . DESTINATION_TYPE_STATE . ' AND
+ cs.StateCountryId = ' . $country_id . ' AND
+ zd.TaxZoneId = ' . $object->GetID() . '
+ ORDER BY cs.' . $name_field;
break;
case 'available':
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1 AND zd.TaxZoneId IS NULL
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ // available states for current country and zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE
+ cs.Type = ' . DESTINATION_TYPE_STATE . '
+ AND zd.TaxZoneId IS NULL
+ AND cs.StateCountryId = ' . $country_id . '
+ ORDER BY cs.' . $name_field;
break;
case 'all':
- $selected_country = $this->Application->GetVar('CountrySelector');
- if (!$selected_country){
- // get 1st available country ID
- $selected_country = $this->Conn->GetOne('SELECT StdDestId FROM '.$destination->TableName.'
- WHERE TaxZoneId='.$zone->GetDBField('TaxZoneId'));
- if ($selected_country){
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
- }
-
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ // all possible states for selected country
+ $sql = 'SELECT ' . $name_field . ', ' . $id_field . '
+ FROM ' . $table_name . '
+ WHERE Type = ' . DESTINATION_TYPE_STATE . ' AND StateCountryId = ' . $country_id . '
+ ORDER BY ' . $name_field;
break;
- case 'has_states':
- $has_states = $this->Conn->GetCol('SELECT DISTINCT DestParentId FROM '.TABLE_PREFIX.'StdDestinations sd
- WHERE sd.DestType=2');
- $selected_country = $this->Application->GetVar('CountrySelector');
-
- if ($selected_country && !in_array($selected_country, $has_states)){
- $selected_country = $has_states[0];
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
-
- if (!$selected_country){
- // get 1st available country ID
- $selected_country = $this->Conn->GetOne('SELECT DestParentId FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd
- ON zd.StdDestId = sd.DestId
- WHERE sd.DestType=2
- AND zd.TaxZoneId='.$zone->GetDBField('TaxZoneId'));
- if ($selected_country){
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
- else {
- $selected_country = $has_states[0];
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
- }
-
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1 AND DestId IN ('.implode(',', $has_states).')
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ default:
+ trigger_error('Unknown "show" parameter value "' . $params['show'] . '" used.', E_USER_ERROR);
break;
}
- $countries = $this->Conn->Query($sql);
- $o = '';
+ $ret = '';
+ $states = $this->Conn->GetCol($sql, $id_field);
+ $block_params = $this->prepareTagParams($params);
+ $block_params['name'] = $params['block'];
- foreach($countries as $key => $country) {
- $param['id'] = $country['DestId'];
- $param['destination_title'] = $this->Application->Phrase($country['DestName']);
- if (isset($selected_country) && $selected_country == $param['id']){
- $param['selected'] = ' selected="selected"';
- }
- else {
- $param['selected']='';
- }
- $o .= $this->Application->ParseBlock($param);
+ foreach($states as $state_id => $state_name) {
+ $block_params['id'] = $state_id;
+ $block_params['destination_title'] = $state_name;
+
+ $ret .= $this->Application->ParseBlock($block_params);
}
- return $o;
+ return $ret;
}
- function ShowStates($param)
+ function ShowZips($params)
{
- $param = $this->prepareTagParams($param);
- $param['name'] = $param['block'];
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
- $destination = &$this->Application->recallObject('taxdst');
- $zone = &$this->Application->recallObject('tax');
+ $destination_table = $this->getDestinationsTable($params);
- switch ($param['show']){
- case 'current':
- $sql = 'SELECT *
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
+ $country_id = (int)$this->Application->GetVar('CountrySelector');
+
+ $current_sql = 'SELECT DestValue
+ FROM ' . $destination_table . '
WHERE
- sd.DestType=2
- AND sd.DestParentId='.$this->Application->GetVar('CountrySelector').'
- AND zd.TaxZoneId='.$zone->GetDBField('TaxZoneId').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ COALESCE(DestValue, "") <> "" AND
+ TaxZoneId = ' . $object->GetID() . '
+ ORDER BY DestValue';
+
+ switch ($params['show']) {
+ case 'current':
+ $sql = $current_sql;
break;
case 'available':
- $sql = 'SELECT *
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
+ $selected_zips = $this->Conn->GetCol($current_sql);
+ $selected_zips = array_map(Array (&$this->Conn, 'qstr'), $selected_zips);
+
+ $sql = 'SELECT DISTINCT DestValue
+ FROM ' . $this->Application->getUnitOption('taxdst', 'TableName') . '
WHERE
- sd.DestType=2
- AND zd.TaxZoneId IS NULL
- AND sd.DestParentId='.$this->Application->GetVar('CountrySelector').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ COALESCE(DestValue, "") <> "" AND
+ TaxZoneId <> ' . $object->GetID() . ' AND
+ ' . ($selected_zips ? 'DestValue NOT IN (' . implode(',', $selected_zips) . ') AND' : '') . '
+ StdDestId = ' . $country_id . '
+ ORDER BY DestValue';
break;
- case 'all':
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 2 AND sd.DestParentId='.$this->Application->GetVar('CountrySelector').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ default:
+ trigger_error('Unknown "show" parameter value "' . $params['show'] . '" used.', E_USER_ERROR);
break;
}
- $states = $this->Conn->Query($sql);
- $o = '';
- foreach($states as $key => $state) {
- $param['id'] = $state['DestId'];
- $param['destination_title'] = $this->Application->Phrase($state['DestName']);
- $o .= $this->Application->ParseBlock($param);
- }
- return $o;
+ $zips = $this->Conn->GetCol($sql);
- }
+ $ret = '';
+ $block_params = $this->prepareTagParams($params);
+ $block_params['name'] = $params['block'];
- function ShowZips($param){
+ foreach($zips as $zip) {
+ $block_params['id'] = '0|' . $zip;
+ $block_params['destination_title'] = $zip;
- $param = $this->prepareTagParams($param);
- $param['name'] = $param['block'];
+ $ret .= $this->Application->ParseBlock($block_params);
+ }
- $destination = &$this->Application->recallObject('taxdst');
- $zone = &$this->Application->recallObject('tax');
+ return $ret;
+ }
- $country_selector = $this->Application->GetVar('CountrySelector');
- if (!$country_selector){
- $country_selector=0;
- }
+ /**
+ * Returns table for shipping zone destinations
+ *
+ * @param Array $params
+ * @return string
+ */
+ function getDestinationsTable($params)
+ {
+ static $table_name = '';
- switch ($param['show']){
- case 'current':
- $sql = 'SELECT * FROM '.$destination->TableName.'
- WHERE NOT(DestValue IS NULL)
- AND DestValue<>""
- AND TaxZoneID='.$zone->GetDBField('TaxZoneId').'
- ORDER BY DestValue
- ';
- break;
- case 'available':
- $selected_zips = $this->Conn->GetCol('SELECT DestValue FROM '.$destination->TableName.'
- WHERE NOT(DestValue IS NULL)
- AND DestValue<>""
- AND TaxZoneID='.$zone->GetDBField('TaxZoneId').'
- ORDER BY DestValue
- ');
-
- $sql = 'SELECT DISTINCT(DestValue) FROM '.$this->Application->getUnitOption('taxdst', 'TableName').'
- WHERE NOT(DestValue IS NULL)
- AND TaxZoneID!='.$zone->GetDBField('TaxZoneId').'
- AND DestValue NOT IN ("'.implode('", "', $selected_zips).'")
- AND DestValue<>"" AND StdDestId='.$country_selector.'
- ORDER BY DestValue
- ';
+ if (!$table_name) {
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
- break;
- case 'all':
- $sql = 'SELECT sd.* FROM '.TABLE_PREFIX.'StdDestinations sd
- WHERE sd.DestType=3 AND sd.DestParentId='.$country_selector.'
- ORDER BY DestValue
- ';
- break;
- }
+ $table_name = $this->Application->getUnitOption('taxdst', 'TableName');
- $zips = $this->Conn->Query($sql);
- $o = '';
- foreach($zips as $key => $zip) {
- $param['id'] = $zip['DestId'].'|'.$zip['DestValue'];
- $param['destination_title'] = $zip['DestValue'];
- $o .= $this->Application->ParseBlock($param);
+ if ($object->IsTempTable()) {
+ $table_name = $this->Application->GetTempName($table_name, 'prefix:' . $this->Prefix);
+ }
}
- return $o;
+ return $table_name;
}
-
}
\ No newline at end of file
Index: branches/5.1.x/units/zones/zones_tag_processor.php
===================================================================
--- branches/5.1.x/units/zones/zones_tag_processor.php (revision 13464)
+++ branches/5.1.x/units/zones/zones_tag_processor.php (revision 13465)
@@ -1,460 +1,272 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class ZonesTagProcessor extends kDBTagProcessor
{
- /*
- function ShowDestinations($param)
+ function ShowCountries($params)
{
- $zone =& $this->Application->recallObject('z');
- $zone->SetDBField('ZoneID', $zone->ID);
- $destination =& $this->Application->recallObject('dst');
-
- if(!$this->Application->GetVar('loaded'))
- {
- if ($zone->GetID() == 0)
- {
- $this->Application->DeleteVar('dst');
- }
- else
- {
- $sql = 'SELECT * FROM '.$destination->TableName.' WHERE ShippingZoneId='.$zone->GetID();
- $res = $this->Conn->Query($sql);
- if (is_array($res)) foreach ($res as $dest_record)
- {
- $temp[$dest_record['ZoneDestId']]['ZoneDestId'] = $dest_record['ZoneDestId'];
- $temp[$dest_record['ZoneDestId']]['StdDestId'] = $dest_record['StdDestId'];
- $temp[$dest_record['ZoneDestId']]['DestValue'] = $dest_record['DestValue'];
- }
- $this->Application->SetVar('dst', $temp);
- }
- }
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
- $hidden_clause = '<input type="hidden" name="loaded" value="1"><input type="hidden" name="zone_id" value="'.$zone->GetDBField('ZoneID').'">';
+ $destination_table = $this->getDestinationsTable($params);
+ $selected_country_id = (int)$this->Application->GetVar('CountrySelector');
- switch ( $zone->GetDBField('Type') )
- {
- case 1:
-
- $sql = 'SELECT * FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1';
- $res = $this->Conn->Query($sql, 'DestId');
- $dropdown = '<select name="country">'."\n";
- foreach ($res as $record)
- {
- $dropdown .= '<option value="'.$record['DestId'].'">'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
- }
- $dropdown .= '</select>'."\n";
+ $name_field = 'l' . $this->Application->GetVar('m_lang') . '_Name';
+ $id_field = $this->Application->getUnitOption('country-state', 'IDField');
+ $table_name = $this->Application->getUnitOption('country-state', 'TableName');
- $form_params = Array();
- $form_params['dropdown'] = $dropdown;
- $form_params['block'] = $param['block'];
- $form_params['res'] = $res;
- $ret = $this->ShowDestionationForm($form_params);
-
- break;
- case 2:
-
- $country_sql = 'SELECT d1.* FROM '.TABLE_PREFIX.'StdDestinations d1,
- '.TABLE_PREFIX.'StdDestinations d2
- WHERE d1.DestType=1 AND d1.DestId=d2.DestParentId
- GROUP BY d1.DestId';
- if( !($current_country = $this->Application->GetVar('StatesCountry')) )
- {
- $current_country_sql = 'SELECT sd.DestParentId FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd
- ON zd.StdDestId = sd.DestId
- WHERE sd.DestType=2 AND zd.ShippingZoneId='.$zone->GetDBField('ZoneID');
- if($zone->GetDBField('ZoneID'))
- {
- $current_country = $this->Conn->GetOne($current_country_sql);
- }
+ switch ($params['show']) {
+ case 'current':
+ // selected countries in current zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE cs.Type = ' . DESTINATION_TYPE_COUNTRY . ' AND zd.ShippingZoneId = ' . $object->GetID() . '
+ ORDER BY cs.' . $name_field;
+ break;
- if(!$current_country)
- {
- $current_country_sql = ' SELECT d1.DestId FROM '.TABLE_PREFIX.'StdDestinations d1
- LEFT JOIN '.TABLE_PREFIX.'StdDestinations d2
- ON d1.DestId = d2.DestParentId
- WHERE d1.DestType=1
- AND d2.DestId IS NOT NULL';
- $current_country = $this->Conn->GetOne($current_country_sql);
- }
- }
- $states_sql = 'SELECT * FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=2 AND DestParentId='.$current_country;
- $countries = $this->Conn->Query($country_sql, 'DestId');
- $states = $this->Conn->Query($states_sql, 'DestId');
-
- if($countries)
- {
- $countries_dropdown = '<select name="StatesCountry" onchange="submit_event(\'z\', \'OnCountryChange\')">'."\n";
- foreach ($countries as $record)
- {
- $countries_dropdown .= '<option value="'.$record['DestId'].'" ';
- if($record['DestId'] == $current_country)
- {
- $countries_dropdown .= 'selected';
- }
- $countries_dropdown .= '>'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
- }
- $countries_dropdown .= '</select>'."\n";
- }
+ case 'available':
+ // available countries in current zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE cs.Type = ' . DESTINATION_TYPE_COUNTRY . ' AND zd.ShippingZoneId IS NULL
+ ORDER BY cs.' . $name_field;
+ break;
- if($states)
- {
- $states_dropdown = '<select name="state">'."\n";
- foreach ($states as $id => $record)
- {
- $states_dropdown .= '<option value="'.$record['DestId'].'">'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
+ case 'all':
+ // always preselect 1st country, when user haven't selected any
+ if (!$selected_country_id) {
+ $sql = 'SELECT StdDestId
+ FROM ' . $destination_table . '
+ WHERE ShippingZoneId = ' . $object->GetID();
+ $selected_country_id = $this->Conn->GetOne($sql);
+
+ if ($selected_country_id) {
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
}
- $states_dropdown .= '</select>'."\n";
}
- $form_params = Array();
- $table = '<table border="0"><tr><td>'.$this->Application->Phrase('la_fld_Country').': </td><td>'.$countries_dropdown.'</td></tr>';
- $table .= '<tr><td>'.$this->Application->Phrase('la_fld_State').': </td><td>'.$states_dropdown.'</td></tr></table>';
- $form_params['dropdown'] = $table;
- $form_params['block'] = $param['block'];
- $form_params['res'] = $states;
- $ret = $this->ShowDestionationForm($form_params);
-
- break;
- case 3:
-
- $country_sql = 'SELECT * FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1';
- if( !($current_country = $this->Application->GetVar('ZIPCountry')) )
- {
- $current_country_sql = 'SELECT StdDestId FROM '.$destination->TableName.'
- WHERE ShippingZoneId='.$zone->GetDBField('ZoneID');
- $cur_country = (int)$this->Conn->GetOne($current_country_sql);
- if($zone->GetDBField('ZoneID') && $cur_country)
- {
- $current_country = $cur_country;
- }
- else
- {
- $current_country_sql = 'SELECT MIN(DestId) FROM '.TABLE_PREFIX.'StdDestinations';
- $current_country = (int)$this->Conn->GetOne($current_country_sql);
- }
- }
- $countries = $this->Conn->Query($country_sql, 'DestId');
+ // all countries
+ $sql = 'SELECT ' . $name_field . ', ' . $id_field . '
+ FROM ' . $table_name . '
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
+ ORDER BY ' . $name_field;
+ break;
- if($countries)
- {
- $countries_dropdown = '<select name="ZIPCountry" onchange="submit_event(\'z\', \'OnCountryChange\')">'."\n";
- foreach ($countries as $record)
- {
- $countries_dropdown .= '<option value="'.$record['DestId'].'" ';
- if($record['DestId'] == $current_country)
- {
- $countries_dropdown .= 'selected';
- }
- $countries_dropdown .= '>'.$this->Application->Phrase($record['DestName']).'</option>'."\n";
- }
- $countries_dropdown .= '</select>'."\n";
- }
+ case 'has_states':
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $has_states = $cs_helper->getCountriesWithStates();
+ if ($selected_country_id && !array_key_exists($selected_country_id, $has_states)) {
+ list ($selected_country_id, ) = each($has_states);
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
+ }
+
+ // preselect country from 1st found state
+ if (!$selected_country_id) {
+ $sql = 'SELECT cs.StateCountryId
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE (cs.Type = ' . DESTINATION_TYPE_STATE . ') AND (zd.ShippingZoneId = ' . $object->GetID() . ')';
+ $selected_country_id = $this->Conn->GetOne($sql);
- $sql = 'SELECT DestValue FROM '.TABLE_PREFIX.'ShippingZonesDestinations WHERE NOT(DestValue IS NULL) AND DestValue<>"" AND StdDestId='.$current_country;
- $res = array_unique( $this->Conn->GetCol($sql) );
- $dropdown = '<input type="text" name="zip_input" id="zip_input" size="15">';
- if($res)
- {
- $dropdown .= ' or <select name="zip_dropdown">'."\n";
- $dropdown .= '<option value=""></option>';
- foreach ($res as $record)
- {
- $dropdown .= '<option value="'.$record.'">'.$record.'</option>'."\n";
+ if ($selected_country_id) {
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
+ }
+ else {
+ list ($selected_country_id, ) = each($has_states);
+ $this->Application->SetVar('CountrySelector', $selected_country_id);
}
- $dropdown .= '</select>'."\n";
}
- $table = '<table border="0"><tr><td>'.$this->Application->Phrase('la_fld_Country').': </td><td>'.$countries_dropdown.'</td></tr>';
- $table .= '<tr><td>'.$this->Application->Phrase('la_fld_ZIP').': </td><td>'.$dropdown.'</td></tr></table>';
-
- $form_params = Array();
- $form_params['dropdown'] = $table;
- $form_params['block'] = $param['block'];
- $form_params['res'] = $res;
- $ret = $this->ShowDestionationForm($form_params);
-
+ // gets only countries with states
+ $sql = 'SELECT ' . $name_field . ', ' . $id_field . '
+ FROM ' . $table_name . '
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . ' AND ' . $id_field . ' IN (' . implode(',', array_keys($has_states)) . ')
+ ORDER BY ' . $name_field;
break;
+
default:
+ trigger_error('Unknown "show" parameter value "' . $params['show'] . '" used.', E_USER_ERROR);
+ break;
}
- $ret .= $hidden_clause;
- return $ret;
- }
-
- function ShowDestionationForm($param)
- {
- $add_button = '<input type="button" class="button" value="'.$this->Application->Phrase('la_btn_AddLocation').'" onclick="submit_event(\'z\', \'OnAddLocation\')">';
+ $ret = '';
+ $countries = $this->Conn->GetCol($sql, $id_field);
- $main_processor =& $this->Application->RecallObject('m_TagProcessor');
- $oddevenparam['odd'] = 'table-color1';
- $oddevenparam['even'] = 'table-color2';
- $ret = '<tr class="'.$main_processor->Odd_Even($oddevenparam).'"><td></td><td>'.$param['dropdown'].'</td><td>'.$add_button.'</td></tr>';
-
- $dest_list = $this->Application->GetVar('dst');
- if (is_array($dest_list) && count($dest_list))
- {
- $ret .= '<tr class="'.$main_processor->Odd_Even($oddevenparam).'"><td></td><td><select multiple name="location_list" onchange="SelectToString(this)">';
- $hidden = '';
-
- foreach ($dest_list as $id => $destination)
- {
- $params = $destination;
- $params['id'] = $id;
- $hidden .= '<input type="hidden" id="dst['.$destination['ZoneDestId'].'][ZoneDestId]" name="dst['.$destination['ZoneDestId'].'][ZoneDestId]" value="'.$destination['ZoneDestId'].'">';
-
- $zones_object =& $this->Application->recallObject('z');
-
- switch($zones_object->GetDBField('Type'))
- {
- case 1:
- $params['destination_title'] = $this->Application->Phrase( $param['res'][$destination['StdDestId']]['DestName'] );
- $hidden .= '<input type="hidden" id="dst['.$destination['ZoneDestId'].'][StdDestId]" name="dst['.$destination['ZoneDestId'].'][StdDestId]" value="'.$destination['StdDestId'].'">';
- break;
- case 2:
- $params['destination_title'] = $this->Application->Phrase( $param['res'][$destination['StdDestId']]['DestName'] );
- $hidden .= '<input type="hidden" id="dst['.$destination['ZoneDestId'].'][StdDestId]" name="dst['.$destination['ZoneDestId'].'][StdDestId]" value="'.$destination['StdDestId'].'">';
- break;
- case 3:
- $params['destination_title'] = $destination['DestValue'];
- $hidden .= '<input type="hidden" id="dst['.$destination['ZoneDestId'].'][DestValue]" name="dst['.$destination['ZoneDestId'].'][DestValue]" value="'.$destination['DestValue'].'">';
+ $block_params = $this->prepareTagParams($params);
+ $block_params['name'] = $params['block'];
- }
+ foreach ($countries as $country_id => $country_name) {
+ $block_params['id'] = $country_id;
+ $block_params['destination_title'] = $country_name;
+ $block_params['selected'] = $selected_country_id == $country_id ? ' selected="selected"' : '';
- $params['name'] = $param['block'];
- $ret .= $main_processor->ParseBlock($params);
- }
- $ret .= '</select></td><td><input type="button" class="button" value="'.$this->Application->Phrase('la_btn_RemoveLocations').'" onclick="remove_location('.$destination['ZoneDestId'].')"></td><tr>';
- $ret .= $hidden;
+ $ret .= $this->Application->ParseBlock($block_params);
}
return $ret;
}
- */
+ function ShowStates($params)
+ {
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
- function ShowCountries($param){
+ $destination_table = $this->getDestinationsTable($params);
- $param = $this->prepareTagParams($param);
- $param['name'] = $param['block'];
+ $name_field = 'l' . $this->Application->GetVar('m_lang') . '_Name';
+ $id_field = $this->Application->getUnitOption('country-state', 'IDField');
+ $table_name = $this->Application->getUnitOption('country-state', 'TableName');
- $destination = &$this->Application->recallObject('dst');
- $zone = &$this->Application->recallObject('z');
+ $country_id = $this->Application->GetVar('CountrySelector');
- $selected_country = Array(); // this prevents 241 warnings to me raised :D
- switch ($param['show']){
+ switch ($params['show']) {
case 'current':
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1 AND zd.ShippingZoneId='.$zone->GetDBField('ZoneID').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ // selected states for current country and zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE
+ cs.Type = ' . DESTINATION_TYPE_STATE . ' AND
+ cs.StateCountryId = ' . $country_id . ' AND
+ zd.ShippingZoneId = ' . $object->GetID() . '
+ ORDER BY cs.' . $name_field;
break;
case 'available':
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1 AND zd.ShippingZoneId IS NULL
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ // available states for current country and zone
+ $sql = 'SELECT cs.' . $name_field . ', cs.' . $id_field . '
+ FROM ' . $table_name . ' cs
+ LEFT JOIN ' . $destination_table . ' zd ON zd.StdDestId = cs.' . $id_field . '
+ WHERE
+ cs.Type = ' . DESTINATION_TYPE_STATE . '
+ AND zd.ShippingZoneId IS NULL
+ AND cs.StateCountryId = ' . $country_id . '
+ ORDER BY cs.' . $name_field;
break;
case 'all':
- $selected_country = $this->Application->GetVar('CountrySelector');
- if (!$selected_country){
- // get 1st available country ID
- $selected_country = $this->Conn->GetOne('SELECT StdDestId FROM '.$destination->TableName.'
- WHERE ShippingZoneId='.$zone->GetDBField('ZoneID'));
- if ($selected_country){
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
- }
-
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ // all possible states for selected country
+ $sql = 'SELECT ' . $name_field . ', ' . $id_field . '
+ FROM ' . $table_name . '
+ WHERE Type = ' . DESTINATION_TYPE_STATE . ' AND StateCountryId = ' . $country_id . '
+ ORDER BY ' . $name_field;
break;
- case 'has_states':
- $has_states = $this->Conn->GetCol('SELECT DISTINCT DestParentId FROM '.TABLE_PREFIX.'StdDestinations sd
- WHERE sd.DestType=2');
- $selected_country = $this->Application->GetVar('CountrySelector');
-
- if ($selected_country && !in_array($selected_country, $has_states)){
- $selected_country = $has_states[0];
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
-
- if (!$selected_country){
- // get 1st available country ID
- $selected_country = $this->Conn->GetOne('SELECT DestParentId FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd
- ON zd.StdDestId = sd.DestId
- WHERE sd.DestType=2
- AND zd.ShippingZoneId='.$zone->GetDBField('ZoneID'));
- if ($selected_country){
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
- else {
- $selected_country = $has_states[0];
- $this->Application->SetVar('CountrySelector', $selected_country);
- }
- }
-
-
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 1 AND DestId IN ('.implode(',', $has_states).')
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ default:
+ trigger_error('Unknown "show" parameter value "' . $params['show'] . '" used.', E_USER_ERROR);
break;
}
- $countries = $this->Conn->Query($sql);
- $o = '';
+ $ret = '';
+ $states = $this->Conn->GetCol($sql, $id_field);
+ $block_params = $this->prepareTagParams($params);
+ $block_params['name'] = $params['block'];
- foreach($countries as $key => $country) {
- $param['id'] = $country['DestId'];
- $param['destination_title'] = $this->Application->Phrase($country['DestName']);
- if ($selected_country && $selected_country == $param['id']){
- $param['selected'] = ' selected="selected"';
- }
- else {
- $param['selected']='';
- }
- $o .= $this->Application->ParseBlock($param);
+ foreach($states as $state_id => $state_name) {
+ $block_params['id'] = $state_id;
+ $block_params['destination_title'] = $state_name;
+
+ $ret .= $this->Application->ParseBlock($block_params);
}
- return $o;
+ return $ret;
}
- function ShowStates($param){
+ function ShowZips($params)
+ {
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
- $param = $this->prepareTagParams($param);
- $param['name'] = $param['block'];
+ $destination_table = $this->getDestinationsTable($params);
- $destination = &$this->Application->recallObject('dst');
- $zone = &$this->Application->recallObject('z');
+ $country_id = (int)$this->Application->GetVar('CountrySelector');
- switch ($param['show']){
- case 'current':
- $sql = 'SELECT *
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
+ $current_sql = 'SELECT DestValue
+ FROM ' . $destination_table . '
WHERE
- sd.DestType=2
- AND sd.DestParentId='.$this->Application->GetVar('CountrySelector').'
- AND zd.ShippingZoneId='.$zone->GetDBField('ZoneID').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ COALESCE(DestValue, "") <> "" AND
+ ShippingZoneID = ' . $object->GetID() . '
+ ORDER BY DestValue';
+
+ switch ($params['show']) {
+ case 'current':
+ $sql = $current_sql;
break;
case 'available':
- $sql = 'SELECT *
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.$destination->TableName.' zd ON zd.StdDestId = sd.DestId
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
+ $selected_zips = $this->Conn->GetCol($current_sql);
+ $selected_zips = array_map(Array (&$this->Conn, 'qstr'), $selected_zips);
+
+ $sql = 'SELECT DISTINCT DestValue
+ FROM ' . $this->Application->getUnitOption('dst', 'TableName') . '
WHERE
- sd.DestType=2
- AND zd.ShippingZoneId IS NULL
- AND sd.DestParentId='.$this->Application->GetVar('CountrySelector').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ COALESCE(DestValue, "") <> "" AND
+ ShippingZoneID <> ' . $object->GetID() . ' AND
+ ' . ($selected_zips ? 'DestValue NOT IN (' . implode(',', $selected_zips) . ') AND' : '') . '
+ StdDestId = ' . $country_id . '
+ ORDER BY DestValue';
break;
- case 'all':
- $sql = 'SELECT sd.*
- FROM '.TABLE_PREFIX.'StdDestinations sd
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = sd.DestName
- WHERE sd.DestType = 2 AND sd.DestParentId='.$this->Application->GetVar('CountrySelector').'
- ORDER BY l' . $this->Application->GetVar('lang.current_id') . '_Translation';
+ default:
+ trigger_error('Unknown "show" parameter value "' . $params['show'] . '" used.', E_USER_ERROR);
break;
}
- $states = $this->Conn->Query($sql);
- $o = '';
- foreach($states as $key => $state) {
- $param['id'] = $state['DestId'];
- $param['destination_title'] = $this->Application->Phrase($state['DestName']);
- $o .= $this->Application->ParseBlock($param);
- }
- return $o;
+ $zips = $this->Conn->GetCol($sql);
- }
+ $ret = '';
+ $block_params = $this->prepareTagParams($params);
+ $block_params['name'] = $params['block'];
- function ShowZips($param){
+ foreach($zips as $zip) {
+ $block_params['id'] = '0|' . $zip;
+ $block_params['destination_title'] = $zip;
- $param = $this->prepareTagParams($param);
- $param['name'] = $param['block'];
+ $ret .= $this->Application->ParseBlock($block_params);
+ }
- $destination = &$this->Application->recallObject('dst');
- $zone = &$this->Application->recallObject('z');
+ return $ret;
+ }
- $country_selector = $this->Application->GetVar('CountrySelector');
- if (!$country_selector){
- $country_selector=0;
- }
+ /**
+ * Returns table for shipping zone destinations
+ *
+ * @param Array $params
+ * @return string
+ */
+ function getDestinationsTable($params)
+ {
+ static $table_name = '';
- switch ($param['show']){
- case 'current':
- $sql = 'SELECT * FROM '.$destination->TableName.'
- WHERE NOT(DestValue IS NULL)
- AND DestValue<>""
- AND ShippingZoneID='.$zone->GetDBField('ZoneID').'
- ORDER BY DestValue
- ';
- break;
- case 'available':
- $selected_zips = $this->Conn->GetCol('SELECT DestValue FROM '.$destination->TableName.'
- WHERE NOT(DestValue IS NULL)
- AND DestValue<>""
- AND ShippingZoneID='.$zone->GetDBField('ZoneID').'
- ORDER BY DestValue
- ');
-
- $sql = 'SELECT DISTINCT(DestValue) FROM '.$this->Application->getUnitOption('dst', 'TableName').'
- WHERE NOT(DestValue IS NULL)
- AND ShippingZoneID!='.$zone->GetDBField('ZoneID').'
- AND DestValue NOT IN ("'.implode('", "', $selected_zips).'")
- AND DestValue<>"" AND StdDestId='.$country_selector.'
- ORDER BY DestValue
- ';
+ if (!$table_name) {
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
- break;
- case 'all':
- $sql = 'SELECT sd.* FROM '.TABLE_PREFIX.'StdDestinations sd
- WHERE sd.DestType=3 AND sd.DestParentId='.$country_selector.'
- ORDER BY DestValue
- ';
- break;
- }
+ $table_name = $this->Application->getUnitOption('dst', 'TableName');
- $zips = $this->Conn->Query($sql);
- $o = '';
- foreach($zips as $key => $zip) {
- $param['id'] = $zip['DestId'].'|'.$zip['DestValue'];
- $param['destination_title'] = $zip['DestValue'];
- $o .= $this->Application->ParseBlock($param);
+ if ($object->IsTempTable()) {
+ $table_name = $this->Application->GetTempName($table_name, 'prefix:' . $this->Prefix);
+ }
}
- return $o;
+ return $table_name;
}
}
\ No newline at end of file
Index: branches/5.1.x/units/orders/orders_event_handler.php
===================================================================
--- branches/5.1.x/units/orders/orders_event_handler.php (revision 13464)
+++ branches/5.1.x/units/orders/orders_event_handler.php (revision 13465)
@@ -1,4129 +1,4132 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class OrdersEventHandler extends kDBEventHandler
{
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
if (!$this->Application->isAdminUser) {
if ($event->Name == 'OnCreate') {
// user can't initiate custom order creation directly
return false;
}
$user_id = $this->Application->RecallVar('user_id');
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ($items_info) {
// when POST is present, then check when is beeing submitted
$order_session_id = $this->Application->RecallVar($event->getPrefixSpecial(true).'_id');
$order_dummy =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true));
foreach ($items_info as $id => $field_values) {
if ($order_session_id != $id) {
// user is trying update not his order, even order from other guest
return false;
}
$order_dummy->Load($id);
// session_id matches order_id from submit
if ($order_dummy->GetDBField('PortalUserId') != $user_id) {
// user performs event on other user order
return false;
}
$status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField'));
if (isset($field_values[$status_field]) && $order_dummy->GetDBField($status_field) != $field_values[$status_field]) {
// user can't change status by himself
return false;
}
if ($order_dummy->GetDBField($status_field) != ORDER_STATUS_INCOMPLETE) {
// user can't edit orders being processed
return false;
}
if ($event->Name == 'OnUpdate') {
// all checks were ok -> it's user's order -> allow to modify
return true;
}
}
}
}
return parent::CheckPermission($event);
}
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
// admin
'OnRecalculateItems' => Array('self' => 'add|edit'),
'OnResetToUser' => Array('self' => 'add|edit'),
'OnResetToBilling' => Array('self' => 'add|edit'),
'OnResetToShipping' => Array('self' => 'add|edit'),
'OnMassOrderApprove' => Array('self' => 'advanced:approve'),
'OnMassOrderDeny' => Array('self' => 'advanced:deny'),
'OnMassOrderArchive' => Array('self' => 'advanced:archive'),
'OnMassPlaceOrder' => Array('self' => 'advanced:place'),
'OnMassOrderProcess' => Array('self' => 'advanced:process'),
'OnMassOrderShip' => Array('self' => 'advanced:ship'),
'OnResetToPending' => Array('self' => 'advanced:reset_to_pending'),
'OnLoadSelected' => Array('self' => 'view'), // print in this case
'OnGoToOrder' => Array('self' => 'view'),
// front-end
'OnViewCart' => Array('self' => true),
'OnAddToCart' => Array('self' => true),
'OnRemoveFromCart' => Array('self' => true),
'OnUpdateCart' => Array('self' => true),
'OnUpdateItemOptions' => Array('self' => true),
'OnCleanupCart' => Array('self' => true),
'OnContinueShopping' => Array('self' => true),
'OnCheckout' => Array('self' => true),
'OnSelectAddress' => Array('self' => true),
'OnProceedToBilling' => Array('self' => true),
'OnProceedToPreview' => Array('self' => true),
'OnCompleteOrder' => Array('self' => true),
'OnRemoveCoupon' => Array('self' => true),
'OnRemoveGiftCertificate' => Array('self' => true),
'OnCancelRecurring' => Array('self' => true),
'OnAddVirtualProductToCart' => Array('self' => true),
'OnItemBuild' => Array('self' => true),
'OnDownloadLabel' => Array('self' => true, 'subitem' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
function mapEvents()
{
parent::mapEvents();
$common_events = Array(
'OnResetToUser' => 'OnResetAddress',
'OnResetToBilling' => 'OnResetAddress',
'OnResetToShipping' => 'OnResetAddress',
'OnMassOrderProcess' => 'MassInventoryAction',
'OnMassOrderApprove' => 'MassInventoryAction',
'OnMassOrderDeny' => 'MassInventoryAction',
'OnMassOrderArchive' => 'MassInventoryAction',
'OnMassOrderShip' => 'MassInventoryAction',
'OnOrderProcess' => 'InventoryAction',
'OnOrderApprove' => 'InventoryAction',
'OnOrderDeny' => 'InventoryAction',
'OnOrderArchive' => 'InventoryAction',
'OnOrderShip' => 'InventoryAction',
);
$this->eventMethods = array_merge($this->eventMethods, $common_events);
}
/* ======================== FRONT ONLY ======================== */
function OnQuietPreSave(&$event)
{
$object =& $event->getObject();
$object->IgnoreValidation = true;
$event->CallSubEvent('OnPreSave');
$object->IgnoreValidation = false;
}
/**
* Sets new address to order
*
* @param kEvent $event
*/
function OnSelectAddress(&$event)
{
if ($this->Application->isAdminUser) {
return ;
}
$object =& $event->getObject();
$shipping_address_id = $this->Application->GetVar('shipping_address_id');
$billing_address_id = $this->Application->GetVar('billing_address_id');
if ($shipping_address_id || $billing_address_id) {
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
$address =& $this->Application->recallObject('addr.-item','addr', Array('skip_autoload' => true));
$addr_list =& $this->Application->recallObject('addr', 'addr_List', Array('per_page'=>-1, 'skip_counting'=>true) );
$addr_list->Query();
}
if ($shipping_address_id > 0) {
$addr_list->CopyAddress($shipping_address_id, 'Shipping');
$address->Load($shipping_address_id);
$address->MarkAddress('Shipping');
$cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
$object->setRequired('ShippingState', false);
}
elseif ($shipping_address_id == -1) {
$object->ResetAddress('Shipping');
}
if ($billing_address_id > 0) {
$addr_list->CopyAddress($billing_address_id, 'Billing');
$address->Load($billing_address_id);
$address->MarkAddress('Billing');
$cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
$object->setRequired('BillingState', false);
}
elseif ($billing_address_id == -1) {
$object->ResetAddress('Billing');
}
$event->redirect = false;
$object->IgnoreValidation = true;
$this->RecalculateTax($event);
$object->Update();
}
/**
* Updates order with registred user id
*
* @param kEvent $event
*/
function OnUserCreate(&$event)
{
if( !($event->MasterEvent->status == erSUCCESS) ) return false;
$ses_id = $this->Application->RecallVar('front_order_id');
if($ses_id)
{
$this->updateUserID($ses_id, $event);
$this->Application->RemoveVar('front_order_id');
}
}
/**
* Enter description here...
*
* @param unknown_type $event
* @return unknown
*/
function OnUserLogin(&$event)
{
if( !($event->MasterEvent->status == erSUCCESS) ) {
return false;
}
$ses_id = $this->Application->RecallVar('ord_id');
if ($ses_id) $this->updateUserID($ses_id, $event);
$user_id = $this->Application->RecallVar('user_id');
$affiliate_id = $this->isAffiliate($user_id);
if($affiliate_id) $this->Application->setVisitField('AffiliateId', $affiliate_id);
$event->CallSubEvent('OnRecalculateItems');
}
function updateUserID($order_id, &$event)
{
$table = $this->Application->getUnitOption($event->Prefix,'TableName');
$id_field = $this->Application->getUnitOption($event->Prefix,'IDField');
$user_id = $this->Application->RecallVar('user_id');
$this->Conn->Query('UPDATE '.$table.' SET PortalUserId = '.$user_id.' WHERE '.$id_field.' = '.$order_id);
$affiliate_id = $this->isAffiliate($user_id);
if($affiliate_id)
{
$this->Conn->Query('UPDATE '.$table.' SET AffiliateId = '.$affiliate_id.' WHERE '.$id_field.' = '.$order_id);
}
}
function isAffiliate($user_id)
{
$affiliate_user =& $this->Application->recallObject('affil.-item', null, Array('skip_autoload' => true) );
$affiliate_user->Load($user_id, 'PortalUserId');
return $affiliate_user->isLoaded() ? $affiliate_user->GetDBField('AffiliateId') : 0;
}
function ChargeOrder(&$order)
{
$gw_data = $order->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$payment_result = $gateway_object->DirectPayment($order->FieldValues, $gw_data['gw_params']);
$sql = 'UPDATE %s SET GWResult1 = %s WHERE %s = %s';
$sql = sprintf($sql, $order->TableName, $this->Conn->qstr($gateway_object->getGWResponce()), $order->IDField, $order->GetID() );
$this->Conn->Query($sql);
$order->SetDBField('GWResult1', $gateway_object->getGWResponce() );
return array('result'=>$payment_result, 'data'=>$gateway_object->parsed_responce, 'gw_data' => $gw_data, 'error_msg'=>$gateway_object->getErrorMsg());
}
function OrderEmailParams(&$order)
{
$billing_email = $order->GetDBField('BillingEmail');
$user_email = $this->Conn->GetOne(' SELECT Email FROM '.$this->Application->getUnitOption('u', 'TableName').'
WHERE PortalUserId = '.$order->GetDBField('PortalUserId'));
$email_params = Array();
$email_params['_user_email'] = $user_email; //for use when shipping vs user is required in InvetnoryAction
$email_params['to_email'] = $billing_email ? $billing_email : $user_email;
$email_params['to_name'] = $order->GetDBField('BillingTo');
return $email_params;
}
function PrepareCoupons(&$event, &$order)
{
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
$order_items->linkToParent($order->Special);
$order_items->Query();
$order_items->GoFirst();
$assigned_coupons = array();
$coup_handler =& $this->Application->recallObject('coup_EventHandler');
foreach($order_items->Records as $product_item)
{
if ($product_item['ItemData']) {
$item_data = unserialize($product_item['ItemData']);
if (isset($item_data['AssignedCoupon']) && $item_data['AssignedCoupon']) {
$coupon_id = $item_data['AssignedCoupon'];
// clone coupon, get new coupon ID
$coupon =& $this->Application->recallObject('coup',null,array('skip_autload' => true));
/* @var $coupon kDBItem */
$coupon->Load($coupon_id);
if (!$coupon->isLoaded()) continue;
$coup_handler->SetNewCode($coupon);
$coupon->NameCopy();
$coupon->SetDBField('Name', $coupon->GetDBField('Name').' (Order #'.$order->GetField('OrderNumber').')');
$coupon->Create();
// add coupon code to array
array_push($assigned_coupons, $coupon->GetDBField('Code'));
}
}
}
/* @var $order OrdersItem */
if ($assigned_coupons) {
$comments = $order->GetDBField('AdminComment');
if ($comments) $comments .= "\r\n";
$comments .= "Issued coupon(s): ". join(',', $assigned_coupons);
$order->SetDBField('AdminComment', $comments);
$order->Update();
}
if ($assigned_coupons) $this->Application->SetVar('order_coupons', join(',', $assigned_coupons));
}
/**
* Completes order if possible
*
* @param kEvent $event
* @return bool
*/
function OnCompleteOrder(&$event)
{
$this->LockTables($event);
if (!$this->CheckQuantites($event)) return;
$this->ReserveItems($event);
$order =& $event->getObject();
$charge_result = $this->ChargeOrder($order);
if (!$charge_result['result']) {
$this->FreeItems($event);
$this->Application->StoreVar('gw_error', $charge_result['error_msg']);
//$this->Application->StoreVar('gw_error', getArrayValue($charge_result, 'data', 'responce_reason_text') );
$event->redirect = $this->Application->GetVar('failure_template');
$event->redirect_params['m_cat_id'] = 0;
if ($event->Special == 'recurring') { // if we set failed status for other than recurring special the redirect will not occur
$event->status = erFAIL;
}
return false;
}
// call CompleteOrder events for items in order BEFORE SplitOrder (because ApproveEvents are called there)
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
$order_items->linkToParent($order->Special);
$order_items->Query(true);
$order_items->GoFirst();
foreach($order_items->Records as $product_item)
{
if (!$product_item['ProductId']) continue; // product may have been deleted
$this->raiseProductEvent('CompleteOrder', $product_item['ProductId'], $product_item);
}
$shipping_control = getArrayValue($charge_result, 'gw_data', 'gw_params', 'shipping_control');
if ($event->Special != 'recurring') {
if ($shipping_control && $shipping_control != SHIPPING_CONTROL_PREAUTH ) {
// we have to do it here, because the coupons are used in the e-mails
$this->PrepareCoupons($event, $order);
}
$email_event_user =& $this->Application->EmailEventUser('ORDER.SUBMIT', $order->GetDBField('PortalUserId'), $this->OrderEmailParams($order));
$email_event_admin =& $this->Application->EmailEventAdmin('ORDER.SUBMIT');
}
if ($shipping_control === false || $shipping_control == SHIPPING_CONTROL_PREAUTH ) {
$order->SetDBField('Status', ORDER_STATUS_PENDING);
$order->Update();
}
else {
$this->SplitOrder($event, $order);
}
if (!$this->Application->isAdminUser) {
// for tracking code
$this->Application->StoreVar('last_order_amount', $order->GetDBField('TotalAmount'));
$this->Application->StoreVar('last_order_number', $order->GetDBField('OrderNumber'));
$this->Application->StoreVar('last_order_customer', $order->GetDBField('BillingTo'));
$this->Application->StoreVar('last_order_user', $order->GetDBField('Username'));
$event->redirect = $this->Application->GetVar('success_template');
$event->redirect_params['m_cat_id'] = 0;
}
else
{
// $event->CallSubEvent('OnSave');
}
$order_id = $order->GetId();
$order_idfield = $this->Application->getUnitOption('ord','IDField');
$order_table = $this->Application->getUnitOption('ord','TableName');
$original_amount = $order->GetDBField('SubTotal') + $order->GetDBField('ShippingCost') + $order->GetDBField('VAT') + $order->GetDBField('ProcessingFee') + $order->GetDBField('InsuranceFee') - $order->GetDBField('GiftCertificateDiscount');
$sql = 'UPDATE '.$order_table.'
SET OriginalAmount = '.$original_amount.'
WHERE '.$order_idfield.' = '.$order_id;
$this->Conn->Query($sql);
$this->Application->StoreVar('front_order_id', $order_id);
$this->Application->RemoveVar('ord_id');
}
/**
* Set billing address same as shipping
*
* @param kEvent $event
*/
function setBillingAddress(&$event)
{
$object =& $event->getObject();
if ($object->HasTangibleItems()) {
if ($this->Application->GetVar('same_address')) {
// copy shipping address to billing
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
list($id, $field_values) = each($items_info);
$address_fields = Array('To', 'Company', 'Phone', 'Fax', 'Email', 'Address1', 'Address2', 'City', 'State', 'Zip', 'Country');
foreach ($address_fields as $address_field) {
$items_info[$id]['Billing'.$address_field] = $object->GetDBField('Shipping'.$address_field);
}
$this->Application->SetVar($event->getPrefixSpecial(true), $items_info);
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnProceedToPreview(&$event)
{
$this->setBillingAddress($event);
$event->CallSubEvent('OnUpdate');
$event->redirect = $this->Application->GetVar('preview_template');
}
function OnViewCart(&$event)
{
$this->StoreContinueShoppingLink();
$event->redirect = $this->Application->GetVar('viewcart_template');
}
function OnContinueShopping(&$event)
{
$env = $this->Application->GetVar('continue_shopping_template');
if (!$env || $env == '__default__') {
$env = $this->Application->RecallVar('continue_shopping');
}
if (!$env) {
$env = 'in-commerce/index';
}
$event->redirect = $env;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCheckout(&$event)
{
$this->OnUpdateCart($event);
if ($event->getEventParam('RecalculateChangedCart'))
{
$event->SetRedirectParam('checkout_error', $event->redirect_params['checkout_error']);
}
else
{
$object =& $event->getObject();
if(!$object->HasTangibleItems())
{
$object->SetDBField('ShippingTo', '');
$object->SetDBField('ShippingCompany', '');
$object->SetDBField('ShippingPhone', '');
$object->SetDBField('ShippingFax', '');
$object->SetDBField('ShippingEmail', '');
$object->SetDBField('ShippingAddress1', '');
$object->SetDBField('ShippingAddress2', '');
$object->SetDBField('ShippingCity', '');
$object->SetDBField('ShippingState', '');
$object->SetDBField('ShippingZip', '');
$object->SetDBField('ShippingCountry', '');
$object->SetDBField('ShippingType', 0);
$object->SetDBField('ShippingCost', 0);
$object->SetDBField('ShippingCustomerAccount', '');
$object->SetDBField('ShippingTracking', '');
$object->SetDBField('ShippingDate', 0);
$object->SetDBField('ShippingOption', 0);
$object->SetDBField('ShippingInfo', '');
$object->Update();
}
$event->redirect = $this->Application->GetVar('next_step_template');
$order_id = $this->Application->GetVar('order_id');
if($order_id !== false) $event->redirect_params['ord_id'] = $order_id;
}
}
/**
* Redirect user to Billing checkout step
*
* @param kEvent $event
*/
function OnProceedToBilling(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id,$field_values) = each($items_info);
$object =& $event->getObject();
$payment_type_id = $object->GetDBField('PaymentType');
if(!$payment_type_id)
{
$default_type = $this->Conn->GetOne('SELECT PaymentTypeId FROM '.TABLE_PREFIX.'PaymentTypes WHERE IsPrimary = 1');
if($default_type)
{
$field_values['PaymentType'] = $default_type;
$items_info[$id] = $field_values;
$this->Application->SetVar( $event->getPrefixSpecial(true), $items_info );
}
}
}
$event->CallSubEvent('OnUpdate');
$event->redirect = $this->Application->GetVar('next_step_template');
}
function OnCancelRecurring(&$event)
{
$order =& $event->GetObject();
$order->SetDBField('IsRecurringBilling', 0);
$order->Update();
if ($this->Application->GetVar('cancelrecurring_ok_template'))
{
$event->redirect = $this->Application->GetVar('cancelrecurring_ok_template');
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnAfterItemUpdate(&$event)
{
$object =& $event->getObject();
$cvv2 = $object->GetDBField('PaymentCVV2');
if($cvv2 !== false) $this->Application->StoreVar('CVV2Code', $cvv2);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnUpdate(&$event)
{
$this->setBillingAddress($event);
- $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
-
- $object =& $event->getObject();
- if( $object->HasTangibleItems() )
- {
- $cs_helper->CheckStateField($event, 'ShippingState', 'ShippingCountry');
- }
-
- $cs_helper->CheckStateField($event, 'BillingState', 'BillingCountry');
-
parent::OnUpdate($event);
if ($this->Application->isAdminUser) {
return true;
}
else {
$event->redirect_params = Array('opener' => 's');
}
if ($event->status == erSUCCESS) {
$this->createMissingAddresses($event);
}
else {
// strange: recalculate total amount on error
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
+
$object->SetDBField('TotalAmount', $object->getTotalAmount());
}
}
/**
* Creates new address
*
* @param kEvent $event
*/
function createMissingAddresses(&$event)
{
if (!$this->Application->LoggedIn()) {
return false;
}
$object =& $event->getObject();
$addr_list =& $this->Application->recallObject('addr', 'addr_List', Array('per_page'=>-1, 'skip_counting'=>true) );
$addr_list->Query();
$address_dummy =& $this->Application->recallObject('addr.-item', null, Array('skip_autoload' => true));
$address_prefixes = Array('Billing', 'Shipping');
$address_fields = Array('To','Company','Phone','Fax','Email','Address1','Address2','City','State','Zip','Country');
foreach ($address_prefixes as $address_prefix) {
$address_id = $this->Application->GetVar(strtolower($address_prefix).'_address_id');
if (!$this->Application->GetVar('check_'.strtolower($address_prefix).'_address')) {
// form type doesn't match check type, e.g. shipping check on billing form
continue;
}
if ($address_id > 0) {
$address_dummy->Load($address_id);
}
else {
$address_dummy->SetDBField('PortalUserId', $this->Application->RecallVar('user_id') );
}
foreach ($address_fields as $address_field) {
$address_dummy->SetDBField($address_field, $object->GetDBField($address_prefix.$address_field));
}
$address_dummy->MarkAddress($address_prefix, false);
$ret = ($address_id > 0) ? $address_dummy->Update() : $address_dummy->Create();
}
}
- /**
- * Enter description here...
- *
- * @param kEvent $event
- */
- function OnPreSave(&$event)
- {
- $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
-
- $object =& $event->getObject();
- if ( $object->GetID() !== false)
- {
- if( $object->HasTangibleItems() )
- {
- $cs_helper->CheckStateField($event, 'ShippingState', 'ShippingCountry');
- }
- $cs_helper->CheckStateField($event, 'BillingState', 'BillingCountry');
- }
-
- parent::OnPreSave($event);
- }
-
function OnUpdateCart(&$event)
{
$this->Application->HandleEvent($items_event, 'orditems:OnUpdate');
return $event->CallSubEvent('OnRecalculateItems');
}
/**
* Adds item to cart
*
* @param kEvent $event
*/
function OnAddToCart(&$event)
{
$this->StoreContinueShoppingLink();
$qty = $this->Application->GetVar('qty');
$options = $this->Application->GetVar('options');
// multiple or options add
$items = Array();
if (is_array($qty)) {
foreach ($qty as $item_id => $combinations)
{
if (is_array($combinations)) {
foreach ($combinations as $comb_id => $comb_qty) {
if ($comb_qty == 0) continue;
$items[] = array('item_id' => $item_id, 'qty' => $comb_qty, 'comb' => $comb_id);
}
}
else {
$items[] = array('item_id' => $item_id, 'qty' => $combinations);
}
}
}
if (!$items) {
if (!$qty || is_array($qty)) $qty = 1;
$item_id = $this->Application->GetVar('p_id');
if (!$item_id) return ;
$items = array(array('item_id' => $item_id, 'qty' => $qty));
}
// remember item data passed to event when called
$default_item_data = $event->getEventParam('ItemData');
$default_item_data = $default_item_data ? unserialize($default_item_data) : Array();
foreach ($items as $an_item) {
$item_id = $an_item['item_id'];
$qty = $an_item['qty'];
$comb = getArrayValue($an_item, 'comb');
$item_data = $default_item_data;
$product =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
$product->Load($item_id);
$event->setEventParam('ItemData', null);
if ($product->GetDBField('AssignedCoupon')) {
$item_data['AssignedCoupon'] = $product->GetDBField('AssignedCoupon');
}
// 1. store options information OR
if ($comb) {
$combination = $this->Conn->GetOne('SELECT Combination FROM '.TABLE_PREFIX.'ProductOptionCombinations WHERE CombinationId = '.$comb);
$item_data['Options'] = unserialize($combination);
}
elseif (is_array($options)) {
$item_data['Options'] = $options[$item_id];
}
// 2. store subscription information OR
if( $product->GetDBField('Type') == 2 ) // subscriptions
{
$item_data = $this->BuildSubscriptionItemData($item_id, $item_data);
}
// 3. store package information
if( $product->GetDBField('Type') == 5 ) // package
{
$package_content_ids = $product->GetPackageContentIds();
$product_package_item =& $this->Application->recallObject('p.-packageitem');
$package_item_data = array();
foreach ($package_content_ids as $package_item_id){
$product_package_item->Load($package_item_id);
$package_item_data[$package_item_id] = array();
if( $product_package_item->GetDBField('Type') == 2 ) // subscriptions
{
$package_item_data[$package_item_id] = $this->BuildSubscriptionItemData($package_item_id, $item_data);
}
}
$item_data['PackageContent'] = $product->GetPackageContentIds();
$item_data['PackageItemsItemData'] = $package_item_data;
}
$event->setEventParam('ItemData', serialize($item_data));
// 1 for PacakgeNum when in admin - temporary solution to overcome splitting into separate sub-orders
// of orders with items added through admin when approving them
$this->AddItemToOrder($event, $item_id, $qty, $this->Application->isAdminUser ? 1 : null);
}
if ($event->status == erSUCCESS && !$event->redirect) {
$event->redirect_params['pass'] = 'm';
$event->redirect_params['pass_category'] = 0; //otherwise mod-rewrite shop-cart URL will include category
$event->redirect = true;
}
else {
if ($this->Application->isAdminUser) {
$event->redirect_params['opener'] = 'u';
}
}
}
/**
* Check if required options are selected & selected option combination is in stock
*
* @param kEvent $event
* @param Array $options
* @param int $product_id
* @param int $qty
* @param int $selection_mode
* @return bool
*/
function CheckOptions(&$event, &$options, $product_id, $qty, $selection_mode)
{
// 1. check for required options
$selection_filter = $selection_mode == 1 ? ' AND OptionType IN (1,3,6) ' : '';
$req_options = $this->Conn->GetCol('SELECT ProductOptionId FROM '.TABLE_PREFIX.'ProductOptions WHERE ProductId = '.$product_id.' AND Required = 1 '.$selection_filter);
$result = true;
foreach ($req_options as $opt_id) {
if (!getArrayValue($options, $opt_id)) {
$this->Application->SetVar('opt_error', 1); //let the template know we have an error
$result = false;
}
}
// 2. check for option combinations in stock
$comb_salt = $this->OptionsSalt($options, true);
if ($comb_salt) {
// such option combination is defined explicitly
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$sql = 'SELECT Availability
FROM '.$poc_table.'
WHERE CombinationCRC = '.$comb_salt;
$comb_availble = $this->Conn->GetOne($sql);
// 2.1. check if Availability flag is set, then
if ($comb_availble == 1) {
// 2.2. check for quantity in stock
$table = Array();
$table['poc'] = $this->Application->getUnitOption('poc', 'TableName');
$table['p'] = $this->Application->getUnitOption('p', 'TableName');
$table['oi'] = $this->TablePrefix($event).'OrderItems';
$object =& $event->getObject();
$ord_id = $object->GetID();
// 2.3. check if some amount of same combination & product are not already in shopping cart
$sql = 'SELECT '.
$table['p'].'.InventoryStatus,'.
$table['p'].'.BackOrder,
IF('.$table['p'].'.InventoryStatus = 2, '.$table['poc'].'.QtyInStock, '.$table['p'].'.QtyInStock) AS QtyInStock,
IF('.$table['oi'].'.OrderItemId IS NULL, 0, '.$table['oi'].'.Quantity) AS Quantity
FROM '.$table['p'].'
LEFT JOIN '.$table['poc'].' ON
'.$table['p'].'.ProductId = '.$table['poc'].'.ProductId
LEFT JOIN '.$table['oi'].' ON
('.$table['oi'].'.OrderId = '.$ord_id.') AND
('.$table['oi'].'.OptionsSalt = '.$comb_salt.') AND
('.$table['oi'].'.ProductId = '.$product_id.') AND
('.$table['oi'].'.BackOrderFlag = 0)
WHERE '.$table['poc'].'.CombinationCRC = '.$comb_salt;
$product_info = $this->Conn->GetRow($sql);
if ($product_info['InventoryStatus']) {
$backordering = $this->Application->ConfigValue('Comm_Enable_Backordering');
if (!$backordering || $product_info['BackOrder'] == 0) {
// backordering is not enabled generally or for this product directly, then check quantities in stock
if ($qty + $product_info['Quantity'] > $product_info['QtyInStock']) {
$this->Application->SetVar('opt_error', 2);
$result = false;
}
}
}
}
elseif ($comb_availble !== false) {
$this->Application->SetVar('opt_error', 2);
$result = false;
}
}
if ($result) {
$event->status = erSUCCESS;
$event->redirect = $this->Application->isAdminUser ? true : $this->Application->GetVar('shop_cart_template');
}
else {
$event->status = erFAIL;
}
return $result;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnUpdateItemOptions(&$event)
{
$opt_data = $this->Application->GetVar('options');
$options = getArrayValue($opt_data, $this->Application->GetVar('p_id'));
if (!$options) {
$qty_data = $this->Application->GetVar('qty');
$comb_id = key(getArrayValue($qty_data, $this->Application->GetVar('p_id')));
$options = unserialize($this->Conn->GetOne('SELECT Combination FROM '.TABLE_PREFIX.'ProductOptionCombinations WHERE CombinationId = '.$comb_id));
}
if (!$options) return;
$ord_item =& $this->Application->recallObject('orditems.-opt', null, Array ('skip_autoload' => true));
/* @var $ord_item kDBItem */
$ord_item->Load($this->Application->GetVar('orditems_id'));
// assuming that quantity cannot be changed during order item editing
if (!$this->CheckOptions($event, $options, $ord_item->GetDBField('ProductId'), 0, $ord_item->GetDBField('OptionsSelectionMode'))) return;
$item_data = unserialize($ord_item->GetDBField('ItemData'));
$item_data['Options'] = $options;
$ord_item->SetDBField('ItemData', serialize($item_data));
$ord_item->SetDBField('OptionsSalt', $this->OptionsSalt($options));
$ord_item->Update();
$event->CallSubEvent('OnRecalculateItems');
if ($event->status == erSUCCESS && $this->Application->isAdminUser) {
$event->redirect_params['opener'] = 'u';
}
}
function BuildSubscriptionItemData($item_id, $item_data)
{
$products_table = $this->Application->getUnitOption('p', 'TableName');
$products_idfield = $this->Application->getUnitOption('p', 'IDField');
$sql = 'SELECT AccessGroupId FROM %s WHERE %s = %s';
$item_data['PortalGroupId'] = $this->Conn->GetOne( sprintf($sql, $products_table, $products_idfield, $item_id) );
$pricing_table = $this->Application->getUnitOption('pr', 'TableName');
$pricing_idfield = $this->Application->getUnitOption('pr', 'IDField');
// $sql = 'SELECT AccessDuration, AccessUnit, DurationType, AccessExpiration FROM %s WHERE %s = %s';
$sql = 'SELECT * FROM %s WHERE %s = %s';
$pricing_id = $this->GetPricingId($item_id, $item_data);
$item_data['PricingId'] = $pricing_id;
$pricing_info = $this->Conn->GetRow( sprintf($sql, $pricing_table, $pricing_idfield, $pricing_id ) );
$unit_secs = Array(1 => 1, 2 => 60, 3 => 3600, 4 => 86400, 5 => 604800, 6 => 2592000, 7 => 31536000);
/*
// Customization healtheconomics.org
$item_data['DurationType'] = $pricing_info['DurationType'];
$item_data['AccessExpiration'] = $pricing_info['AccessExpiration'];
// Customization healtheconomics.org --
*/
$item_data['Duration'] = $pricing_info['AccessDuration'] * $unit_secs[ $pricing_info['AccessUnit'] ];
return $item_data;
}
function OnRemoveCoupon(&$event)
{
$object =& $event->getObject();
$this->RemoveCoupon($object);
$event->CallSubEvent('OnRecalculateItems');
$event->SetRedirectParam('checkout_error', 7);
}
function RemoveCoupon(&$object)
{
$coupon_id = $object->GetDBField('CouponId');
$coupon =& $this->Application->recallObject('coup', null, Array('skip_autoload' => true));
$res = $coupon->Load($coupon_id);
$uses = $coupon->GetDBField('NumberOfUses');
if($res && isset($uses))
{
$coupon->SetDBField('NumberOfUses', $uses + 1);
$coupon->SetDBField('Status', 1);
$coupon->Update();
}
$object->SetDBField('CouponId', 0);
$object->SetDBField('CouponDiscount', 0);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnAddVirtualProductToCart(&$event)
{
$l_info = $this->Application->GetVar('l');
if($l_info)
{
foreach($l_info as $link_id => $link_info) {}
$item_data['LinkId'] = $link_id;
$item_data['ListingTypeId'] = $link_info['ListingTypeId'];
}
else
{
$link_id = $this->Application->GetVar('l_id');
$sql = 'SELECT ResourceId FROM '.$this->Application->getUnitOption('l', 'TableName').'
WHERE LinkId = '.$link_id;
$sql = 'SELECT ListingTypeId FROM '.$this->Application->getUnitOption('ls', 'TableName').'
WHERE ItemResourceId = '.$this->Conn->GetOne($sql);
$item_data['LinkId'] = $link_id;
$item_data['ListingTypeId'] = $this->Conn->GetOne($sql);
}
$sql = 'SELECT VirtualProductId FROM '.$this->Application->getUnitOption('lst', 'TableName').'
WHERE ListingTypeId = '.$item_data['ListingTypeId'];
$item_id = $this->Conn->GetOne($sql);
$event->setEventParam('ItemData', serialize($item_data));
$this->AddItemToOrder($event, $item_id);
$event->redirect = $this->Application->GetVar('shop_cart_template');
// don't pass unused info to shopping cart, brokes old mod-rewrites
$event->SetRedirectParam('pass', 'm'); // not to pass link id
$event->SetRedirectParam('m_cat_id', 0); // not to pass link id
}
function OnRemoveFromCart(&$event)
{
$ord_item_id = $this->Application->GetVar('orditems_id');
$ord_id = $this->getPassedId($event);
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'OrderItems WHERE OrderId = '.$ord_id.' AND OrderItemId = '.$ord_item_id);
$this->OnRecalculateItems($event);
}
function OnCleanupCart(&$event)
{
$object =& $event->getObject();
$sql = 'DELETE FROM '.TABLE_PREFIX.'OrderItems
WHERE OrderId = '.$this->getPassedID($event);
$this->Conn->Query($sql);
$this->RemoveCoupon($object);
$this->RemoveGiftCertificate($object);
$this->OnRecalculateItems($event);
}
/**
* Returns order id from session or last used
*
* @param kEvent $event
* @return int
*/
function getPassedId(&$event)
{
$event->setEventParam('raise_warnings', 0);
$passed = parent::getPassedID($event);
if ($this->Application->isAdminUser) {
// work as usual in admin
return $passed;
}
if ($event->Special == 'last') {
// return last order id (for using on thank you page)
return $this->Application->RecallVar('front_order_id');
}
$ses_id = $this->Application->RecallVar( $event->getPrefixSpecial(true) . '_id' );
if ($passed && ($passed != $ses_id)) {
// order id given in url doesn't match our current order id
$sql = 'SELECT PortalUserId
FROM ' . TABLE_PREFIX . 'Orders
WHERE OrderId = ' . $passed;
$user_id = $this->Conn->GetOne($sql);
if ($user_id == $this->Application->RecallVar('user_id')) {
// current user is owner of order with given id -> allow him to view order details
return $passed;
}
else {
// current user is not owner of given order -> hacking attempt
$this->Application->SetVar($event->getPrefixSpecial().'_id', 0);
return 0;
}
}
else {
// not passed or equals to ses_id
return $ses_id > 0 ? $ses_id : FAKE_ORDER_ID; // FAKE_ORDER_ID helps to keep parent filter for order items set in "kDBList::linkToParent"
}
return $passed;
}
/**
* Load item if id is available
*
* @param kEvent $event
*/
function LoadItem(&$event)
{
$id = $this->getPassedID($event);
if ($id == FAKE_ORDER_ID) {
// if we already know, that there is no such order,
// then don't run database query, that will confirm that
$object =& $event->getObject();
/* @var $object kDBItem */
$object->Clear($id);
return ;
}
parent::LoadItem($event);
}
/**
* Creates new shopping cart
*
* @param kEvent $event
*/
function _createNewCart(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$object->SetDBField('Number', $this->getNextOrderNumber($event));
$object->SetDBField('SubNumber', 0);
$object->SetDBField('Type', ORDER_STATUS_INCOMPLETE);
$object->SetDBField('VisitId', $this->Application->RecallVar('visit_id') );
// get user
$user_id = $this->Application->RecallVar('user_id');
if (!$user_id) {
$user_id = -2; // Guest
}
$object->SetDBField('PortalUserId', $user_id);
// get affiliate
$affiliate_id = $this->isAffiliate($user_id);
if ($affiliate_id) {
$object->SetDBField('AffiliateId', $affiliate_id);
}
else {
$affiliate_storage_method = $this->Application->ConfigValue('Comm_AffiliateStorageMethod');
$object->SetDBField('AffiliateId', $affiliate_storage_method == 1 ? (int)$this->Application->RecallVar('affiliate_id') : (int)$this->Application->GetVar('affiliate_id') );
}
// get payment type
$default_type = $this->Conn->GetOne('SELECT PaymentTypeId FROM '.TABLE_PREFIX.'PaymentTypes WHERE IsPrimary = 1');
if ($default_type) {
$object->SetDBField('PaymentType', $default_type);
}
$created = $object->Create();
if ($created) {
$id = $object->GetID();
$this->Application->SetVar($event->getPrefixSpecial(true) . '_id', $id);
$this->Application->StoreVar($event->getPrefixSpecial(true) . '_id', $id);
return $id;
}
return 0;
}
function StoreContinueShoppingLink()
{
$this->Application->StoreVar('continue_shopping', 'external:'.PROTOCOL.SERVER_NAME.$this->Application->RecallVar('last_url'));
}
/**
* Sets required fields for order, based on current checkout step
* !!! Do not use switch here, since all cases may be on the same form simultaniously
*
* @param kEvent $event
*/
function SetStepRequiredFields(&$event)
{
$order =& $event->getObject();
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ($items_info) {
// updated address available from SUBMIT -> use it
list($id, $field_values) = each($items_info);
}
else {
// no updated address -> use current address
$field_values = Array (
'ShippingCountry' => $order->GetDBField('ShippingCountry'),
'BillingCountry' => $order->GetDBField('BillingCountry'),
'PaymentType' => $order->GetDBField('PaymentType'),
);
}
// shipping address required fields
if ($this->Application->GetVar('check_shipping_address')) {
$has_tangibles = $order->HasTangibleItems();
$req_fields = array('ShippingTo', 'ShippingAddress1', 'ShippingCity', 'ShippingZip', 'ShippingCountry', 'ShippingPhone');
foreach ($req_fields as $field) {
$order->Fields[$field]['required'] = $has_tangibles;
}
- if ($cs_helper->CountryHasStates( getArrayValue($field_values, 'ShippingCountry') )) {
- $order->Fields['ShippingState']['required'] = true; // $has_tangibles
- }
+
+ $order->setRequired('ShippingState', $cs_helper->CountryHasStates( $field_values['ShippingCountry'] ));
}
// billing address required fields
if ($this->Application->GetVar('check_billing_address')) {
$req_fields = array('BillingTo', 'BillingAddress1', 'BillingCity', 'BillingZip', 'BillingCountry', 'BillingPhone');
foreach ($req_fields as $field) {
$order->Fields[$field]['required'] = true;
}
- if ($cs_helper->CountryHasStates( getArrayValue($field_values, 'BillingCountry') )) {
- $order->Fields['BillingState']['required'] = true;
- }
+
+ $order->setRequired('BillingState', $cs_helper->CountryHasStates( $field_values['BillingCountry'] ));
}
$check_cc = $this->Application->GetVar('check_credit_card');
$ord_event = $this->Application->GetVar($event->getPrefixSpecial().'_event');
if (($ord_event !== 'OnProceedToPreview') && !$this->Application->isAdmin) {
// don't check credit card when going from "billing info" to "order preview" step
$check_cc = 0;
}
if ($check_cc && ($field_values['PaymentType'] == $order->GetDBField('PaymentType'))) {
// cc check required AND payment type was not changed during SUBMIT
if ($this->Application->isAdminUser) {
$req_fields = array('PaymentCardType', 'PaymentAccount', 'PaymentNameOnCard', 'PaymentCCExpDate');
}
else {
$req_fields = array('PaymentCardType', 'PaymentAccount', 'PaymentNameOnCard', 'PaymentCCExpDate', 'PaymentCVV2');
}
foreach ($req_fields as $field) {
$order->Fields[$field]['required'] = true;
}
}
}
/**
* Set's order's user_id to user from session or Guest otherwise
*
* @param kEvent $event
*/
function CheckUser(&$event)
{
if ($this->Application->isAdminUser) {
return;
}
$order =& $event->GetObject();
$ses_user = $this->Application->RecallVar('user_id');
if ($order->GetDBField('PortalUserId') != $ses_user) {
if ($ses_user == 0) $ses_user = -2; //Guest
$order->SetDBField('PortalUserId', $ses_user);
// since CheckUser is called in OnBeforeItemUpdate, we don't need to call udpate here, just set the field
}
}
/* ======================== ADMIN ONLY ======================== */
/**
* Prepare temp tables and populate it
* with items selected in the grid
*
* @param kEvent $event
*/
function OnPreCreate(&$event)
{
parent::OnPreCreate($event);
$object =& $event->getObject();
$new_number = $this->getNextOrderNumber($event);
$object->SetDBField('Number', $new_number);
$object->SetDBField('SubNumber', 0);
$object->SetDBField('OrderIP', $_SERVER['REMOTE_ADDR']);
$order_type = $this->getTypeBySpecial( $this->Application->GetVar('order_type') );
$object->SetDBField('Status', $order_type);
}
/**
* When cloning orders set new order number to them
*
* @param kEvent $event
*/
function OnBeforeClone(&$event)
{
$object =& $event->getObject();
if (substr($event->Special, 0, 9) == 'recurring') {
$object->SetDBField('SubNumber', $object->getNextSubNumber());
$object->SetDBField('OriginalAmount', 0); // needed in this case ?
}
else {
$new_number = $this->getNextOrderNumber($event);
$object->SetDBField('Number', $new_number);
$object->SetDBField('SubNumber', 0);
$object->SetDBField('OriginalAmount', 0);
}
$object->SetDBField('OrderDate', adodb_mktime());
$object->UpdateFormattersSubFields();
$object->SetDBField('GWResult1', '');
$object->SetDBField('GWResult2', '');
}
function OnReserveItems(&$event)
{
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
$order_items->linkToParent('-inv');
// force re-query, since we are updateing through orditem ITEM, not the list, and
// OnReserveItems may be called 2 times when fullfilling backorders through product edit - first time
// from FullFillBackorders and second time from OnOrderProcess
$order_items->Query(true);
$order_items->GoFirst();
// query all combinations used in this order
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
$product_object->SwitchToLive();
$order_item =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
$combination_item =& $this->Application->recallObject('poc.-item', null, Array('skip_autoload' => true));
$combinations = $this->queryCombinations($order_items);
$event->status = erSUCCESS;
while (!$order_items->EOL()) {
$rec = $order_items->getCurrentRecord();
$product_object->Load( $rec['ProductId'] );
if (!$product_object->GetDBField('InventoryStatus')) {
$order_items->GoNext();
continue;
}
$inv_object =& $this->getInventoryObject($product_object, $combination_item, $combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ]);
$lack = $rec['Quantity'] - $rec['QuantityReserved'];
if ($lack > 0) {
// reserve lack or what is available (in case if we need to reserve anything, by Alex)
$to_reserve = min($lack, $inv_object->GetDBField('QtyInStock') - $product_object->GetDBField('QtyInStockMin'));
if ($to_reserve < $lack) $event->status = erFAIL; // if we can't reserve the full lack
//reserve in order
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetDBField('QuantityReserved', $rec['QuantityReserved'] + $to_reserve);
$order_item->SetId($rec['OrderItemId']);
$order_item->Update();
//update product - increase reserved, decrease in stock
$inv_object->SetDBField('QtyReserved', $inv_object->GetDBField('QtyReserved') + $to_reserve);
$inv_object->SetDBField('QtyInStock', $inv_object->GetDBField('QtyInStock') - $to_reserve);
$inv_object->SetDBField('QtyBackOrdered', $inv_object->GetDBField('QtyBackOrdered') - $to_reserve);
$inv_object->Update();
if ($product_object->GetDBField('InventoryStatus') == 2) {
// inventory by options, then restore changed combination values back to common $combinations array !!!
$combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ] = $inv_object->FieldValues;
}
}
$order_items->GoNext();
}
return true;
}
function OnOrderPrint(&$event)
{
$event->redirect_params = Array('opener'=>'s');
}
/**
* Processes order each tab info resetting to other tab info / to user info
*
* @param kEvent $event
* @access public
*/
function OnResetAddress(&$event)
{
$to_tab = $this->Application->GetVar('to_tab');
$from_tab = substr($event->Name,strlen('OnResetTo'));
// load values from db
$object =& $event->getObject();
// update values from submit
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info) $field_values = array_shift($items_info);
$object->SetFieldsFromHash($field_values);
$this->DoResetAddress($object, $from_tab, $to_tab);
$object->Update();
$event->redirect = false;
}
/**
* Processes item selection from popup item selector
*
* @todo Is this called ? (by Alex)
* @param kEvent $event
*/
function OnProcessSelected(&$event)
{
$selected_ids = $this->Application->GetVar('selected_ids');
$product_ids = $selected_ids['p'];
if ($product_ids) {
$product_ids = explode(',', $product_ids);
// !!! LOOK OUT - Adding items to Order in admin is handled in order_ITEMS_event_handler !!!
foreach ($product_ids as $product_id) {
$this->AddItemToOrder($event, $product_id);
}
}
$this->finalizePopup($event);
}
function OnMassPlaceOrder(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$ids = $this->StoreSelectedIDs($event);
if($ids)
{
foreach($ids as $id)
{
$object->Load($id);
$this->DoPlaceOrder($event);
}
}
$event->status = erSUCCESS;
}
/**
* Universal
* Checks if QtyInStock is enough to fullfill backorder (Qty - QtyReserved in order)
*
* @param int $ord_id
* @return bool
*/
function ReadyToProcess($ord_id)
{
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' SELECT SUM(IF( IF('.TABLE_PREFIX.'Products.InventoryStatus = 2, '.$poc_table.'.QtyInStock, '.TABLE_PREFIX.'Products.QtyInStock) - '.TABLE_PREFIX.'Products.QtyInStockMin >= ('.TABLE_PREFIX.'OrderItems.Quantity - '.TABLE_PREFIX.'OrderItems.QuantityReserved), 0, 1))
FROM '.TABLE_PREFIX.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Products ON '.TABLE_PREFIX.'Products.ProductId = '.TABLE_PREFIX.'OrderItems.ProductId
LEFT JOIN '.$poc_table.' ON ('.$poc_table.'.CombinationCRC = '.TABLE_PREFIX.'OrderItems.OptionsSalt) AND ('.$poc_table.'.ProductId = '.TABLE_PREFIX.'OrderItems.ProductId)
WHERE OrderId = '.$ord_id.'
GROUP BY OrderId';
// IF (IF(InventoryStatus = 2, poc.QtyInStock, p.QtyInStock) - QtyInStockMin >= (Quantity - QuantityReserved), 0, 1
return ($this->Conn->GetOne($query) == 0);
}
/**
* Return all option combinations used in order
*
* @param kDBList $order_items
* @return Array
*/
function queryCombinations(&$order_items)
{
// 1. collect combination crc used in order
$combinations = Array();
while (!$order_items->EOL()) {
$row = $order_items->getCurrentRecord();
if ($row['OptionsSalt'] == 0) {
$order_items->GoNext();
continue;
}
$combinations[] = '(poc.ProductId = '.$row['ProductId'].') AND (poc.CombinationCRC = '.$row['OptionsSalt'].')';
$order_items->GoNext();
}
$order_items->GoFirst();
$combinations = array_unique($combinations); // if same combination+product found as backorder & normal order item
if ($combinations) {
// 2. query data about combinations
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$sql = 'SELECT CONCAT(poc.ProductId, "_", poc.CombinationCRC) AS CombinationKey, poc.*
FROM '.$poc_table.' poc
WHERE ('.implode(') OR (', $combinations).')';
return $this->Conn->Query($sql, 'CombinationKey');
}
return Array();
}
/**
* Returns object to perform inventory actions on
*
* @param ProductsItem $product current product object in order
* @param kDBItem $combination combination dummy object
* @param Array $combination_data pre-queried combination data
* @return kDBItem
*/
function &getInventoryObject(&$product, &$combination, $combination_data)
{
if ($product->GetDBField('InventoryStatus') == 2) {
// inventory by option combinations
$combination->SetDBFieldsFromHash($combination_data);
$combination->setID($combination_data['CombinationId']);
$change_item =& $combination;
}
else {
// inventory by product ifself
$change_item =& $product;
}
return $change_item;
}
/**
* Approve order ("Pending" tab)
*
* @param kDBList $order_items
* @return int new status of order if any
*/
function approveOrder(&$order_items)
{
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
$order_item =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
$combination_item =& $this->Application->recallObject('poc.-item', null, Array('skip_autoload' => true));
$combinations = $this->queryCombinations($order_items);
while (!$order_items->EOL()) {
$rec = $order_items->getCurrentRecord();
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetId($rec['OrderItemId']);
$order_item->SetDBField('QuantityReserved', 0);
$order_item->Update();
$product_object->Load( $rec['ProductId'] );
if (!$product_object->GetDBField('InventoryStatus')) {
// if no inventory info is collected, then skip this order item
$order_items->GoNext();
continue;
}
$inv_object =& $this->getInventoryObject($product_object, $combination_item, $combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ]);
// decrease QtyReserved by amount of product used in order
$inv_object->SetDBField('QtyReserved', $inv_object->GetDBField('QtyReserved') - $rec['Quantity']);
$inv_object->Update();
if ($product_object->GetDBField('InventoryStatus') == 2) {
// inventory by options, then restore changed combination values back to common $combinations array !!!
$combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ] = $inv_object->FieldValues;
}
$order_items->GoNext();
}
return true;
}
function restoreOrder(&$order_items)
{
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
$product_object->SwitchToLive();
$order_item =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
$combination_item =& $this->Application->recallObject('poc.-item', null, Array('skip_autoload' => true));
$combinations = $this->queryCombinations($order_items);
while( !$order_items->EOL() )
{
$rec = $order_items->getCurrentRecord();
$product_object->Load( $rec['ProductId'] );
if (!$product_object->GetDBField('InventoryStatus')) {
// if no inventory info is collected, then skip this order item
$order_items->GoNext();
continue;
}
$inv_object =& $this->getInventoryObject($product_object, $combination_item, $combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ]);
// cancelling backorderd qty if any
$lack = $rec['Quantity'] - $rec['QuantityReserved'];
if ($lack > 0 && $rec['BackOrderFlag'] > 0) { // lack should have been recorded as QtyBackOrdered
$inv_object->SetDBField('QtyBackOrdered', $inv_object->GetDBField('QtyBackOrdered') - $lack);
}
// canceling reservation in stock
$inv_object->SetDBField('QtyReserved', $inv_object->GetDBField('QtyReserved') - $rec['QuantityReserved']);
// putting remaining freed qty back to stock
$inv_object->SetDBField('QtyInStock', $inv_object->GetDBField('QtyInStock') + $rec['QuantityReserved']);
$inv_object->Update();
$product_h =& $this->Application->recallObject('p_EventHandler');
if ($product_object->GetDBField('InventoryStatus') == 2) {
// inventory by options, then restore changed combination values back to common $combinations array !!!
$combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ] = $inv_object->FieldValues;
// using freed qty to fullfill possible backorders
$product_h->FullfillBackOrders($product_object, $inv_object->GetID());
}
else {
// using freed qty to fullfill possible backorders
$product_h->FullfillBackOrders($product_object, 0);
}
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetId($rec['OrderItemId']);
$order_item->SetDBField('QuantityReserved', 0);
$order_item->Update();
$order_items->GoNext();
}
return true;
}
/**
* Approve order + special processing
*
* @param kEvent $event
*/
function MassInventoryAction(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = erFAIL;
return;
}
// process order products
$object =& $this->Application->recallObject($event->Prefix.'.-inv', null, Array('skip_autoload' => true));
$ids = $this->StoreSelectedIDs($event);
if($ids)
{
foreach($ids as $id)
{
$object->Load($id);
$this->InventoryAction($event);
}
}
}
function InventoryAction(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = erFAIL;
return;
}
$event_status_map = Array(
'OnMassOrderApprove' => ORDER_STATUS_TOSHIP,
'OnOrderApprove' => ORDER_STATUS_TOSHIP,
'OnMassOrderDeny' => ORDER_STATUS_DENIED,
'OnOrderDeny' => ORDER_STATUS_DENIED,
'OnMassOrderArchive' => ORDER_STATUS_ARCHIVED,
'OnOrderArchive' => ORDER_STATUS_ARCHIVED,
'OnMassOrderShip' => ORDER_STATUS_PROCESSED,
'OnOrderShip' => ORDER_STATUS_PROCESSED,
'OnMassOrderProcess' => ORDER_STATUS_TOSHIP,
'OnOrderProcess' => ORDER_STATUS_TOSHIP,
);
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
$order_items->linkToParent('-inv');
$order_items->Query();
$order_items->GoFirst();
$object =& $this->Application->recallObject($event->Prefix.'.-inv');
/* @var $object OrdersItem */
if ($object->GetDBField('OnHold')) {
// any actions have no effect while on hold
return ;
}
// preparing new status, but not setting it yet
$object->SetDBField('Status', $event_status_map[$event->Name]);
$set_new_status = false;
$event->status = erSUCCESS;
$email_params = $this->OrderEmailParams($object);
switch ($event->Name) {
case 'OnMassOrderApprove':
case 'OnOrderApprove':
$set_new_status = false; //on succsessfull approve order will be split and new orders will have new statuses
if ($object->GetDBField('ChargeOnNextApprove')) {
$charge_info = $this->ChargeOrder($object);
if (!$charge_info['result']) {
break;
}
// removing ChargeOnNextApprove
$object->SetDBField('ChargeOnNextApprove', 0);
$sql = 'UPDATE '.$object->TableName.' SET ChargeOnNextApprove = 0 WHERE '.$object->IDField.' = '.$object->GetID();
$this->Conn->Query($sql);
}
// charge user for order in case if we user 2step charging (e.g. AUTH_ONLY + PRIOR_AUTH_CAPTURE)
$gw_data = $object->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$charge_result = $gateway_object->Charge($object->FieldValues, $gw_data['gw_params']);
$sql = 'UPDATE %s SET GWResult2 = %s WHERE %s = %s';
$sql = sprintf($sql, $object->TableName, $this->Conn->qstr($gateway_object->getGWResponce()), $object->IDField, $object->GetID() );
$this->Conn->Query($sql);
$object->SetDBField('GWResult2', $gateway_object->getGWResponce() );
if ($charge_result) {
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
foreach ($order_items->Records as $product_item) {
if (!$product_item['ProductId']) {
// product may have been deleted
continue;
}
$product_object->Load($product_item['ProductId']);
$hits = floor( $product_object->GetDBField('Hits') ) + 1;
$sql = 'SELECT MAX(Hits) FROM '.$this->Application->getUnitOption('p', 'TableName').'
WHERE FLOOR(Hits) = '.$hits;
$hits = ( $res = $this->Conn->GetOne($sql) ) ? $res + 0.000001 : $hits;
$product_object->SetDBField('Hits', $hits);
$product_object->Update();
/*$sql = 'UPDATE '.$this->Application->getUnitOption('p', 'TableName').'
SET Hits = Hits + '.$product_item['Quantity'].'
WHERE ProductId = '.$product_item['ProductId'];
$this->Conn->Query($sql);*/
}
$this->PrepareCoupons($event, $object);
$this->SplitOrder($event, $object);
if ($object->GetDBField('IsRecurringBilling') != 1) {
$email_event_user =& $this->Application->EmailEventUser('ORDER.APPROVE', $object->GetDBField('PortalUserId'), $email_params);
// Mask credit card with XXXX
if ($this->Application->ConfigValue('Comm_MaskProcessedCreditCards')) {
$this->maskCreditCard($object, 'PaymentAccount');
$set_new_status = 1;
}
}
}
break;
case 'OnMassOrderDeny':
case 'OnOrderDeny':
foreach ($order_items->Records as $product_item) {
if (!$product_item['ProductId']) {
// product may have been deleted
continue;
}
$this->raiseProductEvent('Deny', $product_item['ProductId'], $product_item);
}
$email_event_user =& $this->Application->EmailEventUser('ORDER.DENY', $object->GetDBField('PortalUserId'), $email_params);
if ($event->Name == 'OnMassOrderDeny' || $event->Name == 'OnOrderDeny') {
// inform payment gateway that order was declined
$gw_data = $object->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$gateway_object->OrderDeclined($object->FieldValues, $gw_data['gw_params']);
}
// !!! LOOK HERE !!!
// !!!! no break !!!! here on purpose!!!
case 'OnMassOrderArchive':
case 'OnOrderArchive':
// it's critical to update status BEFORE processing items because
// FullfillBackorders could be called during processing and in case
// of order denial/archive fullfill could reserve the qtys back for current backorder
$object->Update();
$this->restoreOrder($order_items);
$set_new_status = false; // already set
break;
case 'OnMassOrderShip':
case 'OnOrderShip':
$ret = Array();
// try to create usps order
if ( $object->GetDBField('ShippingType') == 0 && strpos($object->GetDBField('ShippingInfo'), 'USPS')) {
$ses_usps_erros = Array();
$ret = $this->MakeUSPSOrder($object);
}
if ( !array_key_exists('error_number', $ret) ) {
$set_new_status = $this->approveOrder($order_items);
// $set_new_status = $this->shipOrder($order_items);
$object->SetDBField('ShippingDate', adodb_mktime());
$object->UpdateFormattersSubFields();
$shipping_email = $object->GetDBField('ShippingEmail');
$email_params['to_email'] = $shipping_email ? $shipping_email : $email_params['_user_email'];
$email_event_user =& $this->Application->EmailEventUser('ORDER.SHIP', $object->GetDBField('PortalUserId'), $email_params);
// inform payment gateway that order was shipped
$gw_data = $object->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$gateway_object->OrderShipped($object->FieldValues, $gw_data['gw_params']);
}
else {
$usps_errors[$object->GetField('OrderNumber')] = $ret['error_description'];
$ses_usps_erros = Array();
$ses_usps_erros = unserialize($this->Application->RecallVar('usps_errors'));
if ( is_array($ses_usps_erros) ) {
$usps_errors = array_merge($usps_errors, $ses_usps_erros);
}
$this->Application->StoreVar('usps_errors', serialize($usps_errors));
}
break;
case 'OnMassOrderProcess':
case 'OnOrderProcess':
if ($this->ReadyToProcess($object->GetID())) {
$event->CallSubEvent('OnReserveItems');
if ($event->status == erSUCCESS) $set_new_status = true;
$email_event_user =& $this->Application->EmailEventUser('BACKORDER.PROCESS', $object->GetDBField('PortalUserId'), $email_params);
} else {
$event->status = erFAIL;
}
break;
}
if ($set_new_status) {
$object->Update();
}
}
/**
* Hides last 4 digits from credit card number
*
* @param OrdersItem $object
* @param string $field
*/
function maskCreditCard(&$object, $field)
{
$value = $object->GetDBField($field);
$value = preg_replace('/'.substr($value, -4).'$/', str_repeat('X', 4), $value);
$object->SetDBField($field, $value);
}
/**
* Get next free order number
*
* @param kEvent $event
*/
function getNextOrderNumber(&$event)
{
$object =& $event->getObject();
$sql = 'SELECT MAX(Number)
FROM ' . $this->Application->GetLiveName($object->TableName);
return max($this->Conn->GetOne($sql) + 1, $this->Application->ConfigValue('Comm_Next_Order_Number'));
}
/**
* Set's new order address based on another address from order (e.g. billing from shipping)
*
* @param unknown_type $object
* @param unknown_type $from
* @param unknown_type $to
*/
function DoResetAddress(&$object, $from, $to)
{
$fields = Array('To','Company','Phone','Fax','Email','Address1','Address2','City','State','Zip','Country');
if ($from == 'User') {
// skip theese fields when coping from user, because they are not present in user profile
$tmp_fields = array_flip($fields);
// unset($tmp_fields['Company'], $tmp_fields['Fax'], $tmp_fields['Address2']);
$fields = array_flip($tmp_fields);
}
// apply modification
foreach ($fields as $field_name) {
$object->SetDBField($to.$field_name, $object->GetDBField($from.$field_name));
}
}
/**
* Set's additional view filters set from "Orders" => "Search" tab
*
* @param kEvent $event
*/
function AddFilters(&$event)
{
parent::AddFilters($event);
if($event->Special != 'search') return true;
$search_filter = $this->Application->RecallVar('ord.search_search_filter');
if(!$search_filter) return false;
$search_filter = unserialize($search_filter);
$event->setPseudoClass('_List');
$object =& $event->getObject();
foreach($search_filter as $filter_name => $filter_params)
{
$filter_type = $filter_params['type'] == 'where' ? WHERE_FILTER : HAVING_FILTER;
$object->addFilter($filter_name, $filter_params['value'], $filter_type, FLT_VIEW);
}
}
/**
* Set's status incomplete to all cloned orders
*
* @param kEvent $event
*/
function OnAfterClone(&$event)
{
$id = $event->getEventParam('id');
$table = $this->Application->getUnitOption($event->Prefix,'TableName');
$id_field = $this->Application->getUnitOption($event->Prefix,'IDField');
// set cloned order status to Incomplete
$sql = 'UPDATE '.$table.' SET Status = 0 WHERE '.$id_field.' = '.$id;
$this->Conn->Query($sql);
}
/* ======================== COMMON CODE ======================== */
/**
* Split one timestamp field into 2 virtual fields
*
* @param kEvent $event
* @access public
*/
function OnAfterItemLoad(&$event)
{
// get user fields
$object =& $event->getObject();
$user_id = $object->GetDBField('PortalUserId');
if($user_id)
{
$user_info = $this->Conn->GetRow('SELECT *, CONCAT(FirstName,\' \',LastName) AS UserTo FROM '.TABLE_PREFIX.'PortalUser WHERE PortalUserId = '.$user_id);
$fields = Array('UserTo'=>'UserTo','UserPhone'=>'Phone','UserFax'=>'Fax','UserEmail'=>'Email',
'UserAddress1'=>'Street','UserAddress2'=>'Street2','UserCity'=>'City','UserState'=>'State',
'UserZip'=>'Zip','UserCountry'=>'Country','UserCompany'=>'Company');
foreach($fields as $object_field => $user_field)
{
$object->SetDBField($object_field,$user_info[$user_field]);
}
}
$object->SetDBField('PaymentCVV2', $this->Application->RecallVar('CVV2Code') );
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
$cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
$cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
$this->SetStepRequiredFields($event);
// needed in OnAfterItemUpdate
$this->Application->SetVar('OriginalShippingOption', $object->GetDBField('ShippingOption'));
}
/**
+ * Processes states
+ *
+ * @param kEvent $event
+ */
+ function OnBeforeItemCreate(&$event)
+ {
+ parent::OnBeforeItemCreate($event);
+
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
+ $cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
+ }
+
+ /**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
+ parent::OnBeforeItemUpdate($event);
+
+ $object =& $event->getObject();
+ /* @var $object OrdersItem */
+
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
$cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
$cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
- $object = &$event->getObject();
- if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) return;
+ if ($object->HasTangibleItems()) {
+ $cs_helper->CheckStateField($event, 'ShippingState', 'ShippingCountry', false);
+ }
+
+ $cs_helper->CheckStateField($event, 'BillingState', 'BillingCountry', false);
+
+ if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) {
+ return ;
+ }
$this->CheckUser($event);
if(!$object->GetDBField('OrderIP'))
{
$object->SetDBField('OrderIP', $_SERVER['REMOTE_ADDR']);
}
$shipping_option = $this->Application->GetVar('OriginalShippingOption');
$new_shipping_option = $object->GetDBField('ShippingOption');
if ($shipping_option != $new_shipping_option) {
$this->UpdateShippingOption($event);
}
else {
$this->UpdateShippingTypes($event);
}
$this->RecalculateProcessingFee($event);
$this->UpdateShippingTotal($event);
$this->RecalculateGift($event);
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @access protected
* @see OnListBuild
*/
function SetCustomQuery(&$event)
{
$object =& $event->getObject();
$types = $event->getEventParam('types');
if($types == 'myorders' || $types == 'myrecentorders')
{
$user_id = $this->Application->RecallVar('user_id');
$object->addFilter('myitems_user1','%1$s.PortalUserId = '.$user_id);
$object->addFilter('myitems_user2','%1$s.PortalUserId > 0');
$object->addFilter('Status','%1$s.Status != 0');
}
else if ($event->Special == 'returns') {
// $object->addFilter('returns_filter',TABLE_PREFIX.'Orders.Status = '.ORDER_STATUS_PROCESSED.' AND (
// SELECT SUM(ReturnType)
// FROM '.TABLE_PREFIX.'OrderItems oi
// WHERE oi.OrderId = '.TABLE_PREFIX.'Orders.OrderId
// ) > 0');
$object->addFilter('returns_filter',TABLE_PREFIX.'Orders.Status = '.ORDER_STATUS_PROCESSED.' AND '.TABLE_PREFIX.'Orders.ReturnTotal > 0');
}
else if ($event->Special == 'user') {
$user_id = $this->Application->GetVar('u_id');
$object->addFilter('user_filter','%1$s.PortalUserId = '.$user_id);
}
else {
$special = $event->Special ? $event->Special : $this->Application->GetVar('order_type');
if ($special != 'search') {
// don't filter out orders by special in case of search tab
$object->addFilter( 'status_filter', '%1$s.Status='.$this->getTypeBySpecial($special) );
}
if ( $event->getEventParam('selected_only') ) {
$ids = $this->StoreSelectedIDs($event);
$object->addFilter( 'selected_filter', '%1$s.OrderId IN ('.implode(',', $ids).')');
}
}
}
function getTypeBySpecial($special)
{
$special2type = Array('incomplete'=>0,'pending'=>1,'backorders'=>2,'toship'=>3,'processed'=>4,'denied'=>5,'archived'=>6);
return $special2type[$special];
}
function getSpecialByType($type)
{
$type2special = Array(0=>'incomplete',1=>'pending',2=>'backorders',3=>'toship',4=>'processed',5=>'denied',6=>'archived');
return $type2special[$type];
}
function LockTables(&$event)
{
$read = Array();
$write_lock = '';
$read_lock = '';
$write = Array('Orders','OrderItems','Products');
foreach ($write as $tbl) {
$write_lock .= TABLE_PREFIX.$tbl.' WRITE,';
}
foreach ($read as $tbl) {
$read_lock .= TABLE_PREFIX.$tbl.' READ,';
}
$write_lock = rtrim($write_lock, ',');
$read_lock = rtrim($read_lock, ',');
$lock = trim($read_lock.','.$write_lock, ',');
//$this->Conn->Query('LOCK TABLES '.$lock);
}
/**
* Checks shopping cart products quantities
*
* @param kEvent $event
* @return bool
*/
function CheckQuantites(&$event)
{
if ($this->OnRecalculateItems($event)) { // if something has changed in the order
if ($this->Application->isAdminUser) {
if ($this->UseTempTables($event)) {
$event->redirect = 'in-commerce/orders/orders_edit_items';
}
}
else {
$event->redirect = $this->Application->GetVar('viewcart_template');
}
return false;
}
return true;
}
function DoPlaceOrder(&$event)
{
$order =& $event->getObject();
$table_prefix = $this->TablePrefix($event);
$this->LockTables($event);
if (!$this->CheckQuantites($event)) return false;
//everything is fine - we could reserve items
$this->ReserveItems($event);
$this->SplitOrder($event, $order);
return true;
}
function &queryOrderItems(&$event, $table_prefix)
{
$order =& $event->getObject();
$ord_id = $order->GetId();
// TABLE_PREFIX and $table_prefix are NOT the same !!!
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' SELECT
BackOrderFlag, '.
$table_prefix.'OrderItems.OrderItemId, '.
$table_prefix.'OrderItems.Quantity, '.
$table_prefix.'OrderItems.QuantityReserved,
IF('.TABLE_PREFIX.'Products.InventoryStatus = 2, '.$poc_table.'.QtyInStock, '.TABLE_PREFIX.'Products.QtyInStock) AS QtyInStock, '.
TABLE_PREFIX.'Products.QtyInStockMin, '.
$table_prefix.'OrderItems.ProductId, '.
TABLE_PREFIX.'Products.InventoryStatus,'.
$table_prefix.'OrderItems.OptionsSalt AS CombinationCRC
FROM '.$table_prefix.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Products ON '.TABLE_PREFIX.'Products.ProductId = '.$table_prefix.'OrderItems.ProductId
LEFT JOIN '.$poc_table.' ON ('.$poc_table.'.CombinationCRC = '.$table_prefix.'OrderItems.OptionsSalt) AND ('.$poc_table.'.ProductId = '.$table_prefix.'OrderItems.ProductId)
WHERE OrderId = '.$ord_id.' AND '.TABLE_PREFIX.'Products.Type = 1
ORDER BY BackOrderFlag ASC';
$items = $this->Conn->Query($query);
return $items;
}
function ReserveItems(&$event)
{
$table_prefix = $this->TablePrefix($event);
$items =& $this->queryOrderItems($event, $table_prefix);
foreach ($items as $an_item) {
if (!$an_item['InventoryStatus']) {
$to_reserve = $an_item['Quantity'] - $an_item['QuantityReserved'];
}
else {
if ($an_item['BackOrderFlag'] > 0) { // we don't need to reserve if it's backordered item
$to_reserve = 0;
}
else {
$to_reserve = min($an_item['Quantity']-$an_item['QuantityReserved'], $an_item['QtyInStock']-$an_item['QtyInStockMin']); //it should be equal, but just in case
}
$to_backorder = $an_item['BackOrderFlag'] > 0 ? $an_item['Quantity']-$an_item['QuantityReserved'] : 0;
}
if ($to_backorder < 0) $to_backorder = 0; //just in case
$query = ' UPDATE '.$table_prefix.'OrderItems
SET QuantityReserved = IF(QuantityReserved IS NULL, '.$to_reserve.', QuantityReserved + '.$to_reserve.')
WHERE OrderItemId = '.$an_item['OrderItemId'];
$this->Conn->Query($query);
if (!$an_item['InventoryStatus']) continue;
$update_clause = ' QtyInStock = QtyInStock - '.$to_reserve.',
QtyReserved = QtyReserved + '.$to_reserve.',
QtyBackOrdered = QtyBackOrdered + '.$to_backorder;
if ($an_item['InventoryStatus'] == 1) {
// inventory by product, then update it's quantities
$query = ' UPDATE '.TABLE_PREFIX.'Products
SET '.$update_clause.'
WHERE ProductId = '.$an_item['ProductId'];
}
else {
// inventory = 2 -> by product option combinations
$poc_idfield = $this->Application->getUnitOption('poc', 'IDField');
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' UPDATE '.$poc_table.'
SET '.$update_clause.'
WHERE (ProductId = '.$an_item['ProductId'].') AND (CombinationCRC = '.$an_item['CombinationCRC'].')';
}
$this->Conn->Query($query);
}
}
function FreeItems(&$event)
{
$table_prefix = $this->TablePrefix($event);
$items =& $this->queryOrderItems($event, $table_prefix);
foreach ($items as $an_item) {
$to_free = $an_item['QuantityReserved'];
if ($an_item['InventoryStatus']) {
if ($an_item['BackOrderFlag'] > 0) { // we don't need to free if it's backordered item
$to_free = 0;
}
// what's not reserved goes to backorder in stock for orderitems marked with BackOrderFlag
$to_backorder_free = $an_item['BackOrderFlag'] > 0 ? $an_item['Quantity'] - $an_item['QuantityReserved'] : 0;
if ($to_backorder_free < 0) $to_backorder_free = 0; //just in case
$update_clause = ' QtyInStock = QtyInStock + '.$to_free.',
QtyReserved = QtyReserved - '.$to_free.',
QtyBackOrdered = QtyBackOrdered - '.$to_backorder_free;
if ($an_item['InventoryStatus'] == 1) {
// inventory by product
$query = ' UPDATE '.TABLE_PREFIX.'Products
SET '.$update_clause.'
WHERE ProductId = '.$an_item['ProductId'];
}
else {
// inventory by option combinations
$poc_idfield = $this->Application->getUnitOption('poc', 'IDField');
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' UPDATE '.$poc_table.'
SET '.$update_clause.'
WHERE (ProductId = '.$an_item['ProductId'].') AND (CombinationCRC = '.$an_item['CombinationCRC'].')';
}
$this->Conn->Query($query);
}
$query = ' UPDATE '.$table_prefix.'OrderItems
SET QuantityReserved = IF(QuantityReserved IS NULL, 0, QuantityReserved - '.$to_free.')
WHERE OrderItemId = '.$an_item['OrderItemId'];
$this->Conn->Query($query);
}
}
/**
* Enter description here...
*
* @param kEvent $event
* @param OrdersItem $object
*/
function SplitOrder(&$event, &$object)
{
$affiliate_event = new kEvent('affil:OnOrderApprove');
$affiliate_event->setEventParam('Order_PrefixSpecial', $object->getPrefixSpecial() );
$this->Application->HandleEvent($affiliate_event);
$table_prefix = $this->TablePrefix($event);
$order =& $object;
$ord_id = $order->GetId();
$shipping_option = $order->GetDBField('ShippingOption');
$backorder_select = $shipping_option == 0 ? '0 As BackOrderFlag' : 'BackOrderFlag';
// setting PackageNum to 0 for Non-tangible items, for tangibles first package num is always 1
$query = ' SELECT OrderItemId
FROM '.$table_prefix.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Products
ON '.TABLE_PREFIX.'Products.ProductId = '.$table_prefix.'OrderItems.ProductId
WHERE '.TABLE_PREFIX.'Products.Type > 1 AND OrderId = '.$ord_id;
$non_tangibles = $this->Conn->GetCol($query);
if ($non_tangibles) {
$query = 'UPDATE '.$table_prefix.'OrderItems SET PackageNum = 0 WHERE OrderItemId IN ('.implode(',', $non_tangibles).')';
$this->Conn->Query($query);
}
// grouping_data:
// 0 => Product Type
// 1 => if NOT tangibale and NOT downloadable - OrderItemId,
// 2 => ProductId
// 3 => Shipping PackageNum
$query = 'SELECT
'.$backorder_select.',
PackageNum,
ProductName,
ShippingTypeId,
CONCAT('.TABLE_PREFIX.'Products.Type,
"_",
IF ('.TABLE_PREFIX.'Products.Type NOT IN ('.PRODUCT_TYPE_DOWNLOADABLE.','.PRODUCT_TYPE_TANGIBLE.'),
CONCAT(OrderItemId, "_", '.TABLE_PREFIX.'Products.ProductId),
""),
"_",
PackageNum
) AS Grouping,
SUM(Quantity) AS TotalItems,
SUM('.$table_prefix.'OrderItems.Weight*Quantity) AS TotalWeight,
SUM(Price * Quantity) AS TotalAmount,
SUM(QuantityReserved) AS TotalReserved,
'.TABLE_PREFIX.'Products.Type AS ProductType
FROM '.$table_prefix.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Products
ON '.TABLE_PREFIX.'Products.ProductId = '.$table_prefix.'OrderItems.ProductId
WHERE OrderId = '.$ord_id.'
GROUP BY BackOrderFlag, Grouping
ORDER BY BackOrderFlag ASC, PackageNum ASC, ProductType ASC';
$sub_orders = $this->Conn->Query($query);
$processed_sub_orders = Array();
// in case of recurring billing this will not be 0 as usual
//$first_sub_number = ($event->Special == 'recurring') ? $object->getNextSubNumber() - 1 : 0;
$first_sub_number = $object->GetDBField('SubNumber');
$next_sub_number = $first_sub_number;
$group = 1;
$order_has_gift = $order->GetDBField('GiftCertificateDiscount') > 0 ? 1 : 0;
$skip_types = Array (PRODUCT_TYPE_TANGIBLE, PRODUCT_TYPE_DOWNLOADABLE);
foreach ($sub_orders as $sub_order_data) {
$sub_order =& $this->Application->recallObject('ord.-sub'.$next_sub_number, 'ord');
/* @var $sub_order OrdersItem */
if ($this->UseTempTables($event) && $next_sub_number == 0) {
$sub_order =& $order;
}
$sub_order->SetDBFieldsFromHash($order->FieldValues);
$sub_order->SetDBField('SubNumber', $next_sub_number);
$sub_order->SetDBField('SubTotal', $sub_order_data['TotalAmount']);
$grouping_data = explode('_', $sub_order_data['Grouping']);
$named_grouping_data['Type'] = $grouping_data[0];
if (!in_array($named_grouping_data['Type'], $skip_types)) {
$named_grouping_data['OrderItemId'] = $grouping_data[1];
$named_grouping_data['ProductId'] = $grouping_data[2];
$named_grouping_data['PackageNum'] = $grouping_data[3];
}
else {
$named_grouping_data['PackageNum'] = $grouping_data[2];
}
if ($named_grouping_data['Type'] == PRODUCT_TYPE_TANGIBLE) {
$sub_order->SetDBField('ShippingCost', getArrayValue( unserialize($order->GetDBField('ShippingInfo')), $sub_order_data['PackageNum'], 'TotalCost') );
$sub_order->SetDBField('InsuranceFee', getArrayValue( unserialize($order->GetDBField('ShippingInfo')), $sub_order_data['PackageNum'], 'InsuranceFee') );
$sub_order->SetDBField('ShippingInfo', serialize(Array(1 => getArrayValue( unserialize($order->GetDBField('ShippingInfo')), $sub_order_data['PackageNum']))));
}
else {
$sub_order->SetDBField('ShippingCost', 0);
$sub_order->SetDBField('InsuranceFee', 0);
$sub_order->SetDBField('ShippingInfo', ''); //otherwise orders w/o shipping wills still have shipping info!
}
$amount_percent = $sub_order->getTotalAmount() * 100 / $order->getTotalAmount();
// proportional affiliate commission splitting
if ($order->GetDBField('AffiliateCommission') > 0) {
$sub_order->SetDBField('AffiliateCommission', $order->GetDBField('AffiliateCommission') * $amount_percent / 100 );
}
$amount_percent = ($sub_order->GetDBField('SubTotal') + $sub_order->GetDBField('ShippingCost')) * 100 / ($order->GetDBField('SubTotal') + $order->GetDBField('ShippingCost'));
if ($order->GetDBField('ProcessingFee') > 0) {
$sub_order->SetDBField('ProcessingFee', round($order->GetDBField('ProcessingFee') * $amount_percent / 100, 2));
}
$sub_order->RecalculateTax();
$original_amount = $sub_order->GetDBField('SubTotal') + $sub_order->GetDBField('ShippingCost') + $sub_order->GetDBField('VAT') + $sub_order->GetDBField('ProcessingFee') + $sub_order->GetDBField('InsuranceFee') - $sub_order->GetDBField('GiftCertificateDiscount');
$sub_order->SetDBField('OriginalAmount', $original_amount);
if ($named_grouping_data['Type'] == 1 && ($sub_order_data['BackOrderFlag'] > 0
||
($sub_order_data['TotalItems'] != $sub_order_data['TotalReserved'])) ) {
$sub_order->SetDBField('Status', ORDER_STATUS_BACKORDERS);
if ($event->Special != 'recurring') { // just in case if admin uses tangible backordered products in recurring orders
$email_event_user =& $this->Application->EmailEventUser('BACKORDER.ADD', $sub_order->GetDBField('PortalUserId'), $this->OrderEmailParams($sub_order));
$email_event_admin =& $this->Application->EmailEventAdmin('BACKORDER.ADD');
}
}
else {
switch ($named_grouping_data['Type']) {
case PRODUCT_TYPE_DOWNLOADABLE:
$sql = 'SELECT oi.*
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE (OrderId = %s) AND (p.Type = '.PRODUCT_TYPE_DOWNLOADABLE.')';
$downl_products = $this->Conn->Query( sprintf($sql, $ord_id) );
$product_ids = Array();
foreach ($downl_products as $downl_product) {
$this->raiseProductEvent('Approve', $downl_product['ProductId'], $downl_product, $next_sub_number);
$product_ids[] = $downl_product['ProductId'];
}
break;
case PRODUCT_TYPE_TANGIBLE:
$sql = 'SELECT '.$backorder_select.', oi.*
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE (OrderId = %s) AND (BackOrderFlag = 0) AND (p.Type = '.PRODUCT_TYPE_TANGIBLE.')';
$products = $this->Conn->Query( sprintf($sql, $ord_id) );
foreach ($products as $product) {
$this->raiseProductEvent('Approve', $product['ProductId'], $product, $next_sub_number);
}
break;
default:
$order_item_fields = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'OrderItems WHERE OrderItemId = '.$named_grouping_data['OrderItemId']);
$this->raiseProductEvent('Approve', $named_grouping_data['ProductId'], $order_item_fields, $next_sub_number);
break;
}
$sub_order->SetDBField('Status', $named_grouping_data['Type'] == PRODUCT_TYPE_TANGIBLE ? ORDER_STATUS_TOSHIP : ORDER_STATUS_PROCESSED);
}
if ($next_sub_number == $first_sub_number) {
$sub_order->SetId($order->GetId());
$sub_order->Update();
}
else {
$sub_order->Create();
}
switch ($named_grouping_data['Type']) {
case PRODUCT_TYPE_TANGIBLE:
$query = 'UPDATE '.$table_prefix.'OrderItems SET OrderId = %s WHERE OrderId = %s AND PackageNum = %s';
$query = sprintf($query, $sub_order->GetId(), $ord_id, $sub_order_data['PackageNum']);
break;
case PRODUCT_TYPE_DOWNLOADABLE:
$query = 'UPDATE '.$table_prefix.'OrderItems SET OrderId = %s WHERE OrderId = %s AND ProductId IN (%s)';
$query = sprintf($query, $sub_order->GetId(), $ord_id, implode(',', $product_ids) );
break;
default:
$query = 'UPDATE '.$table_prefix.'OrderItems SET OrderId = %s WHERE OrderId = %s AND OrderItemId = %s';
$query = sprintf($query, $sub_order->GetId(), $ord_id, $named_grouping_data['OrderItemId']);
break;
}
$this->Conn->Query($query);
if ($order_has_gift) {
// gift certificate can be applied only after items are assigned to suborder
$sub_order->RecalculateGift($event);
$original_amount = $sub_order->GetDBField('SubTotal') + $sub_order->GetDBField('ShippingCost') + $sub_order->GetDBField('VAT') + $sub_order->GetDBField('ProcessingFee') + $sub_order->GetDBField('InsuranceFee') - $sub_order->GetDBField('GiftCertificateDiscount');
$sub_order->SetDBField('OriginalAmount', $original_amount);
$sub_order->Update();
}
$processed_sub_orders[] = $sub_order->GetID();
$next_sub_number++;
$group++;
}
foreach ($processed_sub_orders as $sub_id) {
// update DiscountTotal field
$sql = 'SELECT SUM(ROUND(FlatPrice-Price,2)*Quantity) FROM '.$table_prefix.'OrderItems WHERE OrderId = '.$sub_id;
$discount_total = $this->Conn->GetOne($sql);
$sql = 'UPDATE '.$sub_order->TableName.'
SET DiscountTotal = '.$this->Conn->qstr($discount_total).'
WHERE OrderId = '.$sub_id;
$this->Conn->Query($sql);
}
}
/**
* Call products linked event when spefcfic action is made to product in order
*
* @param string $event_type type of event to get from product ProcessingData = {Approve,Deny,CompleteOrder}
* @param int $product_id ID of product to gather processing data from
* @param Array $order_item_fields OrderItems table record fields (with needed product & order in it)
*/
function raiseProductEvent($event_type, $product_id, $order_item_fields, $next_sub_number=null)
{
$sql = 'SELECT ProcessingData
FROM '.TABLE_PREFIX.'Products
WHERE ProductId = '.$product_id;
$processing_data = $this->Conn->GetOne($sql);
if ($processing_data) {
$processing_data = unserialize($processing_data);
$event_key = getArrayValue($processing_data, $event_type.'Event');
// if requested type of event is defined for product, only then process it
if ($event_key) {
$event = new kEvent($event_key);
$event->setEventParam('field_values', $order_item_fields);
$event->setEventParam('next_sub_number', $next_sub_number);
$this->Application->HandleEvent($event);
}
}
}
/**
* Updates product info in shopping cart
*
* @param kEvent $event
* @param unknown_type $prod_id
* @param unknown_type $back_order
* @param unknown_type $qty
* @param unknown_type $price
* @param unknown_type $discounted_price
* @param unknown_type $discount_type
* @param unknown_type $discount_id
* @param unknown_type $order_item_id
* @param unknown_type $options_salt
* @param unknown_type $passed_item_data
* @param unknown_type $cost
* @return unknown
*/
function UpdateOrderItem(&$event, $prod_id, $back_order, $qty, $price, $discounted_price, $discount_type, $discount_id, $order_item_id = 0, $options_salt = 0, $passed_item_data=null, $cost=0)
{
$price = (float) $price;
$discounted_price = (float) $discounted_price;
$qty = (int) $qty;
$ord_id = $this->getPassedId($event);
$table_prefix = $this->TablePrefix($event);
if($order_item_id)
{
$query = ' SELECT OrderItemId, Quantity, FlatPrice, Price, BackOrderFlag, ItemData FROM '.$table_prefix.'OrderItems
WHERE OrderItemId = '.$order_item_id;
}
else
{
// try to load specified Product by its Id and BackOrderFlag in the order
$query = 'SELECT OrderItemId, Quantity, FlatPrice, Price, BackOrderFlag, ItemData FROM '.$table_prefix.'OrderItems
WHERE
OrderId = '.$ord_id.'
AND
ProductId = '.$prod_id.'
AND
BackOrderFlag '.($back_order ? ' >= 1' : ' = 0').'
AND
OptionsSalt = '.$options_salt;
}
$item_row = $this->Conn->GetRow($query);
$item_id = $item_row['OrderItemId'];
$object =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
$item_data = $item_row['ItemData'];
if($item_data)
{
$item_data = unserialize($item_data);
}
$orig_discount_type = (int)getArrayValue($item_data, 'DiscountType');
$orig_discount_id = (int)getArrayValue($item_data, 'DiscountId');
if ($item_id) { // if Product already exists in the order
if ($qty > 0 &&
$item_row['Quantity'] == $qty &&
round($item_row['FlatPrice'], 3) == round($price, 3) &&
round($item_row['Price'], 3) == round($discounted_price, 3) &&
$orig_discount_type == $discount_type &&
$orig_discount_id == $discount_id)
{
return false;
}
$object->Load($item_id);
if ($qty > 0) { // Update Price by _TOTAL_ qty
$object->SetDBField('Quantity', $qty);
$object->SetDBField('FlatPrice', $price );
$object->SetDBField('Price', $discounted_price );
$object->SetDBField('Cost', $cost);
if($item_data = $object->GetDBField('ItemData'))
{
$item_data = unserialize($item_data);
}
else
{
$item_data = Array();
}
$item_data['DiscountType'] = $discount_type;
$item_data['DiscountId'] = $discount_id;
$object->SetDBField('ItemData', serialize($item_data));
$object->Update();
}
else { // delete products with 0 qty
$object->Delete();
}
}
elseif ($qty > 0) { // if we are adding product
$product =& $this->Application->recallObject('p');
$product->Load($prod_id);
$object->SetDBField('ProductId', $prod_id);
$object->SetDBField('ProductName', $product->GetField('Name'));
$object->SetDBField('Quantity', $qty);
$object->SetDBField('FlatPrice', $price );
$object->SetDBField('Price', $discounted_price );
$object->SetDBField('Cost', $cost);
$object->SetDBField('OrderId', $ord_id);
$object->SetDBField('BackOrderFlag', $back_order);
if ($passed_item_data && !is_array($passed_item_data)) {
$passed_item_data = unserialize($passed_item_data);
}
// $item_data = Array('DiscountType' => $discount_type, 'DiscountId' => $discount_id);
$item_data = $passed_item_data;
$object->SetDBField('ItemData', serialize($item_data));
$object->Create();
if( $this->UseTempTables($event) ) $object->SetTempId();
}
else {
return false; // item requiring to set qty to 0, meaning already does not exist
}
return true;
}
function OptionsSalt($options, $comb_only=false)
{
$helper =& $this->Application->recallObject('kProductOptionsHelper');
return $helper->OptionsSalt($options, $comb_only);
}
/**
* Enter description here...
*
* @param kEvent $event
* @param int $item_id
*/
function AddItemToOrder(&$event, $item_id, $qty = null, $package_num = null)
{
if (!isset($qty)) {
$qty = 1;
}
// Loading product to add
$product =& $this->Application->recallObject('p.toadd', null, Array('skip_autoload' => true));
/* @var $product kDBItem */
$product->Load($item_id);
$object =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
/* @var $object kDBItem */
$order =& $this->Application->recallObject('ord');
/* @var $order kDBItem */
if (!$order->isLoaded() && !$this->Application->isAdmin) {
// no order was created before -> create one now
if ($this->_createNewCart($event)) {
$this->LoadItem($event);
}
}
if (!$order->isLoaded()) {
// was unable to create new order
return false;
}
$ord_id = $order->GetID();
if ($item_data = $event->getEventParam('ItemData')) {
$item_data = unserialize($item_data);
}
else {
$item_data = Array ();
}
$options = getArrayValue($item_data, 'Options');
if (!$this->CheckOptions($event, $options, $item_id, $qty, $product->GetDBField('OptionsSelectionMode'))) return;
// Checking if such product already exists in the cart
$keys['OrderId'] = $ord_id;
$keys['ProductId'] = $product->GetId();
if (isset($item_data['Options'])) {
$options_salt = $this->OptionsSalt($item_data['Options']);
$keys['OptionsSalt'] = $options_salt;
}
else {
$options_salt = null;
}
$exists = $object->Load($keys);
$object->SetDBField('ProductId', $product->GetId());
$object->SetDBField('ProductName', $product->GetField('l'.$this->Application->GetDefaultLanguageId().'_Name'));
$object->SetDBField('Weight', $product->GetDBField('Weight'));
if (isset($item_data['Options'])) {
$object->SetDBField('OptionsSalt', $options_salt);
}
if (isset($package_num)) {
$object->SetDBField('PackageNum', $package_num);
}
if($product->GetDBField('Type') == PRODUCT_TYPE_TANGIBLE || $product->GetDBField('Type') == 6)
{
$object->SetDBField('Quantity', $object->GetDBField('Quantity') + $qty);
}
else // Types: 2,3,4
{
$object->SetDBField('Quantity', $qty); // 1
$exists = false;
}
if (isset($item_data['ForcePrice'])) {
$price = $item_data['ForcePrice'];
}
else {
$price = $this->GetPlainProductPrice($product->GetId(), $object->GetDBField('Quantity'), $product->GetDBField('Type'), $order, $options_salt, $item_data);
}
$cost = $this->GetProductCost($product->GetId(), $object->GetDBField('Quantity'), $product->GetDBField('Type'), $options_salt, $item_data);
$object->SetDBField('FlatPrice', $price);
$couponed_price = $this->GetCouponDiscountedPrice($order->GetDBField('CouponId'), $product->GetId(), $price);
$discounted_price = $this->GetDiscountedProductPrice($product->GetId(), $price, $discount_id, $order);
if( $couponed_price < $discounted_price )
{
$discounted_price = $couponed_price;
$discount_type = 'coupon';
$discount_id = $order->GetDBField('CouponId');
}
else
{
$discount_type = 'discount';
$discount_id = $discount_id;
}
$item_data['DiscountType'] = $discount_type;
$item_data['DiscountId'] = $discount_id;
$item_data['IsRecurringBilling'] = $product->GetDBField('IsRecurringBilling');
// it item is processed in order using new style, then put such mark in orderitem record
$processing_data = $product->GetDBField('ProcessingData');
if ($processing_data) {
$processing_data = unserialize($processing_data);
if (getArrayValue($processing_data, 'HasNewProcessing')) {
$item_data['HasNewProcessing'] = 1;
}
}
$object->SetDBField('ItemData', serialize($item_data));
$object->SetDBField('Price', $discounted_price); // will be retrieved later
$object->SetDBField('Cost', $cost);
$object->SetDBField('BackOrderFlag', 0); // it will be updated in OnRecalculateItems later if needed
$object->SetDBField('OrderId', $ord_id);
if ($exists) {
if ($qty > 0) {
$object->Update();
}
else {
$object->Delete();
}
}
else {
$object->Create();
if ($this->UseTempTables($event)) {
$object->setTempID();
}
}
$this->Application->HandleEvent($ord_event, 'ord:OnRecalculateItems');
/*if ($ord_event->getEventParam('RecalculateChangedCart') && !$this->Application->isAdmin) {
$event->SetRedirectParam('checkout_error', $ord_event->redirect_params['checkout_error']);
}*/
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function UpdateShippingTotal(&$event)
{
if ($this->Application->GetVar('ebay_notification') == 1) {
// TODO: get rid of this "if"
return ;
}
$object =& $event->getObject();
$ord_id = $object->GetId();
$shipping_option = $object->GetDBField('ShippingOption');
$backorder_select = $shipping_option == 0 ? '0 As BackOrderFlag' : 'BackOrderFlag';
$table_prefix = $this->TablePrefix($event);
$shipping_info = $object->GetDBField('ShippingInfo') ? unserialize( $object->GetDBField('ShippingInfo') ) : false;
$shipping_total = 0;
$insurance_fee = 0;
if( is_array($shipping_info) )
{
foreach ($shipping_info as $a_shipping)
{
// $id_elements = explode('_', $a_shipping['ShippingTypeId']);
$shipping_total += $a_shipping['TotalCost'];
$insurance_fee += $a_shipping['InsuranceFee'];
}
}
$object->SetDBField('ShippingCost', $shipping_total);
$object->SetDBField('InsuranceFee', $insurance_fee);
// no need to update, it will be called in calling method
$this->RecalculateTax($event);
}
/**
* Recompile shopping cart, splitting or grouping orders and backorders depending on total quantityes.
* First it counts total qty for each ProductId, and then creates order for available items
* and backorder for others. It also updates the sub-total for the order
*
* @param kEvent $event
* @return bool Returns true if items splitting/grouping were changed
*/
function OnRecalculateItems(&$event)
{
if (is_object($event->MasterEvent) && ($event->MasterEvent->status != erSUCCESS)) {
// e.g. master order update failed, don't recalculate order products
return ;
}
if($checkout_error = $this->Application->GetVar('set_checkout_error'))
{
$event->SetRedirectParam('checkout_error', $checkout_error);
}
$order =& $event->getObject();
/* @var $order OrdersItem */
if ( !$order->isLoaded() ) {
$this->LoadItem($event); // try to load
}
$ord_id = (int)$order->GetID();
if ( !$order->isLoaded() ) return; //order has not been created yet
if( $order->GetDBField('Status') != ORDER_STATUS_INCOMPLETE )
{
return;
}
$table_prefix = $this->TablePrefix($event);
// process only tangible products here
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' SELECT oi.ProductId, oi.OptionsSalt, oi.ItemData, SUM(oi.Quantity) AS Quantity,
IF(p.InventoryStatus = 2, poc.QtyInStock, p.QtyInStock) AS QtyInStock,
p.QtyInStockMin, p.BackOrder, p.InventoryStatus
FROM '.$table_prefix.'OrderItems AS oi
LEFT JOIN '.TABLE_PREFIX.'Products AS p ON oi.ProductId = p.ProductId
LEFT JOIN '.$poc_table.' poc ON (poc.CombinationCRC = oi.OptionsSalt) AND (oi.ProductId = poc.ProductId)
WHERE (oi.OrderId = '.$ord_id.') AND (p.Type = 1)
GROUP BY oi.ProductId, OptionsSalt';
$items = $this->Conn->Query($query);
$result = false;
$cost_total = 0;
$sub_total = 0;
$sub_total_flat = 0;
$coupon_discount = 0;
$pending_operations = Array();
$backordering = $this->Application->ConfigValue('Comm_Enable_Backordering');
$coupon_id = $order->GetDBField('CouponId');
foreach ($items as $row) {
$a_item_data = isset($row['ItemData']) ? unserialize($row['ItemData']) : Array();
$min_qty = $this->GetMinQty($row['ProductId']);
if ($row['Quantity'] > 0 && $row['Quantity'] < $min_qty) {
$row['Quantity'] = $min_qty;
$event->SetRedirectParam('checkout_error', 6);
}
$back_order = 0;
$to_order = 0;
if (!$row['InventoryStatus']) {
$available = $row['Quantity']*2; // always available;
}
else {
// if there are not enough qty AND backorder is auto or backorder is always
$available = $row['QtyInStock'] - $row['QtyInStockMin'];
$available = max(0, $available); // just in case
}
if (
$backordering && // backordering generally enabled
(
($row['Quantity'] > $available)
&&
($row['BackOrder'] == 2) //auto
)
||
$row['BackOrder'] == 1 // always
)
{ // split order into order & backorder
if ($row['BackOrder'] == 1) { //Always backorder
$available = 0;
$to_order = 0;
$back_order = $row['Quantity'];
}
else { //Auto
$to_order = $available;
$back_order = $row['Quantity'] - $available;
}
if (isset($a_item_data['ForcePrice'])) {
$price = $a_item_data['ForcePrice'];
}
else {
$price = $this->GetPlainProductPrice( $row['ProductId'], $to_order + $back_order, 1, $order, $row['OptionsSalt'], $row['ItemData'] );
}
$cost = $this->GetProductCost( $row['ProductId'], $to_order + $back_order, 1, $row['OptionsSalt'], $row['ItemData'] );
$discounted_price = $this->GetDiscountedProductPrice( $row['ProductId'], $price, $discount_id, $order );
$couponed_price = $this->GetCouponDiscountedPrice( $coupon_id, $row['ProductId'], $price );
if($couponed_price < $discounted_price)
{
$discounted_price = $couponed_price;
$coupon_discount += ($price - $couponed_price) * ($to_order + $back_order);
$discount_type = 'coupon';
$discount_id = $coupon_id;
}
else
{
$discount_type = 'discount';
}
$pending_operations[] = Array( $row['ProductId'], 0, $to_order, $price, $discounted_price, $discount_type, $discount_id, 0, $row['OptionsSalt'], $row['ItemData'], $cost );
$pending_operations[] = Array( $row['ProductId'], 1, $back_order, $price, $discounted_price, $discount_type, $discount_id, 0, $row['OptionsSalt'], $row['ItemData'], $cost);
}
else { // store as normal order (and remove backorder)
// we could get here with backorder=never then we should order only what's available
$to_order = min($row['Quantity'], $available);
if (isset($a_item_data['ForcePrice'])) {
$price = $a_item_data['ForcePrice'];
}
else {
$price = $this->GetPlainProductPrice( $row['ProductId'], $to_order + $back_order, 1, $order, $row['OptionsSalt'], $row['ItemData'] );
}
$cost = $this->GetProductCost( $row['ProductId'], $to_order + $back_order, 1, $row['OptionsSalt'], $row['ItemData'] );
$discounted_price = $this->GetDiscountedProductPrice( $row['ProductId'], $price, $discount_id, $order );
$couponed_price = $this->GetCouponDiscountedPrice( $coupon_id, $row['ProductId'], $price );
if($couponed_price < $discounted_price)
{
$discounted_price = $couponed_price;
$coupon_discount += ($price - $couponed_price) * ($to_order + $back_order);
$discount_type = 'coupon';
$discount_id = $coupon_id;
}
else
{
$discount_type = 'discount';
}
$pending_operations[] = Array( $row['ProductId'], 0, $to_order, $price, $discounted_price, $discount_type, $discount_id, 0, $row['OptionsSalt'], $row['ItemData'], $cost );
$pending_operations[] = Array( $row['ProductId'], 1, 0, $price, $discounted_price, $discount_type, $discount_id, 0, $row['OptionsSalt'], $row['ItemData'], $cost ); // this removes backorders
if ($to_order < $row['Quantity']) { // has changed
if ($to_order > 0) {
$event->SetRedirectParam('checkout_error', 2);
}
else {
$event->SetRedirectParam('checkout_error', 3);
}
$result = true;
}
}
$sub_total_flat += ($to_order + $back_order) * $price;
$sub_total += ($to_order + $back_order) * $discounted_price;
$cost_total += ($to_order + $back_order) * $cost;
}
// process subscriptions, services and downloadable: begin
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' SELECT oi.OrderItemId, oi.ProductId, oi.Quantity, oi.OptionsSalt, oi.ItemData,
IF(p.InventoryStatus = 2, poc.QtyInStock, p.QtyInStock) AS QtyInStock,
p.QtyInStockMin, p.BackOrder, p.InventoryStatus, p.Type
FROM '.$table_prefix.'OrderItems AS oi
LEFT JOIN '.TABLE_PREFIX.'Products AS p ON oi.ProductId = p.ProductId
LEFT JOIN '.$poc_table.' poc ON (poc.CombinationCRC = oi.OptionsSalt) AND (oi.ProductId = poc.ProductId)
WHERE (oi.OrderId = '.$ord_id.') AND (p.Type IN (2,3,4,5,6))';
$items = $this->Conn->Query($query);
foreach ($items as $row)
{
$a_item_data = isset($row['ItemData']) ? unserialize($row['ItemData']) : Array();
if (isset($a_item_data['ForcePrice'])) {
$price = $a_item_data['ForcePrice'];
}
else {
$price = $this->GetPlainProductPrice( $row['ProductId'], $row['Quantity'], $row['Type'], $order, $row['OptionsSalt'], $row['ItemData'] );
}
$cost = $this->GetProductCost( $row['ProductId'], $row['Quantity'], $row['Type'], $row['OptionsSalt'], $row['ItemData'] );
$discounted_price = $this->GetDiscountedProductPrice( $row['ProductId'], $price, $discount_id, $order );
$couponed_price = $this->GetCouponDiscountedPrice( $coupon_id, $row['ProductId'], $price );
if($couponed_price < $discounted_price)
{
$discounted_price = $couponed_price;
$coupon_discount += ($price - $couponed_price);
$discount_type = 'coupon';
$discount_id = $coupon_id;
}
else
{
$discount_type = 'discount';
}
$pending_operations[] = Array( $row['ProductId'], 0, $row['Quantity'], $price, $discounted_price, $discount_type, $discount_id, $row['OrderItemId'], 0, $row['ItemData'], $cost );
$sub_total_flat += $price * $row['Quantity'];
$sub_total += $discounted_price * $row['Quantity'];
$cost_total += $cost * $row['Quantity'];
}
// process subscriptions, services and downloadable: end
$flat_discount = $this->GetWholeOrderPlainDiscount($global_discount_id, $order);
$flat_discount = ($flat_discount < $sub_total_flat) ? $flat_discount : $sub_total_flat;
$coupon_flat_discount = $this->GetWholeOrderCouponDiscount($coupon_id);
$coupon_flat_discount = ($coupon_flat_discount < $sub_total_flat) ? $coupon_flat_discount : $sub_total_flat;
if($coupon_flat_discount && $coupon_flat_discount > $flat_discount)
{
$flat_discount = $coupon_flat_discount;
$global_discount_type = 'coupon';
$global_discount_id = $coupon_id;
}
else
{
$global_discount_type = 'discount';
}
if($sub_total_flat - $sub_total < $flat_discount)
{
$coupon_discount = ($flat_discount == $coupon_flat_discount) ? $flat_discount : 0;
$sub_total = $sub_total_flat - $flat_discount;
foreach ($pending_operations as $operation_row)
{
list($product_id, $backorder, $qty, $price, $discounted_price, $dummy, $dummy, $order_item_id, $options_salt, $item_data, $cost) = $operation_row;
$new_price = ($price / $sub_total_flat) * $sub_total;
$result = $this->UpdateOrderItem($event, $product_id, $backorder, $qty, $price, $new_price, $global_discount_type, $global_discount_id, $order_item_id, $options_salt, $item_data, $cost) || $result;
}
}
else
{
foreach ($pending_operations as $operation_row)
{
list($product_id, $backorder, $qty, $price, $discounted_price, $discount_type, $discount_id, $order_item_id, $options_salt, $item_data, $cost) = $operation_row;
$result = $this->UpdateOrderItem($event, $product_id, $backorder, $qty, $price, $discounted_price, $discount_type, $discount_id, $order_item_id, $options_salt, $item_data, $cost) || $result;
}
}
$order->SetDBField('SubTotal', $sub_total);
$order->SetDBField('CostTotal', $cost_total);
// $this->CalculateDiscount($event);
$order->SetDBField('DiscountTotal', $sub_total_flat - $sub_total);
if($coupon_id && $coupon_discount == 0)
{
$this->RemoveCoupon($order);
$event->SetRedirectParam('checkout_error', 8);
}
$order->SetDBField('CouponDiscount', $coupon_discount);
if ($result) $this->UpdateShippingOption($event);
$this->UpdateShippingTotal($event);
$this->RecalculateProcessingFee($event);
$this->RecalculateTax($event);
$this->RecalculateGift($event);
if ($event->Name != 'OnAfterItemUpdate') $order->Update();
$event->setEventParam('RecalculateChangedCart', $result);
if (is_object($event->MasterEvent)) {
$event->MasterEvent->setEventParam('RecalculateChangedCart', $result);
}
if ($result && !getArrayValue($event->redirect_params, 'checkout_error')) {
$event->SetRedirectParam('checkout_error', 1);
}
if ($result && is_object($event->MasterEvent) && $event->MasterEvent->Name == 'OnUserLogin')
{
if( ($shop_cart_template = $this->Application->GetVar('shop_cart_template'))
&& is_object($event->MasterEvent->MasterEvent) )
{
$event->MasterEvent->MasterEvent->SetRedirectParam('checkout_error', 9);
$event->MasterEvent->MasterEvent->redirect = $shop_cart_template;
}
}
return $result;
}
/* function GetShippingCost($user_country_id, $user_state_id, $user_zip, $weight, $items, $amount, $shipping_type)
{
$this->Application->recallObject('ShippingQuoteEngine');
$shipping_h =& $this->Application->recallObject('CustomShippingQuoteEngine');
$query = $shipping_h->QueryShippingCost($user_country_id, $user_state_id, $user_zip, $weight, $items, $amount, $shipping_type);
$cost = $this->Conn->GetRow($query);
return $cost['TotalCost'];
}*/
function GetMinQty($p_id)
{
$query = 'SELECT
MIN(pp.MinQty)
FROM '.TABLE_PREFIX.'ProductsPricing AS pp
WHERE pp.ProductId = '.$p_id;
$min_qty = $this->Conn->GetOne($query);
if (!$min_qty) return 1;
return $min_qty;
}
/**
* Return product cost for given qty, taking no discounts into account
*
* @param int $p_id ProductId
* @param int $qty Quantity
* @return float
*/
function GetProductCost($p_id, $qty, $product_type, $options_salt=null, $item_data=null)
{
$user_groups = $this->Application->RecallVar('UserGroups');
if($product_type == 1)
{
// $where_clause = 'pp.ProductId = '.$p_id.' AND pp.MinQty <= '.$qty;
// $orderby_clause = 'ORDER BY ('.$qty.' - pp.MinQty) ASC';
$where_clause = 'GroupId IN ('.$user_groups.') AND pp.ProductId = '.$p_id.' AND pp.MinQty <= '.$qty.' AND ('.$qty.' < pp.MaxQty OR pp.MaxQty=-1)';
$orderby_clause = 'ORDER BY pp.Price ASC';
}
else
{
$price_id = $this->GetPricingId($p_id, $item_data);
$where_clause = 'pp.ProductId = '.$p_id.' AND pp.PriceId = '.$price_id;
$orderby_clause = '';
}
$sql = 'SELECT Cost
FROM '.TABLE_PREFIX.'ProductsPricing AS pp
LEFT JOIN '.TABLE_PREFIX.'Products AS p
ON p.ProductId = pp.ProductId
WHERE '.$where_clause.'
'.$orderby_clause;
// GROUP BY pp.ProductId - removed, this it qty pricing is caclucated incorrectly !!!
$cost = $this->Conn->GetOne($sql);
if (!$cost) $price = 0;
return $cost;
}
/**
* Return product price for given qty, taking no discounts into account
*
* @param int $p_id ProductId
* @param int $qty Quantity
* @return float
*/
function GetPlainProductPrice($p_id, $qty, $product_type, &$order_object, $options_salt=null, $item_data=null)
{
$user_id = $order_object->GetDBField('PortalUserId');
$user_groups = $this->Application->getUserGroups($user_id);
if($product_type == 1)
{
// $where_clause = 'pp.ProductId = '.$p_id.' AND pp.MinQty <= '.$qty;
// $orderby_clause = 'ORDER BY ('.$qty.' - pp.MinQty) ASC';
$where_clause = 'GroupId IN ('.$user_groups.') AND pp.ProductId = '.$p_id.' AND pp.MinQty <= '.$qty.' AND ('.$qty.' < pp.MaxQty OR pp.MaxQty=-1)';
// if we have to stick ti primary group this order by clause force its pricing to go first,
// but if there is no pricing for primary group it will take next optimal
if ($this->Application->ConfigValue('Comm_PriceBracketCalculation') == 1){
if ($user_id <= 0) {
$primary_group = $this->Application->ConfigValue('User_LoggedInGroup'); // actually this is Everyone
}
else {
$primary_group = $this->Conn->GetOne('SELECT GroupId FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId='.$user_id.' AND PrimaryGroup=1');
}
$orderby_clause = 'ORDER BY (IF(GroupId='.$primary_group.',1,2)) ASC, pp.Price ASC';
}
else {
$orderby_clause = 'ORDER BY pp.Price ASC';
}
}
else
{
$price_id = $this->GetPricingId($p_id, $item_data);
$where_clause = 'pp.ProductId = '.$p_id.' AND pp.PriceId = '.$price_id;
$orderby_clause = '';
}
$sql = 'SELECT Price
FROM '.TABLE_PREFIX.'ProductsPricing AS pp
LEFT JOIN '.TABLE_PREFIX.'Products AS p
ON p.ProductId = pp.ProductId
WHERE '.$where_clause.'
'.$orderby_clause;
// GROUP BY pp.ProductId - removed, this it qty pricing is caclucated incorrectly !!!
$price = $this->Conn->GetOne($sql);
if (!$price) $price = 0;
if (isset($item_data) && !is_array($item_data)) {
$item_data = unserialize($item_data);
}
if (isset($item_data['Options'])) {
$addtion = 0;
$opt_helper =& $this->Application->recallObject('kProductOptionsHelper');
foreach ($item_data['Options'] as $opt => $val) {
$data = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'ProductOptions WHERE ProductOptionId = '.$opt);
$parsed = $opt_helper->ExplodeOptionValues($data);
if (!$parsed) continue;
$conv_prices = $parsed['Prices'];
$conv_price_types = $parsed['PriceTypes'];
if (is_array($val)) {
foreach ($val as $a_val) {
if (isset($conv_prices[unhtmlentities($a_val)]) && $conv_prices[unhtmlentities($a_val)]) {
if ($conv_price_types[unhtmlentities($a_val)] == '$') {
$addtion += $conv_prices[unhtmlentities($a_val)];
}
elseif ($conv_price_types[unhtmlentities($a_val)] == '%') {
$addtion += $price * $conv_prices[unhtmlentities($a_val)] / 100;
}
}
}
}
else {
if (isset($conv_prices[unhtmlentities($val)]) && $conv_prices[unhtmlentities($val)]) {
if ($conv_price_types[unhtmlentities($val)] == '$') {
$addtion += $conv_prices[unhtmlentities($val)];
}
elseif ($conv_price_types[unhtmlentities($val)] == '%') {
$addtion += $price * $conv_prices[unhtmlentities($val)] / 100;
}
}
}
}
$price += $addtion;
}
$comb_salt = $this->OptionsSalt( getArrayValue($item_data, 'Options'), 1);
if ($comb_salt) {
$query = 'SELECT * FROM '.TABLE_PREFIX.'ProductOptionCombinations WHERE CombinationCRC = '.$comb_salt;
$comb = $this->Conn->GetRow($query);
if ($comb) {
switch ($comb['PriceType']) {
case 1: // = override
$price = $comb['Price'];
break;
case 2: // flat
$price = $price + $comb['Price'];
break;
case 3: // percent
$price = $price * (1 + $comb['Price'] / 100);
break;
}
}
}
return max($price, 0);
}
/**
* Return product price for given qty, taking possible discounts into account
*
* @param int $p_id ProductId
* @param int $qty Quantity
* @return float
*/
function GetDiscountedProductPrice($p_id, $price, &$discount_id, &$order_object)
{
$discount_id = 0;
$user_id = $order_object->GetDBField('PortalUserId');
$user_groups = $this->Application->getUserGroups($user_id);
$sql = '
SELECT
IF(pd.Type = 1,
'.$price.' - pd.Amount,
IF(pd.Type = 2,
('.$price.' * (1-pd.Amount/100)),
'.$price.'
)
) AS DiscountedPrice,
pd.DiscountId
FROM '.TABLE_PREFIX.'Products AS p
LEFT JOIN '.TABLE_PREFIX.'ProductsDiscountItems AS pdi ON
pdi.ItemResourceId = p.ResourceId OR pdi.ItemType = 0
LEFT JOIN '.TABLE_PREFIX.'ProductsDiscounts AS pd ON
pd.DiscountId = pdi.DiscountId
AND
(pdi.ItemType = 1 OR (pdi.ItemType = 0 AND pd.Type = 2))
AND
pd.Status = 1
AND
( pd.GroupId IN ('.$user_groups.') AND
( (pd.Start IS NULL OR pd.Start < UNIX_TIMESTAMP())
AND
(pd.End IS NULL OR pd.End > UNIX_TIMESTAMP())
)
)
WHERE p.ProductId = '.$p_id.' AND pd.DiscountId IS NOT NULL
';
$pricing = $this->Conn->GetCol($sql, 'DiscountId');
if (!$pricing) return $price;
$discounted_price = min($pricing);
$pricing = array_flip($pricing);
$discount_id = $pricing[$discounted_price];
$discounted_price = min($discounted_price, $price);
return max($discounted_price, 0);
}
function GetCouponDiscountedPrice($coupon_id, $p_id, $price)
{
if(!$coupon_id) return $price;
$sql = '
SELECT
'.$price.' AS Price,
MIN(IF(pc.Type = 1,
'.$price.' - pc.Amount,
IF(pc.Type = 2,
('.$price.' * (1-pc.Amount/100)),
'.$price.'
)
)) AS DiscountedPrice
FROM '.TABLE_PREFIX.'Products AS p
LEFT JOIN '.TABLE_PREFIX.'ProductsCouponItems AS pci ON
pci.ItemResourceId = p.ResourceId OR pci.ItemType = 0
LEFT JOIN '.TABLE_PREFIX.'ProductsCoupons AS pc ON
pc.CouponId = pci.CouponId
AND
(pci.ItemType = 1 OR (pci.ItemType = 0 AND pc.Type = 2))
WHERE p.ProductId = '.$p_id.' AND pci.CouponId = '.$coupon_id.'
GROUP BY p.ProductId
';
$pricing = $this->Conn->GetRow($sql);
if ($pricing === false) return $price;
$price = min($pricing['Price'], $pricing['DiscountedPrice']);
return max($price, 0);
}
function GetWholeOrderPlainDiscount(&$discount_id, &$order_object)
{
$user_id = $order_object->GetDBField('PortalUserId');
$user_groups = $this->Application->getUserGroups($user_id);
$sql = '
SELECT pd.Amount AS Discount, pd.DiscountId
FROM '.TABLE_PREFIX.'ProductsDiscountItems AS pdi
LEFT JOIN '.TABLE_PREFIX.'ProductsDiscounts AS pd
ON
pd.DiscountId = pdi.DiscountId
AND
pdi.ItemType = 0 AND pd.Type = 1
AND
pd.Status = 1
AND
( pd.GroupId IN ('.$user_groups.') AND
( (pd.Start IS NULL OR pd.Start < '.$order_object->GetDBField('OrderDate').')
AND
(pd.End IS NULL OR pd.End > '.$order_object->GetDBField('OrderDate').')
)
)
WHERE pd.DiscountId IS NOT NULL
';
$pricing = $this->Conn->GetCol($sql, 'DiscountId');
if (!$pricing) return 0;
$discounted_price = max($pricing);
$pricing = array_flip($pricing);
$discount_id = $pricing[$discounted_price];
return max($discounted_price, 0);
}
function GetWholeOrderCouponDiscount($coupon_id)
{
if (!$coupon_id) return 0;
$sql = 'SELECT Amount
FROM '.TABLE_PREFIX.'ProductsCouponItems AS pci
LEFT JOIN '.TABLE_PREFIX.'ProductsCoupons AS pc
ON pc.CouponId = pci.CouponId
WHERE pci.CouponId = '.$coupon_id.' AND pci.ItemType = 0 AND pc.Type = 1';
return $this->Conn->GetOne($sql);
}
/**
* Return product pricing id for given product, if not passed - return primary pricing ID
*
* @param int $product_id ProductId
* @return float
*/
function GetPricingId($product_id, $item_data) {
if (!is_array($item_data)) {
$item_data = unserialize($item_data);
}
$price_id = getArrayValue($item_data, 'PricingId');
if (!$price_id) {
$price_id = $this->Application->GetVar('pr_id');
}
if (!$price_id){
$price_id = $this->Conn->GetOne('SELECT PriceId FROM '.TABLE_PREFIX.'ProductsPricing WHERE ProductId='.$product_id.' AND IsPrimary=1');
}
return $price_id;
}
function UpdateShippingOption(&$event)
{
$object =& $event->getObject();
$shipping_option = $object->GetDBField('ShippingOption');
if($shipping_option == '') return;
$table_prefix = $this->TablePrefix($event);
if ($shipping_option == 1 || $shipping_option == 0) { // backorder separately
$query = 'UPDATE '.$table_prefix.'OrderItems SET BackOrderFlag = 1 WHERE OrderId = '.$object->GetId().' AND BackOrderFlag > 1';
$this->Conn->Query($query);
}
if ($shipping_option == 2) {
$query = 'SELECT * FROM '.$table_prefix.'OrderItems WHERE OrderId = '.$object->GetId().' AND BackOrderFlag >= 1 ORDER By ProductName asc';
$items = $this->Conn->Query($query);
$backorder_flag = 2;
foreach ($items as $an_item) {
$query = 'UPDATE '.$table_prefix.'OrderItems SET BackOrderFlag = '.$backorder_flag.' WHERE OrderItemId = '.$an_item['OrderItemId'];
$this->Conn->Query($query);
$backorder_flag++;
}
}
}
function UpdateShippingTypes(&$event)
{
$object =& $this->Application->recallObject($event->getPrefixSpecial());
$ord_id = $object->GetId();
$order_info = $this->Application->GetVar('ord');
$shipping_ids = getArrayValue($order_info, $ord_id, 'ShippingTypeId');
if (!$shipping_ids)
{
return;
}
$last_shippings = unserialize($this->Application->RecallVar('LastShippings'));
$shipping_types = Array();
$ret = true;
foreach($shipping_ids as $package => $id)
{
// try to validate
if ( $object->GetDBField('ShippingType') == 0 && (strpos($id, 'USPS') !== false) && in_array($this->Application->GetVar('t'), Array('in-commerce/checkout/shipping','in-commerce/orders/orders_edit_shipping'))) {
$current_usps_shipping_types = unserialize($this->Application->RecallVar('current_usps_shipping_types'));
$object->SetDBField('ShippingInfo', serialize(Array($package => $current_usps_shipping_types[$id])));
$usps_data = $this->MakeUSPSOrder($object, true);
if ( !isset($usps_data['error_number']) ) {
// update only international shipping
if ( $object->GetDBField('ShippingCountry') != 'USA') {
$last_shippings[$package][$id]['TotalCost'] = $usps_data['Postage'];
}
}
else {
$this->Application->SetVar('usps_errors', $usps_data['error_description']);
$ret = false;
}
$object->SetDBField('ShippingInfo', '');
}
$shipping_types[$package] = $last_shippings[$package][$id];
}
$object->SetDBField('ShippingInfo', serialize($shipping_types));
return $ret;
}
/*function shipOrder(&$order_items)
{
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
$order_item =& $this->Application->recallObject('orditems.-item');
while( !$order_items->EOL() )
{
$rec = $order_items->getCurrentRecord();
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetId($rec['OrderItemId']);
$order_item->SetDBField('QuantityReserved', 0);
$order_item->Update();
$order_items->GoNext();
}
return true;
}*/
function RecalculateTax(&$event)
{
$object =& $event->getObject();
if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) return;
$object->RecalculateTax();
}
function RecalculateProcessingFee(&$event)
{
$object =& $event->getObject();
// Do not reset processing fee while orders are being split (see SplitOrder)
if (preg_match("/^-sub/", $object->Special)) return;
if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) return; //no changes for orders other than incomple or pending
$pt = $object->GetDBField('PaymentType');
$processing_fee = $this->Conn->GetOne('SELECT ProcessingFee FROM '.$this->Application->getUnitOption('pt', 'TableName').' WHERE PaymentTypeId = '.$pt);
$object->SetDBField( 'ProcessingFee', $processing_fee );
$this->UpdateTotals($event);
}
function UpdateTotals(&$event)
{
$object =& $event->getObject();
$object->UpdateTotals();
}
function CalculateDiscount(&$event)
{
$object =& $event->getObject();
$coupon =& $this->Application->recallObject('coup', null, Array('skip_autoload' => true));
if(!$coupon->Load( $object->GetDBField('CouponId'), 'CouponId' ))
{
return false;
}
$sql = 'SELECT Price * Quantity AS Amount, ProductId FROM '.$this->Application->getUnitOption('orditems', 'TableName').'
WHERE OrderId = '.$object->GetDBField('OrderId');
$orditems = $this->Conn->GetCol($sql, 'ProductId');
$sql = 'SELECT coupi.ItemType, p.ProductId FROM '.$this->Application->getUnitOption('coupi', 'TableName').' coupi
LEFT JOIN '.$this->Application->getUnitOption('p', 'TableName').' p
ON coupi.ItemResourceId = p.ResourceId
WHERE CouponId = '.$object->GetDBField('CouponId');
$discounts = $this->Conn->GetCol($sql, 'ProductId');
$discount_amount = 0;
foreach($orditems as $product_id => $amount)
{
if(isset($discounts[$product_id]) || array_search('0', $discounts, true) !== false)
{
switch($coupon->GetDBField('Type'))
{
case 1:
$discount_amount += $coupon->GetDBField('Amount') < $amount ? $coupon->GetDBField('Amount') : $amount;
break;
case 2:
$discount_amount += $amount * $coupon->GetDBField('Amount') / 100;
break;
default:
}
break;
}
}
$object->SetDBField('CouponDiscount', $discount_amount);
return $discount_amount;
}
/**
* Jumps to selected order in order's list from search tab
*
* @param kEvent $event
*/
function OnGoToOrder(&$event)
{
$id = array_shift( $this->StoreSelectedIDs($event) );
$idfield = $this->Application->getUnitOption($event->Prefix,'IDField');
$table = $this->Application->getUnitOption($event->Prefix,'TableName');
$sql = 'SELECT Status FROM %s WHERE %s = %s';
$order_status = $this->Conn->GetOne( sprintf($sql, $table, $idfield, $id) );
$prefix_special = $event->Prefix.'.'.$this->getSpecialByType($order_status);
$orders_list =& $this->Application->recallObject($prefix_special, $event->Prefix.'_List', Array('per_page'=>-1) );
$orders_list->Query();
foreach($orders_list->Records as $row_num => $record)
{
if( $record[$idfield] == $id ) break;
}
$per_page = $this->getPerPage( new kEvent($prefix_special.':OnDummy') );
$page = ceil( ($row_num+1) / $per_page );
$this->Application->StoreVar($prefix_special.'_Page', $page);
$event->redirect = 'in-commerce/orders/orders_'.$this->getSpecialByType($order_status).'_list';
}
/**
* Reset's any selected order state to pending
*
* @param unknown_type $event
*/
function OnResetToPending(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $id => $field_values)
{
$object->Load($id);
$object->SetDBField('Status', ORDER_STATUS_PENDING);
if( $object->Update() )
{
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
break;
}
}
}
}
/**
* Creates list from items selected in grid
*
* @param kEvent $event
*/
function OnLoadSelected(&$event)
{
$event->setPseudoClass('_List');
$object =& $event->getObject( Array('selected_only' => true) );
$event->redirect = false;
}
/**
* Return orders list, that will expire in time specified
*
* @param int $pre_expiration timestamp
* @return Array
*/
function getRecurringOrders($pre_expiration)
{
$ord_table = $this->Application->getUnitOption('ord', 'TableName');
$ord_idfield = $this->Application->getUnitOption('ord', 'IDField');
$processing_allowed = Array(ORDER_STATUS_PROCESSED, ORDER_STATUS_ARCHIVED);
$sql = 'SELECT '.$ord_idfield.', PortalUserId, GroupId, NextCharge
FROM '.$ord_table.'
WHERE (IsRecurringBilling = 1) AND (NextCharge < '.$pre_expiration.') AND Status IN ('.implode(',', $processing_allowed).')';
return $this->Conn->Query($sql, $ord_idfield);
}
/**
* Regular event: checks what orders should expire and renew automatically (if such flag set)
*
* @param kEvent $event
*/
function OnCheckRecurringOrders(&$event)
{
$skip_clause = Array();
$ord_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$ord_idfield = $this->Application->getUnitOption($event->Prefix, 'IDField');
$pre_expiration = adodb_mktime() + $this->Application->ConfigValue('Comm_RecurringChargeInverval') * 3600 * 24;
$to_charge = $this->getRecurringOrders($pre_expiration);
if ($to_charge) {
$order_ids = Array();
foreach ($to_charge as $order_id => $record) {
// skip virtual users (e.g. root, guest, etc.) & invalid subscriptions (with no group specified, no next charge, but Recurring flag set)
if (!$record['PortalUserId'] || !$record['GroupId'] || !$record['NextCharge']) continue;
$order_ids[] = $order_id;
// prevent duplicate user+group pairs
$skip_clause[ 'PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'] ] = $order_id;
}
// process only valid orders
$temp_handler =& $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
$cloned_order_ids = $temp_handler->CloneItems($event->Prefix, 'recurring', $order_ids);
$order =& $this->Application->recallObject($event->Prefix.'.recurring', null, Array('skip_autoload' => true));
foreach ($cloned_order_ids as $order_id) {
$order->Load($order_id);
$this->Application->HandleEvent($complete_event, $event->Prefix.'.recurring:OnCompleteOrder' );
if ($complete_event->status == erSUCCESS) {
//send recurring ok email
$email_event_user =& $this->Application->EmailEventUser('ORDER.RECURRING.PROCESSED', $order->GetDBField('PortalUserId'), $this->OrderEmailParams($order));
$email_event_admin =& $this->Application->EmailEventAdmin('ORDER.RECURRING.PROCESSED');
}
else {
//send Recurring failed event
$order->SetDBField('Status', ORDER_STATUS_DENIED);
$order->Update();
$email_event_user =& $this->Application->EmailEventUser('ORDER.RECURRING.DENIED', $order->GetDBField('PortalUserId'), $this->OrderEmailParams($order));
$email_event_admin =& $this->Application->EmailEventAdmin('ORDER.RECURRING.DENIED');
}
}
// remove recurring flag from all orders found, not to select them next time script runs
$sql = 'UPDATE '.$ord_table.'
SET IsRecurringBilling = 0
WHERE '.$ord_idfield.' IN ('.implode(',', array_keys($to_charge)).')';
$this->Conn->Query($sql);
}
$pre_expiration = adodb_mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24;
$to_charge = $this->getRecurringOrders($pre_expiration);
foreach ($to_charge as $order_id => $record) {
// skip virtual users (e.g. root, guest, etc.) & invalid subscriptions (with no group specified, no next charge, but Recurring flag set)
if (!$record['PortalUserId'] || !$record['GroupId'] || !$record['NextCharge']) continue;
// prevent duplicate user+group pairs
$skip_clause[ 'PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'] ] = $order_id;
}
$skip_clause = array_flip($skip_clause);
$event->MasterEvent->setEventParam('skip_clause', $skip_clause);
}
function OnGeneratePDF(&$event)
{
$this->OnLoadSelected($event);
$this->Application->InitParser();
$o = $this->Application->ParseBlock(array('name'=>'in-commerce/orders/orders_pdf'));
$htmlFile = EXPORT_PATH . '/tmp.html';
$fh = fopen($htmlFile, 'w');
fwrite($fh, $o);
fclose($fh);
// return;
// require_once (FULL_PATH.'html2pdf/PDFEncryptor.php');
// Full path to the file to be converted
// $htmlFile = dirname(__FILE__) . '/test.html';
// The default domain for images that use a relative path
// (you'll need to change the paths in the test.html page
// to an image on your server)
$defaultDomain = DOMAIN;
// Full path to the PDF we are creating
$pdfFile = EXPORT_PATH . '/tmp.pdf';
// Remove old one, just to make sure we are making it afresh
@unlink($pdfFile);
$pdf_helper =& $this->Application->recallObject('kPDFHelper');
$pdf_helper->FileToFile($htmlFile, $pdfFile);
return ;
// DOM PDF VERSION
/*require_once(FULL_PATH.'/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->load_html_file($htmlFile);
if ( isset($base_path) ) {
$dompdf->set_base_path($base_path);
}
$dompdf->set_paper($paper, $orientation);
$dompdf->render();
file_put_contents($pdfFile, $dompdf->output());
return ;*/
// Instnatiate the class with our variables
require_once (FULL_PATH.'/html2pdf/HTML_ToPDF.php');
$pdf = new HTML_ToPDF($htmlFile, $defaultDomain, $pdfFile);
$pdf->setHtml2Ps('/usr/bin/html2ps');
$pdf->setPs2Pdf('/usr/bin/ps2pdf');
$pdf->setGetUrl('/usr/local/bin/curl -i');
// Set headers/footers
$pdf->setHeader('color', 'black');
$pdf->setFooter('left', '');
$pdf->setFooter('right', '$D');
$pdf->setDefaultPath(BASE_PATH.'/kernel/admin_templates/');
$result = $pdf->convert();
// Check if the result was an error
if (PEAR::isError($result)) {
$this->Application->ApplicationDie($result->getMessage());
}
else {
$download_url = rtrim($this->Application->BaseURL(), '/') . EXPORT_BASE_PATH . '/tmp.pdf';
echo "PDF file created successfully: $result";
echo '<br />Click <a href="' . $download_url . '">here</a> to view the PDF file.';
}
}
function OnAfterConfigRead(&$event)
{
parent::OnAfterConfigRead($event);
if (defined('IS_INSTALL') && IS_INSTALL) {
return ;
}
$order_number = (int)$this->Application->ConfigValue('Comm_Order_Number_Format_P');
$order_sub_number = (int)$this->Application->ConfigValue('Comm_Order_Number_Format_S');
$calc_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
foreach ($calc_fields as $special => $fields) {
$calc_fields[$special]['OrderNumber'] = str_replace('6', $order_number, $calc_fields[$special]['OrderNumber']);
$calc_fields[$special]['OrderNumber'] = str_replace('3', $order_sub_number, $calc_fields[$special]['OrderNumber']);
}
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calc_fields);
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$fields['Number']['format'] = str_replace('%06d', '%0'.$order_number.'d', $fields['Number']['format']);
$fields['SubNumber']['format'] = str_replace('%03d', '%0'.$order_sub_number.'d', $fields['SubNumber']['format']);
if (!$this->Application->isAdminUser) {
$user_groups = explode(',', $this->Application->RecallVar('UserGroups'));
$default_group = $this->Application->ConfigValue('User_LoggedInGroup');
if (!in_array($default_group, $user_groups)){
$user_groups[]=$default_group;
}
$fields['PaymentType']['options_sql'] .= ' AND ';
$fields['PaymentType']['options_sql'] .= ' (PortalGroups LIKE "%%,'.implode(',%%" OR PortalGroups LIKE "%%,', $user_groups).',%%")';
}
$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
}
/**
* Allows configuring export options
*
* @param kEvent $event
*/
function OnBeforeExportBegin(&$event)
{
$options = $event->getEventParam('options') ;
$items_list =& $this->Application->recallObject($event->Prefix.'.'.$this->Application->RecallVar('export_oroginal_special'), $event->Prefix.'_List');
$items_list->SetPerPage(-1);
if ($options['export_ids'] != '') {
$items_list->AddFilter('export_ids', $items_list->TableName.'.'.$items_list->IDField.' IN ('.implode(',',$options['export_ids']).')');
}
$options['ForceCountSQL'] = $items_list->getCountSQL( $items_list->GetSelectSQL(true,false) );
$options['ForceSelectSQL'] = $items_list->GetSelectSQL();
$event->setEventParam('options',$options);
$object =& $this->Application->recallObject($event->Prefix.'.export');
/* @var $object kDBItem */
$object->SetField('Number', 999999);
$object->SetField('SubNumber', 999);
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
*/
function getCustomExportColumns(&$event)
{
$columns = parent::getCustomExportColumns($event);
$new_columns = Array(
'__VIRTUAL__CustomerName' => 'CustomerName',
'__VIRTUAL__TotalAmount' => 'TotalAmount',
'__VIRTUAL__AmountWithoutVAT' => 'AmountWithoutVAT',
'__VIRTUAL__SubtotalWithDiscount' => 'SubtotalWithDiscount',
'__VIRTUAL__SubtotalWithoutDiscount' => 'SubtotalWithoutDiscount',
'__VIRTUAL__OrderNumber' => 'OrderNumber',
);
return array_merge_recursive2($columns, $new_columns);
}
function OnSave(&$event)
{
$res = parent::OnSave($event);
if ($event->status == erSUCCESS) {
$copied_ids = unserialize($this->Application->RecallVar($event->Prefix.'_copied_ids'.$this->Application->GetVar('wid'), serialize(array())));
foreach ($copied_ids as $id) {
$an_event = new kEvent($this->Prefix.':Dummy');
$this->Application->SetVar($this->Prefix.'_id', $id);
$this->Application->SetVar($this->Prefix.'_mode', ''); // this is to fool ReserveItems to use live table
$this->ReserveItems($an_event);
}
}
return $res;
}
/**
* Occures before an item is copied to live table (after all foreign keys have been updated)
* Id of item being copied is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnBeforeCopyToLive(&$event)
{
$id = $event->getEventParam('id');
$copied_ids = unserialize($this->Application->RecallVar($event->Prefix.'_copied_ids'.$this->Application->GetVar('wid'), serialize(array())));
array_push($copied_ids, $id);
$this->Application->StoreVar($event->Prefix.'_copied_ids'.$this->Application->GetVar('wid'), serialize($copied_ids) );
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
*/
function checkItemStatus(&$event)
{
if ($this->Application->isAdminUser) {
return true;
}
$object =& $event->getObject();
if (!$object->isLoaded()) {
return true;
}
return $object->GetDBField('PortalUserId') == $this->Application->RecallVar('user_id');
}
// ===== Gift Certificates Related =====
function OnRemoveGiftCertificate(&$event)
{
$object =& $event->getObject();
$this->RemoveGiftCertificate($object);
$event->CallSubEvent('OnRecalculateItems');
$event->SetRedirectParam('checkout_error', 107);
}
function RemoveGiftCertificate(&$object)
{
$object->RemoveGiftCertificate();
}
function RecalculateGift(&$event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) {
return ;
}
$object->RecalculateGift($event);
}
function GetWholeOrderGiftCertificateDiscount($gift_certificate_id)
{
if (!$gift_certificate_id) {
return 0;
}
$sql = 'SELECT Debit
FROM '.TABLE_PREFIX.'GiftCertificates
WHERE GiftCertificateId = '.$gift_certificate_id;
return $this->Conn->GetOne($sql);
}
/**
* Creates new USPS order
*
* @param OrdersItem $object
* @param bool $fake_mode
* @return Array
*/
function MakeUSPSOrder(&$object, $fake_mode = false)
{
$this->Application->recallObject('ShippingQuoteEngine');
$aUSPS = $this->Application->recallObject('USPS', 'USPS');
/* @var $aUSPS USPS */
$ShippingInfo = unserialize($object->GetDBField('ShippingInfo'));
$ShippingCode = $USPSMethod = '';
$ShippingCountry = $aUSPS->GetUSPSCountry($object->GetDBField('ShippingCountry'));
$UserName = explode(" ", $object->GetDBField('ShippingTo'));
$item_table = TABLE_PREFIX.'OrderItems';
if ($this->Application->isAdminUser) {
// this strange contraption actually uses temp table from object (when in temp mode)
$order_table = $object->TableName;
$item_table = str_replace('Orders', 'OrderItems', $order_table);
}
$sOrder = Array (
'FirstName' => $UserName[0],
'LastName' => $UserName[1],
'ShippingCompany' => $object->GetDBField('ShippingCompany'),
'ShippingAddress1' => $object->GetDBField('ShippingAddress1'),
'ShippingAddress2' => $object->GetDBField('ShippingAddress2'),
'ShippingCity' => $object->GetDBField('ShippingCity'),
'ShippingZip' => $object->GetDBField('ShippingZip'),
'ShippingCountry' => $ShippingCountry,
'ShippingPhone' => $aUSPS->PhoneClean($object->GetDBField('ShippingPhone')),
'ShippingFax' => $aUSPS->PhoneClean($object->GetDBField('ShippingFax')),
'ShippingNumBoxes' => '1',
);
$sql = 'SELECT SUM(`Quantity` * `Weight`)
FROM ' . $item_table . '
WHERE ' . $object->IDField . ' = ' . $object->GetID();
$weight = $this->Application->Conn->GetOne($sql);
$f_weight = Kg2Pounds($weight);
$sOrder['ShippingWeight'] = $f_weight[0].'.'.$f_weight[1];
foreach ($ShippingInfo as $k => $ShippingRow) {
$ShippingCode = $ShippingRow['Code'];
}
if ( $object->GetDBField('ShippingCountry') == 'USA' ) {
$sOrder['ShippingState'] = $object->GetDBField('ShippingState');
$USPSMethod = $ShippingCode;
unset($sOrder['ShippingZip']);
$sOrder['ShippingZip5'] = substr(trim($object->GetDBField('ShippingZip')), 0, 5);
$sOrder['ShippingZip4'] = '';
$sOrder['SubTotal'] = $object->GetDBField('SubTotal');
}
else {
$USPSMethod = array_search($ShippingCode, $aUSPS->intl_types);
$sOrder['ShippingProvince'] = '';
if ( $ShippingCountry == 'CA' ) {
$sOrder['ShippingProvince'] = $object->GetField('ShippingState');
}
// add items
$sql = 'SELECT `Quantity`, `Weight`, `Price`
FROM ' . $item_table . '
WHERE ' . $object->IDField . ' = ' . $object->GetID();
$order_items = $this->Application->Conn->Query($sql);
$i = 1;
$Items = Array();
foreach ($order_items as $k => $order_item) {
$p_weight = Array();
$p_weight = Kg2Pounds($order_item['Weight']);
$Items[$i] = Array('Qty' => $order_item['Quantity'], 'Price' => $order_item['Price'], 'NetPounds' => $p_weight[0], 'NetOunces' => $p_weight[1]);
$i++;
}
$sOrder['Items'] = $Items;
$sOrder['InvoiceNumber'] = $object->GetDBField('OrderNumber');
}
$sOrder['ShippingService'] = $USPSMethod;
// make USPS order
$aUSPS->order = $sOrder;
$usps_data = $aUSPS->PostOrder();
// if errors
if ( array_key_exists('error_number', $usps_data) ) {
return $usps_data;
}
if ( array_key_exists('Postage', $usps_data) ) {
$ShippingPrice = '';
$ShippingPrice = $usps_data['Postage'];
}
$ShippingTracking = '';
if ( isset($usps_data['TrackingNumber']) && $usps_data['TrackingNumber'] != '' ) {
$ShippingTracking = $usps_data['TrackingNumber'];
}
if ( isset($usps_data['PostnetBarCode']) && $usps_data['PostnetBarCode'] != '' && $ShippingTracking == '' ) {
$ShippingTracking = $usps_data['PostnetBarCode'];
}
if ($fake_mode == false) {
$object->SetDBField('ShippingTracking', $ShippingTracking);
$object->Update();
}
else {
$full_path = USPS_LABEL_FOLDER . $ShippingTracking . ".pdf";
if (file_exists($full_path)) {
unlink($full_path);
}
}
return $usps_data;
}
/**
* Downloads shipping tracking bar code, that was already generated by USPS service
*
* @param kEvent $event
*/
function OnDownloadLabel(&$event)
{
$event->status = erSTOP;
ini_set('memory_limit', '300M');
ini_set('max_execution_time', '0');
$object =& $event->getObject();
$file = $object->GetDBField('ShippingTracking').'.pdf';
$full_path = USPS_LABEL_FOLDER.$file;
if (!file_exists($full_path) || !is_file($full_path)) {
return ;
}
$mime = function_exists('mime_content_type') ? mime_content_type($full_path) : 'application/download';
header('Content-type: '.$mime);
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile($full_path);
}
}
\ No newline at end of file
Index: branches/5.1.x/units/orders/orders_item.php
===================================================================
--- branches/5.1.x/units/orders/orders_item.php (revision 13464)
+++ branches/5.1.x/units/orders/orders_item.php (revision 13465)
@@ -1,529 +1,530 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class OrdersItem extends kDBItem
{
function OrdersItem()
{
parent::kDBItem();
$this->ErrorMsgs['credit_card_validation_error'] = $this->Application->Phrase('lu_cc_validation_error');
$this->ErrorMsgs['credit_card_expired'] = $this->Application->Phrase('lu_cc_expired');
}
function Load($id, $id_field_name=null)
{
if( $this->Special == 'sitem' && $id == null || (!$this->IsTempTable() && $id == 0))
{
$this->setID(0);
$this->SetDBField('Number',-1);
$this->SetDBField('SubNumber',-1);
// load previously used search params from session
$search_params = $this->Application->RecallVar('ord.search_search_filter');
if($search_params)
{
$search_params = unserialize($search_params);
foreach($search_params as $search_field => $search_params)
{
$this->SetField($search_field, $search_params['search_value']);
}
$this->UpdateFormattersSubFields(); // used for updating separate virtual date/time fields from DB timestamp (for example)
}
return true;
}
else
{
return parent::Load($id,$id_field_name);
}
}
/**
* Return error message for field
*
* @param string $field
* @return string
* @access public
*/
function GetErrorMsg($field)
{
if( $field != 'OrderNumber' ) return parent::GetErrorMsg($field);
$number['error'] = parent::GetErrorMsg('Number');
$number['pseudo'] = getArrayValue($this->FieldErrors['Number'], 'pseudo');
$subnumber['error'] = parent::GetErrorMsg('SubNumber');
$subnumber['pseudo'] = getArrayValue($this->FieldErrors['SubNumber'], 'pseudo');
// if pseudo match & not empty -> return 1st
// if one of pseudos not empty -> return it
// if we got one pseudo "bad_type" and other pseudo "required", then return "bad_type" error message
if( $number['pseudo'] && ($number['pseudo'] == $subnumber['pseudo']) )
{
return $number['error'];
}
if( $number['pseudo'] && !$subnumber['pseudo'] )
{
return $number['error'];
}
if( !$number['pseudo'] && $subnumber['pseudo'] )
{
return $subnumber['error'];
}
if( $number['pseudo'] == 'bad_type' )
{
return $number['error'];
}
if( $subnumber['pseudo'] == 'bad_type' )
{
return $subnumber['error'];
}
// $msg = '['.$number_error.'('.$number_pseudo.')] ['.$subnumber_error.'] ('.$subnumber_pseudo.')';
//
// return $msg;
}
function SetFieldsFromHash($hash, $set_fields=null)
{
parent::SetFieldsFromHash($hash, $set_fields);
$options = $this->GetFieldOptions('PaymentCCExpDate');
if( $this->GetDirtyField($options['month_field']) || $this->GetDirtyField($options['year_field']) )
{
$this->SetDirtyField('PaymentCCExpDate', 0);
$this->SetField('PaymentCCExpDate', 0);
}
}
/**
* Returns gateway data based on payment type used in order
*
* @return Array
*/
function getGatewayData($pt_id=null)
{
// get Gateway fields
if (!isset($pt_id) || !$pt_id) {
$pt_id = $this->GetDBField('PaymentType');
}
$pt_table = $this->Application->getUnitOption('pt','TableName');
$sql = 'SELECT GatewayId FROM %s WHERE PaymentTypeId = %s';
$gw_id = $this->Conn->GetOne( sprintf($sql, $pt_table, $pt_id) );
$sql = 'SELECT * FROM %s WHERE GatewayId = %s';
$ret = $this->Conn->GetRow( sprintf($sql, TABLE_PREFIX.'Gateways', $gw_id) );
// get Gateway parameters based on payment type
$gwf_table = $this->Application->getUnitOption('gwf','TableName');
$gwfv_table = $this->Application->getUnitOption('gwfv','TableName');
$sql = 'SELECT gwfv.Value, gwf.SystemFieldName
FROM %s gwf
LEFT JOIN %s gwfv ON gwf.GWConfigFieldId = gwfv.GWConfigFieldId
WHERE gwfv.PaymentTypeId = %s AND gwf.GatewayId = %s';
$ret['gw_params'] = $this->Conn->GetCol( sprintf($sql, $gwf_table, $gwfv_table, $pt_id, $gw_id), 'SystemFieldName' );
$ret['gw_params']['gateway_id'] = $gw_id;
if ($this->GetDBField('IsRecurringBilling') && $this->Application->ConfigValue('Comm_AutoProcessRecurringOrders')) {
if (isset($ret['gw_params']['shipping_control'])) {
$ret['gw_params']['shipping_control'] = SHIPPING_CONTROL_DIRECT;
}
}
return $ret;
}
/**
* Checks if tangible items are present in order
*
* @return bool
*/
function HasTangibleItems()
{
$sql = 'SELECT COUNT(*)
FROM '.TABLE_PREFIX.'OrderItems orditems
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = orditems.ProductId
WHERE (orditems.OrderId = '.$this->GetID().') AND (p.Type = '.PRODUCT_TYPE_TANGIBLE.')';
return $this->Conn->GetOne($sql) ? true : false;
}
/**
* Calculates tax value of order items based on billing & shipping country specified
*
* @return double
*/
function getTaxPercent()
{
- $sql = 'SELECT DestId FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType = %s AND DestAbbr = %s';
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
- $shipping_country_id = (int) $this->Conn->GetOne( sprintf($sql, 1, $this->Conn->qstr($this->GetDBField('ShippingCountry') ) ) );
- $shipping_state_id = (int) $this->Conn->GetOne( sprintf($sql, 2, $this->Conn->qstr($this->GetDBField('ShippingState') ) ) );
+ $shipping_country_id = $cs_helper->getCountryStateId($this->GetDBField('ShippingCountry'), DESTINATION_TYPE_COUNTRY);
+ $shipping_state_id = $cs_helper->getCountryStateId($this->GetDBField('ShippingState'), DESTINATION_TYPE_STATE);
$shipping_zip = (string) $this->GetDBField('ShippingZip');
- $billing_country_id = (int) $this->Conn->GetOne( sprintf($sql, 1, $this->Conn->qstr($this->GetDBField('BillingCountry') ) ) );
- $billing_state_id = (int) $this->Conn->GetOne( sprintf($sql, 2, $this->Conn->qstr($this->GetDBField('BillingState') ) ) );
+ $billing_country_id = $cs_helper->getCountryStateId($this->GetDBField('BillingCountry'), DESTINATION_TYPE_COUNTRY);
+ $billing_state_id = $cs_helper->getCountryStateId($this->GetDBField('BillingState'), DESTINATION_TYPE_STATE);
$billing_zip = (string) $this->GetDBField('BillingZip');
/*
$dest_ids = array_diff( array_unique( Array( $shipping_country_id, $shipping_state_id, $billing_country_id, $billing_state_id ) ), Array(0) );
$dest_values = array_diff( array_unique( Array( $this->Conn->qstr($shipping_zip), $this->Conn->qstr($billing_zip) ) ), Array('\'\'') );
*/
$tax = false;
$sql = 'SELECT tx.*
FROM '.$this->Application->getUnitOption('tax', 'TableName').' tx
LEFT JOIN '.$this->Application->getUnitOption('taxdst', 'TableName').' txd ON tx.TaxZoneId = txd.TaxZoneId
WHERE
( txd.StdDestId IN ('.$shipping_country_id.','.$shipping_state_id.')
AND
( (txd.DestValue = "" OR txd.DestValue IS NULL)
OR
txd.DestValue = '.$this->Conn->qstr($shipping_zip).'
)
)
OR
( txd.StdDestId IN ('.$billing_country_id.','.$billing_state_id.')
AND
( (txd.DestValue = "" OR txd.DestValue IS NULL)
OR
txd.DestValue = '.$this->Conn->qstr($billing_zip).'
)
)
ORDER BY tx.TaxValue DESC';
$tax = $this->Conn->GetRow($sql);
if ($tax == false) {
$tax['TaxValue'] = 0;
$tax['ApplyToShipping'] = 0;
$tax['ApplyToProcessing'] = 0;
}
return $tax;
}
function RecalculateTax()
{
$tax = $this->getTaxPercent();
$this->SetDBField( 'VATPercent', $tax['TaxValue'] );
$this->SetDBField( 'ShippingTaxable', $tax['ApplyToShipping']);
$this->SetDBField( 'ProcessingTaxable', $tax['ApplyToProcessing']);
$this->UpdateTotals();
$subtotal = $this->GetDBField('AmountWithoutVAT');
$query = 'SELECT SUM(Quantity * Price) FROM '.TABLE_PREFIX.'OrderItems AS oi
LEFT JOIN '.TABLE_PREFIX.'Products AS p
ON p.ProductId = oi.ProductId
WHERE p.Type = 6 AND oi.OrderId = '.$this->GetDBField('OrderId');
$tax_exempt = $this->Conn->GetOne($query);
if ($tax_exempt) $subtotal -= $tax_exempt;
$this->SetDBField( 'VAT', round($subtotal * $tax['TaxValue'] / 100, 2) );
$this->UpdateTotals();
}
function UpdateTotals()
{
$total = 0;
$total += $this->GetDBField('SubTotal');
if ($this->GetDBField('ShippingTaxable')) $total += $this->GetDBField('ShippingCost');
if ($this->GetDBField('ProcessingTaxable')) $total += $this->GetDBField('ProcessingFee');
$this->SetDBField('AmountWithoutVAT', $total);
$total += $this->GetDBField('VAT');
if (!$this->GetDBField('ShippingTaxable')) $total += $this->GetDBField('ShippingCost');
if (!$this->GetDBField('ProcessingTaxable')) $total += $this->GetDBField('ProcessingFee');
$total += $this->GetDBField('InsuranceFee');
$this->SetDBField('TotalAmount', $total);
}
function getTotalAmount()
{
return $this->GetDBField('SubTotal') +
$this->GetDBField('ShippingCost') +
$this->GetDBField('VAT') +
$this->GetDBField('ProcessingFee') +
$this->GetDBField('InsuranceFee') -
$this->GetDBField('GiftCertificateDiscount');
}
/**
* Check field value by user-defined alghoritm
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function CustomValidation($field, $params)
{
$res = true;
$res = $res && $this->ValidateCCNumber($field, $params);
$res = $res && $this->ValidateCCExpiration($field, $params);
return $res;
}
function requireCreditCard()
{
$pt_table = $this->Application->getUnitOption('pt', 'TableName');
$sql = 'SELECT RequireCCFields
FROM '.$pt_table.' pt
LEFT JOIN '.TABLE_PREFIX.'Gateways gw ON gw.GatewayId = pt.GatewayId
WHERE pt.PaymentTypeId = '.$this->GetDBField('PaymentType');
return $this->Conn->GetOne($sql);
}
/**
* Check if field value is valid credit card number against credit card type specified
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateCCNumber($field, $params)
{
$cardtype_field = getArrayValue($params, 'cardtype_field');
$value = $this->GetDBField($field);
if( !$cardtype_field || !$value || !$this->requireCreditCard() ) return true;
if ($this->Application->ConfigValue('Comm_MaskProcessedCreditCards')) {
$mask_found = strpos($value, str_repeat('X', 4)) !== false;
if ($this->Application->isAdminUser && $mask_found) {
// masked card numbers always appear valid in admin
return true;
}
}
if (defined('DEBUG_MODE') && constOn('DBG_PAYMENT_GW')) {
$gw_data = $this->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$test_numbers = $gateway_object->GetTestCCNumbers();
if (in_array($value, $test_numbers)) return true;
}
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
// '1' => 'Visa','2' => 'Mastercard', '3' => 'Amex', '4' => 'Discover', 5 => 'Diners Club', 6 => 'JBC'
// Innocent until proven guilty
$cc_valid = true;
// Get rid of any non-digits
$value = ereg_replace("[^[:digit:]]", '', $value);
// Perform card-specific checks, if applicable
switch( $this->GetDBField($cardtype_field) )
{
case 2: // MasterCard
$cc_valid = ereg("^5[1-5].{14}$", $value);
break;
case 1: // Visa
$cc_valid = ereg("^4.{15}$|^4.{12}$", $value);
break;
case 3: // American Express
$cc_valid = ereg("^3[47].{13}$", $value);
break;
case 4: // Discover
$cc_valid = ereg("^6011.{12}$", $value);
break;
case 5: // Diners Club
$cc_valid = ereg("^30[0-5].{11}$|^3[68].{12}$", $value);
break;
case 6: // JBC
$cc_valid = ereg("^3.{15}$|^2131|1800.{11}$", $value);
break;
default:
$this->FieldErrors[$error_field]['pseudo'] = 'credit_card_validation_error';
return false;
break;
}
// The Luhn formula works right to left, so reverse the number.
$value = strrev($value);
$total = 0;
for($x = 0; $x < strlen($value); $x++)
{
$digit = substr($value, $x, 1);
// If it's an odd digit, double it
if( $x / 2 != floor($x/2) )
{
$digit *= 2;
// If the result is two digits, add them
if( strlen($digit) == 2 )
{
$digit = substr($digit, 0, 1) + substr($digit, 1, 1);
}
}
// Add the current digit, doubled and added if applicable, to the Total
$total += $digit;
}
// If it passed (or bypassed) the card-specific check and the Total is
// evenly divisible by 10, it's cool!
if ($cc_valid && $total % 10 == 0)
{
return true;
}
else
{
$this->FieldErrors[$error_field]['pseudo'] = 'credit_card_validation_error';
return false;
}
}
/**
* Check if field value is non-expired credit card expiration date
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateCCExpiration($field, $params)
{
$formatter = getArrayValue($params, 'formatter');
if( ($formatter != 'kCCDateFormatter') || !$this->requireCreditCard() ) return true;
if(!$this->Application->isAdminUser) {
// validate expiration date only for front
if (preg_match('/([\d]{2})\/([\d]{2})/', $this->GetDBField($field), $rets)) {
$month = $rets[1];
$year = $rets[2];
$now_date = adodb_mktime(0, 0, 0, adodb_date('m'), adodb_date('d'), adodb_date('Y') );
$day_count = adodb_date('t', adodb_mktime(0, 0, 0, $month, 1, $year) );
$cc_date = adodb_mktime(23, 59, 59, $month, $day_count, $year);
if ($cc_date < $now_date) {
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
$this->FieldErrors[$error_field]['pseudo'] = 'credit_card_expired';
return false;
}
}
}
return true;
}
function getNextSubNumber()
{
$table = $this->Application->GetLiveName($this->TableName);
$sql = 'SELECT MAX(SubNumber) FROM '.$table.' WHERE Number = '.$this->GetDBField('Number');
return $this->Conn->GetOne($sql) + 1;
}
function ResetAddress($prefix)
{
$fields = Array('To','Company','Phone','Fax','Email','Address1','Address2','City','State','Zip','Country');
foreach($fields as $field)
{
$this->SetDBField($prefix.$field, $this->Fields[$prefix.$field]['default']);
}
}
function IsProfileAddress($address_type)
{
return $this->Application->GetVar($this->Prefix.'_IsProfileAddress');
}
// ===== Gift Certificates Related =====
function RecalculateGift(&$event)
{
$gc_id = $this->GetDBField('GiftCertificateId');
if ($gc_id < 1) {
return;
}
$gc =& $this->Application->recallObject('gc', null, Array('skip_autoload' => true));
/* @var $gc kDBItem */
$gc->Load($gc_id);
if ($gc->GetDBField('Status') == gcDISABLED) {
// disabled GC
$this->SetDBField('GiftCertificateId', 0);
$this->SetDBField('GiftCertificateDiscount', 0);
// disabled
return;
}
$debit = $gc->GetDBField('Debit') + $this->GetDBField('GiftCertificateDiscount');
$this->UpdateTotals();
$total = $this->GetDBField('TotalAmount');
$gift_certificate_discount = $debit >= $total ? $total : $debit;
$this->SetDBField('TotalAmount', $total - $gift_certificate_discount);
$this->GetDBField('GiftCertificateDiscount', $gift_certificate_discount);
$debit -= $gift_certificate_discount;
$gc->SetDBField('Debit', $debit);
$gc->SetDBField('Status', $debit > 0 ? gcENABLED : gcUSED);
$gc->Update();
if ($gift_certificate_discount == 0) {
$this->RemoveGiftCertificate($object);
$event->SetRedirectParam('checkout_error', 108);
}
$this->SetDBField('GiftCertificateDiscount', $gift_certificate_discount);
}
function RemoveGiftCertificate()
{
$gc_id = $this->GetDBField('GiftCertificateId');
$gc =& $this->Application->recallObject('gc', null, Array('skip_autoload' => true));
/* @var $gc kDBItem */
$gc->Load($gc_id);
$debit = $gc->GetDBField('Debit') + $this->GetDBField('GiftCertificateDiscount');
if ($gc->isLoaded() && ($debit > 0)) {
$gc->SetDBField('Debit', $debit);
$gc->SetDBField('Status', gcENABLED);
$gc->Update();
}
$this->SetDBField('GiftCertificateId', 0);
$this->SetDBField('GiftCertificateDiscount', 0);
}
}
\ No newline at end of file
Index: branches/5.1.x/units/orders/orders_config.php
===================================================================
--- branches/5.1.x/units/orders/orders_config.php (revision 13464)
+++ branches/5.1.x/units/orders/orders_config.php (revision 13465)
@@ -1,500 +1,498 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array(
'Prefix' => 'ord',
'ItemClass' => Array('class'=>'OrdersItem','file'=>'orders_item.php','build_event'=>'OnItemBuild'),
'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'),
'EventHandlerClass' => Array('class'=>'OrdersEventHandler','file'=>'orders_event_handler.php','build_event'=>'OnBuild'),
'TagProcessorClass' => Array('class'=>'OrdersTagProcessor','file'=>'orders_tag_processor.php','build_event'=>'OnBuild'),
'AutoLoad' => true,
'Hooks' => Array(
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'ord',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnPreSave' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnRecalculateItems',
),
/* OnApplyCoupon is called as hook for OnUpdateCart/OnCheckout, which calls OnRecalcualate themself
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'coup',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnApplyCoupon' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnRecalculateItems',
),*/
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnCreate' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnUserCreate',
),
Array(
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array('OnCheckExpiredMembership'),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnCheckRecurringOrders',
),
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnLogin' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnUserLogin',
),
Array(
'Mode' => hBEFORE, // before because OnInpLogin is called after real in-portal login and uses data from hooks
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnInpLogin' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnUserLogin',
),
),
'AggregateTags' => Array(
Array(
'AggregateTo' => 'orditems',
'AggregatedTagName' => 'LinkRemoveFromCart',
'LocalTagName' => 'Orditems_LinkRemoveFromCart',
),
Array(
'AggregateTo' => 'orditems',
'AggregatedTagName' => 'ProductLink',
'LocalTagName' => 'Orderitems_ProductLink',
),
Array(
'AggregateTo' => 'orditems',
'AggregatedTagName' => 'ProductExists',
'LocalTagName' => 'Orderitems_ProductExists',
),
),
'QueryString' => Array(
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'IDField' => 'OrderId',
'StatusField' => Array('Status'), // field, that is affected by Approve/Decline events
'ViewMenuPhrase' => 'la_title_Orders',
'CatalogTabIcon' => 'icon16_item.png',
'TitleField' => 'OrderNumber',
'TitlePresets' => Array(
'default' => Array( 'new_status_labels' => Array('ord'=>'!la_title_Adding_Order!'),
'edit_status_labels' => Array('ord'=>'!la_title_Editing_Order!'),
'new_titlefield' => Array('ord'=>'!la_title_New_Order!'),
),
'orders_incomplete' => Array( 'prefixes' => Array('ord.incomplete_List'),
'format' => "!la_title_IncompleteOrders!",
),
'orders_pending' => Array( 'prefixes' => Array('ord.pending_List'),
'format' => "!la_title_PendingOrders!",
),
'orders_backorders' => Array( 'prefixes' => Array('ord.backorders_List'),
'format' => "!la_title_BackOrders!",
),
'orders_toship' => Array( 'prefixes' => Array('ord.toship_List'),
'format' => "!la_title_OrdersToShip!",
),
'orders_processed' => Array( 'prefixes' => Array('ord.processed_List'),
'format' => "!la_title_OrdersProcessed!",
),
'orders_returns' => Array( 'prefixes' => Array('ord.returns_List'),
'format' => "!la_title_OrdersReturns!",
),
'orders_denied' => Array( 'prefixes' => Array('ord.denied_List'),
'format' => "!la_title_OrdersDenied!",
),
'orders_archived' => Array( 'prefixes' => Array('ord.archived_List'),
'format' => "!la_title_OrdersArchived!",
),
'orders_search' => Array( 'prefixes' => Array('ord.search_List'),
'format' => "!la_title_OrdersSearch!",
),
'orders_edit_general' => Array('prefixes' => Array('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_General!"),
'orders_edit_billing' => Array('prefixes' => Array('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderBilling!"),
'orders_edit_shipping' => Array('prefixes' => Array('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderShipping!"),
'orders_edit_items' => Array('prefixes' => Array('ord', 'orditems_List'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderItems!"),
'orders_edit_preview' => Array('prefixes' => Array('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderPreview!"),
'orders_gw_result' => Array('prefixes' => Array('ord'), 'format' => "!la_title_OrderGWResult!"),
'order_items_edit' => Array( 'prefixes' => Array('ord', 'orditems'),
'new_status_labels' => Array('orditems'=>'!la_title_Adding_Order_Item!'),
'edit_status_labels' => Array('orditems'=>'!la_title_Editing_Order_Item!'),
'new_titlefield' => Array('orditems'=>'!la_title_New_Order_Item!'),
'format' => "#ord_status# '#ord_titlefield#' - #orditems_status# '#orditems_titlefield#'",
),
'orders_export' => Array('format' => '!la_title_OrdersExport!'),
'orders_product_edit' => Array('format' => '!la_title_Editing_Order_Item!'),
),
'EditTabPresets' => Array (
'Default' => Array (
'general' => Array ('title' => 'la_tab_General', 't' => 'in-commerce/orders/orders_edit', 'priority' => 1),
'items' => Array ('title' => 'la_tab_Items', 't' => 'in-commerce/orders/orders_edit_items', 'priority' => 2),
'shipping' => Array ('title' => 'la_tab_Shipping', 't' => 'in-commerce/orders/orders_edit_shipping', 'priority' => 3),
'billing' => Array ('title' => 'la_tab_Billing', 't' => 'in-commerce/orders/orders_edit_billing', 'priority' => 4),
'preview' => Array ('title' => 'la_tab_Preview', 't' => 'in-commerce/orders/orders_edit_preview', 'priority' => 5),
),
),
'PermSection' => Array('main' => 'in-commerce:orders'),
'Sections' => Array(
'in-commerce:orders' => Array(
'parent' => 'in-commerce',
'icon' => 'in-commerce:orders',
'label' => 'la_tab_Orders',
'url' => Array('t' => 'in-commerce/orders/orders_pending_list', 'pass' => 'm'),
'permissions' => Array('view', 'add', 'edit', 'delete', 'advanced:approve', 'advanced:deny', 'advanced:archive', 'advanced:place', 'advanced:process', 'advanced:ship', 'advanced:reset_to_pending'),
'priority' => 1,
'type' => stTREE,
),
),
'SectionAdjustments' => Array (
'in-portal:visits' => Array (
'url' => Array ('t' => 'in-commerce/visits/visits_list_incommerce', 'pass' => 'm'),
),
),
'StatisticsInfo' => Array(
'pending' => Array(
'icon' => 'core:icon16_item.png',
'label' => 'la_title_Orders',
'js_url' => "#url#",
'url' => Array('t' => 'in-commerce/orders/orders_pending_list', 'pass' => 'm'),
'status' => ORDER_STATUS_PENDING,
),
),
'TableName' => TABLE_PREFIX.'Orders',
'FilterMenu' => Array(
'Groups' => Array(
Array('mode' => 'AND', 'filters' => Array(0,1,2,3,4,5,6), 'type' => WHERE_FILTER),
),
'Filters' => Array(
0 => Array('label' => 'la_Incomplete', 'on_sql' => '', 'off_sql' => '%1$s.Status != 0' ),
1 => Array('label' => 'la_Pending', 'on_sql' => '', 'off_sql' => '%1$s.Status != 1' ),
2 => Array('label' => 'la_BackOrders', 'on_sql' => '', 'off_sql' => '%1$s.Status != 2' ),
3 => Array('label' => 'la_ToShip', 'on_sql' => '', 'off_sql' => '%1$s.Status != 3' ),
4 => Array('label' => 'la_Processed', 'on_sql' => '', 'off_sql' => '%1$s.Status != 4' ),
5 => Array('label' => 'la_Denied', 'on_sql' => '', 'off_sql' => '%1$s.Status != 5' ),
6 => Array('label' => 'la_Archived', 'on_sql' => '', 'off_sql' => '%1$s.Status != 6' ),
)
),
'CalculatedFields' => Array(
'' => Array (
'CustomerName' => 'IF( ISNULL(u.Login), IF (%1$s.PortalUserId = -1, \'root\', IF (%1$s.PortalUserId = -2, \'Guest\', \'n/a\')), CONCAT(u.FirstName,\' \',u.LastName) )',
'Username' => 'IF( ISNULL(u.Login),\'root\',u.Login)',
'OrderNumber' => 'CONCAT(LPAD(Number,6,"0"),\'-\',LPAD(SubNumber,3,"0") )',
'SubtotalWithoutDiscount' => '(SubTotal + DiscountTotal)',
'SubtotalWithDiscount' => '(SubTotal)',
'AmountWithoutVAT' => '(SubTotal+IF(ShippingTaxable=1, ShippingCost, 0)+IF(ProcessingTaxable=1, ProcessingFee, 0))',
'TotalAmount' => 'ROUND(SubTotal+ShippingCost+VAT+ProcessingFee+InsuranceFee-GiftCertificateDiscount,2)',
'CouponCode' => 'pc.Code',
'CouponName' => 'pc.Name',
'AffiliateUser' => 'IF( LENGTH(au.Login),au.Login,\'!la_None!\')',
'AffiliatePortalUserId' => 'af.PortalUserId',
'GiftCertificateCode' => 'gc.Code',
'GiftCertificateRecipient' => 'gc.Recipient',
),
'myorders' => Array (
'OrderNumber' => 'CONCAT(LPAD(Number,6,"0"),\'-\',LPAD(SubNumber,3,"0") )',
'SubtotalWithoutDiscount' => '(SubTotal + DiscountTotal)',
'SubtotalWithDiscount' => '(SubTotal)',
'AmountWithoutVAT' => '(SubTotal+IF(ShippingTaxable=1, ShippingCost, 0)+IF(ProcessingTaxable=1, ProcessingFee, 0))',
'TotalAmount' => 'ROUND(SubTotal+ShippingCost+VAT+ProcessingFee+InsuranceFee-GiftCertificateDiscount,2)',
/*'ItemsCount' => 'COUNT(%1$s.OrderId)',*/
),
),
// %1$s - table name of object
// %2$s - calculated fields
'ListSQLs' => Array (
'' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId
LEFT JOIN '.TABLE_PREFIX.'ProductsCoupons pc ON %1$s.CouponId = pc.CouponId
LEFT JOIN '.TABLE_PREFIX.'GiftCertificates gc ON %1$s.GiftCertificateId = gc.GiftCertificateId
LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId
LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId',
'myorders' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId',
// LEFT JOIN '.TABLE_PREFIX.'OrderItems ON %1$s.OrderId = '.TABLE_PREFIX.'OrderItems.OrderId',
),
'ItemSQLs' => Array (
'' => ' SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.PortalUserId = u.PortalUserId
LEFT JOIN '.TABLE_PREFIX.'ProductsCoupons pc ON %1$s.CouponId = pc.CouponId
LEFT JOIN '.TABLE_PREFIX.'GiftCertificates gc ON %1$s.GiftCertificateId = gc.GiftCertificateId
LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId
LEFT JOIN '.TABLE_PREFIX.'PortalUser au ON af.PortalUserId = au.PortalUserId',
),
'SubItems' => Array('orditems'),
'ListSortings' => Array(
'' => Array(
'Sorting' => Array('OrderDate' => 'desc'),
)
),
'Fields' => Array(
'OrderId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0, 'filter_type' => 'equals'),
'Number' => Array('type' => 'int','required'=>1,'formatter'=>'kFormatter', 'unique'=>Array('SubNumber'),'format'=>'%06d', 'max_value_inc'>999999, 'not_null' => '1','default' => 0),
'SubNumber' => Array('type' => 'int','required'=>1,'formatter'=>'kFormatter','unique'=>Array('Number'), 'format'=>'%03d', 'max_value_inc'>999, 'not_null' => '1','default' => 0),
'Status' => Array('type' => 'int', 'formatter'=>'kOptionsFormatter','options'=>Array(0=>'la_Incomplete',1=>'la_Pending',2=>'la_BackOrders',3=>'la_ToShip',4=>'la_Processed',5=>'la_Denied',6=>'la_Archived'), 'use_phrases'=>1, 'not_null' => '1','default' => 0, 'filter_type' => 'equals'),
'OnHold' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options' => Array (0 => 'la_No', 1 => 'la_Yes'), 'use_phrases' => 1,
'not_null' => 1, 'default' => 0
),
'OrderDate' => Array('type' => 'int', 'formatter'=>'kDateFormatter', 'required' => 1, 'default' => '#NOW#'),
'PortalUserId'=>Array('type'=>'int','formatter'=>'kLEFTFormatter', 'error_msgs' => Array ('invalid_option' => '!la_error_UserNotFound!'), 'options'=>Array(-1=>'root',-2=>'Guest'),'left_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'PortalUser WHERE `%s` = \'%s\'','left_key_field'=>'PortalUserId','left_title_field'=>'Login','required'=>1,'not_null'=>1,'default'=>-1),
'OrderIP' => Array('type' => 'string','not_null' => '1','default' => '', 'filter_type' => 'like'),
'UserComment' => Array('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => NULL),
'AdminComment' => Array('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => NULL),
'BillingTo' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingCompany' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingPhone' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingFax' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingEmail' => Array('type' => 'string','formatter'=>'kFormatter', 'regexp'=>'/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i','not_null' => '1','default' => ''),
'BillingAddress1' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingAddress2' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingCity' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingState' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter', 'options' => Array(),
'not_null' => 1, 'default' => ''
),
'BillingZip' => Array('type' => 'string','not_null' => '1','default' => ''),
'BillingCountry' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter',
- 'options_sql' => ' SELECT %1$s
- FROM '.TABLE_PREFIX.'StdDestinations
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = '.TABLE_PREFIX.'StdDestinations.DestName
- WHERE DestType = 1
- ORDER BY l%2$s_Translation',
- 'option_key_field' => 'DestAbbr', 'option_title_field' => 'l%2$s_Translation',
+ 'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
+ FROM '.TABLE_PREFIX.'CountryStates
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
+ ORDER BY Name',
+ 'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => 'USA'
),
'VAT' => Array('type' => 'float','formatter'=>'kFormatter','not_null'=>1,'default' => '0','format'=>'%01.2f'),
'VATPercent' => Array('type' => 'float','formatter'=>'kFormatter','not_null'=>1,'default' => '0','format'=>'%01.3f'),
'PaymentType' => Array('type' => 'int', 'formatter'=>'kOptionsFormatter','options_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'PaymentTypes WHERE Status = 1', 'option_key_field'=>'PaymentTypeId','option_title_field'=>'Description', 'not_null' => 1, 'default' => 0),
'PaymentAccount' => Array('type' => 'string','not_null' => '1', 'cardtype_field' => 'PaymentCardType', 'default' => '', 'filter_type' => 'like'),
'PaymentNameOnCard' => Array('type' => 'string','not_null' => '1','default' => ''),
'PaymentCCExpDate' => Array('type' => 'string', 'formatter'=>'kCCDateFormatter', 'month_field' => 'PaymentCCExpMonth', 'year_field'=>'PaymentCCExpYear', 'not_null' => '1','default' => ''),
'PaymentCardType' => Array('type' => 'string', 'not_null' => 1, 'formatter'=>'kOptionsFormatter', 'options' => Array('' => '','1' => 'Visa','2' => 'Mastercard', '3' => 'Amex', '4' => 'Discover', '5' => 'Diners Club', '6' => 'JBC'), 'default' => ''),
'PaymentExpires' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => '#NOW#'),
'ShippingTo' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingCompany' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingPhone' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingFax' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingEmail' => Array('type' => 'string','formatter'=>'kFormatter', 'regexp'=>'/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i','not_null' => '1','default' => ''),
'ShippingAddress1' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingAddress2' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingCity' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingState' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter', 'options' => Array(),
'not_null' => 1, 'default' => ''
),
'ShippingZip' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingCountry' => Array(
'type' => 'string', 'formatter' => 'kOptionsFormatter',
- 'options_sql' => ' SELECT %1$s
- FROM '.TABLE_PREFIX.'StdDestinations
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = '.TABLE_PREFIX.'StdDestinations.DestName
- WHERE DestType = 1
- ORDER BY l%2$s_Translation',
- 'option_key_field' => 'DestAbbr', 'option_title_field' => 'l%2$s_Translation',
+ 'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
+ FROM '.TABLE_PREFIX.'CountryStates
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
+ ORDER BY Name',
+ 'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => 'USA'
),
'ShippingType' => Array('type' => 'int','formatter'=>'kOptionsFormatter','options_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'ShippingType WHERE Status = 1','option_key_field'=>'ShippingID','option_title_field'=>'Name', 'not_null' => 1, 'default' => 0),
'ShippingCost' => Array('type' => 'double','formatter'=>'kFormatter','format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'ShippingCustomerAccount' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingTracking' => Array('type' => 'string','not_null' => '1','default' => ''),
'ShippingDate' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => null),
'SubTotal' => Array('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'ReturnTotal' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00'),
'CostTotal' => Array('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'OriginalAmount' => Array('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'ShippingOption' => Array('type' => 'int', 'formatter'=>'kOptionsFormatter', 'use_phrases' => 1, 'options' => Array(0 => 'la_ship_all_together', 1 => 'la_ship_backorder_separately', 2 => 'la_ship_backorders_upon_avail'), 'default'=>0),
'ShippingGroupOption' => Array('type' => 'int', 'not_null' => 1, 'formatter'=>'kOptionsFormatter', 'use_phrases' => 1, 'options' => Array(0 => 'la_auto_group_shipments', 1 => 'la_manual_group_shipments'), 'default'=>0),
'GiftCertificateId' => Array('type' => 'int','default' => null),
'GiftCertificateDiscount' => Array('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00',),
'ShippingInfo' => Array('type' => 'string', 'default' => NULL),
'CouponId' => Array('type' => 'int','default' => null),
'CouponDiscount' => Array('type' => 'float','not_null' => '1','default' => '0.00','formatter'=>'kFormatter','format'=>'%01.2f'),
'DiscountTotal' => Array('type' => 'float','not_null' => '1','default' => '0.00','formatter'=>'kFormatter','format'=>'%01.2f'),
'TransactionStatus' => Array('type' => 'int', 'formatter'=>'kOptionsFormatter', 'options' => Array(0=>'la_Invalid', 1 => 'la_Verified', 2 => 'la_Penging'), 'use_phrases'=>1, 'not_null' => '1','default' => 2),
'GWResult1' => Array('type' => 'string', 'formatter'=>'kSerializedFormatter', 'default' => NULL),
'GWResult2' => Array('type' => 'string', 'formatter'=>'kSerializedFormatter', 'default' => NULL),
'AffiliateId' => Array('type'=>'int','formatter'=>'kLEFTFormatter', 'error_msgs' => Array ('invalid_option' => '!la_error_UserNotFound!'), 'options' => Array(0 => 'lu_None'),'left_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'Affiliates af LEFT JOIN '.TABLE_PREFIX.'PortalUser pu ON pu.PortalUserId = af.PortalUserId WHERE `%s` = \'%s\'','left_key_field'=>'AffiliateId','left_title_field'=>'Login','not_null'=>1,'default'=>0),
'VisitId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'AffiliateCommission' => Array('type' => 'double', 'formatter'=>'kFormatter','format'=>'%.02f', 'not_null' => '1','default' => '0.0000'),
'ProcessingFee' => Array('type' => 'double', 'formatter'=>'kFormatter','format'=>'%.02f', 'not_null' => '0','default' => '0.0000'),
'InsuranceFee' => Array ('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'ShippingTaxable' => Array('type' => 'int', 'not_null' => 0, 'default' => 0),
'ProcessingTaxable' => Array('type' => 'int', 'not_null' => 0, 'default' => 0),
'IsRecurringBilling' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 0),
'ChargeOnNextApprove' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 0),
'NextCharge' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => null),
'GroupId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'GoogleOrderNumber' => Array ('type' => 'string', 'default' => NULL), // MySQL BIGINT UNSIGNED = 8 Bytes, PHP int = 4 Bytes -> threat as string
),
'VirtualFields' => Array(
'CustomerName' => Array('type'=>'string','default'=>'','filter_type'=>'like'),
'TotalAmount' => Array('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'AmountWithoutVAT' => Array('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'SubtotalWithDiscount' => Array('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'SubtotalWithoutDiscount' => Array('type' => 'float', 'formatter'=>'kFormatter', 'format'=>'%01.2f', 'not_null' => '1','default' => '0.00'),
'OrderNumber' => Array('type'=>'string','default'=>'', 'filter_type' => 'like'),
// for ResetToUser
'UserTo' => Array('type'=>'string','default'=>''),
'UserCompany' => Array('type'=>'string','default'=>''),
'UserPhone' => Array('type'=>'string','default'=>''),
'UserFax' => Array('type'=>'string','default'=>''),
'UserEmail' => Array('type'=>'string','default'=>''),
'UserAddress1' => Array('type'=>'string','default'=>''),
'UserAddress2' => Array('type'=>'string','default'=>''),
'UserCity' => Array('type'=>'string','default'=>''),
'UserState' => Array('type'=>'string','default'=>''),
'UserZip' => Array('type'=>'string','default'=>''),
'UserCountry' => Array('type'=>'string','default'=>''),
// for Search
'Username' => Array('type'=>'string','filter_type'=>'like'),
'OrderSearchId' => Array('type'=>'int','filter_type'=>'equals','filter_field'=>'OrderId'),
'FromDateTime' => Array('formatter'=>'kDateFormatter','default'=>'','filter_type'=>'range_from','filter_field'=>'OrderDate' ),
'ToDateTime' => Array('formatter'=>'kDateFormatter','default'=>'','filter_type'=>'range_to','filter_field'=>'OrderDate', 'empty_time' => adodb_mktime(23,59,59) ),
'FromAmount' => Array('type'=>'double', 'formatter'=>'kFormatter', 'format'=>'%01.2f','filter_type'=>'range_from','filter_field'=>'TotalAmount'),
'ToAmount' => Array('type'=>'double', 'formatter'=>'kFormatter', 'format'=>'%01.2f','filter_type'=>'range_to','filter_field'=>'TotalAmount'),
'HasBackOrders' => Array('default'=>false),
'PaymentCVV2' => Array('type'=>'string', 'default'=>false),
'AffiliateUser' => Array('type'=>'string', 'filter_type' => 'like'),
'AffiliatePortalUserId' => Array('type'=>'int'),
// export related fields: begin
'ExportFormat' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'CSV', /*2 => 'XML'*/), 'default' => 1),
'ExportFilename' => Array('type' => 'string', 'default' => ''),
'FieldsSeparatedBy' => Array('type' => 'string', 'default' => ','),
'FieldsEnclosedBy' => Array('type' => 'string', 'default' => '"'),
'LineEndings' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'Windows', 2 => 'UNIX'), 'default' => 1),
'LineEndingsInside' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'CRLF', 2 => 'LF'), 'default' => 2),
'IncludeFieldTitles' => Array('type' => 'int', 'default' => 1),
'ExportColumns' => Array('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array()),
'AvailableColumns' => Array('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array()),
'ExportPresets' => Array('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array()),
'ExportSavePreset' => Array('type'=>'int'),
'ExportPresetName' => Array('type'=>'string'),
// export related fields: end
),
'Grids' => Array(
'Default' => Array(
'Icons' => Array(
'default' => 'icon16_item.png',
1 => 'icon16_pending.png',
5 => 'icon16_disabled.png',
'module' => 'core',
),
'Fields' => Array(
'OrderId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 70, ), 'OrderNumber' => Array( 'title' => 'la_col_OrderNumber', 'data_block' => 'grid_ordernumber_td', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'OrderDate' => Array( 'title'=>'la_col_OrderDate', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_date_range_filter', 'width' => 140, ),
'CustomerName' => Array( 'title' => 'la_col_CustomerName', 'data_block' => 'grid_userlink_td', 'user_field' => 'PortalUserId', 'filter_block' => 'grid_like_filter', 'width' => 140, ),
'PaymentType' => Array( 'title' => 'la_col_PaymentType', 'data_block' => 'grid_billinglink_td', 'filter_block' => 'grid_options_filter', 'width' => 140, ),
'TotalAmount' => Array( 'title' => 'la_col_TotalAmount', 'data_block' => 'grid_previewlink_td', 'filter_block' => 'grid_range_filter', 'width' => 140, ),
'AffiliateUser' => Array( 'title' => 'la_col_AffiliateUser', 'data_block' => 'grid_userlink_td', 'user_field' => 'AffiliatePortalUserId', 'filter_block' => 'grid_like_filter', 'width' => 140, ),
'OnHold' => Array ('title' => 'la_col_OnHold', 'filter_block' => 'grid_options_filter', 'width' => 100, ),
),
),
'Search' => Array(
'Icons' => Array(
'default' => 'icon16_item.png',
1 => 'icon16_pending.png',
5 => 'icon16_disabled.png',
'module' => 'core',
),
'Fields' => Array(
'OrderId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 70, ),
'OrderNumber' => Array('title' => 'la_col_OrderNumber', 'data_block' => 'grid_ordernumber_td', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'Status' => Array('title' => 'la_col_Status', 'filter_block' => 'grid_options_filter', 'filter_block' => 'grid_options_filter', 'width' => 100, ),
'OrderDate' => Array('title' => 'la_col_OrderDate', 'filter_block' => 'grid_date_range_filter', 'width' => 140, ),
'CustomerName' => Array('title' => 'la_col_CustomerName', 'data_block' => 'grid_userlink_td', 'user_field' => 'PortalUserId', 'filter_block' => 'grid_like_filter'),
'PaymentType' => Array('title' => 'la_col_PaymentType', 'data_block' => 'grid_billinglink_td', 'filter_block' => 'grid_options_filter'),
'TotalAmount' => Array('title' => 'la_col_TotalAmount', 'data_block' => 'grid_previewlink_td', 'filter_block' => 'grid_float_range_filter'),
'AffiliateUser' => Array( 'title' => 'la_col_AffiliateUser', 'data_block' => 'grid_userlink_td', 'user_field' => 'AffiliatePortalUserId', 'filter_block' => 'grid_user_like_filter'),
'OrderIP' => Array('title' => 'la_col_OrderIP', 'filter_block' => 'grid_like_filter'),
'Username' => Array('title' => 'la_col_Username', 'filter_block' => 'grid_user_like_filter'),
'PaymentAccount' => Array('title' => 'la_col_CreditCardNumber', 'filter_block' => 'grid_like_filter'),
),
),
),
);
\ No newline at end of file
Index: branches/5.1.x/units/orders/orders_tag_processor.php
===================================================================
--- branches/5.1.x/units/orders/orders_tag_processor.php (revision 13464)
+++ branches/5.1.x/units/orders/orders_tag_processor.php (revision 13465)
@@ -1,1488 +1,1491 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class OrdersTagProcessor extends kDBTagProcessor
{
/**
* Print location using only filled in fields
*
* @param Array $params
* @access public
*/
function PrintLocation($params)
{
$object =& $this->getObject($params);
$type = getArrayValue($params,'type');
if($type == 'Company')
{
return $this->PrintCompanyLocation($params);
}
$fields = Array('City','State','Zip','Country');
$ret = '';
foreach($fields as $field)
{
$value = $object->GetField($type.$field);
if ($field == 'Country' && $value) $ret .= '<br/>';
if($value) $ret .= $value.', ';
}
return rtrim($ret,', ');
}
function PrintCompanyLocation($params)
{
$ret = '';
$fields = Array ('City','State','ZIP','Country');
foreach ($fields as $field) {
$value = $this->Application->ConfigValue('Comm_'.$field);
if ($field == 'Country') {
- $sql = 'SELECT DestName
- FROM '.TABLE_PREFIX.'StdDestinations
- WHERE DestAbbr = '.$this->Conn->qstr($value);
- $value = $this->Application->Phrase( $this->Conn->GetOne($sql) );
+ $current_language = $this->Application->GetVar('m_lang');
+ $primary_language = $this->Application->GetDefaultLanguageId();
+
+ $sql = 'SELECT IF(l' . $current_language . '_Name = "", l' . $primary_language . '_Name, l' . $current_language . '_Name)
+ FROM ' . TABLE_PREFIX . 'CountryStates
+ WHERE IsoCode = ' . $this->Conn->qstr($value);
+ $value = $this->Conn->GetOne($sql);
}
if ($field == 'Country' && $value) {
$ret .= '<br/>';
}
if ($value) {
$ret .= $value.', ';
}
}
return rtrim($ret,', ');
}
function Orditems_LinkRemoveFromCart($params)
{
return $this->Application->HREF($this->Application->GetVar('t'), '', Array('pass' => 'm,orditems,ord', 'ord_event' => 'OnRemoveFromCart', 'm_cat_id'=>0));
}
function Orderitems_ProductLink($params)
{
$object =& $this->Application->recallObject('orditems');
$url_params = Array (
'p_id' => $object->GetDBField('ProductId'),
'pass' => 'm,p',
);
return $this->Application->HREF($params['template'], '', $url_params);
}
function Orderitems_ProductExists($params)
{
$object =& $this->Application->recallObject('orditems');
return $object->GetDBField('ProductId') > 0;
}
function PrintCart($params)
{
$o = '';
$params['render_as'] = $params['item_render_as'];
$tag_params = array_merge($params, Array ('per_page' => -1));
$o_items = $this->Application->ProcessParsedTag(rtrim('orditems.'.$this->Special, '.'), 'PrintList', $tag_params);
if ($o_items) {
$cart_params = array('name' => $params['header_render_as']);
$o = $this->Application->ParseBlock($cart_params);
$o .= $o_items;
$cart_params = array('name' => $params['footer_render_as']);
$o .= $this->Application->ParseBlock($cart_params);
} else {
$cart_params = array('name' => $params['empty_cart_render_as']);
$o = $this->Application->ParseBlock($cart_params);
}
return $o;
}
function ShopCartForm($params)
{
return $this->Application->ProcessParsedTag('m', 'ParseBlock', array_merge($params, Array(
'name' => 'kernel_form', 'PrefixSpecial'=>'ord'
)) );
}
function BackOrderFlag($params)
{
$object =& $this->Application->recallObject('orditems');
return $object->GetDBField('BackOrderFlag');
}
function OrderIcon($params)
{
$object =& $this->Application->recallObject('orditems');
if ($object->GetDBField('BackOrderFlag') == 0) {
return $params['ordericon'];
} else {
return $params['backordericon'];
}
}
function Status($params)
{
$status_map = Array(
'incomplete' => ORDER_STATUS_INCOMPLETE,
'pending' => ORDER_STATUS_PENDING,
'backorder' => ORDER_STATUS_BACKORDERS,
'toship' => ORDER_STATUS_TOSHIP,
'processed' => ORDER_STATUS_PROCESSED,
'denied' => ORDER_STATUS_DENIED,
'archived' => ORDER_STATUS_ARCHIVED,
);
$object =& $this->getObject($params);
$status = $object->GetDBField('Status');
$result = true;
if (isset($params['is'])) {
$result = $result && ($status == $status_map[$params['is']]);
}
if (isset($params['is_not'])) {
$result = $result && ($status != $status_map[$params['is_not']]);
}
return $result;
}
function ItemsInCart($params)
{
$object =& $this->getObject($params);
if ($object->GetDBField('Status') != ORDER_STATUS_INCOMPLETE) {
return 0;
}
$object =& $this->Application->recallObject('orditems', 'orditems_List');
/* @var $object kDBList */
return $object->RecordsCount;
}
function CartNotEmpty($params)
{
$object =& $this->getObject($params);
if ($object->GetDBField('Status') != ORDER_STATUS_INCOMPLETE) {
return 0;
}
$order_id = $this->Application->RecallVar('ord_id');
if ($order_id) {
$sql = 'SELECT COUNT(*)
FROM ' . TABLE_PREFIX . 'OrderItems
WHERE OrderId = ' . $order_id;
return $this->Conn->GetOne($sql);
}
return 0;
}
function CartIsEmpty($params)
{
return $this->CartNotEmpty($params) ? false : true;
}
function CartHasBackorders($params)
{
$object =& $this->getObject($params);
$sql = 'SELECT COUNT(*)
FROM ' . TABLE_PREFIX . 'OrderItems
WHERE OrderId = ' . $object->GetID() . '
GROUP BY BackOrderFlag';
$different_types = $this->Conn->GetCol($sql);
return count($different_types) > 1;
}
function PrintShippings($params)
{
$o = '';
$object =& $this->getObject($params);
$ord_id = $object->GetId();
$shipping_option = $object->GetDBField('ShippingOption');
$backorder_select = $shipping_option == 0 ? '0 As BackOrderFlag' : 'BackOrderFlag';
$order_items =& $this->Application->recallObject('orditems', 'orditems_List', Array('skip_autoload' => true) );
$oi_table = $order_items->TableName;
list($split_shipments, $limit_types) = $this->GetShippingLimitations($ord_id);
foreach ($split_shipments as $group => $data)
{
$query = 'UPDATE '.$oi_table.' SET SplitShippingGroup = '.$group.'
WHERE ProductId IN ('.implode(',', $data['Products']).')';
$this->Conn->Query($query);
$limitations_cache[$group] = $data['Types'];
}
$shipping_group_option = $object->GetDBField('ShippingGroupOption');
$shipping_group_select = $shipping_group_option == 0 ? '0 AS SplitShippingGroup' : 'SplitShippingGroup';
if (count($split_shipments) > 1) {
$this->Application->SetVar('shipping_limitations_apply', 1);
// different shipping limitations apply
if ($limit_types == 'NONE') {
// order can't be shipped with single shipping type
$this->Application->SetVar('shipping_limitations_apply', 2);
$shipping_group_select = 'SplitShippingGroup';
$shipping_group_option = 1;
}
}
else {
$this->Application->SetVar('shipping_limitations_apply', 0);
}
$weight_sql = 'IF(oi.Weight IS NULL, 0, oi.Weight * oi.Quantity)';
$query = 'SELECT
'.$backorder_select.',
oi.ProductName,
oi.ShippingTypeId,
SUM(oi.Quantity) AS TotalItems,
SUM('.$weight_sql.') AS TotalWeight,
SUM(oi.Price * oi.Quantity) AS TotalAmount,'.
// calculate free Totals => SUM(ALL) - SUM(PROMO) '
'SUM(oi.Quantity) - SUM(IF(p.MinQtyFreePromoShipping > 0 AND p.MinQtyFreePromoShipping <= oi.Quantity, oi.Quantity, 0)) AS TotalItemsPromo,
SUM('.$weight_sql.') - SUM(IF(p.MinQtyFreePromoShipping > 0 AND p.MinQtyFreePromoShipping <= oi.Quantity, '.$weight_sql.', 0)) AS TotalWeightPromo,
SUM(oi.Price * oi.Quantity) - SUM(IF(p.MinQtyFreePromoShipping > 0 AND p.MinQtyFreePromoShipping <= oi.Quantity, oi.Price * oi.Quantity, 0)) AS TotalAmountPromo,
'.$shipping_group_select.'
FROM '.$oi_table.' oi
LEFT JOIN '.$this->Application->getUnitOption('p', 'TableName').' p
ON oi.ProductId = p.ProductId
WHERE oi.OrderId = '.$ord_id.' AND p.Type = 1
GROUP BY BackOrderFlag, SplitShippingGroup
ORDER BY BackOrderFlag ASC, SplitShippingGroup ASC';
$shipments = $this->Conn->Query($query);
$block_params = Array();
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$block_params['user_country_id'] = $object->GetDBField('ShippingCountry');
$block_params['user_state_id'] = $object->GetDBField('ShippingState');
$block_params['user_zip'] = $object->GetDBField('ShippingZip');
$block_params['user_city'] = $object->GetDBField('ShippingCity');
$block_params['user_addr1'] = $object->GetDBField('ShippingAddress1');
$block_params['user_addr2'] = $object->GetDBField('ShippingAddress2');
$block_params['user_name'] = $object->GetDBField('ShippingTo');
if( ($block_params['user_addr1'] == '' || $block_params['user_city'] == '' ||
$block_params['user_zip'] == '' || $block_params['user_country_id'] == '') &&
getArrayValue($params, 'invalid_address_render_as'))
{
$block_params['name'] = $params['invalid_address_render_as'];
return $this->Application->ParseBlock($block_params);
}
$group = 1;
foreach ($shipments as $shipment) {
$where = array('OrderId = '.$ord_id);
if ($shipping_group_option != 0) {
$where[] = 'SplitShippingGroup = '.$shipment['SplitShippingGroup'];
}
if ($shipping_option > 0) { // not all together
$where[] = 'BackOrderFlag = '.$shipment['BackOrderFlag'];
}
$query = 'UPDATE '.$oi_table.' SET PackageNum = '.$group.'
'.($where ? 'WHERE '.implode(' AND ', $where) : '');
$this->Conn->Query($query);
$group++;
}
$this->Application->RemoveVar('LastShippings');
$group = 1;
$this->Application->SetVar('ShipmentsExists', 1);
foreach ($shipments as $shipment) {
$block_params['package_num'] = $group;
$block_params['limit_types'] = strpos($shipping_group_select, '0 AS') !== false ? $limit_types : $limitations_cache[$shipment['SplitShippingGroup']];
$this->Application->SetVar('ItemShipmentsExists', 1);
switch ($shipment['BackOrderFlag']) {
case 0:
if ( $this->CartHasBackOrders(Array()) && $shipping_option == 0 ) {
$block_params['shipment'] = $this->Application->Phrase('lu_all_available_backordered');
}
else {
$block_params['shipment'] = $this->Application->Phrase('lu_ship_all_available');;
}
break;
case 1:
$block_params['shipment'] = $this->Application->Phrase('lu_ship_all_backordered');;
break;
default:
$block_params['shipment'] = $this->Application->Phrase('lu_ship_backordered');
break;
}
$block_params['promo_weight_metric'] = $shipment['TotalWeightPromo'];
$block_params['promo_amount'] = $shipment['TotalAmountPromo'];
$block_params['promo_items'] = $shipment['TotalItemsPromo'];
$block_params['weight_metric'] = $shipment['TotalWeight'];
$block_params['weight'] = $shipment['TotalWeight'];
$regional =& $this->Application->recallObject('lang.current');
if ($block_params['weight_metric'] == '')
{
$block_params['weight'] = $this->Application->Phrase('lu_NotAvailable');
}
elseif ($regional->GetDBField('UnitSystem') == 1)
{
$block_params['weight'] .= ' '.$this->Application->Phrase('lu_kg');
}
elseif ($regional->GetDBField('UnitSystem') == 2)
{
list($pounds, $ounces) = Kg2Pounds($block_params['weight']);
$block_params['weight'] = $pounds.' '.$this->Application->Phrase('lu_pounds').' '.
$ounces.' '.$this->Application->Phrase('lu_ounces');
}
$block_params['items'] = $shipment['TotalItems'];
$iso = $this->GetISO($params['currency']);
$amount = $this->ConvertCurrency($shipment['TotalAmount'], $iso);
$amount = sprintf("%.2f", $amount);
// $block_params['amount'] = $this->AddCurrencySymbol($amount, $iso);
$block_params['amount'] = $shipment['TotalAmount'];
$block_params['field_name'] = $this->InputName(Array('field' => 'ShippingTypeId')).'['.($group).']';
$parsed_block = $this->Application->ParseBlock($block_params);
if($this->Application->GetVar('ItemShipmentsExists'))
{
$o .= $parsed_block;
}
else
{
$this->Application->SetVar('ShipmentsExists', 0);
if(getArrayValue($params, 'no_shipments_render_as'))
{
$block_params['name'] = $params['no_shipments_render_as'];
return $this->Application->ParseBlock($block_params);
}
}
$group++;
}
if(getArrayValue($params, 'table_header_render_as'))
{
$o = $this->Application->ParseBlock( Array('name' => $params['table_header_render_as']) ).$o;
}
if(getArrayValue($params, 'table_footer_render_as'))
{
$o .= $this->Application->ParseBlock( Array('name' => $params['table_footer_render_as']) );
}
return $o;
}
function GetShippingLimitations($ord_id)
{
/*$query = 'SELECT
c.CachedShippingLimitation
FROM '.TABLE_PREFIX.'OrderItems AS oi
LEFT JOIN '.TABLE_PREFIX.'Products AS p
ON p.ProductId = oi.ProductId
LEFT JOIN '.TABLE_PREFIX.'CategoryItems AS ci
ON ci.ItemResourceId = p.ResourceId
LEFT JOIN '.TABLE_PREFIX.'Category AS c
ON c.CategoryId = ci.CategoryId
WHERE
oi.OrderId = '.$ord_id.'
AND
ci.PrimaryCat = 1
AND
c.CachedShippingMode = 1;';
$cat_limitations = $this->Conn->GetCol($query);*/
$cat_limitations = array();
$query = 'SELECT ShippingLimitation, ShippingMode, oi.ProductId as ProductId
FROM '.TABLE_PREFIX.'Products AS p
LEFT JOIN '.TABLE_PREFIX.'OrderItems AS oi ON
oi.ProductId = p.ProductId
WHERE oi.OrderId = '.$ord_id.' AND p.Type = 1'; // .' AND p.ShippingMode = 1';
$limitations = $this->Conn->Query($query, 'ProductId');
$split_shipments = array();
$limit = false;
$types_index = array();
// group products by shipping type range and caculate intersection of all types available for ALL products
// the intersaction caclulation is needed to determine if the order can be shipped with single type or not
if ($limitations) {
$limit_types = null;
foreach ($limitations as $product_id => $row)
{
// if shipping types are limited - get the types
$types = $row['ShippingLimitation'] != '' ? explode('|', substr($row['ShippingLimitation'], 1, -1)) : array('ANY');
// if shipping is NOT limited to selected types (default - so products with no limitations at all also counts)
if ($row['ShippingMode'] == 0) {
array_push($types, 'ANY'); // can be shipped with ANY (literally) type
$types = array_unique($types);
}
//adding product id to split_shipments group by types range
$i = array_search(serialize($types), $types_index);
if ($i === false) {
$types_index[] = serialize($types);
$i = count($types_index)-1;
}
$split_shipments[$i]['Products'][] = $product_id;
$split_shipments[$i]['Types'] = serialize($types);
if ($limit_types == null) { //it is null only when we process first item with limitations
$limit_types = $types; //initial scope
}
// this is to avoid ANY intersect CUST_1 = (), but allows ANY intersect CUST_1,ANY = (ANY)
if (in_array('ANY', $limit_types) && !in_array('ANY', $types)) {
array_splice($limit_types, array_search('ANY', $limit_types), 1, $types);
}
// this is to avoid CUST_1 intersect ANY = (), but allows CUST_1 intersect CUST_1,ANY = (ANY)
if (!in_array('ANY', $limit_types) && in_array('ANY', $types)) {
array_splice($types, array_search('ANY', $types), 1, $limit_types);
}
$limit_types = array_intersect($limit_types, $types);
}
$limit_types = count($limit_types) > 0 ? serialize(array_unique($limit_types)) : 'NONE';
}
return array($split_shipments, $limit_types);
}
function PaymentTypeForm($params)
{
$object =& $this->getObject($params);
$payment_type_id = $object->GetDBField('PaymentType');
if($payment_type_id)
{
$this->Application->SetVar('pt_id', $payment_type_id);
$block_params['name'] = $this->SelectParam($params, $this->UsingCreditCard($params) ? 'cc_render_as,block_cc' : 'default_render_as,block_default' );
return $this->Application->ParseBlock($block_params);
}
return '';
}
/**
* Returns true in case if credit card was used as payment type for order
*
* @param Array $params
* @return bool
*/
function UsingCreditCard($params)
{
$object =& $this->getObject($params);
$pt = $object->GetDBField('PaymentType');
if (!$pt) {
$pt = $this->Conn->GetOne('SELECT PaymentTypeId FROM '.TABLE_PREFIX.'PaymentTypes WHERE IsPrimary = 1');
$object->SetDBField('PaymentType', $pt);
}
$pt_table = $this->Application->getUnitOption('pt','TableName');
$sql = 'SELECT GatewayId FROM %s WHERE PaymentTypeId = %s';
$gw_id = $this->Conn->GetOne( sprintf( $sql, $pt_table, $pt ) );
$sql = 'SELECT RequireCCFields FROM %s WHERE GatewayId = %s';
return $this->Conn->GetOne( sprintf($sql, TABLE_PREFIX.'Gateways', $gw_id) );
}
function PaymentTypeDescription($params)
{
return $this->Application->ProcessParsedTag('pt', 'Field', array_merge($params, Array(
'field' => 'Description'
)) );
}
function PaymentTypeInstructions($params)
{
return $this->Application->ProcessParsedTag('pt', 'Field', array_merge($params, Array(
'field' => 'Instructions'
)) );
}
function PrintMonthOptions($params)
{
$object =& $this->getObject($params);
$date = explode('/', $object->GetDBField($params['date_field_name']));
if (!$date || sizeof($date) != 2) {
$date=array("", "");
}
$o = '';
$params['name'] = $params['block'];
for ($i = 1; $i <= 12; $i++) {
$month_str = str_pad($i, 2, "0", STR_PAD_LEFT);
if ($date[0] == $month_str) {
$params['selected'] = ' selected';
}else {
$params['selected'] = '';
}
$params['mm'] = $month_str;
$o .= $this->Application->ParseBlock($params);
}
return $o;
}
function PrintYearOptions($params)
{
$object =& $this->getObject($params);
$value = $object->GetDBField( $params['field'] );
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$o = '';
$this_year = adodb_date('y');
for($i = $this_year; $i <= $this_year + 10; $i++)
{
$year_str = str_pad($i, 2, '0', STR_PAD_LEFT);
$block_params['selected'] = ($value == $year_str) ? $params['selected'] : '';
$block_params['key'] = $year_str;
$block_params['option'] = $year_str;
$o .= $this->Application->ParseBlock($block_params);
}
return $o;
}
function PrintMyOrders($params)
{
}
/**
* Checks, that order data can be editied based on it's status
*
* @param Array $params
* @return bool
*/
function OrderEditable($params)
{
$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
if ($this->Application->IsTempMode($this->Prefix, $this->Special)) {
$table_name = $this->Application->GetTempName($table_name, 'prefix:' . $this->Prefix);
}
// use direct select here (not $this->getObject) because this tag is
// used even before "combined_header" block is used (on "orders_edit_items" template)
$sql = 'SELECT Status, PaymentType
FROM ' . $table_name . '
WHERE ' . $id_field . ' = ' . $this->Application->GetVar( $this->getPrefixSpecial() . '_id' );
$order_data = $this->Conn->GetRow($sql);
if (!$order_data) {
// new order adding, when even not in database
return true;
}
switch ($order_data['Status']) {
case ORDER_STATUS_INCOMPLETE:
$ret = true;
break;
case ORDER_STATUS_PENDING:
case ORDER_STATUS_BACKORDERS:
$sql = 'SELECT PlacedOrdersEdit
FROM ' . $this->Application->getUnitOption('pt', 'TableName') . '
WHERE ' . $this->Application->getUnitOption('pt', 'IDField') . ' = ' . $order_data['PaymentType'];
$ret = $this->Conn->GetOne($sql);
break;
default:
$ret = false;
break;
}
return $ret;
}
function CheckoutSteps($params)
{
$steps = explode(',', $params['steps']);
foreach ($steps as $key => $item)
{
$templates[$key] = trim($item);
}
$templates = explode(',', $params['templates']);
foreach ($templates as $key => $item)
{
$templates[$key] = trim($item);
}
$total_steps = count($templates);
$t = $this->Application->GetVar('t');
$o = '';
$block_params = array();
$i = 0;
$passed_current = preg_match("/".preg_quote($templates[count($templates)-1], '/')."/", $t);
foreach ($steps as $step => $name)
{
if (preg_match("/".preg_quote($templates[$step], '/')."/", $t)) {
$block_params['name'] = $this->SelectParam($params, 'current_step_render_as,block_current_step');
$passed_current = true;
}
else {
$block_params['name'] = $passed_current ? $this->SelectParam($params, 'render_as,block') : $this->SelectParam($params, 'passed_step_render_as,block_passed_step');
}
$block_params['title'] = $this->Application->Phrase($name);
$block_params['template'] = $templates[$i];
$block_params['template_link'] = $this->Application->HREF($templates[$step], '', Array('pass'=>'m'));
$block_params['next_step_template'] = isset($templates[$i + 1]) ? $templates[$i + 1] : '';
$block_params['number'] = $i + 1;
$i++;
$o.= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
function ShowOrder($params)
{
$order_params = $this->prepareTagParams($params);
// $order_params['Special'] = 'myorders';
// $order_params['PrefixSpecial'] = 'ord.myorders';
$order_params['name'] = $this->SelectParam($order_params, 'render_as,block');
// $this->Application->SetVar('ord.myorders_id', $this->Application->GetVar('ord_id'));
$object =& $this->getObject($params);
if (!$object->GetDBField('OrderId')) {
return;
}
return $this->Application->ParseBlock($order_params);
}
function BuildListSpecial($params)
{
if ($this->Special != '') {
return $this->Special;
}
$list_unique_key = $this->getUniqueListKey($params);
if ($list_unique_key == '') {
return parent::BuildListSpecial($params);
}
return crc32($list_unique_key);
}
function ListOrders($params)
{
$o = '';
$params['render_as'] = $params['item_render_as'];
$o_orders = $this->PrintList2($params);
if ($o_orders) {
$orders_params = array('name' => $params['header_render_as']);
$o = $this->Application->ParseBlock($orders_params);
$o .= $o_orders;
} else {
$orders_params = array('name' => $params['empty_myorders_render_as']);
$o = $this->Application->ParseBlock($orders_params);
}
return $o;
}
function HasRecentOrders($params)
{
$per_page = $this->SelectParam($params, 'per_page,max_items');
if ($per_page !== false) {
$params['per_page'] = $per_page;
}
return (int)$this->TotalRecords($params) > 0 ? 1 : 0;
}
function ListOrderItems($params)
{
$prefix_special = rtrim('orditems.'.$this->Special, '.');
return $this->Application->ProcessParsedTag($prefix_special, 'PrintList', array_merge($params, Array(
'per_page' => -1
)) );
}
function OrdersLink(){
$params['pass']='m,ord';
$main_processor =& $this->Application->RecallObject('m_TagProcessor');
return $main_processor->Link($params);
}
function PrintAddresses($params)
{
$object =& $this->getObject($params);
$address_list =& $this->Application->recallObject('addr','addr_List', Array('per_page'=>-1, 'skip_counting'=>true) );
$address_list->Query();
$address_id = $this->Application->GetVar($params['type'].'_address_id');
if (!$address_id) {
$sql = 'SELECT '.$address_list->IDField.'
FROM '.$address_list->TableName.'
WHERE PortalUserId = '.$object->GetDBField('PortalUserId').' AND LastUsedAs'.ucfirst($params['type']).' = 1';
$address_id = (int)$this->Conn->GetOne($sql);
}
$ret = '';
$block_params = $this->prepareTagParams($params);
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$address_list->GoFirst();
while (!$address_list->EOL()) {
$selected = ($address_list->GetID() == $address_id);
if ($selected && $address_list->GetDBField('IsProfileAddress')) {
$this->Application->SetVar($this->Prefix.'_IsProfileAddress', true);
}
$block_params['key'] = $address_list->GetID();
$block_params['value'] = $address_list->GetDBField('ShortAddress');
$block_params['selected'] = $selected ? ' selected="selected"' : '';
$ret .= $this->Application->ParseBlock($block_params, 1);
$address_list->GoNext();
}
return $ret;
}
function PrefillRegistrationFields($params)
{
if ( $this->Application->GetVar('fields_prefilled') ) {
return false;
}
$user =& $this->Application->recallObject('u', null, Array ('skip_autoload' => true));
/* @var $user kDBItem */
$order =& $this->Application->recallObject($this->Prefix . '.last');
$order_prefix = $params['type'] == 'billing' ? 'Billing' : 'Shipping';
$order_fields = Array (
'To', 'Company', 'Phone', 'Fax', 'Email', 'Address1',
'Address2', 'City', 'State', 'Zip', 'Country'
);
$names = explode(' ', $order->GetDBField($order_prefix.'To'), 2);
if (!$user->GetDBField('FirstName')) $user->SetDBField('FirstName', getArrayValue($names, 0) );
if (!$user->GetDBField('LastName')) $user->SetDBField('LastName', getArrayValue($names, 1) );
if (!$user->GetDBField('Company')) $user->SetDBField('Company', $order->GetDBField($order_prefix.'Company') );
if (!$user->GetDBField('Phone')) $user->SetDBField('Phone', $order->GetDBField($order_prefix.'Phone') );
if (!$user->GetDBField('Fax')) $user->SetDBField('Fax', $order->GetDBField($order_prefix.'Fax') );
if (!$user->GetDBField('Email')) $user->SetDBField('Email', $order->GetDBField($order_prefix.'Email') );
if (!$user->GetDBField('Street')) $user->SetDBField('Street', $order->GetDBField($order_prefix.'Address1') );
if (!$user->GetDBField('Street2')) $user->SetDBField('Street2', $order->GetDBField($order_prefix.'Address2') );
if (!$user->GetDBField('City')) $user->SetDBField('City', $order->GetDBField($order_prefix.'City') );
if (!$user->GetDBField('State')) $user->SetDBField('State', $order->GetDBField($order_prefix.'State') );
if (!$user->GetDBField('Zip')) $user->SetDBField('Zip', $order->GetDBField($order_prefix.'Zip') );
if (!$user->GetDBField('Country')) $user->SetDBField('Country', $order->GetDBField($order_prefix.'Country') );
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
- $cs_helper->PopulateStates(new kEvent('u:OnBuild') , 'State', 'Country');
+ $cs_helper->PopulateStates(new kEvent('u:OnBuild'), 'State', 'Country');
}
function UserLink($params)
{
$object =& $this->getObject($params);
$user_id = $object->GetDBField( $params['user_field'] );
if ($user_id) {
$url_params = Array (
'm_opener' => 'd',
'u_mode' => 't',
'u_event' => 'OnEdit',
'u_id' => $user_id,
'pass' => 'all,u',
'no_pass_through' => 1,
);
return $this->Application->HREF($params['edit_template'], '', $url_params);
}
}
function UserFound($params)
{
$virtual_users = Array(-1,-2, 0);
$object =& $this->getObject($params);
return !in_array( $object->GetDBField( $params['user_field'] ) , $virtual_users );
}
/**
* Returns a link for editing order
*
* @param Array $params
* @return string
*/
function OrderLink($params)
{
$object =& $this->getObject($params);
$url_params = Array (
'm_opener' => 'd',
$this->Prefix.'_mode' => 't',
$this->Prefix.'_event' => 'OnEdit',
$this->Prefix.'_id' => $object->GetID(),
'pass' => 'all,'.$this->Prefix,
'no_pass_through' => 1,
);
return $this->Application->HREF($params['edit_template'], '', $url_params);
}
function HasOriginalAmount($params)
{
$object =& $this->getObject($params);
$original_amount = $object->GetDBField('OriginalAmount');
return $original_amount && ($original_amount != $object->GetDBField('TotalAmount') );
}
/**
* Returns true, when order has tangible items
*
* @param Array $params
* @return bool
*
* @todo This is copy from OrdersItem::HasTangibleItems. Copy to helper (and create it) and use here.
*/
function OrderHasTangibleItems($params)
{
$object =& $this->getObject($params);
if ($object->GetID() == FAKE_ORDER_ID) {
return false;
}
$sql = 'SELECT COUNT(*)
FROM '.TABLE_PREFIX.'OrderItems orditems
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = orditems.ProductId
WHERE (orditems.OrderId = '.$object->GetID().') AND (p.Type = '.PRODUCT_TYPE_TANGIBLE.')';
return $this->Conn->GetOne($sql) ? true : false;
}
function ShipmentsExists($params)
{
return $this->Application->GetVar('ShipmentsExists') ? 1 : 0;
}
function Field($params)
{
$value = parent::Field($params);
$field = $this->SelectParam($params,'name,field');
if( ($field == 'PaymentAccount') && getArrayValue($params,'masked') )
{
$value = str_repeat('X',12).substr($value,-4);
}
return $value;
}
function CartHasError($params)
{
return $this->Application->GetVar('checkout_error') > 0;
}
function CheckoutError($params)
{
$error_codes = Array (
1 => 'state_changed',
2 => 'qty_unavailable',
3 => 'outofstock',
4 => 'invalid_code',
5 => 'code_expired',
6 => 'min_qty',
7 => 'code_removed',
8 => 'code_removed_automatically',
9 => 'changed_after_login',
10 => 'coupon_applied',
104 => 'invalid_gc_code',
105 => 'gc_code_expired',
107 => 'gc_code_removed',
108 => 'gc_code_removed_automatically',
110 => 'gift_certificate_applied',
);
$error_param = $error_codes[ $this->Application->GetVar('checkout_error') ];
return $this->Application->Phrase($params[$error_param]);
}
function GetFormAction($params)
{
$object =& $this->getObject($params);
/* @var $object OrdersItem */
$gw_data = $object->getGatewayData($params['payment_type_id']);
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
/* @var $gateway_object kGWBase */
return $gateway_object->getFormAction($gw_data['gw_params']);
}
function GetFormHiddenFields($params)
{
$object =& $this->getObject($params);
/* @var $object OrdersItem */
$gw_data = $object->getGatewayData(array_key_exists('payment_type_id', $params) ? $params['payment_type_id'] : null);
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$tpl = '<input type="hidden" name="%s" value="%s" />'."\n";
$hidden_fields = $gateway_object->getHiddenFields($object->FieldValues, $params, $gw_data['gw_params']);
$ret = '';
if (!is_array($hidden_fields)) {
return $hidden_fields;
}
foreach($hidden_fields as $hidden_name => $hidden_value)
{
$ret .= sprintf($tpl, $hidden_name, $hidden_value);
}
return $ret;
}
function NeedsPlaceButton($params)
{
$object =& $this->getObject($params);
$gw_data = $object->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
return $gateway_object->NeedPlaceButton($object->FieldValues, $params, $gw_data['gw_params']);
}
function HasGatewayError($params)
{
return $this->Application->RecallVar('gw_error');
}
function ShowGatewayError($params)
{
$ret = $this->Application->RecallVar('gw_error');
$this->Application->RemoveVar('gw_error');
return $ret;
}
function ShippingType($params)
{
$object =& $this->getObject($params);
$shipping_info = unserialize( $object->GetDBField('ShippingInfo') );
if (count($shipping_info) > 1) {
return $this->Application->Phrase('lu_MultipleShippingTypes');
}
$shipping_info = array_shift($shipping_info);
return $shipping_info['ShippingName'];
}
function DiscountHelpLink($params)
{
$params['pass'] = 'all,orditems';
$params['m_cat_id'] = 0;
$m_tag_processor =& $this->Application->recallObject('m_TagProcessor');
return $m_tag_processor->Link($params);
}
function DiscountField($params)
{
$orditems =& $this->Application->recallObject( 'orditems' );
$item_data = $orditems->GetDBField('ItemData');
if(!$item_data) return '';
$item_data = unserialize($item_data);
$discount_prefix = ($item_data['DiscountType'] == 'coupon') ? 'coup' : 'd';
$discount =& $this->Application->recallObject($discount_prefix, null, Array('skip_autoload' => true));
if(!$discount->isLoaded())
{
$discount->Load($item_data['DiscountId']);
}
return $discount->GetField( $this->SelectParam($params, 'field,name') );
}
function HasDiscount($params)
{
$object =& $this->getObject($params);
return (float)$object->GetDBField('DiscountTotal') ? 1 : 0;
}
/**
* Allows to check if required product types are present in order
*
* @param Array $params
*/
function HasProductType($params)
{
$product_types = Array('tangible' => 1, 'subscription' => 2, 'service' => 3, 'downloadable' => 4, 'package' => 5, 'gift' => 6);
$object =& $this->getObject($params);
$sql = 'SELECT COUNT(*)
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE (oi.OrderId = '.$object->GetID().') AND (p.Type = '.$product_types[ $params['type'] ].')';
return $this->Conn->GetOne($sql);
}
function PrintSerializedFields($params)
{
$object =& $this->getObject($params);
$field = $this->SelectParam($params, 'field');
if (!$field) $field = $this->Application->GetVar('field');
$data = unserialize($object->GetDBField($field));
$o = '';
$block_params['name'] = $params['render_as'];
foreach ($data as $field => $value) {
$block_params['field'] = $field;
$block_params['value'] = $value;
$o .= $this->Application->ParseBlock($block_params);
}
return $o;
}
function OrderProductEmail($params)
{
$order =& $this->Application->recallObject('ord');
$orditems =& $this->Application->recallObject('orditems');
$sql = 'SELECT ResourceId
FROM '.TABLE_PREFIX.'Products
WHERE ProductId = '.$orditems->GetDBField('ProductId');
$resource_id = $this->Conn->GetOne($sql);
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$custom_fields = $this->Application->getUnitOption('p', 'CustomFields');
$custom_name = $ml_formatter->LangFieldName('cust_'.array_search($params['msg_custom_field'], $custom_fields));
$sql = 'SELECT '.$custom_name.'
FROM '.$this->Application->getUnitOption('p-cdata', 'TableName').'
WHERE ResourceId = '.$resource_id;
$message_template = $this->Conn->GetOne($sql);
if (!$message_template || trim($message_template) == '') {
// message template missing
return ;
}
$from_name = strip_tags($this->Application->ConfigValue('Site_Name'));
$from_email = $this->Application->ConfigValue('Smtp_AdminMailFrom');
$to_name = $order->GetDBField('BillingTo');
$to_email = $order->GetDBField('BillingEmail');
if (!$to_email) {
// billing email is empty, then use user's email
$sql = 'SELECT Email
FROM '.$this->Application->getUnitOption('u', 'TableName').'
WHERE PortalUserId = '.$order->GetDBField('PortalUserId');
$to_email = $this->Conn->GetOne($sql);
}
$esender =& $application->recallObject('EmailSender.-product');
/* @var $esender kEmailSendingHelper */
$esender->SetFrom($from_email, $from_name);
$esender->AddTo($to_email, $to_name);
$email_events_eh =& $this->Application->recallObject('emailevents_EventHandler');
/* @var $email_events_eh EmailEventsEventsHandler */
list ($message_headers, $message_body) = $email_events_eh->ParseMessageBody($message_template, Array());
if (!trim($message_body)) {
// message body missing
return false;
}
foreach ($message_headers as $header_name => $header_value) {
$esender->SetEncodedHeader($header_name, $header_value);
}
$esender->SetHTML($message_body);
$esender->Deliver();
}
function PrintTotals($params)
{
$order =& $this->getObject($params);
$totals = array();
if (ABS($order->GetDBField('SubTotal') - $order->GetDBField('AmountWithoutVAT')) > 0.01) {
$totals[] = 'products';
}
$has_tangible = $this->OrderHasTangibleItems($params);
if ($has_tangible && $order->GetDBField('ShippingTaxable')) {
$totals[] = 'shipping';
}
if ($order->GetDBField('ProcessingFee') > 0 && $order->GetDBField('ProcessingTaxable')) {
$totals[] = 'processing';
}
if ($order->GetDBField('ReturnTotal') > 0 && $order->GetDBField('ReturnTotal')) {
$totals[] = 'return';
}
$totals[] = 'sub_total';
if ($order->GetDBField('VAT') > 0) {
$totals[] = 'vat';
}
if ($has_tangible && !$order->GetDBField('ShippingTaxable')) {
$totals[] = 'shipping';
}
if ($order->GetDBField('ProcessingFee') > 0 && !$order->GetDBField('ProcessingTaxable')) {
$totals[] = 'processing';
}
$o = '';
foreach ($totals as $type)
{
if ($element = getArrayValue($params, $type.'_render_as')) {
$o .= $this->Application->ParseBlock( array('name' => $element), 1 );
}
}
return $o;
}
function ShowDefaultAddress($params)
{
$address_type = ucfirst($params['type']);
if ($this->Application->GetVar('check_'.strtolower($address_type).'_address')) {
// form type doesn't match check type, e.g. shipping check on billing form
return '';
}
// for required field highlighting on form when no submit made
$this->Application->SetVar('check_'.strtolower($address_type).'_address', 'true');
/*if ((strtolower($address_type) == 'billing') && $this->UsingCreditCard($params)) {
$this->Application->SetVar('check_credit_card', 'true');
}*/
$this->Application->HandleEvent(new kEvent('ord:SetStepRequiredFields'));
$user_id = $this->Application->RecallVar('user_id');
$sql = 'SELECT AddressId
FROM '.TABLE_PREFIX.'Addresses
WHERE PortalUserId = '.$user_id.' AND LastUsedAs'.$address_type.' = 1';
$address_id = $this->Conn->GetOne($sql);
if (!$address_id) {
return '';
}
$addr_list =& $this->Application->recallObject('addr', 'addr_List', Array('per_page'=>-1, 'skip_counting'=>true) );
$addr_list->Query();
$object =& $this->getObject();
if (!$addr_list->CheckAddress($object->FieldValues, $address_type)) {
$addr_list->CopyAddress($address_id, $address_type);
}
}
function IsProfileAddress($params)
{
$object =& $this->getObject($params);
$address_type = ucfirst($params['type']);
return $object->IsProfileAddress($address_type);
}
function HasPayPalSubscription($params)
{
$object =& $this->getObject($params);
$sql = 'SELECT COUNT(*)
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE (oi.OrderId = '.$object->GetID().') AND (p.PayPalRecurring = 1)';
return $this->Conn->GetOne($sql);
}
function GetPayPalSubscriptionForm($params)
{
$object =& $this->getObject($params);
$gw_data = $object->getGatewayData($params['payment_type_id']);
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$sql = 'SELECT oi.*
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE (oi.OrderId = '.$object->GetID().') AND (p.PayPalRecurring = 1)';
$order_item = $this->Conn->GetRow($sql);
$order_item_data = unserialize($order_item['ItemData']);
$cycle = ceil($order_item_data['Duration'] / 86400);
$cycle_units = 'D';
$item_data = $object->FieldValues;
$item_data['item_name'] = $order_item['ProductName'];
$item_data['item_number'] = $order_item['OrderItemId'];
$item_data['custom'] = $order_item['OrderId'];
$item_data['a1'] = '';
$item_data['p1'] = '';
$item_data['t1'] = '';
$item_data['a2'] = '';
$item_data['p2'] = '';
$item_data['t2'] = '';
$item_data['a3'] = $order_item['Price']; //rate
$item_data['p3'] = $cycle; //cycle
$item_data['t3'] = $cycle_units; //cycle units D (days), W (weeks), M (months), Y (years)
$item_data['src'] = '1'; // Recurring payments. If set to 1, the payment will recur unless your customer cancels the subscription before the end of the billing cycle.
$item_data['sra'] = '1'; // Reattempt on failure. If set to 1, and the payment fails, the payment will be reattempted two more times. After the third failure, the subscription will be cancelled.
$item_data['srt'] = ''; // Recurring Times. This is the number of payments which will occur at the regular rate.
$hidden_fields = $gateway_object->getSubscriptionFields($item_data, $params, $gw_data['gw_params']);
$ret = '';
if (!is_array($hidden_fields)) {
return $hidden_fields;
}
$tpl = '<input type="hidden" name="%s" value="%s" />'."\n";
foreach($hidden_fields as $hidden_name => $hidden_value)
{
$ret .= sprintf($tpl, $hidden_name, $hidden_value);
}
return $ret;
}
function UserHasPendingOrders($params)
{
$sql = 'SELECT OrderId FROM '.$this->Application->getUnitOption($this->Prefix, 'TableName').'
WHERE PortalUserId = '.$this->Application->RecallVar('user_id').'
AND Status = '.ORDER_STATUS_PENDING;
return $this->Conn->GetOne($sql) ? 1 : 0;
}
function AllowAddAddress($params)
{
$user =& $this->Application->recallObject('u.current');
if ($user->GetDBField('cust_shipping_addr_block')) return false;
$address_list =& $this->Application->recallObject('addr','addr_List', Array('per_page'=>-1, 'skip_counting'=>true) );
$address_list->Query();
$max = $this->Application->ConfigValue('MaxAddresses');
return $max <= 0 ? true : $address_list->RecordsCount < $max;
}
function FreePromoShippingAvailable($params)
{
$object =& $this->Application->recallObject('orditems');
$free_ship = $object->GetDBField('MinQtyFreePromoShipping');
$tangible = ($object->GetDBField('Type') == 1)? 1 : 0;
return ($tangible && ($free_ship > 0 && $free_ship <= $object->GetDBField('Quantity')))? 1 : 0;
}
/**
* Creates link for removing coupon or gift certificate
*
* @param Array $params
* @return string
*/
function RemoveCouponLink($params)
{
$type = strtolower($params['type']);
$url_params = Array (
'pass' => 'm,ord',
'ord_event' => ($type == 'coupon') ? 'OnRemoveCoupon' : 'OnRemoveGiftCertificate',
'm_cat_id' => 0,
);
return $this->Application->HREF('', '', $url_params);
}
/**
* Calculates total weight of items in shopping cart
*
* @param Array $params
* @return float
*/
function TotalOrderWeight($params)
{
$object =& $this->getObject();
/* @var $object kDBItem */
$sql = 'SELECT SUM( IF(oi.Weight IS NULL, 0, oi.Weight * oi.Quantity) )
FROM '.TABLE_PREFIX.'OrderItems oi
WHERE oi.OrderId = '.$object->GetID();
$total_weight = $this->Conn->GetOne($sql);
if ($total_weight == '') {
// zero weight -> return text about it
return $this->Application->Phrase('lu_NotAvailable');
}
$regional =& $this->Application->recallObject('lang.current');
switch ($regional->GetDBField('UnitSystem')) {
case 1:
// metric system -> add kg sign
$total_weight .= ' '.$this->Application->Phrase('lu_kg');
break;
case 2:
// uk system -> convert to pounds
list($pounds, $ounces) = Kg2Pounds($total_weight);
$total_weight = $pounds.' '.$this->Application->Phrase('lu_pounds').' '.$ounces.' '.$this->Application->Phrase('lu_ounces');
break;
}
return $total_weight;
}
function InitCatalogTab($params)
{
$tab_params['mode'] = $this->Application->GetVar('tm'); // single/multi selection possible
$tab_params['special'] = $this->Application->GetVar('ts'); // use special for this tab
$tab_params['dependant'] = $this->Application->GetVar('td'); // is grid dependant on categories grid
// set default params (same as in catalog)
if ($tab_params['mode'] === false) $tab_params['mode'] = 'multi';
if ($tab_params['special'] === false) $tab_params['special'] = '';
if ($tab_params['dependant'] === false) $tab_params['dependant'] = 'yes';
// pass params to block with tab content
$params['name'] = $params['render_as'];
$params['prefix'] = trim($this->Prefix.'.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.');
$params['cat_prefix'] = trim('c.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.');
$params['tab_mode'] = $tab_params['mode'];
$params['grid_name'] = ($tab_params['mode'] == 'multi') ? $params['default_grid'] : $params['radio_grid'];
$params['tab_dependant'] = $tab_params['dependant'];
$params['show_category'] = $tab_params['special'] == 'showall' ? 1 : 0; // this is advanced view -> show category name
return $this->Application->ParseBlock($params, 1);
}
/**
* Checks if required payment method is available
*
* @param Array $params
* @return bool
*/
function HasPaymentGateway($params)
{
static $payment_types = Array ();
$gw_name = $params['name'];
if (!array_key_exists($gw_name, $payment_types)) {
$sql = 'SELECT pt.PaymentTypeId, pt.PortalGroups
FROM '.TABLE_PREFIX.'PaymentTypes pt
LEFT JOIN '.TABLE_PREFIX.'Gateways g ON pt.GatewayId = g.GatewayId
WHERE (g.Name = '.$this->Conn->qstr($params['name']).') AND (pt.Status = '.STATUS_ACTIVE.')';
$payment_types[$gw_name] = $this->Conn->GetRow($sql);
}
if (!$payment_types[$gw_name]) {
return false;
}
$pt_groups = explode(',', substr($payment_types[$gw_name]['PortalGroups'], 1, -1));
$user_groups = explode(',', $this->Application->RecallVar('UserGroups'));
return array_intersect($user_groups, $pt_groups) ? $payment_types[$gw_name]['PaymentTypeId'] : false;
}
function DisplayPaymentGateway($params)
{
$payment_type_id = $this->HasPaymentGateway($params);
if (!$payment_type_id) {
return '';
}
$object =& $this->getObject($params);
/* @var $object OrdersItem */
$gw_data = $object->getGatewayData($payment_type_id);
$block_params = $gw_data['gw_params'];
$block_params['name'] = $params['render_as'];
$block_params['payment_type_id'] = $payment_type_id;
return $this->Application->ParseBlock($block_params);
}
/**
* Checks, that USPS returned valid label
*
* @param Array $params
* @return bool
*/
function USPSLabelFound($params)
{
$object =& $this->getObject($params);
/* @var $object kDBItem */
$full_path = USPS_LABEL_FOLDER . $object->GetDBField( $params['field'] ) . '.pdf';
return file_exists($full_path) && is_file($full_path);
}
/**
* Prints USPS errors from session
*
* @param Array $params
* @return string
*/
function PrintUSPSErrors($params)
{
$o = '';
$ses_usps_erros = Array();
$ses_usps_erros = unserialize($this->Application->RecallVar('usps_errors'));
if ( count($ses_usps_erros) > 0 && is_array($ses_usps_erros)) {
foreach ( $ses_usps_erros as $order_number => $error_description ) {
$block_params = Array();
$block_params['name'] = $params['render_as'];
$block_params['order_number'] = $order_number;
$block_params['error_description'] = $error_description;
$o.=$this->Application->ParseBlock($block_params, 1);
}
$this->Application->RemoveVar('usps_errors');
}
return $o;
}
}
\ No newline at end of file
Index: branches/5.1.x/units/addresses/addresses_event_handler.php
===================================================================
--- branches/5.1.x/units/addresses/addresses_event_handler.php (revision 13464)
+++ branches/5.1.x/units/addresses/addresses_event_handler.php (revision 13465)
@@ -1,321 +1,321 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class AddressesEventHandler extends kDBEventHandler {
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
// user can view any form on front-end
'OnItemBuild' => Array('subitem' => true),
'OnUpdate' => Array('subitem' => true),
'OnCreate' => Array('subitem' => true),
'OnDelete' => Array('subitem' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Get's special of main item for linking with subitem
*
* @param kEvent $event
* @return string
*/
function getMainSpecial(&$event)
{
return '';
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
if ($this->Application->isAdminUser) {
return ;
}
$object =& $event->getObject();
$user_id = $this->Application->RecallVar('user_id');
$object->addFilter('myitems_user','%1$s.PortalUserId = '.$user_id);
}
/**
* Makes "use as $type" mark unique among user addresses
*
* @param kDBItem $object
* @param string $type
*/
function processLastUsed(&$object, $type)
{
$is_last = $object->GetDBField('LastUsedAs'.$type);
if ($is_last) {
$fields_hash = Array (
'LastUsedAs'.$type => 0,
);
$this->Conn->doUpdate($fields_hash, $object->TableName, 'PortalUserId = '.$object->GetDBField('PortalUserId'));
}
}
/**
* Ensures, that user have only one "use as billing" / "use as shipping" address
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
if (!$object->isLoaded() || !$this->checkItemStatus($event)) {
// not trivially loaded object OR not current user address
$event->status = erPERM_FAIL;
return ;
}
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $cs_helper->CheckStateField($event, 'State', 'Country');
+ $cs_helper->PopulateStates($event, 'State', 'Country');
+
$this->processLastUsed($object, 'Shipping');
$this->processLastUsed($object, 'Billing');
}
function OnUpdate(&$event)
{
- $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
- /* @var $cs_helper kCountryStatesHelper */
-
- $cs_helper->CheckStateField($event, 'State', 'Country');
-
parent::OnUpdate($event);
$this->setNextTemplate($event);
}
/**
* Creates new user
*
* @param kEvent $event
*/
function OnCreate(&$event)
{
- $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
- /* @var $cs_helper kCountryStatesHelper */
-
- $cs_helper->CheckStateField($event, 'State', 'Country');
-
parent::OnCreate($event);
$this->setNextTemplate($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function setNextTemplate(&$event)
{
if ($this->Application->isAdminUser) {
return ;
}
$event->SetRedirectParam('opener', 's');
$next_template = $this->Application->GetVar('next_template');
if ($next_template) {
$event->redirect = $next_template;
}
}
/**
- * [HOOK] Prefill states dropdown with correct values
+ * Fills states for object country
*
* @param kEvent $event
- * @access public
*/
- function OnPrepareStates(&$event)
+ function OnAfterItemLoad(&$event)
{
- $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
- $cs_helper->PopulateStates($event, 'State', 'Country');
+ parent::OnAfterItemLoad($event);
- $object =& $event->MasterEvent->getObject();
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
- if( $object->isRequired('Country') && $cs_helper->CountryHasStates( $object->GetDBField('Country') ) ) $object->setRequired('State', true);
+ $cs_helper->PopulateStates($event, 'State', 'Country');
}
-
/**
* [HOOK] Update PortalUser table when address marked as ProfileAddress is changed via addr prefix object
*
* @param kEvent $event
*/
function OnUpdateProfileAddress(&$event)
{
$user =& $this->Application->recallObject('u.current');
if ($this->Application->GetVar('billing_address_id') > 0) {
$address_id = $this->Application->GetVar('billing_address_id');
}
elseif ($this->Application->GetVar('shipping_address_id') > 0) {
$address_id = $this->Application->GetVar('shipping_address_id');
}
else {
$address_id = false;
}
if (!$address_id) {
return true;
}
$address =& $event->getObject(Array('skip_autoload' => true));
$address->Load($address_id);
if (!$address->GetDBField('IsProfileAddress')) {
return true;
}
$field_map = Array( 'Company' => 1,
'Phone' => 1,
'Fax' => 1,
'Email' => 1,
'Address1' => 'Street',
'Address2' => 'Street2',
'City' => 1,
'State' => 1,
'Zip' => 1,
'Country' => 1,
);
$user->setName( $address->GetDBField('To') );
foreach ($field_map as $src_field => $dst_field) {
if ($dst_field == 1) $dst_field = $src_field;
$user->SetDBField($dst_field, $address->GetDBField($src_field));
}
return $user->Update();
}
/**
* [HOOK] Create user profile address based on PortalUser table data
*
* @param kEvent $event
*/
function OnUpdateUserProfile(&$event)
{
$user =& $event->MasterEvent->getObject();
$load_keys = Array('PortalUserId' => $user->GetID(), 'IsProfileAddress' => 1);
$address =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true));
$address->Load($load_keys);
$field_map = Array( 'PortalUserId' => 1,
'Company' => 1,
'Phone' => 1,
'Fax' => 1,
'Email' => 1,
'Address1' => 'Street',
'Address2' => 'Street2',
'City' => 1,
'State' => 1,
'Zip' => 1,
'Country' => 1,
);
$full_name = trim($user->GetDBField('FirstName').' '.$user->GetDBField('LastName'));
$address->SetDBField('To', $full_name);
$address->SetDBField('IsProfileAddress', 1);
foreach ($field_map as $dst_field => $src_field) {
if ($src_field == 1) $src_field = $dst_field;
$address->SetDBField($dst_field, $user->GetDBField($src_field));
}
$sql = 'SELECT SUM(IF(LastUsedAsBilling = 1, 1, 0 )) AS HasBilling, SUM(IF(LastUsedAsShipping = 1, 1, 0)) AS HasShipping
FROM '.$address->TableName.'
WHERE PortalUserId = '.$user->GetID();
$address_status = $this->Conn->GetRow($sql);
if (!$address_status['HasBilling']) {
$address->SetDBField('LastUsedAsBilling', 1);
}
if (!$address_status['HasShipping']) {
$address->SetDBField('LastUsedAsShipping', 1);
}
return $address->isLoaded() ? $address->Update() : $address->Create();
}
/**
* Checks if user trying to manipulate address that he Owns (exception for Admins)
* (non permission-based)
*
* @param kEvent $event
* @return bool
*/
function checkItemStatus(&$event)
{
if ($this->Application->isAdminUser) {
return true;
}
if (!$this->Application->LoggedIn()) {
return false;
}
$object =& $event->getObject();
if (!$object->isLoaded()) {
return true;
}
return $object->GetDBField('PortalUserId') == $this->Application->RecallVar('user_id');
}
/**
* Ensures, that user have only one "use as billing" / "use as shipping" address
* Disables Guest ability to create addresses
*
* @param kEvent $event
*/
function OnBeforeItemCreate(&$event)
{
if (!$this->Application->LoggedIn()) {
$event->status = erPERM_FAIL;
return ;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('PortalUserId', $this->Application->RecallVar('user_id'));
+ $cs_helper =& $this->Application->recallObject('CountryStatesHelper');
+ /* @var $cs_helper kCountryStatesHelper */
+
+ $cs_helper->CheckStateField($event, 'State', 'Country');
+ $cs_helper->PopulateStates($event, 'State', 'Country');
+
$this->processLastUsed($object, 'Shipping');
$this->processLastUsed($object, 'Billing');
}
function OnBeforeItemDelete(&$event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
if (!$object->isLoaded() || !$this->checkItemStatus($event)) {
// not trivially loaded object OR not current user address
$event->status = erPERM_FAIL;
return ;
}
}
}
\ No newline at end of file
Index: branches/5.1.x/units/addresses/addresses_config.php
===================================================================
--- branches/5.1.x/units/addresses/addresses_config.php (revision 13464)
+++ branches/5.1.x/units/addresses/addresses_config.php (revision 13465)
@@ -1,130 +1,118 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array(
'Prefix' => 'addr',
'ItemClass' => Array('class'=>'AddressesItem','file'=>'addresses_item.php','build_event'=>'OnItemBuild'),
'ListClass' => Array('class'=>'AddressesList','file'=>'addresses_list.php','build_event'=>'OnListBuild'),
'EventHandlerClass' => Array('class' => 'AddressesEventHandler', 'file' => 'addresses_event_handler.php', 'build_event' => 'OnBuild'),
'TagProcessorClass' => Array('class' => 'AddressesTagProcessor', 'file' => 'addresses_tag_processor.php', 'build_event' => 'OnBuild'),
'AutoLoad' => true,
'Hooks' => Array(
- Array(
- 'Mode' => hAFTER,
- 'Conditional' => false,
- 'HookToPrefix' => '',
- 'HookToSpecial' => '*',
- 'HookToEvent' => Array('OnAfterItemLoad', 'OnBeforeItemCreate', 'OnBeforeItemUpdate'),
- 'DoPrefix' => '',
- 'DoSpecial' => '*',
- 'DoEvent' => 'OnPrepareStates',
- ),
-
// create/update profile addres (in addresses table)
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => '#PARENT#',
'HookToSpecial' => '*',
'HookToEvent' => Array('OnAfterItemCreate', 'OnAfterItemUpdate'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnUpdateUserProfile',
),
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => '',
'HookToSpecial' => '*',
'HookToEvent' => Array('OnAfterItemCreate', 'OnAfterItemUpdate'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnUpdateProfileAddress',
),
),
'QueryString' => Array(
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'IDField' => 'AddressId',
'TableName' => TABLE_PREFIX.'Addresses',
'ParentTableKey'=> 'PortalUserId', // linked field in master table
'ForeignKey' => 'PortalUserId', // linked field in subtable
'ParentPrefix' => 'u',
'AutoDelete' => true,
'AutoClone' => true,
'CalculatedFields' => Array(
'' => Array(
'ShortAddress' => 'CONCAT( TRIM(CONCAT(Address1," ",Address2)),", ",City," ...")',
),
),
'ListSQLs' => Array('' => 'SELECT %1$s.* %2$s FROM %1$s'), // key - special, value - list select sql
'ItemSQLs' => Array( ''=>'SELECT * FROM %s'),
'ListSortings' => Array('' => Array('Sorting' => Array('IsProfileAddress' => 'desc')) ),
'Fields' => Array(
'AddressId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'PortalUserId' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'To' => Array('type' => 'string','not_null' => '1', 'required' => 1, 'default' => ''),
'Company' => Array('type' => 'string','not_null' => '1','default' => ''),
'Phone' => Array('type' => 'string','not_null' => '1', 'required' => 1, 'default' => ''),
'Fax' => Array('type' => 'string','not_null' => '1','default' => ''),
'Email' => Array('type' => 'string','formatter'=>'kFormatter', 'regexp'=>'/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i','not_null' => '1','default' => ''),
'Address1' => Array('type' => 'string','not_null' => '1', 'required' => 1, 'default' => ''),
'Address2' => Array('type' => 'string','not_null' => '1','default' => ''),
'City' => Array('type' => 'string','not_null' => '1', 'required' => 1, 'default' => ''),
'State' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter', 'options' => Array(),
'not_null' => '1', 'default' => ''
),
'Zip' => Array('type' => 'string','not_null' => '1', 'required' => 1, 'default' => ''),
'Country' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter',
- 'options_sql' => ' SELECT %1$s
- FROM '.TABLE_PREFIX.'StdDestinations
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = '.TABLE_PREFIX.'StdDestinations.DestName
- WHERE DestType = 1
- ORDER BY l%2$s_Translation',
- 'option_key_field' => 'DestAbbr', 'option_title_field' => 'l%2$s_Translation',
+ 'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
+ FROM ' . TABLE_PREFIX . 'CountryStates
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
+ ORDER BY Name',
+ 'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => '1', 'required' => 1, 'default' => ''
),
'LastUsedAsBilling' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'LastUsedAsShipping' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'IsProfileAddress' => Array('type' => 'int','not_null' => 1, 'default' => 0),
),
'VirtualFields' => Array(
'ShortAddress' => Array('type'=>'string'),
),
'Grids' => Array(),
);
\ No newline at end of file
Index: branches/5.1.x/units/gift_certificates/gift_certificates_config.php
===================================================================
--- branches/5.1.x/units/gift_certificates/gift_certificates_config.php (revision 13464)
+++ branches/5.1.x/units/gift_certificates/gift_certificates_config.php (revision 13465)
@@ -1,151 +1,150 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'gc',
'ItemClass' => Array ('class' => 'kDBItem', 'file' => '', 'build_event' => 'OnItemBuild'),
'ListClass' => Array ('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
'EventHandlerClass' => Array ('class' => 'GiftCertificateEventHandler', 'file' => 'gift_certificates_eh.php', 'build_event' => 'OnBuild'),
'TagProcessorClass' => Array ('class' => 'GiftCertificateTagProcessor', 'file' => 'gift_certificates_tp.php', 'build_event' => 'OnBuild'),
'AutoLoad' => true,
'Hooks' => Array (
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => 'ord',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnUpdateCart', 'OnCheckout' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnApplyGiftCertificate',
),
),
'QueryString' => Array (
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'IDField' => 'GiftCertificateId',
'StatusField' => Array('Status'),
'TitleField' => 'Recipient',
'TableName' => TABLE_PREFIX.'GiftCertificates',
'TitlePresets' => Array (
'default' => Array (
'new_status_labels' => Array ('gc' => '!la_title_AddingGiftCertificate!'),
'edit_status_labels' => Array ('gc' => '!la_title_EditingGiftCertificate!'),
'new_titlefield' => Array ('gc' => '!la_title_NewGiftCertificate!'),
),
'gift_certificates_list' => Array ('prefixes' => Array ('gc_List'), 'format' => "!la_title_GiftCertificates!",),
'gift_certificates_edit' => Array ('prefixes' => Array ('gc'), 'format' => "#gc_status# '#gc_titlefield#' - !la_title_General!",),
),
'PermSection' => Array ('main' => 'in-commerce:gift-certificates'),
'Sections' => Array (
'in-commerce:gift-certificates' => Array (
'parent' => 'in-commerce:discounts_folder',
'icon' => 'discounts_coupons',
'label' => 'la_tab_GiftCertificates',
'url' => Array('t' => 'in-commerce/discounts/gift_certificate_list', 'pass' => 'm'),
'permissions' => Array('view', 'add', 'edit', 'delete', 'advanced:approve', 'advanced:decline'),
'priority' => 3.3, // <parent_priority>.<own_priority>, because this section replaces parent in tree
'type' => stTAB,
),
),
'FilterMenu' => Array (
'Groups' => Array(
Array ('mode' => 'AND', 'filters' => Array(0,1,2), 'type' => WHERE_FILTER),
),
'Filters' => Array(
0 => Array('label' =>'la_Enabled', 'on_sql' => '', 'off_sql' => 'Status != 1' ),
1 => Array('label' => 'la_Used', 'on_sql' => '', 'off_sql' => 'Status != 2' ),
2 => Array('label' => 'la_Disabled', 'on_sql' => '', 'off_sql' => 'Status != 0' ),
)
),
'ListSQLs' => Array ('' => 'SELECT %1$s.* %2$s FROM %1$s',),
'ItemSQLs' => Array ('' => 'SELECT * FROM %1$s',),
'ListSortings' => Array (
'' => Array(
'Sorting' => Array('Recipient' => 'asc'),
)
),
'Fields' => Array (
'GiftCertificateId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'OrderId' => Array ('type' => 'int', 'default' => 0),
'Status' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array ( 1 => 'la_Enabled', 2 => 'la_Used', 0 => 'la_Disabled' ), 'use_phrases' => 1, 'not_null' => 1, 'default' => 2 ),
'SendVia' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array ( 0 => 'la_opt_Email', 1 => 'la_opt_PostalMail'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 0 ),
'Purchaser' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'Recipient' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'RecipientEmail' => Array('type' => 'string', 'formatter'=>'kFormatter', 'regexp'=>'/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i', 'sample_value' => 'email@domain.com', 'not_null' => '1', 'required'=>1, 'default' => '', 'error_msgs' => Array('invalid_format'=>'!la_invalid_email!') ),
'RecipientFirstname' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'RecipientLastname' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'RecipientAddress1' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'RecipientAddress2' => Array('type'=>'string', 'default'=>null, 'max_len'=>255),
'RecipientCity' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'RecipientState' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'RecipientZipcode' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255),
'RecipientCountry' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter',
- 'options_sql' => ' SELECT %1$s
- FROM '.TABLE_PREFIX.'StdDestinations
- LEFT JOIN '.TABLE_PREFIX.'Phrase ON '.TABLE_PREFIX.'Phrase.Phrase = '.TABLE_PREFIX.'StdDestinations.DestName
- WHERE DestType = 1
- ORDER BY l%2$s_Translation',
- 'option_key_field' => 'DestAbbr', 'option_title_field' => 'l%2$s_Translation',
+ 'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
+ FROM '.TABLE_PREFIX.'CountryStates
+ WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
+ ORDER BY Name',
+ 'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => 1, 'required' => 1, 'default' => 'USA'
),
'RecipientPhone' => Array('type'=>'string','default'=>null, 'max_len'=>255),
'Message' => Array('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => null),
'Code' => Array('type'=>'string','required'=>1,'default'=>null, 'max_len'=>255, 'unique'=>Array('Code')),
'AddDate' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => '#NOW#',),
'Expiration' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => null,),
'Amount' => Array('type'=>'double', 'default' => null, 'required' => 1, 'min_value_exc' => 0),
'Debit' => Array('type'=>'double', 'default' => null),
),
'Grids' => Array (
'Default' => Array (
'Icons' => Array(
'default' => 'icon16_item.png',
0 => 'icon16_disabled.png',
1 => 'icon16_item.png',
2 => 'icon16_pending.png',
'module' => 'core',
),
'Fields' => Array (
'GiftCertificateId' => Array ('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 60, ),
'Code' => Array ('title' => 'la_col_Code', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'Status' => Array ('title' => 'la_col_Status', 'filter_block' => 'grid_options_filter', 'width' => 100, ),
'Debit' => Array ('title' => 'la_col_RemainingAmount', 'filter_block' => 'grid_float_range_filter', 'width' => 160, ),
'Amount' => Array ('title' => 'la_col_Amount', 'filter_block' => 'grid_float_range_filter', 'width' => 100, ),
'Expiration' => Array ('title'=>'la_col_Expiration', 'filter_block' => 'grid_date_range_filter', 'width' => 145, ),
),
),
),
);
\ No newline at end of file
Index: branches/5.1.x/admin_templates/shipping/zone_edit.tpl
===================================================================
--- branches/5.1.x/admin_templates/shipping/zone_edit.tpl (revision 13464)
+++ branches/5.1.x/admin_templates/shipping/zone_edit.tpl (revision 13465)
@@ -1,384 +1,384 @@
<inp2:adm_SetPopupSize width="650" height="480"/>
<inp2:m_include t="incs/header"/>
<inp2:m_RenderElement name="combined_header" prefix="s" section="in-commerce:shipping" title_preset="zones_edit"/>
<!-- ToolBar -->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('select', '<inp2:m_phrase label="la_ToolTip_Save" escape="1"/>', function() {
SelectAll(document.getElementById('location_list[]'));
SelectToString(document.getElementById('location_list[]'));
submit_event('z','<inp2:z_SaveEvent/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('cancel', '<inp2:m_phrase label="la_ToolTip_Cancel" escape="1"/>', function() {
submit_event('z','OnCancel');
}
) );
a_toolbar.AddButton( new ToolBarSeparator('sep1') );
a_toolbar.AddButton( new ToolBarButton('prev', '<inp2:m_phrase label="la_ToolTip_Prev" escape="1"/>', function() {
go_to_id('z', '<inp2:z_PrevId/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('next', '<inp2:m_phrase label="la_ToolTip_Next" escape="1"/>', function() {
go_to_id('z', '<inp2:z_NextId/>');
}
) );
a_toolbar.AddButton( new ToolBarSeparator('sep2') );
a_toolbar.Render();
<inp2:m_if check="z_IsSingle" >
a_toolbar.HideButton('prev');
a_toolbar.HideButton('next');
a_toolbar.HideButton('sep1');
a_toolbar.HideButton('sep2');
<inp2:m_else/>
<inp2:m_if check="z_IsLast" >
a_toolbar.DisableButton('next');
</inp2:m_if>
<inp2:m_if check="z_IsFirst" >
a_toolbar.DisableButton('prev');
</inp2:m_if>
</inp2:m_if>
</script>
</td>
</tr>
</tbody>
</table>
-<inp2:m_DefineElement name="destination_block">
+<inp2:m_DefineElement name="destination_block" selected="">
<option value="<inp2:m_param name="id"/>" <inp2:m_param name="selected"/>><inp2:m_param name="destination_title"/></option>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="countries_multiple">
<tr class="<inp2:m_odd_even odd='edit-form-odd' even='edit-form-even'/>">
<inp2:m_inc param="tab_index" by="1"/>
<td class="label-cell">&nbsp;</td>
<td class="control-mid">&nbsp;</td>
<td class="control-cell">
<table>
<tr><td>
<inp2:m_Phrase label="la_zones_SelectedCountries"/>:<br/>
<select name="location_list[]" id="location_list[]" multiple onchange="SelectToString(this)" size="10" style="width: 200px">
<inp2:z_ShowCountries block="destination_block" show="current"/>
</select>
</td>
<td>
<input class="button" type=button onclick="MoveSelected(this.form.ShippingZoneIdChooser, document.getElementById('location_list[]'))" value="&lt;"><br/>
<input class="button" type=button onclick="MoveSelected(document.getElementById('location_list[]'), this.form.ShippingZoneIdChooser)" value="&gt;">
</td>
<td>
<inp2:m_Phrase label="la_zones_AvailableCountries"/>:<br/>
<select name="ShippingZoneIdChooser" multiple size="10" size="10" style="width: 200px">
<inp2:z_ShowCountries block="destination_block" show="available"/>
</select>
</td>
</tr>
</table>
</td>
</tr>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="states_multiple">
<tr class="<inp2:m_odd_even odd='edit-form-odd' even='edit-form-even'/>">
<td class="label-cell">&nbsp;</td>
<td class="control-mid">&nbsp;</td>
<td class="control-cell">
<select name="CountrySelector" onChange="change_country()">
<inp2:z_ShowCountries block="destination_block" show="has_states"/>
</select>
<br />
<table>
<tr><td>
<inp2:m_Phrase label="la_zones_SelectedStates"/>:<br/>
<select name="location_list[]" id="location_list[]" multiple onchange="SelectToString(this)" size="10" style="width: 200px">
<inp2:z_ShowStates block="destination_block" show="current"/>
</select>
</td>
<td>
<input class="button" type=button onclick="MoveSelected(this.form.ShippingZoneIdChooser, document.getElementById('location_list[]'))" value="&lt;"><br/>
<input class="button" type=button onclick="MoveSelected(document.getElementById('location_list[]'), this.form.ShippingZoneIdChooser)" value="&gt;">
</td>
<td>
<inp2:m_Phrase label="la_zones_AvailableStates"/>:<br/>
<select name="ShippingZoneIdChooser" multiple size="10" style="width: 200px">
<inp2:z_ShowStates block="destination_block" show="available"/>
</select>
</td>
</tr>
</table>
</td>
</tr>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="zips_multiple">
<tr class="<inp2:m_odd_even odd='edit-form-odd' even='edit-form-even'/>">
<td class="label-cell">&nbsp;</td>
<td class="control-mid">&nbsp;</td>
<td class="control-cell">
<select name="CountrySelector" onChange="change_country()">
<inp2:z_ShowCountries block="destination_block" show="all"/>
</select>
<br />
<table>
<tr><td>
<inp2:m_Phrase label="la_zones_SelectedZips"/>:<br/>
<select name="location_list[]" id="location_list[]" multiple onchange="SelectToString(this)" size="10" style="width: 200px">
<inp2:z_ShowZips block="destination_block" show="current"/>
</select>
</td>
<td>
<input class="button" type=button onclick="MoveSelected(this.form.ShippingZoneIdChooser, document.getElementById('location_list[]'))" value="&lt;"><br/>
<input class="button" type=button onclick="MoveSelected(document.getElementById('location_list[]'), this.form.ShippingZoneIdChooser)" value="&gt;">
</td>
<td>
<inp2:m_Phrase label="la_zones_AvailableZips"/>:<br/>
<select name="ShippingZoneIdChooser" multiple size="10" style="width: 200px">
<inp2:z_ShowZips block="destination_block" show="available"/>
</select>
</td>
</tr>
</table>
<br>
<input type="text" name="zone_add" id="zone_add"> <input type="button" onClick="add_zone(document.getElementById('location_list[]'))" value="<inp2:m_Phrase label='la_btn_AddLocation'/>" class="button"/>
</td>
</tr>
</inp2:m_DefineElement>
<inp2:z_SaveWarning name="grid_save_warning"/>
<inp2:z_ErrorWarning name="form_error_warning"/>
+<!--## used for OnCountryChange event ##-->
+<input type="hidden" name="z_id" value="<inp2:z_Field name='ZoneID'/>"/>
+
<div id="scroll_container">
<table class="edit-form">
<inp2:m_RenderElement name="subsection" title="!la_section_ShippingZone!"/>
<inp2:m_RenderElement name="inp_id_label" prefix="z" field="ZoneID" title="!la_fld_Id!"/>
<inp2:m_RenderElement name="inp_label" prefix="z" field="ShippingTypeID" title="!la_fld_ShippingTypeId!"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="z" field="Name" title="!la_fld_ShipZoneName!" size="40"/>
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="z" field="CODallowed" title="!la_fld_CODallowed!"/>
<inp2:m_RenderElement name="inp_edit_radio" prefix="z" field="Type" title="!la_fld_Zone_Type!"/>
- <!-- <inp2:z_ShowDestinations block="destination_block" /> -->
-
- <inp2:m_if check="z_fieldequals" field="Type" value="1" >
+ <inp2:m_if check="z_Field" field="Type" equals_to="1" db="db">
<inp2:m_RenderElement name="countries_multiple" prefix="z" />
</inp2:m_if>
- <inp2:m_if check="z_fieldequals" field="Type" value="2" >
+ <inp2:m_if check="z_Field" field="Type" equals_to="2" db="db">
<inp2:m_RenderElement name="states_multiple" prefix="z" />
</inp2:m_if>
- <inp2:m_if check="z_fieldequals" field="Type" value="3" >
+ <inp2:m_if check="z_Field" field="Type" equals_to="3" db="db">
<inp2:m_RenderElement name="zips_multiple" prefix="z" />
</inp2:m_if>
<inp2:m_RenderElement name="inp_edit_filler"/>
</table>
</div>
<input type="hidden" value="" name="location_id" id="location_id">
<input type="hidden" value="" name="selected_destinations" id="selected_destinations">
<input type="hidden" name="z_OriginalSaveEvent" id="z_OriginalSaveEvent" value="<inp2:z_SaveEvent/>">
-<input type="hidden" name="z[<inp2:z_field field="ZoneID"/>][ShippingTypeID]" id="z[<inp2:z_field field="ZoneID"/>][ShippingTypeID]" value="<inp2:z_field field="ShippingTypeID"/>">
-<input type="hidden" name="z_id" id="z_id" value="<inp2:z_Field field="ZoneID"/>">
+<inp2:m_RenderElement name="inp_edit_hidden" prefix="z" field="ShippingTypeID"/>
<script>
document.getElementById('z[<inp2:z_field field="ZoneID"/>][Type]_1').onchange = change_type;
document.getElementById('z[<inp2:z_field field="ZoneID"/>][Type]_2').onchange = change_type;
document.getElementById('z[<inp2:z_field field="ZoneID"/>][Type]_3').onchange = change_type;
function change_type()
{
submit_event('z','OnTypeChange');
}
function change_country()
{
submit_event('z','OnCountryChange');
}
function remove_location(location_id)
{
document.getElementById('location_id').value = location_id;
submit_event('z', 'OnRemoveLocation');
}
function SelectToString(aSelect)
{
// written by Slava, patched by Alex, modified by SergeyG
var result = '';
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
if(aSelect.options[i].selected == true) result += cur.value+',';
}
if(result.length > 0) result = result.substring(0,result.length-1);
document.getElementById('selected_destinations').value = result;
return result;
}
function add_zone(aSelect){
var el = document.getElementById('zone_add');
if (el)
{
if (el.value=='') return;
var found = false;
var valueArray;
for (i = 0; i < aSelect.options.length; i++){
valueArray = aSelect.options[i].value.split("|");
if (valueArray[1] == el.value){
found = true;
break;
}
}
if (!found){
aSelect.options[aSelect.length] = new Option(el.value, '0|'+el.value);
el.value='';
}
}
}
function SelectContainsValue(selectObject, searchValue)
{
for (i = 0; i < selectObject.options.length; i++){
if (selectObject.options[i].text == searchValue){
return true;
}
}
return false;
}
function SelectToArray(aSelect)
{
var an_arr = new Array();
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
an_arr[an_arr.length] = new Array(cur.text, cur.value, cur.selected);
}
return an_arr;
}
function ArrayToSelect(anArray, aSelect)
{
var initial_length = aSelect.length;
for (var i=initial_length-1; i >= 0; i--) { aSelect.options[i] = null; }
for (var i=0; i < anArray.length; i++)
{
cur = anArray[i];
aSelect.options[aSelect.length] = new Option(cur[0], cur[1]);
}
}
function SelectCompare(a, b)
{
if (a[0] < b[0])
return -1;
if (a[0] > b[0])
return 1;
return 0;
}
function MoveSelected(FromList, ToList)
{
FromArr = SelectToArray(FromList);
ToArr = SelectToArray(ToList);
NewFrom = Array();
for (var i=FromArr.length-1; i >= 0; i--)
{
cur = FromArr[i];
if (cur[2] && !SelectContainsValue(ToList, cur[0])) {
ToArr[ToArr.length] = cur;
}
else if(SelectContainsValue(ToList, cur[0])) {
}
else {
NewFrom[NewFrom.length] = cur;
}
}
NewFrom.sort(SelectCompare);
ToArr.sort(SelectCompare);
FromList = ArrayToSelect(NewFrom, FromList);
ToList = ArrayToSelect(ToArr, ToList);
}
function SelectToString2(aSelect)
{
var result = '';
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
result += cur.value+',';
}
return result;
}
function SelectAll(aSelect)
{
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
aSelect.options[i].selected = true;
}
// -----------
}
function OnlySelectedToString(aSelect)
{
var result = '';
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
if (cur.selected)
result += cur.value+',';
}
return result;
}
function SelectMultipleSelected(aSelect, aStr)
{
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
if (aStr.match("(^|\,)+"+cur.value+"(,|$)+") ) {
aSelect.options[i].selected = true;
}
}
}
function SelectAll(aSelect)
{
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
aSelect.options[i].selected = true;
}
}
// --------------
</SCRIPT>
<inp2:m_include t="incs/footer"/>
\ No newline at end of file
Index: branches/5.1.x/admin_templates/taxes/taxes_edit.tpl
===================================================================
--- branches/5.1.x/admin_templates/taxes/taxes_edit.tpl (revision 13464)
+++ branches/5.1.x/admin_templates/taxes/taxes_edit.tpl (revision 13465)
@@ -1,384 +1,382 @@
<inp2:adm_SetPopupSize width="850" height="610"/>
<inp2:m_include t="incs/header"/>
<inp2:m_RenderElement name="combined_header" prefix="tax" section="in-commerce:taxes" title_preset="taxes_edit"/>
<!-- ToolBar -->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('select', '<inp2:m_phrase label="la_ToolTip_Save" escape="1"/>', function() {
SelectAll(document.getElementById('location_list[]'));
SelectToString(document.getElementById('location_list[]'));
submit_event('tax','<inp2:tax_SaveEvent/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('cancel', '<inp2:m_phrase label="la_ToolTip_Cancel" escape="1"/>', function() {
submit_event('tax','OnCancel');
}
) );
a_toolbar.AddButton( new ToolBarSeparator('sep1') );
a_toolbar.AddButton( new ToolBarButton('prev', '<inp2:m_phrase label="la_ToolTip_Prev" escape="1"/>', function() {
go_to_id('tax', '<inp2:tax_PrevId/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('next', '<inp2:m_phrase label="la_ToolTip_Next" escape="1"/>', function() {
go_to_id('tax', '<inp2:tax_NextId/>');
}
) );
a_toolbar.Render();
<inp2:m_if check="tax_IsSingle" >
a_toolbar.HideButton('prev');
a_toolbar.HideButton('next');
a_toolbar.HideButton('sep1');
a_toolbar.HideButton('sep2');
<inp2:m_else/>
<inp2:m_if check="tax_IsLast" >
a_toolbar.DisableButton('next');
</inp2:m_if>
<inp2:m_if check="tax_IsFirst" >
a_toolbar.DisableButton('prev');
</inp2:m_if>
</inp2:m_if>
</script>
</td>
</tr>
</tbody>
</table>
-<inp2:m_DefineElement name="destination_block">
+<inp2:m_DefineElement name="destination_block" selected="">
<option value="<inp2:m_param name="id"/>" <inp2:m_param name="selected"/>><inp2:m_param name="destination_title"/></option>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="countries_multiple">
<tr class="<inp2:m_odd_even odd='edit-form-odd' even='edit-form-even'/>">
<inp2:m_inc param="tab_index" by="1"/>
<td class="label-cell">&nbsp;</td>
<td class="control-mid">&nbsp;</td>
<td class="control-cell">
<table>
<tr><td>
<inp2:m_Phrase label="la_zones_SelectedCountries"/>:<br/>
<select name="location_list[]" id="location_list[]" multiple onchange="SelectToString(this)" size="10" style="width: 200px">
<inp2:tax_ShowCountries block="destination_block" show="current"/>
</select>
</td>
<td>
<input class="button" type=button onclick="MoveSelected(document.getElementById('location_list[]'), this.form.TaxZoneIdChooser)" value="&gt;"><br>
<input class="button" type=button onclick="MoveSelected(this.form.TaxZoneIdChooser, document.getElementById('location_list[]'))" value="&lt;">
</td>
<td>
<inp2:m_Phrase label="la_zones_AvailableCountries"/>:<br/>
<select name="TaxZoneIdChooser" multiple size="10" size="10" style="width: 200px">
<inp2:tax_ShowCountries block="destination_block" show="available"/>
</select>
</td>
</tr>
</table>
<!-- <select name="<inp2:tax_InputName field="TaxZoneId" />" multiple> -->
</td>
</tr>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="states_multiple">
<tr class="<inp2:m_odd_even odd='edit-form-odd' even='edit-form-even'/>">
<inp2:m_inc param="tab_index" by="1"/>
<td class="label-cell">&nbsp;</td>
<td class="control-mid">&nbsp;</td>
<td class="control-cell">
<select name="CountrySelector" onChange="change_country()">
<inp2:tax_ShowCountries block="destination_block" show="has_states"/>
</select>
<br />
<table>
<tr><td>
<inp2:m_Phrase label="la_zones_SelectedStates"/>:<br/>
<select name="location_list[]" id="location_list[]" multiple onchange="SelectToString(this)" size="10" style="width: 200px">
<inp2:tax_ShowStates block="destination_block" show="current"/>
</select>
</td>
<td>
<input class="button" type=button onclick="MoveSelected(document.getElementById('location_list[]'), this.form.TaxZoneIdChooser)" value="&gt;"><br>
<input class="button" type=button onclick="MoveSelected(this.form.TaxZoneIdChooser, document.getElementById('location_list[]'))" value="&lt;">
</td>
<td>
<inp2:m_Phrase label="la_zones_AvailableStates"/>:<br/>
<select name="TaxZoneIdChooser" multiple size="10" style="width: 200px">
<inp2:tax_ShowStates block="destination_block" show="available"/>
</select>
</td>
</tr>
</table>
</td>
</tr>
</inp2:m_DefineElement>
<inp2:m_DefineElement name="zips_multiple">
<tr class="<inp2:m_odd_even odd='edit-form-odd' even='edit-form-even'/>">
<inp2:m_inc param="tab_index" by="1"/>
<td class="label-cell">&nbsp;</td>
<td class="control-mid">&nbsp;</td>
<td class="control-cell">
<select name="CountrySelector" onChange="change_country()">
<inp2:tax_ShowCountries block="destination_block" show="all"/>
</select>
<br />
<table>
<tr><td>
<inp2:m_Phrase label="la_zones_SelectedZips"/>:<br/>
<select name="location_list[]" id="location_list[]" multiple onchange="SelectToString(this)" size="10" style="width: 200px">
<inp2:tax_ShowZips block="destination_block" show="current"/>
</select>
</td>
<td>
<input class="button" type=button onclick="MoveSelected(document.getElementById('location_list[]'), this.form.TaxZoneIdChooser)" value="&gt;"><br>
<input class="button" type=button onclick="MoveSelected(this.form.TaxZoneIdChooser, document.getElementById('location_list[]'))" value="&lt;">
</td>
<td>
<inp2:m_Phrase label="la_zones_AvailableZips"/>:<br/>
<select name="TaxZoneIdChooser" multiple size="10" style="width: 200px">
<inp2:tax_ShowZips block="destination_block" show="available"/>
</select>
</td>
</tr>
</table>
<br>
<input type="text" name="zone_add" id="zone_add"> <input type="button" onClick="add_zone(document.getElementById('location_list[]'))" value="<inp2:m_Phrase label='la_btn_AddLocation'/>" class="button"/>
</td>
</tr>
</inp2:m_DefineElement>
<inp2:tax_SaveWarning name="grid_save_warning"/>
<inp2:tax_ErrorWarning name="form_error_warning"/>
<div id="scroll_container">
<table class="edit-form">
<inp2:m_RenderElement name="subsection" title="!la_section_TaxZone!"/>
<inp2:m_RenderElement name="inp_id_label" prefix="tax" field="TaxZoneId" title="!la_fld_Id!"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="tax" field="Name" title="!la_fld_ZoneName!" size="40"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="tax" field="TaxValue" title="!la_fld_TaxValue!" size="40"/>
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="tax" field="ApplyToShipping" title="!la_fld_TaxApplyToShipping!"/>
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="tax" field="ApplyToProcessing" title="!la_fld_TaxApplyToProcessing!"/>
<inp2:m_RenderElement name="inp_edit_radio" prefix="tax" field="Type" title="!la_fld_ZoneType!"/>
- <!-- <inp2:tax_ShowDestinations block="destination_block" /> -->
-
- <inp2:m_if check="tax_fieldequals" field="Type" value="1" >
+ <inp2:m_if check="tax_Field" field="Type" equals_to="1" db="db">
<inp2:m_RenderElement name="countries_multiple" prefix="tax" />
</inp2:m_if>
- <inp2:m_if check="tax_fieldequals" field="Type" value="2" >
+ <inp2:m_if check="tax_Field" field="Type" equals_to="2" db="db">
<inp2:m_RenderElement name="states_multiple" prefix="tax" />
</inp2:m_if>
- <inp2:m_if check="tax_fieldequals" field="Type" value="3" >
+ <inp2:m_if check="tax_Field" field="Type" equals_to="3" db="db">
<inp2:m_RenderElement name="zips_multiple" prefix="tax" />
</inp2:m_if>
<inp2:m_RenderElement name="inp_edit_filler"/>
</table>
</div>
<input type="hidden" value="" name="location_id" id="location_id">
<input type="hidden" value="" name="selected_destinations" id="selected_destinations">
<input type="hidden" name="tax_OriginalSaveEvent" id="tax_OriginalSaveEvent" value="<inp2:tax_SaveEvent/>">
<script>
document.getElementById('tax[<inp2:tax_field field="TaxZoneId"/>][Type]_1').onchange = change_type;
document.getElementById('tax[<inp2:tax_field field="TaxZoneId"/>][Type]_2').onchange = change_type;
document.getElementById('tax[<inp2:tax_field field="TaxZoneId"/>][Type]_3').onchange = change_type;
function change_type()
{
submit_event('tax','OnTypeChange');
}
function change_country()
{
submit_event('tax','OnCountryChange');
}
function remove_location(location_id)
{
document.getElementById('location_id').value = location_id;
submit_event('tax', 'OnRemoveLocation');
}
function SelectToString(aSelect)
{
// written by Slava, patched by Alex, modified by SergeyG
var result = '';
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
if(aSelect.options[i].selected == true) result += cur.value+',';
}
if(result.length > 0) result = result.substring(0,result.length-1);
document.getElementById('selected_destinations').value = result;
return result;
}
function add_zone(aSelect){
var el = document.getElementById('zone_add');
if (el)
{
if (el.value=='') return;
var found = false;
var valueArray;
for (i = 0; i < aSelect.options.length; i++){
valueArray = aSelect.options[i].value.split("|");
if (valueArray[1] == el.value){
found = true;
break;
}
}
if (!found){
aSelect.options[aSelect.length] = new Option(el.value, '0|'+el.value);
el.value='';
}
}
}
function SelectContainsValue(selectObject, searchValue)
{
for (i = 0; i < selectObject.options.length; i++){
if (selectObject.options[i].text == searchValue){
return true;
}
}
return false;
}
function SelectToArray(aSelect)
{
var an_arr = new Array();
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
an_arr[an_arr.length] = new Array(cur.text, cur.value, cur.selected);
}
return an_arr;
}
function ArrayToSelect(anArray, aSelect)
{
var initial_length = aSelect.length;
for (var i=initial_length-1; i >= 0; i--) { aSelect.options[i] = null; }
for (var i=0; i < anArray.length; i++)
{
cur = anArray[i];
aSelect.options[aSelect.length] = new Option(cur[0], cur[1]);
}
}
function SelectCompare(a, b)
{
if (a[0] < b[0])
return -1;
if (a[0] > b[0])
return 1;
return 0;
}
function MoveSelected(FromList, ToList)
{
FromArr = SelectToArray(FromList);
ToArr = SelectToArray(ToList);
NewFrom = Array();
for (var i=FromArr.length-1; i >= 0; i--)
{
cur = FromArr[i];
if (cur[2] && !SelectContainsValue(ToList, cur[0])) {
ToArr[ToArr.length] = cur;
}
else if(SelectContainsValue(ToList, cur[0])) {
}
else {
NewFrom[NewFrom.length] = cur;
}
}
NewFrom.sort(SelectCompare);
ToArr.sort(SelectCompare);
FromList = ArrayToSelect(NewFrom, FromList);
ToList = ArrayToSelect(ToArr, ToList);
}
function SelectToString2(aSelect)
{
var result = '';
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
result += cur.value+',';
}
return result;
}
function SelectAll(aSelect)
{
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
aSelect.options[i].selected = true;
}
// -----------
}
function OnlySelectedToString(aSelect)
{
var result = '';
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
if (cur.selected)
result += cur.value+',';
}
return result;
}
function SelectMultipleSelected(aSelect, aStr)
{
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
if (aStr.match("(^|\,)+"+cur.value+"(,|$)+") ) {
aSelect.options[i].selected = true;
}
}
}
function SelectAll(aSelect)
{
for (var i=0; i < aSelect.length; i++)
{
cur = aSelect.options[i];
aSelect.options[i].selected = true;
}
}
// --------------
</SCRIPT>
<inp2:m_include t="incs/footer"/>
\ No newline at end of file
Index: branches/5.1.x/admin_templates/discounts/gift_certificate_edit.tpl
===================================================================
--- branches/5.1.x/admin_templates/discounts/gift_certificate_edit.tpl (revision 13464)
+++ branches/5.1.x/admin_templates/discounts/gift_certificate_edit.tpl (revision 13465)
@@ -1,171 +1,171 @@
<inp2:adm_SetPopupSize width="780" height="640"/>
<inp2:m_include t="incs/header"/>
<inp2:m_RenderElement name="combined_header" prefix="gc" section="in-commerce:gift-certificates" title_preset="gift_certificates_edit"/>
<!-- ToolBar -->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('select', '<inp2:m_phrase label="la_ToolTip_Save" escape="1"/>', function() {
submit_event('gc','<inp2:gc_SaveEvent/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('in-commerce:save_and_print', '<inp2:m_phrase label="la_ToolTip_SaveAndPrint" escape="1"/>', function() {
set_hidden_field('print_certificate', 1);
submit_event('gc','<inp2:gc_SaveEvent/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('cancel', '<inp2:m_phrase label="la_ToolTip_Cancel" escape="1"/>', function() {
submit_event('gc','OnCancel');
}
) );
a_toolbar.AddButton( new ToolBarSeparator('sep1') );
a_toolbar.AddButton( new ToolBarButton('prev', '<inp2:m_phrase label="la_ToolTip_Prev" escape="1"/>', function() {
go_to_id('gc', '<inp2:gc_PrevId/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('next', '<inp2:m_phrase label="la_ToolTip_Next" escape="1"/>', function() {
go_to_id('gc', '<inp2:gc_NextId/>');
}
) );
a_toolbar.Render();
<inp2:m_if check="gc_IsSingle" >
a_toolbar.HideButton('prev');
a_toolbar.HideButton('next');
a_toolbar.HideButton('sep1');
<inp2:m_else/>
<inp2:m_if check="gc_IsLast" >
a_toolbar.DisableButton('next');
</inp2:m_if>
<inp2:m_if check="gc_IsFirst" >
a_toolbar.DisableButton('prev');
</inp2:m_if>
</inp2:m_if>
</script>
</td>
</tr>
</tbody>
</table>
<script language="JavaScript">
function Random(N) {
return Math.floor(N * (Math.random() % 1));
}
function generateRandomCode(elementId){
var j, S = "", d;
for (j = 0; j < 10; j++) {
d=Random(2);
if (d==1)
S += String.fromCharCode(65 + Random(26));
else
S += String(Random(9));
}
document.getElementById(elementId).value=S;
}
</script>
<inp2:m_DefineElement name="inp_edit_box_generate" class="" onblur="" maxlength="" is_last="0">
<inp2:m_if check="{$prefix}_FieldVisible" field="$field">
<tr class="<inp2:m_odd_even odd='edit-form-odd' even='edit-form-even'/>">
<inp2:m_RenderElement name="inp_edit_field_caption" prefix="$prefix" field="$field" title="$title" is_last="$is_last"/>
<td class="control-cell">
<input type="text" name="<inp2:{$prefix}_InputName field='$field'/>" id="<inp2:{$prefix}_InputName field='$field'/>" value="<inp2:{$prefix}_Field field='$field'/>" tabindex="<inp2:m_get param='tab_index'/>" size="<inp2:m_param name='size'/>">
<input type="button" class="button" onClick="generateRandomCode('<inp2:{$prefix}_InputName field='$field'/>')" value="<inp2:m_Phrase label='la_GenerateCode' />" />
</td>
<inp2:m_RenderElement name="inp_edit_error" pass_params="1"/>
</tr>
</inp2:m_if>
</inp2:m_DefineElement>
<inp2:gc_SaveWarning name="grid_save_warning"/>
<inp2:gc_ErrorWarning name="form_error_warning"/>
<div id="scroll_container">
<table class="edit-form">
<inp2:m_RenderElement name="subsection" title="!la_section_General!"/>
<inp2:m_RenderElement name="inp_id_label" prefix="gc" field="GiftCertificateId" title="la_fld_Id"/>
<inp2:m_if check="gc_HasOrder">
<inp2:m_RenderElement name="inp_label" prefix="gc" field="Purchaser" title="!la_fld_SenderName!" size="35"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="Recipient" title="!la_fld_RecipientName!" size="35"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="Message" title="!la_fld_MessageText!" cols="35" rows="7"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="Amount" title="!la_fld_Amount!" size="7"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="SendVia" title="!la_fld_DeliveryMethod!"/>
<inp2:m_else/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="Purchaser" title="!la_fld_SenderName!" size="35"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="Recipient" title="!la_fld_RecipientName!" size="35"/>
<inp2:m_RenderElement name="inp_edit_textarea" prefix="gc" field="Message" title="!la_fld_MessageText!" cols="35" rows="7"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="Amount" title="!la_fld_Amount!" size="7"/>
<inp2:m_RenderElement name="inp_edit_radio" prefix="gc" field="SendVia" title="!la_fld_DeliveryMethod!"/>
</inp2:m_if>
<inp2:m_RenderElement name="subsection" title="!la_section_EmailDelivery!"/>
<inp2:m_if check="gc_HasOrder">
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientEmail" title="!la_fld_Email!" size="35"/>
<inp2:m_else/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientEmail" title="!la_fld_Email!" size="35"/>
</inp2:m_if>
<inp2:m_RenderElement name="subsection" title="!la_section_PostalDelivery!"/>
<inp2:m_if check="gc_HasOrder">
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientFirstname" title="la_fld_FirstName" size="35"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientLastname" title="la_fld_LastName" size="35"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientAddress1" title="la_fld_AddressLine1"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientAddress2" title="la_fld_AddressLine2"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientCity" title="la_fld_City"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientZipcode" title="la_fld_Zip"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientState" title="la_fld_State"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientCountry" title="la_fld_Country"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="RecipientPhone" title="la_fld_Phone"/>
<inp2:m_else/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientFirstname" title="la_fld_FirstName" size="35"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientLastname" title="la_fld_LastName" size="35"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientAddress1" title="la_fld_AddressLine1"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientAddress2" title="la_fld_AddressLine2"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientCity" title="la_fld_City"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientZipcode" title="la_fld_Zip"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientState" title="la_fld_State"/>
- <inp2:m_RenderElement name="inp_edit_options" prefix="gc" field="RecipientCountry" title="la_fld_Country"/>
+ <inp2:m_RenderElement name="inp_edit_options" prefix="gc" field="RecipientCountry" title="la_fld_Country" has_empty="1"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="gc" field="RecipientPhone" title="la_fld_Phone"/>
</inp2:m_if>
<inp2:m_RenderElement name="subsection" title="la_section_Properties"/>
<inp2:m_RenderElement name="inp_edit_radio" prefix="gc" field="Status" title="!la_fld_Status!"/>
<inp2:m_if check="gc_HasOrder">
<inp2:m_RenderElement name="inp_label" prefix="gc" field="AddDate" title="la_fld_CreatedOn"/>
<inp2:m_RenderElement name="inp_label" prefix="gc" field="Code" title="!la_fld_Code!" size="35"/>
<inp2:m_else/>
<inp2:m_RenderElement name="inp_edit_date_time" prefix="gc" field="AddDate" title="la_fld_CreatedOn"/>
<inp2:m_RenderElement name="inp_edit_box_generate" prefix="gc" field="Code" title="!la_fld_Code!" size="35"/>
</inp2:m_if>
<inp2:m_if check="gc_IsNewItem" inverse="inverse">
<inp2:m_RenderElement name="inp_label" prefix="gc" field="Debit" title="!la_fld_RemainingAmount!" size="7"/>
</inp2:m_if>
<inp2:m_if check="gc_HasOrder">
<inp2:m_RenderElement name="inp_label" prefix="gc" field="Expiration" title="!la_fld_Expiration!" size="10"/>
<inp2:m_else/>
<inp2:m_RenderElement name="inp_edit_date_time" prefix="gc" field="Expiration" title="!la_fld_Expiration!" size="10"/>
</inp2:m_if>
<inp2:m_RenderElement name="inp_edit_filler"/>
</table>
</div>
<inp2:m_include t="incs/footer"/>
\ No newline at end of file
Index: branches/5.1.x/install/upgrades.sql
===================================================================
--- branches/5.1.x/install/upgrades.sql (revision 13464)
+++ branches/5.1.x/install/upgrades.sql (revision 13465)
@@ -1,125 +1,129 @@
# ===== v 4.3.9 =====
INSERT INTO ImportScripts VALUES (DEFAULT, 'Products from CSV file [In-Commerce]', '', 'p', 'In-Commerce', '', 'CSV', '1');
ALTER TABLE Products ADD OnSale TINYINT(1) NOT NULL default '0' AFTER Featured, ADD INDEX (OnSale);
UPDATE Phrase SET Module = 'In-Commerce' WHERE Phrase IN ('lu_comm_Images', 'lu_comm_ImagesHeader');
# ===== v 5.0.0 =====
UPDATE Category SET Template = '/in-commerce/designs/section' WHERE Template = 'in-commerce/store/category';
UPDATE Category SET CachedTemplate = '/in-commerce/designs/section' WHERE CachedTemplate = 'in-commerce/store/category';
UPDATE ConfigurationValues SET VariableValue = '/in-commerce/designs/section' WHERE VariableName = 'p_CategoryTemplate';
UPDATE ConfigurationValues SET VariableValue = 'in-commerce/designs/detail' WHERE VariableName = 'p_ItemTemplate';
DELETE FROM PersistantSessionData WHERE VariableName IN ('affil_columns_.', 'ap_columns_.', 'apayments_columns_.', 'apayments.log_columns_.', 'd_columns_.', 'coup_columns_.', 'file_columns_.', 'po_columns_.', 'z_columns_.', 'tax_columns_.');
DELETE FROM PersistantSessionData WHERE VariableName LIKE '%ord.%';
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:products.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:setting_folder.view', 11, 1, 1, 0);
INSERT INTO ShippingQuoteEngines VALUES (DEFAULT, 'USPS.com', 0, 0, 0, 'a:21:{s:12:"AccountLogin";s:0:"";s:15:"AccountPassword";N;s:10:"UPSEnabled";N;s:10:"UPSAccount";s:0:"";s:11:"UPSInvoiced";N;s:10:"FDXEnabled";N;s:10:"FDXAccount";s:0:"";s:10:"DHLEnabled";N;s:10:"DHLAccount";s:0:"";s:11:"DHLInvoiced";N;s:10:"USPEnabled";N;s:10:"USPAccount";s:0:"";s:11:"USPInvoiced";N;s:10:"ARBEnabled";N;s:10:"ARBAccount";s:0:"";s:11:"ARBInvoiced";N;s:10:"1DYEnabled";N;s:10:"2DYEnabled";N;s:10:"3DYEnabled";N;s:10:"GNDEnabled";N;s:10:"ShipMethod";N;}', 'USPS');
INSERT INTO ConfigurationAdmin VALUES ('Comm_CompanyName', 'la_Text_ContactsGeneral', 'la_text_CompanyName', 'text', NULL, NULL, 10.01, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'Comm_CompanyName', '', 'In-Commerce', 'in-commerce:contacts');
UPDATE ConfigurationAdmin SET prompt = 'la_text_StoreName', DisplayOrder = 10.02 WHERE VariableName = 'Comm_StoreName';
INSERT INTO ConfigurationAdmin VALUES ('Comm_Contacts_Name', 'la_Text_ContactsGeneral', 'la_text_ContactName', 'text', NULL, NULL, 10.03, 0, 0);
INSERT INTO ConfigurationValues VALUES (DEFAULT, 'Comm_Contacts_Name', '', 'In-Commerce', 'in-commerce:contacts');
UPDATE ConfigurationAdmin SET DisplayOrder = 10.04 WHERE VariableName = 'Comm_Contacts_Phone';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.05 WHERE VariableName = 'Comm_Contacts_Fax';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.06 WHERE VariableName = 'Comm_Contacts_Email';
UPDATE ConfigurationAdmin SET DisplayOrder = 10.07 WHERE VariableName = 'Comm_Contacts_Additional';
DELETE FROM Phrase WHERE Phrase IN ('la_fld_ManufacturerId', 'la_fld_DiscountId', 'la_fld_CouponId', 'la_fld_AffiliatePlanId', 'la_fld_AffiliateId', 'la_fld_ZoneId', 'la_fld_EngineId', 'la_fld_ShippingId', 'la_fld_ProductId', 'la_fld_OptionId', 'la_fld_CurrencyId', 'la_fld_Zone_Name');
UPDATE Phrase SET Module = 'In-Commerce' WHERE ((Phrase LIKE '%Product%' OR Phrase LIKE '%Shipping%' OR Phrase LIKE '%Coupon%' OR Phrase LIKE '%Discount%' OR Phrase LIKE '%Report%' OR Phrase LIKE '%Currency%' OR Phrase LIKE '%Cart%') AND (Module = 'Core'));
# ===== v 5.0.1 =====
UPDATE ConfigurationValues SET VariableValue = 'in-commerce/products/product_detail' WHERE VariableName = 'p_ItemTemplate';
UPDATE ConfigurationAdmin SET ValueList = '1=la_opt_Session,2=la_opt_PermanentCookie' WHERE VariableName = 'Comm_AffiliateStorageMethod';
UPDATE ConfigurationAdmin SET ValueList = 'ASC=la_common_Ascending,DESC=la_common_Descending'
WHERE VariableName IN ('product_OrderProductsByDir', 'product_OrderProductsThenByDir');
UPDATE ConfigurationAdmin SET ValueList = '1=la_opt_PriceCalculationByPrimary,2=la_opt_PriceCalculationByOptimal'
WHERE VariableName = 'Comm_PriceBracketCalculation';
UPDATE ConfigurationAdmin
SET ValueList = '1=la_opt_Sec,60=la_opt_Min,3600=la_opt_Hour,86400=la_opt_Day,604800=la_opt_Week,2419200=la_opt_Month,29030400=la_opt_Year'
WHERE VariableName IN ('product_ReviewDelay_Interval', 'product_RatingDelay_Interval');
UPDATE CustomField SET FieldLabel = 'la_fld_cust_p_ItemTemplate', Prompt = 'la_fld_cust_p_ItemTemplate' WHERE FieldName = 'p_ItemTemplate';
UPDATE Events SET Type = 1 WHERE Event = 'BACKORDER.FULLFILL';
UPDATE ConfigurationAdmin SET ValueList = 'style="width: 50px;"' WHERE VariableName IN ('product_RatingDelay_Value', 'product_ReviewDelay_Value');
# ===== v 5.0.2-B1 =====
ALTER TABLE AffiliatePayments
CHANGE Comment Comment text NULL,
CHANGE PaymentDate PaymentDate INT(10) UNSIGNED NULL DEFAULT NULL;
ALTER TABLE AffiliatePaymentTypes CHANGE Description Description text NULL;
ALTER TABLE Affiliates
CHANGE Comments Comments text NULL,
CHANGE CreatedOn CreatedOn INT(11) NULL DEFAULT NULL;
ALTER TABLE Manufacturers CHANGE Description Description text NULL;
ALTER TABLE Orders
CHANGE UserComment UserComment text NULL,
CHANGE AdminComment AdminComment text NULL,
CHANGE GWResult1 GWResult1 MEDIUMTEXT NULL,
CHANGE GWResult2 GWResult2 MEDIUMTEXT NULL,
CHANGE OrderDate OrderDate INT(10) UNSIGNED NULL DEFAULT NULL,
CHANGE PaymentExpires PaymentExpires INT(10) UNSIGNED NULL DEFAULT NULL;
ALTER TABLE PaymentTypes CHANGE PortalGroups PortalGroups text NULL;
ALTER TABLE ProductOptionCombinations CHANGE Combination Combination text NULL;
ALTER TABLE Products
CHANGE ShippingLimitation ShippingLimitation text NULL,
CHANGE PackageContent PackageContent MEDIUMTEXT NULL;
ALTER TABLE ShippingQuoteEngines CHANGE Properties Properties text NULL;
ALTER TABLE ShippingType CHANGE PortalGroups PortalGroups text NULL;
ALTER TABLE ProductFiles
CHANGE ProductId ProductId INT(11) NOT NULL DEFAULT '0',
CHANGE `Name` `Name` VARCHAR(255) NOT NULL DEFAULT '',
CHANGE Version Version VARCHAR(100) NOT NULL DEFAULT '',
CHANGE FilePath FilePath VARCHAR(255) NOT NULL DEFAULT '',
CHANGE RealPath RealPath VARCHAR(255) NOT NULL DEFAULT '',
CHANGE Size Size INT(11) NOT NULL DEFAULT '0',
CHANGE AddedOn AddedOn INT(11) NULL DEFAULT NULL;
ALTER TABLE UserFileAccess
CHANGE ProductId ProductId INT( 11 ) NOT NULL DEFAULT '0',
CHANGE PortalUserId PortalUserId INT( 11 ) NOT NULL DEFAULT '0';
ALTER TABLE GatewayConfigFields CHANGE ValueList ValueList MEDIUMTEXT NULL;
ALTER TABLE Currencies
CHANGE `Status` `Status` SMALLINT(6) NOT NULL DEFAULT '1',
CHANGE Modified Modified INT(11) NULL DEFAULT NULL;
ALTER TABLE GiftCertificates CHANGE `Status` `Status` TINYINT(1) NOT NULL DEFAULT '2';
ALTER TABLE UserDownloads
CHANGE StartedOn StartedOn INT(11) NULL DEFAULT NULL,
CHANGE EndedOn EndedOn INT(11) NULL DEFAULT NULL;
# ===== v 5.0.2-B2 =====
# ===== v 5.0.2-RC1 =====
# ===== v 5.0.2 =====
# ===== v 5.1.0-B1 =====
-UPDATE Modules SET Path = 'modules/in-commerce/' WHERE `Name` = 'In-Commerce';
\ No newline at end of file
+UPDATE Modules SET Path = 'modules/in-commerce/' WHERE `Name` = 'In-Commerce';
+
+UPDATE ConfigurationValues
+SET ValueList = '0=lu_none||<SQL+>SELECT l%3$s_Name AS OptionName, CountryStateId AS OptionValue FROM <PREFIX>CountryStates WHERE Type = 1 ORDER BY OptionName</SQL>'
+WHERE ValueList = '0=lu_none||<SQL>SELECT DestName AS OptionName, DestAbbr AS OptionValue FROM <PREFIX>StdDestinations WHERE DestParentId IS NULL Order BY OptionName</SQL>';
\ No newline at end of file
Index: branches/5.1.x/install/install_data.sql
===================================================================
--- branches/5.1.x/install/install_data.sql (revision 13464)
+++ branches/5.1.x/install/install_data.sql (revision 13465)
@@ -1,515 +1,515 @@
# Section "in-commerce:contacts":
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_CompanyName', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ContactsGeneral', 'la_text_CompanyName', 'text', NULL, NULL, 10.01, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_StoreName', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ContactsGeneral', 'la_text_StoreName', 'text', NULL, NULL, 10.02, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Contacts_Name', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ContactsGeneral', 'la_text_ContactName', 'text', NULL, NULL, 10.03, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Contacts_Phone', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ContactsGeneral', 'la_text_Phone', 'text', NULL, NULL, 10.04, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Contacts_Fax', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ContactsGeneral', 'la_text_Fax', 'text', NULL, NULL, 10.05, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Contacts_Email', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ContactsGeneral', 'la_text_Email', 'text', NULL, NULL, 10.06, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Contacts_Additional', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ContactsGeneral', 'la_text_Additional', 'textarea', NULL, NULL, 10.07, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_AddressLine1', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_StoreAddress', 'la_AddressLine1', 'text', NULL, NULL, 20.01, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_AddressLine2', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_StoreAddress', 'la_AddressLine2', 'text', NULL, NULL, 20.02, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_City', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_StoreAddress', 'la_City', 'text', NULL, NULL, 20.03, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_ZIP', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_StoreAddress', 'la_ZIP', 'text', NULL, NULL, 20.04, 0, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Country', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_StoreAddress', 'la_Country', 'select', NULL, '0=lu_none,<SQL>SELECT DestName AS OptionName, DestAbbr AS OptionValue FROM <PREFIX>StdDestinations WHERE DestParentId IS NULL Order BY OptionName</SQL>', 20.05, 0, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Country', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_StoreAddress', 'la_Country', 'select', NULL, '0=lu_none||<SQL+>SELECT l%3$s_Name AS OptionName, CountryStateId AS OptionValue FROM <PREFIX>CountryStates WHERE Type = 1 ORDER BY OptionName</SQL>', 20.05, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_State', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_StoreAddress', 'la_State', 'text', NULL, '', 20.06, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Shipping_AddressLine1', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ShippingAddress', 'la_AddressLine1', 'text', NULL, NULL, 30.01, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Shipping_AddressLine2', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ShippingAddress', 'la_AddressLine2', 'text', NULL, NULL, 30.02, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Shipping_City', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ShippingAddress', 'la_City', 'text', NULL, NULL, 30.03, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Shipping_ZIP', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ShippingAddress', 'la_ZIP', 'text', NULL, NULL, 30.04, 0, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Shipping_Country', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ShippingAddress', 'la_Country', 'select', NULL, '0=lu_none,<SQL>SELECT DestName AS OptionName, DestAbbr AS OptionValue FROM <PREFIX>StdDestinations WHERE DestParentId IS NULL Order BY OptionName</SQL>', 30.05, 0, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Shipping_Country', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ShippingAddress', 'la_Country', 'select', NULL, '0=lu_none||<SQL+>SELECT l%3$s_Name AS OptionName, CountryStateId AS OptionValue FROM <PREFIX>CountryStates WHERE Type = 1 ORDER BY OptionName</SQL>', 30.05, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Shipping_State', '', 'In-Commerce', 'in-commerce:contacts', 'la_Text_ShippingAddress', 'la_State', 'text', NULL, NULL, 30.06, 0, 1, NULL);
# Section "in-commerce:general":
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_RequireLoginBeforeCheckout', '0', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_orders_RequireLogin', 'checkbox', NULL, NULL, 10.01, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Allow_Order_Different_Types', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_AllowOrderDifferentTypes', 'checkbox', NULL, NULL, 10.02, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Enable_Backordering', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_EnableBackordering', 'checkbox', NULL, NULL, 10.03, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Process_Backorders_Auto', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_ProcessBackorderingAuto', 'checkbox', NULL, NULL, 10.04, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Next_Order_Number', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_orders_NextOrderNumber', 'text', NULL, NULL, 10.05, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Order_Number_Format_P', '6', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_OrderMainNumberDigits', 'text', NULL, NULL, 10.06, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Order_Number_Format_S', '3', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_OrderSecNumberDigits', 'text', NULL, NULL, 10.07, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_RecurringChargeInverval', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_RecurringChargeInverval', 'text', NULL, NULL, 10.08, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_AutoProcessRecurringOrders', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_AutoProcessRecurringOrders', 'checkbox', NULL, NULL, 10.09, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'MaxAddresses', '0', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_MaxAddresses', 'text', NULL, NULL, 10.1, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_MaskProcessedCreditCards', '0', 'In-Commerce', 'in-commerce:general', 'la_Text_Orders', 'la_MaskProcessedCreditCards', 'checkbox', NULL, NULL, 10.11, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_AllowOrderingInNonPrimaryCurrency', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Currencies', 'la_AllowOrderingInNonPrimaryCurrency', 'checkbox', NULL, NULL, 20.01, 0, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_ExchangeRateSource', '3', 'In-Commerce', 'in-commerce:general', 'la_Text_Currencies', 'la_ExchangeRateSource', 'select', NULL, '2=la_FederalReserveBank,3=la_EuropeanCentralBank,1=la_BankOfLatvia', 20.02, 0, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_ExchangeRateSource', '3', 'In-Commerce', 'in-commerce:general', 'la_Text_Currencies', 'la_ExchangeRateSource', 'select', NULL, '2=la_FederalReserveBank||3=la_EuropeanCentralBank||1=la_BankOfLatvia', 20.02, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_DefaultCouponDuration', '14', 'In-Commerce', 'in-commerce:general', 'la_Text_Coupons', 'la_conf_DefaultCouponDuration', 'text', NULL, NULL, 30.01, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_RegisterAsAffiliate', '0', 'In-Commerce', 'in-commerce:general', 'la_Text_Affiliates', 'la_prompt_register_as_affiliate', 'checkbox', NULL, '', 40.01, 0, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_AffiliateStorageMethod', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Affiliates', 'la_prompt_affiliate_storage_method', 'radio', NULL, '1=la_opt_Session,2=la_opt_PermanentCookie', 40.02, 0, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_AffiliateStorageMethod', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_Affiliates', 'la_prompt_affiliate_storage_method', 'radio', NULL, '1=la_opt_Session||2=la_opt_PermanentCookie', 40.02, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_AffiliateCookieDuration', '30', 'In-Commerce', 'in-commerce:general', 'la_Text_Affiliates', 'la_prompt_affiliate_cookie_duration', 'text', NULL, '', 40.03, 0, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_PriceBracketCalculation', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_PricingCalculation', 'la_prompt_PriceBracketCalculation', 'radio', NULL, '1=la_opt_PriceCalculationByPrimary,2=la_opt_PriceCalculationByOptimal', 50, 0, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_PriceBracketCalculation', '1', 'In-Commerce', 'in-commerce:general', 'la_Text_PricingCalculation', 'la_prompt_PriceBracketCalculation', 'radio', NULL, '1=la_opt_PriceCalculationByPrimary||2=la_opt_PriceCalculationByOptimal', 50, 0, 1, NULL);
# Section "in-commerce:output":
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsBy', 'Name', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_OrderProductsBy', 'select', NULL, '=la_none,Name=la_fld_Title,SKU=la_fld_SKU,Manufacturer=la_fld_Manufacturer,Price=la_fld_Price,CreatedOn=la_fld_CreatedOn,Modified=la_fld_Modified,Qty=la_fld_Qty,<SQL>SELECT Prompt AS OptionName, CONCAT("cust_", FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 11) AND (IsSystem = 0)</SQL>', 10.01, 1, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsByDir', 'ASC', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_OrderProductsBy', 'select', NULL, 'ASC=la_common_Ascending,DESC=la_common_Descending', 10.01, 2, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsThenBy', 'Price', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_ThenBy', 'select', NULL, '=la_none,Name=la_fld_Title,SKU=la_fld_SKU,Manufacturer=la_fld_Manufacturer,Price=la_fld_Price,CreatedOn=la_fld_CreatedOn,Modified=la_fld_Modified,Qty=la_fld_Qty,<SQL>SELECT Prompt AS OptionName, CONCAT("cust_", FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 11) AND (IsSystem = 0)</SQL>', 10.02, 1, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsThenByDir', 'ASC', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_ThenBy', 'select', NULL, 'ASC=la_common_Ascending,DESC=la_common_Descending', 10.02, 2, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsBy', 'Name', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_OrderProductsBy', 'select', NULL, '=la_none||Name=la_fld_Title||SKU=la_fld_SKU||Manufacturer=la_fld_Manufacturer||Price=la_fld_Price||CreatedOn=la_fld_CreatedOn||Modified=la_fld_Modified||Qty=la_fld_Qty||<SQL>SELECT Prompt AS OptionName CONCAT("cust_" FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 11) AND (IsSystem = 0)</SQL>', 10.01, 1, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsByDir', 'ASC', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_OrderProductsBy', 'select', NULL, 'ASC=la_common_Ascending||DESC=la_common_Descending', 10.01, 2, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsThenBy', 'Price', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_ThenBy', 'select', NULL, '=la_none||Name=la_fld_Title||SKU=la_fld_SKU||Manufacturer=la_fld_Manufacturer||Price=la_fld_Price||CreatedOn=la_fld_CreatedOn||Modified=la_fld_Modified||Qty=la_fld_Qty||<SQL>SELECT Prompt AS OptionName CONCAT("cust_" FieldName) AS OptionValue FROM <PREFIX>CustomField WHERE (Type = 11) AND (IsSystem = 0)</SQL>', 10.02, 1, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_OrderProductsThenByDir', 'ASC', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_ThenBy', 'select', NULL, 'ASC=la_common_Ascending||DESC=la_common_Descending', 10.02, 2, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Perpage_Products', '10', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_Perpage_Products', 'text', NULL, NULL, 10.03, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Perpage_Products_Short', '3', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_Perpage_Products_Shortlist', 'text', NULL, NULL, 10.04, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Product_NewDays', '7', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_DaysToBeNew', 'text', NULL, NULL, 10.05, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Product_MinPopRating', '4', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_fld_Product_MinPopRating', 'text', NULL, NULL, 10.06, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Product_MinPopVotes', '1', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_fld_Product_MinPopVotes', 'text', NULL, NULL, 10.07, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Product_MaxHotNumber', '5', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_fld_Product_MaxHotNumber', 'text', NULL, NULL, 10.08, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'products_EditorPicksAboveRegular', '1', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_conf_EditorPicksAboveRegular', 'checkbox', NULL, NULL, 10.09, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_RatingDelay_Value', '30', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_prompt_DupRating', 'text', '', 'style="width: 50px;"', 10.1, 1, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_RatingDelay_Interval', '86400', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_prompt_DupRating', 'select', '', '1=la_opt_Sec,60=la_opt_Min,3600=la_opt_Hour,86400=la_opt_Day,604800=la_opt_Week,2419200=la_opt_Month,29030400=la_opt_Year', 10.1, 2, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_RatingDelay_Interval', '86400', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_prompt_DupRating', 'select', '', '1=la_opt_Sec||60=la_opt_Min||3600=la_opt_Hour||86400=la_opt_Day||604800=la_opt_Week||2419200=la_opt_Month||29030400=la_opt_Year', 10.1, 2, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'ShowProductImagesInOrders', '0', 'In-Commerce', 'in-commerce:output', 'la_Text_Products', 'la_config_ShowProductImagesInOrders', 'checkbox', NULL, NULL, 10.11, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Perpage_Reviews', '10', 'In-Commerce', 'in-commerce:output', 'la_Text_Reviews', 'la_config_PerpageReviews', 'text', NULL, NULL, 20.01, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_ReviewDelay_Value', '30', 'In-Commerce', 'in-commerce:output', 'la_Text_Reviews', 'la_prompt_DupReviews', 'text', '', 'style="width: 50px;"', 20.02, 1, 1, NULL);
-INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_ReviewDelay_Interval', '86400', 'In-Commerce', 'in-commerce:output', 'la_Text_Reviews', 'la_prompt_DupReviews', 'select', '', '1=la_opt_Sec,60=la_opt_Min,3600=la_opt_Hour,86400=la_opt_Day,604800=la_opt_Week,2419200=la_opt_Month,29030400=la_opt_Year', 20.02, 2, 1, NULL);
+INSERT INTO ConfigurationValues VALUES(DEFAULT, 'product_ReviewDelay_Interval', '86400', 'In-Commerce', 'in-commerce:output', 'la_Text_Reviews', 'la_prompt_DupReviews', 'select', '', '1=la_opt_Sec||60=la_opt_Min||3600=la_opt_Hour||86400=la_opt_Day||604800=la_opt_Week||2419200=la_opt_Month||29030400=la_opt_Year', 20.02, 2, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Perpage_Manufacturers', '10', 'In-Commerce', 'in-commerce:output', 'la_Text_Manufacturers', 'la_Perpage_Manufacturers', 'text', NULL, NULL, 30.01, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Comm_Perpage_Manufacturers_Short', '3', 'In-Commerce', 'in-commerce:output', 'la_Text_Manufacturers', 'la_Perpage_Manufacturers_Short', 'text', NULL, NULL, 30.02, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'p_CategoryTemplate', '/in-commerce/designs/section', 'In-Commerce', 'in-commerce:output', 'la_section_Templates', 'la_fld_CategoryTemplate', 'text', '', '', 40.01, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'p_ItemTemplate', 'in-commerce/designs/detail', 'In-Commerce', 'in-commerce:output', 'la_section_Templates', 'la_fld_ItemTemplate', 'text', '', '', 40.02, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'p_MaxImageCount', '5', 'In-Commerce', 'in-commerce:output', 'la_section_ImageSettings', 'la_config_MaxImageCount', 'text', '', '', 50.01, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'p_ThumbnailImageWidth', '120', 'In-Commerce', 'in-commerce:output', 'la_section_ImageSettings', 'la_config_ThumbnailImageWidth', 'text', '', '', 50.02, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'p_ThumbnailImageHeight', '120', 'In-Commerce', 'in-commerce:output', 'la_section_ImageSettings', 'la_config_ThumbnailImageHeight', 'text', '', '', 50.03, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'p_FullImageWidth', '450', 'In-Commerce', 'in-commerce:output', 'la_section_ImageSettings', 'la_config_FullImageWidth', 'text', '', '', 50.04, 0, 0, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'p_FullImageHeight', '450', 'In-Commerce', 'in-commerce:output', 'la_section_ImageSettings', 'la_config_FullImageHeight', 'text', '', '', 50.05, 0, 0, NULL);
# Section "in-commerce:search":
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'Search_ShowMultiple_products', '1', 'In-Commerce', 'in-commerce:search', 'la_config_ShowMultiple', 'la_Text_MultipleShow', 'text', NULL, NULL, 0, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'SearchRel_Keyword_products', '70', 'In-Commerce', 'in-commerce:search', 'la_config_SearchRel_DefaultKeyword', 'la_text_keyword', 'text', NULL, NULL, 0, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'SearchRel_Pop_products', '10', 'In-Commerce', 'in-commerce:search', 'la_config_DefaultPop', 'la_text_popularity', 'text', NULL, NULL, 0, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'SearchRel_Rating_products', '10', 'In-Commerce', 'in-commerce:search', 'la_config_DefaultRating', 'la_prompt_Rating', 'text', NULL, NULL, 0, 0, 1, NULL);
INSERT INTO ConfigurationValues VALUES(DEFAULT, 'SearchRel_Increase_products', '30', 'In-Commerce', 'in-commerce:search', 'la_config_DefaultIncreaseImportance', 'la_text_increase_importance', 'text', NULL, NULL, 0, 0, 1, NULL);
INSERT INTO Currencies VALUES (6, 'AFA', '', 0, 'la_AFA', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (7, 'ALL', '', 0, 'la_ALL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (8, 'DZD', '', 0, 'la_DZD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (9, 'ADP', '', 0, 'la_ADP', 1, 1124019233, 0, 0, 0);
INSERT INTO Currencies VALUES (10, 'AOA', '', 0, 'la_AOA', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (11, 'ARS', '', 0, 'la_ARS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (12, 'AMD', '', 0, 'la_AMD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (13, 'AWG', '', 0, 'la_AWG', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (14, 'AZM', '', 0, 'la_AZM', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (15, 'BSD', '', 0, 'la_BSD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (16, 'BHD', '', 0, 'la_BHD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (17, 'BDT', '', 0, 'la_BDT', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (18, 'BBD', '', 0, 'la_BBD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (19, 'BYR', '', 0, 'la_BYR', 0.46440677966102, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (20, 'BZD', '', 0, 'la_BZD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (21, 'BMD', '', 0, 'la_BMD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (22, 'BTN', '', 0, 'la_BTN', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (23, 'INR', '', 0, 'la_INR', 0.022962112514351, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (24, 'BOV', '', 0, 'la_BOV', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (25, 'BOB', '', 0, 'la_BOB', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (26, 'BAM', '', 0, 'la_BAM', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (27, 'BWP', '', 0, 'la_BWP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (28, 'BRL', '', 0, 'la_BRL', 0.42331625957753, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (29, 'BND', '', 0, 'la_BND', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (30, 'BGL', '', 0, 'la_BGL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (31, 'BGN', '', 0, 'la_BGN', 0.60754639807761, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (32, 'BIF', '', 0, 'la_BIF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (33, 'KHR', '', 0, 'la_KHR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (34, 'CAD', '', 0, 'la_CAD', 0.80579100834068, 1120657409, 0, 0, 0);
INSERT INTO Currencies VALUES (35, 'CVE', '', 0, 'la_CVE', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (36, 'KYD', '', 0, 'la_KYD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (37, 'XAF', '', 0, 'la_XAF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (38, 'CLF', '', 0, 'la_CLF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (39, 'CLP', '', 0, 'la_CLP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (40, 'CNY', '', 0, 'la_CNY', 0.12082358922217, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (41, 'COP', '', 0, 'la_COP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (42, 'KMF', '', 0, 'la_KMF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (43, 'CDF', '', 0, 'la_CDF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (44, 'CRC', '', 0, 'la_CRC', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (45, 'HRK', '', 0, 'la_HRK', 0.16222968545216, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (46, 'CUP', '', 0, 'la_CUP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (47, 'CYP', '', 0, 'la_CYP', 2.0723753051971, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (48, 'CZK', '', 0, 'la_CZK', 0.039512535745162, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (49, 'DKK', '', 0, 'la_DKK', 0.15944343065693, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (50, 'DJF', '', 0, 'la_DJF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (51, 'DOP', '', 0, 'la_DOP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (52, 'TPE', '', 0, 'la_TPE', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (53, 'ECV', '', 0, 'la_ECV', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (54, 'ECS', '', 0, 'la_ECS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (55, 'EGP', '', 0, 'la_EGP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (56, 'SVC', '', 0, 'la_SVC', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (57, 'ERN', '', 0, 'la_ERN', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (58, 'EEK', '', 0, 'la_EEK', 0.075946211956591, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (59, 'ETB', '', 0, 'la_ETB', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (60, 'FKP', '', 0, 'la_FKP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (61, 'FJD', '', 0, 'la_FJD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (62, 'GMD', '', 0, 'la_GMD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (63, 'GEL', '', 0, 'la_GEL', 1, 1124019233, 0, 0, 0);
INSERT INTO Currencies VALUES (64, 'GHC', '', 0, 'la_GHC', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (65, 'GIP', '', 0, 'la_GIP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (66, 'GTQ', '', 0, 'la_GTQ', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (67, 'GNF', '', 0, 'la_GNF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (68, 'GWP', '', 0, 'la_GWP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (69, 'GYD', '', 0, 'la_GYD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (70, 'HTG', '', 0, 'la_HTG', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (71, 'HNL', '', 0, 'la_HNL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (72, 'HKD', '', 0, 'la_HKD', 0.1286359158665, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (73, 'HUF', '', 0, 'la_HUF', 0.0048070388349515, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (74, 'ISK', '', 0, 'la_ISK', 0.015143366891806, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (75, 'IDR', '', 0, 'la_IDR', 0.00010126584435926, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (76, 'IRR', '', 0, 'la_IRR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (77, 'IQD', '', 0, 'la_IQD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (78, 'ILS', '', 0, 'la_ILS', 0.21864406779661, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (79, 'JMD', '', 0, 'la_JMD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (80, 'JPY', '', 0, 'la_JPY', 0.0089325716003909, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (81, 'JOD', '', 0, 'la_JOD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (82, 'KZT', '', 0, 'la_KZT', 7.3559322033898, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (83, 'KES', '', 0, 'la_KES', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (84, 'AUD', '', 0, 'la_AUD', 0.74088160109733, 1120650640, 1, 0, 0);
INSERT INTO Currencies VALUES (85, 'KPW', '', 0, 'la_KPW', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (86, 'KRW', '', 0, 'la_KRW', 0.00095066281590758, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (87, 'KWD', '', 0, 'la_KWD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (88, 'KGS', '', 0, 'la_KGS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (89, 'LAK', '', 0, 'la_LAK', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (90, 'LVL', '', 0, 'la_LVL', 1.7697169946847, 1124019016, 0, 0, 0);
INSERT INTO Currencies VALUES (91, 'LBP', '', 0, 'la_LBP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (92, 'LSL', '', 0, 'la_LSL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (93, 'LRD', '', 0, 'la_LRD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (94, 'LYD', '', 0, 'la_LYD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (95, 'CHF', '', 0, 'la_CHF', 0.76560788608981, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (96, 'LTL', '', 0, 'la_LTL', 0.34415546802595, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (97, 'MOP', '', 0, 'la_MOP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (98, 'MKD', '', 0, 'la_MKD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (99, 'MGF', '', 0, 'la_MGF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (100, 'MWK', '', 0, 'la_MWK', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (101, 'MYR', '', 0, 'la_MYR', 0.2631019594819, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (102, 'MVR', '', 0, 'la_MVR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (103, 'MTL', '', 0, 'la_MTL', 2.7679944095038, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (104, 'EUR', '&euro;&nbsp;', 0, 'la_EUR', 1.2319, 1124019016, 1, 0, 0);
INSERT INTO Currencies VALUES (105, 'MRO', '', 0, 'la_MRO', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (106, 'MUR', '', 0, 'la_MUR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (107, 'MXN', '', 0, 'la_MXN', 0.092980009298001, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (108, 'MXV', '', 0, 'la_MXV', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (109, 'MDL', '', 0, 'la_MDL', 0.079830508474576, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (110, 'MNT', '', 0, 'la_MNT', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (111, 'XCD', '', 0, 'la_XCD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (112, 'MZM', '', 0, 'la_MZM', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (113, 'MMK', '', 0, 'la_MMK', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (114, 'ZAR', '', 0, 'la_ZAR', 0.14487399875645, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (115, 'NAD', '', 0, 'la_NAD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (116, 'NPR', '', 0, 'la_NPR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (117, 'ANG', '', 0, 'la_ANG', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (118, 'XPF', '', 0, 'la_XPF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (119, 'NZD', '', 0, 'la_NZD', 0.67409802586794, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (120, 'NIO', '', 0, 'la_NIO', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (121, 'NGN', '', 0, 'la_NGN', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (122, 'NOK', '', 0, 'la_NOK', 0.15015163002274, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (123, 'OMR', '', 0, 'la_OMR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (124, 'PKR', '', 0, 'la_PKR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (125, 'PAB', '', 0, 'la_PAB', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (126, 'PGK', '', 0, 'la_PGK', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (127, 'PYG', '', 0, 'la_PYG', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (128, 'PEN', '', 0, 'la_PEN', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (129, 'PHP', '', 0, 'la_PHP', 0.017769769111138, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (130, 'PLN', '', 0, 'la_PLN', 0.29408270844161, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (131, 'USD', '$&nbsp;', 0, 'la_USD', 1, 1124019100, 1, 1, 0);
INSERT INTO Currencies VALUES (132, 'QAR', '', 0, 'la_QAR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (133, 'ROL', '', 0, 'la_ROL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (134, 'RUB', NULL, 0, 'la_RUB', 0.0347, 1123850285, 0, 0, 0);
INSERT INTO Currencies VALUES (136, 'RWF', '', 0, 'la_RWF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (137, 'SHP', '', 0, 'la_SHP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (138, 'WST', '', 0, 'la_WST', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (139, 'STD', '', 0, 'la_STD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (140, 'SAR', '', 0, 'la_SAR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (141, 'SCR', '', 0, 'la_SCR', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (142, 'SLL', '', 0, 'la_SLL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (143, 'SGD', '', 0, 'la_SGD', 0.58838383838384, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (144, 'SKK', '', 0, 'la_SKK', 0.031050431147113, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (145, 'SIT', '', 0, 'la_SIT', 0.0049628299365185, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (146, 'SBD', '', 0, 'la_SBD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (147, 'SOS', '', 0, 'la_SOS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (148, 'LKR', '', 0, 'la_LKR', 0.0099920063948841, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (149, 'SDD', '', 0, 'la_SDD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (150, 'SRG', '', 0, 'la_SRG', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (151, 'SZL', '', 0, 'la_SZL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (152, 'SEK', '', 0, 'la_SEK', 0.12594327624216, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (153, 'SYP', '', 0, 'la_SYP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (154, 'TWD', '', 0, 'la_TWD', 0.031298904538341, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (155, 'TJS', '', 0, 'la_TJS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (156, 'TZS', '', 0, 'la_TZS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (157, 'THB', '', 0, 'la_THB', 0.024061474911918, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (158, 'XOF', '', 0, 'la_XOF', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (159, 'NZD', '', 0, 'la_NZD', 0.67409802586794, 1120650640, 0, 0, 0);
INSERT INTO Currencies VALUES (160, 'TOP', '', 0, 'la_TOP', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (161, 'TTD', '', 0, 'la_TTD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (162, 'TND', '', 0, 'la_TND', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (163, 'TRL', '', 0, 'la_TRL', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (164, 'TMM', '', 0, 'la_TMM', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (165, 'UGX', '', 0, 'la_UGX', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (166, 'UAH', '', 0, 'la_UAH', 0.19830508474576, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (167, 'AED', '', 0, 'la_AED', 0.2728813559322, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (168, 'GBP', NULL, 0, 'la_GBP', 1.7543367535248, 1120657409, 1, 0, 0);
INSERT INTO Currencies VALUES (169, 'USS', '', 0, 'la_USS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (170, 'USN', '', 0, 'la_USN', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (171, 'UYU', '', 0, 'la_UYU', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (172, 'UZS', '', 0, 'la_UZS', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (173, 'VUV', '', 0, 'la_VUV', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (174, 'VEB', '', 0, 'la_VEB', 0.00046628741956542, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (175, 'VND', '', 0, 'la_VND', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (176, 'MAD', '', 0, 'la_MAD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (177, 'YER', '', 0, 'la_YER', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (178, 'YUM', '', 0, 'la_YUM', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (179, 'ZMK', '', 0, 'la_ZMK', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (180, 'ZWD', '', 0, 'la_ZWD', 1, 1120641028, 0, 0, 0);
INSERT INTO Currencies VALUES (181, 'AFN', '', 0, 'la_AFN', 0.02, 1120641028, 0, 0, 0);
INSERT INTO CustomField VALUES (DEFAULT, 11, 'Features', 'la_Features', 1, 'la_Text_CustomFields', 'la_Features', 'textarea', 'rows="5" cols="70"', '', 0, 1, 0, 0);
INSERT INTO CustomField VALUES (DEFAULT, 11, 'Availability', 'la_Availability', 1, 'la_Text_CustomFields', 'la_Availability', 'text', 'size="70"', '', 0, 1, 0, 0);
INSERT INTO CustomField VALUES (DEFAULT, 1, 'p_ItemTemplate', 'la_fld_cust_p_ItemTemplate', 0, 'la_title_SystemCF', 'la_fld_cust_p_ItemTemplate', 'text', NULL, '', 0, 0, 1, 0);
INSERT INTO CustomField VALUES (DEFAULT, 6, 'shipping_addr_block', 'la_fld_BlockShippingAddress', 0, 'la_section_StoreSettings', 'la_fld_BlockShippingAddress', 'checkbox', '1=+Block', '', 0, 1, 1, 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.SUBMIT', NULL, 1, 1, NULL, 'In-Commerce', 'Order Submitted', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.SUBMIT', NULL, 1, 1, NULL, 'In-Commerce', 'Order Submitted', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.APPROVE', NULL, 1, 0, NULL, 'In-Commerce', 'Order Approved', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.DENY', NULL, 1, 0, NULL, 'In-Commerce', 'Order Denied', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.SHIP', NULL, 1, 0, NULL, 'In-Commerce', 'Order Shipped', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'BACKORDER.ADD', NULL, 1, 1, NULL, 'In-Commerce', 'Backorder Added', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'BACKORDER.ADD', NULL, 1, 1, NULL, 'In-Commerce', 'Backorder Added', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'BACKORDER.FULLFILL', NULL, 1, 0, NULL, 'In-Commerce', 'Back-order is Fulfilled', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'BACKORDER.PROCESS', NULL, 1, 0, NULL, 'In-Commerce', 'Backorder Processed', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'PRODUCT.SUGGEST', NULL, 1, 0, NULL, 'In-Commerce', 'Suggest product to a friend', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'PRODUCT.SUGGEST', NULL, 1, 1, NULL, 'In-Commerce', 'Suggest product to a friend', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.REGISTER', NULL, 1, 1, NULL, 'In-Commerce', 'Affiliate registered', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.REGISTER', NULL, 1, 1, NULL, 'In-Commerce', 'Affiliate registered', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.PAYMENT', NULL, 1, 0, NULL, 'In-Commerce', 'Affiliate payment issued', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.PAYMENT', NULL, 1, 0, NULL, 'In-Commerce', 'Affiliate payment issued', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.REGISTRATION.APPROVED', NULL, 1, 0, NULL, 'In-Commerce', 'Affiliate registration approved', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.REGISTRATION.APPROVED', NULL, 0, 0, NULL, 'In-Commerce', 'Affiliate registration approved', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.REGISTRATION.DENIED', NULL, 1, 0, NULL, 'In-Commerce', 'Affiliate registration denied', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.REGISTRATION.DENIED', NULL, 0, 0, NULL, 'In-Commerce', 'Affiliate registration denied', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.PAYMENT.TYPE.CHANGED', NULL, 1, 0, NULL, 'In-Commerce', 'Affiliate payment type changed', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'AFFILIATE.PAYMENT.TYPE.CHANGED', NULL, 1, 0, NULL, 'In-Commerce', 'Affiliate payment type changed', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.RECURRING.PROCESSED', NULL, 1, 0, NULL, 'In-Commerce', 'Recurring Order Processed', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.RECURRING.PROCESSED', NULL, 1, 0, NULL, 'In-Commerce', 'Recurring Order Processed', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.RECURRING.DENIED', NULL, 1, 0, NULL, 'In-Commerce', 'Recurring Order Denied', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'ORDER.RECURRING.DENIED', NULL, 1, 0, NULL, 'In-Commerce', 'Recurring Order Denied', 1);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'USER.GIFTCERTIFICATE', NULL, 1, 0, NULL, 'In-Commerce', 'Gift Certificate', 0);
INSERT INTO Events (EventId, Event, ReplacementTags, Enabled, FrontEndOnly, FromUserId, Module, Description, Type) VALUES(DEFAULT, 'USER.GIFTCERTIFICATE', NULL, 1, 0, NULL, 'In-Commerce', 'Gift Certificate', 1);
INSERT INTO GatewayConfigFields VALUES (1, 'submit_url', 'Gateway URL', 'text', '', 2);
INSERT INTO GatewayConfigFields VALUES (2, 'user_account', 'Authorize.net User Name', 'text', '', 2);
INSERT INTO GatewayConfigFields VALUES (4, 'transaction_key', 'Authorize.net Transaction Key', 'text', '', 2);
INSERT INTO GatewayConfigFields VALUES (9, 'business_account', 'Username', 'text', '', 4);
INSERT INTO GatewayConfigFields VALUES (10, 'submit_url', 'Gateway URL', 'text', '', 4);
INSERT INTO GatewayConfigFields VALUES (11, 'currency_code', 'Payment Currency Code', 'text', '', 4);
INSERT INTO GatewayConfigFields VALUES (12, 'shipping_control', 'Shipping Control', 'select', '3=la_CreditDirect,4=la_CreditPreAuthorize', 2);
INSERT INTO GatewayConfigFields VALUES (13, 'encapsulate_char', 'Encapsulate Char', 'text', '', 2);
INSERT INTO GatewayConfigFields VALUES (14, 'shipping_control', 'Shipping Control', 'select', '3=la_CreditDirect,4=la_CreditPreAuthorize', 4);
INSERT INTO GatewayConfigValues VALUES (36, 12, 3, '4');
INSERT INTO GatewayConfigValues VALUES (35, 1, 3, 'https://secure.authorize.net/gateway/transact.dll');
INSERT INTO GatewayConfigValues VALUES (34, 2, 3, '');
INSERT INTO GatewayConfigValues VALUES (33, 4, 3, '');
INSERT INTO GatewayConfigValues VALUES (32, 9, 4, '');
INSERT INTO GatewayConfigValues VALUES (31, 10, 4, 'https://www.paypal.com/cgi-bin/webscr');
INSERT INTO GatewayConfigValues VALUES (37, 11, 4, 'USD');
INSERT INTO GatewayConfigValues VALUES (38, 13, 3, '|');
INSERT INTO GatewayConfigValues VALUES (39, 14, 4, '4');
INSERT INTO Gateways VALUES (1, 'None', 'kGWBase', 'gw_base.php', 0);
INSERT INTO Gateways VALUES (2, 'Credit Card (Authorize.Net)', 'kGWAuthorizeNet', 'authorizenet.php', 1);
INSERT INTO Gateways VALUES (3, 'Credit Card (Manual Processing)', 'kGWBase', 'gw_base.php', 1);
INSERT INTO Gateways VALUES (4, 'PayPal', 'kGWPayPal', 'paypal.php', 0);
INSERT INTO ItemTypes VALUES (11, 'In-Commerce', 'p', 'Products', 'Name', 'CreatedById', NULL, NULL, '', 0, '', 'ProductsItem', 'Product');
INSERT INTO ItemTypes VALUES (13, 'In-Commerce', 'ord', 'Orders', 'OrderNumber', '', NULL, NULL, '', 0, '', 'OrdersItem', 'Order');
INSERT INTO PaymentTypes VALUES (1, 'Credit Card (manual)', 'Credit Card', 'Please enter your credit card details.', NULL, 1, 0, 1, 1, 3, DEFAULT, DEFAULT, ',15,');
INSERT INTO PaymentTypes VALUES (4, 'PayPal', 'PayPal', 'You will be redirected to PayPal site to make the payment after confirming your order on the next checkout step.', NULL, 0, 0, 0, 1, 4, DEFAULT, DEFAULT, ',15,');
INSERT INTO PaymentTypes VALUES (2, 'Check/MO', 'Check or Money Order', NULL, NULL, 0, 0, 0, 1, 1, 1, DEFAULT, ',15,');
INSERT INTO PaymentTypes VALUES (3, 'Authorize.Net', 'Credit Card', 'Please enter your Credit Card details below. Your credit card will not be charged until you confirm your purchase on the next(last) step of checkout process.', NULL, 0, 0, 0, 1, 2, DEFAULT, DEFAULT, ',15,');
INSERT INTO PaymentTypeCurrencies VALUES (DEFAULT, 4, 131);
INSERT INTO PaymentTypeCurrencies VALUES (DEFAULT, 2, 131);
INSERT INTO PaymentTypeCurrencies VALUES (DEFAULT, 3, 131);
INSERT INTO PaymentTypeCurrencies VALUES (DEFAULT, 1, 131);
INSERT INTO PermissionConfig VALUES (DEFAULT, 'PRODUCT.RATE', 'lu_PermName_Product.Rate_desc', 'lu_PermName_Product.Rate_error', 'In-Commerce');
INSERT INTO PermissionConfig VALUES (DEFAULT, 'PRODUCT.REVIEW', 'lu_PermName_Product.Review_desc', 'lu_PermName_Product.Review_error', 'In-Commerce');
INSERT INTO PermissionConfig VALUES (DEFAULT, 'PRODUCT.REVIEW.PENDING', 'lu_PermName_Product.Review_Pending_desc', ' lu_PermName_Product.Review_Pending_error', 'In-Commerce');
INSERT INTO PermissionConfig VALUES (DEFAULT, 'PRODUCT.ADD', 'lu_PermName_Product.Add_desc', 'lu_PermName_Product.Add_error', 'In-Commerce');
INSERT INTO PermissionConfig VALUES (DEFAULT, 'PRODUCT.DELETE', 'lu_PermName_Product.Delete_desc', 'lu_PermName_Product.Delete_error', 'In-Commerce');
INSERT INTO PermissionConfig VALUES (DEFAULT, 'PRODUCT.MODIFY', 'lu_PermName_Product.Modify_desc', 'lu_PermName_Product.Modify_desc', 'In-Commerce');
INSERT INTO PermissionConfig VALUES (DEFAULT, 'PRODUCT.VIEW', 'lu_PermName_Product.View_desc', 'lu_PermName_Product.View_error', 'In-Commerce');
INSERT INTO Permissions VALUES (DEFAULT, 'CATEGORY.VIEW', 14, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.VIEW', 14, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.RATE', 13, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.REVIEW', 13, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.REVIEW.PENDING', 13, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'CATEGORY.VIEW', 13, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'FAVORITES', 13, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.VIEW', 13, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'CATEGORY.VIEW', 12, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.VIEW', 12, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'CATEGORY.VIEW', 11, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.ADD', 11, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.DELETE', 11, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.MODIFY', 11, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'PRODUCT.VIEW', 11, 1, 0, {ProductCatId});
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:products.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:setting_folder.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.advanced:deny', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.advanced:archive', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.advanced:place', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.advanced:process', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.advanced:ship', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:orders.advanced:reset_to_pending', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:discounts.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:discounts.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:discounts.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:discounts.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:discounts.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:discounts.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:coupons.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:coupons.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:coupons.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:coupons.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:coupons.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:coupons.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:manufacturers.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:manufacturers.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:manufacturers.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:manufacturers.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.advanced:move_up', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.advanced:move_down', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.advanced:update_rate', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:currencies.advanced:set_primary', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping_quote_engines.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping_quote_engines.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping_quote_engines.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:shipping_quote_engines.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:payment_types.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:payment_types.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:payment_types.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:payment_types.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:taxes.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:taxes.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:taxes.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:taxes.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliates.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliates.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliates.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliates.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliates.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliates.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_plans.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_plans.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_plans.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_plans.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_plans.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_plans.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_plans.advanced:set_primary', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.advanced:set_primary', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.advanced:move_up', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:affiliate_payment_types.advanced:move_down', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:general.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:general.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:output.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:output.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:search.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:search.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:incommerce_configemail.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:incommerce_configemail.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:contacts.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:contacts.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:configuration_custom.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:configuration_custom.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:configuration_custom.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:configuration_custom.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:paymentlog.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:downloadlog.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:downloadlog.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:gift-certificates.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:gift-certificates.add', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:gift-certificates.edit', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:gift-certificates.delete', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:gift-certificates.advanced:approve', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:gift-certificates.advanced:decline', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:reports.view', 11, 1, 1, 0);
INSERT INTO Permissions VALUES (DEFAULT, 'in-commerce:reports.add', 11, 1, 1, 0);
INSERT INTO SearchConfig VALUES ('Products', 'OrgId', 0, 0, 'lu_fielddesc_prod_orgid', 'lu_field_orgid', 'In-Commerce', 'la_Text_Products', 19, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'NewItem', 0, 1, 'lu_fielddesc_prod_newitem', 'lu_field_newproduct', 'In-Commerce', 'la_Text_Products', 18, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'PopItem', 0, 1, 'lu_fielddesc_prod_popitem', 'lu_field_popproduct', 'In-Commerce', 'la_Text_Products', 17, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'HotItem', 0, 1, 'lu_fielddesc_prod_topseller', 'lu_field_topseller', 'In-Commerce', 'la_Text_Products', 16, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'EditorsPick', 0, 1, 'lu_fielddesc_prod_editorspick', 'lu_field_editorspick', 'In-Commerce', 'la_Text_Products', 14, DEFAULT, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'CachedReviewsQty', 0, 0, 'lu_fielddesc_prod_cachedreviewsqty', 'lu_field_cachedreviewsqty', 'In-Commerce', 'la_Text_Products', 9, DEFAULT, 0, 'range', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'CachedVotesQty', 0, 0, 'lu_fielddesc_prod_cachedvotesqty', 'lu_field_cachedvotesqty', 'In-Commerce', 'la_Text_Products', 8, DEFAULT, 0, 'range', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'ProductId', 0, 0, 'lu_fielddesc_prod_productid', 'lu_field_productid', 'In-Commerce', 'la_Text_Products', 0, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'Name', 1, 1, 'lu_fielddesc_prod_producttitle', 'lu_field_producttitle', 'In-Commerce', 'la_Text_Products', 1, DEFAULT, 3, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'Description', 1, 1, 'lu_fielddesc_prod_description', 'lu_field_description', 'In-Commerce', 'la_Text_Products', 2, DEFAULT, 1, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'CreatedOn', 0, 1, 'lu_fielddesc_prod_createdon', 'lu_field_createdon', 'In-Commerce', 'la_Text_Products', 4, DEFAULT, 0, 'date', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'Modified', 0, 1, 'lu_fielddesc_prod_modified', 'lu_field_modified', 'In-Commerce', 'la_Text_Products', 5, DEFAULT, 0, 'date', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'Hits', 0, 1, 'lu_fielddesc_prod_qtysold', 'lu_field_qtysold', 'In-Commerce', 'la_Text_Products', 6, DEFAULT, 0, 'range', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'CachedRating', 0, 0, 'lu_fielddesc_prod_cachedrating', 'lu_field_cachedrating', 'In-Commerce', 'la_Text_Products', 7, DEFAULT, 0, 'range', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('CustomField', 'Features', 1, 0, 'la_Features', 'la_Features', 'In-Commerce', 'la_Text_CustomFields', 0, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'SKU', 1, 1, 'lu_fielddesc_prod_sku', 'lu_field_sku', 'In-Commerce', 'la_Text_Products', 0, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'DescriptionExcerpt', 1, 0, 'lu_fielddesc_prod_descriptionex', 'lu_field_descriptionex', 'In-Commerce', 'la_Text_Products', 2, DEFAULT, 1, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'ManufacturerId', 1, 1, 'lu_fielddesc_prod_manufacturer', 'lu_field_manufacturer', 'In-Commerce', 'la_Text_Products', 3, DEFAULT, 2, 'text', 'Manufacturers.Name', '{ForeignTable}.ManufacturerId={LocalTable}.ManufacturerId', NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('Products', 'Price', 1, 1, 'lu_fielddesc_prod_price', 'lu_field_price', 'In-Commerce', 'la_Text_Products', 23, DEFAULT, 2, 'range', 'CALC:MIN( IF({PREFIX}ProductsDiscounts.Type = 1, {PREFIX}ProductsPricing.Price - {PREFIX}ProductsDiscounts.Amount, IF({PREFIX}ProductsDiscounts.Type = 2, ({PREFIX}ProductsPricing.Price * (1-{PREFIX}ProductsDiscounts.Amount/100)), {PREFIX}ProductsPricing.Price ) ) )', '{PREFIX}ProductsPricing ON {PREFIX}ProductsPricing.ProductId = {PREFIX}Products.ProductId AND {PREFIX}ProductsPricing.IsPrimary = 1 LEFT JOIN {PREFIX}ProductsDiscountItems ON {PREFIX}ProductsDiscountItems.ItemResourceId = {PREFIX}Products.ResourceId LEFT JOIN {PREFIX}ProductsDiscounts ON {PREFIX}ProductsDiscounts.DiscountId = {PREFIX}ProductsDiscountItems.DiscountId AND {PREFIX}ProductsDiscounts.Status = 1 AND {PREFIX}ProductsDiscountItems.ItemType = 1 AND ( {PREFIX}ProductsDiscounts.GroupId IN ({USER_GROUPS},NULL) AND ( ({PREFIX}ProductsDiscounts.Start IS NULL OR {PREFIX}ProductsDiscounts.Start < UNIX_TIMESTAMP()) AND ({PREFIX}ProductsDiscounts.Start IS NULL OR {PREFIX}ProductsDiscounts.End > UNIX_TIMESTAMP()) ) )', NULL, NULL, NULL, NULL, NULL);
INSERT INTO SearchConfig VALUES ('CustomField', 'Availability', 0, 0, 'la_Availability', 'la_Availability', 'In-Commerce', 'la_Text_CustomFields', 0, DEFAULT, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO ShippingQuoteEngines VALUES (1, 'Intershipper.com', 0, 0, 0, 'a:21:{s:12:"AccountLogin";N;s:15:"AccountPassword";s:0:"";s:10:"UPSEnabled";i:1;s:10:"UPSAccount";N;s:11:"UPSInvoiced";N;s:10:"FDXEnabled";i:1;s:10:"FDXAccount";N;s:10:"DHLEnabled";i:1;s:10:"DHLAccount";N;s:11:"DHLInvoiced";i:0;s:10:"USPEnabled";i:1;s:10:"USPAccount";N;s:11:"USPInvoiced";i:0;s:10:"ARBEnabled";i:1;s:10:"ARBAccount";N;s:11:"ARBInvoiced";N;s:10:"1DYEnabled";i:1;s:10:"2DYEnabled";i:1;s:10:"3DYEnabled";i:1;s:10:"GNDEnabled";i:1;s:10:"ShipMethod";s:3:"DRP";}', 'Intershipper');
INSERT INTO ShippingQuoteEngines VALUES ( DEFAULT, 'USPS.com', 0, 0, 0, 'a:21:{s:12:"AccountLogin";s:0:"";s:15:"AccountPassword";N;s:10:"UPSEnabled";N;s:10:"UPSAccount";s:0:"";s:11:"UPSInvoiced";N;s:10:"FDXEnabled";N;s:10:"FDXAccount";s:0:"";s:10:"DHLEnabled";N;s:10:"DHLAccount";s:0:"";s:11:"DHLInvoiced";N;s:10:"USPEnabled";N;s:10:"USPAccount";s:0:"";s:11:"USPInvoiced";N;s:10:"ARBEnabled";N;s:10:"ARBAccount";s:0:"";s:11:"ARBInvoiced";N;s:10:"1DYEnabled";N;s:10:"2DYEnabled";N;s:10:"3DYEnabled";N;s:10:"GNDEnabled";N;s:10:"ShipMethod";N;}', 'USPS' ) ;
INSERT INTO StylesheetSelectors VALUES (27, 1, 'Block Header', 'td.block-header', 'a:6:{s:5:"color";s:7:"#FFFFFF";s:9:"font-size";s:4:"14px";s:11:"font-weight";s:4:"bold";s:16:"background-color";s:7:"#80B0C7";s:6:"border";s:4:"none";s:7:"padding";s:3:"5px";}', 'Block Header', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (167, 1, 'Calendar''s selected days', '.calendar tbody .selected', 'a:0:{}', '', 1, 'font-weight: bold;\r\nbackground-color: #9ED7ED;\r\nborder: 1px solid #83B2C5;', 0);
INSERT INTO StylesheetSelectors VALUES (39, 1, 'Main Left Column', '.main-column-left', 'a:1:{s:11:"padding-top";s:4:"10px";}', 'Main Left Column', 1, 'width:200px;', 0);
INSERT INTO StylesheetSelectors VALUES (90, 1, 'Toolbar Bottom', 'td.toolbar-bottom', 'a:0:{}', 'Bottom toolbar ', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (166, 1, 'Calendar''s weekends', '.calendar .weekend', 'a:0:{}', '', 1, 'color: #990000;', 0);
INSERT INTO StylesheetSelectors VALUES (29, 1, 'Featured Item Block Header', '.featured-block-header', 'a:0:{}', 'Featured Item Block Header', 2, '', 27);
INSERT INTO StylesheetSelectors VALUES (36, 1, 'Actions Block header', '.actions-block-header', 'a:2:{s:5:"color";s:7:"#0200AF";s:16:"background-color";s:7:"#89E867";}', 'Actions block appears on the inner pages like product details', 2, '', 27);
INSERT INTO StylesheetSelectors VALUES (28, 1, 'Categories Block Header', '.categories-block-header', 'a:0:{}', 'Categories Block Header', 2, '', 27);
INSERT INTO StylesheetSelectors VALUES (150, 1, 'Editors Pick Block', '.pick-products-block', 'a:0:{}', 'Editor Picks Block', 2, '', 30);
INSERT INTO StylesheetSelectors VALUES (149, 1, 'New Products Block Header', '.new-products-block-header', 'a:2:{s:16:"background-color";s:7:"#23BC06";s:6:"border";s:14:"1px solid #aaa";}', 'New Products Block Header', 2, '', 27);
INSERT INTO StylesheetSelectors VALUES (152, 1, 'Toolbar Link', 'a.toolbar', 'a:2:{s:5:"color";s:7:"#003399";s:15:"text-decoration";s:9:"underline";}', 'Toolbar Link', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (168, 1, 'Calendar''s highlighted day', '.calendar tbody .hilite', 'a:0:{}', '', 1, 'background-color: #f6f6f6;\r\nborder: 1px solid #83B2C5 !important;', 0);
INSERT INTO StylesheetSelectors VALUES (162, 1, 'Calendar''s top and bottom titles', '.calendar .title', 'a:0:{}', '', 1, 'color: #00309C;\r\nbackground-color: #98CEE4;\r\nborder: 1px solid #83B2C5;\r\nborder-top: 0px;\r\npadding: 1px;', 0);
INSERT INTO StylesheetSelectors VALUES (163, 1, 'Calendar''s control buttons', '.calendar .calendar_button', 'a:0:{}', '', 1, 'color: black;\r\nfont-size: 12px;\r\nbackground-color: #eeeeee;', 0);
INSERT INTO StylesheetSelectors VALUES (30, 1, 'Block without a border', '.block-no-border', 'a:2:{s:6:"border";s:4:"none";s:13:"margin-bottom";s:4:"10px";}', 'Block without a border', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (164, 1, 'Calendar''s day names', '.calendar thead .name', 'a:0:{}', '', 1, 'background-color: #DEEEF6;\r\nborder-bottom: 1px solid #000000;', 0);
INSERT INTO StylesheetSelectors VALUES (165, 1, 'Calendar''s days', '.calendar tbody .day', 'a:0:{}', '', 1, 'text-align: right;\r\npadding: 2px 4px 2px 2px;\r\nwidth: 2em;\r\nborder: 1px solid #fefefe;', 0);
INSERT INTO StylesheetSelectors VALUES (154, 1, 'Category Link', 'a.subcat', 'a:3:{s:5:"color";s:7:"#003399";s:11:"font-weight";s:4:"bold";s:15:"text-decoration";s:9:"underline";}', 'Category Link', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (40, 1, 'Main Center Column', '.main-column-center', 'a:1:{s:11:"padding-top";s:4:"10px";}', 'Main Center Column', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (37, 1, 'Actions Block', '.actions-block', 'a:0:{}', '', 2, '', 34);
INSERT INTO StylesheetSelectors VALUES (151, 1, 'Editor Picks Block Header', '.pick-products-block-header', 'a:3:{s:5:"color";s:7:"#34871F";s:16:"background-color";s:7:"#89E867";s:6:"border";s:14:"1px solid #aaa";}', 'Editor Picks Block Header', 2, '', 27);
INSERT INTO StylesheetSelectors VALUES (38, 1, 'Categories Block', '.categories-block', 'a:0:{}', '', 2, '', 34);
INSERT INTO StylesheetSelectors VALUES (32, 1, 'Button', '.button', 'a:7:{s:4:"font";s:37:"Verdana, Arial, Helvetica, sans-serif";s:5:"color";s:7:"#003399";s:11:"font-weight";s:4:"bold";s:16:"background-color";s:7:"#99CCFF";s:6:"border";s:17:"1px solid #FFFFFF";s:7:"padding";s:15:"1px 4px 1px 4px";s:5:"width";s:4:"auto";}', 'Button class used in all templates', 1, 'border-bottom-color: #003399;\r\nborder-right-color: #003399;\r\noverflow: visible;', 0);
INSERT INTO StylesheetSelectors VALUES (34, 1, 'Block with border (side block)', '.block', 'a:3:{s:16:"background-color";s:7:"#FFFFFF";s:6:"border";s:17:"1px solid #999999";s:13:"margin-bottom";s:4:"10px";}', 'Block with border (side block)', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (153, 1, 'Toolbar Link Mouseover (hover)', 'a.toolbar:hover', 'a:1:{s:5:"color";s:7:"#FFFFFF";}', 'Toolbar Link Mouseover (hover)', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (41, 1, 'Main Right Column', '.main-column-right', 'a:1:{s:11:"padding-top";s:4:"10px";}', 'Main Right Column', 1, 'width:210px;', 0);
INSERT INTO StylesheetSelectors VALUES (156, 1, 'Category Link Mouseover (hover)', 'a.subcat:hover', 'a:1:{s:5:"color";s:7:"#2FEF0E";}', 'Category Link Mouseover (hover)', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (148, 1, 'New Products Block', '.new-products-block', 'a:0:{}', 'New Products Block', 2, '', 30);
INSERT INTO StylesheetSelectors VALUES (157, 1, 'Link', 'a', 'a:2:{s:5:"color";s:7:"#003399";s:15:"text-decoration";s:9:"underline";}', 'Link', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (33, 1, 'Page Body', 'body', 'a:3:{s:9:"font-size";s:5:"small";s:16:"background-color";s:7:"#FFFFFF";s:6:"margin";s:4:"15px";}', 'Page Body', 1, 'width: auto;', 0);
INSERT INTO StylesheetSelectors VALUES (158, 1, 'Link Mouseover (hover)', 'a:hover', 'a:1:{s:5:"color";s:7:"#2FEF0E";}', 'Link Mouseover (hover)', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (35, 1, 'Toolbar Top', 'td.toolbar', 'a:8:{s:5:"color";s:7:"#3C7D9B";s:9:"font-size";s:5:"small";s:10:"background";s:41:"url(incommerce/bg1.gif) repeat-x left top";s:16:"background-color";s:7:"#99CCFF";s:10:"margin-top";s:3:"7px";s:12:"margin-right";s:4:"20px";s:13:"margin-bottom";s:3:"7px";s:11:"margin-left";s:4:"20px";}', 'Top toolbar', 1, '', 0);
INSERT INTO StylesheetSelectors VALUES (31, 1, 'Featured Item Block', '.featured-block', 'a:0:{}', 'Featured Item Block', 2, '', 30);
INSERT INTO Stylesheets VALUES (1, 'OnlineStore', 'This is default stylesheet supplied with OnlineStore theme', '.my_selector {\r\n background-color: #000000;\r\n}', 1124387197, 1);
DELETE FROM Cache WHERE VarName = 'config_files';
INSERT INTO ImportScripts VALUES (DEFAULT, 'Products from CSV file [In-Commerce]', '', 'p', 'In-Commerce', '', 'CSV', '1');
INSERT INTO Modules VALUES ('In-Commerce', 'modules/in-commerce/', 'p', DEFAULT, 1, 4, 'in-commerce/', 2, NULL);

Event Timeline