Page MenuHomeIn-Portal Phabricator

in-commerce
No OneTemporary

File Metadata

Created
Wed, Feb 26, 1:51 PM

in-commerce

Index: branches/5.2.x/units/affiliate_plans/affiliate_plans_event_handler.php
===================================================================
--- branches/5.2.x/units/affiliate_plans/affiliate_plans_event_handler.php (revision 14624)
+++ branches/5.2.x/units/affiliate_plans/affiliate_plans_event_handler.php (revision 14625)
@@ -1,92 +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 AffiliatePlansEventHandler extends kDBEventHandler {
- function SetCustomQuery(&$event)
+ /**
+ * Apply any custom changes to list's sql query
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
+ */
+ protected function SetCustomQuery(&$event)
{
if($event->Special == 'active')
{
$object =& $event->getObject();
$object->addFilter('active', '%1$s.Enabled = 1');
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
$object =& $event->getObject();
$object->SetDBField('IsPrimary', 1);
$object->Update();
}
/**
- * Enter description here...
+ * Occurs before updating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemUpdate(&$event)
+ {
+ parent::OnBeforeItemUpdate($event);
+
+ $this->itemChanged($event);
+ }
+
+ /**
+ * Occurs before creating item
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemUpdate(&$event)
+ protected function OnBeforeItemCreate(&$event)
+ {
+ parent::OnBeforeItemCreate($event);
+
+ $this->itemChanged($event);
+ }
+
+ /**
+ * Occurs before item is changed
+ *
+ * @param kEvent $event
+ */
+ function itemChanged(&$event)
{
$object =& $event->getObject();
+ /* @var $object kDBItem */
$live_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
- $plans_count = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$live_table);
- if(!$plans_count) $object->SetDBField('IsPrimary', 1);
+ $plans_count = $this->Conn->GetOne('SELECT COUNT(*) FROM ' . $live_table);
+ if ( !$plans_count ) {
+ $object->SetDBField('IsPrimary', 1);
+ }
- if( $object->GetDBField('IsPrimary') && $object->Validate() )
- {
- $sql = 'UPDATE '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
+ if ( $object->GetDBField('IsPrimary') && $object->Validate() ) {
+ $sql = 'UPDATE ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
SET IsPrimary = 0';
$this->Conn->Query($sql);
- $status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );
+ $status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField'));
$object->SetDBField($status_field, 1);
}
}
- function OnBeforeItemCreate(&$event)
+ /**
+ * Don't allow to delete primary affiliate plan
+ *
+ * @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
+ */
+ protected function customProcessing(&$event, $type)
{
- $this->OnBeforeItemUpdate($event);
- }
+ if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
+ $ids = $event->getEventParam('ids');
- function OnMassDelete(&$event)
- {
- if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
- $event->status = kEvent::erFAIL;
- return;
- }
+ $sql = 'SELECT ' . $this->Application->getUnitOption($event->Prefix, 'IDField') . '
+ FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
+ WHERE IsPrimary = 1';
+ $primary_id = $this->Conn->GetOne($sql);
- $ids = $this->StoreSelectedIDs($event);
- $event->setEventParam('ids', $ids );
- $ids = $event->getEventParam('ids');
-
- $temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
-
- $sql = 'SELECT AffiliatePlanId FROM '.$this->Application->getUnitOption('ap', 'TableName').'
- WHERE IsPrimary = 1';
- $primary_id = $this->Conn->GetOne($sql);
- $ids = array_diff($ids, Array($primary_id));
+ $ids = array_diff($ids, Array ($primary_id));
- if($ids)
- {
- $temp->DeleteItems($event->Prefix, $event->Special, $ids);
+ $event->setEventParam('ids', $ids);
}
- $this->clearSelectedIDs($event);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/gateways/gw_tag_processor.php
===================================================================
--- branches/5.2.x/units/gateways/gw_tag_processor.php (revision 14624)
+++ branches/5.2.x/units/gateways/gw_tag_processor.php (revision 14625)
@@ -1,120 +1,125 @@
<?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 GatewayTagProcessor extends kDBTagProcessor {
/**
* Payment gateway config values for current payment type
*
* @var Array
* @access private
*/
var $ConfigValues=Array();
/**
* Payment type id for current gateway values
*
* @var int
* @access private
*/
var $PaymentTypeID=0;
function initGWConfigValues()
{
$payment_type_id = $this->Application->GetVar('pt_id');
$GWConfigValue =& $this->Application->recallObject('gwfv');
$sql = 'SELECT Value, GWConfigFieldId FROM '.$GWConfigValue->TableName.' WHERE PaymentTypeId = '.$payment_type_id;
$this->ConfigValues = $this->Conn->GetCol($sql,'GWConfigFieldId');
}
function gwConfigValue($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$id = $object->GetID();
$value = isset($this->ConfigValues[$id]) ? $this->ConfigValues[$id] : '';
if (!array_key_exists('no_special', $params) || !$params['no_special']) {
$value = htmlspecialchars($value);
}
if ( getArrayValue($params,'checked') ) {
$value = ($value == 1) ? 'checked' : '';
}
return $value;
}
function PrintList($params)
{
$list =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix.'_List', $params);
$id_field = $this->Application->getUnitOption($this->Prefix,'IDField');
$list->Query();
$list->GoFirst();
$block_params=$this->prepareTagParams($params);
$block_params['name']=$params['block'];
$block_params['pass_params']='true';
$payment_type_object =& $this->Application->recallObject('pt');
$o = '';
while (!$list->EOL())
{
$this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) );
$display_style = $payment_type_object->GetDBField('GatewayId') == $list->GetDBField('GatewayId') ? 'table-row' : 'none';
$block_params['input_block'] = $params['input_block_prefix'].$list->GetDBField('ElementType');
$block_params['gateway_id'] = $list->GetDBField('GatewayId');
$block_params['display'] = $display_style;
$o .= $this->Application->ParseBlock($block_params, 1);
$list->GoNext();
}
return $o;
}
- function PredefinedOptions($params)
+ /**
+ * Prints list a all possible field options
+ *
+ * @param Array $params
+ * @return string
+ * @access protected
+ */
+ protected function PredefinedOptions($params)
{
- $object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
-
- $value = $this->gwConfigValue($params);
-
- $options = explode(',', $object->GetDBField('ValueList') );
+ $object =& $this->getObject($params);
+ /* @var $object kDBItem */
$block_params = $this->prepareTagParams($params);
-
$block_params['name'] = $this->SelectParam($params, 'render_as,block');
$block_params['pass_params'] = 'true';
$o = '';
- foreach ($options as $key_val)
- {
- list($key,$val) = explode('=', $key_val);
+ $value = $this->gwConfigValue($params);
+ $options = explode(',', $object->GetDBField('ValueList'));
+
+ foreach ($options as $key_val) {
+ list($key, $val) = explode('=', $key_val);
$block_params['key'] = $key;
$block_params['option'] = $val;
- $block_params['selected'] = ( $key == $value ? ' '.$params['selected'] : '');
+ $block_params['selected'] = ($key == $value ? ' ' . $params['selected'] : '');
$block_params['PrefixSpecial'] = $this->getPrefixSpecial();
$o .= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
}
\ No newline at end of file
Index: branches/5.2.x/units/product_options/product_options_event_handler.php
===================================================================
--- branches/5.2.x/units/product_options/product_options_event_handler.php (revision 14624)
+++ branches/5.2.x/units/product_options/product_options_event_handler.php (revision 14625)
@@ -1,76 +1,84 @@
<?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 ProductOptionsEventHandler extends kDBEventHandler{
- function SetCustomQuery(&$event)
+ /**
+ * Apply any custom changes to list's sql query
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
+ */
+ protected function SetCustomQuery(&$event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
$selectable_only = $event->getEventParam('selectable_only');
if ($selectable_only) {
$object->addFilter('types_filter', 'OptionType IN (1,3,6)');
}
}
/**
* Updates temp_id to live_id in options combinations
*
* !Not called when "po" doesn't have subitems (temp handler problem)
*
* @param kEvent $event
*/
function OnAfterCopyToLive(&$event)
{
$id = $event->getEventParam('id');
$temp_id = $event->getEventParam('temp_id');
if ($id == $temp_id) return;
$poc_table = $this->Application->GetTempName(TABLE_PREFIX.'ProductOptionCombinations', 'prefix:p');
$query = 'SELECT * FROM '.$poc_table;
$combs = $this->Conn->Query($query);
foreach ($combs as $a_comb) {
$comb_data = unserialize($a_comb['Combination']);
$n_combs = array();
foreach ($comb_data as $key => $val)
{
$n_key = $key == $temp_id ? $id : $key;
$n_combs[$n_key] = $val;
}
ksort($n_combs);
$n_combs = serialize($n_combs);
$n_crc = crc32($n_combs);
$query = 'UPDATE '.$poc_table.' SET
Combination = '.$this->Conn->qstr($n_combs).', CombinationCRC = '.$n_crc.' WHERE CombinationId = '.$a_comb['CombinationId'];
$this->Conn->Query($query);
}
}
function OnAfterClone(&$event)
{
$id = $event->getEventParam('id');
$org_id = $event->getEventParam('original_id');
// storing original to new ids mapping to use in poc:OnBeforeClone
$options_mapping = $this->Application->GetVar('poc_mapping');
if (!$options_mapping) $options_mapping = array();
$options_mapping[$org_id] = $id;
$this->Application->SetVar('poc_mapping', $options_mapping);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/pricing/pricing_event_handler.php
===================================================================
--- branches/5.2.x/units/pricing/pricing_event_handler.php (revision 14624)
+++ branches/5.2.x/units/pricing/pricing_event_handler.php (revision 14625)
@@ -1,484 +1,509 @@
<?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.
*/
// include globals.php from current folder
kUtil::includeOnce(MODULES_PATH .'/in-commerce/units/pricing/globals.php');
class PricingEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnMoreBrackets' => Array('subitem' => 'add|edit'),
'OnInfinity' => Array('subitem' => 'add|edit'),
'OnArrange' => Array('subitem' => 'add|edit'),
'OnDeleteBrackets' => Array('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decine and so on events
$brackets_events = Array(
'OnMoreBrackets' => 'PricingBracketsAction',
'OnArrange' => 'PricingBracketsAction',
'OnInfinity' => 'PricingBracketsAction',
'OnDeleteBrackets' => 'PricingBracketsAction',
);
$this->eventMethods = array_merge($this->eventMethods, $brackets_events);
}
function PricingBracketsAction(&$event)
{
$event->redirect=false;
$temp = $this->Application->GetVar($event->getPrefixSpecial(true));
// $object =& $event->GetObject();
// $formatter =& $this->Application->recallObject('kFormatter');
// $temp = $formatter->TypeCastArray($temp, $object);
//uasort($temp, 'pr_bracket_comp');
$bracket =& $this->Application->recallObject($event->getPrefixSpecial());
foreach($temp as $id => $record)
{
if( $record['MaxQty'] == '&#8734;' || $record['MaxQty'] == '∞')
{
$temp[$id]['MaxQty'] = -1;
}
}
$group_id = $this->Application->getVar('group_id');
if($group_id>0){
$where_group=' GroupId = '.$group_id.' ';
}
else {
$where_group= ' TRUE ';
}
switch ($event->Name)
{
case 'OnMoreBrackets':
$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$bracket->IDField.') FROM '.$bracket->TableName);
if($new_id > 0) $new_id = 0;
do
{
$new_id--;
} while
($this->check_array($this->Application->GetVar($event->getPrefixSpecial(true)), 'PriceId', $new_id));
$last_max_qty = $this->Conn->GetOne('SELECT MAX(MaxQty) FROM '.$bracket->TableName.' WHERE '.$where_group);
$min_qty = $this->Conn->GetOne('SELECT MIN(MaxQty) FROM '.$bracket->TableName.' WHERE '.$where_group);
if ($min_qty==-1) $last_max_qty = -1;
if (!$last_max_qty) $last_max_qty=1;
for($i = $new_id; $i > $new_id - 5; $i--)
{
$temp[$i]['PriceId'] = $i;
$temp[$i]['MinQty'] = ($i == $new_id-4 && $last_max_qty != -1) ? $last_max_qty : '';
$temp[$i]['MaxQty'] = ($i == $new_id-4 && $last_max_qty != -1) ? -1 : '';
$temp[$i]['Price'] = '';
$temp[$i]['Cost'] = '';
$temp[$i]['Points'] = '';
$temp[$i]['Negotiated'] = '0';
$temp[$i]['IsPrimary'] = '0';
$temp[$i]['GroupId'] = $group_id;
}
$this->Application->SetVar($event->getPrefixSpecial(true), $temp);
$event->CallSubEvent('OnPreSaveBrackets');
break;
case 'OnArrange':
$temp=$this->OnArrangeBrackets($event, $temp, $bracket);
$this->Application->SetVar($event->getPrefixSpecial(true), $temp);
$event->CallSubEvent('OnPreSaveBrackets');
break;
case 'OnInfinity':
$temp=$this->OnArrangeBrackets($event, $temp, $bracket);
$this->Application->SetVar($event->getPrefixSpecial(true), $temp);
$event->CallSubEvent('OnPreSaveBrackets');
$infinite_exists = $this->Conn->GetOne('SELECT count(*) FROM '.$bracket->TableName.' WHERE MaxQty=-1 '.' AND '.$where_group);
if($infinite_exists==0){
reset($temp);
$last_bracket=end($temp);
$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$bracket->IDField.') FROM '.$bracket->TableName);
$brackets_exist = (int)$this->Conn->GetOne('SELECT COUNT(*) FROM '.$bracket->TableName.' WHERE '.$where_group);
if($new_id > 0) $new_id = 0;
do
{
$new_id--;
} while
($this->check_array($this->Application->GetVar($event->getPrefixSpecial(true)), 'PriceId', $new_id));
$infinite_bracket['PriceId'] = $new_id;
$infinite_bracket['MinQty'] = ($brackets_exist>0)?$last_bracket['MaxQty']:1;
$infinite_bracket['MaxQty'] = '-1';
$infinite_bracket['Price'] = '';
$infinite_bracket['Cost'] = '';
$infinite_bracket['Points'] = '';
$infinite_bracket['Negotiated'] = '0';
$infinite_bracket['IsPrimary'] = '0';
$infinite_bracket['GroupId'] = $group_id;
$temp[$new_id]=$infinite_bracket;
reset($temp);
}
$this->Application->SetVar($event->getPrefixSpecial(true), $temp);
$event->CallSubEvent('OnPreSaveBrackets');
break;
case 'OnDeleteBrackets':
if ($group_id) {
$temp = ''; // delete all pricings from "pr_tang" var
$sql = 'DELETE FROM ' . $bracket->TableName . '
WHERE ProductId = ' . $this->Application->GetVar('p_id') . ' AND GroupId = ' . $group_id;
$this->Conn->Query($sql);
}
break;
default:
}
$this->Application->SetVar($event->getPrefixSpecial(true), $temp); // store pr_tang var
}
function OnPreSaveBrackets(&$event)
{
if( $this->Application->GetVar('pr_tang') ) {
$object =& $event->GetObject();
/* @var $object kDBItem */
$product_id = $this->Application->GetVar('p_id');
$group_id = $this->Application->getVar('group_id');
$sql = 'SELECT PriceId
FROM ' . $object->TableName . '
WHERE ProductId = ' . $product_id . ' ' . ($group_id? 'AND GroupId = ' . $group_id : '');
$stored_ids = $this->Conn->GetCol($sql);
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); // get pr_tang var
uasort($items_info, 'pr_bracket_comp');
foreach ($items_info as $item_id => $values) {
if (in_array($item_id, $stored_ids)) { //if it's already exist
$object->Load($item_id);
$object->SetFieldsFromHash($values);
if (!$object->Validate()) {
unset($stored_ids[array_search($item_id, $stored_ids)]);
$event->redirect = false;
continue;
}
if( $object->Update($item_id) ) {
$event->status=kEvent::erSUCCESS;
}
else {
$event->status=kEvent::erFAIL;
$event->redirect=false;
break;
}
unset($stored_ids[array_search($item_id, $stored_ids)]);
}
else {
$object->Clear();
$object->SetFieldsFromHash($values);
$object->SetDBField('ProductId', $product_id);
if( $object->Create() ) {
$event->status=kEvent::erSUCCESS;
}
}
}
// delete
foreach ($stored_ids as $stored_id) {
$this->Conn->Query('DELETE FROM ' . $object->TableName . ' WHERE PriceId = ' . $stored_id);
}
}
}
- function customProcessing(&$event,$type)
+ /**
+ * Apply custom processing to item
+ *
+ * @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
+ */
+ protected function customProcessing(&$event,$type)
{
$bracket =& $event->getObject();
switch ($type)
{
case 'before':
$bracket->SetDBField('ProductId', $this->Application->GetVar('p_id'));
if( $bracket->GetDBField('MaxQty') == '&#8734;' || $bracket->GetDBField('MaxQty') == '∞' )
{
$bracket->SetDBField('MaxQty', -1);
}
break;
case 'after':
break;
default:
}
}
function OnArrangeBrackets(&$event, &$temp, &$bracket)
{
$temp_orig = $temp;
reset($temp);
if (is_array($temp))
{
// array to store max values (2nd column)
$end_values = Array();
// get minimal value of Min
$first_elem=current($temp);
$start = $first_elem['MinQty'];
if (!$start){
$start = 1;
}
foreach($temp as $id => $record)
{
/*
This 3-ifs logic fixes collision with invalid input values having
1 pricing record.
The logic is:
1) If we got Max less than Min, we set Min to 1 that gives us
integrity.
2) If we got equal values for Min and Max, we set range 1..Max like
in previous. But if Min was 1 and Max was 1 we set full range 1..infinity
3) If we got Max = 0 we just set it tom infinity because we can't
guess what user meant
*/
if (sizeof($temp) == 1 && $record['MinQty'] > ($record['MaxQty'] == -1 ? $record['MinQty']+1 : $record['MaxQty']) ){
$record['MinQty'] = 1;
$temp[$id]['MinQty'] = 1;
$start = 1;
}
if (sizeof($temp) == 1 && $record['MinQty'] == $record['MaxQty']){
if ($record['MaxQty'] == 1){
$record['MaxQty'] = -1;
$temp[$id]['MaxQty'] = -1;
}
else {
$record['MinQty'] = 1;
$temp[$id]['MinQty'] = 1;
}
}
if (sizeof($temp) == 1 && $record['MaxQty'] == 0){
$record['MaxQty'] = -1;
$temp[$id]['MaxQty'] = -1;
}
if(
// MAX is less than start
($record['MaxQty'] <= $start && $record['MaxQty'] != -1) ||
// Max is empty
!$record['MaxQty'] ||
// Max already defined in $end_values
(array_search($record['MaxQty'], $end_values) !== false)
) { // then delete from brackets list
unset($temp[$id]);
}
else { // this is when ok - add to end_values list
$end_values[] = $record['MaxQty'];
}
}
// sort brackets by 2nd column (Max values)
uasort($temp, 'pr_bracket_comp');
reset($temp);
$first_item=each($temp);
$first_item_key=$first_item['key'];
$group_id = $this->Application->getVar('group_id');
$default_group = $this->Application->ConfigValue('User_LoggedInGroup');
if($group_id>0){
$where_group=' AND GroupId = '.$group_id.' ';
}
$ids = $this->Conn->GetCol('SELECT PriceId FROM '.$bracket->TableName.' WHERE ProductId='.$this->Application->GetVar('p_id').' '.$where_group);
if(is_array($ids)) {
usort($ids, 'pr_bracket_id_sort');
}
$min_id = min( min($ids) - 1, -1 );
foreach($temp as $key => $record)
{
$temp[$key]['MinQty']=$start;
$temp[$key]['IsPrimary']=0;
$temp[$key]['GroupId']=$group_id;
$start=$temp[$key]['MaxQty'];
}
if ($temp[$first_item_key]['GroupId'] == $default_group) {
$temp[$first_item_key]['IsPrimary']=1;
}
}
return $temp;
}
/**
* Set's price as primary for product
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$this->StoreSelectedIDs($event);
$ids=$this->getSelectedIDs($event);
if($ids)
{
$id = array_shift($ids);
$table_info = $object->getLinkedInfo();
$this->Conn->Query('UPDATE '.$object->TableName.' SET IsPrimary = 0 WHERE '.$table_info['ForeignKey'].' = '.$table_info['ParentId']);
$this->Conn->Query('UPDATE '.$object->TableName.' SET IsPrimary = 1 WHERE ('.$table_info['ForeignKey'].' = '.$table_info['ParentId'].') AND (PriceId = '.$id.')');
}
$event->setRedirectParams(Array('opener' => 's'), true);
}
/**
- * Resets primary mark for other pricings of given product, when current pricing is primary
+ * Resets primary mark for other prices of given product, when current pricing is primary
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemUpdate(&$event)
+ protected function OnBeforeItemUpdate(&$event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
- if ($object->GetDBField('IsPrimary') == 1) {
- // make all pricings non primary, when this one is
+ if ( $object->GetDBField('IsPrimary') == 1 ) {
+ // make all prices non primary, when this one is
$sql = 'UPDATE ' . $object->TableName . '
SET IsPrimary = 0
WHERE (ProductId = ' . $object->GetDBField('ProductId') . ') AND (' . $object->IDField . ' <> ' . $object->GetID() . ')';
$this->Conn->Query($sql);
}
}
/**
- * Enter description here...
+ * Occurs before creating item
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemCreate(&$event)
+ protected function OnBeforeItemCreate(&$event)
{
+ parent::OnBeforeItemCreate($event);
+
$object =& $event->getObject();
+ /* @var $object kDBItem */
+
$table_info = $object->getLinkedInfo($event->Special);
- $table_info['ParentId'] = ($table_info['ParentId']?$table_info['ParentId']:0);
+ $table_info['ParentId'] = ($table_info['ParentId'] ? $table_info['ParentId'] : 0);
- if ( $object->GetDBField('IsPrimary') == 1 ){
- $this->Conn->Query('UPDATE '.$object->TableName.' SET IsPrimary = 0 WHERE '.$table_info['ForeignKey'].' = '.$table_info['ParentId']);
+ if ( $object->GetDBField('IsPrimary') == 1 ) {
+ $sql = 'UPDATE ' . $object->TableName . '
+ SET IsPrimary = 0
+ WHERE ' . $table_info['ForeignKey'] . ' = ' . $table_info['ParentId'];
+ $this->Conn->Query($sql);
}
else {
- $prices_qty = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$object->TableName.' WHERE '.$table_info['ForeignKey'].' = '.$table_info['ParentId']);
+ $sql = 'SELECT COUNT(*)
+ FROM ' . $object->TableName . '
+ WHERE ' . $table_info['ForeignKey'] . ' = ' . $table_info['ParentId'];
+ $prices_qty = $this->Conn->GetOne($sql);
- if ($prices_qty == 0) {
+ if ( $prices_qty == 0 ) {
$object->SetDBField('IsPrimary', 1);
}
}
}
/**
- * Enter description here...
+ * Apply any custom changes to list's sql query
*
* @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
*/
- function SetCustomQuery(&$event)
+ protected function SetCustomQuery(&$event)
{
$object =& $event->getObject();
if ($this->Application->isAdminUser) {
return ;
}
if ( $this->Application->ConfigValue('Comm_PriceBracketCalculation') == 1 ) {
$sql = 'SELECT PrimaryGroupId
FROM ' . TABLE_PREFIX . 'PortalUser
WHERE PortalUserId = ' . $this->Application->GetVar('u_id');
$pricing_group = $this->Conn->GetOne($sql);
if ($pricing_group) {
$sql = 'SELECT COUNT(*)
FROM ' . TABLE_PREFIX . 'ProductsPricing
WHERE ProductId = ' . $this->Application->GetVar('p_id') . ' AND GroupId = ' . $pricing_group . ' AND Price IS NOT NULL';
$pricing_for_group_exists = $this->Conn->GetOne($sql);
}
if ( !$pricing_group || !$pricing_for_group_exists ) {
$pricing_group = $this->Application->ConfigValue('User_LoggedInGroup');
}
}
else {
$user_groups = $this->Application->RecallVar('UserGroups');
//$cheapest_group = $this->Conn->GetOne('SELECT GroupId FROM '.$object->TableName.' WHERE ProductId='.$this->Application->GetVar('p_id').' AND Price IS NOT NULL AND GroupId IN ('.$user_groups.') AND MinQty = 1 GROUP BY GroupId ORDER BY Price ASC');
$sql = 'SELECT PriceId, Price, GroupId
FROM ' . $object->TableName . '
WHERE ProductId = ' . $this->Application->GetVar('p_id') . ' AND Price IS NOT NULL AND GroupId IN (' . $user_groups . ')
ORDER BY GroupId ASC, MinQty ASC';
$effective_brackets = $this->Conn->Query($sql, 'PriceId');
$group_prices = array();
$min_price = -1;
$cheapest_group = 0;
foreach ($effective_brackets as $bracket) {
if (!isset($group_prices[$bracket['GroupId']])) {
$group_prices[$bracket['GroupId']] = $bracket['Price'];
if ($bracket['Price'] < $min_price || $min_price == -1) {
$min_price = $bracket['Price'];
$cheapest_group = $bracket['GroupId'];
}
}
}
if (!$cheapest_group) {
$cheapest_group = $this->Application->ConfigValue('User_LoggedInGroup');
}
$pricing_group = $cheapest_group;
}
$object->addFilter('price_user_group', $object->TableName.'.GroupId='.$pricing_group);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/brackets/brackets_event_handler.php
===================================================================
--- branches/5.2.x/units/brackets/brackets_event_handler.php (revision 14624)
+++ branches/5.2.x/units/brackets/brackets_event_handler.php (revision 14625)
@@ -1,206 +1,234 @@
<?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 standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnMoreBrackets' => Array('subitem' => 'add|edit'),
'OnInfinity' => Array('subitem' => 'add|edit'),
'OnArrange' => Array('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
- function prepareObject(&$object, &$event)
+ /**
+ * 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)
- {
+ 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');
- if($lang_object->GetDBField('UnitSystem') == 2 && $shipping_object->GetDBField('Type') == 1)
- {
- $fields = Array('Start', 'End');
$formatter =& $this->Application->recallObject('kUnitFormatter');
- foreach($fields as $field)
- {
+ /* @var $formatter kUnitFormatter */
+
+ foreach ($fields as $field) {
+ $object->SetFieldOption($field, 'formatter', 'kUnitFormatter');
$options = $object->GetFieldOptions($field);
- $options['formatter'] = 'kUnitFormatter';
- $object->SetFieldOptions($field, $options);
+
$formatter->prepareOptions($field, $options, $object);
}
}
}
function prepareBrackets(&$event)
{
$lang_object =& $this->Application->recallObject('lang.current');
$shipping_object =& $this->Application->recallObject('s');
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'] === '')
{
$item_info[$id]['Start'] = '';
}
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;')
{
$item_info[$id]['End'] = '&#8734;';
}
elseif($item_info[$id]['End_a'] === '' && $item_info[$id]['End_b'] === '')
{
$item_info[$id]['End'] = '';
}
else
{
$item_info[$id]['End'] = kUtil::Pounds2Kg($item_info[$id]['End_a'], $item_info[$id]['End_b']);
}
}
$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);
$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->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;
$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');
}
- function OnBeforeItemUpdate(&$event)
+ /**
+ * 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');
- $brackets_helper->InitHelper('Start', 'End', Array(), $default_start );
+ /* @var $brackets_helper kBracketsHelper */
+
+ $brackets_helper->InitHelper('Start', 'End', Array (), $default_start);
$brackets_helper->replaceInfinity($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveBrackets(&$event)
{
$lang_object =& $this->Application->recallObject('lang.current');
$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)
{
$item_info[$id]['End_a'] = -1 / kUtil::POUND_TO_KG;
$item_info[$id]['End_b'] = 0;
}
}
$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->OnPreSaveBrackets($event);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/files/files.php
===================================================================
--- branches/5.2.x/units/files/files.php (revision 14624)
+++ branches/5.2.x/units/files/files.php (revision 14625)
@@ -1,29 +1,37 @@
<?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!');
+defined('FULL_PATH') or die('restricted access!');
- class FilesItem extends kDBItem {
+class FilesItem extends kDBItem {
- public function Delete($id = null)
- {
- $this->Load($id);
- $upload_dir = $this->Fields['FilePath']['upload_dir'];
- $file_path = FULL_PATH.$upload_dir.$this->GetDBField('FilePath');
- if(file_exists($file_path))
- {
- unlink($file_path);
- }
- return parent::Delete($id);
+ /**
+ * Deletes the record from database
+ *
+ * @param int $id
+ * @return bool
+ * @access public
+ */
+ public function Delete($id = null)
+ {
+ $this->Load($id);
+ $upload_dir = $this->Fields['FilePath']['upload_dir'];
+ $file_path = FULL_PATH . $upload_dir . $this->GetDBField('FilePath');
+
+ if ( file_exists($file_path) ) {
+ unlink($file_path);
}
- }
\ No newline at end of file
+
+ return parent::Delete($id);
+ }
+}
\ No newline at end of file
Index: branches/5.2.x/units/affiliate_payments/affiliate_payments_event_handler.php
===================================================================
--- branches/5.2.x/units/affiliate_payments/affiliate_payments_event_handler.php (revision 14624)
+++ branches/5.2.x/units/affiliate_payments/affiliate_payments_event_handler.php (revision 14625)
@@ -1,118 +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 AffiliatePaymentsEventHandler extends kDBEventHandler {
/**
- * Enter description here...
+ * Apply some special processing to object being
+ * recalled before using it in other events that
+ * call prepareObject
*
- * @param kDBItem $object
+ * @param kDBItem|kDBList $object
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function prepareObject(&$object, &$event)
+ protected function prepareObject(&$object, &$event)
{
- if($event->Special == 'log') return false;
+ if ( $event->Special == 'log' ) {
+ return ;
+ }
$parent_info = $object->getLinkedInfo();
+
$parent_object =& $this->Application->recallObject($parent_info['ParentPrefix']);
+ /* @var $parent_object kDBItem */
+
$options = $object->getFieldOptions('PaymentTypeId');
- if($parent_object->isLoaded())
- {
+ if ( $parent_object->isLoaded() ) {
$options['default'] = $parent_object->GetDBField('PaymentTypeId');
$object->SetDBField('PaymentTypeId', $parent_object->GetDBField('PaymentTypeId'));
}
- if($this->Application->GetVar($event->getPrefixSpecial().'_event') != 'OnNew' && $this->Application->GetVar($event->getPrefixSpecial().'_event') != 'OnCreate')
- {
+ if ( $this->Application->GetVar($event->getPrefixSpecial() . '_event') != 'OnNew' && $this->Application->GetVar($event->getPrefixSpecial() . '_event') != 'OnCreate' ) {
$options['options'][0] = '';
}
$object->setFieldOptions('PaymentTypeId', $options);
}
/**
* Set's fields based on affiliate currently beeing edited
*
* @param kEvent $event
*/
function OnNew(&$event)
{
parent::OnNew($event);
$affiliate =& $this->Application->recallObject('affil');
$object =& $event->getObject( Array('skip_autoload'=>true) );
$object->SetDBField('Amount', $affiliate->GetDBField('AmountToPay') );
$object->SetDBField('AffiliateId', $affiliate->GetID() );
}
/**
- * Set's day of payment for newly created payments
+ * Updates Affiliate Record On Successfully payment creation
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemCreate(&$event)
+ protected function OnAfterItemCreate(&$event)
{
- $object =& $event->getObject( Array('skip_autoload'=>true) );
- }
+ parent::OnAfterItemCreate($event);
+
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
- /**
- * Updates Affiliate Record On Successfuly payment creation
- *
- * @param kEvent $event
- */
- function OnAfterItemCreate(&$event)
- {
- $object =& $event->getObject( Array('skip_autoload' => true) );
$parent_info = $object->getLinkedInfo();
- $sql = 'SELECT MAX(PaymentDate) FROM '.$object->TableName.'
- WHERE '.$parent_info['ParentTableKey'].' = '.$parent_info['ParentId'];
- $payment_date = $this->Conn->GetOne($sql);
- $amount_payed = $object->GetDBField('Amount');
+ $sql = 'SELECT MAX(PaymentDate)
+ FROM ' . $object->TableName . '
+ WHERE ' . $parent_info['ParentTableKey'] . ' = ' . $parent_info['ParentId'];
+ $payment_date = $this->Conn->GetOne($sql);
$affiliate =& $this->Application->recallObject('affil');
- $affiliate->SetDBField( 'AmountToPay', $affiliate->GetDBField('AmountToPay') - $amount_payed );
+ /* @var $affiliate kDBItem */
+
+ $affiliate->SetDBField('AmountToPay', $affiliate->GetDBField('AmountToPay') - $object->GetDBField('Amount'));
$affiliate->SetDBField('LastPaymentDate_date', $payment_date);
$affiliate->SetDBField('LastPaymentDate_time', $payment_date);
$affiliate->Update();
}
- function SetCustomQuery(&$event)
+ /**
+ * Apply any custom changes to list's sql query
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
+ */
+ protected function SetCustomQuery(&$event)
{
$object =& $event->getObject();
if($event->Special == 'log')
{
$object->removeFilter('parent_filter');
}
$types = $event->getEventParam('types');
if ($types=='my_payments')
{
$user_id = $this->Application->RecallVar('user_id');
$object->removeFilter('parent_filter');
$object->addFilter('my_payments', 'au.PortalUserId = '.$user_id);
}
if ($types=='myvisitororders')
{
$user_id = $this->Application->RecallVar('user_id');
$object->addFilter('myitems_orders','ord.OrderId IS NOT NULL');
$object->addFilter('myitems_user1','au.PortalUserId = '.$user_id);
$object->addFilter('myitems_user2','au.PortalUserId > 0');
}
}
}
\ 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 14624)
+++ branches/5.2.x/units/destinations/dst_event_handler.php (revision 14625)
@@ -1,113 +1,121 @@
<?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) );
$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);
}
}
}
}
- function customProcessing(&$event, $type)
+ /**
+ * 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/affiliate_payment_types/affiliate_payment_types_event_handler.php
===================================================================
--- branches/5.2.x/units/affiliate_payment_types/affiliate_payment_types_event_handler.php (revision 14624)
+++ branches/5.2.x/units/affiliate_payment_types/affiliate_payment_types_event_handler.php (revision 14625)
@@ -1,88 +1,120 @@
<?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 AffiliatePaymentTypesEventHandler extends kDBEventHandler {
- function SetCustomQuery(&$event)
+ /**
+ * Lists only active affiliate payment types on Front-End
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
+ */
+ protected function SetCustomQuery(&$event)
{
- if($event->Special == 'active')
- {
+ if ( !$this->Application->isAdmin ) {
$object =& $event->getObject();
- $object->addFilter('active', '%1$s.Status = 1');
+ /* @var $object kDBList */
+
+ $object->addFilter('active', '%1$s.Status = ' . STATUS_ACTIVE);
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
$object =& $event->getObject();
$object->SetDBField('IsPrimary', 1);
$object->Update();
}
/**
- * Enter description here...
+ * Ensures, that user have only one "use as billing" / "use as shipping" address
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemUpdate(&$event)
+ {
+ parent::OnBeforeItemUpdate($event);
+
+ $this->itemChanged($event);
+ }
+
+ /**
+ * Occurs before creating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemCreate(&$event)
+ {
+ parent::OnBeforeItemCreate($event);
+
+ $this->itemChanged($event);
+ }
+
+ /**
+ * Occurs before item is changed
*
* @param kEvent $event
*/
- function OnBeforeItemUpdate(&$event)
+ function itemChanged(&$event)
{
$object =& $event->getObject();
+ /* @var $object kDBItem */
- if ($object->GetDBField('IsPrimary') && $object->Validate()) {
- $table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
- $sql = 'UPDATE '.$table_name.' SET IsPrimary = 0';
+ if ( $object->GetDBField('IsPrimary') && $object->Validate() ) {
+ $sql = 'UPDATE ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
+ SET IsPrimary = 0';
$this->Conn->Query($sql);
- $status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );
+ $status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') );
$object->SetDBField($status_field, 1);
}
}
- function OnBeforeItemCreate(&$event)
+ /**
+ * Don't allow to delete primary affiliate payment type
+ *
+ * @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
+ */
+ protected function customProcessing(&$event, $type)
{
- $this->OnBeforeItemUpdate($event);
- }
+ if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
+ $ids = $event->getEventParam('ids');
- function OnMassDelete(&$event)
- {
- if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
- $event->status = kEvent::erFAIL;
- return;
- }
+ $sql = 'SELECT ' . $this->Application->getUnitOption($event->Prefix, 'IDField') . '
+ FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
+ WHERE IsPrimary = 1';
+ $primary_id = $this->Conn->GetOne($sql);
+
+ $ids = array_diff($ids, Array ($primary_id));
- $this->StoreSelectedIDs($event);
- $event->setEventParam('ids', $this->getSelectedIDs($event) );
- $ids = $event->getEventParam('ids');
-
- $temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
-
- $sql = 'SELECT AffiliatePlanId FROM '.$this->Application->getUnitOption('ap', 'TableName').'
- WHERE IsPrimary = 1';
- $primary_id = $this->Conn->GetOne($sql);
- $ids = array_diff($ids, Array($primary_id));
-
- if($ids)
- {
- $temp->DeleteItems($event->Prefix, $event->Special, $ids);
+ $event->setEventParam('ids', $ids);
}
- $this->clearSelectedIDs($event);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/shipping_quote_engines/shipping_quote_engine_event_handler.php
===================================================================
--- branches/5.2.x/units/shipping_quote_engines/shipping_quote_engine_event_handler.php (revision 14624)
+++ branches/5.2.x/units/shipping_quote_engines/shipping_quote_engine_event_handler.php (revision 14625)
@@ -1,148 +1,154 @@
<?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...
+ * Occurs before updating item
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemUpdate(&$event)
+ protected function OnBeforeItemUpdate(&$event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
- $engine =& $this->Application->recallObject( $object->GetDBField('ClassName') );
+ $engine =& $this->Application->recallObject($object->GetDBField('ClassName'));
/* @var $engine ShippingQuoteEngine */
$engine_fields = $engine->GetEngineFields();
$properties = $object->GetDBField('Properties');
$properties = $properties ? unserialize($properties) : Array ();
// common fields for all shipping quote engines
- if ($object->GetDBField('AccountPassword') != '') {
+ if ( $object->GetDBField('AccountPassword') != '' ) {
// don't erase password by accident
$engine_fields[] = 'AccountPassword';
}
// save shipping quote specific fields
foreach ($engine_fields as $engine_field) {
$properties[$engine_field] = $object->GetDBField($engine_field);
}
$object->SetDBField('Properties', serialize($properties));
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$from_country = $this->Application->ConfigValue('Comm_Shipping_Country');
$has_states = strlen($from_country) == 3 ? $cs_helper->CountryHasStates($from_country) : false;
- $valid_address = $from_country && ($has_states && $this->Application->ConfigValue('Comm_Shipping_State') || !$has_states) &&
- $this->Application->ConfigValue('Comm_Shipping_City') && $this->Application->ConfigValue('Comm_Shipping_ZIP');
+ $valid_address = $from_country && ($has_states && $this->Application->ConfigValue('Comm_Shipping_State') || !$has_states) && $this->Application->ConfigValue('Comm_Shipping_City') && $this->Application->ConfigValue('Comm_Shipping_ZIP');
- if (!function_exists('curl_init')) {
+ if ( !function_exists('curl_init') ) {
$object->SetError('Status', 'curl_not_present');
}
- elseif (($object->GetDBField('Status') == STATUS_ACTIVE) && !$valid_address) {
+ elseif ( ($object->GetDBField('Status') == STATUS_ACTIVE) && !$valid_address ) {
$object->SetError('Status', 'from_info_not_filled_in');
}
}
/**
- * Enter description here...
+ * Apply same processing to each item being selected in grid
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function iterateItems(&$event)
+ protected function iterateItems(&$event)
{
-// $event->setEventParam('SkipProcessing', 1);
parent::iterateItems($event);
- if($event->Name == 'OnMassApprove')
- {
+
+ if ( $event->Name == 'OnMassApprove' ) {
$event->status = kEvent::erSUCCESS;
$event->redirect = true;
}
}
/**
* Sets virtual fields from serialized properties array
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnAfterItemLoad(&$event)
+ protected function OnAfterItemLoad(&$event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$properties = $object->GetDBField('Properties');
- if ($properties) {
- $object->SetDBFieldsFromHash( unserialize($properties) );
+ if ( $properties ) {
+ $object->SetDBFieldsFromHash(unserialize($properties));
}
}
/**
* Deletes cached shipping quotes on any setting change
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnAfterItemCreate(&$event)
+ protected function OnAfterItemCreate(&$event)
{
parent::OnAfterItemCreate($event);
$this->_deleteQuoteCache();
}
/**
* Deletes cached shipping quotes on any setting change
*
* @param kEvent $event
*/
function OnAfterItemUpdate(&$event)
{
parent::OnAfterItemUpdate($event);
$this->_deleteQuoteCache();
}
/**
* Deletes cached shipping quotes on any setting change
*
* @param kEvent $event
*/
function OnAfterItemDelete(&$event)
{
parent::OnAfterItemDelete($event);
$this->_deleteQuoteCache();
}
/**
* Deletes cached shipping quotes
*
*/
function _deleteQuoteCache()
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName LIKE "ShippingQuotes%"';
$this->Conn->Query($sql);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/product_option_combinations/product_option_combinations_event_handler.php
===================================================================
--- branches/5.2.x/units/product_option_combinations/product_option_combinations_event_handler.php (revision 14624)
+++ branches/5.2.x/units/product_option_combinations/product_option_combinations_event_handler.php (revision 14625)
@@ -1,382 +1,408 @@
<?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 ProductOptionCombinationsEventHandler extends kDBEventHandler {
/**
* Apply custom processing to item
*
* @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
*/
- function customProcessing(&$event, $type)
+ protected function customProcessing(&$event, $type)
{
if ($type == 'after') {
return true;
}
switch ($event->Name) {
case 'OnCreate':
case 'OnUpdate':
$object =& $event->getObject();
$options = unserialize($object->GetDBField('Combination'));
ksort($options);
$object->SetDBField('CombinationCRC', crc32(serialize($options)));
break;
case 'OnMassDelete':
// delete only option combinations that has no assiciated inventory
$object =& $event->getObject();
$ids = $event->getEventParam('ids');
$sql = 'SELECT '.$object->IDField.'
FROM '.$object->TableName.'
WHERE ('.$object->IDField.' IN ('.implode(',', $ids).')) AND
(QtyInStock = 0) AND (QtyReserved = 0) AND (QtyBackOrdered = 0) AND (QtyOnOrder = 0)';
$event->setEventParam('ids', $this->Conn->GetCol($sql));
break;
}
}
/**
* GetOptionValues
*
* @param kEvent $event
*/
function GetOptionValues(&$event, $option_id)
{
$object =& $event->getObject();
if ($object->IsTempTable()) {
$table = $this->Application->GetTempName(TABLE_PREFIX.'ProductOptions', 'prefix:'.$event->Prefix);
}
else {
$table = TABLE_PREFIX.'ProductOptions';
}
$query = 'SELECT `Values` FROM '.$table.' WHERE ProductOptionId = '.$option_id;
return explode(',', $this->Conn->GetOne($query));
}
function CreateCombinations(&$event, $fields, $current_option=null)
{
$recursed = false;
$combination = $fields['Combination'];
foreach ($combination as $option_id => $option)
{
if ($option_id == $current_option || $recursed) continue;
if ($option == '_ANY_') {
$recursed = true;
$values = $this->GetOptionValues($event, $option_id);
foreach ($values as $a_value) {
$fields['Combination'][$option_id] = $a_value;
$this->CreateCombinations($event, $fields, $option_id);
}
}
}
if (!$recursed) {
$object =& $event->getObject();
/* @var $object kDBItem */
$salt = $fields['Combination'];
ksort($salt);
$object->Load(crc32(serialize($salt)), 'CombinationCRC');
$object->SetFieldsFromHash($fields);
$this->customProcessing($event,'before');
if ( $object->isLoaded() ) { // Update if such combination already exists
if( $object->Update() )
{
$this->customProcessing($event,'after');
$event->status=kEvent::erSUCCESS;
}
}
else {
if( $object->Create($event->getEventParam('ForceCreateId')) )
{
$this->customProcessing($event,'after');
$event->status=kEvent::erSUCCESS;
}
}
}
}
function UpdateCombinations(&$event, $fields, $current_option=null)
{
$recursed = false;
$combination = $fields['Combination'];
foreach ($combination as $option_id => $option)
{
if ($option_id == $current_option || $recursed) continue;
if ($option == '_ANY_') {
$recursed = true;
$values = $this->GetOptionValues($event, $option_id);
foreach ($values as $a_value) {
$fields['Combination'][$option_id] = $a_value;
$this->UpdateCombinations($event, $fields, $option_id);
}
}
}
if (!$recursed) {
$object =& $event->getObject();
/* @var $object kDBItem */
$edit_id = $object->GetId();
$salt = $fields['Combination'];
ksort($salt);
// try to load combination by salt - if loaded, it will update the combination
$object->Load(crc32(serialize($salt)), 'CombinationCRC');
if ( !$object->isLoaded() ) {
$object->Load($edit_id);
}
$object->SetFieldsFromHash($fields);
$this->customProcessing($event,'before');
if( $object->Update() )
{
$this->customProcessing($event,'after');
$event->status=kEvent::erSUCCESS;
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCreate(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id,$field_values) = each($items_info);
$object->SetFieldsFromHash($field_values);
if (!$object->Validate()) {
$event->status = kEvent::erFAIL;
$event->redirect = false;
$this->Application->SetVar($event->getPrefixSpecial().'_SaveEvent','OnCreate');
$object->setID($id);
return;
}
$this->CreateCombinations($event, $field_values);
}
}
function OnUpdate(&$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->SetFieldsFromHash($field_values);
if (!$object->Validate()) {
$event->status = kEvent::erFAIL;
$event->redirect = false;
return;
}
$this->UpdateCombinations($event, $field_values);
/*$this->customProcessing($event, 'before');
if( $object->Update($id) )
{
$this->customProcessing($event, 'after');
$event->status=kEvent::erSUCCESS;
}
else
{
$event->status=kEvent::erFAIL;
$event->redirect=false;
break;
}*/
}
}
$this->Application->SetVar($event->GetPrefixSpecial().'_id', '');
}
/**
* Builds item (loads if needed)
*
* @param kEvent $event
* @access protected
*/
function OnItemBuild(&$event)
{
$object =& $event->getObject();
$this->dbBuild($object,$event);
$sql = $this->ItemPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
// 2. loads if allowed
$auto_load = $this->Application->getUnitOption($event->Prefix,'AutoLoad');
$skip_autload = $event->getEventParam('skip_autoload');
if($auto_load && !$skip_autload) $this->LoadItem($event);
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->getPrefixSpecial().'_GoTab', '');
$actions->Set($event->getPrefixSpecial().'_GoId', '');
}
- function LoadItem(&$event)
+ /**
+ * Load item if id is available
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function LoadItem(&$event)
{
$object =& $event->getObject();
+ /* @var $object kDBItem */
+
$id = $this->getPassedID($event);
- if (!$id) {
+
+ if ( !$id ) {
$event->CallSubEvent('OnNew');
+
+ return ;
}
- else {
- if ($object->Load($id) )
- {
- $actions =& $this->Application->recallObject('kActions');
- $actions->Set($event->getPrefixSpecial().'_id', $object->GetId() );
- }
- else
- {
- //$object->setID($id);
- }
+
+ if ( $object->Load($id) ) {
+ $actions =& $this->Application->recallObject('kActions');
+ /* @var $actions Params */
+
+ $actions->Set($event->getPrefixSpecial() . '_id', $object->GetId());
}
}
/**
* Get's special of main item for linking with subitem
*
* @param kEvent $event
* @return string
*/
function getMainSpecial(&$event)
{
$special = $event->getEventParam('main_special');
if($special === false || $special == '$main_special')
{
$special = $event->Special;
}
if ($special == 'grid') {
$special = '';
}
return $special;
}
- function OnBeforeClone(&$event)
+ /**
+ * Occurs before an item has been cloned
+ * Id of newly created item is passed as event' 'id' param
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeClone(&$event)
{
+ parent::OnBeforeClone($event);
+
$event->Init($event->Prefix, '-item');
$object =& $event->getObject();
$options_mapping = $this->Application->GetVar('poc_mapping');
if (!$options_mapping) return;
foreach ($options_mapping as $original => $new)
{
$comb_data = unserialize($object->GetDBField('Combination'));
$n_combs = array();
foreach ($comb_data as $key => $val)
{
$n_key = $key == $original ? $new : $key;
$n_combs[$n_key] = $val;
}
ksort($n_combs);
$n_combs = serialize($n_combs);
$n_crc = crc32($n_combs);
$object->SetDBField('Combination', $n_combs);
$object->SetDBField('CombinationCRC', $n_crc);
}
}
/**
* Restore back values from live table to temp table before overwriting live with temp
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeDeleteFromLive(&$event)
+ protected function OnBeforeDeleteFromLive(&$event)
{
+ parent::OnBeforeDeleteFromLive($event);
+
// check if product inventory management is via options and then proceed
$id = $event->getEventParam('id');
$products_table = $this->Application->getUnitOption('p', 'TableName');
$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$sql = 'SELECT p.InventoryStatus
- FROM '.$products_table.' p
- LEFT JOIN '.$table_name.' poc ON poc.ProductId = p.ProductId
- WHERE poc.'.$id_field.' = '.$id;
+ FROM ' . $products_table . ' p
+ LEFT JOIN ' . $table_name . ' poc ON poc.ProductId = p.ProductId
+ WHERE poc.' . $id_field . ' = ' . $id;
+ $inventory_status = $this->Conn->GetOne($sql);
- if ($this->Conn->GetOne($sql) == 2) {
- $live_object =& $this->Application->recallObject($event->Prefix.'.itemlive', null, Array('skip_autoload' => true));
+ if ( $inventory_status == ProductInventory::BY_OPTIONS ) {
+ $live_object =& $this->Application->recallObject($event->Prefix . '.itemlive', null, Array ('skip_autoload' => true));
/* @var $live_object kDBItem */
$live_object->SwitchToLive();
$live_object->Load($id);
- $temp_object =& $this->Application->recallObject($event->Prefix.'.itemtemp', null, Array('skip_autoload' => true));
+ $temp_object =& $this->Application->recallObject($event->Prefix . '.itemtemp', null, Array ('skip_autoload' => true));
/* @var $temp_object kDBItem */
$temp_object->SwitchToTemp();
$temp_object->Load($id);
- $temp_object->SetDBFieldsFromHash($live_object->GetFieldValues(), Array('QtyInStock','QtyReserved','QtyBackOrdered','QtyOnOrder'));
+ $temp_object->SetDBFieldsFromHash($live_object->GetFieldValues(), Array ('QtyInStock', 'QtyReserved', 'QtyBackOrdered', 'QtyOnOrder'));
$temp_object->Update();
}
}
/**
* Create search filters based on search query
*
* @param kEvent $event
* @access protected
*/
function OnSearch(&$event)
{
parent::OnSearch($event);
$this->_saveProduct($event);
}
/**
* Clear search keywords
*
* @param kEvent $event
* @access protected
*/
function OnSearchReset(&$event)
{
parent::OnSearchReset($event);
$this->_saveProduct($event);
}
/**
* Makes event remember product id (if passed)
*
* @param kEvent $event
*/
function _saveProduct(&$event)
{
$product_id = $this->Application->GetVar('p_id');
if ($product_id) {
$event->SetRedirectParam('p_id', $product_id);
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/product_option_combinations/product_option_formatters.php
===================================================================
--- branches/5.2.x/units/product_option_combinations/product_option_formatters.php (revision 14624)
+++ branches/5.2.x/units/product_option_combinations/product_option_formatters.php (revision 14625)
@@ -1,134 +1,143 @@
<?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 kCombinationFormatter extends kFormatter {
+ /**
+ * Formats value of a given field
+ *
+ * @param string $value
+ * @param string $field_name
+ * @param kDBItem|kDBList $object
+ * @param string $format
+ * @return string
+ */
function Format($value, $field_name, $object, $format=null)
{
$o = '';
$options = $object->GetFieldOptions($field_name);
if ( isset($format) ) $options['format'] = $format;
$data = unserialize($value);
$opt_helper =& $this->Application->recallObject('kProductOptionsHelper');
$top_prefix = $this->Application->GetTopmostPrefix($object->Prefix);
$use_temp = substr($this->Application->GetVar($top_prefix.'_mode'), 0, 1) == 't';
foreach ($data as $key=>$val) {
$conv_key = $opt_helper->ConvertKey($key, $object->GetDBField('ProductId'),$use_temp);
if (is_array($val)) {
$val = join(',', $val);
}
$o .= sprintf($options['format'], $conv_key['Name'], $val);
}
return $o;
}
/**
* Performs basic type validation on form field value
*
* @param mixed $value
* @param string $field_name
* @param kDBItem $object
* @return mixed
+ * @access public
*/
- function Parse($value, $field_name, &$object)
+ public function Parse($value, $field_name, &$object)
{
- if (!is_array($value)) {
+ if ( !is_array($value) ) {
$object->SetError($field_name, 'required');
return '';
}
else {
if ( $object->isRequired($field_name) ) {
- foreach ($value as $key=>$val)
- {
- if ($val == '') {
+ foreach ($value as $key => $val) {
+ if ( $val == '' ) {
$object->SetError($field_name, 'required');
}
}
}
}
return serialize($value);
}
}
class kCombPriceFormatter extends kFormatter {
/**
- * Enter description here...
+ * Formats value of a given field
*
- * @param mixed $value
+ * @param string $value
* @param string $field_name
- * @param kDBItem $object
+ * @param kDBItem|kDBList $object
* @param string $format
* @return string
*/
function Format($value, $field_name, $object, $format=null)
{
$options = $object->GetFieldOptions($field_name);
$converted = array_key_exists('converted', $options) ? $options['converted'] : false;
if ($converted) {
$lang =& $this->Application->recallObject('lang.current');
return $lang->formatNumber($object->GetDBField($field_name), 2);
}
$data = unserialize($object->GetDBField('Combination'));
$opt_helper =& $this->Application->recallObject('kProductOptionsHelper');
$price = $object->GetDBField('BasePrice');
$addition = 0;
$top_prefix = $this->Application->GetTopmostPrefix($object->Prefix);
$use_temp = substr($this->Application->GetVar($top_prefix.'_mode'), 0, 1) == 't';
foreach ($data as $key=>$val) {
$conv_key = $opt_helper->ConvertKey($key, $object->GetDBField('ProductId'), $use_temp);
$parsed = $opt_helper->ExplodeOptionValues($conv_key);
if (!$parsed) continue;
$conv_prices = $parsed['Prices'];
$conv_price_types = $parsed['PriceTypes'];
if ($conv_price_types[$val] == '$')
{
$addition += $conv_prices[$val];
}
elseif ($conv_price_types[$val] == '%')
{
$addition += $price * $conv_prices[$val] / 100;
}
}
$price += $addition;
$price_type = $object->GetDBField('PriceType');
$price_mod = $object->GetDBField('Price');
switch ($price_type) {
case 1: // = override
$price = $price_mod;
break;
case 2: // flat
$price = $price + $price_mod;
break;
case 3: // percent
$price = $price * (1 + $price_mod / 100);
break;
}
return $price;
}
}
\ No newline at end of file
Index: branches/5.2.x/units/payment_type/payment_type_event_handler.php
===================================================================
--- branches/5.2.x/units/payment_type/payment_type_event_handler.php (revision 14624)
+++ branches/5.2.x/units/payment_type/payment_type_event_handler.php (revision 14625)
@@ -1,255 +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 PaymentTypeEventHandler extends kDBEventHandler
{
function mapEvents()
{
parent::mapEvents();
$common_events = Array (
'OnMassApprove'=>'iterateItems',
'OnMassDecline'=>'OnMassDecline',
'OnMassMoveUp'=>'iterateItems',
'OnMassMoveDown'=>'iterateItems',
);
$this->eventMethods = array_merge($this->eventMethods, $common_events);
}
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnItemBuild' => Array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Set's new category as primary for product
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$this->StoreSelectedIDs($event);
$ids=$this->getSelectedIDs($event);
if($ids)
{
$id = array_shift($ids);
$table_info = $object->getLinkedInfo();
$this->Conn->Query('UPDATE '.$object->TableName.' SET IsPrimary = 0 ');
$this->Conn->Query('UPDATE '.$object->TableName.' SET IsPrimary = 1, Status = 1 WHERE PaymentTypeId = '.$id.' ');
}
$event->setRedirectParams(Array('opener' => 's'), true);
}
function OnMassDecline(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$this->StoreSelectedIDs($event);
$ids=$this->getSelectedIDs($event);
if($ids)
{
$status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );
foreach($ids as $id)
{
$object->Load($id);
if (!$object->GetDBField("IsPrimary")){
$object->SetDBField($status_field, 0);
}
if( $object->Update() )
{
$event->status = kEvent::erSUCCESS;
$event->setRedirectParams(Array('opener' => 's'), true);
}
else
{
$event->status = kEvent::erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
- * Occurse before updating item
+ * Occurs before updating item
*
* @param kEvent $event
- * @access public
+ * @return void
+ * @access protected
*/
- function OnBeforeItemUpdate(&$event)
+ protected function OnBeforeItemUpdate(&$event)
{
parent::OnBeforeItemUpdate($event);
- $object = &$event->getObject();
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
- $status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );
+ $status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') );
- if($object->GetDBField('IsPrimary')==1 && $object->GetDBField($status_field)==0){
+ if ( $object->GetDBField('IsPrimary') == 1 && $object->GetDBField($status_field) == 0 ) {
$object->SetDBField($status_field, 1);
}
$this->convertGroups($event);
}
/**
- * Occurse before creating item
+ * Occurs before creating item
*
* @param kEvent $event
- * @access public
+ * @return void
+ * @access protected
*/
- function OnBeforeItemCreate(&$event)
+ protected function OnBeforeItemCreate(&$event)
{
parent::OnBeforeItemCreate($event);
$this->convertGroups($event);
}
/**
* Disable delete on primary payment type
*
* @param kEvent $event
+ * @param string $type
+ * @return void
* @access protected
*/
-
- function customProcessing(&$event, $when){
- if ($event->Name == 'OnMassDelete' && $when == 'before'){
+ protected function customProcessing(&$event, $type)
+ {
+ if ($event->Name == 'OnMassDelete' && $type == 'before'){
$object = &$event->getObject();
$ids = $event->getEventParam('ids');
$ids_ok=array();
foreach ($ids as $key => $id){
$object->Load($id);
if ($object->GetDBField('IsPrimary')){
$this->Application->StoreVar('pt_delete_error', '1');
}else{
$ids_ok[]=$id;
}
}
$event->setEventParam('ids', $ids_ok);
}
}
- function OnSave(&$event)
+ /**
+ * Saves content of temp table into live and
+ * redirects to event' default redirect (normally grid template)
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnSave(&$event)
{
$this->Application->StoreVar('check_unused_currencies', 1);
+
parent::OnSave($event);
}
/**
* Sets default payment type group
*
* @param kEvent $event
*/
function OnAfterConfigRead(&$event)
{
parent::OnAfterConfigRead($event);
$default_group = $this->Application->ConfigValue('User_LoggedInGroup');
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$fields['PortalGroups']['default'] = ','.$default_group.',';
$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
}
/**
* Earlier version of group selector control needs such conversion (also used in shipping)
*
* @param kEvent $event
*/
function convertGroups(&$event)
{
$object =& $event->getObject();
$selected_groups = $object->GetDBField('PortalGroups');
if ($selected_groups) {
$selected_groups = str_replace('|', ',', $selected_groups);
$selected_groups = ','.trim($selected_groups, ',').',';
$object->SetDBField('PortalGroups', $selected_groups);
}
}
/**
* Returns ID of current item to be edited
* by checking ID passed in get/post as prefix_id
* or by looking at first from selected ids, stored.
* Returned id is also stored in Session in case
* it was explicitly passed as get/post
*
* @param kEvent $event
* @return int
*/
function getPassedID(&$event)
{
if ($event->Special == 'auto-ord') {
$main_object =& $this->Application->recallObject('ord');
/* @var $main_object kDBItem */
return $main_object->GetDBField('PaymentType');
}
return parent::getPassedID($event);
}
/**
- * Apply system filter to themes list
+ * Apply any custom changes to list's sql query
*
* @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
*/
- function SetCustomQuery(&$event)
+ protected function SetCustomQuery(&$event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
if (in_array($event->Special, Array ('enabled', 'selected', 'available')) || !$this->Application->isAdminUser) {
// "enabled" special or Front-End
$object->addFilter('enabled_filter', '%1$s.Status = ' . STATUS_ACTIVE);
}
// site domain payment type picker
if ($event->Special == 'selected' || $event->Special == 'available') {
$edit_picker_helper =& $this->Application->recallObject('EditPickerHelper');
/* @var $edit_picker_helper EditPickerHelper */
$edit_picker_helper->applyFilter($event, 'PaymentTypes');
}
// apply domain-based payment type filtering
$payment_types = $this->Application->siteDomainField('PaymentTypes');
if (strlen($payment_types)) {
$payment_types = explode('|', substr($payment_types, 1, -1));
$object->addFilter('domain_filter', '%1$s.PaymentTypeId IN (' . implode(',', $payment_types) . ')');
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/manufacturers/manufacturers_event_handler.php
===================================================================
--- branches/5.2.x/units/manufacturers/manufacturers_event_handler.php (revision 14624)
+++ branches/5.2.x/units/manufacturers/manufacturers_event_handler.php (revision 14625)
@@ -1,123 +1,130 @@
<?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...
+ * Apply any custom changes to list's sql query
*
* @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
*/
- function SetCustomQuery(&$event)
+ protected 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
+ * Pre-fills states dropdown with correct values
*
* @param kEvent $event
- * @access public
+ * @return void
+ * @access protected
*/
- function OnAfterItemLoad(&$event)
+ protected function OnAfterItemLoad(&$event)
{
parent::OnAfterItemLoad($event);
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$cs_helper->PopulateStates($event, 'State', 'Country');
}
/**
* Processes states
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemUpdate(&$event)
+ protected function OnBeforeItemUpdate(&$event)
{
parent::OnBeforeItemUpdate($event);
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$cs_helper->CheckStateField($event, 'State', 'Country');
$cs_helper->PopulateStates($event, 'State', 'Country');
}
/**
* Processes states
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemCreate(&$event)
+ protected function OnBeforeItemCreate(&$event)
{
parent::OnBeforeItemCreate($event);
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$cs_helper->CheckStateField($event, 'State', 'Country');
$cs_helper->PopulateStates($event, 'State', 'Country');
}
}
\ No newline at end of file
Index: branches/5.2.x/units/shipping/shipping_event_handler.php
===================================================================
--- branches/5.2.x/units/shipping/shipping_event_handler.php (revision 14624)
+++ branches/5.2.x/units/shipping/shipping_event_handler.php (revision 14625)
@@ -1,203 +1,239 @@
<?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 ShippingEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnFlip' => Array('self' => 'add|edit'),
'OnApplyModifier' => Array('self' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Presets shipping cost object based on shipping fields
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnAfterItemLoad(&$event)
+ protected function OnAfterItemLoad(&$event)
{
parent::OnAfterItemLoad($event);
- if (!$this->Application->isAdminUser) {
- return ;
+ if ( !$this->Application->isAdminUser ) {
+ return;
}
$object =& $event->getObject();
+ /* @var $object kDBItem */
- $format = '%01.'.$object->GetDBField('PrecisionAfterSep').'f'; // %01.2f
+ $format = '%01.' . $object->GetDBField('PrecisionAfterSep') . 'f'; // %01.2f
$zero_if_empty = $object->GetDBField('ZeroIfEmpty');
$sc_object =& $this->Application->recallObject('sc', null, Array ('raise_warnings' => 0));
/* @var $sc_object kDBItem */
// change default shipping cost values ("Costs" tab on shipping editing) based on field from "Shipping Type"
$flat_options = $sc_object->GetFieldOptions('Flat');
$flat_options['format'] = $format;
$flat_options['default'] = $zero_if_empty ? 0 : null;
$sc_object->SetFieldOptions('Flat', $flat_options);
- $perunit_options = $sc_object->GetFieldOptions('PerUnit');
- $perunit_options['format'] = $format;
- $perunit_options['default'] = $zero_if_empty ? 0 : null;
- $sc_object->SetFieldOptions('PerUnit', $perunit_options);
+ $per_unit_options = $sc_object->GetFieldOptions('PerUnit');
+ $per_unit_options['format'] = $format;
+ $per_unit_options['default'] = $zero_if_empty ? 0 : null;
+ $sc_object->SetFieldOptions('PerUnit', $per_unit_options);
}
/**
* Enter description here...
*
* @param kEvent $event
* @return unknown
*/
function OnApplyModifier(&$event)
{
// $event->CallSubEvent('');
$zones_object =& $this->Application->recallObject('z');
$cost_object =& $this->Application->recallObject('sc');
$object = $event->getObject();
$operation = $this->Application->GetVar('operation');
$formatter =& $this->Application->recallObject('kFormatter');
$modify_by = $formatter->TypeCast($this->Application->GetVar('modify_by'), array('type'=>'float'));
$cost_type = $object->GetDBField('CostType');
$brackets = $this->Application->GetVar('br');
$zones = $this->Application->GetVar('z');
$conditions = Array();
if( is_array($zones) ) {
$conditions['zones'] = 'ZoneID IN ('.implode( ',', array_keys($zones) ).')';
}
if( is_array($brackets) ) {
$conditions['brackets'] = 'BracketId IN ('.implode( ',', array_keys($brackets) ).')';
}
$conditions = implode(' OR ', $conditions);
if(!$conditions)
{
$this->finalizePopup($event);
return false;
}
$sql = 'SELECT ShippingCostId FROM '.$cost_object->TableName.' WHERE '.$conditions;
$res = $this->Conn->GetCol($sql);
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');
}
foreach($affected_fields as $field)
{
if($operation == '/' && $modify_by == 0) break;
$sql = 'UPDATE '.$cost_object->TableName.'
SET '.$field.'='.$field.$operation.$modify_by.'
WHERE ShippingCostId IN ('.implode(',', $res).')
AND NOT('.$field.' IS NULL)
AND '.$field.$operation.$modify_by.'>=0';
$this->Conn->Query($sql);
}
$this->finalizePopup($event);
}
function OnFlip(&$event)
{
$object =& $event->getObject();
$aligment = $this->Application->GetLinkedVar('CostsTableAligment');
$new_align = $aligment ? 0 : 1;
$this->Application->SetVar('CostsTableAligment', $new_align);
$this->Application->LinkVar('CostsTableAligment');
$this->OnPreSave($event);
$event->status=kEvent::erSUCCESS;
}
- function OnSave(&$event)
+ /**
+ * Saves content of temp table into live and
+ * redirects to event' default redirect (normally grid template)
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnSave(&$event)
{
$this->OnAfterItemLoad($event);
parent::OnSave($event);
}
- function OnAfterItemCreate(&$event)
+ /**
+ * Occurs after creating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnAfterItemCreate(&$event)
{
+ parent::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);
}
- function OnPreSaveCreated(&$event){
+ /**
+ * Creates a new item in temp table and
+ * stores item id in App vars and Session on success
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnPreSaveCreated(&$event)
+ {
parent::OnPreSaveCreated($event);
- $default_group = $this->Application->ConfigValue('User_LoggedInGroup');
+ $object =& $event->getObject( Array ('skip_autoload' => true) );
+ /* @var $object kDBItem */
- $object =& $event->getObject( Array('skip_autoload' => true) );
-
- $object->SetDBField('PortalGroups', ','.$default_group.',');
+ $object->SetDBField('PortalGroups', ',' . $this->Application->ConfigValue('User_LoggedInGroup') . ',');
}
function UpdateGroups(&$event){
$object = &$event->getObject();
if ($event->Name == 'OnPreSaveCreated') {
$default_group = $this->Application->ConfigValue('User_LoggedInGroup');
$selected_groups = $default_group;
}
else {
$selected_groups = $object->GetDBField('PortalGroups');
}
if ($selected_groups && $selected_groups!='') {
$selected_groups = str_replace('|', ',', $selected_groups);
$selected_groups = ','.trim($selected_groups, ',').',';
$object->SetDBField('PortalGroups', $selected_groups);
}
}
- function customProcessing(&$event, $when){
+ /**
+ * Apply custom processing to item
+ *
+ * @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
+ */
+ protected function customProcessing(&$event, $type)
+ {
$this->UpdateGroups($event);
-
}
}
\ No newline at end of file
Index: branches/5.2.x/units/taxes/taxes_event_handler.php
===================================================================
--- branches/5.2.x/units/taxes/taxes_event_handler.php (revision 14624)
+++ branches/5.2.x/units/taxes/taxes_event_handler.php (revision 14625)
@@ -1,253 +1,238 @@
<?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 TaxesEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnTypeChange' => Array('self' => 'add|edit'),
'OnCountryChange' => Array('self' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decine and so on events
$zones_events = Array( 'OnAddLocation' => 'DestinationAction',
'OnRemoveLocation' => 'DestinationAction',
'OnLoadZoneForm' => 'DestinationAction',
/*'OnCountryChange' => 'DestinationAction',*/
'OnNew' => 'DestinationAction');
$this->eventMethods = array_merge($this->eventMethods, $zones_events);
}
- function customProcessing(&$event, $type)
+ /**
+ * Apply custom processing to item
+ *
+ * @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
+ */
+ protected function customProcessing(&$event, $type)
{
- $zone_object =& $event->GetObject();
- switch($type)
- {
- case 'before':
+ $zone_object =& $event->getObject();
+ /* @var $zone_object kDBItem */
- break;
- case 'after':
- $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
- $dst_object =& $this->Application->RecallObject('taxdst');
- if ($event->Name == 'OnUpdate')
- {
- $sql = 'DELETE FROM '.$dst_object->TableName.' WHERE TaxZoneId='.$zone_object->GetID();
- $this->Conn->Query($sql);
- }
- else
- {
- $temp = $this->Application->GetVar('taxdst');
- foreach ($temp as $key => $value)
- {
- $temp[$key]['TaxZoneId'] = $zone_object->GetID();
- }
- $this->Application->SetVar('taxdst', $temp);
+ if ( $type == 'after' ) {
+ $dst_object =& $this->Application->recallObject('taxdst');
+ /* @var $dst_object kDBItem */
+
+ if ( $event->Name == 'OnUpdate' ) {
+ $sql = 'DELETE FROM ' . $dst_object->TableName . '
+ WHERE TaxZoneId = ' . $zone_object->GetID();
+ $this->Conn->Query($sql);
+ }
+ else {
+ $temp = $this->Application->GetVar('taxdst', Array ());
+
+ foreach ($temp as $key => $value) {
+ $temp[$key]['TaxZoneId'] = $zone_object->GetID();
}
- $dst_event = new kEvent();
- $dst_event->Init('taxdst');
- $dst_event->Name = 'OnCreate';
- $this->Application->HandleEvent($dst_event);
- break;
+ $this->Application->SetVar('taxdst', $temp);
+ }
- default:
+ $dst_event = new kEvent('taxdst:OnCreate');
+ $this->Application->HandleEvent($dst_event);
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnTypeChange(&$event)
{
$this->Application->DeleteVar('taxdst');
$event->CallSubEvent('OnPreSave');
$event->redirect = false;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function DestinationAction(&$event)
{
$event->redirect = false;
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $item_id => $field_values)
{
// this is to receive $item_id
}
}
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->Load($item_id);
$object->SetFieldsFromHash($field_values);
$object->SetDBField('TaxZoneID', $item_id);
$destination =& $this->Application->recallObject('taxdst');
$tax_object =& $this->Application->recallObject('tax');
switch($event->Name)
{
case 'OnAddLocation':
$temp = $this->Application->GetVar('taxdst');
$zip = $this->Application->GetVar('zip_input') ? $this->Application->GetVar('zip_input') : $this->Application->GetVar('zip_dropdown');
$exist=0;
switch ($object->GetDBField('Type'))
{
case 1:
$location_id = $this->Application->GetVar('country');
break;
case 2:
$location_id = $this->Application->GetVar('state');
break;
default:
$location_id = $this->Application->GetVar('StatesCountry');
foreach($temp as $temp_id => $temp_val){
if ($temp_val['DestValue']==$zip){
$exist=1;
break;
}
}
}
if ($exist == 0){
$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$destination->IDField.') FROM '.$destination->TableName);
if($new_id > 0) $new_id = 0;
do
{
$new_id--;
} while ($this->check_array($this->Application->GetVar('taxdst'), 'TaxZoneDestId', $new_id));
if( ($location_id && !$this->check_array($temp, 'StdDestId', $location_id)) ||
($zip && !$this->check_array($temp, 'DestValue', $zip)) )
{
if($tax_object->GetDBField('Type') == 3 && $zip ==''){
continue;
}
$temp[$new_id]['TaxZoneDestId'] = $new_id;
$temp[$new_id]['StdDestId'] = $location_id;
$temp[$new_id]['DestValue'] = $zip ? $zip : '';
$this->Application->SetVar('taxdst', $temp);
}
}
break;
case 'OnRemoveLocation':
$temp = $this->Application->GetVar('taxdst');
$selected_destinations = explode(',', $this->Application->GetVar('selected_destinations'));
foreach ($selected_destinations as $dest)
{
unset( $temp[$dest] );
if (strlen($dest)>0){
$sql = 'DELETE FROM '.$destination->TableName.' WHERE TaxZoneDestId ='.$dest;
$this->Conn->Query($sql);
}
}
$this->Application->SetVar('taxdst', $temp);
break;
case 'OnLoadZoneForm':
$sql = 'SELECT * FROM '.$destination->TableName.' WHERE TaxZoneId='.$item_id;
$res = $this->Conn->Query($sql);
$temp = Array();
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);
//$object =& $event->getObject();
//$object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
break;
case 'OnNew':
//$object =& $event->getObject();
//$object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
break;
case 'OnCountryChange':
$this->Application->DeleteVar('taxdst');
break;
default:
}
$event->CallSubEvent("OnPreSave");
}
- function OnMassDelete(&$event)
- {
- $this->StoreSelectedIDs($event);
-
- $event->setEventParam('ids', $this->getSelectedIDs($event) );
- $this->customProcessing($event, 'before');
- $ids = $event->getEventParam('ids');
- $ids = implode(',', $ids);
-
- $dst =& $this->Application->recallObject('taxdst');
- $sql = 'DELETE FROM '.$dst->TableName.' WHERE TaxZoneId IN ('.$ids.')';
- $this->Conn->Query($sql);
-
- parent::OnMassDelete($event);
- }
-
function OnCountryChange(&$event)
{
$destinations = &$this->Application->recallObject('taxdst');
$queryDel="DELETE FROM ".$destinations->TableName." WHERE TaxZoneId=".(int)$this->Application->GetVar('tax_id');
$this->Conn->Query($queryDel);
$this->Application->DeleteVar('taxdst');
$event->CallSubEvent('OnPreSave');
$event->redirect = false;
}
}
\ No newline at end of file
Index: branches/5.2.x/units/coupons/coupons_event_handler.php
===================================================================
--- branches/5.2.x/units/coupons/coupons_event_handler.php (revision 14624)
+++ branches/5.2.x/units/coupons/coupons_event_handler.php (revision 14625)
@@ -1,238 +1,281 @@
<?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 CouponsEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnItemBuild' => Array('self' => true),
'OnApplyClone' => Array('self' => 'add'),
'OnPrepareClone' => Array('self' => 'view'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Prepares coupon cloning
*
* @param kEvent $event
*/
function OnPrepareClone(&$event)
{
$this->StoreSelectedIDs($event);
$event->CallSubEvent('OnNew');
$object =& $event->getObject();
/* @var $object kDBItem */
$this->setCloningRequired($object);
$clone_count = $this->Application->RecallVar('CoupLastCloneCount');
if ( is_numeric($clone_count) && $clone_count > 0 ) {
$object->SetDBField('CouponCount', $clone_count);
}
$expire_days = $this->Application->ConfigValue('Comm_DefaultCouponDuration');
$default_expiration = strtotime('+' . $expire_days . ' days');
$object->SetDBField('DefaultExpiration_date', $default_expiration);
$object->SetDBField('DefaultExpiration_time', $default_expiration);
}
-
- function OnBeforeClone(&$event)
+ /**
+ * Occurs before an item has been cloned
+ * Id of newly created item is passed as event' 'id' param
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeClone(&$event)
{
parent::OnBeforeClone($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$this->SetNewCode($object);
$object->SetDBField('LastUsedBy', NULL);
$object->SetDBField('LastUsedOn', NULL);
$object->SetDBField('NumberOfUses', NULL);
$expiration = $this->Application->GetVar('clone_coupon_expiration');
$object->SetDBField('Expiration_date', $expiration);
$object->SetDBField('Expiration_time', $expiration);
}
function OnApplyClone(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$object =& $event->getObject( Array ('skip_autoload' => true) );
/* @var $object kDBItem */
$this->setCloningRequired($object);
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
list($id, $field_values) = each($items_info);
$object->SetFieldsFromHash($field_values);
$object->setID($id);
if ( !$object->Validate() ) {
$event->status = kEvent::erFAIL;
return ;
}
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
/* @var $temp kTempTablesHandler */
$original_coupon_ids = $this->getSelectedIDs($event, true);
$clone_count = $object->GetDBField('CouponCount');
$this->Application->StoreVar('CoupLastCloneCount', $clone_count);
$this->Application->SetVar('clone_coupon_expiration', $object->GetDBField('DefaultExpiration'));
for ($i = 0; $i < $clone_count; $i++) {
$temp->CloneItems($event->Prefix, $event->Special, $original_coupon_ids);
}
$this->finalizePopup($event);
}
function setCloningRequired(&$object)
{
$this->RemoveRequiredFields($object);
$object->setRequired('CouponCount');
$object->setRequired('DefaultExpiration');
}
function SetNewCode(&$item)
{
do{
$new_code = $this->RandomCouponCode(10);
$exists = $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'ProductsCoupons WHERE Code='.$this->Conn->qstr($new_code));
if ($exists){
$new_code = false;
}
} while (!$new_code);
$item->SetDBField('Code', $new_code);
}
function RandomCouponCode($size)
{
$rand_code = "";
for ($i=0; $i<10; $i++){
$is_letter = rand(0,1);
if ($is_letter){
$rand_char = chr(rand(65,90));
}else{
$rand_char = rand(0,9);
}
$rand_code .= $rand_char;
}
return $rand_code;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnApplyCoupon(&$event)
{
$code = $this->Application->GetVar('coupon_code');
if ($code == '') {
return ;
}
$object =& $event->getObject(Array('skip_autoload' => true));
$object->Load($code, 'Code');
if (!$object->isLoaded()) {
$event->status = kEvent::erFAIL;
$this->Application->SetVar('set_checkout_error', 4);
$event->redirect = false; // check!!!
return ;
}
$expire_date = $object->GetDBField('Expiration');
$number_of_use = $object->GetDBField('NumberOfUses');
if( $object->GetDBField('Status') != 1 || ($expire_date && $expire_date < adodb_mktime()) ||
(isset($number_of_use) && $number_of_use <= 0))
{
$event->status = kEvent::erFAIL;
$this->Application->SetVar('set_checkout_error', 5);
$event->redirect->false;
return ;
}
$last_used = adodb_mktime();
$object->SetDBField('LastUsedBy', $this->Application->RecallVar('user_id'));
$object->SetDBField('LastUsedOn_date', $last_used);
$object->SetDBField('LastUsedOn_time', $last_used);
if(isset($number_of_use))
{
$object->SetDBField('NumberOfUses', $number_of_use - 1);
if($number_of_use == 1)
{
$object->SetDBField('Status', 2);
}
}
$object->Update();
$this->Application->setUnitOption('ord', 'AutoLoad', true);
$order =& $this->Application->recallObject('ord');
$order->SetDBField('CouponId', $object->GetDBField('CouponId'));
$order->Update();
$this->Application->SetVar('set_checkout_error', 10);
}
/**
- * Enter description here...
+ * Prepare temp tables for creating new item
+ * but does not create it. Actual create is
+ * done in OnPreSaveCreated
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnPreCreate(&$event){
-
+ protected function OnPreCreate(&$event)
+ {
parent::OnPreCreate($event);
- $object = &$event->getObject();
- $exp_date = adodb_mktime();
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
+ $exp_date = adodb_mktime();
$default_duration = $this->Application->ConfigValue('Comm_DefaultCouponDuration');
- if ($default_duration && $default_duration>0){
- $exp_date += (int)$default_duration*86400;
+ if ( $default_duration && $default_duration > 0 ) {
+ $exp_date += (int)$default_duration * 86400;
}
+
$object->SetDBField('Expiration_date', $exp_date);
}
- function OnBeforeItemUpdate(&$event)
+ /**
+ * Occurs before updating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemUpdate(&$event)
+ {
+ parent::OnBeforeItemUpdate($event);
+
+ $this->itemChanged($event);
+ }
+
+ /**
+ * Occurs before creating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemCreate(&$event)
{
- $object =& $event->getObject();
- $object->SetDBField( 'Amount', abs($object->GetDBField('Amount')) );
+ parent::OnBeforeItemCreate($event);
+
+ $this->itemChanged($event);
}
- function OnBeforeItemCreate(&$event)
+ /**
+ * Occurs before item is changed
+ *
+ * @param kEvent $event
+ */
+ function itemChanged(&$event)
{
- $this->OnBeforeItemUpdate($event);
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
+
+ $object->SetDBField('Amount', abs($object->GetDBField('Amount')));
}
}
\ 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 14624)
+++ branches/5.2.x/units/shipping_costs/shipping_costs_event_handler.php (revision 14625)
@@ -1,235 +1,243 @@
<?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 standart 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) );
$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);
$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);
}
}
}
}
/**
* 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;
}
- function customProcessing(&$event, $type)
+ /**
+ * 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') )
{
$shipping_obj =& $this->Application->recallObject('s');
$cost =& $event->getObject();
$zero_if_empty = $shipping_obj->GetDBField('ZeroIfEmpty');
if($cost->GetDBField('Flat') == '')
{
$flat = $zero_if_empty ? 0 : null;
$cost->SetDBField('Flat', $flat);
}
if($cost->GetDBField('PerUnit') == '')
{
$per_unit = $zero_if_empty ? 0 : null;
$cost->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/zones/zones_event_handler.php
===================================================================
--- branches/5.2.x/units/zones/zones_event_handler.php (revision 14624)
+++ branches/5.2.x/units/zones/zones_event_handler.php (revision 14625)
@@ -1,252 +1,253 @@
<?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 ZonesEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnTypeChange' => Array('subitem' => 'add|edit'),
'OnCountryChange' => Array('subitem' => 'add|edit'),
'OnLoadZoneForm' => Array('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decine and so on events
$zones_events = Array( 'OnAddLocation' => 'DestinationAction',
'OnRemoveLocation' => 'DestinationAction',
'OnLoadZoneForm' => 'DestinationAction',
/*'OnCountryChange' => 'DestinationAction',*/);
$this->eventMethods = array_merge($this->eventMethods, $zones_events);
}
- function customProcessing(&$event, $type)
+ /**
+ * Apply custom processing to item
+ *
+ * @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
+ */
+ protected function customProcessing(&$event, $type)
{
- $zone_object =& $event->GetObject();
- switch($type)
- {
+ $zone_object =& $event->getObject();
+ /* @var $zone_object kDBItem */
+
+ switch ( $type ) {
case 'before':
- if ($event->Name == 'OnCreate')
- {
+ if ( $event->Name == 'OnCreate' ) {
$zone_object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
}
break;
+
case 'after':
- $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
- $dst_object =& $this->Application->RecallObject('dst');
- if ($event->Name == 'OnUpdate')
- {
- $sql = 'DELETE FROM '.$dst_object->TableName.' WHERE ShippingZoneId='.$zone_object->GetID();
+ $dst_object =& $this->Application->recallObject('dst');
+ /* @var $dst_object kDBItem */
+
+ if ( $event->Name == 'OnUpdate' ) {
+ $sql = 'DELETE FROM ' . $dst_object->TableName . '
+ WHERE ShippingZoneId = ' . $zone_object->GetID();
$this->Conn->Query($sql);
}
- else
- {
- $temp = $this->Application->GetVar('dst');
- foreach ($temp as $key => $value)
- {
+ else {
+ $temp = $this->Application->GetVar('dst', Array ());
+ foreach ($temp as $key => $value) {
$temp[$key]['ShippingZoneId'] = $zone_object->GetID();
}
$this->Application->SetVar('dst', $temp);
}
- $dst_event = new kEvent();
- $dst_event->Init('dst');
- $dst_event->Name = 'OnCreate';
+ $dst_event = new kEvent('dst:OnCreate');
$this->Application->HandleEvent($dst_event);
break;
-
- default:
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnTypeChange(&$event)
{
$this->Application->DeleteVar('dst');
$event->CallSubEvent($this->Application->GetVar('z_OriginalSaveEvent'));
$event->redirect = false;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function DestinationAction(&$event)
{
$event->redirect = false;
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $item_id => $field_values)
{
// this is to receive $item_id
}
}
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->Load($item_id);
$object->SetFieldsFromHash($field_values);
$object->SetDBField('ZoneID', $item_id);
$destination =& $this->Application->recallObject('dst');
switch($event->Name)
{
case 'OnAddLocation':
$new_id = (int)$this->Conn->GetOne('SELECT MIN('.$destination->IDField.') FROM '.$destination->TableName);
if($new_id > 0) $new_id = 0;
do
{
$new_id--;
} while ($this->check_array($this->Application->GetVar('dst'), 'ZoneDestId', $new_id));
switch ($object->GetDBField('Type'))
{
case 1:
$location_id = $this->Application->GetVar('country');
break;
case 2:
$location_id = $this->Application->GetVar('state');
break;
default:
$location_id = '';
}
$temp = $this->Application->GetVar('dst');
$zip = $this->Application->GetVar('zip_input') ? $this->Application->GetVar('zip_input') : $this->Application->GetVar('zip_dropdown');
if( ($location_id && !$this->check_array($temp, 'StdDestId', $location_id)) ||
($zip && !$this->check_array($temp, 'DestValue', $zip)) )
{
$temp[$new_id]['ZoneDestId'] = $new_id;
$temp[$new_id]['StdDestId'] = $location_id;
$temp[$new_id]['DestValue'] = $zip ? $zip : '';
$this->Application->SetVar('dst', $temp);
}
break;
case 'OnRemoveLocation':
$temp = $this->Application->GetVar('dst');
$selected_destinations = explode(',', $this->Application->GetVar('selected_destinations'));
foreach ($selected_destinations as $dest)
{
unset( $temp[$dest] );
}
$this->Application->SetVar('dst', $temp);
break;
case 'OnLoadZoneForm':
$sql = 'SELECT * FROM '.$destination->TableName.' WHERE ShippingZoneId='.$item_id;
$res = $this->Conn->Query($sql);
$temp = Array();
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 =& $event->getObject();
$object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
$this->Application->StoreVar('zone_mode'.$this->Application->GetVar('m_wid'), 'edit');
break;
/*case 'OnNew':
$object =& $event->getObject();
$object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
break;*/
case 'OnCountryChange':
$this->Application->DeleteVar('dst');
break;
default:
}
}
- function OnMassDelete(&$event)
- {
- $ids = $this->StoreSelectedIDs($event);
-
- $event->setEventParam('ids', $ids);
- $this->customProcessing($event, 'before');
- $ids = $event->getEventParam('ids');
- $ids = implode(',', $ids);
-
- $dst =& $this->Application->recallObject('dst');
- $sql = 'DELETE FROM '.$dst->TableName.' WHERE ShippingZoneId IN ('.$ids.')';
- $this->Conn->Query($sql);
-
- parent::OnMassDelete($event);
- }
-
function OnCountryChange(&$event)
{
$destinations = &$this->Application->recallObject('dst');
$queryDel="DELETE FROM ".$destinations->TableName." WHERE ShippingZoneId=".$this->Application->GetVar($event->Prefix.'_id');
$this->Conn->Query($queryDel);
$this->Application->DeleteVar('dst');
$event->CallSubEvent($this->Application->GetVar('z_OriginalSaveEvent'));
$event->redirect = false;
}
- function OnCancel(&$event){
-
+ /**
+ * Cancels kDBItem Editing/Creation
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ function OnCancel(&$event)
+ {
parent::OnCancel($event);
+
$dst_object = &$this->Application->recallObject('dst');
- $delete_zones_sql = 'DELETE FROM '.$dst_object->TableName.' WHERE ShippingZoneId = 0';
+ /* @var $dst_object kDBItem */
+
+ $delete_zones_sql = ' DELETE FROM ' . $dst_object->TableName . '
+ WHERE ShippingZoneId = 0';
$this->Conn->Query($delete_zones_sql);
// if cancelling after create
- if ($this->Application->RecallVar('zone_mode'.$this->Application->GetVar('m_wid')) == 'create') {
+ if ( $this->Application->RecallVar('zone_mode' . $this->Application->GetVar('m_wid')) == 'create' ) {
$zone =& $event->getObject();
+ /* @var $zone kDBItem */
+
$zone->Delete();
}
}
function OnNew(&$event)
{
parent::OnNew($event);
$this->Application->StoreVar('zone_mode'.$this->Application->GetVar('m_wid'), 'create');
}
}
\ No newline at end of file
Index: branches/5.2.x/units/affiliate_plans_brackets/affiliate_plans_brackets_event_handler.php
===================================================================
--- branches/5.2.x/units/affiliate_plans_brackets/affiliate_plans_brackets_event_handler.php (revision 14624)
+++ branches/5.2.x/units/affiliate_plans_brackets/affiliate_plans_brackets_event_handler.php (revision 14625)
@@ -1,103 +1,116 @@
<?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 AffiliatePlansBracketsEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnMoreBrackets' => Array('subitem' => 'add|edit'),
'OnInfinity' => Array('subitem' => 'add|edit'),
'OnArrange' => Array('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Adds additional 5 empty brackets
*
* @param kEvent $event
*/
function OnMoreBrackets(&$event)
{
$event->redirect = false;
$brackets_helper =& $this->Application->recallObject('BracketsHelper');
$brackets_helper->InitHelper('FromAmount', 'ToAmount', Array('Percent' => '') );
$brackets_helper->OnMoreBrackets($event);
}
/**
* Arrange brackets
*
* @param kEvent $event
*/
function OnArrange(&$event)
{
$event->redirect = false;
$brackets_helper =& $this->Application->recallObject('BracketsHelper');
$brackets_helper->InitHelper('FromAmount', 'ToAmount', Array('Percent' => '') );
$brackets_helper->arrangeBrackets($event);
$event->CallSubEvent('OnPreSaveBrackets');
}
/**
* Arrange infinity brackets
*
* @param kEvent $event
*/
function OnInfinity(&$event)
{
$event->redirect = false;
$brackets_helper =& $this->Application->recallObject('BracketsHelper');
$brackets_helper->InitHelper('FromAmount', 'ToAmount', Array('Percent' => '') );
$brackets_helper->arrangeBrackets($event);
$event->CallSubEvent('OnPreSaveBrackets');
$brackets_helper->OnInfinity($event);
$event->CallSubEvent('OnPreSaveBrackets');
}
- function OnBeforeItemUpdate(&$event)
+ /**
+ * Occurs before updating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemUpdate(&$event)
{
+ parent::OnBeforeItemUpdate($event);
+
$object =& $event->getObject();
+ /* @var $object kDBItem */
+
$linked_info = $object->getLinkedInfo();
$object->SetDBField($linked_info['ParentTableKey'], $linked_info['ParentId']);
$brackets_helper =& $this->Application->recallObject('BracketsHelper');
- $brackets_helper->InitHelper('FromAmount', 'ToAmount', Array('Percent' => '') );
+ /* @var $brackets_helper kBracketsHelper */
+
+ $brackets_helper->InitHelper('FromAmount', 'ToAmount', Array ('Percent' => ''));
$brackets_helper->replaceInfinity($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveBrackets(&$event)
{
$brackets_helper =& $this->Application->recallObject('BracketsHelper');
$brackets_helper->InitHelper('FromAmount', 'ToAmount', Array('Percent' => '') );
$brackets_helper->OnPreSaveBrackets($event);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/currencies/currencies_event_handler.php
===================================================================
--- branches/5.2.x/units/currencies/currencies_event_handler.php (revision 14624)
+++ branches/5.2.x/units/currencies/currencies_event_handler.php (revision 14625)
@@ -1,262 +1,274 @@
<?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 CurrenciesEventHandler extends kDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
// admin
'OnUpdateRate' => Array('self' => 'add|edit'),
'OnUpdateRates' => Array('self' => 'advanced:update_rate|add|edit'),
'OnDisableUnused' => Array('self' => 'edit'),
// front
'OnChangeCurrency' => Array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSetPrimary(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$object =& $event->getObject();
$object->SetDBField('IsPrimary', 1);
$object->Update();
}
/**
- * Enter description here...
+ * Occurs before updating item
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemUpdate(&$event)
+ protected function OnBeforeItemUpdate(&$event)
{
+ parent::OnBeforeItemUpdate($event);
+
$object =& $event->getObject();
- if($object->GetDBField('IsPrimary') && $object->Validate())
- {
- $sql = 'UPDATE '.$this->Application->getUnitOption($this->Prefix, 'TableName').'
+ /* @var $object kDBItem */
+
+ if ( $object->GetDBField('IsPrimary') && $object->Validate() ) {
+ $sql = 'UPDATE ' . $this->Application->getUnitOption($this->Prefix, 'TableName') . '
SET IsPrimary = 0
- WHERE CurrencyId <> '.$object->GetDBField('CurrencyId');
+ WHERE CurrencyId <> ' . $object->GetDBField('CurrencyId');
$this->Conn->Query($sql);
+
$object->SetDBField('Status', 1);
}
- $object->SetDBField('Modified_date', adodb_mktime() );
- $object->SetDBField('Modified_time', adodb_mktime() );
- if($object->GetDBField('Status') == 0)
- {
- $sql = 'DELETE FROM '.$this->Application->getUnitOption('ptc', 'TableName').
- ' WHERE CurrencyId='.$object->GetDBField('CurrencyId');
+ $object->SetDBField('Modified_date', adodb_mktime());
+ $object->SetDBField('Modified_time', adodb_mktime());
+
+ if ( $object->GetDBField('Status') == 0 ) {
+ $sql = 'DELETE FROM ' . $this->Application->getUnitOption('ptc', 'TableName') . '
+ WHERE CurrencyId = ' . $object->GetDBField('CurrencyId');
$this->Conn->Query($sql);
}
}
/**
- * Enter description here...
+ * Apply any custom changes to list's sql query
*
* @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
*/
- function SetCustomQuery(&$event)
+ protected function SetCustomQuery(&$event)
{
$object =& $event->getObject();
if ($event->Special == 'active') {
$object =& $event->getObject();
$object->addFilter('status_filter', '%1$s.Status = 1');
}
if (!$this->Application->isAdminUser) {
$object->addFilter('status_filter', $object->TableName.'.Status = 1');
}
// site domain currency picker
if ($event->Special == 'selected' || $event->Special == 'available') {
$edit_picker_helper =& $this->Application->recallObject('EditPickerHelper');
/* @var $edit_picker_helper EditPickerHelper */
$edit_picker_helper->applyFilter($event, 'Currencies');
$object->addFilter('status_filter', '%1$s.Status = ' . STATUS_ACTIVE);
}
// apply domain-based currency filtering
$currencies = $this->Application->siteDomainField('Currencies');
if (strlen($currencies)) {
$currencies = explode('|', substr($currencies, 1, -1));
$object->addFilter('domain_filter', '%1$s.CurrencyId IN (' . implode(',', $currencies) . ')');
}
}
/**
- * Enter description here...
+ * Saves content of temp table into live and
+ * redirects to event' default redirect (normally grid template)
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnSave(&$event)
+ protected function OnSave(&$event)
{
- $this->Application->StoreVar( 'saved_curr_ids', $this->Application->RecallVar($event->Prefix.'_selected_ids') );
+ $this->Application->StoreVar('saved_curr_ids', $this->Application->RecallVar($event->Prefix . '_selected_ids'));
+
parent::OnSave($event);
}
-
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnDisableUnused(&$event)
{
if($unused_ids = $this->Application->GetVar('unused_ids'))
{
$sql = 'UPDATE '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
SET Status = 0
WHERE CurrencyId IN('.$unused_ids.') AND IsPrimary <> 1';
$this->Conn->Query($sql);
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnUpdateRate(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$event->CallSubEvent('OnPreSave');
$rate_source = $this->Application->ConfigValue('Comm_ExchangeRateSource');
$rate_source_classes = Array( 2 => 'FRNYCurrencyRates',
3 => 'ECBCurrencyRates',
1 => 'BankLVCurrencyRates'
);
$rates_class = $rate_source_classes[$rate_source];
$rates =& $this->Application->recallObject($rates_class);
$rates->GetRatesData();
$object =& $event->getObject();
/* @var $object kDBItem */
$iso = $object->GetDBField('ISO');
$rates->StoreRates($iso);
if($rates->GetRate($iso, 'PRIMARY'))
{
$event->status=kEvent::erSUCCESS;
}
else
{
$event->status=kEvent::erFAIL;
$event->redirect=false;
$object->SetError('RateToPrimary', 'couldnt_retrieve_rate', 'la_couldnt_retrieve_rate');
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnUpdateRates(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$ids = $this->StoreSelectedIDs($event);
$event->setEventParam('ids', $ids);
$ids = $event->getEventParam('ids');
$object =& $event->getObject();
if(is_array($ids) && $ids[0])
{
$sql = 'SELECT ISO FROM '.$object->TableName.' WHERE CurrencyId IN ('.implode(',', $ids).')';
$iso_list = $this->Conn->GetCol($sql);
}
$rate_source = $this->Application->ConfigValue('Comm_ExchangeRateSource');
$rate_source_classes = Array( 2 => 'FRNYCurrencyRates',
3 => 'ECBCurrencyRates',
1 => 'BankLVCurrencyRates'
);
$rates_class = $rate_source_classes[$rate_source];
$rates =& $this->Application->recallObject($rates_class);
$rates->GetRatesData();
if($iso_list)
{
$rates->StoreRates($iso_list);
}
else
{
$rates->StoreRates();
}
}
function OnChangeCurrency(&$event)
{
$currency_iso = $this->Application->GetVar('curr_iso');
$available_currencies = $this->Application->siteDomainField('Currencies');
if ($available_currencies) {
if (strpos($available_currencies, '|' . $currency_iso . '|') === false) {
// currency isn't allowed in site domain
return ;
}
}
$this->Application->StoreVar('curr_iso', $currency_iso);
}
/**
* Changes default module to custom (when available)
*
* @param kEvent $event
*/
function OnAfterConfigRead(&$event)
{
parent::OnAfterConfigRead($event);
// make sure, that currency Translation is on current language
$language_id = $this->Application->GetVar('m_lang');
$calculated_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
foreach ($calculated_fields[''] as $field_name => $field_expression) {
$calculated_fields[''][$field_name] = str_replace('%4$s', $language_id, $field_expression);
}
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calculated_fields);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/products/products_event_handler.php
===================================================================
--- branches/5.2.x/units/products/products_event_handler.php (revision 14624)
+++ branches/5.2.x/units/products/products_event_handler.php (revision 14625)
@@ -1,1336 +1,1386 @@
<?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 ProductsEventHandler extends kCatDBEventHandler {
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
// front
'OnCancelAction' => Array('self' => true),
'OnRateProduct' => Array('self' => true),
'OnClearRecent' => Array('self' => true),
'OnRecommendProduct' => Array('self' => true),
// admin
'OnQtyAdd' => Array('self' => 'add|edit'),
'OnQtyRemove' => Array('self' => 'add|edit'),
'OnQtyOrder' => Array('self' => 'add|edit'),
'OnQtyReceiveOrder' => Array('self' => 'add|edit'),
'OnQtyCancelOrder' => Array('self' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decine and so on events
$product_events = Array( 'OnQtyAdd'=>'InventoryAction',
'OnQtyRemove'=>'InventoryAction',
'OnQtyOrder'=>'InventoryAction',
'OnQtyReceiveOrder'=>'InventoryAction',
'OnQtyCancelOrder'=>'InventoryAction',);
$this->eventMethods = array_merge($this->eventMethods, $product_events);
}
/**
* Sets default processing data for subscriptions
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnBeforeItemCreate(&$event)
+ protected function OnBeforeItemCreate(&$event)
{
parent::OnBeforeItemCreate($event);
$object =& $event->getObject();
+ /* @var $object kDBItem */
- $product_approve_events = Array(
+ $product_approve_events = Array (
2 => 'p:OnSubscriptionApprove',
4 => 'p:OnDownloadableApprove',
5 => 'p:OnPackageApprove'
);
$product_type = $object->GetDBField('Type');
- $type_found = in_array($product_type, array_keys($product_approve_events) );
+ $type_found = in_array($product_type, array_keys($product_approve_events));
- if ($type_found && !$object->GetDBField('ProcessingData') ) {
- $processing_data = Array('ApproveEvent' => $product_approve_events[$product_type] );
- $object->SetDBField( 'ProcessingData', serialize($processing_data) );
+ if ( $type_found && !$object->GetDBField('ProcessingData') ) {
+ $processing_data = Array ('ApproveEvent' => $product_approve_events[$product_type]);
+ $object->SetDBField('ProcessingData', serialize($processing_data));
}
}
/**
* Process product count manipulations
*
* @param kEvent $event
* @access private
*/
function InventoryAction(&$event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetFieldsFromHash( $this->getSubmittedFields($event) );
if ($object->GetDBField('InventoryStatus') == 2) {
// inventory by options (use first selected combination in grid)
$combination_id = array_shift( array_keys( $this->Application->GetVar('poc_grid') ) );
}
else {
// inventory by product
$combination_id = 0;
}
// save id of selected option combination & preselect it in grid
$this->Application->SetVar('combination_id', $combination_id);
$this->ScheduleInventoryAction($event->Name, $object->GetId(), $object->GetDBField('Qty'), $combination_id);
$object->Validate();
if ( !$object->GetErrorPseudo('Qty') ){
// only update, when no error on that field
$this->modifyInventory($event->Name, $object, $object->GetDBField('Qty'), $combination_id);
}
$object->SetDBField('Qty', null);
$event->redirect = false;
}
/**
* Perform inventory action on supplied object
*
* @param string $action event name which is actually called by user
* @param ProductsItem $product
* @param int $qty
* @param int $combination_id
*/
function modifyInventory($action, &$product, $qty, $combination_id)
{
if ($product->GetDBField('InventoryStatus') == 2) {
// save inventory changes to option combination instead of product
$object =& $this->Application->recallObject('poc.-item', null, Array('skip_autoload' => true));
$object->Load($combination_id);
}
elseif ($combination_id > 0) {
// combination id present, but not inventory by combinations => skip
return false;
}
elseif ($product->GetDBField('InventoryStatus') == 1) {
// save inventory changes to product
$object =& $product;
}
else {
// product has inventory actions, but don't use inventory => skip
return false;
}
if (!$object->isLoaded()) {
// product/combination in action doesn't exist in database by now
return false;
}
switch ($action) {
case 'OnQtyAdd':
$object->SetDBField('QtyInStock', $object->GetDBField('QtyInStock') + $qty);
break;
case 'OnQtyRemove':
if ($object->GetDBField('QtyInStock') < $qty) {
$qty = $object->GetDBField('QtyInStock');
}
$object->SetDBField('QtyInStock', $object->GetDBField('QtyInStock') - $qty);
break;
case 'OnQtyOrder':
$object->SetDBField('QtyOnOrder', $object->GetDBField('QtyOnOrder') + $qty);
break;
case 'OnQtyReceiveOrder':
$object->SetDBField('QtyOnOrder', $object->GetDBField('QtyOnOrder') - $qty);
$object->SetDBField('QtyInStock', $object->GetDBField('QtyInStock') + $qty);
break;
case 'OnQtyCancelOrder':
$object->SetDBField('QtyOnOrder', $object->GetDBField('QtyOnOrder') - $qty);
break;
}
return $object->Update();
}
function ScheduleInventoryAction($action, $prod_id, $qty, $combination_id = 0)
{
$inv_actions = $this->Application->RecallVar('inventory_actions');
if (!$inv_actions) {
$inv_actions = Array();
}
else {
$inv_actions = unserialize($inv_actions);
}
array_push($inv_actions, Array('action' => $action, 'product_id' => $prod_id, 'combination_id' => $combination_id, 'qty' => $qty));
$this->Application->StoreVar('inventory_actions', serialize($inv_actions));
}
function RealInventoryAction($action, $prod_id, $qty, $combination_id)
{
$product =& $this->Application->recallObject('p.liveitem', null, Array('skip_autoload' => true));
$product->SwitchToLive();
$product->Load($prod_id);
$this->modifyInventory($action, $product, $qty, $combination_id);
}
function RunScheduledInventoryActions(&$event)
{
$inv_actions = $this->Application->GetVar('inventory_actions');
if (!$inv_actions) {
return;
}
$inv_actions = unserialize($inv_actions);
$products = array();
foreach($inv_actions as $an_action) {
$this->RealInventoryAction($an_action['action'], $an_action['product_id'], $an_action['qty'], $an_action['combination_id']);
array_push($products, $an_action['product_id'].'_'.$an_action['combination_id']);
}
$products = array_unique($products);
if ($products) {
$product_obj =& $this->Application->recallObject('p.liveitem', null, Array('skip_autoload' => true));
$product_obj->SwitchToLive();
foreach ($products as $product_key) {
list($prod_id, $combination_id) = explode('_', $product_key);
$product_obj->Load($prod_id);
$this->FullfillBackOrders($product_obj, $combination_id);
}
}
}
/**
* In case if products arrived into inventory and they are required by old (non processed) orders, then use them (products) in that orders
*
* @param ProductsItem $product
* @param int $combination_id
*/
function FullfillBackOrders(&$product, $combination_id)
{
if ( !$this->Application->ConfigValue('Comm_Process_Backorders_Auto') ) return;
if ($combination_id && ($product->GetDBField('InventoryStatus') == 2)) {
// if combination id present and inventory by combinations
$poc_idfield = $this->Application->getUnitOption('poc', 'IDField');
$poc_tablename = $this->Application->getUnitOption('poc', 'TableName');
$sql = 'SELECT QtyInStock
FROM '.$poc_tablename.'
WHERE '.$poc_idfield.' = '.$combination_id;
$stock_qty = $this->Conn->GetOne($sql);
}
else {
// inventory by product
$stock_qty = $product->GetDBField('QtyInStock');
}
$qty = (int) $stock_qty - $product->GetDBField('QtyInStockMin');
$prod_id = $product->GetID();
if ($prod_id <= 0 || !$prod_id || $qty <= 0) return;
//selecting up to $qty backorders with $prod_id where full qty is not reserved
$query = 'SELECT '.TABLE_PREFIX.'Orders.OrderId
FROM '.TABLE_PREFIX.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Orders ON '.TABLE_PREFIX.'Orders.OrderId = '.TABLE_PREFIX.'OrderItems.OrderId
WHERE (ProductId = '.$prod_id.') AND (Quantity > QuantityReserved) AND (Status = '.ORDER_STATUS_BACKORDERS.')
GROUP BY '.TABLE_PREFIX.'Orders.OrderId
ORDER BY OrderDate ASC
LIMIT 0,'.$qty; //assuming 1 item per order - minimum possible
$orders = $this->Conn->GetCol($query);
if (!$orders) return;
$order =& $this->Application->recallObject('ord.-inv', null, Array('skip_autoload' => true));
foreach ($orders as $ord_id) {
$order->Load($ord_id);
$email_event_admin =& $this->Application->EmailEventAdmin('BACKORDER.FULLFILL');
//reserve what's possible in any case
$this->Application->HandleEvent( $event, 'ord:OnReserveItems' );
if ($event->status == kEvent::erSUCCESS) { //
//in case the order is ready to process - process it
$this->Application->HandleEvent( $event, 'ord:OnOrderProcess' );
}
}
}
- function OnBeforeDeleteFromLive(&$event)
+ /**
+ * Occurs before an item is deleted from live table when copying from temp
+ * (temp handler deleted all items from live and then copy over all items from temp)
+ * Id of item being deleted is passed as event' 'id' param
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeDeleteFromLive(&$event)
{
- $id = $event->getEventParam('id');
- $product =& $this->Application->recallObject($event->Prefix.'.itemlive', null, Array('skip_autoload' => true));
+ parent::OnBeforeDeleteFromLive($event);
+
+ $product =& $this->Application->recallObject($event->Prefix . '.itemlive', null, Array ('skip_autoload' => true));
/* @var $product kCatDBItem */
$product->SwitchToLive();
- if (!$product->Load($id)) return ; // this will make sure New product will not be overwritten with empty data
+ $id = $event->getEventParam('id');
+
+ if ( !$product->Load($id) ) {
+ // this will make sure New product will not be overwritten with empty data
+ return ;
+ }
- $temp =& $this->Application->recallObject($event->Prefix.'.itemtemp', null, Array('skip_autoload' => true));
+ $temp =& $this->Application->recallObject($event->Prefix . '.itemtemp', null, Array ('skip_autoload' => true));
/* @var $temp kCatDBItem */
$temp->SwitchToTemp();
$temp->Load($id);
- $temp->SetDBFieldsFromHash($product->GetFieldValues(), Array('QtyInStock','QtyReserved','QtyBackOrdered','QtyOnOrder'));
+ $temp->SetDBFieldsFromHash($product->GetFieldValues(), Array ('QtyInStock', 'QtyReserved', 'QtyBackOrdered', 'QtyOnOrder'));
$temp->Update();
}
function clearSelectedIDs(&$event)
{
parent::clearSelectedIDs($event);
$this->Application->SetVar('inventory_actions', $this->Application->RecallVar('inventory_actions'));
$this->Application->RemoveVar('inventory_actions');
}
- function OnSave(&$event)
+ /**
+ * Saves content of temp table into live and
+ * redirects to event' default redirect (normally grid template)
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnSave(&$event)
{
- $res = parent::OnSave($event);
- if ($event->status == kEvent::erSUCCESS) {
+ parent::OnSave($event);
+
+ if ( $event->status == kEvent::erSUCCESS ) {
$this->RunScheduledInventoryActions($event);
}
- return $res;
}
- function OnPreCreate(&$event)
+ /**
+ * Prepare temp tables for creating new item
+ * but does not create it. Actual create is
+ * done in OnPreSaveCreated
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnPreCreate(&$event)
{
parent::onPreCreate($event);
- $object =& $event->GetObject();
- $object->SetDBField('Type', $this->Application->GetVar( $event->getPrefixSpecial(true).'_new_type' ));
- }
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
+
+ $object->SetDBField('Type', $this->Application->GetVar($event->getPrefixSpecial(true) . '_new_type'));
+ }
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveAndGo(&$event) {
$event->CallSubEvent('OnPreSave');
$this->LoadItem($event);
$object =& $event->getObject();
$from_type = $object->GetDBField('Type');
if ($event->status==kEvent::erSUCCESS) {
$this->Application->SetVar($event->getPrefixSpecial().'_id', $this->Application->GetVar($event->getPrefixSpecial(true).'_GoId'));
$this->LoadItem($event);
$to_type = $object->GetDBField('Type');
if ($from_type != $to_type) {
$from_tabs = $this->GetTabs($from_type);
$from_tab_i = array_search($this->Application->GetVar('t'), $from_tabs);
$to_tabs = $this->GetTabs($to_type);
$to_tab = $this->Application->GetVar('t');
$found = false;
while ( !isset($to_tabs[$from_tab_i]) && $from_tab_i < count($to_tabs)) {
$from_tab_i++;
}
if ( !isset($to_tabs[$from_tab_i]) ) $from_tab_i = 0;
$to_tab = $to_tabs[$from_tab_i];
$event->redirect = $to_tab;
}
}
}
function GetTabs($type)
{
switch($type)
{
case 1:
return Array(
0 => 'in-commerce/products/products_edit',
1 => 'in-commerce/products/products_inventory',
2 => 'in-commerce/products/products_pricing',
3 => 'in-commerce/products/products_categories',
4 => 'in-commerce/products/products_images',
5 => 'in-commerce/products/products_reviews',
6 => 'in-commerce/products/products_custom',
);
case 2:
return Array(
0 => 'in-commerce/products/products_edit',
1 => 'in-commerce/products/products_access',
/*2 => 'in-commerce/products/products_access_pricing',*/
3 => 'in-commerce/products/products_categories',
4 => 'in-commerce/products/products_images',
5 => 'in-commerce/products/products_reviews',
6 => 'in-commerce/products/products_custom',
);
case 3:
return Array(
0 => 'in-commerce/products/products_edit',
2 => 'in-commerce/products/products_access_pricing',
3 => 'in-commerce/products/products_categories',
4 => 'in-commerce/products/products_images',
5 => 'in-commerce/products/products_reviews',
6 => 'in-commerce/products/products_custom',
);
case 4:
return Array(
0 => 'in-commerce/products/products_edit',
2 => 'in-commerce/products/products_files',
3 => 'in-commerce/products/products_categories',
4 => 'in-commerce/products/products_images',
5 => 'in-commerce/products/products_reviews',
6 => 'in-commerce/products/products_custom',
);
}
}
/**
* Return type clauses for list bulding on front
*
* @param kEvent $event
* @return Array
*/
function getTypeClauses(&$event)
{
$types=$event->getEventParam('types');
$except_types=$event->getEventParam('except');
$object =& $event->getObject();
$type_clauses = parent::getTypeClauses($event);
$type_clauses['featured']['include']='%1$s.Featured=1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
$type_clauses['featured']['except']='%1$s.Featured!=1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
$type_clauses['featured']['having_filter']=false;
$type_clauses['onsale']['include']='%1$s.OnSale=1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
$type_clauses['onsale']['except']='%1$s.OnSale!=1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
$type_clauses['onsale']['having_filter']=false;
// products from selected manufacturer: begin
$manufacturer = $event->getEventParam('manufacturer');
if ( !$manufacturer ) {
$manufacturer = $this->Application->GetVar('manuf_id');
}
if ( $manufacturer ) {
$type_clauses['manufacturer']['include'] = '%1$s.ManufacturerId='.$manufacturer.' AND PrimaryCat = 1';
$type_clauses['manufacturer']['except'] = '%1$s.ManufacturerId!='.$manufacturer.' AND PrimaryCat = 1';
$type_clauses['manufacturer']['having_filter'] = false;
}
// products from selected manufacturer: end
// recent products: begin
$recent = $this->Application->RecallVar('recent_products');
if ($recent) {
$recent = unserialize($recent);
$type_clauses['recent']['include'] = '%1$s.ProductId IN ('.implode(',', $recent).') AND PrimaryCat = 1';
$type_clauses['recent']['except'] = '%1$s.ProductId NOT IN ('.implode(',', $recent).') AND PrimaryCat = 1';
}
else {
$type_clauses['recent']['include']='0';
$type_clauses['recent']['except']='1';
}
$type_clauses['recent']['having_filter']=false;
// recent products: end
// products already in shopping cart: begin
if (strpos($types, 'in_cart') !== false || strpos($except_types, 'in_cart') !== false) {
$order_id = $this->Application->RecallVar('ord_id');
if ($order_id) {
$in_cart = $this->Conn->GetCol('SELECT ProductId FROM '.TABLE_PREFIX.'OrderItems WHERE OrderId = '.$order_id);
if ($in_cart) {
$type_clauses['in_cart']['include'] = '%1$s.ProductId IN ('.implode(',', $in_cart).') AND PrimaryCat = 1';
$type_clauses['in_cart']['except'] = '%1$s.ProductId NOT IN ('.implode(',', $in_cart).') AND PrimaryCat = 1';
}
else {
$type_clauses['in_cart']['include']='0';
$type_clauses['in_cart']['except']='1';
}
}
else {
$type_clauses['in_cart']['include']='0';
$type_clauses['in_cart']['except']='1';
}
$type_clauses['in_cart']['having_filter']=false;
}
// products already in shopping cart: end
// my downloadable products: begin
if (strpos($types, 'my_downloads') !== false || strpos($except_types, 'my_downloads') !== false)
{
$user_id = $this->Application->RecallVar('user_id');
$my_downloads = ($user_id > 0) ? $this->Conn->GetCol('SELECT ProductId FROM '.TABLE_PREFIX.'UserFileAccess WHERE PortalUserId = '.$user_id) : false;
if ($my_downloads)
{
$type_clauses['my_downloads']['include'] = '%1$s.ProductId IN ('.implode(',', $my_downloads).') AND PrimaryCat = 1';
$type_clauses['my_downloads']['except'] = '%1$s.ProductId NOT IN ('.implode(',', $my_downloads).') AND PrimaryCat = 1';
}
else
{
$type_clauses['my_downloads']['include'] = '0';
$type_clauses['my_downloads']['except'] = '1';
}
$type_clauses['my_downloads']['having_filter'] = false;
}
// my downloadable products: end
// my favorite products: begin
if (strpos($types, 'wish_list') !== false || strpos($except_types, 'wish_list') !== false) {
$sql = 'SELECT ResourceId FROM '.$this->Application->getUnitOption('fav', 'TableName').'
WHERE PortalUserId = '.(int)$this->Application->RecallVar('user_id');
$wishlist_ids = $this->Conn->GetCol($sql);
if ($wishlist_ids) {
$type_clauses['wish_list']['include'] = '%1$s.ResourceId IN ('.implode(',', $wishlist_ids).') AND PrimaryCat = 1';
$type_clauses['wish_list']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $wishlist_ids).') AND PrimaryCat = 1';
}
else {
$type_clauses['wish_list']['include']='0';
$type_clauses['wish_list']['except']='1';
}
$type_clauses['wish_list']['having_filter']=false;
}
// my favorite products: end
// products from package: begin
if (strpos($types, 'content') !== false) {
$object->removeFilter('category_filter');
$object->AddGroupByField('%1$s.ProductId');
$item_type = $this->Application->getUnitOption('p', 'ItemType');
$object_product = &$this->Application->recallObject($event->Prefix);
$content_ids_array = $object_product->GetPackageContentIds();
if (sizeof($content_ids_array)==0) {
$content_ids_array = array('-1');
}
if (sizeof($content_ids_array)>0) {
$type_clauses['content']['include'] = '%1$s.ProductId IN ('.implode(',', $content_ids_array).')';
}
else {
$type_clauses['content']['include']='0';
}
$type_clauses['related']['having_filter']=false;
}
// products from package: end
$object->addFilter('not_virtual', '%1$s.Virtual = 0');
if (!$this->Application->isAdminUser) {
$object->addFilter('expire_filter', '%1$s.Expire IS NULL OR %1$s.Expire > UNIX_TIMESTAMP()');
}
return $type_clauses;
}
function OnClearRecent(&$event)
{
$this->Application->RemoveVar('recent_products');
}
/**
* Occurs, when user rates a product
*
* @param kEvent $event
*/
function OnRateProduct(&$event)
{
$event->setRedirectParams(Array('pass' => 'all,p'), true);
$event->redirect = $this->Application->GetVar('success_template');
$object =& $event->getObject();
/* @var $object kDBItem */
$user_id = $this->Application->RecallVar('user_id');
$sql = ' SELECT * FROM '.TABLE_PREFIX.'SpamControl
WHERE ItemResourceId='.$object->GetDBField('ResourceId').'
AND IPaddress="'.$_SERVER['REMOTE_ADDR'].'"
AND PortalUserId='.$user_id.'
AND DataType="Rating"';
$res = $this->Conn->GetRow($sql);
if( $res && $res['Expire'] < adodb_mktime() )
{
$sql = ' DELETE FROM '.TABLE_PREFIX.'SpamControl
WHERE ItemResourceId='.$object->GetDBField('ResourceId').'
AND IPaddress="'.$_SERVER['REMOTE_ADDR'].'"
AND PortalUserId='.$user_id.'
AND DataType="Rating"';
$this->Conn->Query($sql);
unset($res);
}
$new_rating = $this->Application->GetVar('rating');
if($new_rating !== false && !$res)
{
$rating = $object->GetDBField('CachedRating');
$votes = $object->GetDBField('CachedVotesQty');
$new_votes = $votes + 1;
$rating = (($rating * $votes) + $new_rating) / $new_votes;
$object->SetDBField('CachedRating', $rating);
$object->SetDBField('CachedVotesQty', $new_votes);
$object->Update();
$expire = adodb_mktime() + $this->Application->ConfigValue('product_ReviewDelay_Value') * $this->Application->ConfigValue('product_ReviewDelay_Interval');
$sql = ' INSERT INTO '.TABLE_PREFIX.'SpamControl
(ItemResourceId, IPaddress, PortalUserId, DataType, Expire)
VALUES ('.$object->GetDBField('ResourceId').',
"'.$_SERVER['REMOTE_ADDR'].'",
'.$user_id.',
"Rating",
'.$expire.')';
$this->Conn->Query($sql);
}
else
{
$event->status == kEvent::erFAIL;
$event->redirect=false;
$object->SetError('CachedRating', 'too_frequent', 'lu_ferror_rate_duplicate');
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnCancelAction(&$event)
{
$event->setRedirectParams(Array('pass' => 'all,p'), true);
$event->redirect = $this->Application->GetVar('cancel_template');
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnRecommendProduct(&$event)
{
// used for error reporting only -> rewrite code + theme (by Alex)
$object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); // TODO: change theme too
/* @var $object kDBItem */
$friend_email = $this->Application->GetVar('friend_email');
$friend_name = $this->Application->GetVar('friend_name');
$my_email = $this->Application->GetVar('your_email');
$my_name = $this->Application->GetVar('your_name');
$my_message = $this->Application->GetVar('your_message');
$send_params = array();
$send_params['to_email']=$friend_email;
$send_params['to_name']=$friend_name;
$send_params['from_email']=$my_email;
$send_params['from_name']=$my_name;
$send_params['message']=$my_message;
if (preg_match('/'.REGEX_EMAIL_USER.'@'.REGEX_EMAIL_DOMAIN.'/', $friend_email)) {
$user_id = $this->Application->RecallVar('user_id');
$email_event = &$this->Application->EmailEventUser('PRODUCT.SUGGEST', $user_id, $send_params);
$email_event = &$this->Application->EmailEventAdmin('PRODUCT.SUGGEST');
if ($email_event->status == kEvent::erSUCCESS){
$event->setRedirectParams(Array('opener' => 's', 'pass' => 'all'), true);
$event->redirect = $this->Application->GetVar('template_success');
}
else {
// $event->setRedirectParams(Array('opener' => 's', 'pass' => 'all'), true);
// $event->redirect = $this->Application->GetVar('template_fail');
$object->SetError('Email', 'send_error', 'lu_email_send_error');
$event->status = kEvent::erFAIL;
}
}
else {
$object->SetError('Email', 'invalid_email', 'lu_InvalidEmail');
$event->status = kEvent::erFAIL;
}
}
/**
* Creates/updates virtual product based on listing type data
*
* @param kEvent $event
*/
function OnSaveVirtualProduct(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$listing_type =& $this->Application->recallObject('lst', null, Array('skip_autoload' => true));
$listing_type->Load($event->MasterEvent->getEventParam('id'));
$product_id = $listing_type->GetDBField('VirtualProductId');
if ($product_id) {
$object->Load($product_id);
}
if (!$listing_type->GetDBField('EnableBuying')) {
if ($product_id) {
// delete virtual product here
$temp_handler =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$temp_handler->DeleteItems($event->Prefix, $event->Special, Array($product_id));
$listing_type->SetDBField('VirtualProductId', 0);
$listing_type->Update();
}
return true;
}
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$object->SetDBField($ml_formatter->LangFieldName('Name'), $listing_type->GetDBField('ShopCartName') );
$object->SetDBField($ml_formatter->LangFieldName('Description'), $listing_type->GetDBField('Description'));
$object->SetDBField('SKU', 'ENHANCE_LINK_'.abs( crc32( $listing_type->GetDBField('Name') ) ) );
if ($product_id) {
$object->Update();
}
else {
$object->SetDBField('Type', 2);
$object->SetDBField('Status', 1);
$object->SetDBField('HotItem', 0);
$object->SetDBField('PopItem', 0);
$object->SetDBField('NewItem', 0);
$object->SetDBField('Virtual', 1);
// $processing_data = Array('ApproveEvent' => 'ls:EnhanceLinkAfterOrderApprove', 'ExpireEvent' => 'ls:ExpireLink');
$processing_data = Array( 'ApproveEvent' => 'ls:EnhanceLinkAfterOrderApprove',
'DenyEvent' => 'ls:EnhanceLinkAfterOrderDeny',
'CompleteOrderEvent' => 'ls:EnhancedLinkOnCompleteOrder',
'ExpireEvent' => 'ls:ExpireLink',
'HasNewProcessing' => 1);
$object->SetDBField('ProcessingData', serialize($processing_data));
$object->Create();
$listing_type->SetDBField('VirtualProductId', $object->GetID());
$listing_type->Update();
}
$additiona_fields = Array( 'AccessDuration' => $listing_type->GetDBField('Duration'),
'AccessUnit' => $listing_type->GetDBField('DurationType'),
);
$this->setPrimaryPrice($object->GetID(), (double)$listing_type->GetDBField('Price'), $additiona_fields);
}
/**
* [HOOK] Deletes virtual product when listing type is deleted
*
* @param kEvent $event
*/
function OnDeleteListingType(&$event)
{
$listing_type = $event->MasterEvent->getObject();
$product_id = $listing_type->GetDBField('VirtualProductId');
if ($product_id) {
$temp_handler =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$temp_handler->DeleteItems($event->Prefix, $event->Special, Array($product_id));
}
}
/**
* Extends user membership in group when his order is approved
*
* @param kEvent $event
*/
function OnSubscriptionApprove(&$event)
{
$field_values = $event->getEventParam('field_values');
$item_data = unserialize($field_values['ItemData']);
if ( !getArrayValue($item_data,'PortalGroupId') ) {
// is subscription product, but no group defined in it's properties
trigger_error('Invalid product <b>'.$field_values['ProductName'].'</b> (id: '.$field_values['ProductId'].')', E_USER_WARNING);
return false;
}
$sql = 'SELECT PortalUserId
FROM ' . $this->Application->getUnitOption('ord', 'TableName') . '
WHERE ' . $this->Application->getUnitOption('ord', 'IDField') . ' = ' . $field_values['OrderId'];
$user_id = $this->Conn->GetOne($sql);
$group_id = $item_data['PortalGroupId'];
$duration = $item_data['Duration'];
$sql = 'SELECT *
FROM ' . TABLE_PREFIX . 'UserGroup
WHERE PortalUserId = ' . $user_id;
$user_groups = $this->Conn->Query($sql, 'GroupId');
if ( !isset($user_groups[$group_id]) ) {
$expire = adodb_mktime() + $duration;
}
else {
$expire = $user_groups[$group_id]['MembershipExpires'];
$expire = $expire < adodb_mktime() ? adodb_mktime() + $duration : $expire + $duration;
}
/*// Customization healtheconomics.org
if ($item_data['DurationType'] == 2) {
$expire = $item_data['AccessExpiration'];
}
// Customization healtheconomics.org --*/
$fields_hash = Array (
'PortalUserId' => $user_id,
'GroupId' => $group_id,
'MembershipExpires' => $expire,
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'UserGroup', 'REPLACE');
$sub_order =& $this->Application->recallObject('ord.-sub'.$event->getEventParam('next_sub_number'), 'ord');
$sub_order->SetDBField('IsRecurringBilling', getArrayValue($item_data, 'IsRecurringBilling') ? 1 : 0);
$sub_order->SetDBField('GroupId', $group_id);
$sub_order->SetDBField('NextCharge_date', $expire);
$sub_order->SetDBField('NextCharge_time', $expire);
}
function OnDownloadableApprove(&$event)
{
$field_values = $event->getEventParam('field_values');
$product_id = $field_values['ProductId'];
$sql = 'SELECT PortalUserId FROM '.$this->Application->getUnitOption('ord', 'TableName').'
WHERE OrderId = '.$field_values['OrderId'];
$user_id = $this->Conn->GetOne($sql);
$sql = 'INSERT INTO '.TABLE_PREFIX.'UserFileAccess VALUES("", '.$product_id.', '.$user_id.')';
$this->Conn->Query($sql);
}
function OnPackageApprove(&$event){
$field_values = $event->getEventParam('field_values');
$item_data = unserialize($field_values['ItemData']);
$package_content_ids = $item_data['PackageContent'];
$object_item = &$this->Application->recallObject('p.packageitem', null, array('skip_autoload'=>true));
foreach ($package_content_ids as $package_item_id) {
$object_field_values = array();
// query processing data from product and run approve event
$sql = 'SELECT ProcessingData FROM '.TABLE_PREFIX.'Products WHERE ProductId = '.$package_item_id;
$processing_data = $this->Conn->GetOne($sql);
if($processing_data)
{
$processing_data = unserialize($processing_data);
$approve_event = new kEvent($processing_data['ApproveEvent']);
//$order_item_fields = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'OrderItems WHERE OrderItemId = '.$grouping_data[1]);
$object_item->Load($package_item_id);
$object_field_values['OrderId'] = $field_values['OrderId'];
$object_field_values['ProductId'] = $package_item_id;
$object_field_values['ItemData'] = serialize($item_data['PackageItemsItemData'][$package_item_id]);
$approve_event->setEventParam('field_values', $object_field_values);
$this->Application->HandleEvent($approve_event);
}
}
}
/**
- * Checks, that all required product options are filled in before product is saved
+ * Saves edited item into temp table
+ * If there is no id, new item is created in temp table
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnPreSave(&$event)
+ protected function OnPreSave(&$event)
{
$this->CheckRequiredOptions($event);
parent::OnPreSave($event);
}
/**
* Set new price to ProductsPricing
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnAfterItemCreate(&$event)
+ protected function OnAfterItemCreate(&$event)
{
parent::OnAfterItemCreate($event);
$this->_updateProductPrice($event);
}
/**
* Set new price to ProductsPricing
*
* @param kEvent $event
*/
function OnAfterItemUpdate(&$event)
{
parent::OnAfterItemUpdate($event);
$this->_updateProductPrice($event);
}
/**
* Updates product's primary price based on Price virtual field value
*
* @param kEvent $event
*/
function _updateProductPrice(&$event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$price = $object->GetDBField('Price');
// always create primary pricing, to show on Pricing tab (in admin) for tangible products
$force_create = ($object->GetDBField('Type') == PRODUCT_TYPE_TANGIBLE) && is_null($price);
if ($force_create || ($price != $object->GetOriginalField('Price'))) {
// new product OR price was changed in virtual field
$this->setPrimaryPrice($object->GetID(), (float)$price);
}
}
function CheckRequiredOptions(&$event)
{
$object =& $event->getObject();
if ($object->GetDBField('ProductId') == '') return ; // if product does not have ID - it's not yet created
$opt_object =& $this->Application->recallObject('po', null, Array('skip_autoload' => true) );
$has_required = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$opt_object->TableName.' WHERE Required = 1 AND ProductId = '.$object->GetDBField('ProductId'));
//we need to imitate data sumbit, as parent' PreSave sets object values from $items_info
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$items_info[$object->GetDBField('ProductId')]['HasRequiredOptions'] = $has_required ? '1' : '0';
$this->Application->SetVar($event->getPrefixSpecial(true), $items_info);
$object->SetDBField('HasRequiredOptions', $has_required ? 1 : 0);
}
/**
* Sets required price in primary price backed, if it's missing, then create it
*
* @param int $product_id
* @param double $price
* @param Array $additional_fields
* @return bool
*/
function setPrimaryPrice($product_id, $price, $additional_fields = Array())
{
$pr_object =& $this->Application->recallObject('pr.-item', null, Array('skip_autoload' => true) );
/* @var $pr_object kDBItem */
$pr_object->Load( Array('ProductId' => $product_id, 'IsPrimary' => 1) );
$sql = 'SELECT COUNT(*) FROM '.$pr_object->TableName.' WHERE ProductId = '.$product_id;
$has_pricings = $this->Conn->GetOne($sql);
if ($additional_fields) {
$pr_object->SetDBFieldsFromHash($additional_fields);
}
if( ($price === false) && $has_pricings ) return false;
if( $pr_object->isLoaded() )
{
$pr_object->SetField('Price', $price);
return $pr_object->Update();
}
else
{
$group_id = $this->Application->ConfigValue('User_LoggedInGroup');
$field_values = Array('ProductId' => $product_id, 'IsPrimary' => 1, 'MinQty' => 1, 'MaxQty' => -1, 'GroupId'=>$group_id);
$pr_object->SetDBFieldsFromHash($field_values);
$pr_object->SetField('Price', $price);
return $pr_object->Create();
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnAfterItemDelete(&$event)
{
$product_id = $event->getEventParam('id');
if(!$product_id)
{
return;
}
$sql = 'DELETE FROM '.TABLE_PREFIX.'UserFileAccess
WHERE ProductId = '.$product_id;
$this->Conn->Query($sql);
}
/**
* Load price from temp table if product mode is temp table
*
* @param kEvent $event
*/
- function OnAfterItemLoad(&$event)
+
+ /**
+ * Load price from temp table if product mode is temp table
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnAfterItemLoad(&$event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object ProductsItem */
$a_pricing = $object->getPrimaryPricing();
- if (!$a_pricing) {
+ if ( !$a_pricing ) {
// pricing doesn't exist for new products
$price = $cost = null;
}
else {
$price = (float)$a_pricing['Price'];
$cost = (float)$a_pricing['Cost'];
}
// set original fields to use them in OnAfterItemCreate/OnAfterItemUpdate later
$object->SetDBField('Price', $price);
$object->SetOriginalField('Price', $price);
$object->SetDBField('Cost', $cost);
$object->SetOriginalField('Cost', $cost);
}
/**
* Allows to add products to package besides all that parent method does
*
* @param kEvent $event
*/
function OnProcessSelected(&$event)
{
$dst_field = $this->Application->RecallVar('dst_field');
if ($dst_field == 'PackageContent') {
$this->OnAddToPackage($event);
}
elseif ($dst_field == 'AssignedCoupon') {
$coupon_id = $this->Application->GetVar('selected_ids');
$object =& $event->getObject();
$object->SetDBField('AssignedCoupon', $coupon_id);
$this->RemoveRequiredFields($object);
$object->Update();
}
else {
parent::OnProcessSelected($event);
}
$this->finalizePopup($event);
}
/**
* Called when some products are selected in products selector for this prefix
*
* @param kEvent $event
*/
function OnAddToPackage(&$event)
{
$selected_ids = $this->Application->GetVar('selected_ids');
// update current package content with selected products
$object =& $event->getObject();
/* @var $object ProductsItem */
$product_ids = $selected_ids['p'] ? explode(',', $selected_ids['p']) : Array();
if ($product_ids) {
$current_ids = $object->GetPackageContentIds();
$current_ids = array_unique(array_merge($current_ids, $product_ids));
// remove package product from selected list
$this_product = array_search($object->GetID(), $current_ids);
if ($this_product !== false) {
unset($current_ids[$this_product]);
}
$dst_field = $this->Application->RecallVar('dst_field');
$object->SetDBField($dst_field, '|'.implode('|', $current_ids).'|');
$object->Update();
$this->ProcessPackageItems($event);
}
$this->finalizePopup($event);
}
function ProcessPackageItems(&$event)
{
//$this->Application->SetVar('p_mode', 't');
$object =& $event->getObject();
/* @var $object ProductsItem */
$content_ids = $object->GetPackageContentIds();
if (sizeof($content_ids) > 0) {
$total_weight = $this->Conn->GetOne('SELECT SUM(Weight) FROM '.TABLE_PREFIX.'Products WHERE ProductId IN ('.implode(', ', $content_ids).') AND Type=1');
if (!$total_weight) $total_weight = 0;
$this->Conn->Query('UPDATE '.$object->TableName.' SET Weight='.$total_weight.' WHERE ProductId='.$object->GetID());
}
/*
$this->Application->SetVar('p_mode', false);
$list = &$this->Application->recallObject('p.content', 'p_List', array('types'=>'content'));
$this->Application->SetVar('p_mode', 't');
$list->Query();
$total_weight_a = 0;
$total_weight_b = 0;
$list->GoFirst();
while (!$list->EOL())
{
if ($list->GetDBField('Type')==1){
$total_weight_a += $list->GetField('Weight_a');
$total_weight_b += $list->GetField('Weight_b');
}
$list->GoNext();
}
$object->SetField('Weight_a', $total_weight_a);
$object->SetField('Weight_b', $total_weight_b);
*/
//$object->Update();
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSaveItems(&$event)
{
//$event->CallSubEvent('OnUpdate');
$event->redirect = false;
//$event->setRedirectParams(Array('opener'=>'s','pass'=>'all,p'), true);
}
/**
* Removes product from package
*
* @param kEvent $event
*/
function OnRemovePackageItem(&$event) {
$this->Application->SetVar('p_mode', 't');
$object =& $event->getObject();
$items_info = $this->Application->GetVar('p_content');
if($items_info)
{
$product_ids = array_keys($items_info);
$current_ids = $object->GetPackageContentIds();
$current_ids_flip = array_flip($current_ids);
foreach($product_ids as $key=>$val){
unset($current_ids_flip[$val]);
}
$current_ids = array_keys($current_ids_flip);
$current_ids_str = '|'.implode('|', array_unique($current_ids)).'|';
$object->SetDBField('PackageContent', $current_ids_str);
}
$object->Update();
$this->ProcessPackageItems($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemDelete(&$event){
$object = &$event->getObject();
$product_includes_in = $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'Products WHERE PackageContent LIKE "%|'.$object->GetID().'%"');
if ($product_includes_in > 0){
$event->status=kEvent::erFAIL;
}
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
*/
function getCustomExportColumns(&$event)
{
$columns = parent::getCustomExportColumns($event);
$new_columns = Array(
'__VIRTUAL__Price' => 'Price',
'__VIRTUAL__Cost' => 'Cost',
);
return array_merge($columns, $new_columns);
}
/**
* Sets non standart virtual fields (e.g. to other tables)
*
* @param kEvent $event
*/
function setCustomExportColumns(&$event)
{
parent::setCustomExportColumns($event);
$object =& $event->getObject();
$this->setPrimaryPrice($object->GetID(), (double)$object->GetDBField('Price'), Array('Cost' => (double)$object->GetDBField('Cost')) );
}
function OnPreSaveAndOpenPopup(&$event)
{
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
$event->redirect = $this->Application->GetVar('t');
// pass ID too, in case if product is created by OnPreSave call to ensure proper editing
$event->setRedirectParams( Array(
'pass' => 'all',
$event->getPrefixSpecial(true).'_id' => $object->GetID(),
), true);
}
function getPassedID(&$event)
{
$event->setEventParam('raise_warnings', 0);
$passed = parent::getPassedID($event);
if ($passed) {
return $passed;
}
if ($this->Application->isAdminUser) {
// we may get product id out of OrderItem, if it exists
$ord_item =& $this->Application->recallObject('orditems', null, Array ('raise_warnings' => 0));
if ($ord_item->GetDBField('ProductId')) {
$passed = $ord_item->GetDBField('ProductId');
}
}
return $passed;
}
function OnAfterConfigRead(&$event)
{
parent::OnAfterConfigRead($event);
if (!$this->Application->LoggedIn()) {
return ;
}
$user_id = $this->Application->RecallVar('user_id');
$sql = 'SELECT PrimaryGroupId
FROM ' . TABLE_PREFIX . 'PortalUser
WHERE PortalUserId = ' . $user_id;
$primary_group_id = $this->Conn->GetOne($sql);
if (!$primary_group_id) {
return;
}
$sub_select = ' SELECT pp.Price
FROM ' . TABLE_PREFIX . 'ProductsPricing AS pp
WHERE pp.ProductId = %1$s.ProductId AND GroupId = ' . $primary_group_id . '
ORDER BY MinQty
LIMIT 0,1';
$calculated_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
$calculated_fields['']['Price'] = 'IFNULL((' . $sub_select . '), ' . $calculated_fields['']['Price'] . ')';
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calculated_fields);
}
/**
* Starts product editing, remove any pending inventory actions
*
* @param kEvent $event
*/
function OnEdit(&$event)
{
$this->Application->RemoveVar('inventory_actions');
parent::OnEdit($event);
}
/**
* Adds "Shop Cart" tab on paid listing type editing tab
*
* @param kEvent $event
*/
function OnModifyPaidListingConfig(&$event)
{
$edit_tab_presets = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'EditTabPresets');
$edit_tab_presets['Default']['shopping_cart'] = Array ('title' => 'la_tab_ShopCartEntry', 't' => 'in-commerce/paid_listings/paid_listing_type_shopcart', 'priority' => 2);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'EditTabPresets', $edit_tab_presets);
}
/**
* [HOOK] Allows to add cloned subitem to given prefix
*
* @param kEvent $event
*/
function OnCloneSubItem(&$event)
{
parent::OnCloneSubItem($event);
if ($event->MasterEvent->Prefix == 'rev') {
$clones = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'Clones');
$subitem_prefix = $event->Prefix . '-' . $event->MasterEvent->Prefix;
$clones[$subitem_prefix]['ConfigMapping'] = Array (
'PerPage' => 'Comm_Perpage_Reviews',
'ReviewDelayInterval' => 'product_ReviewDelay_Value',
'ReviewDelayValue' => 'product_ReviewDelay_Interval',
);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'Clones', $clones);
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/affiliates/affiliates_tag_processor.php
===================================================================
--- branches/5.2.x/units/affiliates/affiliates_tag_processor.php (revision 14624)
+++ branches/5.2.x/units/affiliates/affiliates_tag_processor.php (revision 14625)
@@ -1,144 +1,166 @@
<?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 AffiliatesTagProcessor extends kDBTagProcessor {
/**
* Returns link to be placed on other sites
*
* @param Array $params
* @return string
*/
function GetAffiliateLink($params)
{
$object =& $this->getObject($params);
$params['affiliate'] = $object->GetDBField('AffiliateCode');
$params['prefix'] = '_FRONT_END_';
$params['index_file'] = 'index.php';
$params['__SSL__'] = 0;
$params['__NO_SID__'] = 1; // don't work
$link = $this->Application->ProcessParsedTag('m', 'Link', $params);
// remove env manually
return preg_replace('/(.*)\/index.php\?env=(.*?)&amp;(.*)/', '\\1/index.php?\\3', $link);
}
/**
* Returns link to be placed on other sites (for current user)
*
* @param Array $params
* @return string
*/
function GetUserAffiliateLink($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, array_merge($params, array('skip_autoload'=>true)) );
$object->Load(array('PortalUserId' => $this->Application->RecallVar('user_id')));
// return $this->GetAffiliateLink($params);
$params['index_file'] = 'index.php';
$params['affiliate'] = $object->GetDBField('AffiliateCode');
$params['__SSL__'] = 0;
$params['__NO_SID__'] = 1; // don't work
$link = $this->Application->ProcessParsedTag('m', 'Link', $params);
// remove env manually
return preg_replace('/(.*)\/index.php\?env=(.*?)&amp;(.*)/', '\\1/index.php?\\3', $link);
}
/**
- * Returns true if user is affiliate
+ * [Aggregated Tag] Returns true if user is affiliate
*
* @param Array $params
* @return bool
+ * @access protected
*/
- function User_IsAffiliate($params)
+ protected function User_IsAffiliate($params)
{
- $object =& $this->Application->recallObject($this->Prefix.'.user', $this->Prefix, Array('skip_autoload'=>true) );
- $object->Load( $this->Application->RecallVar('user_id'), 'PortalUserId' );
-
+ $object =& $this->Application->recallObject($this->Prefix . '.user');
+ /* @var $object kDBItem */
+
return $object->isLoaded();
}
- function User_AffiliateIsNotActive($params)
+ /**
+ * [Aggregated Tag] Checks, that affiliate record for current user exists and is active
+ *
+ * @param $params
+ * @return bool
+ * @access protected
+ */
+ protected function User_AffiliateIsActive($params)
{
- $object =& $this->Application->recallObject($this->Prefix.'.user', $this->Prefix, Array('skip_autoload'=>true) );
- $object->Load( $this->Application->RecallVar('user_id'), 'PortalUserId' );
+ $object =& $this->Application->recallObject($this->Prefix . '.user');
+ /* @var $object kDBItem */
- return $object->isLoaded() && ($object->GetDBField('Status') != 1);
+ return $object->isLoaded() && ($object->GetDBField('Status') == STATUS_ACTIVE);
}
/**
* Returns url for editing user from current record
*
* @param Array $params
* @return string
*/
function UserLink($params)
{
$object =& $this->getObject($params);
$user_id = $object->GetDBField('PortalUserId');
if ($user_id) {
$url_params = Array (
'm_opener' => 'd',
'u_mode' => 't',
'u_event' => 'OnEdit',
'u_id' => $user_id,
'pass' => 'all,u'
);
return $this->Application->HREF($params['edit_template'], '', $url_params);
}
}
function CurrentUserAffiliateField($params)
{
$object =& $this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix, array_merge($params, Array('skip_autoload' => true)) );
$object->Load( Array('PortalUserId'=>$this->Application->RecallVar('user_id')) );
return $object->GetField($this->SelectParam($params, 'field,name'));
}
function IsAffiliateOrRegisterAsAffiliateAllowed($params)
{
- $object =& $this->Application->recallObject($this->Prefix.'.user', $this->Prefix, Array('skip_autoload'=>true) );
- $object->Load( $this->Application->RecallVar('user_id'), 'PortalUserId' );
+ $object =& $this->Application->recallObject($this->Prefix . '.user');
+ /* @var $object kDBItem */
- return ($this->Application->ConfigValue('Comm_RegisterAsAffiliate') || $object->isLoaded()) ? 1 : 0;
+ return $this->Application->ConfigValue('Comm_RegisterAsAffiliate') || $object->isLoaded() ? 1 : 0;
}
/**
- * [AGGREGATED TAG] Checks if affilite registration is allowed
+ * [AGGREGATED TAG] Checks if affiliate registration is allowed
*
* @param Array $params
* @return int
*/
function AllowAffiliateRegistration($params)
{
return $this->Application->ConfigValue('Comm_RegisterAsAffiliate') ? 1 : 0;
}
function Main_RequireAffiliate($params)
{
$t = $params['registration_template'];
- if( !$this->User_IsAffiliate($params) )
- {
- $redirect_params = Array( 'next_template' => $this->Application->GetVar('t') );
+
+ if ( !$this->User_IsAffiliate($params) ) {
+ $redirect_params = Array ('next_template' => $this->Application->GetVar('t'));
$this->Application->Redirect($t, $redirect_params);
}
}
+
+ /**
+ * Calls OnNew event from template, when no other event submitted
+ *
+ * @param Array $params
+ */
+ function PresetFormFields($params)
+ {
+ $prefix = $this->getPrefixSpecial();
+
+ if ( !$this->Application->GetVar($prefix . '_event') && !$this->Application->GetVar('u.register_event') ) {
+ $this->Application->HandleEvent(new kEvent($prefix . ':OnNew'));
+ }
+ }
}
\ No newline at end of file
Index: branches/5.2.x/units/taxesdestinations/taxes_dst_event_handler.php
===================================================================
--- branches/5.2.x/units/taxesdestinations/taxes_dst_event_handler.php (revision 14624)
+++ branches/5.2.x/units/taxesdestinations/taxes_dst_event_handler.php (revision 14625)
@@ -1,161 +1,169 @@
<?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 TaxDstEventHandler extends kDBEventHandler {
/**
* Saves items
*
* @param kEvent $event
*/
function OnSaveDestinations(&$event){
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$tax_object =& $this->Application->recallObject('tax');
$std_dest_id=$this->Application->GetVar('StatesCountry');
if($items_info)
{
$taxdest =& $this->Application->recallObject($event->getPrefixSpecial(true), null);
$parent_info=&$object->GetLinkedInfo();
$queryDel="DELETE FROM ".$object->TableName." WHERE TaxZoneId=".$parent_info['ParentId'];
$this->Conn->Query($queryDel);
foreach($items_info as $id => $field_values)
{
if($tax_object->GetDBField('Type') == 3 && (!$field_values['DestValue'] || $field_values['DestValue']=='')){
continue;
}
if (!$field_values['StdDestId']){
$field_values['StdDestId']=$std_dest_id;
}
$field_values['TaxZoneId']=$parent_info['ParentId'];
if ($taxdest->Load($field_values['TaxZoneDestId'], "TaxZoneDestId")){
$taxdest->SetFieldsFromHash($field_values);
$taxdest->Update($field_values['TaxZoneDestId']);
}else{
$taxdest->SetFieldsFromHash($field_values);
$taxdest->Create($field_values['TaxZoneDestId']);
}
}
}
}
/**
* Creates item from submit data
*
* @param kEvent $event
*/
function OnCreate(&$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->SetFieldsFromHash($field_values);
$this->customProcessing($event,'before');
if ( $object->Create() ) {
$this->customProcessing($event,'after');
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
$this->Application->SetVar($event->getPrefixSpecial().'_SaveEvent','OnCreate');
$object->setID(0);
}
}
}
}
- function customProcessing(&$event, $type)
+ /**
+ * Apply custom processing to item
+ *
+ * @param kEvent $event
+ * @param string $type
+ * @return void
+ * @access protected
+ */
+ protected function customProcessing(&$event, $type)
{
switch($type)
{
case 'before':
$object =& $event->getObject();
$events = $this->Application->GetVar('events');
if($events['tax'] == 'OnUpdate')
{
$object->SetDBField('TaxZoneId', $this->Application->GetVar('tax_id'));
}
$tax_object =& $this->Application->recallObject('tax');
if($tax_object->GetDBField('Type') == 3)
{
$tax_object->SetDBField('StdDestId', $this->Application->GetVar('StatesCountry'));
}
break;
default:
}
}
/**
*
*
* @param kEvent $event
*/
function OnZoneUpdate(&$event) {
$object = &$event->getObject();
$zone_object = &$this->Application->recallObject('tax');
$zone_id = (int)$this->Application->GetVar('tax_id');
$zone_type = $zone_object->GetDBField('Type');
$delete_zones_sql = 'DELETE FROM '.$object->TableName.' WHERE TaxZoneId = '.$zone_id;
$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 ($tax_dest_id, $dest_value) = explode('|', $dest_id);
$dest_id = $this->Application->GetVar('CountrySelector');
}
else {
$dest_value = '';
}
if ($dest_id > 0){
$object->SetDBField('TaxZoneId', $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/discounts/discounts_event_handler.php
===================================================================
--- branches/5.2.x/units/discounts/discounts_event_handler.php (revision 14624)
+++ branches/5.2.x/units/discounts/discounts_event_handler.php (revision 14625)
@@ -1,28 +1,58 @@
<?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 DiscountsEventHandler extends kDBEventHandler {
- function OnBeforeItemUpdate(&$event)
+ /**
+ * Occurs before updating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemUpdate(&$event)
{
- $object =& $event->getObject();
- $object->SetDBField( 'Amount', abs($object->GetDBField('Amount')) );
+ parent::OnBeforeItemUpdate($event);
+
+ $this->itemChanged($event);
+ }
+
+ /**
+ * Occurs before creating item
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnBeforeItemCreate(&$event)
+ {
+ parent::OnBeforeItemCreate($event);
+
+ $this->itemChanged($event);
}
- function OnBeforeItemCreate(&$event)
+ /**
+ * Occurs before item changed
+ *
+ * @param kEvent $event
+ */
+ function itemChanged(&$event)
{
- $this->OnBeforeItemUpdate($event);
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
+
+ $object->SetDBField('Amount', abs($object->GetDBField('Amount')));
}
}
\ No newline at end of file
Index: branches/5.2.x/units/order_items/order_items_event_handler.php
===================================================================
--- branches/5.2.x/units/order_items/order_items_event_handler.php (revision 14624)
+++ branches/5.2.x/units/order_items/order_items_event_handler.php (revision 14625)
@@ -1,233 +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 OrderItemsEventHandler extends kDBEventHandler
{
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnItemBuild' => Array ('subitem' => true),
'OnSaveItems' => Array ('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Processes item selection from popup item selector
*
* @param kEvent $event
*/
function OnProcessSelected(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$selected_ids = $this->Application->GetVar('selected_ids');
$product_ids = $selected_ids['p'];
if ($product_ids) {
//after adding Options Selection during adding products to order in admin, selector is in single mode
// = allows selecting one item at a time, but we leave this code just in case :)
$product_ids = explode(',', $product_ids);
$product_object =& $this->Application->recallObject('p.-item', null, array('skip_autoload' => true));
foreach ($product_ids as $product_id) {
$product_object->Load($product_id);
$sql = 'SELECT COUNT(*)
FROM ' . $this->Application->getUnitOption('po', 'TableName') . '
WHERE (Required = 1) AND (ProductId = ' . $product_id . ')';
if ( $this->Conn->GetOne($sql) ) {
$url_params = Array (
$event->Prefix . '_event' => 'OnNew',
'p_id' => $product_id,
'm_opener' => 's',
);
$this->Application->EventManager->openerStackPush('in-commerce/orders/order_product_edit', $url_params, 'm,ord,p');
}
else {
$orders_h =& $this->Application->recallObject('ord_EventHandler');
/* @var $orders_h OrdersEventHandler */
// 1 for PacakgeNum - temporary solution to overcome splitting into separate sub-orders
// of orders with items added through admin when approving them
$orders_h->AddItemToOrder($event, $product_id, null, 1);
}
}
}
$this->finalizePopup($event);
}
/**
* Updates subtotal field in order record.
* Only for "Items" tab in "Orders -> Order Edit" in Admin
*
* @param kEvent $event
*/
function OnUpdate(&$event)
{
parent::OnUpdate($event);
if ( ($this->Application->GetVar('t') != 'in-commerce/orders/orders_edit_items') ) {
return true;
}
$object =& $event->getObject();
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if (!$items_info) {
return ;
}
$sub_total = $this->getSubTotal($items_info);
$return_total = $this->getReturnTotal($items_info);
$table_info = $object->getLinkedInfo();
$main_object =& $this->Application->recallObject($table_info['ParentPrefix']);
if ($sub_total !== false) {
$main_object->SetDBField('SubTotal', $sub_total);
}
$main_object->SetDBField('ReturnTotal', $return_total);
$main_object->Update();
}
/**
* Returns subtotal
*
* @param Array $items_info
* @return float
*/
function getSubTotal($items_info)
{
$sub_total = 0;
foreach ($items_info as $id => $field_values) {
if (!array_key_exists('Price', $field_values)) {
return false;
}
$sub_total += $field_values['Quantity'] * $field_values['Price'];
}
return $sub_total;
}
/**
* Returns total returned amount (refund)
*
* @param Array $items_info
* @return float
*/
function getReturnTotal($items_info)
{
$return_total = 0;
foreach ($items_info as $id => $field_values) {
$return_total += $field_values['ReturnAmount'];
}
return $return_total;
}
/**
* Saves selected items
*
* @param kEvent $event
*/
function OnSaveItems(&$event)
{
$event->CallSubEvent('OnUpdate');
$event->redirect = false;
$event->setRedirectParams(Array('opener'=>'s','pass'=>'all'), true);
}
/**
* Occures after an item has been cloned
* Id of newly created item is passed as event' 'id' param
*
* @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');
$sql = 'UPDATE '.$table.' SET QuantityReserved = NULL WHERE '.$id_field.' = '.$id;
$this->Conn->Query($sql);
}
- function OnAfterItemLoad(&$event)
+ /**
+ * Occurs after loading item, 'id' parameter
+ * allows to get id of item that was loaded
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ */
+ protected function OnAfterItemLoad(&$event)
{
+ parent::OnAfterItemLoad($event);
+
$object =& $event->getObject();
- if( $item_info = $object->GetDBField('ItemData') )
- {
+ /* @var $object kDBItem */
+
+ if ( $item_info = $object->GetDBField('ItemData') ) {
$item_info = unserialize($item_info);
$object->SetDBField('DiscountType', getArrayValue($item_info, 'DiscountType'));
$object->SetDBField('DiscountId', getArrayValue($item_info, 'DiscountId'));
}
}
- function SetCustomQuery(&$event)
+ /**
+ * Apply any custom changes to list's sql query
+ *
+ * @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
+ */
+ protected function SetCustomQuery(&$event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
$package_num = $event->getEventParam('package_num');
if ($package_num) $object->addFilter('package_num', 'PackageNum = '.$package_num);
$type = $event->getEventParam('product_type');
if ($type) {
$object->addFilter('product_type', 'p.Type ='.$type);
}
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
*/
function checkItemStatus(&$event)
{
if ($this->Application->IsAdmin()) {
return true;
}
$object =& $event->getObject();
if (!$object->isLoaded()) {
return true;
}
$order =& $this->Application->recallObject('ord');
/* @var $order kDBItem */
if ($order->isLoaded() && ($order->GetID() == $object->GetDBField('OrderId'))) {
return $order->GetDBField('PortalUserId') == $this->Application->RecallVar('user_id');
}
return false;
}
}
\ No newline at end of file
Index: branches/5.2.x/units/addresses/addresses_event_handler.php
===================================================================
--- branches/5.2.x/units/addresses/addresses_event_handler.php (revision 14624)
+++ branches/5.2.x/units/addresses/addresses_event_handler.php (revision 14625)
@@ -1,338 +1,351 @@
<?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...
+ * Apply any custom changes to list's sql query
*
* @param kEvent $event
+ * @return void
+ * @access protected
+ * @see kDBEventHandler::OnListBuild()
*/
- function SetCustomQuery(&$event)
+ protected 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
+ * @return void
+ * @access protected
*/
- function OnBeforeItemUpdate(&$event)
+ protected function OnBeforeItemUpdate(&$event)
{
+ parent::OnBeforeItemUpdate($event);
+
$object =& $event->getObject();
/* @var $object kDBItem */
- if (!$object->isLoaded() || !$this->checkItemStatus($event)) {
+ if ( !$object->isLoaded() || !$this->checkItemStatus($event) ) {
// not trivially loaded object OR not current user address
$event->status = kEvent::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)
{
parent::OnUpdate($event);
$this->setNextTemplate($event);
}
/**
* Creates new user
*
* @param kEvent $event
*/
function OnCreate(&$event)
{
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;
}
}
/**
* Fills states for object country
*
* @param kEvent $event
+ * @return void
+ * @access protected
*/
- function OnAfterItemLoad(&$event)
+ protected function OnAfterItemLoad(&$event)
{
parent::OnAfterItemLoad($event);
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$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
+ * @return void
+ * @access protected
*/
- function OnBeforeItemCreate(&$event)
+ protected function OnBeforeItemCreate(&$event)
{
- if (!$this->Application->LoggedIn()) {
+ parent::OnBeforeItemCreate($event);
+
+ if ( !$this->Application->LoggedIn() ) {
$event->status = kEvent::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 = kEvent::erPERM_FAIL;
return ;
}
}
/**
* Sets default country for new addresses to Latvia
*
* @param kEvent $event
*/
function OnAfterConfigRead(&$event)
{
parent::OnAfterConfigRead($event);
$site_helper =& $this->Application->recallObject('SiteHelper');
/* @var $site_helper SiteHelper */
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$fields['Country']['default'] = $site_helper->getDefaultCountry('Shipping');
$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
}
}
\ No newline at end of file

Event Timeline