Page MenuHomeIn-Portal Phabricator

in-commerce
No OneTemporary

File Metadata

Created
Wed, Feb 26, 2:07 PM

in-commerce

Index: branches/5.2.x/units/brackets/brackets_event_handler.php
===================================================================
--- branches/5.2.x/units/brackets/brackets_event_handler.php (revision 14871)
+++ branches/5.2.x/units/brackets/brackets_event_handler.php (revision 14872)
@@ -1,234 +1,228 @@
<?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 BracketsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
- $permissions = Array(
- 'OnMoreBrackets' => Array('subitem' => 'add|edit'),
- 'OnInfinity' => Array('subitem' => 'add|edit'),
- 'OnArrange' => Array('subitem' => 'add|edit'),
- );
+
+ $permissions = Array (
+ 'OnMoreBrackets' => Array ('subitem' => 'add|edit'),
+ 'OnInfinity' => Array ('subitem' => 'add|edit'),
+ 'OnArrange' => Array ('subitem' => 'add|edit'),
+ );
+
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Apply some special processing to object being
* recalled before using it in other events that
* call prepareObject
*
* @param kDBItem|kDBList $object
* @param kEvent $event
* @return void
* @access protected
*/
protected function prepareObject(&$object, &$event)
{
if ( $this->Application->GetVar('s_id') === false ) {
return;
}
$shipping_object =& $this->Application->recallObject('s');
/* @var $shipping_object kDBItem */
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
if ( $lang_object->GetDBField('UnitSystem') == 2 && $shipping_object->GetDBField('Type') == 1 ) {
$fields = Array ('Start', 'End');
$formatter =& $this->Application->recallObject('kUnitFormatter');
/* @var $formatter kUnitFormatter */
foreach ($fields as $field) {
$object->SetFieldOption($field, 'formatter', 'kUnitFormatter');
$options = $object->GetFieldOptions($field);
$formatter->prepareOptions($field, $options, $object);
}
}
}
function prepareBrackets(&$event)
{
$lang_object =& $this->Application->recallObject('lang.current');
+ /* @var $lang_object LanguagesItem */
+
$shipping_object =& $this->Application->recallObject('s');
- if($lang_object->GetDBField('UnitSystem') != 2 || $shipping_object->GetDBField('Type') != 1)
- {
+ /* @var $shipping_object kDBItem */
+
+ if ( $lang_object->GetDBField('UnitSystem') != 2 || $shipping_object->GetDBField('Type') != 1 ) {
return;
}
$item_info = $this->Application->GetVar( $event->getPrefixSpecial() );
- foreach($item_info as $id => $item_data)
- {
- if($item_info[$id]['Start_a'] === '' && $item_info[$id]['Start_b'] === '')
- {
+
+ foreach ($item_info as $id => $item_data) {
+ if ( $item_info[$id]['Start_a'] === '' && $item_info[$id]['Start_b'] === '' ) {
$item_info[$id]['Start'] = '';
}
- else
- {
+ else {
$item_info[$id]['Start'] = kUtil::Pounds2Kg($item_info[$id]['Start_a'], $item_info[$id]['Start_b']);
}
- if($item_info[$id]['End_a'] == '&#8734;' || $item_info[$id]['End_a'] == '&infin;')
- {
+ if ( $item_info[$id]['End_a'] == '&#8734;' || $item_info[$id]['End_a'] == '&infin;' ) {
$item_info[$id]['End'] = '&#8734;';
}
- elseif($item_info[$id]['End_a'] === '' && $item_info[$id]['End_b'] === '')
- {
+ elseif ( $item_info[$id]['End_a'] === '' && $item_info[$id]['End_b'] === '' ) {
$item_info[$id]['End'] = '';
}
- else
- {
+ else {
$item_info[$id]['End'] = kUtil::Pounds2Kg($item_info[$id]['End_a'], $item_info[$id]['End_b']);
}
}
- $this->Application->SetVar( $event->getPrefixSpecial(), $item_info );
+
+ $this->Application->SetVar($event->getPrefixSpecial(), $item_info);
}
/**
* Adds additional 5 empty brackets
*
* @param kEvent $event
*/
function OnMoreBrackets(&$event)
{
- $shipping_object =& $this->Application->recallObject('s');
- $default_start = ($shipping_object->GetDBField('Type') == 1) ? 0 : 1;
-
- $this->prepareBrackets($event);
+ $brackets_helper =& $this->getHelper($event);
- $event->redirect = false;
-
- $brackets_helper =& $this->Application->recallObject('BracketsHelper');
- $brackets_helper->InitHelper('Start', 'End', Array(), $default_start );
$brackets_helper->OnMoreBrackets($event);
}
/**
* Arrange brackets
*
* @param kEvent $event
*/
function OnArrange(&$event)
{
- $shipping_object =& $this->Application->recallObject('s');
- $default_start = ($shipping_object->GetDBField('Type') == 1) ? 0 : 1;
-
- $this->prepareBrackets($event);
-
- $event->redirect = false;
- $brackets_helper =& $this->Application->recallObject('BracketsHelper');
- /* @var $brackets_helper kBracketsHelper */
-
- $brackets_helper->InitHelper('Start', 'End', Array(), $default_start);
+ $brackets_helper =& $this->getHelper($event);
$brackets_helper->arrangeBrackets($event);
$event->CallSubEvent('OnPreSaveBrackets');
}
/**
* Arrange infinity brackets
*
* @param kEvent $event
*/
function OnInfinity(&$event)
{
- $shipping_object =& $this->Application->recallObject('s');
- $default_start = ($shipping_object->GetDBField('Type') == 1) ? 0 : 1;
+ $brackets_helper =& $this->getHelper($event);
- $this->prepareBrackets($event);
-
- $event->redirect = false;
- $brackets_helper =& $this->Application->recallObject('BracketsHelper');
- $brackets_helper->InitHelper('Start', 'End', Array(), $default_start );
$brackets_helper->arrangeBrackets($event);
-
$event->CallSubEvent('OnPreSaveBrackets');
$brackets_helper->OnInfinity($event);
-
$event->CallSubEvent('OnPreSaveBrackets');
}
/**
+ * Initializes kBracketsHelper class based on event
+ *
+ * @param kEvent $event
+ * @param bool $event_readonly
+ * @return kBracketsHelper
+ */
+ protected function &getHelper(&$event, $event_readonly = false)
+ {
+ $shipping_object =& $this->Application->recallObject('s');
+ /* @var $shipping_object kDBItem */
+
+ $default_start = $shipping_object->GetDBField('Type') == 1 ? 0 : 1;
+
+ if ( !$event_readonly ) {
+ $this->prepareBrackets($event);
+ $event->redirect = false;
+ }
+
+ $brackets_helper =& $this->Application->recallObject('BracketsHelper');
+ /* @var $brackets_helper kBracketsHelper */
+
+ $brackets_helper->InitHelper('Start', 'End', Array (), $default_start);
+
+ return $brackets_helper;
+ }
+
+ /**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
protected function OnBeforeItemUpdate(&$event)
{
parent::OnBeforeItemUpdate($event);
- $shipping_object =& $this->Application->recallObject('s');
- /* @var $shipping_object kDBItem */
-
- $default_start = ($shipping_object->GetDBField('Type') == 1) ? 0 : 1;
-
$object =& $event->getObject();
/* @var $object kDBItem */
$linked_info = $object->getLinkedInfo();
$object->SetDBField($linked_info['ParentTableKey'], $linked_info['ParentId']);
- $brackets_helper =& $this->Application->recallObject('BracketsHelper');
- /* @var $brackets_helper kBracketsHelper */
-
- $brackets_helper->InitHelper('Start', 'End', Array (), $default_start);
+ $brackets_helper =& $this->getHelper($event, true);
$brackets_helper->replaceInfinity($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveBrackets(&$event)
{
$lang_object =& $this->Application->recallObject('lang.current');
+ /* @var $lang_object LanguagesItem */
+
$shipping_object =& $this->Application->recallObject('s');
- if($lang_object->GetDBField('UnitSystem') == 2 && $shipping_object->GetDBField('Type') == 1)
- {
- $item_info = $this->Application->GetVar( $event->getPrefixSpecial() );
- if(is_array($item_info))
- {
- foreach($item_info as $id => $values)
- {
- if($values['End'] == -1)
- {
+ /* @var $shipping_object kDBItem */
+
+ if ( $lang_object->GetDBField('UnitSystem') == 2 && $shipping_object->GetDBField('Type') == 1 ) {
+ $item_info = $this->Application->GetVar($event->getPrefixSpecial());
+
+ if ( is_array($item_info) ) {
+ foreach ($item_info as $id => $values) {
+ if ( $values['End'] == -1 ) {
$item_info[$id]['End_a'] = -1 / kUtil::POUND_TO_KG;
$item_info[$id]['End_b'] = 0;
}
}
- $this->Application->SetVar( $event->getPrefixSpecial(), $item_info );
+ $this->Application->SetVar($event->getPrefixSpecial(), $item_info);
}
}
- $default_start = ($shipping_object->GetDBField('Type') == 1) ? 0 : 1;
-
- $brackets_helper =& $this->Application->recallObject('BracketsHelper');
- $brackets_helper->InitHelper('Start', 'End', Array(), $default_start );
+ $brackets_helper =& $this->getHelper($event, true);
$brackets_helper->OnPreSaveBrackets($event);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/destinations/dst_event_handler.php
===================================================================
--- branches/5.2.x/units/destinations/dst_event_handler.php (revision 14871)
+++ branches/5.2.x/units/destinations/dst_event_handler.php (revision 14872)
@@ -1,121 +1,124 @@
<?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 DstEventHandler extends kDBEventHandler {
/**
* Creates item from submit data
*
* @param kEvent $event
*/
function OnCreate(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
+ /* @var $object kDBItem */
- $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
- if($items_info)
- {
- foreach($items_info as $id => $field_values)
- {
- $object->SetFieldsFromHash($field_values);
- $this->customProcessing($event, 'before');
-
- if ( $object->Create() ) {
- $this->customProcessing($event, 'after');
- $event->status = kEvent::erSUCCESS;
- }
- else {
- $event->status = kEvent::erFAIL;
- $event->redirect = false;
- $this->Application->SetVar($event->getPrefixSpecial().'_SaveEvent','OnCreate');
- $object->setID(0);
- }
+ // creates multiple db records from single request (OnCreate event only creates 1 record)
+ $items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
+
+ if ( !$items_info ) {
+ return;
+ }
+
+ foreach ($items_info as $field_values) {
+ $object->SetFieldsFromHash($field_values);
+ $this->customProcessing($event, 'before');
+
+ if ( $object->Create() ) {
+ $this->customProcessing($event, 'after');
+ $event->status = kEvent::erSUCCESS;
+ }
+ else {
+ $event->status = kEvent::erFAIL;
+ $event->redirect = false;
+ $this->Application->SetVar($event->getPrefixSpecial() . '_SaveEvent', 'OnCreate');
+ $object->setID(0);
}
}
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
protected function customProcessing(&$event, $type)
{
if($type != 'before') return ;
$object =& $event->getObject();
$events = $this->Application->GetVar('events');
if($events['z'] == 'OnUpdate')
{
$object->SetDBField('ShippingZoneId', $this->Application->GetVar('z_id'));
}
$zone_object =& $this->Application->recallObject('z');
if($zone_object->GetDBField('Type') == 3)
{
$object->SetDBField('StdDestId', $this->Application->GetVar('ZIPCountry'));
}
}
/**
*
*
* @param kEvent $event
*/
function OnZoneUpdate(&$event) {
$object = &$event->getObject();
$zone_object = &$this->Application->recallObject('z');
$zone_id = (int)$zone_object->GetID();
$zone_type = $zone_object->GetDBField('Type');
$delete_zones_sql = 'DELETE FROM '.$object->TableName.' WHERE ShippingZoneId = '.$zone_id;
$this->Conn->Query($delete_zones_sql);
if ($zone_id != 0){
$delete_zones_sql = 'DELETE FROM '.$object->TableName.' WHERE ShippingZoneId = 0';
$this->Conn->Query($delete_zones_sql);
}
$selected_destinations = $this->Application->GetVar('selected_destinations');
$selected_destinations_array = explode(',', $selected_destinations);
$selected_destinations_array = array_unique($selected_destinations_array);
foreach ($selected_destinations_array as $key => $dest_id) {
if ($zone_object->GetDBField('Type') == 3){
list ($zone_dest_id, $dest_value) = explode('|', $dest_id);
$dest_id = $this->Application->GetVar('CountrySelector');
}
else {
$dest_value = '';
}
if ($dest_id > 0){
$object->SetDBField('ShippingZoneId', $zone_id);
$object->SetDBField('StdDestId', $dest_id);
$object->SetDBField('DestValue', $dest_value);
$object->Create();
}
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/shipping_costs/shipping_costs_event_handler.php
===================================================================
--- branches/5.2.x/units/shipping_costs/shipping_costs_event_handler.php (revision 14871)
+++ branches/5.2.x/units/shipping_costs/shipping_costs_event_handler.php (revision 14872)
@@ -1,243 +1,252 @@
<?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 ShippingCostsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnPropagate' => Array('subitem' => 'add|edit'),
'OnClearAll' => Array('subitem' => 'add|edit'),
'OnSaveCreated' => Array('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCreate(&$event)
{
- $object =& $event->getObject( Array('skip_autoload' => true) );
+ $object =& $event->getObject(Array ('skip_autoload' => true));
+ /* @var $object kDBItem */
+
$zones_object =& $this->Application->recallObject('z');
- $sql = 'SELECT ZoneID FROM '.$zones_object->TableName.' WHERE ShippingTypeID='.$this->Application->GetVar('s_id');
+ $sql = 'SELECT ZoneID
+ FROM ' . $zones_object->TableName . '
+ WHERE ShippingTypeID = ' . $this->Application->GetVar('s_id');
$res = $this->Conn->GetCol($sql);
- $sql = 'DELETE FROM '.$object->TableName.' WHERE ZoneID IN ('.implode(',', $res).')';
+
+ $sql = 'DELETE FROM ' . $object->TableName . '
+ WHERE ZoneID IN (' . implode(',', $res) . ')';
$this->Conn->Query($sql);
- $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
- if($items_info)
- {
- foreach($items_info as $id => $field_values)
- {
- $object->SetFieldsFromHash($field_values);
- $this->customProcessing($event,'before');
+ // creates multiple db records from single request (OnCreate event only creates 1 record)
+ $items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
- if( $object->Create() ) {
- $this->customProcessing($event,'after');
- $event->status = kEvent::erSUCCESS;
- }
- else {
- $event->status = kEvent::erFAIL;
- $event->redirect = false;
- $this->Application->SetVar($event->getPrefixSpecial().'_SaveEvent','OnCreate');
- $object->setID(0);
- }
+ if ( !$items_info ) {
+ return;
+ }
+
+ foreach ($items_info as $field_values) {
+ $object->SetFieldsFromHash($field_values);
+ $this->customProcessing($event, 'before');
+
+ if ( $object->Create() ) {
+ $this->customProcessing($event, 'after');
+ $event->status = kEvent::erSUCCESS;
+ }
+ else {
+ $event->status = kEvent::erFAIL;
+ $event->redirect = false;
+ $this->Application->SetVar($event->getPrefixSpecial() . '_SaveEvent', 'OnCreate');
+ $object->setID(0);
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPropagate(&$event)
{
// $this->OnCreate(&$event);
$object =& $event->getObject();
$shipping_object =& $this->Application->recallObject('s');
if( $this->Application->GetVar('br_propagate_id') )
{
$propagate_id = $this->Application->GetVar('br_propagate_id');
$idfield = 'BracketId';
}
else
{
$propagate_id = $this->Application->GetVar('z_propagate_id');
$idfield = 'ZoneID';
}
$cost_type = $shipping_object->GetDBField('CostType');
switch($cost_type)
{
case 1:
$affected_fields = Array(0 => 'Flat');
break;
case 2:
$affected_fields = Array(0 => 'PerUnit');
break;
default:
$affected_fields = Array(0 => 'PerUnit', 1 => 'Flat');
break;
}
$sql = 'SELECT ShippingCostId,'.implode(',', $affected_fields).'
FROM '.$object->TableName.'
WHERE '.$idfield.'='.$propagate_id;
$res = $this->Conn->Query($sql);
if(is_array($res))
{
$res = array_reverse($res);
foreach($affected_fields as $field)
{
$first_elem = getArrayValue($res, 0);
if( (double)$first_elem[$field] )
{
$iterating_value = $first_elem[$field];
$second_elem = getArrayValue($res, 1);
if( is_array($second_elem) && (double)$second_elem[$field] )
{
$increment = $second_elem[$field] - $first_elem[$field];
}
else
{
$increment = 0;
}
foreach($res as $record)
{
$object->Load($record['ShippingCostId']);
$new_value = ($iterating_value >= 0) ? $iterating_value : null;
$object->SetDBField($field, $new_value);
$object->Update();
$iterating_value += $increment;
}
}
}
}
/* $shipping_event = new kEvent();
$shipping_event->Init('s');
$shipping_event->Name = 'OnPreSave';
$shipping_event->status = kEvent::erFATAL;
$this->Application->HandleEvent(&$shipping_event);*/
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnClearAll(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$zones_object =& $this->Application->recallObject('z');
$sql = 'SELECT ZoneID FROM '.$zones_object->TableName.' WHERE ShippingTypeID='.$this->Application->GetVar('s_id');
$res = $this->Conn->GetCol($sql);
$sql = 'DELETE FROM '.$object->TableName.' WHERE ZoneID IN ('.implode(',', $res).')';
$this->Conn->Query($sql);
$event->setRedirectParams(Array('opener' => 's', 'pass_events' => false), true);
$event->status = kEvent::erSUCCESS;
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
protected function customProcessing(&$event, $type)
{
- if( $type == 'before' && $this->Application->GetVar('sc') )
- {
+ if ( $type == 'before' && $this->Application->GetVar('sc') ) {
$shipping_obj =& $this->Application->recallObject('s');
- $cost =& $event->getObject();
+ /* @var $shipping_obj kDBItem */
+
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
+
$zero_if_empty = $shipping_obj->GetDBField('ZeroIfEmpty');
- if($cost->GetDBField('Flat') == '')
- {
+ if ( $object->GetDBField('Flat') == '' ) {
$flat = $zero_if_empty ? 0 : null;
- $cost->SetDBField('Flat', $flat);
+ $object->SetDBField('Flat', $flat);
}
- if($cost->GetDBField('PerUnit') == '')
- {
+ if ( $object->GetDBField('PerUnit') == '' ) {
$per_unit = $zero_if_empty ? 0 : null;
- $cost->SetDBField('PerUnit', $per_unit);
+ $object->SetDBField('PerUnit', $per_unit);
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSaveCreated(&$event)
{
$event->CallSubEvent('OnCreate');
$event->redirect = false;
$event->setRedirectParams(Array('opener'=>'s','pass'=>'all'), true);
}
function OnAfterCopyToTemp(&$event)
{
$id = $event->getEventParam('id');
$object =& $this->Application->recallObject($event->Prefix.'.-item', $event->Prefix);
$object->SwitchToTemp();
$object->Load($id);
$shipping_obj =& $this->Application->recallObject('s');
$lang_object =& $this->Application->recallObject('lang.current');
// by weight and US/UK system - we need to store recalculated price per Kg cause shipping calculation is done per Kg!
if ($shipping_obj->GetDBField('Type') == 1 && $lang_object->GetDBField('UnitSystem') == 2) {
$object->SetDBField('PerUnit', $object->GetDBField('PerUnit') * kUtil::POUND_TO_KG);
$object->Update(null, true);
}
}
function OnBeforeCopyToLive(&$event)
{
$id = $event->getEventParam('id');
$object =& $this->Application->recallObject($event->Prefix.'.-item', $event->Prefix);
$object->SwitchToTemp();
$object->Load($id);
$shipping_obj =& $this->Application->recallObject('s');
$lang_object =& $this->Application->recallObject('lang.current');
// by weight and US/UK system - we need to store recalculated price per Kg cause shipping calculation is done per Kg!
if ($shipping_obj->GetDBField('Type') == 1 && $lang_object->GetDBField('UnitSystem') == 2) {
$object->SetDBField('PerUnit', $object->GetDBField('PerUnit') / kUtil::POUND_TO_KG);
$object->Update(null, true);
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/orders/order_calculator.php
===================================================================
--- branches/5.2.x/units/orders/order_calculator.php (revision 14871)
+++ branches/5.2.x/units/orders/order_calculator.php (revision 14872)
@@ -1,860 +1,859 @@
<?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!');
/**
* Performs order price calculations
*
*/
class OrderCalculator extends kBase {
/**
* Order manager instance
*
* @var OrderManager
*/
protected $manager = null;
/**
* Items, associated with current order
*
* @var Array
*/
protected $items = Array ();
/**
* Creates new clean instance of calculator
*
*/
public function __construct()
{
parent::__construct();
$this->reset();
}
/**
* Sets order manager instance to calculator
*
* @param OrderManager $manager
*/
public function setManager(&$manager)
{
$this->manager =& $manager;
}
public function reset()
{
$this->items = Array ();
}
/**
* Returns order object used in order manager
*
* @return OrdersItem
*/
protected function &getOrder()
{
$order =& $this->manager->getOrder();
return $order;
}
/**
* Sets checkout error
*
* @param int $error_type = {product,coupon,gc}
* @param int $error_code
* @param int $product_id - {ProductId}:{OptionsSalt}:{BackOrderFlag}:{FieldName}
* @return void
* @access protected
*/
protected function setError($error_type, $error_code, $product_id = null)
{
$this->manager->setError($error_type, $error_code, $product_id);
}
/**
* Perform order calculations and prepares operations for order manager
*
*/
public function calculate()
{
$this->queryItems();
$this->groupItems();
$this->generateOperations();
$this->applyWholeOrderFlatDiscount();
}
/**
* Groups order items, when requested
*
* @return Array
*/
protected function groupItems()
{
$skipped_items = Array ();
foreach ($this->items as $item_id => $item_data) {
if ( in_array($item_id, $skipped_items) ) {
continue;
}
$group_items = $this->getItemsToGroupWith($item_id);
if (!$group_items) {
continue;
}
foreach ($group_items as $group_item_id) {
$this->items[$item_id]['Quantity'] += $this->items[$group_item_id]['Quantity'];
$this->items[$group_item_id]['Quantity'] = 0;
}
$skipped_items = array_merge($skipped_items, $group_items);
}
}
/**
* Returns order item ids, that can be grouped with given order item id
*
* @param int $target_item_id
* @return Array
* @see OrderCalculator::canBeGrouped
*/
protected function getItemsToGroupWith($target_item_id)
{
$ret = Array ();
foreach ($this->items as $item_id => $item_data) {
if ( $this->canBeGrouped($this->items[$item_id], $this->items[$target_item_id]) ) {
$ret[] = $item_id;
}
}
return array_diff($ret, Array ($target_item_id));
}
/**
* Checks if 2 given order items can be grouped together
*
* @param Array $src_item
* @param Array $dst_item
* @return bool
*/
public function canBeGrouped($src_item, $dst_item)
{
if ($dst_item['Type'] != PRODUCT_TYPE_TANGIBLE) {
return false;
}
return ($src_item['ProductId'] == $dst_item['ProductId']) && ($src_item['OptionsSalt'] == $dst_item['OptionsSalt']);
}
/**
* Retrieves order contents from database
*
*/
protected function queryItems()
{
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' SELECT oi.ProductId, oi.OptionsSalt, oi.ItemData, oi.Quantity,
IF(p.InventoryStatus = ' . ProductInventory::BY_OPTIONS . ', poc.QtyInStock, p.QtyInStock) AS QtyInStock,
p.QtyInStockMin, p.BackOrder, p.InventoryStatus,
p.Type, oi.OrderItemId
FROM ' . $this->getTable('orditems') . ' 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 = ' . $this->getOrder()->GetID();
$this->items = $this->Conn->Query($query, 'OrderItemId');
}
/**
* Generates operations and returns true, when something was changed
*
* @return bool
*/
protected function generateOperations()
{
$this->manager->resetOperationTotals();
foreach ($this->items as $item) {
$this->ensureMinQty($item);
$to_order = $back_order = 0;
$available = $this->getAvailableQty($item);
if ( $this->allowBackordering($item) ) {
// split order into order & backorder
if ($item['BackOrder'] == ProductBackorder::ALWAYS) {
$to_order = $available = 0;
$back_order = $item['Quantity'];
}
elseif ($item['BackOrder'] == ProductBackorder::AUTO) {
$to_order = $available;
$back_order = $item['Quantity'] - $available;
}
$qty = $to_order + $back_order;
$price = $this->getPlainProductPrice($item, $qty);
$cost = $this->getProductCost($item, $qty);
$discount_info = $this->getDiscountInfo( $item['ProductId'], $price, $qty );
$this->manager->addOperation($item, 0, $to_order, $price, $cost, $discount_info);
$this->manager->addOperation($item, 1, $back_order, $price, $cost, $discount_info);
}
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($item['Quantity'], $available);
$price = $this->getPlainProductPrice($item, $to_order);
$cost = $this->getProductCost($item, $to_order);
$discount_info = $this->getDiscountInfo( $item['ProductId'], $price, $to_order );
$this->manager->addOperation($item, 0, $to_order, $price, $cost, $discount_info, $item['OrderItemId']);
$this->manager->addOperation($item, 1, 0, $price, $cost, $discount_info); // remove backorder record
if ($to_order < $item['Quantity']) {
// ordered less, then requested -> inform user
if ( $to_order > 0 ) {
$this->setError(OrderCheckoutErrorType::PRODUCT, OrderCheckoutError::QTY_UNAVAILABLE, $item['ProductId'] . ':' . $item['OptionsSalt'] . ':0:Quantity');
}
else {
$this->setError(OrderCheckoutErrorType::PRODUCT, OrderCheckoutError::QTY_OUT_OF_STOCK, $item['ProductId'] . ':' . $item['OptionsSalt'] . ':0:Quantity');
}
}
}
}
}
/**
* Adds product to order (not to db)
*
* @param Array $item
* @param kCatDBItem $product
* @param int $qty
*/
public function addProduct($item, &$product, $qty)
{
$this->updateItemDataFromProduct($item, $product);
$price = $this->getPlainProductPrice($item, $qty);
$cost = $this->getProductCost($item, $qty);
$discount_info = $this->getDiscountInfo( $item['ProductId'], $price, $qty );
$this->manager->addOperation( $item, 0, $qty, $price, $cost, $discount_info, $item['OrderItemId'] );
}
/**
* Apply whole order flat discount after sub-total been calculated
*
*/
protected function applyWholeOrderFlatDiscount()
{
$sub_total_flat = $this->manager->getOperationTotal('SubTotalFlat');
$flat_discount = min( $sub_total_flat, $this->getWholeOrderPlainDiscount($global_discount_id) );
$coupon_flat_discount = min( $sub_total_flat, $this->getWholeOrderCouponDiscount() );
if ($coupon_flat_discount && $coupon_flat_discount > $flat_discount) {
$global_discount_type = 'coupon';
$flat_discount = $coupon_flat_discount;
$global_discount_id = $coupon_id;
}
else {
$global_discount_type = 'discount';
}
$sub_total = $this->manager->getOperationTotal('SubTotal');
if ($sub_total_flat - $sub_total < $flat_discount) {
// individual item discounts together are smaller when order flat discount
$this->manager->setOperationTotal('CouponDiscount', $flat_discount == $coupon_flat_discount ? $flat_discount : 0);
$this->manager->setOperationTotal('SubTotal', $sub_total_flat - $flat_discount);
// replace discount for each operation
foreach ($this->operations as $index => $operation) {
$discounted_price = ($operation['Price'] / $sub_total_flat) * $sub_total;
$this->operations[$index]['DiscountInfo'] = Array ($global_discount_id, $global_discount_type, $discounted_price, 0);
}
}
}
/**
* Returns discount information for given product price and qty
*
* @param int $product_id
* @param float $price
* @param int $qty
* @return Array
*/
protected function getDiscountInfo($product_id, $price, $qty)
{
$discounted_price = $this->getDiscountedProductPrice($product_id, $price, $discount_id);
$couponed_price = $this->getCouponDiscountedPrice($product_id, $price);
if ($couponed_price < $discounted_price) {
$discount_type = 'coupon';
$discount_id = $coupon_id;
$discounted_price = $couponed_price;
$coupon_discount = ($price - $couponed_price) * $qty;
}
else {
$coupon_discount = 0;
$discount_type = 'discount';
}
return Array ($discount_id, $discount_type, $discounted_price, $coupon_discount);
}
/**
* Returns product qty, available for ordering
*
* @param Array $item
* @return int
*/
protected function getAvailableQty($item)
{
if ( $item['InventoryStatus'] == ProductInventory::DISABLED ) {
// always available
return $item['Quantity'] * 2;
}
return max(0, $item['QtyInStock'] - $item['QtyInStockMin']);
}
/**
* Checks, that product in given order item can be backordered
*
* @param Array $item
* @return bool
*/
protected function allowBackordering($item)
{
if ($item['BackOrder'] == ProductBackorder::ALWAYS) {
return true;
}
$available = $this->getAvailableQty($item);
$backordering = $this->Application->ConfigValue('Comm_Enable_Backordering');
return $backordering && ($item['Quantity'] > $available) && ($item['BackOrder'] == ProductBackorder::AUTO);
}
/**
* Make sure, that user can't order less, then minimal required qty of product
*
* @param Array $item
*/
protected function ensureMinQty(&$item)
{
$sql = 'SELECT MIN(MinQty)
FROM ' . TABLE_PREFIX . 'ProductsPricing
WHERE ProductId = ' . $item['ProductId'];
$min_qty = max(1, $this->Conn->GetOne($sql));
$qty = $item['Quantity'];
if ($qty > 0 && $qty < $min_qty) {
// qty in cart increased to meat minimal qry requirements of given product
$this->setError(OrderCheckoutErrorType::PRODUCT, OrderCheckoutError::QTY_CHANGED_TO_MINIMAL, $item['ProductId'] . ':' . $item['OptionsSalt'] . ':0:Quantity');
$item['Quantity'] = $min_qty;
}
}
/**
* Return product price for given qty, taking no discounts into account
*
* @param Array $item
* @param int $qty
* @return float
*/
public function getPlainProductPrice($item, $qty)
{
$item_data = $this->getItemData($item);
if ( isset($item_data['ForcePrice']) ) {
return $item_data['ForcePrice'];
}
$pricing_id = $this->getPriceBracketByQty($item, $qty);
$sql = 'SELECT Price
FROM ' . TABLE_PREFIX . 'ProductsPricing
WHERE PriceId = ' . $pricing_id;
$price = (float)$this->Conn->GetOne($sql);
if ( isset($item_data['Options']) ) {
$price += $this->getOptionPriceAddition($price, $item_data);
$price = $this->getCombinationPriceOverride($price, $item_data);
}
return max($price, 0);
}
/**
* Return product cost for given qty, taking no discounts into account
*
* @param Array $item
* @param int $qty
* @return float
*/
public function getProductCost($item, $qty)
{
$pricing_id = $this->getPriceBracketByQty($item, $qty);
$sql = 'SELECT Cost
FROM ' . TABLE_PREFIX . 'ProductsPricing
WHERE PriceId = ' . $pricing_id;
return (float)$this->Conn->GetOne($sql);
}
/**
* Return product price for given qty, taking no discounts into account
*
* @param Array $item
* @param int $qty
* @return float
*/
protected function getPriceBracketByQty($item, $qty)
{
$orderby_clause = '';
$where_clause = Array ();
$product_id = $item['ProductId'];
if ( $this->usePriceBrackets($item) ) {
$user_id = $this->getOrder()->GetDBField('PortalUserId');
$where_clause = Array (
'GroupId IN (' . $this->Application->getUserGroups($user_id) . ')',
'pp.ProductId = ' . $product_id,
'pp.MinQty <= ' . $qty,
$qty . ' < pp.MaxQty OR pp.MaxQty = -1',
);
$orderby_clause = $this->getPriceBracketOrderClause($user_id);
}
else {
$item_data = $this->getItemData($item);
$where_clause = Array(
'pp.ProductId = ' . $product_id,
'pp.PriceId = ' . $this->getPriceBracketFromRequest($product_id, $item_data),
);
}
$sql = 'SELECT pp.PriceId
FROM ' . TABLE_PREFIX . 'ProductsPricing AS pp
LEFT JOIN ' . TABLE_PREFIX . 'Products AS p ON p.ProductId = pp.ProductId
WHERE (' . implode(') AND (', $where_clause) . ')';
if ($orderby_clause) {
$sql .= ' ORDER BY ' . $orderby_clause;
}
return (float)$this->Conn->GetOne($sql);
}
/**
* Checks if price brackets should be used in price calculations
*
* @param Array $item
* @return bool
*/
protected function usePriceBrackets($item)
{
return $item['Type'] == PRODUCT_TYPE_TANGIBLE;
}
/**
* Return product pricing id for given product.
* If not passed - return primary pricing ID
*
* @param int $product_id
* @return int
*/
public function getPriceBracketFromRequest($product_id, $item_data)
{
if ( !is_array($item_data) ) {
$item_data = unserialize($item_data);
}
// remembered pricing during checkout
if ( isset($item_data['PricingId']) && $item_data['PricingId'] ) {
return $item_data['PricingId'];
}
// selected pricing from product detail page
$price_id = $this->Application->GetVar('pr_id');
if ($price_id) {
return $price_id;
}
$sql = 'SELECT PriceId
FROM ' . TABLE_PREFIX . 'ProductsPricing
WHERE ProductId = ' . $product_id . ' AND IsPrimary = 1';
return $this->Conn->GetOne($sql);
}
/**
* Returns order clause for price bracket selection based on configration
*
* @param int $user_id
* @return string
*/
protected function getPriceBracketOrderClause($user_id)
{
if ($this->Application->ConfigValue('Comm_PriceBracketCalculation') == 1) {
// if we have to stick to primary group, then its pricing will go first,
// but if there is no pricing for primary group, then next optimal will be taken
$primary_group = $this->getUserPrimaryGroup($user_id);
return '( IF(GroupId = ' . $primary_group . ', 1, 2) ) ASC, pp.Price ASC';
}
return 'pp.Price ASC';
}
/**
* Returns addition to product price based on used product option
*
* @param float $price
* @param Array $item_data
* @return float
*/
protected function getOptionPriceAddition($price, $item_data)
{
- $addtion = 0;
+ $addition = 0;
$opt_helper =& $this->Application->recallObject('kProductOptionsHelper');
/* @var $opt_helper kProductOptionsHelper */
foreach ($item_data['Options'] as $opt => $val) {
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'ProductOptions
WHERE ProductOptionId = ' . $opt;
$data = $this->Conn->GetRow($sql);
$parsed = $opt_helper->ExplodeOptionValues($data);
- if (!$parsed) {
+ if ( !$parsed ) {
continue;
}
- $conv_prices = $parsed['Prices'];
- $conv_price_types = $parsed['PriceTypes'];
-
if ( is_array($val) ) {
foreach ($val as $a_val) {
- $a_val = kUtil::unhtmlentities($a_val);
-
- if ( isset($conv_prices[$a_val]) && $conv_prices[$a_val] ) {
- if ( $conv_price_types[$a_val] == '$' ) {
- $addtion += $conv_prices[$a_val];
- }
- elseif ($conv_price_types[$a_val] == '%') {
- $addtion += $price * $conv_prices[$a_val] / 100;
- }
- }
+ $addition += $this->formatPrice($a_val, $price, $parsed);
}
}
else {
- $a_val = kUtil::unhtmlentities($val);
+ $addition += $this->formatPrice($val, $price, $parsed);
+ }
+ }
- if ( isset($conv_prices[$a_val]) && $conv_prices[$a_val] ) {
- if ($conv_price_types[$a_val] == '$') {
- $addtion += $conv_prices[$a_val];
- }
- elseif ($conv_price_types[$a_val] == '%') {
- $addtion += $price * $conv_prices[$a_val] / 100;
- }
- }
+ return $addition;
+ }
+
+ protected function formatPrice($a_val, $price, $parsed)
+ {
+ $a_val = kUtil::unhtmlentities($a_val);
+
+ $addition = 0;
+ $conv_prices = $parsed['Prices'];
+ $conv_price_types = $parsed['PriceTypes'];
+
+ if ( isset($conv_prices[$a_val]) && $conv_prices[$a_val] ) {
+ if ($conv_price_types[$a_val] == '$') {
+ $addition += $conv_prices[$a_val];
+ }
+ elseif ($conv_price_types[$a_val] == '%') {
+ $addition += $price * $conv_prices[$a_val] / 100;
}
}
- return $addtion;
+ return $addition;
}
/**
* Returns product price after applying combination price override
*
* @param float $price
* @param Array $item_data
* @return float
*/
protected function getCombinationPriceOverride($price, $item_data)
{
$combination_salt = $this->generateOptionsSalt( $item_data['Options'] );
if (!$combination_salt) {
return $price;
}
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'ProductOptionCombinations
WHERE CombinationCRC = ' . $combination_salt;
$combination = $this->Conn->GetRow($sql);
if (!$combination) {
return $price;
}
switch ( $combination['PriceType'] ) {
case OptionCombinationPriceType::EQUALS:
return $combination['Price'];
break;
case OptionCombinationPriceType::FLAT:
return $price + $combination['Price'];
break;
case OptionCombinationPriceType::PECENT:
return $price * (1 + $combination['Price'] / 100);
break;
}
return $price;
}
/**
* Generates salt for given option set
*
* @param Array $options
* @return int
*/
public function generateOptionsSalt($options)
{
$opt_helper =& $this->Application->recallObject('kProductOptionsHelper');
/* @var $opt_helper kProductOptionsHelper */
return $opt_helper->OptionsSalt($options, true);
}
/**
* Return product price for given qty, taking possible discounts into account
*
* @param int $product_id
* @param int $price
* @param int $discount_id
* @return float
*/
public function getDiscountedProductPrice($product_id, $price, &$discount_id)
{
$discount_id = 0;
$user_id = $this->getOrder()->GetDBField('PortalUserId');
$join_clause = Array (
'd.DiscountId = di.DiscountId',
'di.ItemType = ' . DiscountItemType::PRODUCT . ' OR (di.ItemType = ' . DiscountItemType::WHOLE_ORDER . ' AND d.Type = ' . DiscountType::PERCENT . ')',
'd.Status = ' . STATUS_ACTIVE,
'd.GroupId IN (' . $this->Application->getUserGroups($user_id) . ')',
'd.Start IS NULL OR d.Start < ' . $this->getOrder()->GetDBField('OrderDate'),
'd.End IS NULL OR d.End > ' . $this->getOrder()->GetDBField('OrderDate'),
);
$sql = 'SELECT
CASE d.Type
WHEN ' . DiscountType::FLAT . ' THEN ' . $price . ' - d.Amount
WHEN ' . DiscountType::PERCENT . ' THEN ' . $price . ' * (1 - d.Amount / 100)
ELSE ' . $price . '
END, d.DiscountId
FROM ' . TABLE_PREFIX . 'Products AS p
LEFT JOIN ' . TABLE_PREFIX . 'ProductsDiscountItems AS di ON (di.ItemResourceId = p.ResourceId) OR (di.ItemType = ' . DiscountItemType::WHOLE_ORDER . ')
LEFT JOIN ' . TABLE_PREFIX . 'ProductsDiscounts AS d ON (' . implode(') AND (', $join_clause) . ')
WHERE (p.ProductId = ' . $product_id . ') AND (d.DiscountId IS NOT NULL)';
$pricing = $this->Conn->GetCol($sql, 'DiscountId');
if (!$pricing) {
return $price;
}
// get minimal price + discount
$discounted_price = min($pricing);
$pricing = array_flip($pricing);
$discount_id = $pricing[$discounted_price];
// optimal discount, but prevent negative price
return max( min($discounted_price, $price), 0 );
}
public function getWholeOrderPlainDiscount(&$discount_id)
{
$discount_id = 0;
$user_id = $this->getOrder()->GetDBField('PortalUserId');
$join_clause = Array (
'd.DiscountId = di.DiscountId',
'di.ItemType = ' . DiscountItemType::WHOLE_ORDER . ' AND d.Type = ' . DiscountType::FLAT,
'd.Status = ' . STATUS_ACTIVE,
'd.GroupId IN (' . $this->Application->getUserGroups($user_id) . ')',
'd.Start IS NULL OR d.Start < ' . $this->getOrder()->GetDBField('OrderDate'),
'd.End IS NULL OR d.End > ' . $this->getOrder()->GetDBField('OrderDate'),
);
$sql = 'SELECT d.Amount AS Discount, d.DiscountId
FROM ' . TABLE_PREFIX . 'ProductsDiscountItems AS di
LEFT JOIN ' . TABLE_PREFIX . 'ProductsDiscounts AS d ON (' . implode(') AND (', $join_clause) . ')
WHERE d.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);
}
public function getCouponDiscountedPrice($product_id, $price)
{
if ( !$this->getCoupon() ) {
return $price;
}
$join_clause = Array (
'c.CouponId = ci.CouponId',
'ci.ItemType = ' . CouponItemType::PRODUCT . ' OR (ci.ItemType = ' . CouponItemType::WHOLE_ORDER . ' AND c.Type = ' . CouponType::PERCENT . ')',
);
$sql = 'SELECT
MIN(
CASE c.Type
WHEN ' . CouponType::FLAT . ' THEN ' . $price . ' - c.Amount
WHEN ' . CouponType::PERCENT . ' THEN ' . $price . ' * (1 - c.Amount / 100)
ELSE ' . $price . '
END
)
FROM ' . TABLE_PREFIX . 'Products AS p
LEFT JOIN ' . TABLE_PREFIX . 'ProductsCouponItems AS ci ON (ci.ItemResourceId = p.ResourceId) OR (ci.ItemType = ' . CouponItemType::WHOLE_ORDER . ')
LEFT JOIN ' . TABLE_PREFIX . 'ProductsCoupons AS c ON (' . implode(') AND (', $join_clause) . ')
WHERE p.ProductId = ' . $product_id . ' AND ci.CouponId = ' . $this->getCoupon() . '
GROUP BY p.ProductId';
$coupon_price = $this->Conn->GetOne($sql);
if ($coupon_price === false) {
return $price;
}
return max( min($price, $coupon_price), 0 );
}
public function getWholeOrderCouponDiscount()
{
if ( !$this->getCoupon() ) {
return 0;
}
$where_clause = Array (
'ci.CouponId = ' . $this->getCoupon(),
'ci.ItemType = ' . CouponItemType::WHOLE_ORDER,
'c.Type = ' . CouponType::FLAT,
);
$sql = 'SELECT Amount
FROM ' . TABLE_PREFIX . 'ProductsCouponItems AS ci
LEFT JOIN ' . TABLE_PREFIX . 'ProductsCoupons AS c ON c.CouponId = ci.CouponId
WHERE (' . implode(') AND (', $where_clause) . ')';
return $this->Conn->GetOne($sql);
}
protected function getCoupon()
{
return $this->getOrder()->GetDBField('CouponId');
}
/**
* Returns primary group of given user
*
* @param int $user_id
* @return int
*/
protected function getUserPrimaryGroup($user_id)
{
if ($user_id > 0) {
$sql = 'SELECT PrimaryGroupId
FROM ' . TABLE_PREFIX . 'PortalUser
WHERE PortalUserId = ' . $user_id;
return $this->Conn->GetOne($sql);
}
return $this->Application->ConfigValue('User_LoggedInGroup');
}
/**
* Returns ItemData associated with given order item
*
* @param Array $item
* @return Array
*/
protected function getItemData($item)
{
$item_data = $item['ItemData'];
if ( is_array($item_data) ) {
return $item_data;
}
return $item_data ? unserialize($item_data) : Array ();
}
/**
* Sets ItemData according to product
*
* @param Array $item
* @param kCatDBItem $product
*/
protected function updateItemDataFromProduct(&$item, &$product)
{
$item_data = $this->getItemData($item);
$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 ( isset($processing_data['HasNewProcessing']) ) {
$item_data['HasNewProcessing'] = 1;
}
}
$item['ItemData'] = serialize($item_data);
}
/**
* Returns table name according to order temp mode
*
* @param string $prefix
* @return string
*/
protected function getTable($prefix)
{
return $this->manager->getTable($prefix);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/products/products_tag_processor.php
===================================================================
--- branches/5.2.x/units/products/products_tag_processor.php (revision 14871)
+++ branches/5.2.x/units/products/products_tag_processor.php (revision 14872)
@@ -1,764 +1,757 @@
<?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 ProductsTagProcessor extends kCatDBTagProcessor {
function Rating($params)
{
$object =& $this->getObject($params);
$rating = round($object->GetDBField('CachedRating') );
$o = '';
for ($i = 0; $i < $rating; $i++) {
$o .= $this->Application->ParseBlock( Array('name' => $this->SelectParam($params, 'star_on_render_as,block_star_on')) );
}
for ($i = 0; $i < 5 - $rating; $i++) {
$o .= $this->Application->ParseBlock( Array('name' => $this->SelectParam($params, 'star_off_render_as,block_star_off')) );
}
return $o;
}
function NewMark($params)
{
$object =& $this->getObject($params);
$o = '';
if($object->GetDBField('IsNew'))
{
$o .= $this->Application->ParseBlock( Array('name' => $this->SelectParam($params, 'render_as,block')) );
}
return $o;
}
function HotMark($params)
{
$object =& $this->getObject($params);
$o = '';
if($object->GetDBField('IsHot'))
{
$o .= $this->Application->ParseBlock( Array('name' => $this->SelectParam($params, 'render_as,block')) );
}
return $o;
}
function TopSellerMark($params)
{
return $this->HotMark($params);
}
function PopMark($params)
{
$object =& $this->getObject($params);
$o = '';
if($object->GetDBField('IsPop'))
{
$o .= $this->Application->ParseBlock( Array('name' => $this->SelectParam($params, 'render_as,block')) );
}
return $o;
}
function EdPickMark($params)
{
$object =& $this->getObject($params);
$o = '';
if($object->GetDBField('EditorsPick'))
{
$o .= $this->Application->ParseBlock( Array('name' => $this->SelectParam($params, 'render_as,block')) );
}
return $o;
}
/**
* Parses block only if item is favorite
*
* @param Array $params
* @return string
* @deprecated used only in default,onlinestore
*/
function FavoriteMark($params)
{
if ($this->IsFavorite($params)) {
return $this->Application->ParseBlock( Array( 'name' => $this->SelectParam($params, 'render_as,block') ) );
}
return '';
}
function CurrentCategory($params)
{
$sql = "SELECT Name
FROM ".TABLE_PREFIX."Category
WHERE CategoryId=".$this->Application->GetVar("m_cat_id");
return $this->Conn->GetOne($sql);
}
function RateForm($params)
{
$params['name'] = $this->SelectParam($params, 'render_as,block');
$labels = explode(',', $params['labels']);
$o = '';
$star_block = $this->SelectParam($params, 'star_render_as,star_block');
for($i = 5; $i >= 0; $i--)
{
$params['rating'] = $i;
$params['label'] = $this->Application->Phrase($labels[5 - $i]);
$params['stars'] = '';
for($j = $i; $j > 0; $j--)
{
$params['stars'] .= $this->Application->ParseBlock(Array('name' => $star_block));
}
$o .= $this->Application->ParseBlock($params);
}
return $o;
}
/**
* Parses block for changing favorite status
*
* @param Array $params
* @return string
* @deprecated used only in default,onlinestore
*/
function FavoriteToggle($params)
{
$block_params = Array ();
$block_names = $this->IsFavorite($params) ? 'remove_favorite_render_as,block_remove_favorite' : 'add_favorite_render_as,block_add_favorite';
$block_params['name'] = $this->SelectParam($params, $block_names);
$params['template'] = $params[$this->IsFavorite($params) ? 'template_on_remove' : 'template_on_add'];
$remove_params = Array (
'remove_favorite_render_as', 'block_remove_favorite', 'add_to_wish_list_render_as', 'block_add_to_wish_list',
'add_favorite_render_as', 'block_add_favorite', 'remove_from_wish_list_render_as', 'block_remove_from_wish_list',
'template_on_remove', 'template_on_add'
);
foreach ($params as $param_name => $param_value) {
if (in_array($param_name, $remove_params)) {
unset($params[$param_name]);
}
}
$block_params['wish_list_toggle_link'] = $this->FavoriteToggleLink($params);
return $this->Application->ParseBlock($block_params);
}
function WishListToggleLink($params)
{
$params['block_add_favorite'] = $this->SelectParam($params, 'add_to_wish_list_render_as,block_add_to_wish_list');
$params['block_remove_favorite'] = $this->SelectParam($params, 'remove_from_wish_list_render_as,block_remove_from_wish_list');
return $this->FavoriteToggle($params);
}
function AddReviewLink($params)
{
$o = $this->Application->ParseBlock( Array('name' => $this->SelectParam($params, 'render_as,block')) );
return $o;
}
function ListProducts($params)
{
return $this->PrintList2($params);
}
function ListRelatedProducts($params)
{
// $related = &$this->Application->recallObject('rel');
return $this->PrintList2($params);
}
function BuildListSpecial($params)
{
if ($this->Special != '') return $this->Special;
if ( isset($params['parent_cat_id']) ) {
$parent_cat_id = $params['parent_cat_id'];
}
else {
$parent_cat_id = $this->Application->GetVar('c_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
}
if ( isset($params['manufacturer']) ) {
$manufacturer = $params['manufacturer'];
}
else {
$manufacturer = $this->Application->GetVar('manuf_id');
}
$recursive = isset($params['recursive']);
$list_unique_key = $this->getUniqueListKey($params).$recursive;
if ($list_unique_key == '') {
return parent::BuildListSpecial($params);
}
return crc32($parent_cat_id.$list_unique_key.$manufacturer);
}
function ProductList($params)
{
if($params['shortlist'])
{
$params['per_page'] = $this->Application->ConfigValue('Comm_Perpage_Products_Short');
}
$object =& $this->Application->recallObject( $this->getPrefixSpecial() , $this->Prefix.'_List', $params );
switch($params['ListType'])
{
case 'favorites':
return $this->PrintList($params);
break;
case 'search':
default:
if(isset($params['block']))
{
return $this->PrintList($params);
}
else
{
$params['block'] = $params['block_main'];
$params['row_start_block'] = $params['block_row_start'];
$params['row_end_block'] = $params['block_row_end'];
return $this->PrintList2($params);
}
}
}
/**
* Adds product to recently viewed list (only in case, when not already there)
*
* @param Array $params
*/
function AddToRecent($params)
{
$recent_products = $this->Application->RecallVar('recent_products');
if (!$recent_products) {
$recent_products = Array();
}
else {
$recent_products = unserialize($recent_products);
}
$product_id = $this->Application->GetVar('p_id');
if (!in_array($product_id, $recent_products)) {
array_push($recent_products, $product_id);
$this->Application->StoreVar('recent_products', serialize($recent_products));
}
}
function SearchMoreLink($params)
{
$object =& $this->GetList($params);
$o = '';
if($object->GetPerPage() < $this->SearchResultsCount())
{
$o = $this->Application->ParseBlock( Array('name' => $params['block']) );
}
return $o;
}
function AddToCartLink($params)
{
$object =& $this->getObject($params);
if ($object->GetDBField('HasRequiredOptions')) {
$t = $params['product_template'];
if (!$t) {
$theme =& $this->Application->recallObject('theme.current');
if ($theme->GetDBField('Name') == 'onlinestore') {
$t = 'in-commerce/product/details';
}
elseif ($theme->GetDBField('Name') == 'default') {
$t = 'in-commerce/product';
}
}
$link_params = Array('m_cat_id' => $object->GetDBField('CategoryId'), 'pass' => 'm,p');
}
else {
$t = $params['template'];
$link_params = Array('m_cat_id' => $object->GetDBField('CategoryId'), 'pass' => 'm,p,ord', 'ord_event' => 'OnAddToCart');
}
$this->Application->SetVar('p_id', $this->Application->GetVar($this->getPrefixSpecial().'_id'));
return $this->Application->HREF($t, '', $link_params);
}
function SearchResultsCount($params)
{
$search_results_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = ' SELECT COUNT(ResourceId)
FROM '.$search_results_table.'
WHERE ItemType=11';
return $this->Conn->GetOne($sql);
}
function DetailsLink($params)
{
$this->Application->SetVar( $this->Prefix.'_id', $this->Application->GetVar($this->getPrefixSpecial().'_id') );
$ret = $this->Application->HREF('in-commerce/details', '', Array('pass' => 'all,p'));
return $ret;
}
function ProductLink($params)
{
return $this->ItemLink($params, 'product');
}
function ProductFileLink($params)
{
// 'p_id'=>'0', ??
$params = array_merge($params, Array('pass'=>'all,m,p,file.downl'));
$product_id = getArrayValue($params,'product_id');
if (!$product_id) {
$product_id = $this->Application->GetVar($this->Prefix.'_id');
}
$params['p_id'] = $product_id;
$product =& $this->Application->recallObject($this->getPrefixSpecial());
$params['m_cat_id'] = $product->GetDBField('CategoryId');
$main_processor =& $this->Application->recallObject('m_TagProcessor');
return $main_processor->T($params);
}
function GetMarkedVal($params)
{
$list =& $this->GetList($params);
return $this->Application->RecallVar($list->getPrefixSpecial().$params['name']);
}
function SortingOptions($params)
{
$list =& $this->GetList($params);
- $sorting_field_selected = $this->Application->RecallVar($list->getPrefixSpecial().$params['sorting_select_name']);
+ $sorting_field_selected = $this->Application->RecallVar($list->getPrefixSpecial() . $params['sorting_select_name']);
- if (!$sorting_field_selected){
+ if ( !$sorting_field_selected ) {
$sorting_field_selected = $this->Application->ConfigValue('product_OrderProductsBy');
}
$sql = 'SELECT ValueList
FROM ' . TABLE_PREFIX . 'ConfigurationValues
WHERE VariableName = "product_OrderProductsBy"';
$field_list_plain = $this->Conn->GetOne($sql);
$field_list = explode(',', $field_list_plain);
$o = '';
+ $option_params = $this->prepareTagParams($params);
- foreach ($field_list as $key=>$field){
+ foreach ($field_list as $field) {
list($fieldname, $fieldlabel) = explode('=', $field);
- $option_params = $this->prepareTagParams($params);
+
$option_params['fieldname'] = $fieldname;
$option_params['fieldlabel'] = $this->Application->Phrase($fieldlabel);
$option_params['name'] = $params['block_options'];
- if ($fieldname == $sorting_field_selected){
- $option_params['selected'] = 'selected';
- }else{
- $option_params['selected'] = '';
- }
+ $option_params['selected'] = $fieldname == $sorting_field_selected ? 'selected' : '';
+
$o .= $this->Application->ParseBlock($option_params);
}
return $o;
}
function SortingDirectionOptions($params)
{
$list =& $this->GetList($params);
- $sorting_dir_selected = $this->Application->RecallVar($list->getPrefixSpecial().$params['sorting_select_name']);
+ $sorting_dir_selected = $this->Application->RecallVar($list->getPrefixSpecial() . $params['sorting_select_name']);
- if (!$sorting_dir_selected){
+ if ( !$sorting_dir_selected ) {
$sorting_dir_selected = $this->Application->ConfigValue('product_OrderProductsByDir');
}
$o = '';
- $field_list = array('asc' => 'lu_Ascending', 'desc' => 'lu_Descending');
-
- foreach ($field_list as $fieldname=>$fieldlabel){
+ $field_list = array ('asc' => 'lu_Ascending', 'desc' => 'lu_Descending');
+ $option_params = $this->prepareTagParams($params);
- $option_params = $this->prepareTagParams($params);
+ foreach ($field_list as $fieldname => $fieldlabel) {
$option_params['fieldname'] = $fieldname;
$option_params['fieldlabel'] = $this->Application->Phrase($fieldlabel);
$option_params['name'] = $params['block_options'];
- if ($fieldname == $sorting_dir_selected){
- $option_params['selected'] = 'selected';
- }else{
- $option_params['selected'] = '';
- }
- $o .= $this->Application->ParseBlock($option_params);
+ $option_params['selected'] = $fieldname == $sorting_dir_selected ? 'selected' : '';
+ $o .= $this->Application->ParseBlock($option_params);
}
return $o;
}
function ErrorMessage($params)
{
if( $this->Application->GetVar('keywords_too_short') )
{
$ret = $this->Application->ParseBlock(Array('name' => $this->SelectParam($params, 'keywords_too_short_render_as,block_keywords_too_short')));
}
elseif( $this->Application->GetVar('adv_search_error') )
{
$ret = $this->Application->ParseBlock(Array('name' => $this->SelectParam($params, 'adv_search_error_render_as,block_adv_search_error')));
}
else
{
$ret = $this->Application->ParseBlock(Array('name' => $this->SelectParam($params, 'no_found_render_as,block_no_found')));
}
return $ret;
}
function ListReviews($params)
{
$review_tag_processor =& $this->Application->recallObject('rev.product_TagProcessor');
return $review_tag_processor->PrintList($params);
}
function ReviewCount($params)
{
$review_tag_processor =& $this->Application->recallObject('rev.product_TagProcessor');
return $review_tag_processor->TotalRecords($params);
}
function InitList($params){
$passed_manuf_id = $this->Application->GetVar('manuf_id');
if ($passed_manuf_id && !isset($params['manufacturer'])){
$params['manufacturer'] = $passed_manuf_id;
}
parent::InitList($params);
}
/**
* Builds link to manufacturer page
*
* @param Array $params
* @return string
*/
function ManufacturerLink($params)
{
if ( array_key_exists('manufacturer_id', $params) ) {
// use direct manufacturer from tag
$params['manuf_id'] = $params['manufacturer_id'];
unset($params['manufacturer_id']);
}
else {
// use product's manufacturer
$object =& $this->getObject($params);
$item_manufacturer_id = $object->GetDBField('ManufacturerId');
if ($item_manufacturer_id){
$params['manuf_id'] = $item_manufacturer_id;
}
}
$params['pass'] = 'm,manuf';
$params['m_cat_id'] = 0;
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
function AlreadyReviewed($params)
{
$rev_tag_processor =& $this->Application->recallObject('rev_TagProcessor');
return $rev_tag_processor->AlreadyReviewed($params);
}
function PrepareSearchResults($params)
{
$names_mapping = $this->Application->GetVar('NamesToSpecialMapping');
if($this->Application->GetVar('search_type') == 'advanced' || !getArrayValue($names_mapping, $this->Prefix, 'search_results'))
{
$params = Array('list_name' => 'search_results',
'types' => 'search',
'parent_cat_id' => 'any',
'recursive' => 'true',
'per_page' => 'short_list'
);
$this->InitList($params);
}
return '';
}
function Available($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
if (!$object->GetDBField('InventoryStatus')) return true;
$backordering = $this->Application->ConfigValue('Comm_Enable_Backordering');
if ($object->GetDBField('InventoryStatus') == 2) {
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$sql = 'SELECT SUM(IF(QtyInStock > '.$object->GetDBField('QtyInStockMin').', 1, 0))
FROM '.$poc_table.'
WHERE (ProductId = '.$object->GetID().') AND (Availability = 1)';
$stock_available = $this->Conn->GetOne($sql) > 0; // at least one option combination present
}
else {
$stock_available = $object->GetDBField('QtyInStock') > $object->GetDBField('QtyInStockMin');
}
$prod_backordering = $object->GetDBField('BackOrder');
if ($stock_available) return true;
// stock is NOT available:
if (!$backordering || $prod_backordering == 0) return false; // if backordering is generaly disabled or disabled for product (Never)
// backordering enabled; (auto or always mode)
return true;
}
function IsSubscription($params)
{
$object = &$this->Application->recallObject($this->getPrefixSpecial());
return ($object->GetDBField('Type') == 2);
}
function IsTangible($params)
{
$object = &$this->Application->recallObject($this->getPrefixSpecial());
return ($object->GetDBField('Type') == 1);
}
function HasFiles($params)
{
$sql = 'SELECT COUNT(FileId) FROM '.$this->Application->getUnitOption('file', 'TableName').'
WHERE ProductId = '.$this->Application->GetVar('p_id').' AND Status = 1';
return $this->Conn->GetOne($sql) ? 1 : 0;
}
function UniqueFileName($params)
{
$file_object =& $this->Application->recallObject('file.downl');
return ($file_object->GetDBField('Name') &&
$file_object->GetDBField('Name') != $file_object->GetDBField('FilePath'))
? 1 : 0;
}
function FileDownload($params)
{
$file_id = $this->Application->GetVar('file.downl_id');
$product_id = $file_id ? $this->Conn->GetOne('SELECT ProductId
FROM '.$this->Application->getUnitOption('file', 'TableName').'
WHERE FileId = '.$file_id) :
$this->Application->GetVar($this->getPrefixSpecial().'_id');
$download_helper_class = $this->Application->getUnitOption($this->Prefix, 'DownloadHelperClass');
if (!$download_helper_class) {
$download_helper_class = 'DownloadHelper';
}
$download_helper =& $this->Application->recallObject($download_helper_class);
if (!$download_helper->CheckAccess($file_id, $product_id)) {
$this->Application->ApplicationDie('File Access permission check failed!');
}
$file_info = $download_helper->SendFile($file_id, $product_id);
$download_helper->LogDownload($product_id, $file_info);
define('DBG_SKIP_REPORTING', 1);
$this->Application->ApplicationDie();
}
function PictureLink($params)
{
if (getArrayValue($params, 'picture_list')) {
$params['img_id'] = $this->Application->GetVar('img_id');
$params['pass'] = 'all,p,img';
unset($params['picture_list']);
}
else {
$params['pass'] = 'all,p';
}
return $this->Application->ProcessParsedTag('m', 'Link', $params);
}
function ShouldListOptions($params)
{
$object =& $this->getObject($params);
$req_filter = '';
if (getArrayValue($params, 'required_only')) {
$req_filter = ' AND Required = 1';
}
$query = 'SELECT COUNT(*) FROM '.TABLE_PREFIX.'ProductOptions WHERE ProductId = '.$object->GetID().$req_filter;
$res = $this->Conn->GetOne($query);
return $res > 0;
}
function CountOptions($params)
{
$object =& $this->getObject($params);
$query = 'SELECT COUNT(*) FROM '.TABLE_PREFIX.'ProductOptions WHERE ProductId = '.$object->GetID();
$res = $this->Conn->GetOne($query);
$max = $this->SelectParam($params, 'greater');
if (!$max) $max = 0;
return $res > $max;
}
function OptionsUpdateMode($params)
{
return $this->Application->GetVar('orditems_id') !== false;
}
function OptionsHaveError($params)
{
return $this->Application->GetVar('opt_error') > 0;
}
function OptionsError($params)
{
switch ($this->Application->GetVar('opt_error')) {
case 1:
return $this->Application->Phrase($params['required']);
case 2:
return $this->Application->Phrase($params['not_available']);
}
}
function ListShippingTypes($params)
{
$quote_engine_collector =& $this->Application->recallObject('ShippingQuoteCollector');
/* @var $quote_engine_collector ShippingQuoteCollector */
$types = $quote_engine_collector->GetAvailableShippingTypes();
$object =& $this->getObject($params);
$selected = $object->GetDBField('ShippingLimitation');
$selected = explode('|', substr($selected, 1, -1));
$o = '';
foreach ($types as $a_type)
{
$is_selected = in_array($a_type['_Id'], $selected);
$continue = $params['mode'] == 'selected' ? !$is_selected : $is_selected;
if ($continue) continue;
$block_params = $a_type;
$block_params['name'] = $params['render_as'];
$o .= $this->Application->ParseBlock($block_params);
}
return $o;
}
function PageLink($params)
{
$manufacturer_id = $this->Application->GetVar('manuf_id');
if ($manufacturer_id) {
$params['pass'] = 'm,'.$this->getPrefixSpecial().',manuf';
}
return parent::PageLink($params);
}
/**
* Calculate savings based on price & market price relationship
*
* @param Array $params
* @return int
*/
function Savings($params)
{
$object =& $this->getObject($params);
/* @var $object kDBItem */
$price = $object->GetDBField('Price');
$msrp = $object->GetDBField('MSRP');
$value = 0;
if (isset($params['type']) && ($params['type'] == 'percent')) {
if ($msrp > 0) {
return 100 - round($price * 100 / $msrp);
}
}
else {
if ($msrp > $price) {
$value = $msrp - $price;
}
}
if (isset($params['currency'])) {
$lang =& $this->Application->recallObject('lang.current');
/* @var $lang LanguagesItem */
$iso = $this->GetISO($params['currency']);
$value = $this->ConvertCurrency($value, $iso);
$value = $lang->formatNumber( sprintf('%.2f', $value) );
$value = $this->AddCurrencySymbol($value, $iso);
}
return $value;
}
/**
* Hides permission tab, when it's not allowed by configuration settings
*
* @param Array $params
*/
function ModifyUnitConfig($params)
{
$edit_tab_presets = $this->Application->getUnitOption($this->Prefix, 'EditTabPresets');
$edit_tab_preset = $edit_tab_presets['Default'];
$object =& $this->getObject($params);
/* @var $object kDBItem */
$product_type = $object->GetDBField('Type');
if ($product_type != PRODUCT_TYPE_TANGIBLE) {
unset($edit_tab_preset['inventory']);
}
if ($product_type == PRODUCT_TYPE_SUBSCRIPTION) {
unset($edit_tab_preset['options']);
}
else {
unset($edit_tab_preset['access_and_pricing']);
}
if ($product_type != PRODUCT_TYPE_TANGIBLE && $product_type != PRODUCT_TYPE_PACKAGE) {
unset($edit_tab_preset['pricing']);
}
else {
unset($edit_tab_preset['pricing2']);
}
if ($product_type != PRODUCT_TYPE_DOWNLOADABLE) {
unset($edit_tab_preset['files_and_pricing']);
}
if ($product_type != PRODUCT_TYPE_PACKAGE) {
unset($edit_tab_preset['package_content']);
}
$edit_tab_presets['Default'] = $edit_tab_preset;
$this->Application->setUnitOption($this->Prefix, 'EditTabPresets', $edit_tab_presets);
}
}
\ No newline at end of file
Index: branches/5.2.x/install/upgrades.php
===================================================================
--- branches/5.2.x/install/upgrades.php (revision 14871)
+++ branches/5.2.x/install/upgrades.php (revision 14872)
@@ -1,167 +1,142 @@
<?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!');
$upgrade_class = 'InCommerceUpgrades';
/**
* Class, that holds all upgrade scripts for "In-Commerce" module
*
*/
class InCommerceUpgrades extends kUpgradeHelper {
public function __construct()
{
parent::__construct();
$this->dependencies = Array (
'4.3.9' => Array ('Core' => '4.3.9'),
'5.0.0' => Array ('Core' => '5.0.0'),
'5.0.1' => Array ('Core' => '5.0.1'),
'5.0.2-B1' => Array ('Core' => '5.0.2-B1'),
'5.0.2-B2' => Array ('Core' => '5.0.2-B2'),
'5.0.2-RC1' => Array ('Core' => '5.0.2-RC1'),
'5.0.2' => Array ('Core' => '5.0.2'),
'5.0.3-B1' => Array ('Core' => '5.0.3-B1'),
'5.0.3-B2' => Array ('Core' => '5.0.3-B2'),
'5.0.3-RC1' => Array ('Core' => '5.0.3-RC1'),
'5.0.3' => Array ('Core' => '5.0.3'),
'5.0.4-B1' => Array ('Core' => '5.0.4-B1'),
'5.0.4-B2' => Array ('Core' => '5.0.4-B2'),
'5.0.4' => Array ('Core' => '5.0.4'),
'5.1.0-B1' => Array ('Core' => '5.1.0-B1'),
'5.1.0-B2' => Array ('Core' => '5.1.0-B2'),
'5.1.0-RC1' => Array ('Core' => '5.1.0-RC1'),
'5.1.0' => Array ('Core' => '5.1.0'),
'5.1.1-B1' => Array ('Core' => '5.1.1-B1'),
'5.1.1-B2' => Array ('Core' => '5.1.1-B2'),
'5.1.1-RC1' => Array ('Core' => '5.1.1-RC1'),
'5.1.1' => Array ('Core' => '5.1.1'),
'5.1.2-B1' => Array ('Core' => '5.1.2-B1'),
'5.1.2-B2' => Array ('Core' => '5.1.2-B2'),
'5.1.2-RC1' => Array ('Core' => '5.1.2-RC1'),
'5.1.2' => Array ('Core' => '5.1.2'),
'5.1.3-B1' => Array ('Core' => '5.1.3-B1'),
'5.1.3-B2' => Array ('Core' => '5.1.3-B2'),
'5.1.3-RC1' => Array ('Core' => '5.1.3-RC1'),
'5.1.3-RC2' => Array ('Core' => '5.1.3-RC2'),
'5.1.3' => Array ('Core' => '5.1.3'),
);
}
/**
* Changes table structure, where multilingual fields of TEXT type are present
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_0_0($mode)
{
if ($mode == 'after') {
// update icon
$root_category = $this->Application->findModule('Name', 'In-Commerce', 'RootCat');
$sql = 'UPDATE ' . $this->Application->getUnitOption('c', 'TableName') . '
SET UseMenuIconUrl = 1, MenuIconUrl = "in-commerce/img/menu_products.gif"
WHERE ' . $this->Application->getUnitOption('c', 'IDField') . ' = ' . $root_category;
$this->Conn->Query($sql);
$this->_updateDetailTemplate('p', 'in-commerce/product/details', 'in-commerce/designs/detail');
// copy store name to company name
$store_name = $this->Application->ConfigValue('Comm_StoreName');
$sql = 'UPDATE ' . TABLE_PREFIX . 'ConfigurationValues
SET VariableValue = ' . $this->Conn->qstr($store_name) . '
WHERE VariableName = "Comm_CompanyName"';
$this->Conn->Query($sql);
}
}
/**
- * Replaces deprecated detail template design with new one
- *
- * @param string $prefix
- * @param string $from_template
- * @param string $to_template
- */
- function _updateDetailTemplate($prefix, $from_template, $to_template)
- {
- $sql = 'SELECT CustomFieldId
- FROM ' . TABLE_PREFIX . 'CustomField
- WHERE FieldName = "' . $prefix . '_ItemTemplate"';
- $custom_field_id = $this->Conn->GetOne($sql);
-
- $ml_formatter =& $this->Application->recallObject('kMultiLanguage');
- /* @var $ml_formatter kMultiLanguage */
-
- $field = $ml_formatter->LangFieldName('cust_' . $custom_field_id, true);
-
- $sql = 'UPDATE ' . TABLE_PREFIX . 'CategoryCustomData
- SET ' . $field . ' = "' . $to_template . '"
- WHERE ' . $field . ' = "' . $from_template . '"';
- $this->Conn->Query($sql);
- }
-
- /**
* Update to 5.0.1, update details template
*
* @param string $mode when called mode {before, after)
*/
function Upgrade_5_0_1($mode)
{
if ($mode == 'after') {
$this->_updateDetailTemplate('p', 'in-commerce/designs/detail', 'in-commerce/products/product_detail');
// clean incomplete orders 5+ hours old
// don't use ORDER_STATUS_INCOMPLETE constant, since it's not available upgrade
$delete_timestamp = mktime() - (3600 * 5);
$sql = 'SELECT OrderId FROM ' . TABLE_PREFIX . 'Orders
WHERE Status = ' . 0 . '
AND OrderDate < ' . $delete_timestamp;
$orders_to_delete = $this->Conn->GetCol($sql);
if ( $orders_to_delete && is_array($orders_to_delete) ) {
$this->Conn->Query( 'DELETE FROM ' . TABLE_PREFIX . 'OrderItems
WHERE OrderId IN ( ' . implode(',', $orders_to_delete) . ' )' );
$this->Conn->Query( 'DELETE FROM ' . TABLE_PREFIX . 'Orders
WHERE Status = ' . 0 . '
AND OrderDate < ' . $delete_timestamp );
}
// delete old events
$events_to_delete = Array ( 'SITE.SUGGEST' );
$sql = 'SELECT EventId FROM ' . TABLE_PREFIX . 'Events
WHERE Event IN ("' . implode('","', $events_to_delete) . '")';
$event_ids = $this->Conn->GetCol($sql);
if ($event_ids) {
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'EmailMessage
WHERE EventId IN (' . implode(',', $event_ids) . ')';
$this->Conn->Query($sql);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Events
WHERE EventId IN (' . implode(',', $event_ids) . ')';
$this->Conn->Query($sql);
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Phrase
WHERE Phrase IN ("la_event_user.suggest_site")';
$this->Conn->Query($sql);
}
}
}
}
\ No newline at end of file

Event Timeline