Page MenuHomeIn-Portal Phabricator

in-commerce
No OneTemporary

File Metadata

Created
Mon, Jan 6, 12:23 AM

in-commerce

This file is larger than 256 KB, so syntax highlighting was skipped.
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 15133)
+++ branches/5.2.x/units/affiliate_plans/affiliate_plans_event_handler.php (revision 15134)
@@ -1,127 +1,127 @@
<?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 {
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
if ( $event->Special == 'active' ) {
$object =& $event->getObject();
/* @var $object kDBList */
$object->addFilter('active', '%1$s.Enabled = 1');
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnSetPrimary(&$event)
+ function OnSetPrimary($event)
{
$object =& $event->getObject();
$object->SetDBField('IsPrimary', 1);
$object->Update();
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->itemChanged($event);
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->itemChanged($event);
}
/**
* Occurs before item is changed
*
* @param kEvent $event
*/
- function itemChanged(&$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);
}
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'));
$object->SetDBField($status_field, 1);
}
}
/**
* Don't allow to delete primary affiliate plan
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
$ids = $event->getEventParam('ids');
$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));
$event->setEventParam('ids', $ids);
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/affiliate_plans_items/affiliate_plans_items_event_handler.php
===================================================================
--- branches/5.2.x/units/affiliate_plans_items/affiliate_plans_items_event_handler.php (revision 15133)
+++ branches/5.2.x/units/affiliate_plans_items/affiliate_plans_items_event_handler.php (revision 15134)
@@ -1,94 +1,94 @@
<?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!');
// NOT IN USE RIGHT NOW (by Alex)
class AffiliatePlansItemsEventHandler extends kDBEventHandler {
/**
* Adds selected items to affiliate products
*
* @param kEvent $event
*/
- function OnProcessSelected(&$event)
+ function OnProcessSelected($event)
{
// uses another handler event, because does the same stuff but on different table
$di_handler =& $this->Application->recallObject('di_EventHandler');
$di_handler->OnProcessSelected($event);
}
/**
* Allows to set discount on entire order
*
* @param kEvent $event
* @todo get parent item id through $object->getLinkedInfo()['ParentId']
* @access public
*/
- function OnEntireOrder(&$event)
+ function OnEntireOrder($event)
{
$object =& $event->GetObject();
$sql = 'DELETE FROM '.$object->TableName.' WHERE AffiliatePlanId='.$this->Application->GetVar('ap_id');
$this->Conn->Query($sql);
$object->SetDBField('AffiliatePlanId', $this->Application->GetVar('ap_id'));
$object->SetDBField('ItemResourceId', -1);
$object->SetDBField('ItemType', 0);
if ( $object->Create() ) {
$this->customProcessing($event, 'after');
$event->status = kEvent::erSUCCESS;
$event->SetRedirectParam('opener', 's'); //stay!
}
else {
$event->status = kEvent::erFAIL;
$this->Application->SetVar($event->getPrefixSpecial().'_SaveEvent','OnCreate');
$object->setID(0);
}
}
/**
* Deletes discount items where hooked item (product) is used
*
* @param kEvent $event
*/
- function OnDeleteDiscountedItem(&$event)
+ function OnDeleteDiscountedItem($event)
{
$main_object =& $event->MasterEvent->getObject();
$resource_id = $main_object->GetDBField('ResourceId');
$table = $this->Application->getUnitOption($event->Prefix,'TableName');
$sql = 'DELETE FROM '.$table.' WHERE ItemResourceId = '.$resource_id;
$this->Conn->Query($sql);
}
/**
* Makes ItemName calculated field from primary language
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
$calculated_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
$language_id = $this->Application->GetVar('m_lang');
$primary_language_id = $this->Application->GetDefaultLanguageId();
$calculated_fields['']['ItemName'] = 'COALESCE(p.l' . $language_id . '_Name, p.l' . $primary_language_id . '_Name)';
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calculated_fields);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/gateways/gw_event_handler.php
===================================================================
--- branches/5.2.x/units/gateways/gw_event_handler.php (revision 15133)
+++ branches/5.2.x/units/gateways/gw_event_handler.php (revision 15134)
@@ -1,85 +1,85 @@
<?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 GatewayEventHandler extends kDBEventHandler {
- function OnSaveValues(&$event)
+ function OnSaveValues($event)
{
// if there is no id - it means we need to create an item
$item_id = $this->getPassedID($event);
$event->setPseudoClass('_List');
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$PaymentType_info = $this->Application->GetVar( 'pt' );
$GWConfigValue =& $this->Application->recallObject('gwfv');
$GWConfigValue->SetDBField('PaymentTypeId', $this->Application->GetVar('pt_id'));
//deleting old values
$sql = 'DELETE FROM '.$GWConfigValue->TableName.' WHERE PaymentTypeId = '.$this->Application->GetVar('pt_id');
$res = $this->Conn->Query($sql);
//selecting fields for selected gateway only
$sql = 'SELECT GWConfigFieldId FROM '.TABLE_PREFIX.'GatewayConfigFields
WHERE GatewayId = '.$PaymentType_info[$this->Application->GetVar('pt_id')]['GatewayId'];
$res = $this->Conn->GetCol($sql);
if($items_info)
{
foreach($res as $gw_field_id)
{
$field_values = $items_info[$gw_field_id];
$field_values['GWConfigFieldId'] = $gw_field_id;
$GWConfigValue->SetFieldsFromHash($field_values);
if( $GWConfigValue->Create() )
{
$event->status=kEvent::erSUCCESS;
}
else
{
$event->status=kEvent::erFAIL;
break;
}
}
}
}
- protected function OnCheckGateways(&$event)
+ protected function OnCheckGateways($event)
{
if ( !$this->Application->isAdminUser ) {
return;
}
$gateways = glob(GW_CLASS_PATH . DIRECTORY_SEPARATOR . '*.php');
if ( !$gateways ) {
return;
}
foreach ($gateways as $gateway_file) {
$class_name = false;
include_once($gateway_file);
if ( !$class_name ) {
continue;
}
$tmp = new $class_name();
/* @var $tmp kGWBase */
$tmp->Install();
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/gateways/gw_classes/notify_scripts/google_checkout_notify.php
===================================================================
--- branches/5.2.x/units/gateways/gw_classes/notify_scripts/google_checkout_notify.php (revision 15133)
+++ branches/5.2.x/units/gateways/gw_classes/notify_scripts/google_checkout_notify.php (revision 15134)
@@ -1,51 +1,50 @@
<?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.
*/
define('ADMIN', 1);
define('FULL_PATH', realpath(dirname(__FILE__) . '/../../../../../..'));
include_once(FULL_PATH.'/core/kernel/startup.php');
$application =& kApplication::Instance();
$application->Init();
$sql = 'SELECT PaymentTypeId FROM '.TABLE_PREFIX.'PaymentTypes AS pt
LEFT JOIN '.TABLE_PREFIX.'Gateways AS g ON g.GatewayId = pt.GatewayId
WHERE g.ClassName = "kGWGoogleCheckout"';
$payment_type_id = $application->Conn->GetOne($sql);
$application->SetVar('payment_type_id', $payment_type_id); // keep, because kGWGoogleCheckout::processNewOrderNotification relies on this
$order =& $application->recallObject('ord', null, Array ('skip_autoload' => true));
/* @var $order OrdersItem */
$gw_data = $order->getGatewayData($application->GetVar('payment_type_id'));
$application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $application->recallObject( $gw_data['ClassName'] );
$transaction_status = $gateway_object->processNotification($gw_data['gw_params']);
$sql = 'UPDATE '.$order->TableName.'
SET TransactionStatus = '.$transaction_status.'
WHERE '.$order->IDField.' = '.$order->GetID();
$application->Conn->Query($sql);
$order->SetDBField('TransactionStatus', $transaction_status);
if ($transaction_status == 1) {
- $dummy_var = '10';
$application->SetVar('ord_id', $order->GetID()); // used in OrdersEventHandler::UpdateOrderItem
- $application->HandleEvent($dummy_var, 'ord:OnCompleteOrder');
+ $application->HandleEvent(new kEvent('ord:OnCompleteOrder'));
}
$application->Done();
\ No newline at end of file
Index: branches/5.2.x/units/gateways/gw_classes/paypal.php
===================================================================
--- branches/5.2.x/units/gateways/gw_classes/paypal.php (revision 15133)
+++ branches/5.2.x/units/gateways/gw_classes/paypal.php (revision 15134)
@@ -1,268 +1,268 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
require_once GW_CLASS_PATH.'/gw_base.php';
class kGWPayPal extends kGWBase
{
/**
* Returns payment form submit url
*
* @param Array $gw_params gateway params from payment type config
* @return string
*/
function getFormAction($gw_params)
{
return $gw_params['submit_url'];
}
/**
* Processed input data and convets it to fields understandable by gateway
*
* @param Array $item_data
* @param Array $tag_params additional params for gateway passed through tag
* @param Array $gw_params gateway params from payment type config
* @return Array
*/
function getHiddenFields($item_data, $tag_params, $gw_params)
{
$ret = Array();
$ret['item_name'] = 'Order #'.$item_data['OrderNumber'];
$ret['item_number'] = 'order:'.$item_data['OrderNumber'];
$selected_cur = $this->Application->RecallVar('curr_iso');
$available = explode(',', $gw_params['currency_code']);
$target = in_array($selected_cur, $available) ? $selected_cur : $available[0];
if( !$this->IsTestMode() )
{
$currency_iso = $gw_params['currency_code'];
$ret['amount'] = $this->ConvertCurrency($item_data['SubTotal'], $target);
$ret['shipping'] = $this->ConvertCurrency($item_data['ShippingCost'], $target);
$ret['tax'] = $this->ConvertCurrency($item_data['VAT'], $target);
}
else
{
$ret['amount'] = 1;
$ret['shipping'] = 0;
$ret['tax'] = 0;
}
$ret['quantity'] = 1;
$ret['cancel_return'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));
$ret['return'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
$ret['no_note'] = 1; // customer is not prompted for notes
$ret['no_shipping'] = 1; // customer is not prompted for shipping address
$ret['rm'] = 2; // return method - POST
$ret['currency_code'] = $target;
$ret['invoice'] = $item_data['OrderNumber'];
$ret['business'] = $gw_params['business_account'];
// prepopulated fields
$ret['address_override'] = 1; // override user's stored address
$ret['email'] = $item_data['BillingEmail'];
list($first_name, $last_name) = explode(' ', $item_data['BillingTo']);
$ret['first_name'] = $first_name;
$ret['last_name'] = $last_name;
$ret['address1'] = $item_data['BillingAddress1'];
$ret['address2'] = $item_data['BillingAddress2'];
$ret['city'] = $item_data['BillingCity'];
$ret['state'] = $item_data['BillingState'];
$ret['zip'] = $item_data['BillingZip'];
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$ret['country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$ret['notify_url'] = $this->getNotificationUrl() . '?sid=' . $this->Application->GetSID() . '&admin=1&order_id=' . $item_data['OrderId'];
$ret['cmd'] = '_xclick'; // act as "Buy Now" PayPal button
return $ret;
}
function getSubscriptionFields($item_data, $tag_params, $gw_params)
{
$ret = Array();
$ret['item_name'] = $item_data['item_name'];
$ret['item_number'] = $item_data['item_number'];
$ret['a1'] = $item_data['a1'];
$ret['p1'] = $item_data['p1'];
$ret['t1'] = $item_data['t1'];
$ret['a2'] = $item_data['a2'];
$ret['p2'] = $item_data['p2'];
$ret['t2'] = $item_data['t2'];
$ret['p3'] = $item_data['p3'];
$ret['t3'] = $item_data['t3'];
$ret['src'] = $item_data['src'];
$ret['sra'] = $item_data['sra'];
$ret['srt'] = $item_data['srt'];
$ret['custom'] = $item_data['OrderId'];
$currency_iso = $gw_params['currency_code'];
$ret['a3'] = $this->ConvertCurrency($item_data['a3'], $currency_iso);;
$ret['tax'] = $this->ConvertCurrency($item_data['VAT'], $currency_iso);
if( $this->Application->isDebugMode() )
{
}
else
{
}
// $ret['quantity'] = 1;
$ret['cancel_return'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));
$ret['return'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
$ret['no_note'] = 1; // customer is not prompted for notes
$ret['no_shipping'] = 1; // customer is not prompted for shipping address
$ret['rm'] = 2; // return method - POST
$ret['currency_code'] = $gw_params['currency_code'];
$ret['invoice'] = $item_data['OrderNumber'];
$ret['business'] = $gw_params['business_account'];
// prepopulated fields
$ret['address_override'] = 1; // override user's stored address
$ret['email'] = $item_data['BillingEmail'];
list($first_name, $last_name) = explode(' ', $item_data['BillingTo']);
$ret['first_name'] = $first_name;
$ret['last_name'] = $last_name;
$ret['address1'] = $item_data['BillingAddress1'];
$ret['address2'] = $item_data['BillingAddress2'];
$ret['city'] = $item_data['BillingCity'];
$ret['state'] = $item_data['BillingState'];
$ret['zip'] = $item_data['BillingZip'];
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$ret['country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
$ret['notify_url'] = $this->getNotificationUrl() . '?sid='.$this->Application->GetSID().'&admin=1&order_id='.$item_data['OrderId'].'&payment_type_id='.$tag_params['payment_type_id'];
$ret['cmd'] = '_xclick-subscriptions'; // act as "Buy Now" PayPal button
$real_ret = array();
foreach ($ret as $key => $val)
{
if ($val == '') continue;
$real_ret[$key] = $val;
}
return $real_ret;
}
function processNotification($gw_params)
{
$payment_status = $_POST['payment_status']; // save payment_status for later proceeding
$_POST['cmd'] = '_notify-validate';
// status, of that PayPal server really has sent such notification to us
$status_map = Array('INVALID' => 0, 'VERIFIED' => 1);
$curl_helper =& $this->Application->recallObject('CurlHelper');
/* @var $curl_helper kCurlHelper */
$curl_helper->SetPostData($_POST);
$n_status = $curl_helper->Send($gw_params['submit_url']); // INVALID, VERIFIED
$n_status = $status_map[$n_status];
$success = ($n_status == 1) && ($payment_status == 'Completed') ? 1:0 ; // 1:0 is on purpose, false will result an SQL error !
if (!$success) return;
$type = $_POST['txn_type'];
switch ($type)
{
case 'subscr_signup':
break;
case 'subscr_cancel':
break;
case 'subscr_failed':
break;
case 'subscr_payment':
$field_values = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'OrderItems WHERE OrderItemId = '.$_POST['item_number']);
- $this->Application->HandleEvent($an_event, 'p:OnSubscriptionApprove', array('field_values' => $field_values));
+ $this->Application->HandleEvent(new kEvent('p:OnSubscriptionApprove', array('field_values' => $field_values)));
$success = 0; //this will eliminate OnCompleteOrder in gw_notify!
$org_order = $this->Application->recallObject('ord.-original', 'ord', Array('skip_autoload' => true));
/* @var $org_order kDBItem */
$org_order->Load($field_values['OrderId']);
$order = $this->Application->recallObject('ord.-paypal', 'ord');
$order->SetDBFieldsFromHash($org_order->GetFieldValues());
$order->SetDBField('SubTotal', $field_values['Price']);
$order->SetDBField('OriginalAmout', $field_values['Price']);
$order->SetDBField('OrderDate', adodb_mktime());
$order->UpdateFormattersSubFields();
$dup_item = false;
if ($org_order->GetDBField('Status') >= ORDER_STATUS_PROCESSED) {
$sql = 'SELECT MAX(SubNumber) FROM '.TABLE_PREFIX.'Orders WHERE Number = '.$org_order->GetDBField('Number');
$num = $this->Conn->GetOne($sql) + 1;
$order->SetDBField('SubNumber', $num);
$dup_item = true;
}
else {
$sql = 'SELECT MAX(Number) FROM '.TABLE_PREFIX.'Orders';
$num = $this->Conn->GetOne($sql) + 1;
$order->SetDBField('Number', $num);
$order->SetDBField('SubNumber', 0);
}
$order->SetDBField('PaymentType', $this->Application->GetVar('payment_type_id'));
$info = array(
'BillingTo' => $_POST['first_name'].' '.$_POST['last_name'],
'BillingCompany' => 'n/a (PayPal)',
'BillingPhone' => 'n/a (PayPal)',
'BillingFax' => '',
'BillingEmail' => $_POST['payer_email'],
'BillingAddress1' => 'n/a (PayPal)',
'BillingCity' => 'n/a (PayPal)',
'BillingState' => 'n/a (PayPal)',
'BillingZip' => 'n/a (PayPal)',
'BillingCountry' => '???',
);
$order->SetFieldsFromHash($info);
$order->SetDBField('Status', ORDER_STATUS_PROCESSED);
$order->Create();
if ($dup_item) {
$query = 'INSERT INTO '.TABLE_PREFIX.'OrderItems
(OrderId, ProductId, ProductName, Quantity, QuantityReserved, FlatPrice, Price, BackOrderFlag, Weight, ShippingTypeId, ItemData, OptionsSalt)
SELECT
'.$order->GetId().' AS OrderId, ProductId, ProductName, Quantity, QuantityReserved, FlatPrice, Price, BackOrderFlag, Weight, ShippingTypeId, ItemData, OptionsSalt
FROM '.TABLE_PREFIX.'OrderItems
WHERE OrderItemId = '.$field_values['OrderItemId'];
}
else {
$query = 'UPDATE '.TABLE_PREFIX.'OrderItems SET OrderId = %s WHERE OrderItemId = %s';
$query = sprintf($query, $order->GetId(), $field_values['OrderItemId']);
}
$this->Conn->Query($query);
break;
case 'subscr_eot':
break;
case 'subscr_modify':
break;
}
return $success;
}
}
\ No newline at end of file
Index: branches/5.2.x/units/sections/section_eh.php
===================================================================
--- branches/5.2.x/units/sections/section_eh.php (revision 15133)
+++ branches/5.2.x/units/sections/section_eh.php (revision 15134)
@@ -1,101 +1,101 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2010 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 InCommerceEventHandler extends kEventHandler {
/**
* [HOOK] Creates site domain editing tab
*
* @param kEvent $event
*/
- function OnModifySiteDomainConfig(&$event)
+ function OnModifySiteDomainConfig($event)
{
$edit_tab_presets = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'EditTabPresets');
$edit_tab_presets['Default']['in-commerce'] = Array (
'title' => 'la_title_In-Commerce', 't' => 'in-commerce/site_domains/site_domain_edit', 'priority' => 2.1
);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'EditTabPresets', $edit_tab_presets);
$title_presets = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'TitlePresets');
$title_presets['site_domain_edit_in_commerce'] = Array (
'prefixes' => Array ('site-domain'), 'format' => "#site-domain_status# '#site-domain_titlefield#' - !la_title_In-Commerce!",
'toolbar_buttons' => Array ('select', 'cancel', 'reset_edit', 'prev', 'next'),
);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'TitlePresets', $title_presets);
$new_fields = Array (
'BillingCountry' => Array (
'type' => 'string', 'max_len' => 3,
'formatter' => 'kOptionsFormatter',
'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
FROM ' . TABLE_PREFIX . 'CountryStates
WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
ORDER BY Name',
'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => ''
),
'ShippingCountry' => Array (
'type' => 'string', 'max_len' => 3,
'formatter' => 'kOptionsFormatter',
'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
FROM ' . TABLE_PREFIX . 'CountryStates
WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
ORDER BY Name',
'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => ''
),
'PrimaryCurrencyId' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM ' . TABLE_PREFIX . 'Currencies WHERE Status = 1 ORDER BY ISO', 'option_key_field' => 'CurrencyId', 'option_title_field' => 'Name', 'use_phrases' => 1,
'not_null' => 1, 'default' => 0
),
'Currencies' => Array (
'type' => 'string', 'max_len' => 255,
'formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM ' . TABLE_PREFIX . 'Currencies WHERE Status = 1 ORDER BY ISO', 'option_key_field' => 'CurrencyId', 'option_title_field' => 'Name', 'use_phrases' => 1,
'not_null' => 1, 'default' => ''
),
'PrimaryPaymentTypeId' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM ' . TABLE_PREFIX . 'PaymentTypes WHERE Status = 1 ORDER BY Name ASC', 'option_key_field' => 'PaymentTypeId', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => 0
),
'PaymentTypes' => Array (
'type' => 'string', 'max_len' => 255,
'formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM ' . TABLE_PREFIX . 'PaymentTypes WHERE Status = 1 ORDER BY Name ASC', 'option_key_field' => 'PaymentTypeId', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => ''
),
);
$fields = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'Fields');
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'Fields', array_merge($fields, $new_fields));
$new_columns = Array (
'BillingCountry' => Array ('filter_block' => 'grid_options_filter', 'width' => 250, ),
'ShippingCountry' => Array ('filter_block' => 'grid_options_filter', 'width' => 250, ),
'PrimaryCurrencyId' => Array ('title' => 'column:la_fld_Currency', 'filter_block' => 'grid_options_filter', 'width' => 250, ),
'PrimaryPaymentTypeId' => Array ('title' => 'column:la_fld_PaymentType', 'filter_block' => 'grid_options_filter', 'width' => 250, ),
);
$grids = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'Grids');
$grids['Default']['Fields'] = array_merge($grids['Default']['Fields'], $new_columns);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'Grids', $grids);
if (!$this->Application->isAdmin && is_object($this->Application->siteDomain)) {
// re-configure object, because it's recalled before kUnitConfigReader::AfterConfigRead is called
$this->Application->siteDomain->Configure();
}
}
}
Index: branches/5.2.x/units/downloads/downloads_config.php
===================================================================
--- branches/5.2.x/units/downloads/downloads_config.php (revision 15133)
+++ branches/5.2.x/units/downloads/downloads_config.php (revision 15134)
@@ -1,114 +1,114 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array(
'Prefix' => 'down',
'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'),
'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'),
'EventHandlerClass' => Array('class'=>'kDBEventHandler','file'=>'','build_event'=>'OnBuild'),
'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'),
'RegisterClasses' => Array(
- Array('pseudo'=>'DownloadHelper','class'=>'DownloadHelper','file'=>'download_helper.php','build_event'=>'','require_classes'=>'kHelper'),
+ Array('pseudo' => 'DownloadHelper', 'class' => 'DownloadHelper', 'file' => 'download_helper.php', 'build_event' => ''),
),
'AutoLoad' => true,
'Hooks' => Array(
/*Array(
'Mode' => hBEFORE,
'Conditional' => true,
'HookToPrefix' => 'p',
'HookToSpecial' => '',
'HookToEvent' => Array( 'onPreSave' ),
'DoPrefix' => 'pr',
'DoSpecial' => 'tang',
'DoEvent' => 'OnArrange',
),*/
),
'QueryString' => Array(
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'TitlePresets' => Array(
'downloads_list'=>Array( 'prefixes' => Array('down_List'),
'format' => "!la_title_FileDownloads!",
),
),
'PermSection' => Array('main' => 'in-commerce:downloadlog'),
'Sections' => Array(
'in-commerce:downloadlog' => Array(
'parent' => 'in-portal:reports',
'icon' => 'download_log',
'label' => 'la_tab_DownloadLog',
'url' => Array('t' => 'in-commerce/downloads/downloads_list', 'pass' => 'm'),
'permissions' => Array('view', 'delete'),
'priority' => 7,
'type' => stTREE,
),
),
'IDField' => 'DownloadId',
'TitleField' => 'Name',
'TableName' => TABLE_PREFIX.'UserDownloads',
'ListSQLs' => Array( ''=>'SELECT * FROM %s',
), // key - special, value - list select sql
'ItemSQLs' => Array( ''=>'SELECT * FROM %s',
),
'ListSortings' => Array(
'' => Array(
'Sorting' => Array('StartedOn' => 'desc'),
)
),
'Fields' => Array(
'DownloadId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'PortalUserId' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'Username' => Array('type' => 'string','not_null' => 1, 'default' => ''),
'ProductId' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'ProductName' => Array('type' => 'string','not_null' => 1, 'default' => ''),
'FileId' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'Filename' => Array('type' => 'string','not_null' => 1, 'default' => ''),
'IPAddress' => Array('type' => 'string','not_null' => 1, 'default' => ''),
'StartedOn' => Array('type' => 'int','formatter' => 'kDateFormatter', 'default' => NULL),
'EndedOn' => Array('type' => 'int','formatter' => 'kDateFormatter', 'default' => NULL),
),
'VirtualFields' => Array(
),
'Grids' => Array(
'Default' => Array(
'Icons' => Array (
'default' => 'icon16_item.png',
0 => 'icon16_disabled.png',
1 => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array(
'DownloadId' => Array( 'title'=>'column:la_fld_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 60, ),
'Username' => Array( 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'ProductName' => Array( 'title'=>'la_col_DownloadedProductName', 'filter_block' => 'grid_like_filter', 'width' => 150, ),
'Filename' => Array( 'title'=>'la_col_DownloadedFileName', 'filter_block' => 'grid_like_filter', 'width' => 150, ),
'IPAddress' => Array( 'filter_block' => 'grid_like_filter', 'width' => 150, ),
'StartedOn' => Array( 'title'=>'la_col_StartedOn', 'filter_block' => 'grid_date_range_filter', 'width' => 150, ),
),
),
),
);
\ 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 15133)
+++ branches/5.2.x/units/product_options/product_options_event_handler.php (revision 15134)
@@ -1,110 +1,110 @@
<?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{
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
$selectable_only = $event->getEventParam('selectable_only');
if ( $selectable_only ) {
$object =& $event->getObject();
/* @var $object kDBList */
$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
* @return void
* @access protected
*/
- protected function OnAfterCopyToLive(kEvent &$event)
+ protected function OnAfterCopyToLive(kEvent $event)
{
parent::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');
$sql = 'SELECT *
FROM ' . $poc_table;
$combs = $this->Conn->Query($sql);
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);
$sql = 'UPDATE ' . $poc_table . '
SET
Combination = ' . $this->Conn->qstr($n_combs) . ',
CombinationCRC = ' . $n_crc . '
WHERE CombinationId = ' . $a_comb['CombinationId'];
$this->Conn->Query($sql);
}
}
/**
* Occurs after 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 OnAfterClone(kEvent &$event)
+ protected function OnAfterClone(kEvent $event)
{
parent::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 15133)
+++ branches/5.2.x/units/pricing/pricing_event_handler.php (revision 15134)
@@ -1,522 +1,522 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2011 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!');
// include globals.php from current folder
kUtil::includeOnce(MODULES_PATH .'/in-commerce/units/pricing/globals.php');
class PricingEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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);
}
/**
* Define alternative event processing method names
*
* @return void
* @see kEventHandler::$eventMethods
* @access protected
*/
protected function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decline 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)
+ 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)
+ 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 => $field_values) {
if (in_array($item_id, $stored_ids)) { //if it's already exist
$object->Load($item_id);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_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($field_values, $this->getRequestProtectedFields($field_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);
}
}
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
$bracket =& $event->getObject();
/* @var $bracket kDBItem */
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;
}
}
- function OnArrangeBrackets(&$event, &$temp, &$bracket)
+ 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)
+ 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->SetRedirectParam('opener', 's');
}
/**
* Resets primary mark for other prices of given product, when current pricing is primary
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
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);
}
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $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);
if ( $object->GetDBField('IsPrimary') == 1 ) {
$sql = 'UPDATE ' . $object->TableName . '
SET IsPrimary = 0
WHERE ' . $table_info['ForeignKey'] . ' = ' . $table_info['ParentId'];
$this->Conn->Query($sql);
}
else {
$sql = 'SELECT COUNT(*)
FROM ' . $object->TableName . '
WHERE ' . $table_info['ForeignKey'] . ' = ' . $table_info['ParentId'];
$prices_qty = $this->Conn->GetOne($sql);
if ( $prices_qty == 0 ) {
$object->SetDBField('IsPrimary', 1);
}
}
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
$object =& $event->getObject();
/* @var $object kDBList */
if ( $this->Application->isAdminUser ) {
return;
}
if ( $this->Application->ConfigValue('Comm_PriceBracketCalculation') == 1 ) {
$sql = 'SELECT PrimaryGroupId
FROM ' . TABLE_PREFIX . 'Users
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/reports/reports_event_handler.php
===================================================================
--- branches/5.2.x/units/reports/reports_event_handler.php (revision 15133)
+++ branches/5.2.x/units/reports/reports_event_handler.php (revision 15134)
@@ -1,844 +1,844 @@
<?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 ReportsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
// user can view any form on front-end
'OnRunReport' => Array ('self' => 'view'),
'OnUpdateConfig' => Array ('self' => 'view'),
'OnChangeStatistics' => Array ('self' => 'view'),
'OnPieChart' => Array ('self' => 'view'),
'OnPrintChart' => Array ('self' => 'view'),
'OnExportReport' => Array ('self' => 'view'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
- function OnRunReport(&$event)
+ function OnRunReport($event)
{
$this->Application->LinkVar('reports_finish_t');
$progress_t = $this->Application->GetVar('progress_t');
$event->redirect = $progress_t;
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info) $field_values = array_shift($items_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
$object->UpdateFormattersMasterFields();
$field_values['offset'] = 0;
$table_name = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_SaleReport';
$field_values['table_name'] = $table_name;
$this->Conn->Query('DROP TABLE IF EXISTS '.$table_name);
$filter_value = '';
$from = $object->GetDBField('FromDateTime');
$to = $object->GetDBField('ToDateTime');
$day_seconds = 23 * 60 * 60 + 59 * 60 + 59;
if ($from && !$to) {
$to = $from + $day_seconds;
}
elseif (!$from && $to) {
$from = $to - $day_seconds;
}
if ($from && $to) {
$filter_value = 'AND o.OrderDate >= '.$from.' AND o.OrderDate <= '.$to;
}
$ebay_table_fields = '';
$ebay_joins = '';
$ebay_query_fields = '';
$user_id = $this->Application->RecallVar('user_id');
$sql = 'DELETE FROM '.TABLE_PREFIX.'UserPersistentSessionData
WHERE
PortalUserId = "'.$user_id.'"
AND VariableName LIKE \'rep_columns_%\'';
$this->Conn->Query($sql);
if ($this->Application->isModuleEnabled('in-auction'))
{
if (in_array($field_values['ReportType'], Array(1,5))) // not overall.
{
$ebay_table_fields = ',
StoreQty int(11) NOT NULL DEFAULT 0,
eBayQty int(11) NOT NULL DEFAULT 0,
StoreAmount double(10,4) NOT NULL DEFAULT 0,
eBayAmount double(10,4) NOT NULL DEFAULT 0,
StoreProfit double(10,4) NOT NULL DEFAULT 0,
eBayProfit double(10,4) NOT NULL DEFAULT 0';
$ebay_joins = '
LEFT JOIN '.TABLE_PREFIX.'eBayOrderItems AS eod
ON od.OptionsSalt = eod.OptionsSalt
';
$ebay_query_fields = ',
SUM(IF(ISNULL(eod.OptionsSalt), od.Quantity, 0)) as StoreQty,
SUM(IF(ISNULL(eod.OptionsSalt), 0, od.Quantity)) as eBayQty,
SUM(IF(ISNULL(eod.OptionsSalt), od.Price * od.Quantity, 0)) as StoreAmount,
SUM(IF(ISNULL(eod.OptionsSalt), 0, od.Price * od.Quantity)) as eBayAmount,
SUM(IF(ISNULL(eod.OptionsSalt), (od.Price - od.Cost) * od.Quantity, 0)) as StoreProfit,
SUM(IF(ISNULL(eod.OptionsSalt), 0, (od.Price - od.Cost) * od.Quantity)) as eBayProfit
';
}
}
if ($field_values['ReportType'] == 1) { // by Category
$q = 'CREATE TABLE '.$table_name.' (
CategoryId int(11) NOT NULL DEFAULT 0,
Qty int(11) NOT NULL DEFAULT 0,
Cost double(10,4) NOT NULL DEFAULT 0,
Amount double(10,4) NOT NULL DEFAULT 0,
Tax double(10,4) NOT NULL DEFAULT 0,
Shipping double(10,4) NOT NULL DEFAULT 0,
Processing double(10,4) NOT NULL DEFAULT 0,
Profit double(10,4) NOT NULL DEFAULT 0
'.$ebay_table_fields.'
)';
$field_values['total'] = $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'Categories');
$this->Conn->Query($q);
$q = 'INSERT INTO '.$field_values['table_name'].'
SELECT
c.CategoryId,
SUM(od.Quantity) as Qty,
SUM(od.Cost * od.Quantity) as Cost,
SUM(od.Price * od.Quantity) as SaleAmount,
SUM(o.VAT * od.Price * od.Quantity / o.SubTotal) as Tax,
SUM(o.ShippingCost * od.Price * od.Quantity / o.SubTotal) as Shipping,
SUM(o.ProcessingFee * od.Price * od.Quantity / o.SubTotal) as Processing,
SUM((od.Price - od.Cost) * od.Quantity) as Profit'
.$ebay_query_fields.'
FROM '.TABLE_PREFIX.'Orders AS o
LEFT JOIN '.TABLE_PREFIX.'OrderItems AS od
ON od.OrderId = o.OrderId
LEFT JOIN '.TABLE_PREFIX.'Products AS p
ON p.ProductId = od.ProductId
LEFT JOIN '.TABLE_PREFIX.'CategoryItems AS ci
ON ci.ItemResourceId = p.ResourceId
LEFT JOIN '.TABLE_PREFIX.'Categories AS c
ON c.CategoryId = ci.CategoryId
'.$ebay_joins.'
WHERE
o.Status IN (4,6)
AND
ci.PrimaryCat = 1
'.$filter_value.'
GROUP BY c.CategoryId
HAVING NOT ISNULL(CategoryId)
';
$this->Conn->Query($q);
}
elseif ($field_values['ReportType'] == 2) { // by User
$q = 'CREATE TABLE '.$table_name.' (
PortalUserId int(11) NOT NULL DEFAULT 0,
Qty int(11) NOT NULL DEFAULT 0,
Cost double(10,4) NOT NULL DEFAULT 0,
Amount double(10,4) NOT NULL DEFAULT 0,
Tax double(10,4) NOT NULL DEFAULT 0,
Shipping double(10,4) NOT NULL DEFAULT 0,
Processing double(10,4) NOT NULL DEFAULT 0,
Profit double(10,4) NOT NULL DEFAULT 0
)';
$field_values['total'] = $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'Categories');
$this->Conn->Query($q);
$q = 'INSERT INTO '.$field_values['table_name'].'
SELECT
u.PortalUserId,
SUM(od.Quantity) as Qty,
SUM(od.Cost * od.Quantity) as Cost,
SUM(od.Price * od.Quantity) as SaleAmount,
SUM(o.VAT * od.Price * od.Quantity / o.SubTotal) as Tax,
SUM(o.ShippingCost * od.Price * od.Quantity / o.SubTotal) as Shipping,
SUM(o.ProcessingFee * od.Price * od.Quantity / o.SubTotal) as Processing,
SUM((od.Price - od.Cost) * od.Quantity) as Profit
FROM '.TABLE_PREFIX.'Orders AS o
LEFT JOIN '.TABLE_PREFIX.'OrderItems AS od
ON od.OrderId = o.OrderId
LEFT JOIN '.TABLE_PREFIX.'Users AS u
ON u.PortalUserId = o.PortalUserId
WHERE
o.Status IN (4,6)
'.$filter_value.'
GROUP BY u.PortalUserId
HAVING NOT ISNULL(PortalUserId)
';
$this->Conn->Query($q);
}
elseif ($field_values['ReportType'] == 5) { // by Product
$q = 'CREATE TABLE '.$table_name.' (
ProductId int(11) NOT NULL DEFAULT 0,
Qty int(11) NOT NULL DEFAULT 0,
Cost double(10,4) NOT NULL DEFAULT 0,
Amount double(10,4) NOT NULL DEFAULT 0,
Tax double(10,4) NOT NULL DEFAULT 0,
Shipping double(10,4) NOT NULL DEFAULT 0,
Processing double(10,4) NOT NULL DEFAULT 0,
Profit double(10,4) NOT NULL DEFAULT 0'
.$ebay_table_fields.'
)';
$field_values['total'] = $this->Conn->GetOne('SELECT COUNT(*) FROM '.TABLE_PREFIX.'Products');
$this->Conn->Query($q);
$q = 'INSERT INTO '.$field_values['table_name'].'
SELECT
p.ProductId,
SUM(od.Quantity) as Qty,
SUM(od.Cost * od.Quantity) as Cost,
SUM(od.Price * od.Quantity) as SaleAmount,
SUM(o.VAT * od.Price * od.Quantity / o.SubTotal) as Tax,
SUM(o.ShippingCost * od.Price * od.Quantity / o.SubTotal) as Shipping,
SUM(o.ProcessingFee * od.Price * od.Quantity / o.SubTotal) as Processing,
SUM((od.Price - od.Cost) * od.Quantity) as Profit'
.$ebay_query_fields.'
FROM '.TABLE_PREFIX.'Orders AS o
LEFT JOIN '.TABLE_PREFIX.'OrderItems AS od
ON od.OrderId = o.OrderId
LEFT JOIN '.TABLE_PREFIX.'Products AS p
ON p.ProductId = od.ProductId
'.$ebay_joins.'
WHERE
o.Status IN (4,6)
'.$filter_value.'
GROUP BY p.ProductId
HAVING NOT ISNULL(ProductId)
';
$this->Conn->Query($q);
}
elseif ($field_values['ReportType'] == 12) { // Overall
$q = 'CREATE TABLE '.$table_name.' (
Marketplace tinyint(1) NOT NULL DEFAULT 0,
Qty int(11) NOT NULL DEFAULT 0,
Cost double(10,4) NOT NULL DEFAULT 0,
Amount double(10,4) NOT NULL DEFAULT 0,
Tax double(10,4) NOT NULL DEFAULT 0,
Shipping double(10,4) NOT NULL DEFAULT 0,
Processing double(10,4) NOT NULL DEFAULT 0,
Profit double(10,4) NOT NULL DEFAULT 0
)';
$this->Conn->Query($q);
if ($this->Application->isModuleEnabled('in-auction'))
{
$field_values['total'] = 2;
$q = 'INSERT INTO '.$field_values['table_name'].'
SELECT
1 AS Marketplace,
SUM(IF(ISNULL(eod.OptionsSalt), od.Quantity, 0)) as Qty,
SUM(IF(ISNULL(eod.OptionsSalt), od.Cost * od.Quantity, 0)) as Cost,
SUM(IF(ISNULL(eod.OptionsSalt), od.Price * od.Quantity, 0)) as SaleAmount,
SUM(IF(ISNULL(eod.OptionsSalt), o.VAT * od.Price * od.Quantity / o.SubTotal, 0)) as Tax,
SUM(IF(ISNULL(eod.OptionsSalt), o.ShippingCost * od.Price * od.Quantity / o.SubTotal, 0)) as Shipping,
SUM(IF(ISNULL(eod.OptionsSalt), o.ProcessingFee * od.Price * od.Quantity / o.SubTotal, 0)) as Processing,
SUM(IF(ISNULL(eod.OptionsSalt), (od.Price - od.Cost) * od.Quantity, 0)) as Profit
FROM '.TABLE_PREFIX.'Orders AS o
LEFT JOIN '.TABLE_PREFIX.'OrderItems AS od
ON od.OrderId = o.OrderId
LEFT JOIN '.TABLE_PREFIX.'eBayOrderItems AS eod
ON od.OptionsSalt = eod.OptionsSalt
WHERE
o.Status IN (4,6)
'.$filter_value;
$this->Conn->Query($q);
$q = 'INSERT INTO '.$field_values['table_name'].'
SELECT
2 AS Marketplace,
SUM(IF(ISNULL(eod.OptionsSalt), 0, od.Quantity)) as Qty,
SUM(IF(ISNULL(eod.OptionsSalt), 0, od.Cost * od.Quantity)) as Cost,
SUM(IF(ISNULL(eod.OptionsSalt), 0, od.Price * od.Quantity)) as SaleAmount,
SUM(IF(ISNULL(eod.OptionsSalt), 0, o.VAT * od.Price * od.Quantity / o.SubTotal)) as Tax,
SUM(IF(ISNULL(eod.OptionsSalt), 0, o.ShippingCost * od.Price * od.Quantity / o.SubTotal)) as Shipping,
SUM(IF(ISNULL(eod.OptionsSalt), 0, o.ProcessingFee * od.Price * od.Quantity / o.SubTotal)) as Processing,
SUM(IF(ISNULL(eod.OptionsSalt), 0, (od.Price - od.Cost) * od.Quantity)) as Profit
FROM '.TABLE_PREFIX.'Orders AS o
LEFT JOIN '.TABLE_PREFIX.'OrderItems AS od
ON od.OrderId = o.OrderId
LEFT JOIN '.TABLE_PREFIX.'eBayOrderItems AS eod
ON od.OptionsSalt = eod.OptionsSalt
WHERE
o.Status IN (4,6)
'.$filter_value;
$this->Conn->Query($q);
} else {
$field_values['total'] = 1;
$q = 'INSERT INTO '.$field_values['table_name'].'
SELECT
1 AS Marketplace,
SUM(od.Quantity) as Qty,
SUM(od.Cost * od.Quantity) as Cost,
SUM(od.Price * od.Quantity) as SaleAmount,
SUM(o.VAT * od.Price * od.Quantity / o.SubTotal) as Tax,
SUM(o.ShippingCost * od.Price * od.Quantity / o.SubTotal) as Shipping,
SUM(o.ProcessingFee * od.Price * od.Quantity / o.SubTotal) as Processing,
SUM((od.Price - od.Cost) * od.Quantity) as Profit
FROM '.TABLE_PREFIX.'Orders AS o
LEFT JOIN '.TABLE_PREFIX.'OrderItems AS od
ON od.OrderId = o.OrderId
WHERE
o.Status IN (4,6)
'.$filter_value;
$this->Conn->Query($q);
}
}
$vars = array('rep_Page', 'rep_Sort1', 'rep_Sort1_Dir', 'rep_Sort2', 'rep_Sort2_Dir');
foreach ($vars as $var_name) {
$this->Application->RemoveVar($var_name);
}
//temporary
$event->redirect = $this->Application->GetVar('reports_finish_t');
$field_values['from'] = $from;
$field_values['to'] = $to;
$this->Application->StoreVar('report_options', serialize($field_values));
}
- function OnUpdateConfig(&$event)
+ function OnUpdateConfig($event)
{
$report = $this->Application->RecallVar('report_options');
if (!$report) {
return ;
}
$field_values = unserialize($report);
$rep_options = $this->Application->getUnitOptions('rep');
$new_options = Array ();
$new_options['TableName'] = $field_values['table_name'];
$new_options['Fields'] = Array (
'Qty' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%d', 'default' => 0, 'totals' => 'sum'),
'Cost' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'Amount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'Tax' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'Shipping' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'Processing' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'Profit' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
);
if ( $this->Application->isModuleEnabled('in-auction') ) {
if ( in_Array ($field_values['ReportType'], Array (1, 5)) ) {
$new_options['Fields'] += Array (
'StoreQty' => Array ('type' => 'int', 'formatter' => 'kFormatter', 'format' => '%d', 'default' => 0, 'totals' => 'sum'),
'StoreAmount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'StoreProfit' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'eBayQty' => Array ('type' => 'int', 'formatter' => 'kFormatter', 'format' => '%d', 'default' => 0, 'totals' => 'sum'),
'eBayAmount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
'eBayProfit' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => 0, 'totals' => 'sum'),
);
}
}
if ($field_values['ReportType'] == 1) { // by Category
$new_options['ListSQLs'][''] =
'SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Categories AS c
ON c.CategoryId = %1$s.CategoryId';
$new_options['Grids']['Default'] = Array (
'Icons' => Array (
'default' => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array (
'CategoryName' => Array ('title' => 'la_col_CategoryName', 'filter_block' => 'grid_like_filter'),
'Qty' => Array ('td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'StoreQty' => Array ('title' => 'la_col_StoreQty', 'td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'eBayQty' => Array ('title' => 'la_col_eBayQty', 'td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Cost' => Array ('td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Amount' => Array ('title' => 'la_col_GMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'StoreAmount' => Array ('title' => 'la_col_StoreGMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'eBayAmount' => Array ('title' => 'la_col_eBayGMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Tax' => Array ('title' => 'la_col_Tax', 'td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Shipping' => Array ('title' => 'la_col_Shipping', 'td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Processing' => Array ('title' => 'la_col_Processing', 'td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Profit' => Array ('title' => 'la_col_Profit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'StoreProfit' => Array ('title' => 'la_col_StoreProfit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'eBayProfit' => Array ('title' => 'la_col_eBayProfit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
),
);
if (!$this->Application->isModuleEnabled('in-auction')) {
$a_fields =& $new_options['Grids']['Default']['Fields'];
unset($a_fields['StoreQty']);
unset($a_fields['eBayQty']);
unset($a_fields['StoreAmount']);
unset($a_fields['eBayAmount']);
unset($a_fields['StoreProfit']);
unset($a_fields['eBayProfit']);
}
$new_options['VirtualFields'] = array_merge($rep_options['VirtualFields'], Array (
'CategoryName' => Array ('type' => 'string', 'default' => ''),
'Metric' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => $this->GetMetricOptions($new_options, 'CategoryName'),
'use_phrases' => 1,
'default' => 0,
),
));
$lang = $this->Application->GetVar('m_lang');
// products root category
$products_category_id = $this->Application->findModule('Name', 'In-Commerce', 'RootCat');
// get root category name
$sql = 'SELECT LENGTH(l' . $lang . '_CachedNavbar)
FROM ' . TABLE_PREFIX . 'Categories
WHERE CategoryId = '.$products_category_id;
$root_length = $this->Conn->GetOne($sql) + 4;
$new_options['CalculatedFields'][''] = array(
'CategoryName' => 'REPLACE(SUBSTR(c.l'.$lang.'_CachedNavbar, '.$root_length.'), "&|&", " > ")',
);
}
elseif ($field_values['ReportType'] == 2) { // by User
$new_options['ListSQLs'][''] =
'SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Users AS u
ON u.PortalUserId = %1$s.PortalUserId';
$new_options['Grids']['Default'] = Array (
'Icons' => Array (
'default' => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array (
'Login' => Array ('filter_block' => 'grid_like_filter'),
'FirstName' => Array ('filter_block' => 'grid_like_filter'),
'LastName' => Array ('filter_block' => 'grid_like_filter'),
'Qty' => Array ('td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Cost' => Array ('td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Amount' => Array ('title' => 'la_col_GMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Tax' => Array ('title' => 'la_col_Tax', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Shipping' => Array ('title' => 'la_col_Shipping', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Processing' => Array ('title' => 'la_col_Processing', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Profit' => Array ('title' => 'la_col_Profit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
),
);
$new_options['VirtualFields'] = array_merge($rep_options['VirtualFields'], Array (
'Login' => Array ('type' => 'string', 'default' => ''),
'FirstName' => Array ('type' => 'string', 'default' => ''),
'LastName' => Array ('type' => 'string', 'default' => ''),
));
$new_options['CalculatedFields'][''] = Array (
'Login' => 'u.Username',
'FirstName' => 'u.FirstName',
'LastName' => 'u.LastName',
);
}
elseif ($field_values['ReportType'] == 5) { // by Product
$new_options['ListSQLs'][''] =
'SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Products AS p
ON p.ProductId = %1$s.ProductId';
$new_options['Grids']['Default'] = Array (
'Icons' => Array (
'default' => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array (
'ProductName' => Array ('title' => 'la_col_ProductName', 'filter_block' => 'grid_like_filter'),
'Qty' => Array ('td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'StoreQty' => Array ('title' => 'la_col_StoreQty', 'td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'eBayQty' => Array ('title' => 'la_col_eBayQty', 'td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Cost' => Array ('td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Amount' => Array ('title' => 'la_col_GMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'StoreAmount' => Array ('title' => 'la_col_StoreGMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'eBayAmount' => Array ('title' => 'la_col_eBayGMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Tax' => Array ('title' => 'la_col_Tax', 'td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Shipping' => Array ('title' => 'la_col_Shipping', 'td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Processing' => Array ('title' => 'la_col_Processing', 'td_style' => 'text-align: right', 'total' => 'sum', 'hidden' => 1, 'filter_block' => 'grid_range_filter'),
'Profit' => Array ('title' => 'la_col_Profit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'StoreProfit' => Array ('title' => 'la_col_StoreProfit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'eBayProfit' => Array ('title' => 'la_col_eBayProfit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
),
);
if (!$this->Application->isModuleEnabled('in-auction'))
{
$a_fields =& $new_options['Grids']['Default']['Fields'];
unset($a_fields['StoreQty']);
unset($a_fields['eBayQty']);
unset($a_fields['StoreAmount']);
unset($a_fields['eBayAmount']);
unset($a_fields['StoreProfit']);
unset($a_fields['eBayProfit']);
}
$new_options['VirtualFields'] = array_merge($rep_options['VirtualFields'], Array (
'ProductName' => Array ('type' => 'string', 'default' => ''),
'Metric' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => $this->GetMetricOptions($new_options, 'ProductName'),
'use_phrases' => 1,
'default' => 0
),
));
$lang = $this->Application->GetVar('m_lang');
$new_options['CalculatedFields'][''] = Array (
'ProductName' => 'p.l'.$lang.'_Name',
);
}
elseif ($field_values['ReportType'] == 12) { // Overall
$new_options['ListSQLs'][''] =
'SELECT %1$s.* %2$s FROM %1$s';
$new_options['Fields']['Marketplace'] = Array (
'formatter' => 'kOptionsFormatter',
'options' => Array (
1 => 'la_OnlineStore',
2 => 'la_eBayMarketplace',
),
'use_phrases' => 1,
'default' => 1
);
$new_options['Grids']['Default'] = Array(
'Icons' => Array(
'default' => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array(
'Marketplace' => Array ('title' => 'la_col_Marketplace', 'filter_block' => 'grid_options_filter'),
'Qty' => Array ('td_style' => 'text-align: center', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Cost' => Array ('td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Amount' => Array ('title' => 'la_col_GMV', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Tax' => Array ('title' => 'la_col_Tax', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Shipping' => Array ('title' => 'la_col_Shipping', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Processing' => Array ('title' => 'la_col_Processing', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
'Profit' => Array ('title' => 'la_col_Profit', 'td_style' => 'text-align: right', 'total' => 'sum', 'filter_block' => 'grid_range_filter'),
),
);
$new_options['VirtualFields'] = array_merge($rep_options['VirtualFields'], array(
'Metric' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => $this->GetMetricOptions($new_options, 'Marketplace'),
'use_phrases' => 1,
'default' => 0
),
));
$lang = $this->Application->GetVar('m_lang');
}
$new_options['ListSortings'] = Array(
'' => Array(
'Sorting' => Array('Amount' => 'desc'),
)
);
foreach ($new_options as $key => $val) {
$this->Application->setUnitOption('rep', $key, $val);
}
}
/**
* Enter description here...
*
* @param kdbItem $object
* @param string $search_field
* @param string $value
* @param string $type
*/
function processRangeField(&$object, $search_field, $type)
{
$value = $object->GetField($search_field);
if (!$value) return false;
$lang_current =& $this->Application->recallObject('lang.current');
$dt_separator = getArrayValue($object->GetFieldOptions($search_field), 'date_time_separator');
if (!$dt_separator) {
$dt_separator = ' ';
}
$time = ($type == 'from') ? adodb_mktime(0, 0, 0) : adodb_mktime(23, 59, 59);
$time = adodb_date($lang_current->GetDBField('InputTimeFormat'), $time);
$full_value = $value.$dt_separator.$time;
$formatter =& $this->Application->recallObject( $object->GetFieldOption($search_field, 'formatter') );
$value_ts = $formatter->Parse($full_value, $search_field, $object);
if ( $object->GetErrorPseudo($search_field) ) {
// invalid format -> ignore this date in search
$object->RemoveError($search_field);
return false;
}
return $value_ts;
}
/**
* Generate Metric Field Options
*
* @param array $a_config_options
* @param string $exclude_field
*/
function GetMetricOptions(&$a_config_options, $exclude_field)
{
$a_ret = Array();
foreach ($a_config_options['Grids']['Default']['Fields'] AS $field => $a_options)
{
if ($field == $exclude_field)
{
continue;
}
$a_ret[$field] = $a_options['title'];
}
return $a_ret;
}
- function OnChangeStatistics(&$event)
+ function OnChangeStatistics($event)
{
$this->Application->StoreVar('ChartMetric', $this->Application->GetVar('metric'));
}
- function OnPieChart(&$event)
+ function OnPieChart($event)
{
$ChartHelper =& $this->Application->RecallObject('ChartHelper');
header("Content-type: image/png");
$width = $event->getEventParam('width');
if (!$width) {
$width = 800;
}
$height = $event->getEventParam('height');
if (!$height) {
$height = 600;
}
$a_data = unserialize($this->Application->RecallVar('graph_data'));
$chart = new LibchartPieChart($width, $height);
$dataSet = new LibchartXYDataSet();
foreach ($a_data AS $key=>$a_values)
{
$dataSet->addPoint(new LibchartPoint($a_values['Name'], $a_values['Metric']));
// $dataSet->addPoint(new LibchartPoint($a_values['Name'].' ('.$a_values['Metric'].')', $a_values['Metric']));
}
$chart->setDataSet($dataSet);
$chart->setTitle($this->Application->RecallVar('graph_metric'));
$chart->render();
$event->status = kEvent::erSTOP;
}
/** Generates png-chart output
*
* @param kEvent $event
*/
- function OnPrintChart(&$event)
+ function OnPrintChart($event)
{
$ChartHelper =& $this->Application->RecallObject('ChartHelper');
header("Content-type: image/png");
$width = $this->Application->GetVar('width');
if ($width == 0)
{
$width = 800;
}
$height = $this->Application->GetVar('height');
if ($height == 0)
{
$height = 400;
}
$chart = new LibchartLineChart($width, $height);
$a_labels = unserialize($this->Application->RecallVar('graph_labels'));
if ($this->Application->isModuleEnabled('in-auction'))
{
$serie1 = new LibchartXYDataSet();
$a_serie = unserialize($this->Application->RecallVar('graph_serie1'));
foreach ($a_labels AS $key=>$value)
{
$serie1->addPoint(new LibchartPoint($value, $a_serie[$key]));
}
}
$serie2 = new LibchartXYDataSet();
$a_serie = unserialize($this->Application->RecallVar('graph_serie2'));
foreach ($a_labels AS $key=>$value)
{
$serie2->addPoint(new LibchartPoint($value, $a_serie[$key]));
}
$dataSet = new LibchartXYSeriesDataSet();
if ($this->Application->isModuleEnabled('in-auction'))
{
$dataSet->addSerie($this->Application->RecallVar('graph_serie1_label'), $serie1);
}
$dataSet->addSerie($this->Application->RecallVar('graph_serie2_label'), $serie2);
$chart->setDataSet($dataSet);
$chart->setTitle($this->Application->RecallVar('graph_metric'));
$Plot =& $chart->getPlot();
$Plot->setGraphCaptionRatio(0.7);
$chart->render();
$event->status = kEvent::erSTOP;
}
- function OnExportReport(&$event)
+ function OnExportReport($event)
{
$report =& $this->Application->recallObject($event->getPrefixSpecial(),'rep_List',Array('skip_counting'=>true,'per_page'=>-1) );
/* @var $report kDBList*/
$ReportItem =& $this->Application->recallObject('rep.item', 'rep', Array('skip_autoload' => true));
/* @var $ReportItem kDBItem*/
$a_grids = $this->Application->getUnitOption('rep', 'Grids');
$a_fields = $a_grids['Default']['Fields'];
$ret = '';
foreach ($a_fields AS $field => $a_props)
{
$ret .= '<commas>'.$field.'<commas><tab>';
}
$ret = substr($ret, 0, strlen($ret) - 5).'<cr>';
$report->Query(true);
$report->GoFirst();
$counter = 0;
$a_totals = Array();
foreach ($a_fields AS $field => $a_props) {
$counter++;
if ($counter == 1)
{
continue;
}
$a_totals[$field] = 0;
}
foreach($report->Records as $a_row) {
$ReportItem->SetFieldsFromHash($a_row);
$row = '';
foreach ($a_fields AS $field => $a_props)
{
$row .= '<commas>'.$ReportItem->GetField($field).'<commas><tab>';
$a_totals[$field] += $a_row[$field];
}
$ret .= substr($row, 0, strlen($row) - 5).'<cr>';
}
// totals
$ReportItem->SetFieldsFromHash($a_totals);
$counter = 0;
foreach ($a_fields AS $field => $a_props)
{
$counter++;
if ($counter == 1)
{
$row = '<commas><commas><tab>';
continue;
}
$row .= '<commas>'.$ReportItem->GetField($field).'<commas><tab>';
}
$ret .= substr($row, 0, strlen($row) - 5).'<cr>';
$ret = str_replace("\r",'', $ret);
$ret = str_replace("\n",'', $ret);
$ret = str_replace('"','\'\'', $ret);
$ret = str_replace('<commas>','"', $ret);
$ret = str_replace('<tab>',',', $ret);
$ret = str_replace('<cr>',"\r", $ret);
$report_options = unserialize($this->Application->RecallVar('report_options'));
switch ($report_options['ReportType'])
{
case 1:
$file_name = '-ByCategory';
break;
case 2:
$file_name = '-ByUser';
break;
case 5:
$file_name = '-ByProduct';
break;
case 12:
$file_name = '';
break;
}
header("Content-type: application/txt");
header("Content-length: ".(string)strlen($ret));
header("Content-Disposition: attachment; filename=\"".html_entity_decode('SalesReport'.$file_name.'-'.date('d-M-Y').'.csv')."\"");
header("Pragma: no-cache"); //some IE-fixing stuff
echo $ret;
exit();
}
}
\ 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 15133)
+++ branches/5.2.x/units/brackets/brackets_event_handler.php (revision 15134)
@@ -1,231 +1,231 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class BracketsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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);
}
/**
* 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, kEvent &$event)
+ protected function prepareObject(&$object, kEvent $event)
{
if ( $this->Application->GetVar('s_id') === false ) {
return;
}
$shipping_object =& $this->Application->recallObject('s');
/* @var $shipping_object kDBItem */
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
if ( $lang_object->GetDBField('UnitSystem') == 2 && $shipping_object->GetDBField('Type') == 1 ) {
$fields = Array ('Start', 'End');
$formatter =& $this->Application->recallObject('kUnitFormatter');
/* @var $formatter kUnitFormatter */
foreach ($fields as $field) {
$object->SetFieldOption($field, 'formatter', 'kUnitFormatter');
$options = $object->GetFieldOptions($field);
$formatter->prepareOptions($field, $options, $object);
}
}
}
- function prepareBrackets(&$event)
+ function prepareBrackets($event)
{
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
$shipping_object =& $this->Application->recallObject('s');
/* @var $shipping_object kDBItem */
if ( $lang_object->GetDBField('UnitSystem') != 2 || $shipping_object->GetDBField('Type') != 1 ) {
return;
}
$item_info = $this->Application->GetVar( $event->getPrefixSpecial() );
foreach ($item_info as $id => $item_data) {
if ( $item_info[$id]['Start_a'] === '' && $item_info[$id]['Start_b'] === '' ) {
$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)
+ function OnMoreBrackets($event)
{
$brackets_helper =& $this->getHelper($event);
$brackets_helper->OnMoreBrackets($event);
}
/**
* Arrange brackets
*
* @param kEvent $event
*/
- function OnArrange(&$event)
+ function OnArrange($event)
{
$brackets_helper =& $this->getHelper($event);
$brackets_helper->arrangeBrackets($event);
$event->CallSubEvent('OnPreSaveBrackets');
}
/**
* Arrange infinity brackets
*
* @param kEvent $event
*/
- function OnInfinity(&$event)
+ function OnInfinity($event)
{
$brackets_helper =& $this->getHelper($event);
$brackets_helper->arrangeBrackets($event);
$event->CallSubEvent('OnPreSaveBrackets');
$brackets_helper->OnInfinity($event);
$event->CallSubEvent('OnPreSaveBrackets');
}
/**
* Initializes kBracketsHelper class based on event
*
* @param kEvent $event
* @param bool $event_readonly
* @return kBracketsHelper
*/
- protected function &getHelper(&$event, $event_readonly = false)
+ protected function &getHelper($event, $event_readonly = false)
{
$shipping_object =& $this->Application->recallObject('s');
/* @var $shipping_object kDBItem */
$default_start = $shipping_object->GetDBField('Type') == 1 ? 0 : 1;
if ( !$event_readonly ) {
$this->prepareBrackets($event);
$event->redirect = false;
}
$brackets_helper =& $this->Application->recallObject('BracketsHelper');
/* @var $brackets_helper kBracketsHelper */
$brackets_helper->InitHelper('Start', 'End', Array (), $default_start);
return $brackets_helper;
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $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->getHelper($event, true);
$brackets_helper->replaceInfinity($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnPreSaveBrackets(&$event)
+ function OnPreSaveBrackets($event)
{
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
$shipping_object =& $this->Application->recallObject('s');
/* @var $shipping_object kDBItem */
if ( $lang_object->GetDBField('UnitSystem') == 2 && $shipping_object->GetDBField('Type') == 1 ) {
$item_info = $this->Application->GetVar($event->getPrefixSpecial());
if ( is_array($item_info) ) {
foreach ($item_info as $id => $values) {
if ( $values['End'] == -1 ) {
$item_info[$id]['End_a'] = -1 / kUtil::POUND_TO_KG;
$item_info[$id]['End_b'] = 0;
}
}
$this->Application->SetVar($event->getPrefixSpecial(), $item_info);
}
}
$brackets_helper =& $this->getHelper($event, true);
$brackets_helper->OnPreSaveBrackets($event);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/payment_type_currencies/payment_type_currencies_event_handler.php
===================================================================
--- branches/5.2.x/units/payment_type_currencies/payment_type_currencies_event_handler.php (revision 15133)
+++ branches/5.2.x/units/payment_type_currencies/payment_type_currencies_event_handler.php (revision 15134)
@@ -1,63 +1,63 @@
<?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 PaymentTypeCurrenciesEventHandler extends kDBEventHandler {
/**
* Creates new kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnCreate(kEvent &$event)
+ protected function OnCreate(kEvent $event)
{
$currency_id_list = $this->Application->GetVar('currency_list');
if ( !$currency_id_list ) {
return;
}
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$pt_id = $this->Application->GetVar('pt_id');
if ( $pt_id === false ) {
return;
}
$sql = 'DELETE FROM ' . $object->TableName . '
WHERE PaymentTypeId = ' . $pt_id;
$this->Conn->Query($sql);
foreach ($currency_id_list as $id) {
$object->SetDBField('CurrencyId', $id);
$object->SetDBField('PaymentTypeId', $pt_id);
$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);
}
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/helpers/helpers_config.php
===================================================================
--- branches/5.2.x/units/helpers/helpers_config.php (revision 15133)
+++ branches/5.2.x/units/helpers/helpers_config.php (revision 15134)
@@ -1,18 +1,18 @@
<?php
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'in-commerce-helpers',
'EventHandlerClass' => Array ('class' => 'kEventHandler', 'file' => '', 'build_event' => 'OnBuild'),
'RegisterClasses' => Array (
- Array ('pseudo' => 'OrderHelper', 'class' => 'OrderHelper', 'file' => 'order_helper.php', 'build_event' => '', 'require_classes' => 'kHelper'),
+ Array ('pseudo' => 'OrderHelper', 'class' => 'OrderHelper', 'file' => 'order_helper.php', 'build_event' => ''),
Array ('pseudo' => 'CurrencyRates', 'class' => 'CurrencyRates', 'file' => 'currency_rates.php', 'build_event' => ''),
- Array ('pseudo' => 'BankLVCurrencyRates', 'class' => 'BankLVCurrencyRates', 'file' => 'bank_lv_currency_rates.php', 'require_classes' => 'CurrencyRates', 'build_event' => ''),
- Array ('pseudo' => 'ECBCurrencyRates', 'class' => 'ECBCurrencyRates', 'file' => 'ecb_currency_rates.php', 'require_classes' => 'CurrencyRates', 'build_event' => ''),
- Array ('pseudo' => 'FRNYCurrencyRates', 'class' => 'FRNYCurrencyRates', 'file' => 'frny_currency_rates.php', 'require_classes' => 'CurrencyRates', 'build_event' => ''),
+ Array ('pseudo' => 'BankLVCurrencyRates', 'class' => 'BankLVCurrencyRates', 'file' => 'bank_lv_currency_rates.php', 'build_event' => ''),
+ Array ('pseudo' => 'ECBCurrencyRates', 'class' => 'ECBCurrencyRates', 'file' => 'ecb_currency_rates.php', 'build_event' => ''),
+ Array ('pseudo' => 'FRNYCurrencyRates', 'class' => 'FRNYCurrencyRates', 'file' => 'frny_currency_rates.php', 'build_event' => ''),
),
);
Index: branches/5.2.x/units/files/files_event_handler.php
===================================================================
--- branches/5.2.x/units/files/files_event_handler.php (revision 15133)
+++ branches/5.2.x/units/files/files_event_handler.php (revision 15134)
@@ -1,188 +1,188 @@
<?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 FilesEventHandler extends kDBEventHandler {
/**
* Returns special of main item for linking with sub-item
*
* @param kEvent $event
* @return string
* @access protected
*/
- protected function getMainSpecial(kEvent &$event)
+ protected function getMainSpecial(kEvent $event)
{
if ( $event->Special == 'downl' ) {
return '';
}
return parent::getMainSpecial($event);
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
switch ($event->Special) {
case 'downl':
$object->addFilter('is_active', '%1$s.Status = 1');
break;
}
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->itemChanged($event);
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->itemChanged($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$parent_info = $object->getLinkedInfo($event->Special);
$sql = 'SELECT FileId
FROM ' . $object->TableName . '
WHERE IsPrimary = 1 AND ' . $parent_info['ForeignKey'] . ' = ' . $parent_info['ParentId'];
$file_id = $this->Conn->GetOne($sql);
if ( !$file_id ) {
$object->SetDBField('IsPrimary', 1);
$object->SetDBField('Status', 1);
}
$object->SetDBField('AddedById', $this->Application->RecallVar('user_id'));
}
/**
* Occurs before item is changed
*
* @param kEvent $event
*/
- function itemChanged(&$event)
+ function itemChanged($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
if ( $object->GetDBField('IsPrimary') ) {
$parent_info = $object->getLinkedInfo($event->Special);
$sql = 'UPDATE ' . $object->TableName . '
SET IsPrimary = 0
WHERE ' . $parent_info['ForeignKey'] . ' = ' . $parent_info['ParentId'];
$this->Conn->Query($sql);
$object->SetDBField('Status', 1);
}
if ( $object->GetDBField('Name') == '' ) {
$object->SetDBField('Name', $object->GetDBField('FilePath'));
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnSetPrimary(&$event)
+ function OnSetPrimary($event)
{
$ids = $this->StoreSelectedIDs($event);
$id = array_shift($ids);
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$object->Load($id);
$object->SetDBField('IsPrimary', 1);
$object->Update();
}
/**
* Don't allow to delete primary product file, when there are no more files
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
$ids = $event->getEventParam('ids');
$object =& $event->getObject();
/* @var $object kDBItem */
$parent_info = $object->getLinkedInfo($event->Special);
$sql = 'SELECT FileId
FROM ' . $object->TableName . '
WHERE IsPrimary = 1 AND ' . $parent_info['ForeignKey'] . ' = ' . $parent_info['ParentId'];
$primary_file_id = $this->Conn->GetOne($sql);
if ( $primary_file_id ) {
$file_id_index = array_search($primary_file_id, $ids);
if ( $file_id_index ) {
// allow deleting of primary product file, when there is another file to make primary
$sql = 'SELECT COUNT(*)
FROM ' . $object->TableName . '
WHERE IsPrimary = 0 AND ' . $parent_info['ForeignKey'] . ' = ' . $parent_info['ParentId'];
$non_primary_file_count = $this->Conn->GetOne($sql);
if ( $non_primary_file_count ) {
unset($ids[$file_id_index]);
}
}
}
$event->setEventParam('ids', $ids);
}
}
}
\ 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 15133)
+++ branches/5.2.x/units/affiliate_payments/affiliate_payments_event_handler.php (revision 15134)
@@ -1,138 +1,138 @@
<?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 {
/**
* 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, kEvent &$event)
+ protected function prepareObject(&$object, kEvent $event)
{
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() ) {
$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' ) {
$options['options'][0] = '';
}
$object->setFieldOptions('PaymentTypeId', $options);
}
/**
* Set's fields based on affiliate currently being edited
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnNew(kEvent &$event)
+ protected function OnNew(kEvent $event)
{
parent::OnNew($event);
$affiliate =& $this->Application->recallObject('affil');
/* @var $affiliate kDBItem */
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$object->SetDBField('Amount', $affiliate->GetDBField('AmountToPay'));
$object->SetDBField('AffiliateId', $affiliate->GetID());
}
/**
* Updates Affiliate Record On Successfully payment creation
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemCreate(kEvent &$event)
+ protected function OnAfterItemCreate(kEvent $event)
{
parent::OnAfterItemCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$parent_info = $object->getLinkedInfo();
$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');
/* @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();
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
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 15133)
+++ branches/5.2.x/units/destinations/dst_event_handler.php (revision 15134)
@@ -1,131 +1,132 @@
<?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
* @return void
* @access protected
*/
- protected function OnCreate(kEvent &$event)
+ protected function OnCreate(kEvent $event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
// creates multiple db records from single request (OnCreate event only creates 1 record)
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
foreach ($items_info as $field_values) {
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
$this->customProcessing($event, 'before');
if ( $object->Create() ) {
$this->customProcessing($event, 'after');
$event->status = kEvent::erSUCCESS;
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
$this->Application->SetVar($event->getPrefixSpecial() . '_SaveEvent', 'OnCreate');
$object->setID(0);
}
}
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
if ( $type != 'before' ) {
return;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$events = $this->Application->GetVar('events');
if ( $events['z'] == 'OnUpdate' ) {
$object->SetDBField('ShippingZoneId', $this->Application->GetVar('z_id'));
}
$zone_object =& $this->Application->recallObject('z');
/* @var $zone_object kDBItem */
if ( $zone_object->GetDBField('Type') == 3 ) {
$object->SetDBField('StdDestId', $this->Application->GetVar('ZIPCountry'));
}
}
/**
*
*
* @param kEvent $event
*/
- function OnZoneUpdate(&$event) {
+ function OnZoneUpdate($event) {
- $object = &$event->getObject();
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
$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 15133)
+++ branches/5.2.x/units/affiliate_payment_types/affiliate_payment_types_event_handler.php (revision 15134)
@@ -1,124 +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 AffiliatePaymentTypesEventHandler extends kDBEventHandler {
/**
* Lists only active affiliate payment types on Front-End
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
if ( !$this->Application->isAdmin ) {
$object =& $event->getObject();
/* @var $object kDBList */
$object->addFilter('active', '%1$s.Status = ' . STATUS_ACTIVE);
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnSetPrimary(&$event)
+ function OnSetPrimary($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('IsPrimary', 1);
$object->Update();
}
/**
* Ensures, that user have only one "use as billing" / "use as shipping" address
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->itemChanged($event);
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->itemChanged($event);
}
/**
* Occurs before item is changed
*
* @param kEvent $event
*/
- function itemChanged(&$event)
+ function itemChanged($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
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') );
$object->SetDBField($status_field, 1);
}
}
/**
* Don't allow to delete primary affiliate payment type
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
$ids = $event->getEventParam('ids');
$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));
$event->setEventParam('ids', $ids);
}
}
}
\ No newline at end of file
Index: branches/5.2.x/units/shipping_quote_engines/shipping_quote_engines_config.php
===================================================================
--- branches/5.2.x/units/shipping_quote_engines/shipping_quote_engines_config.php (revision 15133)
+++ branches/5.2.x/units/shipping_quote_engines/shipping_quote_engines_config.php (revision 15134)
@@ -1,218 +1,218 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'sqe',
'ItemClass' => Array ('class' => 'kDBItem', 'file' => '', 'build_event' => 'OnItemBuild'),
'ListClass' => Array ('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
'EventHandlerClass' => Array ('class' => 'ShippingQuoteEngineEventHandler', 'file' => 'shipping_quote_engine_event_handler.php', 'build_event' => 'OnBuild'),
'TagProcessorClass' => Array ('class' => 'kDBTagProcessor', 'file' => '', 'build_event' => 'OnBuild'),
'RegisterClasses' => Array (
Array ('pseudo' => 'ShippingQuoteEngine', 'class' => 'ShippingQuoteEngine', 'file' => 'shipping_quote_engine.php', 'build_event' => ''),
- Array ('pseudo' => 'CustomShippingQuoteEngine', 'class' => 'CustomShippingQuoteEngine', 'file' => 'custom_shipping_quote_engine.php', 'require_classes' => 'ShippingQuoteEngine', 'build_event' => ''),
- Array ('pseudo' => 'Intershipper', 'class' => 'Intershipper', 'file' => 'intershipper.php', 'require_classes' => 'ShippingQuoteEngine', 'build_event' => ''),
- Array ('pseudo' => 'USPS', 'class' => 'USPS', 'file' => 'usps.php', 'require_classes' => 'ShippingQuoteEngine', 'build_event' => ''),
- Array ('pseudo' => 'ShippingQuoteCollector', 'class' => 'ShippingQuoteCollector', 'file' => 'shipping_quote_collector.php', 'build_event' => '', 'require_classes' => 'ShippingQuoteEngine'),
+ Array ('pseudo' => 'CustomShippingQuoteEngine', 'class' => 'CustomShippingQuoteEngine', 'file' => 'custom_shipping_quote_engine.php', 'build_event' => ''),
+ Array ('pseudo' => 'Intershipper', 'class' => 'Intershipper', 'file' => 'intershipper.php', 'build_event' => ''),
+ Array ('pseudo' => 'USPS', 'class' => 'USPS', 'file' => 'usps.php', 'build_event' => ''),
+ Array ('pseudo' => 'ShippingQuoteCollector', 'class' => 'ShippingQuoteCollector', 'file' => 'shipping_quote_collector.php', 'build_event' => ''),
),
'AutoLoad' => true,
'Hooks' => Array (
),
'QueryString' => Array (
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'IDField' => 'EngineId',
'StatusField' => Array ('Status'),
'TitleField' => 'Name',
'TitlePresets' => Array (
'default' => Array ( 'edit_status_labels' => Array ('sqe' => '!la_title_EditingShippingQuoteEngine!'),
),
'engine_list' =>Array ( 'prefixes' => Array ('sqe_List'),
'format' => "!la_title_ShippingQuoteEngines!",
),
'engine_edit' =>Array ( 'prefixes' => Array ('sqe'),
'format' => "#sqe_status# '#sqe_titlefield#' - !la_title_General!",
),
),
'PermSection' => Array ('main' => 'in-commerce:shipping_quote_engines'),
'Sections' => Array (
'in-commerce:shipping_quote_engines' => Array (
'parent' => 'in-commerce:shipping_folder',
'icon' => 'conf_shipping',
'label' => 'la_tab_ShippingQuoteEngines',
'url' => Array ('t' => 'in-commerce/shipping/shipping_list', 'pass' => 'm'),
'permissions' => Array ('view', 'edit', 'advanced:approve', 'advanced:decline'),
'priority' => 4.2,
'type' => stTAB,
),
),
'TableName' => TABLE_PREFIX.'ShippingQuoteEngines',
'ListSQLs' => Array ( '' => 'SELECT * FROM %s'),
// key - special, value - list select sql
'ItemSQLs' => Array ( '' => 'SELECT * FROM %s'),
'ListSortings' => Array (
'' => Array (
'Sorting' => Array ('Name' => 'asc'),
)
),
'Fields' => Array (
'EngineId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'Name' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'FlatSurcharge' => Array ('type' => 'double', 'not_null' => 1, 'default' => '0'),
'PercentSurcharge' => Array ('type' => 'double', 'not_null' => 1, 'default' => '0'),
'Status' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'la_Enabled', 0 => 'la_Disabled'), 'use_phrases' => 1,
'error_msgs' => Array (
'curl_not_present' => '!la_error_EnableCurlFirst!',
'from_info_not_filled_in' => '!la_error_FillInShippingFromAddress!',
),
'default' => 0, 'not_null' => 1,
),
'Properties' => Array ('type' => 'string', 'default' => NULL),
'ClassName' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
),
'VirtualFields' => Array (
'AccountLogin' => Array ('type' => 'string', 'default' => ''),
'AccountPassword' => Array ('type' => 'string', 'default' => ''),
'UPSEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'UPSAccount' => Array ('type' => 'string', 'default' => ''),
'UPSInvoiced' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Invoiced', 0 => 'NotInvoiced'),
'default' => 0
),
'FDXEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'FDXAccount' => Array ('type' => 'string', 'default' => ''),
'FDXInvoiced' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Invoiced', 0 => 'NotInvoiced'),
'default' => 0
),
'DHLEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'DHLAccount' => Array ('type' => 'string', 'default' => ''),
'DHLInvoiced' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Invoiced', 0 => 'NotInvoiced'),
'default' => 0
),
'USPEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'USPAccount' => Array ('type' => 'string', 'default' => ''),
'USPInvoiced' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Invoiced', 0 => 'NotInvoiced'),
'default' => 0
),
'ARBEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'ARBAccount' => Array ('type' => 'string', 'default' => ''),
'ARBInvoiced' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Invoiced', 0 => 'NotInvoiced'),
'default' => 0
),
'1DYEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'2DYEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'3DYEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'GNDEnabled' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'Enabled', 0 => 'Disabled'),
'default' => 0
),
'ShipMethod' => Array (
'type' => 'string',
'formatter' => 'kOptionsFormatter',
'options' => Array (
'DRP' => 'Drop-Off At Carrier Location',
'PCK' => 'Schedule A Special Pickup',
'SCD' => 'Regularly Scheduled Pickup'),
'default' => null
),
),
'Grids' => Array (
'Default' => Array (
'Icons' => Array (
'default' => 'icon16_item.png',
0 => 'icon16_disabled.png',
1 => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array (
'EngineId' => Array ( 'title' => 'column:la_fld_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 50, ),
'Name' => Array ( 'title' => 'column:la_fld_ShippingQuoteEngineName', 'filter_block' => 'grid_like_filter', 'width' => 250, ),
'FlatSurcharge' => Array ( 'filter_block' => 'grid_range_filter', 'width' => 150, ),
'PercentSurcharge' => Array ( 'filter_block' => 'grid_range_filter', 'width' => 150, ),
'Status' => Array ('filter_block' => 'grid_options_filter', 'width' => 150, ),
),
),
),
);
\ 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 15133)
+++ branches/5.2.x/units/shipping_quote_engines/shipping_quote_engine_event_handler.php (revision 15134)
@@ -1,158 +1,158 @@
<?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 {
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$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') != '' ) {
// 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');
if ( !function_exists('curl_init') ) {
$object->SetError('Status', 'curl_not_present');
}
elseif ( ($object->GetDBField('Status') == STATUS_ACTIVE) && !$valid_address ) {
$object->SetError('Status', 'from_info_not_filled_in');
}
}
/**
* Apply same processing to each item being selected in grid
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function iterateItems(kEvent &$event)
+ protected function iterateItems(kEvent $event)
{
parent::iterateItems($event);
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
*/
- protected function OnAfterItemLoad(kEvent &$event)
+ protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$properties = $object->GetDBField('Properties');
if ( $properties ) {
$object->SetDBFieldsFromHash(unserialize($properties));
}
}
/**
* Deletes cached shipping quotes on any setting change
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemCreate(kEvent &$event)
+ protected function OnAfterItemCreate(kEvent $event)
{
parent::OnAfterItemCreate($event);
$this->_deleteQuoteCache();
}
/**
* Deletes cached shipping quotes on any setting change
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemUpdate(kEvent &$event)
+ protected function OnAfterItemUpdate(kEvent $event)
{
parent::OnAfterItemUpdate($event);
$this->_deleteQuoteCache();
}
/**
* Deletes cached shipping quotes on any setting change
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemDelete(kEvent &$event)
+ protected function OnAfterItemDelete(kEvent $event)
{
parent::OnAfterItemDelete($event);
$this->_deleteQuoteCache();
}
/**
* Deletes cached shipping quotes
*
*/
function _deleteQuoteCache()
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemCache
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 15133)
+++ branches/5.2.x/units/product_option_combinations/product_option_combinations_event_handler.php (revision 15134)
@@ -1,443 +1,443 @@
<?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
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
if ( $type == 'after' ) {
return;
}
switch ($event->Name) {
case 'OnCreate':
case 'OnUpdate':
$object =& $event->getObject();
/* @var $object kDBItem */
$options = unserialize($object->GetDBField('Combination'));
ksort($options);
$object->SetDBField('CombinationCRC', crc32(serialize($options)));
break;
case 'OnMassDelete':
// delete only option combinations that has no associated inventory
$object =& $event->getObject();
/* @var $object kDBItem */
$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)
+ 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)
+ 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)
+ 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;
}
}
}
/**
* Creates new kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnCreate(kEvent &$event)
+ protected function OnCreate(kEvent $event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
list($id, $field_values) = each($items_info);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($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);
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnUpdate(kEvent &$event)
+ protected function OnUpdate(kEvent $event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $id => $field_values)
{
$object->Load($id);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($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)
*
* Pattern: Prototype Manager
*
* @param kEvent $event
* @access protected
*/
- protected function OnItemBuild(kEvent &$event)
+ protected function OnItemBuild(kEvent $event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$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_autoload = $event->getEventParam('skip_autoload');
if ( $auto_load && !$skip_autoload ) {
$this->LoadItem($event);
}
$actions =& $this->Application->recallObject('kActions');
/* @var $actions Params */
$actions->Set($event->getPrefixSpecial() . '_GoTab', '');
$actions->Set($event->getPrefixSpecial() . '_GoId', '');
}
/**
* Load item if id is available
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function LoadItem(kEvent &$event)
+ protected function LoadItem(kEvent $event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$id = $this->getPassedID($event);
if ( !$id ) {
$event->CallSubEvent('OnNew');
return;
}
if ( $object->Load($id) ) {
$actions =& $this->Application->recallObject('kActions');
/* @var $actions Params */
$actions->Set($event->getPrefixSpecial() . '_id', $object->GetId());
}
}
/**
* Returns special of main item for linking with sub-item
*
* @param kEvent $event
* @return string
* @access protected
*/
- protected function getMainSpecial(kEvent &$event)
+ protected function getMainSpecial(kEvent $event)
{
$special = $event->getEventParam('main_special');
if ( $special === false || $special == '$main_special' ) {
$special = $event->Special;
}
if ( $special == 'grid' ) {
$special = '';
}
return $special;
}
/**
* 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(kEvent &$event)
+ protected function OnBeforeClone(kEvent $event)
{
parent::OnBeforeClone($event);
$event->Init($event->Prefix, '-item');
$object =& $event->getObject();
/* @var $object kDBItem */
$options_mapping = $this->Application->GetVar('poc_mapping');
if ( !$options_mapping ) {
return;
}
foreach ($options_mapping as $original => $new) {
$n_combs = array ();
$comb_data = unserialize($object->GetDBField('Combination'));
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
*/
- protected function OnBeforeDeleteFromLive(kEvent &$event)
+ protected function OnBeforeDeleteFromLive(kEvent $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;
$inventory_status = $this->Conn->GetOne($sql);
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));
/* @var $temp_object kDBItem */
$temp_object->SwitchToTemp();
$temp_object->Load($id);
$temp_object->SetDBFieldsFromHash($live_object->GetFieldValues(), Array ('QtyInStock', 'QtyReserved', 'QtyBackOrdered', 'QtyOnOrder'));
$temp_object->Update();
}
}
/**
* Create search filters based on search query
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnSearch(kEvent &$event)
+ protected function OnSearch(kEvent $event)
{
parent::OnSearch($event);
$this->_saveProduct($event);
}
/**
* Clear search keywords
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnSearchReset(kEvent &$event)
+ protected function OnSearchReset(kEvent $event)
{
parent::OnSearchReset($event);
$this->_saveProduct($event);
}
/**
* Makes event remember product id (if passed)
*
* @param kEvent $event
*/
- function _saveProduct(&$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_combinations_config.php
===================================================================
--- branches/5.2.x/units/product_option_combinations/product_option_combinations_config.php (revision 15133)
+++ branches/5.2.x/units/product_option_combinations/product_option_combinations_config.php (revision 15134)
@@ -1,142 +1,142 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'poc',
'ItemClass' => Array ('class' => 'kPOCItem', 'file' => 'products_option_combination_item.php', 'build_event' => 'OnItemBuild'),
'ListClass' => Array ('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
'EventHandlerClass' => Array ('class' => 'ProductOptionCombinationsEventHandler', 'file' => 'product_option_combinations_event_handler.php', 'build_event' => 'OnBuild'),
'TagProcessorClass' => Array ('class' => 'ProductOptionCombinationsTagProcessor', 'file' => 'product_option_combinations_tag_processor.php', 'build_event' => 'OnBuild'),
'RegisterClasses' => Array (
- Array ('pseudo' => 'kCombinationFormatter', 'class' => 'kCombinationFormatter', 'file' => 'product_option_formatters.php', 'build_event' => '', 'require_classes' => 'kFormatter'),
- Array ('pseudo' => 'kCombPriceFormatter', 'class' => 'kCombPriceFormatter', 'file' => 'product_option_formatters.php', 'build_event' => '', 'require_classes' => 'kFormatter'),
+ Array ('pseudo' => 'kCombinationFormatter', 'class' => 'kCombinationFormatter', 'file' => 'product_option_formatters.php', 'build_event' => ''),
+ Array ('pseudo' => 'kCombPriceFormatter', 'class' => 'kCombPriceFormatter', 'file' => 'product_option_formatters.php', 'build_event' => ''),
),
'AutoLoad' => true,
'Hooks' => Array (
),
'AggregateTags' => Array (
),
'QueryString' => Array (
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
),
'TitleField' => 'CombinationId',
'IDField' => 'CombinationId',
'TableName' => TABLE_PREFIX.'ProductOptionCombinations',
'ForeignKey' => Array ('p' => 'ProductId'),
'ParentTableKey' => Array ('p' => 'ProductId'),
'ParentPrefix' => 'p',
'AutoDelete' => true,
'AutoClone' => true,
'ListSQLs' => Array ( '' => 'SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Products ON '.TABLE_PREFIX.'Products.ProductId = %1$s.ProductId
LEFT JOIN '.TABLE_PREFIX.'ProductsPricing ON '.TABLE_PREFIX.'ProductsPricing.ProductId = %1$s.ProductId AND '.TABLE_PREFIX.'ProductsPricing.IsPrimary = 1
',
), // key - special, value - list select sql
'ItemSQLs' => Array ( '' => 'SELECT * FROM %s',
),
'ListSortings' => Array (
'' => Array (
'Sorting' => Array ('Combination' => 'asc'),
'ForcedSorting' => Array ('Priority' => 'desc'),
)
),
'Fields' => Array (
'CombinationId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0, ),
'ProductId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0, ),
'Combination' => Array ('type' => 'string', 'required' => 1, 'formatter' => 'kCombinationFormatter', 'format' =>"%s: %s<br>", 'default' => NULL),
'CombinationCRC' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0, ),
'PriceType' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Txt_=', 2 => 'la_Flat', 3 => 'la_Percent'), 'use_phrases' => 1, 'default' => 3, ),
'Price' => Array ('type' => 'float', 'required' => 1, 'formatter' => 'kFormatter', 'default' => '', ),
'WeightType' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Txt_=', 2 => 'la_Flat', 3 => 'la_Percent'), 'use_phrases' => 1, 'default' => 3, ),
'Weight' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'default' => 0, ),
'Availability' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array ( 0 => 'la_No', 1 => 'la_Yes', ), 'use_phrases' => 1,
'not_null' => 1, 'default' => 1,
),
'Priority' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0, ),
'QtyInStock' => Array ('type' => 'int', 'not_null' => '1', 'default' => 0),
'QtyReserved' => Array ('type' => 'int', 'not_null' => '1', 'default' => 0),
'QtyBackOrdered' => Array ('type' => 'int', 'not_null' => '1', 'default' => 0),
'QtyOnOrder' => Array ('type' => 'int', 'not_null' => '1', 'default' => 0),
'SKU' => Array ('type' => 'string', 'not_null' => '1', 'default' => ''),
),
'CalculatedFields' => Array (
'' => Array (
'FinalPrice' => 'IF(%1$s.PriceType = 1, %1$s.Price,
IF(%1$s.PriceType = 2, '.TABLE_PREFIX.'ProductsPricing.Price + %1$s.Price,
'.TABLE_PREFIX.'ProductsPricing.Price * (1 + %1$s.Price/100)
)
)',
'BasePrice' => TABLE_PREFIX.'ProductsPricing.Price',
),
),
'VirtualFields' => Array (
'FinalPrice' => Array ('type' => 'float', 'formatter' => 'kCombPriceFormatter', 'format' => '%.2f', 'default' => NULL),
'BasePrice' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => NULL),
),
'Grids' => Array (
'Default' => Array (
'Icons' => Array (
'default' => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array (
'Combination' => Array ( 'title' => 'la_col_Combination', 'data_block' => 'grid_combination_td', 'filter_block' => 'grid_empty_filter'),
'SKU' => Array ( 'filter_block' => 'grid_like_filter'),
'Availability' => Array ( 'filter_block' => 'grid_options_filter'),
'Price' => Array ( 'data_block' => 'price_td', 'filter_block' => 'grid_range_filter'),
// 'Weight' => Array ( 'data_block' => 'weight_td', 'filter_block' => 'grid_range_filter'),
),
),
'Inventory' => Array (
'Icons' => Array (
'default' => 'icon16_item.png',
'module' => 'core',
),
'Selector' => 'radio',
'Fields' => Array (
'Combination' => Array ('title' => 'la_col_Combination', 'data_block' => 'grid_combination_td', 'filter_block' => 'grid_empty_filter'),
'SKU' => Array ('filter_block' => 'grid_like_filter'),
'QtyInStock' => Array ('filter_block' => 'grid_range_filter'),
'QtyReserved' => Array ('filter_block' => 'grid_range_filter'),
'QtyBackOrdered' => Array ('filter_block' => 'grid_range_filter'),
'QtyOnOrder' => Array ('filter_block' => 'grid_range_filter'),
),
),
'Radio' => Array (
'Selector' => 'radio',
'Icons' => Array (
'default' => 'icon16_item.png',
'module' => 'core',
),
'Fields' => Array (
'Combination' => Array ( 'title' => 'la_col_Combination', 'data_block' => 'grid_combination_td', 'filter_block' => 'grid_empty_filter'),
'FinalPrice' => Array ( 'title' => 'column:la_fld_Price', 'data_block' => 'grid_data_td', 'currency' => 'primary', 'filter_block' => 'grid_range_filter'),
// 'Weight' => Array ('data_block' => 'weight_td', 'filter_block' => 'grid_range_filter'),
),
),
),
);
\ 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 15133)
+++ branches/5.2.x/units/payment_type/payment_type_event_handler.php (revision 15134)
@@ -1,295 +1,295 @@
<?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
{
/**
* Define alternative event processing method names
*
* @return void
* @see kEventHandler::$eventMethods
* @access protected
*/
protected 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 standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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)
+ 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->SetRedirectParam('opener', 's');
}
- function OnMassDecline(&$event)
+ function OnMassDecline($event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$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->SetRedirectParam('opener', 's');
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') );
if ( $object->GetDBField('IsPrimary') == 1 && $object->GetDBField($status_field) == 0 ) {
$object->SetDBField($status_field, 1);
}
$this->convertGroups($event);
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->convertGroups($event);
}
/**
* Disable delete on primary payment type
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
$object =& $event->getObject();
/* @var $object kDBItem */
$ids_ok = Array ();
$ids = $event->getEventParam('ids');
foreach ($ids as $id) {
$object->Load($id);
if ( $object->GetDBField('IsPrimary') ) {
$this->Application->StoreVar('pt_delete_error', '1');
}
else {
$ids_ok[] = $id;
}
}
$event->setEventParam('ids', $ids_ok);
}
}
/**
* 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(kEvent &$event)
+ protected function OnSave(kEvent $event)
{
$this->Application->StoreVar('check_unused_currencies', 1);
parent::OnSave($event);
}
/**
* Sets default payment type group
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $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)
+ 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
* @access public
*/
- public function getPassedID(kEvent &$event)
+ public function getPassedID(kEvent $event)
{
if ( $event->Special == 'auto-ord' ) {
$main_object =& $this->Application->recallObject('ord');
/* @var $main_object kDBItem */
return $main_object->GetDBField('PaymentType');
}
elseif ( substr($event->Special, 0, 3) == 'gw-' ) {
// returns first matched enabled payment type
return Array (
'Status' => STATUS_ACTIVE,
TABLE_PREFIX . 'Gateways.Name' => $event->getEventParam('gateway')
);
}
return parent::getPassedID($event);
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $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 15133)
+++ branches/5.2.x/units/manufacturers/manufacturers_event_handler.php (revision 15134)
@@ -1,137 +1,137 @@
<?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 standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnItemBuild' => Array('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
if ( $this->Application->isAdminUser ) {
return;
}
$category_id = $this->Application->GetVar('m_cat_id');
$parent_category_id = $event->getEventParam('parent_cat_id');
if ( (string)$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 . 'Categories 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();
/* @var $object kDBList */
$object->addFilter('category_manufacturer_filter', $manufacturers ? '%1$s.ManufacturerId IN (' . implode(',', $manufacturers) . ')' : 'FALSE');
}
/**
* Pre-fills states dropdown with correct values
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemLoad(kEvent &$event)
+ protected function OnAfterItemLoad(kEvent $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
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $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
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $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 15133)
+++ branches/5.2.x/units/shipping/shipping_event_handler.php (revision 15134)
@@ -1,274 +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 ShippingEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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
*/
- protected function OnAfterItemLoad(kEvent &$event)
+ protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
if ( !$this->Application->isAdminUser ) {
return;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$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);
$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)
+ function OnApplyModifier($event)
{
$cost_object =& $this->Application->recallObject('sc');
/* @var $cost_object kDBItem */
$object =& $event->getObject();
/* @var $object kDBItem */
$operation = $this->Application->GetVar('operation');
$formatter =& $this->Application->recallObject('kFormatter');
/* @var $formatter 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 ;
}
$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)
+ 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;
}
/**
* 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(kEvent &$event)
+ protected function OnSave(kEvent $event)
{
$this->OnAfterItemLoad($event);
parent::OnSave($event);
}
/**
* Occurs after creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemCreate(kEvent &$event)
+ protected function OnAfterItemCreate(kEvent $event)
{
parent::OnAfterItemCreate($event);
$event->CallSubEvent('OnAnyChange');
}
/**
* Occurs after updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemUpdate(kEvent &$event)
+ protected function OnAfterItemUpdate(kEvent $event)
{
parent::OnAfterItemUpdate($event);
$event->CallSubEvent('OnAnyChange');
}
/**
* Occurs after deleting item, id of deleted item
* is stored as 'id' param of event
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemDelete(kEvent &$event)
+ protected function OnAfterItemDelete(kEvent $event)
{
parent::OnAfterItemDelete($event);
$event->CallSubEvent('OnAnyChange');
}
- function OnAnyChange(&$event)
+ function OnAnyChange($event)
{
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'SystemCache
WHERE VarName LIKE "ShippingQuotes%"';
$this->Conn->Query($sql);
}
/**
* 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(kEvent &$event)
+ protected function OnPreSaveCreated(kEvent $event)
{
parent::OnPreSaveCreated($event);
$object =& $event->getObject( Array ('skip_autoload' => true) );
/* @var $object kDBItem */
$object->SetDBField('PortalGroups', ',' . $this->Application->ConfigValue('User_LoggedInGroup') . ',');
}
- function UpdateGroups(&$event)
+ function UpdateGroups($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
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);
}
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $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 15133)
+++ branches/5.2.x/units/taxes/taxes_event_handler.php (revision 15134)
@@ -1,253 +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 TaxesEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnTypeChange' => Array('self' => 'add|edit'),
'OnCountryChange' => Array('self' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Define alternative event processing method names
*
* @return void
* @see kEventHandler::$eventMethods
* @access protected
*/
protected 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);
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
$zone_object =& $event->getObject();
/* @var $zone_object kDBItem */
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();
}
$this->Application->SetVar('taxdst', $temp);
}
- $dst_event = new kEvent('taxdst:OnCreate');
- $this->Application->HandleEvent($dst_event);
+ $this->Application->HandleEvent(new kEvent('taxdst:OnCreate'));
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnTypeChange(&$event)
+ function OnTypeChange($event)
{
$this->Application->DeleteVar('taxdst');
$event->CallSubEvent('OnPreSave');
$event->redirect = false;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function DestinationAction(&$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 OnCountryChange(&$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 15133)
+++ branches/5.2.x/units/coupons/coupons_event_handler.php (revision 15134)
@@ -1,234 +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 CouponsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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)
+ 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);
}
/**
* 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(kEvent &$event)
+ protected function OnBeforeClone(kEvent $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)
+ 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, $this->getRequestProtectedFields($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);
}
$event->SetRedirectParam('opener', 'u');
}
/**
* Sets fields required during coupon cloning
*
* @param kDBItem $object
* @return void
* @access protected
*/
protected function setCloningRequired(&$object)
{
$this->RemoveRequiredFields($object);
$object->setRequired('CouponCount');
$object->setRequired('DefaultExpiration');
}
function SetNewCode(&$item)
{
do{
$new_code = $this->RandomCouponCode();
$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()
{
$rand_code = '';
for ($i = 0; $i < 10; $i++) {
$is_letter = rand(0, 1);
$rand_code .= ($is_letter ? chr(rand(65, 90)) : rand(0, 9));
}
return $rand_code;
}
/**
* 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(kEvent &$event)
+ protected function OnPreCreate(kEvent $event)
{
parent::OnPreCreate($event);
$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;
}
$object->SetDBField('Expiration_date', $exp_date);
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->itemChanged($event);
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->itemChanged($event);
}
/**
* Occurs before item is changed
*
* @param kEvent $event
*/
- function itemChanged(&$event)
+ function itemChanged($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/discount_items/discount_items_event_handler.php
===================================================================
--- branches/5.2.x/units/discount_items/discount_items_event_handler.php (revision 15133)
+++ branches/5.2.x/units/discount_items/discount_items_event_handler.php (revision 15134)
@@ -1,161 +1,161 @@
<?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 DiscountItemsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnEntireOrder' => Array ('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Adds products from selected categories and their sub-categories and directly selected products to discount items with duplicate checking
*
* @param kEvent $event
*/
- function OnProcessSelected(&$event)
+ function OnProcessSelected($event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$selected_ids = $this->Application->GetVar('selected_ids');
if ($selected_ids['c'] == $this->Application->GetVar('m_cat_id')) {
// no categories were selected, so selector returned current in catalog. This is not needed here
$selected_ids['c'] = '';
}
$table_data = $object->getLinkedInfo();
// in selectors we could select category & item together
$prefixes = Array('c', 'p');
foreach ($prefixes as $prefix) {
$item_ids = $selected_ids[$prefix] ? explode(',', $selected_ids[$prefix]) : Array();
if (!$item_ids) continue;
if ($prefix == 'c') {
// select all products from selected categories and their subcategories
$sql = 'SELECT DISTINCT p.ResourceId
FROM '.TABLE_PREFIX.'Categories c
LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON c.CategoryId = ci.CategoryId
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ResourceId = ci.ItemResourceId
WHERE (p.ProductId IS NOT NULL) AND (c.ParentPath LIKE "%|'.implode('|%" OR c.ParentPath LIKE "%|', $item_ids).'|%")';
$resource_ids = $this->Conn->GetCol($sql);
}
else {
// select selected prodcts
$sql = 'SELECT ResourceId
FROM '.$this->Application->getUnitOption($prefix, 'TableName').'
WHERE '.$this->Application->getUnitOption($prefix, 'IDField').' IN ('.implode(',', $item_ids).')';
$resource_ids = $this->Conn->GetCol($sql);
}
if (!$resource_ids) continue;
$sql = 'SELECT ItemResourceId
FROM '.$object->TableName.'
WHERE ('.$table_data['ForeignKey'].' = '.$table_data['ParentId'].') AND (ItemResourceId IN ('.implode(',', $resource_ids).'))';
// 1. don't insert items, that are already in
$skip_resource_ids = $this->Conn->GetCol($sql);
$resource_ids = array_diff($resource_ids, $skip_resource_ids); // process only not already in db resourceids for current discount
// 2. insert ids, that left
foreach ($resource_ids as $resource_id) {
$object->SetDBField($table_data['ForeignKey'], $table_data['ParentId']);
$object->SetDBField('ItemResourceId', $resource_id);
$object->SetDBField('ItemType', 1);
$object->Create();
}
}
$this->finalizePopup($event);
}
/**
* Allows to set discount on entire order
*
* @param kEvent $event
* @todo get parent item id through $object->getLinkedInfo()['ParentId']
* @access public
*/
- function OnEntireOrder(&$event)
+ function OnEntireOrder($event)
{
$object =& $event->GetObject();
$sql = 'DELETE FROM '.$object->TableName.' WHERE DiscountId='.$this->Application->GetVar('d_id');
$this->Conn->Query($sql);
$object->SetDBField('DiscountId', $this->Application->GetVar('d_id'));
$object->SetDBField('ItemResourceId', -1);
$object->SetDBField('ItemType', 0);
if ( $object->Create() ) {
$this->customProcessing($event,'after');
$event->status = kEvent::erSUCCESS;
$event->SetRedirectParam('opener', 's');
}
else {
$event->status = kEvent::erFAIL;
$this->Application->SetVar($event->getPrefixSpecial().'_SaveEvent','OnCreate');
$object->setID(0);
}
}
/**
* Deletes discount items where hooked item (product) is used
*
* @param kEvent $event
*/
- function OnDeleteDiscountedItem(&$event)
+ function OnDeleteDiscountedItem($event)
{
$main_object =& $event->MasterEvent->getObject();
$resource_id = $main_object->GetDBField('ResourceId');
$table = $this->Application->getUnitOption($event->Prefix,'TableName');
$sql = 'DELETE FROM '.$table.' WHERE ItemResourceId = '.$resource_id;
$this->Conn->Query($sql);
}
/**
* Makes ItemName calculated field from primary language
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
$calculated_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
$language_id = $this->Application->GetVar('m_lang');
$primary_language_id = $this->Application->GetDefaultLanguageId();
$calculated_fields['']['ItemName'] = 'COALESCE(p.l' . $language_id . '_Name, p.l' . $primary_language_id . '_Name)';
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calculated_fields);
}
}
\ 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 15133)
+++ branches/5.2.x/units/shipping_costs/shipping_costs_event_handler.php (revision 15134)
@@ -1,301 +1,299 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class ShippingCostsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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);
}
/**
* Creates new kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnCreate(kEvent &$event)
+ protected function OnCreate(kEvent $event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$zones_object =& $this->Application->recallObject('z');
$sql = 'SELECT ZoneID
FROM ' . $zones_object->TableName . '
WHERE ShippingTypeID = ' . $this->Application->GetVar('s_id');
$res = $this->Conn->GetCol($sql);
$sql = 'DELETE FROM ' . $object->TableName . '
WHERE ZoneID IN (' . implode(',', $res) . ')';
$this->Conn->Query($sql);
// creates multiple db records from single request (OnCreate event only creates 1 record)
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
foreach ($items_info as $field_values) {
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($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)
+ function OnPropagate($event)
{
- // $this->OnCreate(&$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 = new kEvent('s:OnPreSave');
$shipping_event->status = kEvent::erFATAL;
- $this->Application->HandleEvent(&$shipping_event);*/
+ $this->Application->HandleEvent($shipping_event);*/
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnClearAll(&$event)
+ function OnClearAll($event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$zones_object =& $this->Application->recallObject('z');
/* @var $zones_object kDBItem */
$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));
$event->status = kEvent::erSUCCESS;
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
if ( $type == 'before' && $this->Application->GetVar('sc') ) {
$shipping_obj =& $this->Application->recallObject('s');
/* @var $shipping_obj kDBItem */
$object =& $event->getObject();
/* @var $object kDBItem */
$zero_if_empty = $shipping_obj->GetDBField('ZeroIfEmpty');
if ( $object->GetDBField('Flat') == '' ) {
$flat = $zero_if_empty ? 0 : null;
$object->SetDBField('Flat', $flat);
}
if ( $object->GetDBField('PerUnit') == '' ) {
$per_unit = $zero_if_empty ? 0 : null;
$object->SetDBField('PerUnit', $per_unit);
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnSaveCreated(&$event)
+ function OnSaveCreated($event)
{
$event->CallSubEvent('OnCreate');
$event->redirect = false;
$event->setRedirectParams(Array ('opener' => 's', 'pass' => 'all'));
}
/**
* Occurs after an item has been copied to temp
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterCopyToTemp(kEvent &$event)
+ protected function OnAfterCopyToTemp(kEvent $event)
{
parent::OnAfterCopyToTemp($event);
$id = $event->getEventParam('id');
$object =& $this->Application->recallObject($event->Prefix . '.-item', $event->Prefix);
/* @var $object kDBItem */
$object->SwitchToTemp();
$object->Load($id);
$shipping_obj =& $this->Application->recallObject('s');
/* @var $shipping_obj kDBItem */
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
// 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);
}
}
/**
* Occurs before an item is copied to live table (after all foreign keys have been updated)
* Id of item being copied is passed as event' 'id' param
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeCopyToLive(kEvent &$event)
+ protected function OnBeforeCopyToLive(kEvent $event)
{
parent::OnBeforeCopyToLive($event);
$id = $event->getEventParam('id');
$object =& $this->Application->recallObject($event->Prefix . '.-item', $event->Prefix);
/* @var $object kDBItem */
$object->SwitchToTemp();
$object->Load($id);
$shipping_obj =& $this->Application->recallObject('s');
/* @var $shipping_obj kDBItem */
$lang_object =& $this->Application->recallObject('lang.current');
/* @var $lang_object LanguagesItem */
// 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 15133)
+++ branches/5.2.x/units/zones/zones_event_handler.php (revision 15134)
@@ -1,276 +1,275 @@
<?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 standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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);
}
/**
* Define alternative event processing method names
*
* @return void
* @see kEventHandler::$eventMethods
* @access protected
*/
protected function mapEvents()
{
parent::mapEvents(); // ensure auto-adding of approve/decline and so on events
$zones_events = Array(
'OnAddLocation' => 'DestinationAction',
'OnRemoveLocation' => 'DestinationAction',
'OnLoadZoneForm' => 'DestinationAction',
/*'OnCountryChange' => 'DestinationAction',*/
);
$this->eventMethods = array_merge($this->eventMethods, $zones_events);
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
$zone_object =& $event->getObject();
/* @var $zone_object kDBItem */
switch ($type) {
case 'before':
if ( $event->Name == 'OnCreate' ) {
$zone_object->SetDBField('ShippingTypeID', $this->Application->GetVar('s_id'));
}
break;
case 'after':
$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', Array ());
foreach ($temp as $key => $value) {
$temp[$key]['ShippingZoneId'] = $zone_object->GetID();
}
$this->Application->SetVar('dst', $temp);
}
- $dst_event = new kEvent('dst:OnCreate');
- $this->Application->HandleEvent($dst_event);
+ $this->Application->HandleEvent(new kEvent('dst:OnCreate'));
break;
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnTypeChange(&$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)
+ 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 OnCountryChange(&$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;
}
/**
* Cancels kDBItem Editing/Creation
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnCancel(kEvent &$event)
+ protected function OnCancel(kEvent $event)
{
parent::OnCancel($event);
$dst_object = &$this->Application->recallObject('dst');
/* @var $dst_object kDBItem */
$sql = 'DELETE FROM ' . $dst_object->TableName . '
WHERE ShippingZoneId = 0';
$this->Conn->Query($sql);
// if cancelling after create
if ( $this->Application->RecallVar('zone_mode' . $this->Application->GetVar('m_wid')) == 'create' ) {
$zone =& $event->getObject();
/* @var $zone kDBItem */
$zone->Delete();
}
}
/**
* Prepares new kDBItem object
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnNew(kEvent &$event)
+ protected function OnNew(kEvent $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/orders/orders_event_handler.php
===================================================================
--- branches/5.2.x/units/orders/orders_event_handler.php (revision 15133)
+++ branches/5.2.x/units/orders/orders_event_handler.php (revision 15134)
@@ -1,3985 +1,3984 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class OrdersEventHandler extends kDBEventHandler
{
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
- public function CheckPermission(kEvent &$event)
+ public function CheckPermission(kEvent $event)
{
if ( !$this->Application->isAdminUser ) {
if ( $event->Name == 'OnCreate' ) {
// user can't initiate custom order creation directly
return false;
}
$user_id = $this->Application->RecallVar('user_id');
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( $items_info ) {
// when POST is present, then check when is beeing submitted
$order_session_id = $this->Application->RecallVar($event->getPrefixSpecial(true) . '_id');
$order_dummy =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true));
/* @var $order_dummy OrdersItem */
foreach ($items_info as $id => $field_values) {
if ( $order_session_id != $id ) {
// user is trying update not his order, even order from other guest
return false;
}
$order_dummy->Load($id);
// session_id matches order_id from submit
if ( $order_dummy->GetDBField('PortalUserId') != $user_id ) {
// user performs event on other user order
return false;
}
$status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField'));
if ( isset($field_values[$status_field]) && $order_dummy->GetDBField($status_field) != $field_values[$status_field] ) {
// user can't change status by himself
return false;
}
if ( $order_dummy->GetDBField($status_field) != ORDER_STATUS_INCOMPLETE ) {
// user can't edit orders being processed
return false;
}
if ( $event->Name == 'OnUpdate' ) {
// all checks were ok -> it's user's order -> allow to modify
return true;
}
}
}
}
if ( $event->Name == 'OnQuietPreSave' ) {
$section = $event->getSection();
if ( $this->isNewItemCreate($event) ) {
return $this->Application->CheckPermission($section . '.add', 1);
}
else {
return $this->Application->CheckPermission($section . '.add', 1) || $this->Application->CheckPermission($section . '.edit', 1);
}
}
return parent::CheckPermission($event);
}
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
// admin
'OnRecalculateItems' => Array('self' => 'add|edit'),
'OnResetToUser' => Array('self' => 'add|edit'),
'OnResetToBilling' => Array('self' => 'add|edit'),
'OnResetToShipping' => Array('self' => 'add|edit'),
'OnMassOrderApprove' => Array('self' => 'advanced:approve'),
'OnMassOrderDeny' => Array('self' => 'advanced:deny'),
'OnMassOrderArchive' => Array('self' => 'advanced:archive'),
'OnMassPlaceOrder' => Array('self' => 'advanced:place'),
'OnMassOrderProcess' => Array('self' => 'advanced:process'),
'OnMassOrderShip' => Array('self' => 'advanced:ship'),
'OnResetToPending' => Array('self' => 'advanced:reset_to_pending'),
'OnLoadSelected' => Array('self' => 'view'), // print in this case
'OnGoToOrder' => Array('self' => 'view'),
// front-end
'OnViewCart' => Array('self' => true),
'OnAddToCart' => Array('self' => true),
'OnRemoveFromCart' => Array('self' => true),
'OnUpdateCart' => Array('self' => true),
'OnUpdateCartJSON' => Array('self' => true),
'OnUpdateItemOptions' => Array('self' => true),
'OnCleanupCart' => Array('self' => true),
'OnContinueShopping' => Array('self' => true),
'OnCheckout' => Array('self' => true),
'OnSelectAddress' => Array('self' => true),
'OnProceedToBilling' => Array('self' => true),
'OnProceedToPreview' => Array('self' => true),
'OnCompleteOrder' => Array('self' => true),
'OnUpdateAjax' => Array('self' => true),
'OnRemoveCoupon' => Array('self' => true),
'OnRemoveGiftCertificate' => Array('self' => true),
'OnCancelRecurring' => Array('self' => true),
'OnAddVirtualProductToCart' => Array('self' => true),
'OnItemBuild' => Array('self' => true),
'OnDownloadLabel' => Array('self' => true, 'subitem' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Define alternative event processing method names
*
* @return void
* @see kEventHandler::$eventMethods
* @access protected
*/
protected function mapEvents()
{
parent::mapEvents();
$common_events = Array (
'OnResetToUser' => 'OnResetAddress',
'OnResetToBilling' => 'OnResetAddress',
'OnResetToShipping' => 'OnResetAddress',
'OnMassOrderProcess' => 'MassInventoryAction',
'OnMassOrderApprove' => 'MassInventoryAction',
'OnMassOrderDeny' => 'MassInventoryAction',
'OnMassOrderArchive' => 'MassInventoryAction',
'OnMassOrderShip' => 'MassInventoryAction',
'OnOrderProcess' => 'InventoryAction',
'OnOrderApprove' => 'InventoryAction',
'OnOrderDeny' => 'InventoryAction',
'OnOrderArchive' => 'InventoryAction',
'OnOrderShip' => 'InventoryAction',
);
$this->eventMethods = array_merge($this->eventMethods, $common_events);
}
/* ======================== FRONT ONLY ======================== */
- function OnQuietPreSave(&$event)
+ function OnQuietPreSave($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$object->IgnoreValidation = true;
$event->CallSubEvent('OnPreSave');
$object->IgnoreValidation = false;
}
/**
* Sets new address to order
*
* @param kEvent $event
*/
- function OnSelectAddress(&$event)
+ function OnSelectAddress($event)
{
if ($this->Application->isAdminUser) {
return ;
}
$object =& $event->getObject();
/* @var $object OrdersItem */
$shipping_address_id = $this->Application->GetVar('shipping_address_id');
$billing_address_id = $this->Application->GetVar('billing_address_id');
if ($shipping_address_id || $billing_address_id) {
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$address =& $this->Application->recallObject('addr.-item','addr', Array('skip_autoload' => true));
/* @var $address AddressesItem */
$addr_list =& $this->Application->recallObject('addr', 'addr_List', Array('per_page'=>-1, 'skip_counting'=>true) );
/* @var $addr_list AddressesList */
$addr_list->Query();
}
if ($shipping_address_id > 0) {
$addr_list->CopyAddress($shipping_address_id, 'Shipping');
$address->Load($shipping_address_id);
$address->MarkAddress('Shipping');
$cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
$object->setRequired('ShippingState', false);
}
elseif ($shipping_address_id == -1) {
$object->ResetAddress('Shipping');
}
if ($billing_address_id > 0) {
$addr_list->CopyAddress($billing_address_id, 'Billing');
$address->Load($billing_address_id);
$address->MarkAddress('Billing');
$cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
$object->setRequired('BillingState', false);
}
elseif ($billing_address_id == -1) {
$object->ResetAddress('Billing');
}
$event->redirect = false;
$object->IgnoreValidation = true;
$this->RecalculateTax($event);
$object->Update();
}
/**
* Updates order with registred user id
*
* @param kEvent $event
*/
- function OnUserCreate(&$event)
+ function OnUserCreate($event)
{
if( !($event->MasterEvent->status == kEvent::erSUCCESS) ) return false;
$ses_id = $this->Application->RecallVar('front_order_id');
if($ses_id)
{
$this->updateUserID($ses_id, $event);
$this->Application->RemoveVar('front_order_id');
}
}
/**
* Updates shopping cart with logged-in user details
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnUserLogin(&$event)
+ protected function OnUserLogin($event)
{
if ( ($event->MasterEvent->status != kEvent::erSUCCESS) || kUtil::constOn('IS_INSTALL') ) {
// login failed OR login during installation
return;
}
$ses_id = $this->Application->RecallVar('ord_id');
if ( $ses_id ) {
$this->updateUserID($ses_id, $event);
}
$user_id = $this->Application->RecallVar('user_id');
$affiliate_id = $this->isAffiliate($user_id);
if ( $affiliate_id ) {
$this->Application->setVisitField('AffiliateId', $affiliate_id);
}
$event->CallSubEvent('OnRecalculateItems');
}
/**
* Puts ID of just logged-in user into current order
*
* @param int $order_id
* @param kEvent $event
* @return void
*/
- function updateUserID($order_id, &$event)
+ function updateUserID($order_id, $event)
{
$user =& $this->Application->recallObject('u.current');
/* @var $user UsersItem */
$affiliate_id = $this->isAffiliate( $user->GetID() );
$fields_hash = Array (
'PortalUserId' => $user->GetID(),
'BillingEmail' => $user->GetDBField('Email'),
);
if ( $affiliate_id ) {
$fields_hash['AffiliateId'] = $affiliate_id;
}
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
$this->Conn->doUpdate($fields_hash, $table_name, $id_field . ' = ' . $order_id);
$object =& $event->getObject();
/* @var $object kDBItem */
// set user id to object, since it will be used during order update from OnRecalculateItems event
$object->SetDBField('PortalUserId', $user->GetID());
}
function isAffiliate($user_id)
{
$affiliate_user =& $this->Application->recallObject('affil.-item', null, Array('skip_autoload' => true) );
/* @var $affiliate_user kDBItem */
$affiliate_user->Load($user_id, 'PortalUserId');
return $affiliate_user->isLoaded() ? $affiliate_user->GetDBField('AffiliateId') : 0;
}
/**
* Charge order
*
* @param OrdersItem $order
* @return Array
*/
function ChargeOrder(&$order)
{
$gw_data = $order->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
/* @var $gateway_object kGWBase */
$payment_result = $gateway_object->DirectPayment($order->GetFieldValues(), $gw_data['gw_params']);
$sql = 'UPDATE %s SET GWResult1 = %s WHERE %s = %s';
$sql = sprintf($sql, $order->TableName, $this->Conn->qstr($gateway_object->getGWResponce()), $order->IDField, $order->GetID() );
$this->Conn->Query($sql);
$order->SetDBField('GWResult1', $gateway_object->getGWResponce() );
return array('result'=>$payment_result, 'data'=>$gateway_object->parsed_responce, 'gw_data' => $gw_data, 'error_msg'=>$gateway_object->getErrorMsg());
}
/**
* Returns parameters, used to send order-related e-mails
*
* @param OrdersItem $order
* @return array
*/
function OrderEmailParams(&$order)
{
$billing_email = $order->GetDBField('BillingEmail');
$user_email = $this->Conn->GetOne(' SELECT Email FROM '.$this->Application->getUnitOption('u', 'TableName').'
WHERE PortalUserId = '.$order->GetDBField('PortalUserId'));
$email_params = Array();
$email_params['_user_email'] = $user_email; //for use when shipping vs user is required in InventoryAction
$email_params['to_email'] = $billing_email ? $billing_email : $user_email;
$email_params['to_name'] = $order->GetDBField('BillingTo');
return $email_params;
}
- function PrepareCoupons(&$event, &$order)
+ function PrepareCoupons($event, &$order)
{
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
/* @var $order_items kDBList */
$order_items->linkToParent($order->Special);
$order_items->Query();
$order_items->GoFirst();
$assigned_coupons = array();
$coup_handler =& $this->Application->recallObject('coup_EventHandler');
foreach($order_items->Records as $product_item)
{
if ($product_item['ItemData']) {
$item_data = unserialize($product_item['ItemData']);
if (isset($item_data['AssignedCoupon']) && $item_data['AssignedCoupon']) {
$coupon_id = $item_data['AssignedCoupon'];
// clone coupon, get new coupon ID
$coupon =& $this->Application->recallObject('coup',null,array('skip_autload' => true));
/* @var $coupon kDBItem */
$coupon->Load($coupon_id);
if (!$coupon->isLoaded()) continue;
$coup_handler->SetNewCode($coupon);
$coupon->NameCopy();
$coupon->SetDBField('Name', $coupon->GetDBField('Name').' (Order #'.$order->GetField('OrderNumber').')');
$coupon->Create();
// add coupon code to array
array_push($assigned_coupons, $coupon->GetDBField('Code'));
}
}
}
/* @var $order OrdersItem */
if ($assigned_coupons) {
$comments = $order->GetDBField('AdminComment');
if ($comments) $comments .= "\r\n";
$comments .= "Issued coupon(s): ". join(',', $assigned_coupons);
$order->SetDBField('AdminComment', $comments);
$order->Update();
}
if ($assigned_coupons) $this->Application->SetVar('order_coupons', join(',', $assigned_coupons));
}
/**
* Completes order if possible
*
* @param kEvent $event
* @return bool
*/
- function OnCompleteOrder(&$event)
+ function OnCompleteOrder($event)
{
$this->LockTables($event);
if ( !$this->CheckQuantites($event) ) {
return;
}
$this->ReserveItems($event);
$order =& $event->getObject();
/* @var $order OrdersItem */
$charge_result = $this->ChargeOrder($order);
if (!$charge_result['result']) {
$this->FreeItems($event);
$this->Application->StoreVar('gw_error', $charge_result['error_msg']);
//$this->Application->StoreVar('gw_error', getArrayValue($charge_result, 'data', 'responce_reason_text') );
$event->redirect = $this->Application->GetVar('failure_template');
$event->SetRedirectParam('m_cat_id', 0);
if ($event->Special == 'recurring') { // if we set failed status for other than recurring special the redirect will not occur
$event->status = kEvent::erFAIL;
}
return false;
}
// call CompleteOrder events for items in order BEFORE SplitOrder (because ApproveEvents are called there)
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
/* @var $order_items kDBList */
$order_items->linkToParent($order->Special);
$order_items->Query(true);
$order_items->GoFirst();
foreach($order_items->Records as $product_item)
{
if (!$product_item['ProductId']) continue; // product may have been deleted
$this->raiseProductEvent('CompleteOrder', $product_item['ProductId'], $product_item);
}
$shipping_control = getArrayValue($charge_result, 'gw_data', 'gw_params', 'shipping_control');
if ($event->Special != 'recurring') {
if ($shipping_control && $shipping_control != SHIPPING_CONTROL_PREAUTH ) {
// we have to do it here, because the coupons are used in the e-mails
$this->PrepareCoupons($event, $order);
}
$this->Application->EmailEventUser('ORDER.SUBMIT', $order->GetDBField('PortalUserId'), $this->OrderEmailParams($order));
$this->Application->EmailEventAdmin('ORDER.SUBMIT');
}
if ($shipping_control === false || $shipping_control == SHIPPING_CONTROL_PREAUTH ) {
$order->SetDBField('Status', ORDER_STATUS_PENDING);
$order->Update();
}
else {
$this->SplitOrder($event, $order);
}
if (!$this->Application->isAdminUser) {
// for tracking code
$this->Application->StoreVar('last_order_amount', $order->GetDBField('TotalAmount'));
$this->Application->StoreVar('last_order_number', $order->GetDBField('OrderNumber'));
$this->Application->StoreVar('last_order_customer', $order->GetDBField('BillingTo'));
$this->Application->StoreVar('last_order_user', $order->GetDBField('Username'));
$event->redirect = $this->Application->GetVar('success_template');
$event->SetRedirectParam('m_cat_id', 0);
}
else
{
// $event->CallSubEvent('OnSave');
}
$order_id = $order->GetId();
$order_idfield = $this->Application->getUnitOption('ord','IDField');
$order_table = $this->Application->getUnitOption('ord','TableName');
$original_amount = $order->GetDBField('SubTotal') + $order->GetDBField('ShippingCost') + $order->GetDBField('VAT') + $order->GetDBField('ProcessingFee') + $order->GetDBField('InsuranceFee') - $order->GetDBField('GiftCertificateDiscount');
$sql = 'UPDATE '.$order_table.'
SET OriginalAmount = '.$original_amount.'
WHERE '.$order_idfield.' = '.$order_id;
$this->Conn->Query($sql);
$this->Application->StoreVar('front_order_id', $order_id);
$this->Application->RemoveVar('ord_id');
$this->Application->Session->SetCookie('shop_cart_cookie', '', strtotime('-1 month'));
}
/**
* Set billing address same as shipping
*
* @param kEvent $event
*/
- function setBillingAddress(&$event)
+ function setBillingAddress($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
if ( $object->HasTangibleItems() ) {
if ( $this->Application->GetVar('same_address') ) {
// copy shipping address to billing
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
list($id, $field_values) = each($items_info);
$address_fields = Array (
'To', 'Company', 'Phone', 'Fax', 'Email',
'Address1', 'Address2', 'City', 'State',
'Zip', 'Country'
);
foreach ($address_fields as $address_field) {
$items_info[$id]['Billing' . $address_field] = $object->GetDBField('Shipping' . $address_field);
}
$this->Application->SetVar($event->getPrefixSpecial(true), $items_info);
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnProceedToPreview(&$event)
+ function OnProceedToPreview($event)
{
$this->setBillingAddress($event);
$event->CallSubEvent('OnUpdate');
$event->redirect = $this->Application->GetVar('preview_template');
}
- function OnViewCart(&$event)
+ function OnViewCart($event)
{
$this->StoreContinueShoppingLink();
$event->redirect = $this->Application->GetVar('viewcart_template');
}
- function OnContinueShopping(&$event)
+ function OnContinueShopping($event)
{
$order_helper =& $this->Application->recallObject('OrderHelper');
/* @var $order_helper OrderHelper */
$template = $this->Application->GetVar('continue_shopping_template');
$event->redirect = $order_helper->getContinueShoppingTemplate($template);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnCheckout(&$event)
+ function OnCheckout($event)
{
$this->OnUpdateCart($event);
if ( !$event->getEventParam('RecalculateChangedCart') ) {
$object =& $event->getObject();
/* @var $object OrdersItem */
if ( !$object->HasTangibleItems() ) {
$object->SetDBField('ShippingTo', '');
$object->SetDBField('ShippingCompany', '');
$object->SetDBField('ShippingPhone', '');
$object->SetDBField('ShippingFax', '');
$object->SetDBField('ShippingEmail', '');
$object->SetDBField('ShippingAddress1', '');
$object->SetDBField('ShippingAddress2', '');
$object->SetDBField('ShippingCity', '');
$object->SetDBField('ShippingState', '');
$object->SetDBField('ShippingZip', '');
$object->SetDBField('ShippingCountry', '');
$object->SetDBField('ShippingType', 0);
$object->SetDBField('ShippingCost', 0);
$object->SetDBField('ShippingCustomerAccount', '');
$object->SetDBField('ShippingTracking', '');
$object->SetDBField('ShippingDate', 0);
$object->SetDBField('ShippingOption', 0);
$object->SetDBField('ShippingInfo', '');
$object->Update();
}
$event->redirect = $this->Application->GetVar('next_step_template');
$order_id = $this->Application->GetVar('order_id');
if ( $order_id !== false ) {
$event->SetRedirectParam('ord_id', $order_id);
}
}
}
/**
* Restores order from cookie
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnRestoreOrder(kEvent &$event)
+ protected function OnRestoreOrder(kEvent $event)
{
if ( $this->Application->isAdmin || $this->Application->RecallVar('ord_id') ) {
// admin OR there is an active order -> don't restore from cookie
return;
}
$shop_cart_cookie = $this->Application->GetVarDirect('shop_cart_cookie', 'Cookie');
if ( !$shop_cart_cookie ) {
return;
}
$user_id = $this->Application->RecallVar('user_id');
$sql = 'SELECT OrderId
FROM ' . TABLE_PREFIX . 'Orders
WHERE (OrderId = ' . (int)$shop_cart_cookie . ') AND (Status = ' . ORDER_STATUS_INCOMPLETE . ') AND (PortalUserId = ' . $user_id . ')';
$order_id = $this->Conn->GetOne($sql);
if ( $order_id ) {
$this->Application->StoreVar('ord_id', $order_id);
}
}
/**
* Redirect user to Billing checkout step
*
* @param kEvent $event
*/
- function OnProceedToBilling(&$event)
+ function OnProceedToBilling($event)
{
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( $items_info ) {
list($id, $field_values) = each($items_info);
$object =& $event->getObject();
/* @var $object kDBItem */
$payment_type_id = $object->GetDBField('PaymentType');
if ( !$payment_type_id ) {
$default_type = $this->_getDefaultPaymentType();
if ( $default_type ) {
$field_values['PaymentType'] = $default_type;
$items_info[$id] = $field_values;
$this->Application->SetVar($event->getPrefixSpecial(true), $items_info);
}
}
}
$event->CallSubEvent('OnUpdate');
$event->redirect = $this->Application->GetVar('next_step_template');
}
/**
* Removes reoccurring mark from the order
*
* @param kEvent $event
* @return void
*/
- protected function OnCancelRecurring(&$event)
+ protected function OnCancelRecurring($event)
{
$order =& $event->getObject();
/* @var $order OrdersItem */
$order->SetDBField('IsRecurringBilling', 0);
$order->Update();
if ( $this->Application->GetVar('cancelrecurring_ok_template') ) {
$event->redirect = $this->Application->GetVar('cancelrecurring_ok_template');
}
}
/**
* Occurs after updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemUpdate(kEvent &$event)
+ protected function OnAfterItemUpdate(kEvent $event)
{
parent::OnAfterItemUpdate($event);
$object =& $event->getObject();
/* @var $object OrdersItem */
$cvv2 = $object->GetDBField('PaymentCVV2');
if ( $cvv2 !== false ) {
$this->Application->StoreVar('CVV2Code', $cvv2);
}
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnUpdate(kEvent &$event)
+ protected function OnUpdate(kEvent $event)
{
$this->setBillingAddress($event);
parent::OnUpdate($event);
if ($this->Application->isAdminUser) {
return ;
}
else {
$event->SetRedirectParam('opener', 's');
}
if ($event->status == kEvent::erSUCCESS) {
$this->createMissingAddresses($event);
}
else {
// strange: recalculate total amount on error
$object =& $event->getObject();
/* @var $object OrdersItem */
$object->SetDBField('TotalAmount', $object->getTotalAmount());
}
}
/**
* Creates new address
*
* @param kEvent $event
*/
- function createMissingAddresses(&$event)
+ function createMissingAddresses($event)
{
if ( !$this->Application->LoggedIn() ) {
return ;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$addr_list =& $this->Application->recallObject('addr', 'addr_List', Array ('per_page' => -1, 'skip_counting' => true));
/* @var $addr_list kDBList */
$addr_list->Query();
$address_dummy =& $this->Application->recallObject('addr.-item', null, Array ('skip_autoload' => true));
/* @var $address_dummy AddressesItem */
$address_prefixes = Array ('Billing', 'Shipping');
$address_fields = Array (
'To', 'Company', 'Phone', 'Fax', 'Email', 'Address1',
'Address2', 'City', 'State', 'Zip', 'Country'
);
foreach ($address_prefixes as $address_prefix) {
$address_id = $this->Application->GetVar(strtolower($address_prefix) . '_address_id');
if ( !$this->Application->GetVar('check_' . strtolower($address_prefix) . '_address') ) {
// form type doesn't match check type, e.g. shipping check on billing form
continue;
}
if ( $address_id > 0 ) {
$address_dummy->Load($address_id);
}
else {
$address_dummy->SetDBField('PortalUserId', $this->Application->RecallVar('user_id'));
}
foreach ($address_fields as $address_field) {
$address_dummy->SetDBField($address_field, $object->GetDBField($address_prefix . $address_field));
}
$address_dummy->MarkAddress($address_prefix, false);
$ret = ($address_id > 0) ? $address_dummy->Update() : $address_dummy->Create();
}
}
/**
* Updates shopping cart content
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnUpdateCart(&$event)
+ protected function OnUpdateCart($event)
{
- $this->Application->HandleEvent($items_event, 'orditems:OnUpdate');
+ $this->Application->HandleEvent(new kEvent('orditems:OnUpdate'));
$event->CallSubEvent('OnRecalculateItems');
}
/**
* Updates cart and returns various info in JSON format
*
* @param kEvent $event
*/
- function OnUpdateCartJSON(&$event)
+ function OnUpdateCartJSON($event)
{
if ( $this->Application->GetVar('ajax') != 'yes' ) {
return;
}
$object =& $event->getObject();
/* @var $object kDBItem */
// 1. delete given order item by id
$delete_id = $this->Application->GetVar('delete_id');
if ( $delete_id !== false ) {
$sql = 'DELETE FROM ' . TABLE_PREFIX . 'OrderItems
WHERE OrderId = ' . $object->GetID() . ' AND OrderItemId = ' . (int)$delete_id;
$this->Conn->Query($sql);
}
// 2. remove coupon
$remove = $this->Application->GetVar('remove');
if ( $remove == 'coupon' ) {
$this->RemoveCoupon($object);
$object->setCheckoutError(OrderCheckoutErrorType::COUPON, OrderCheckoutError::COUPON_REMOVED);
}
elseif ( $remove == 'gift_certificate' ) {
$this->RemoveGiftCertificate($object);
$object->setCheckoutError(OrderCheckoutErrorType::GIFT_CERTIFICATE, OrderCheckoutError::GC_REMOVED);
}
// 3. update product quantities and recalculate all discounts
- $this->Application->HandleEvent($items_event, 'orditems:OnUpdate');
+ $this->Application->HandleEvent(new kEvent('orditems:OnUpdate'));
$event->CallSubEvent('OnRecalculateItems');
// 4. remove "orditems" object of kDBItem class, since getOrderInfo uses kDBList object under same prefix
$this->Application->removeObject('orditems');
$order_helper =& $this->Application->recallObject('OrderHelper');
/* @var $order_helper OrderHelper */
$event->status = kEvent::erSTOP;
$currency = $this->Application->GetVar('currency', 'selected');
echo json_encode( $order_helper->getOrderInfo($object, $currency) );
}
/**
* Adds item to cart
*
* @param kEvent $event
*/
- function OnAddToCart(&$event)
+ function OnAddToCart($event)
{
$this->StoreContinueShoppingLink();
$qty = $this->Application->GetVar('qty');
$options = $this->Application->GetVar('options');
// multiple or options add
$items = Array();
if (is_array($qty)) {
foreach ($qty as $item_id => $combinations)
{
if (is_array($combinations)) {
foreach ($combinations as $comb_id => $comb_qty) {
if ($comb_qty == 0) continue;
$items[] = array('item_id' => $item_id, 'qty' => $comb_qty, 'comb' => $comb_id);
}
}
else {
$items[] = array('item_id' => $item_id, 'qty' => $combinations);
}
}
}
if (!$items) {
if (!$qty || is_array($qty)) $qty = 1;
$item_id = $this->Application->GetVar('p_id');
if (!$item_id) return ;
$items = array(array('item_id' => $item_id, 'qty' => $qty));
}
// remember item data passed to event when called
$default_item_data = $event->getEventParam('ItemData');
$default_item_data = $default_item_data ? unserialize($default_item_data) : Array();
foreach ($items as $an_item) {
$item_id = $an_item['item_id'];
$qty = $an_item['qty'];
$comb = getArrayValue($an_item, 'comb');
$item_data = $default_item_data;
$product =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
/* @var $product ProductsItem */
$product->Load($item_id);
$event->setEventParam('ItemData', null);
if ($product->GetDBField('AssignedCoupon')) {
$item_data['AssignedCoupon'] = $product->GetDBField('AssignedCoupon');
}
// 1. store options information OR
if ($comb) {
$combination = $this->Conn->GetOne('SELECT Combination FROM '.TABLE_PREFIX.'ProductOptionCombinations WHERE CombinationId = '.$comb);
$item_data['Options'] = unserialize($combination);
}
elseif (is_array($options)) {
$item_data['Options'] = $options[$item_id];
}
// 2. store subscription information OR
if( $product->GetDBField('Type') == 2 ) // subscriptions
{
$item_data = $this->BuildSubscriptionItemData($item_id, $item_data);
}
// 3. store package information
if( $product->GetDBField('Type') == 5 ) // package
{
$package_content_ids = $product->GetPackageContentIds();
$product_package_item =& $this->Application->recallObject('p.-packageitem');
/* @var $product_package_item ProductsItem */
$package_item_data = array();
foreach ($package_content_ids as $package_item_id){
$product_package_item->Load($package_item_id);
$package_item_data[$package_item_id] = array();
if( $product_package_item->GetDBField('Type') == 2 ) // subscriptions
{
$package_item_data[$package_item_id] = $this->BuildSubscriptionItemData($package_item_id, $item_data);
}
}
$item_data['PackageContent'] = $product->GetPackageContentIds();
$item_data['PackageItemsItemData'] = $package_item_data;
}
$event->setEventParam('ItemData', serialize($item_data));
// 1 for PacakgeNum when in admin - temporary solution to overcome splitting into separate sub-orders
// of orders with items added through admin when approving them
$this->AddItemToOrder($event, $item_id, $qty, $this->Application->isAdminUser ? 1 : null);
}
if ($event->status == kEvent::erSUCCESS && !$event->redirect) {
$event->SetRedirectParam('pass', 'm');
$event->SetRedirectParam('pass_category', 0); //otherwise mod-rewrite shop-cart URL will include category
$event->redirect = true;
}
else {
if ($this->Application->isAdminUser) {
$event->SetRedirectParam('opener', 'u');
}
}
}
/**
* Returns table prefix from event (temp or live)
*
* @param kEvent $event
* @return string
* @todo Needed? Should be refactored (by Alex)
*/
- function TablePrefix(kEvent &$event)
+ function TablePrefix(kEvent $event)
{
return $this->UseTempTables($event) ? $this->Application->GetTempTablePrefix('prefix:' . $event->Prefix) . TABLE_PREFIX : TABLE_PREFIX;
}
/**
* Check if required options are selected & selected option combination is in stock
*
* @param kEvent $event
* @param Array $options
* @param int $product_id
* @param int $qty
* @param int $selection_mode
* @return bool
*/
- function CheckOptions(&$event, &$options, $product_id, $qty, $selection_mode)
+ function CheckOptions($event, &$options, $product_id, $qty, $selection_mode)
{
// 1. check for required options
$selection_filter = $selection_mode == 1 ? ' AND OptionType IN (1,3,6) ' : '';
$req_options = $this->Conn->GetCol('SELECT ProductOptionId FROM '.TABLE_PREFIX.'ProductOptions WHERE ProductId = '.$product_id.' AND Required = 1 '.$selection_filter);
$result = true;
foreach ($req_options as $opt_id) {
if (!getArrayValue($options, $opt_id)) {
$this->Application->SetVar('opt_error', 1); //let the template know we have an error
$result = false;
}
}
// 2. check for option combinations in stock
$comb_salt = $this->OptionsSalt($options, true);
if ($comb_salt) {
// such option combination is defined explicitly
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$sql = 'SELECT Availability
FROM '.$poc_table.'
WHERE CombinationCRC = '.$comb_salt;
$comb_availble = $this->Conn->GetOne($sql);
// 2.1. check if Availability flag is set, then
if ($comb_availble == 1) {
// 2.2. check for quantity in stock
$table = Array();
$table['poc'] = $this->Application->getUnitOption('poc', 'TableName');
$table['p'] = $this->Application->getUnitOption('p', 'TableName');
$table['oi'] = $this->TablePrefix($event).'OrderItems';
$object =& $event->getObject();
$ord_id = $object->GetID();
// 2.3. check if some amount of same combination & product are not already in shopping cart
$sql = 'SELECT '.
$table['p'].'.InventoryStatus,'.
$table['p'].'.BackOrder,
IF('.$table['p'].'.InventoryStatus = 2, '.$table['poc'].'.QtyInStock, '.$table['p'].'.QtyInStock) AS QtyInStock,
IF('.$table['oi'].'.OrderItemId IS NULL, 0, '.$table['oi'].'.Quantity) AS Quantity
FROM '.$table['p'].'
LEFT JOIN '.$table['poc'].' ON
'.$table['p'].'.ProductId = '.$table['poc'].'.ProductId
LEFT JOIN '.$table['oi'].' ON
('.$table['oi'].'.OrderId = '.$ord_id.') AND
('.$table['oi'].'.OptionsSalt = '.$comb_salt.') AND
('.$table['oi'].'.ProductId = '.$product_id.') AND
('.$table['oi'].'.BackOrderFlag = 0)
WHERE '.$table['poc'].'.CombinationCRC = '.$comb_salt;
$product_info = $this->Conn->GetRow($sql);
if ($product_info['InventoryStatus']) {
$backordering = $this->Application->ConfigValue('Comm_Enable_Backordering');
if (!$backordering || $product_info['BackOrder'] == 0) {
// backordering is not enabled generally or for this product directly, then check quantities in stock
if ($qty + $product_info['Quantity'] > $product_info['QtyInStock']) {
$this->Application->SetVar('opt_error', 2);
$result = false;
}
}
}
}
elseif ($comb_availble !== false) {
$this->Application->SetVar('opt_error', 2);
$result = false;
}
}
if ($result) {
$event->status = kEvent::erSUCCESS;
$shop_cart_template = $this->Application->GetVar('shop_cart_template');
$event->redirect = $this->Application->isAdminUser || !$shop_cart_template ? true : $shop_cart_template;
}
else {
$event->status = kEvent::erFAIL;
}
return $result;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnUpdateItemOptions(&$event)
+ function OnUpdateItemOptions($event)
{
$opt_data = $this->Application->GetVar('options');
$options = getArrayValue($opt_data, $this->Application->GetVar('p_id'));
if (!$options) {
$qty_data = $this->Application->GetVar('qty');
$comb_id = key(getArrayValue($qty_data, $this->Application->GetVar('p_id')));
$options = unserialize($this->Conn->GetOne('SELECT Combination FROM '.TABLE_PREFIX.'ProductOptionCombinations WHERE CombinationId = '.$comb_id));
}
if (!$options) return;
$ord_item =& $this->Application->recallObject('orditems.-opt', null, Array ('skip_autoload' => true));
/* @var $ord_item kDBItem */
$ord_item->Load($this->Application->GetVar('orditems_id'));
// assuming that quantity cannot be changed during order item editing
if (!$this->CheckOptions($event, $options, $ord_item->GetDBField('ProductId'), 0, $ord_item->GetDBField('OptionsSelectionMode'))) return;
$item_data = unserialize($ord_item->GetDBField('ItemData'));
$item_data['Options'] = $options;
$ord_item->SetDBField('ItemData', serialize($item_data));
$ord_item->SetDBField('OptionsSalt', $this->OptionsSalt($options));
$ord_item->Update();
$event->CallSubEvent('OnRecalculateItems');
if ($event->status == kEvent::erSUCCESS && $this->Application->isAdminUser) {
$event->SetRedirectParam('opener', 'u');
}
}
function BuildSubscriptionItemData($item_id, $item_data)
{
$products_table = $this->Application->getUnitOption('p', 'TableName');
$products_idfield = $this->Application->getUnitOption('p', 'IDField');
$sql = 'SELECT AccessGroupId FROM %s WHERE %s = %s';
$item_data['PortalGroupId'] = $this->Conn->GetOne( sprintf($sql, $products_table, $products_idfield, $item_id) );
$pricing_table = $this->Application->getUnitOption('pr', 'TableName');
$pricing_idfield = $this->Application->getUnitOption('pr', 'IDField');
/* TODO check on implementation
$sql = 'SELECT AccessDuration, AccessUnit, DurationType, AccessExpiration FROM %s WHERE %s = %s';
*/
$sql = 'SELECT * FROM %s WHERE %s = %s';
$pricing_id = $this->GetPricingId($item_id, $item_data);
$item_data['PricingId'] = $pricing_id;
$pricing_info = $this->Conn->GetRow( sprintf($sql, $pricing_table, $pricing_idfield, $pricing_id ) );
$unit_secs = Array(1 => 1, 2 => 60, 3 => 3600, 4 => 86400, 5 => 604800, 6 => 2592000, 7 => 31536000);
/* TODO check on implementation (code from customization healtheconomics.org)
$item_data['DurationType'] = $pricing_info['DurationType'];
$item_data['AccessExpiration'] = $pricing_info['AccessExpiration'];
*/
$item_data['Duration'] = $pricing_info['AccessDuration'] * $unit_secs[ $pricing_info['AccessUnit'] ];
return $item_data;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnApplyCoupon(&$event)
+ function OnApplyCoupon($event)
{
$code = $this->Application->GetVar('coupon_code');
if ($code == '') {
return ;
}
$object =& $event->getObject();
/* @var $object OrdersItem */
$coupon =& $this->Application->recallObject('coup', null, Array ('skip_autoload' => true));
/* @var $coupon kDBItem */
$coupon->Load($code, 'Code');
if ( !$coupon->isLoaded() ) {
$event->status = kEvent::erFAIL;
$object->setCheckoutError(OrderCheckoutErrorType::COUPON, OrderCheckoutError::COUPON_CODE_INVALID);
$event->redirect = false; // check!!!
return ;
}
$expire_date = $coupon->GetDBField('Expiration');
$number_of_use = $coupon->GetDBField('NumberOfUses');
if ( $coupon->GetDBField('Status') != 1 || ($expire_date && $expire_date < adodb_mktime()) ||
(isset($number_of_use) && $number_of_use <= 0))
{
$event->status = kEvent::erFAIL;
$object->setCheckoutError(OrderCheckoutErrorType::COUPON, OrderCheckoutError::COUPON_CODE_EXPIRED);
$event->redirect = false;
return ;
}
$last_used = adodb_mktime();
$coupon->SetDBField('LastUsedBy', $this->Application->RecallVar('user_id'));
$coupon->SetDBField('LastUsedOn_date', $last_used);
$coupon->SetDBField('LastUsedOn_time', $last_used);
if ( isset($number_of_use) ) {
$coupon->SetDBField('NumberOfUses', $number_of_use - 1);
if ($number_of_use == 1) {
$coupon->SetDBField('Status', 2);
}
}
$coupon->Update();
$this->Application->setUnitOption('ord', 'AutoLoad', true);
$order =& $this->Application->recallObject('ord');
/* @var $order OrdersItem */
$order->SetDBField('CouponId', $coupon->GetDBField('CouponId'));
$order->SetDBField('CouponName', $coupon->GetDBField('Name')); // calculated field
$order->Update();
$object->setCheckoutError(OrderCheckoutErrorType::COUPON, OrderCheckoutError::COUPON_APPLIED);
// OnApplyCoupon is called as hook for OnUpdateCart/OnCheckout, which calls OnRecalcualate themself
}
/**
* Removes coupon from order
*
* @param kEvent $event
* @deprecated
*/
- function OnRemoveCoupon(&$event)
+ function OnRemoveCoupon($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
$this->RemoveCoupon($object);
$object->setCheckoutError(OrderCheckoutErrorType::COUPON, OrderCheckoutError::COUPON_REMOVED);
$event->CallSubEvent('OnRecalculateItems');
}
/**
* Removes coupon from a given order
*
* @param OrdersItem $object
*/
function RemoveCoupon(&$object)
{
$coupon =& $this->Application->recallObject('coup', null, Array('skip_autoload' => true));
/* @var $coupon kDBItem */
$coupon->Load( $object->GetDBField('CouponId') );
if ( $coupon->isLoaded() ) {
$coupon->SetDBField('NumberOfUses', $coupon->GetDBField('NumberOfUses') + 1);
$coupon->SetDBField('Status', STATUS_ACTIVE);
$coupon->Update();
}
$object->SetDBField('CouponId', 0);
$object->SetDBField('CouponName', ''); // calculated field
$object->SetDBField('CouponDiscount', 0);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnAddVirtualProductToCart(&$event)
+ function OnAddVirtualProductToCart($event)
{
$l_info = $this->Application->GetVar('l');
if($l_info)
{
foreach($l_info as $link_id => $link_info) {}
$item_data['LinkId'] = $link_id;
$item_data['ListingTypeId'] = $link_info['ListingTypeId'];
}
else
{
$link_id = $this->Application->GetVar('l_id');
$sql = 'SELECT ResourceId FROM '.$this->Application->getUnitOption('l', 'TableName').'
WHERE LinkId = '.$link_id;
$sql = 'SELECT ListingTypeId FROM '.$this->Application->getUnitOption('ls', 'TableName').'
WHERE ItemResourceId = '.$this->Conn->GetOne($sql);
$item_data['LinkId'] = $link_id;
$item_data['ListingTypeId'] = $this->Conn->GetOne($sql);
}
$sql = 'SELECT VirtualProductId FROM '.$this->Application->getUnitOption('lst', 'TableName').'
WHERE ListingTypeId = '.$item_data['ListingTypeId'];
$item_id = $this->Conn->GetOne($sql);
$event->setEventParam('ItemData', serialize($item_data));
$this->AddItemToOrder($event, $item_id);
$shop_cart_template = $this->Application->GetVar('shop_cart_template');
if ( $shop_cart_template ) {
$event->redirect = $shop_cart_template;
}
// don't pass unused info to shopping cart, brokes old mod-rewrites
$event->SetRedirectParam('pass', 'm'); // not to pass link id
$event->SetRedirectParam('m_cat_id', 0); // not to pass link id
}
- function OnRemoveFromCart(&$event)
+ function OnRemoveFromCart($event)
{
$ord_item_id = $this->Application->GetVar('orditems_id');
$ord_id = $this->getPassedID($event);
$this->Conn->Query('DELETE FROM '.TABLE_PREFIX.'OrderItems WHERE OrderId = '.$ord_id.' AND OrderItemId = '.$ord_item_id);
$this->OnRecalculateItems($event);
}
- function OnCleanupCart(&$event)
+ function OnCleanupCart($event)
{
$object =& $event->getObject();
$sql = 'DELETE FROM '.TABLE_PREFIX.'OrderItems
WHERE OrderId = '.$this->getPassedID($event);
$this->Conn->Query($sql);
$this->RemoveCoupon($object);
$this->RemoveGiftCertificate($object);
$this->OnRecalculateItems($event);
}
/**
* Returns order id from session or last used
*
* @param kEvent $event
* @return int
* @access public
*/
- public function getPassedID(kEvent &$event)
+ public function getPassedID(kEvent $event)
{
$event->setEventParam('raise_warnings', 0);
$passed = parent::getPassedID($event);
if ( $this->Application->isAdminUser ) {
// work as usual in admin
return $passed;
}
if ( $event->Special == 'last' ) {
// return last order id (for using on thank you page)
$order_id = $this->Application->RecallVar('front_order_id');
return $order_id > 0 ? $order_id : FAKE_ORDER_ID; // FAKE_ORDER_ID helps to keep parent filter for order items set in "kDBList::linkToParent"
}
$ses_id = $this->Application->RecallVar($event->getPrefixSpecial(true) . '_id');
if ( $passed && ($passed != $ses_id) ) {
// order id given in url doesn't match our current order id
$sql = 'SELECT PortalUserId
FROM ' . TABLE_PREFIX . 'Orders
WHERE OrderId = ' . $passed;
$user_id = $this->Conn->GetOne($sql);
if ( $user_id == $this->Application->RecallVar('user_id') ) {
// current user is owner of order with given id -> allow him to view order details
return $passed;
}
else {
// current user is not owner of given order -> hacking attempt
$this->Application->SetVar($event->getPrefixSpecial() . '_id', 0);
return 0;
}
}
// not passed or equals to ses_id
return $ses_id > 0 ? $ses_id : FAKE_ORDER_ID; // FAKE_ORDER_ID helps to keep parent filter for order items set in "kDBList::linkToParent"
}
/**
* Load item if id is available
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function LoadItem(kEvent &$event)
+ protected function LoadItem(kEvent $event)
{
$id = $this->getPassedID($event);
if ( $id == FAKE_ORDER_ID ) {
// if we already know, that there is no such order,
// then don't run database query, that will confirm that
$object =& $event->getObject();
/* @var $object kDBItem */
$object->Clear($id);
return;
}
parent::LoadItem($event);
}
/**
* Creates new shopping cart
*
* @param kEvent $event
*/
- function _createNewCart(&$event)
+ function _createNewCart($event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$this->setNextOrderNumber($event);
$object->SetDBField('Status', ORDER_STATUS_INCOMPLETE);
$object->SetDBField('VisitId', $this->Application->RecallVar('visit_id') );
// get user
if ( $this->Application->LoggedIn() ) {
$user =& $this->Application->recallObject('u.current');
/* @var $user UsersItem */
$user_id = $user->GetID();
$object->SetDBField('BillingEmail', $user->GetDBField('Email'));
}
else {
$user_id = USER_GUEST;
}
$object->SetDBField('PortalUserId', $user_id);
// get affiliate
$affiliate_id = $this->isAffiliate($user_id);
if ( $affiliate_id ) {
$object->SetDBField('AffiliateId', $affiliate_id);
}
else {
$affiliate_storage_method = $this->Application->ConfigValue('Comm_AffiliateStorageMethod');
if ( $affiliate_storage_method == 1 ) {
$object->SetDBField('AffiliateId', (int)$this->Application->RecallVar('affiliate_id'));
}
else {
$object->SetDBField('AffiliateId', (int)$this->Application->GetVar('affiliate_id'));
}
}
// get payment type
$default_type = $this->_getDefaultPaymentType();
if ( $default_type ) {
$object->SetDBField('PaymentType', $default_type);
}
// vat setting
$object->SetDBField('VATIncluded', $this->Application->ConfigValue('OrderVATIncluded'));
$created = $object->Create();
if ( $created ) {
$id = $object->GetID();
$this->Application->SetVar($event->getPrefixSpecial(true) . '_id', $id);
$this->Application->StoreVar($event->getPrefixSpecial(true) . '_id', $id);
$this->Application->Session->SetCookie('shop_cart_cookie', $id, strtotime('+1 month'));
return $id;
}
return 0;
}
/**
* Returns default payment type for order
*
* @return int
*/
function _getDefaultPaymentType()
{
$default_type = $this->Application->siteDomainField('PrimaryPaymentTypeId');
if (!$default_type) {
$sql = 'SELECT PaymentTypeId
FROM ' . TABLE_PREFIX . 'PaymentTypes
WHERE IsPrimary = 1';
$default_type = $this->Conn->GetOne($sql);
}
return $default_type;
}
function StoreContinueShoppingLink()
{
$this->Application->StoreVar('continue_shopping', 'external:'.PROTOCOL.SERVER_NAME.$this->Application->RecallVar('last_url'));
}
/**
* Sets required fields for order, based on current checkout step
* !!! Do not use switch here, since all cases may be on the same form simultaneously
*
* @param kEvent $event
*/
- function SetStepRequiredFields(&$event)
+ function SetStepRequiredFields($event)
{
$order =& $event->getObject();
/* @var $order OrdersItem */
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ($items_info) {
// updated address available from SUBMIT -> use it
list($id, $field_values) = each($items_info);
}
else {
// no updated address -> use current address
$field_values = Array (
'ShippingCountry' => $order->GetDBField('ShippingCountry'),
'BillingCountry' => $order->GetDBField('BillingCountry'),
'PaymentType' => $order->GetDBField('PaymentType'),
);
}
// shipping address required fields
if ($this->Application->GetVar('check_shipping_address')) {
$has_tangibles = $order->HasTangibleItems();
$req_fields = array('ShippingTo', 'ShippingAddress1', 'ShippingCity', 'ShippingZip', 'ShippingCountry', /*'ShippingPhone',*/ 'BillingEmail');
$order->setRequired($req_fields, $has_tangibles);
$order->setRequired('ShippingState', $cs_helper->CountryHasStates( $field_values['ShippingCountry'] ));
}
// billing address required fields
if ($this->Application->GetVar('check_billing_address')) {
$req_fields = array('BillingTo', 'BillingAddress1', 'BillingCity', 'BillingZip', 'BillingCountry', 'BillingPhone', 'BillingEmail');
$order->setRequired($req_fields);
$order->setRequired('BillingState', $cs_helper->CountryHasStates( $field_values['BillingCountry'] ));
}
$check_cc = $this->Application->GetVar('check_credit_card');
if ( $check_cc && ($field_values['PaymentType'] == $order->GetDBField('PaymentType')) ) {
// cc check required AND payment type was not changed during SUBMIT
if ( $this->Application->isAdminUser ) {
$req_fields = Array (/*'PaymentCardType',*/ 'PaymentAccount', /*'PaymentNameOnCard',*/ 'PaymentCCExpDate');
}
else {
$req_fields = Array (/*'PaymentCardType',*/ 'PaymentAccount', /*'PaymentNameOnCard',*/ 'PaymentCCExpDate', 'PaymentCVV2');
}
$order->setRequired($req_fields);
}
}
/**
* Set's order's user_id to user from session or Guest otherwise
*
* @param kEvent $event
*/
- function CheckUser(&$event)
+ function CheckUser($event)
{
if ($this->Application->isAdminUser || defined('GW_NOTIFY')) {
// don't check for user in order while processing payment
// gateways, because they can do cross-domain ssl redirects
return;
}
$order =& $event->getObject();
/* @var $order OrdersItem */
$ses_user = $this->Application->RecallVar('user_id');
if ( $order->GetDBField('PortalUserId') != $ses_user ) {
if ( $ses_user == 0 ) {
$ses_user = USER_GUEST;
}
$order->SetDBField('PortalUserId', $ses_user);
// since CheckUser is called in OnBeforeItemUpdate, we don't need to call udpate here, just set the field
}
}
/* ======================== ADMIN ONLY ======================== */
/**
* Prepare temp tables 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(kEvent &$event)
+ protected function OnPreCreate(kEvent $event)
{
parent::OnPreCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$this->setNextOrderNumber($event);
$object->SetDBField('OrderIP', $_SERVER['REMOTE_ADDR']);
$order_type = $this->getTypeBySpecial( $this->Application->GetVar('order_type') );
$object->SetDBField('Status', $order_type);
}
/**
* When cloning orders set new order number to them
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeClone(kEvent &$event)
+ protected function OnBeforeClone(kEvent $event)
{
parent::OnBeforeClone($event);
$object =& $event->getObject();
/* @var $object OrdersItem */
if ( substr($event->Special, 0, 9) == 'recurring' ) {
$object->SetDBField('SubNumber', $object->getNextSubNumber());
$object->SetDBField('OriginalAmount', 0); // needed in this case ?
}
else {
$this->setNextOrderNumber($event);
$object->SetDBField('OriginalAmount', 0);
}
$object->SetDBField('OrderDate', adodb_mktime());
$object->UpdateFormattersSubFields();
$object->SetDBField('GWResult1', '');
$object->SetDBField('GWResult2', '');
}
- function OnReserveItems(&$event)
+ function OnReserveItems($event)
{
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
/* @var $order_items kDBList */
$order_items->linkToParent('-inv');
// force re-query, since we are updateing through orditem ITEM, not the list, and
// OnReserveItems may be called 2 times when fullfilling backorders through product edit - first time
// from FullFillBackorders and second time from OnOrderProcess
$order_items->Query(true);
$order_items->GoFirst();
// query all combinations used in this order
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
/* @var $product_object kCatDBItem */
$product_object->SwitchToLive();
$order_item =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
/* @var $order_item kDBItem */
$combination_item =& $this->Application->recallObject('poc.-item', null, Array('skip_autoload' => true));
/* @var $combination_item kDBItem */
$combinations = $this->queryCombinations($order_items);
$event->status = kEvent::erSUCCESS;
while (!$order_items->EOL()) {
$rec = $order_items->getCurrentRecord();
$product_object->Load( $rec['ProductId'] );
if (!$product_object->GetDBField('InventoryStatus')) {
$order_items->GoNext();
continue;
}
$inv_object =& $this->getInventoryObject($product_object, $combination_item, $combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ]);
$lack = $rec['Quantity'] - $rec['QuantityReserved'];
if ($lack > 0) {
// reserve lack or what is available (in case if we need to reserve anything, by Alex)
$to_reserve = min($lack, $inv_object->GetDBField('QtyInStock') - $product_object->GetDBField('QtyInStockMin'));
if ($to_reserve < $lack) $event->status = kEvent::erFAIL; // if we can't reserve the full lack
//reserve in order
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetDBField('QuantityReserved', $rec['QuantityReserved'] + $to_reserve);
$order_item->SetId($rec['OrderItemId']);
$order_item->Update();
//update product - increase reserved, decrease in stock
$inv_object->SetDBField('QtyReserved', $inv_object->GetDBField('QtyReserved') + $to_reserve);
$inv_object->SetDBField('QtyInStock', $inv_object->GetDBField('QtyInStock') - $to_reserve);
$inv_object->SetDBField('QtyBackOrdered', $inv_object->GetDBField('QtyBackOrdered') - $to_reserve);
$inv_object->Update();
if ($product_object->GetDBField('InventoryStatus') == 2) {
// inventory by options, then restore changed combination values back to common $combinations array !!!
$combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ] = $inv_object->GetFieldValues();
}
}
$order_items->GoNext();
}
return true;
}
- function OnOrderPrint(&$event)
+ function OnOrderPrint($event)
{
$event->SetRedirectParam('opener', 's');
}
/**
* Processes order each tab info resetting to other tab info / to user info
*
* @param kEvent $event
* @access public
*/
- function OnResetAddress(&$event)
+ function OnResetAddress($event)
{
$to_tab = $this->Application->GetVar('to_tab');
$from_tab = substr($event->Name, strlen('OnResetTo'));
// load values from db
$object =& $event->getObject();
/* @var $object kDBItem */
// update values from submit
$field_values = $this->getSubmittedFields($event);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
$this->DoResetAddress($object, $from_tab, $to_tab);
$object->Update();
$event->redirect = false;
}
/**
* Processes item selection from popup item selector
*
* @todo Is this called ? (by Alex)
* @param kEvent $event
*/
- function OnProcessSelected(&$event)
+ function OnProcessSelected($event)
{
$selected_ids = $this->Application->GetVar('selected_ids');
$product_ids = $selected_ids['p'];
if ($product_ids) {
$product_ids = explode(',', $product_ids);
// !!! LOOK OUT - Adding items to Order in admin is handled in order_ITEMS_event_handler !!!
foreach ($product_ids as $product_id) {
$this->AddItemToOrder($event, $product_id);
}
}
$event->SetRedirectParam('opener', 'u');
}
- function OnMassPlaceOrder(&$event)
+ function OnMassPlaceOrder($event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$ids = $this->StoreSelectedIDs($event);
if($ids)
{
foreach($ids as $id)
{
$object->Load($id);
$this->DoPlaceOrder($event);
}
}
$event->status = kEvent::erSUCCESS;
}
/**
* Universal
* Checks if QtyInStock is enough to fullfill backorder (Qty - QtyReserved in order)
*
* @param int $ord_id
* @return bool
*/
function ReadyToProcess($ord_id)
{
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' SELECT SUM(IF( IF('.TABLE_PREFIX.'Products.InventoryStatus = 2, '.$poc_table.'.QtyInStock, '.TABLE_PREFIX.'Products.QtyInStock) - '.TABLE_PREFIX.'Products.QtyInStockMin >= ('.TABLE_PREFIX.'OrderItems.Quantity - '.TABLE_PREFIX.'OrderItems.QuantityReserved), 0, 1))
FROM '.TABLE_PREFIX.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Products ON '.TABLE_PREFIX.'Products.ProductId = '.TABLE_PREFIX.'OrderItems.ProductId
LEFT JOIN '.$poc_table.' ON ('.$poc_table.'.CombinationCRC = '.TABLE_PREFIX.'OrderItems.OptionsSalt) AND ('.$poc_table.'.ProductId = '.TABLE_PREFIX.'OrderItems.ProductId)
WHERE OrderId = '.$ord_id.'
GROUP BY OrderId';
// IF (IF(InventoryStatus = 2, poc.QtyInStock, p.QtyInStock) - QtyInStockMin >= (Quantity - QuantityReserved), 0, 1
return ($this->Conn->GetOne($query) == 0);
}
/**
* Return all option combinations used in order
*
* @param kDBList $order_items
* @return Array
*/
function queryCombinations(&$order_items)
{
// 1. collect combination crc used in order
$combinations = Array();
while (!$order_items->EOL()) {
$row = $order_items->getCurrentRecord();
if ($row['OptionsSalt'] == 0) {
$order_items->GoNext();
continue;
}
$combinations[] = '(poc.ProductId = '.$row['ProductId'].') AND (poc.CombinationCRC = '.$row['OptionsSalt'].')';
$order_items->GoNext();
}
$order_items->GoFirst();
$combinations = array_unique($combinations); // if same combination+product found as backorder & normal order item
if ($combinations) {
// 2. query data about combinations
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$sql = 'SELECT CONCAT(poc.ProductId, "_", poc.CombinationCRC) AS CombinationKey, poc.*
FROM '.$poc_table.' poc
WHERE ('.implode(') OR (', $combinations).')';
return $this->Conn->Query($sql, 'CombinationKey');
}
return Array();
}
/**
* Returns object to perform inventory actions on
*
* @param ProductsItem $product current product object in order
* @param kDBItem $combination combination dummy object
* @param Array $combination_data pre-queried combination data
* @return kDBItem
*/
function &getInventoryObject(&$product, &$combination, $combination_data)
{
if ($product->GetDBField('InventoryStatus') == 2) {
// inventory by option combinations
$combination->SetDBFieldsFromHash($combination_data);
$combination->setID($combination_data['CombinationId']);
$change_item =& $combination;
}
else {
// inventory by product ifself
$change_item =& $product;
}
return $change_item;
}
/**
* Approve order ("Pending" tab)
*
* @param kDBList $order_items
* @return int new status of order if any
*/
function approveOrder(&$order_items)
{
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
$order_item =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
$combination_item =& $this->Application->recallObject('poc.-item', null, Array('skip_autoload' => true));
$combinations = $this->queryCombinations($order_items);
while (!$order_items->EOL()) {
$rec = $order_items->getCurrentRecord();
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetId($rec['OrderItemId']);
$order_item->SetDBField('QuantityReserved', 0);
$order_item->Update();
$product_object->Load( $rec['ProductId'] );
if (!$product_object->GetDBField('InventoryStatus')) {
// if no inventory info is collected, then skip this order item
$order_items->GoNext();
continue;
}
$inv_object =& $this->getInventoryObject($product_object, $combination_item, $combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ]);
// decrease QtyReserved by amount of product used in order
$inv_object->SetDBField('QtyReserved', $inv_object->GetDBField('QtyReserved') - $rec['Quantity']);
$inv_object->Update();
if ($product_object->GetDBField('InventoryStatus') == 2) {
// inventory by options, then restore changed combination values back to common $combinations array !!!
$combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ] = $inv_object->GetFieldValues();
}
$order_items->GoNext();
}
return true;
}
/**
* Restores reserved items in the order
*
* @param kDBList $order_items
* @return bool
*/
function restoreOrder(&$order_items)
{
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
/* @var $product_object kCatDBItem */
$product_object->SwitchToLive();
$order_item =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
/* @var $order_item kDBItem */
$combination_item =& $this->Application->recallObject('poc.-item', null, Array('skip_autoload' => true));
/* @var $combination_item kDBItem */
$combinations = $this->queryCombinations($order_items);
while( !$order_items->EOL() )
{
$rec = $order_items->getCurrentRecord();
$product_object->Load( $rec['ProductId'] );
if (!$product_object->GetDBField('InventoryStatus')) {
// if no inventory info is collected, then skip this order item
$order_items->GoNext();
continue;
}
$inv_object =& $this->getInventoryObject($product_object, $combination_item, $combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ]);
// cancelling backorderd qty if any
$lack = $rec['Quantity'] - $rec['QuantityReserved'];
if ($lack > 0 && $rec['BackOrderFlag'] > 0) { // lack should have been recorded as QtyBackOrdered
$inv_object->SetDBField('QtyBackOrdered', $inv_object->GetDBField('QtyBackOrdered') - $lack);
}
// canceling reservation in stock
$inv_object->SetDBField('QtyReserved', $inv_object->GetDBField('QtyReserved') - $rec['QuantityReserved']);
// putting remaining freed qty back to stock
$inv_object->SetDBField('QtyInStock', $inv_object->GetDBField('QtyInStock') + $rec['QuantityReserved']);
$inv_object->Update();
$product_h =& $this->Application->recallObject('p_EventHandler');
/* @var $product_h ProductsEventHandler */
if ($product_object->GetDBField('InventoryStatus') == 2) {
// inventory by options, then restore changed combination values back to common $combinations array !!!
$combinations[ $rec['ProductId'].'_'.$rec['OptionsSalt'] ] = $inv_object->GetFieldValues();
// using freed qty to fulfill possible backorders
$product_h->FullfillBackOrders($product_object, $inv_object->GetID());
}
else {
// using freed qty to fulfill possible backorders
$product_h->FullfillBackOrders($product_object, 0);
}
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetId($rec['OrderItemId']);
$order_item->SetDBField('QuantityReserved', 0);
$order_item->Update();
$order_items->GoNext();
}
return true;
}
/**
* Approve order + special processing
*
* @param kEvent $event
*/
- function MassInventoryAction(&$event)
+ function MassInventoryAction($event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
// process order products
$object =& $this->Application->recallObject($event->Prefix . '.-inv', null, Array ('skip_autoload' => true));
/* @var $object kDBItem */
$ids = $this->StoreSelectedIDs($event);
if ( $ids ) {
foreach ($ids as $id) {
$object->Load($id);
$this->InventoryAction($event);
}
}
}
- function InventoryAction(&$event)
+ function InventoryAction($event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$event_status_map = Array(
'OnMassOrderApprove' => ORDER_STATUS_TOSHIP,
'OnOrderApprove' => ORDER_STATUS_TOSHIP,
'OnMassOrderDeny' => ORDER_STATUS_DENIED,
'OnOrderDeny' => ORDER_STATUS_DENIED,
'OnMassOrderArchive' => ORDER_STATUS_ARCHIVED,
'OnOrderArchive' => ORDER_STATUS_ARCHIVED,
'OnMassOrderShip' => ORDER_STATUS_PROCESSED,
'OnOrderShip' => ORDER_STATUS_PROCESSED,
'OnMassOrderProcess' => ORDER_STATUS_TOSHIP,
'OnOrderProcess' => ORDER_STATUS_TOSHIP,
);
$order_items =& $this->Application->recallObject('orditems.-inv','orditems_List',Array('skip_counting'=>true,'per_page'=>-1) );
/* @var $order_items kDBList */
$order_items->linkToParent('-inv');
$order_items->Query();
$order_items->GoFirst();
$object =& $this->Application->recallObject($event->Prefix.'.-inv');
/* @var $object OrdersItem */
if ($object->GetDBField('OnHold')) {
// any actions have no effect while on hold
return ;
}
// save original order status
$original_order_status = $object->GetDBField('Status');
// preparing new status, but not setting it yet
$object->SetDBField('Status', $event_status_map[$event->Name]);
$set_new_status = false;
$event->status = kEvent::erSUCCESS;
$email_params = $this->OrderEmailParams($object);
switch ($event->Name) {
case 'OnMassOrderApprove':
case 'OnOrderApprove':
$set_new_status = false; //on successful approve order will be split and new orders will have new statuses
if ($object->GetDBField('ChargeOnNextApprove')) {
$charge_info = $this->ChargeOrder($object);
if (!$charge_info['result']) {
break;
}
// removing ChargeOnNextApprove
$object->SetDBField('ChargeOnNextApprove', 0);
$sql = 'UPDATE '.$object->TableName.' SET ChargeOnNextApprove = 0 WHERE '.$object->IDField.' = '.$object->GetID();
$this->Conn->Query($sql);
}
// charge user for order in case if we user 2step charging (e.g. AUTH_ONLY + PRIOR_AUTH_CAPTURE)
$gw_data = $object->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
/* @var $gateway_object kGWBase */
$charge_result = $gateway_object->Charge($object->GetFieldValues(), $gw_data['gw_params']);
$sql = 'UPDATE %s SET GWResult2 = %s WHERE %s = %s';
$sql = sprintf($sql, $object->TableName, $this->Conn->qstr($gateway_object->getGWResponce()), $object->IDField, $object->GetID() );
$this->Conn->Query($sql);
$object->SetDBField('GWResult2', $gateway_object->getGWResponce() );
if ($charge_result) {
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
/* @var $product_object ProductsItem */
foreach ($order_items->Records as $product_item) {
if (!$product_item['ProductId']) {
// product may have been deleted
continue;
}
$product_object->Load($product_item['ProductId']);
$hits = floor( $product_object->GetDBField('Hits') ) + 1;
$sql = 'SELECT MAX(Hits) FROM '.$this->Application->getUnitOption('p', 'TableName').'
WHERE FLOOR(Hits) = '.$hits;
$hits = ( $res = $this->Conn->GetOne($sql) ) ? $res + 0.000001 : $hits;
$product_object->SetDBField('Hits', $hits);
$product_object->Update();
/*$sql = 'UPDATE '.$this->Application->getUnitOption('p', 'TableName').'
SET Hits = Hits + '.$product_item['Quantity'].'
WHERE ProductId = '.$product_item['ProductId'];
$this->Conn->Query($sql);*/
}
$this->PrepareCoupons($event, $object);
$this->SplitOrder($event, $object);
if ($object->GetDBField('IsRecurringBilling') != 1) {
$this->Application->EmailEventUser('ORDER.APPROVE', $object->GetDBField('PortalUserId'), $email_params);
// Mask credit card with XXXX
if ($this->Application->ConfigValue('Comm_MaskProcessedCreditCards')) {
$this->maskCreditCard($object, 'PaymentAccount');
$set_new_status = 1;
}
}
}
break;
case 'OnMassOrderDeny':
case 'OnOrderDeny':
foreach ($order_items->Records as $product_item) {
if (!$product_item['ProductId']) {
// product may have been deleted
continue;
}
$this->raiseProductEvent('Deny', $product_item['ProductId'], $product_item);
}
if ( ($original_order_status != ORDER_STATUS_INCOMPLETE ) && ($event->Name == 'OnMassOrderDeny' || $event->Name == 'OnOrderDeny') ) {
$this->Application->EmailEventUser('ORDER.DENY', $object->GetDBField('PortalUserId'), $email_params);
// inform payment gateway that order was declined
$gw_data = $object->getGatewayData();
if ( $gw_data ) {
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH . '/' . $gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$gateway_object->OrderDeclined($object->GetFieldValues(), $gw_data['gw_params']);
}
}
// !!! LOOK HERE !!!
// !!!! no break !!!! here on purpose!!!
case 'OnMassOrderArchive':
case 'OnOrderArchive':
// it's critical to update status BEFORE processing items because
// FullfillBackorders could be called during processing and in case
// of order denial/archive fullfill could reserve the qtys back for current backorder
$object->Update();
$this->restoreOrder($order_items);
$set_new_status = false; // already set
break;
case 'OnMassOrderShip':
case 'OnOrderShip':
$ret = Array ();
$shipping_info = $object->GetDBField('ShippingInfo');
if ($shipping_info) {
$quote_engine_collector =& $this->Application->recallObject('ShippingQuoteCollector');
/* @var $quote_engine_collector ShippingQuoteCollector */
$shipping_info = unserialize($shipping_info);
$sqe_class_name = $quote_engine_collector->GetClassByType($shipping_info, 1);
}
// try to create usps order
if (($object->GetDBField('ShippingType') == 0) && ($sqe_class_name !== false)) {
$shipping_quote_engine =& $this->Application->recallObject($sqe_class_name);
/* @var $shipping_quote_engine ShippingQuoteEngine */
$ret = $shipping_quote_engine->MakeOrder($object);
}
if ( !array_key_exists('error_number', $ret) ) {
$set_new_status = $this->approveOrder($order_items);
// $set_new_status = $this->shipOrder($order_items);
$object->SetDBField('ShippingDate', adodb_mktime());
$object->UpdateFormattersSubFields();
$shipping_email = $object->GetDBField('ShippingEmail');
$email_params['to_email'] = $shipping_email ? $shipping_email : $email_params['_user_email'];
$email_event_user =& $this->Application->EmailEventUser('ORDER.SHIP', $object->GetDBField('PortalUserId'), $email_params);
// inform payment gateway that order was shipped
$gw_data = $object->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$gateway_object->OrderShipped($object->GetFieldValues(), $gw_data['gw_params']);
}
else {
$sqe_errors = $this->Application->RecallVar('sqe_errors');
$sqe_errors = $sqe_errors ? unserialize($sqe_errors) : Array ();
$sqe_errors[ $object->GetField('OrderNumber') ] = $ret['error_description'];
$this->Application->StoreVar('sqe_errors', serialize($sqe_errors));
}
break;
case 'OnMassOrderProcess':
case 'OnOrderProcess':
if ($this->ReadyToProcess($object->GetID())) {
$event->CallSubEvent('OnReserveItems');
if ($event->status == kEvent::erSUCCESS) $set_new_status = true;
$email_event_user =& $this->Application->EmailEventUser('BACKORDER.PROCESS', $object->GetDBField('PortalUserId'), $email_params);
} else {
$event->status = kEvent::erFAIL;
}
break;
}
if ($set_new_status) {
$object->Update();
}
}
/**
* Hides last 4 digits from credit card number
*
* @param OrdersItem $object
* @param string $field
*/
function maskCreditCard(&$object, $field)
{
$value = $object->GetDBField($field);
$value = preg_replace('/'.substr($value, -4).'$/', str_repeat('X', 4), $value);
$object->SetDBField($field, $value);
}
/**
* Set next available order number
*
* @param kEvent $event
*/
- function setNextOrderNumber(&$event)
+ function setNextOrderNumber($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
$sql = 'SELECT MAX(Number)
FROM ' . $this->Application->GetLiveName($object->TableName);
$next_order_number = $this->Conn->GetOne($sql) + 1;
$next_order_number = max($next_order_number, $this->Application->ConfigValue('Comm_Next_Order_Number'));
$this->Application->SetConfigValue('Comm_Next_Order_Number', $next_order_number + 1);
$object->SetDBField('Number', $next_order_number);
$object->SetDBField('SubNumber', 0);
// set virtual field too
$number_format = (int)$this->Application->ConfigValue('Comm_Order_Number_Format_P');
$sub_number_format = (int)$this->Application->ConfigValue('Comm_Order_Number_Format_S');
$order_number = sprintf('%0' . $number_format . 'd', $next_order_number) . '-' . str_repeat('0', $sub_number_format);
$object->SetDBField('OrderNumber', $order_number);
}
/**
* Set's new order address based on another address from order (e.g. billing from shipping)
*
* @param unknown_type $object
* @param unknown_type $from
* @param unknown_type $to
*/
function DoResetAddress(&$object, $from, $to)
{
$fields = Array('To','Company','Phone','Fax','Email','Address1','Address2','City','State','Zip','Country');
if ($from == 'User') {
// skip these fields when coping from user, because they are not present in user profile
$tmp_fields = array_flip($fields);
// unset($tmp_fields['Company'], $tmp_fields['Fax'], $tmp_fields['Address2']);
$fields = array_flip($tmp_fields);
}
// apply modification
foreach ($fields as $field_name) {
$object->SetDBField($to.$field_name, $object->GetDBField($from.$field_name));
}
}
/**
* Set's status incomplete to all cloned orders
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterClone(kEvent &$event)
+ protected function OnAfterClone(kEvent $event)
{
parent::OnAfterClone($event);
$id = $event->getEventParam('id');
$table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
// set cloned order status to Incomplete
$sql = 'UPDATE ' . $table . '
SET Status = 0
WHERE ' . $id_field . ' = ' . $id;
$this->Conn->Query($sql);
}
/* ======================== COMMON CODE ======================== */
/**
* Split one timestamp field into 2 virtual fields
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemLoad(kEvent &$event)
+ protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object kDBItem */
// get user fields
$user_id = $object->GetDBField('PortalUserId');
if ( $user_id ) {
$sql = 'SELECT *, CONCAT(FirstName,\' \',LastName) AS UserTo
FROM ' . TABLE_PREFIX . 'Users
WHERE PortalUserId = ' . $user_id;
$user_info = $this->Conn->GetRow($sql);
$fields = Array(
'UserTo'=>'UserTo','UserPhone'=>'Phone','UserFax'=>'Fax','UserEmail'=>'Email',
'UserAddress1'=>'Street','UserAddress2'=>'Street2','UserCity'=>'City','UserState'=>'State',
'UserZip'=>'Zip','UserCountry'=>'Country','UserCompany'=>'Company'
);
foreach ($fields as $object_field => $user_field) {
$object->SetDBField($object_field, $user_info[$user_field]);
}
}
$object->SetDBField('PaymentCVV2', $this->Application->RecallVar('CVV2Code'));
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
$cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
$this->SetStepRequiredFields($event);
// needed in OnAfterItemUpdate
$this->Application->SetVar('OriginalShippingOption', $object->GetDBField('ShippingOption'));
}
/**
* Processes states
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
$cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
}
/**
* Processes states
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object OrdersItem */
$old_payment_type = $object->GetOriginalField('PaymentType');
$new_payment_type = $object->GetDBField('PaymentType');
if ( $new_payment_type != $old_payment_type ) {
// payment type changed -> check that it's allowed
$available_payment_types = $this->Application->siteDomainField('PaymentTypes');
if ( $available_payment_types ) {
if ( strpos($available_payment_types, '|' . $new_payment_type . '|') === false ) {
// payment type isn't allowed in site domain
$object->SetDBField('PaymentType', $old_payment_type);
}
}
}
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$cs_helper->PopulateStates($event, 'ShippingState', 'ShippingCountry');
$cs_helper->PopulateStates($event, 'BillingState', 'BillingCountry');
if ( $object->HasTangibleItems() ) {
$cs_helper->CheckStateField($event, 'ShippingState', 'ShippingCountry', false);
}
$cs_helper->CheckStateField($event, 'BillingState', 'BillingCountry', false);
if ( $object->GetDBField('Status') > ORDER_STATUS_PENDING ) {
return ;
}
$this->CheckUser($event);
if ( !$object->GetDBField('OrderIP') ) {
$object->SetDBField('OrderIP', $_SERVER['REMOTE_ADDR']);
}
$shipping_option = $this->Application->GetVar('OriginalShippingOption');
$new_shipping_option = $object->GetDBField('ShippingOption');
if ( $shipping_option != $new_shipping_option ) {
$this->UpdateShippingOption($event);
}
else {
$this->UpdateShippingTypes($event);
}
$this->RecalculateProcessingFee($event);
$this->UpdateShippingTotal($event);
$this->RecalculateGift($event);
// guess fields from "One Step Checkout" form
if ( $object->GetDBField('PaymentAccount') ) {
$order_helper =& $this->Application->recallObject('OrderHelper');
/* @var $order_helper OrderHelper */
$object->SetDBField('PaymentCardType', $order_helper->getCreditCartType($object->GetDBField('PaymentAccount')));
}
else {
$object->SetDBField('PaymentCardType', '');
}
if ( !$object->GetDBField('PaymentNameOnCard') ) {
$object->SetDBField('PaymentNameOnCard', $object->GetDBField('BillingTo'));
}
if ( is_object($event->MasterEvent) && $event->MasterEvent->Name == 'OnUpdateAjax' && $this->Application->GetVar('create_account') && $object->Validate() ) {
$this->createAccountFromOrder($event);
}
}
/**
* Creates user account
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function createAccountFromOrder(&$event)
+ protected function createAccountFromOrder($event)
{
$order =& $event->getObject();
/* @var $order OrdersItem */
$order_helper =& $this->Application->recallObject('OrderHelper');
/* @var $order_helper OrderHelper */
$user_fields = $order_helper->getUserFields($order);
$user_fields['Password'] = $order->GetDBField('UserPassword_plain');
$user_fields['VerifyPassword'] = $order->GetDBField('VerifyUserPassword_plain');
if ( $order->GetDBField('PortalUserId') == USER_GUEST ) {
// will also auto-login user when created
$this->Application->SetVar('u_register', Array (USER_GUEST => $user_fields));
- $user_event = new kEvent('u.register:OnCreate');
- $this->Application->HandleEvent($user_event);
+ $this->Application->HandleEvent(new kEvent('u.register:OnCreate'));
}
else {
$user =& $this->Application->recallObject('u.current');
/* @var $user UsersItem */
$user->SetFieldsFromHash($user_fields);
if ( !$user->Update() ) {
$order->SetError('BillingEmail', $user->GetErrorPseudo('Email'));
}
}
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
$types = $event->getEventParam('types');
if ( $types == 'myorders' || $types == 'myrecentorders' ) {
$user_id = $this->Application->RecallVar('user_id');
$object->addFilter('myitems_user1', '%1$s.PortalUserId = ' . $user_id);
$object->addFilter('myitems_user2', '%1$s.PortalUserId > 0');
$object->addFilter('Status', '%1$s.Status != 0');
}
else if ($event->Special == 'returns') {
// $object->addFilter('returns_filter',TABLE_PREFIX.'Orders.Status = '.ORDER_STATUS_PROCESSED.' AND (
// SELECT SUM(ReturnType)
// FROM '.TABLE_PREFIX.'OrderItems oi
// WHERE oi.OrderId = '.TABLE_PREFIX.'Orders.OrderId
// ) > 0');
$object->addFilter('returns_filter', TABLE_PREFIX . 'Orders.Status = ' . ORDER_STATUS_PROCESSED . ' AND ' . TABLE_PREFIX . 'Orders.ReturnTotal > 0');
}
else if ( $event->Special == 'user' ) {
$user_id = $this->Application->GetVar('u_id');
$object->addFilter('user_filter', '%1$s.PortalUserId = ' . $user_id);
}
else {
$special = $event->Special ? $event->Special : $this->Application->GetVar('order_type');
if ( $special != 'search' ) {
// don't filter out orders by special in case of search tab
$object->addFilter('status_filter', '%1$s.Status=' . $this->getTypeBySpecial($special));
}
if ( $event->getEventParam('selected_only') ) {
$ids = $this->StoreSelectedIDs($event);
$object->addFilter('selected_filter', '%1$s.OrderId IN (' . implode(',', $ids) . ')');
}
}
}
function getTypeBySpecial($special)
{
$special2type = Array('incomplete'=>0,'pending'=>1,'backorders'=>2,'toship'=>3,'processed'=>4,'denied'=>5,'archived'=>6);
return $special2type[$special];
}
function getSpecialByType($type)
{
$type2special = Array(0=>'incomplete',1=>'pending',2=>'backorders',3=>'toship',4=>'processed',5=>'denied',6=>'archived');
return $type2special[$type];
}
- function LockTables(&$event)
+ function LockTables($event)
{
$read = Array();
$write_lock = '';
$read_lock = '';
$write = Array('Orders','OrderItems','Products');
foreach ($write as $tbl) {
$write_lock .= TABLE_PREFIX.$tbl.' WRITE,';
}
foreach ($read as $tbl) {
$read_lock .= TABLE_PREFIX.$tbl.' READ,';
}
$write_lock = rtrim($write_lock, ',');
$read_lock = rtrim($read_lock, ',');
$lock = trim($read_lock.','.$write_lock, ',');
//$this->Conn->Query('LOCK TABLES '.$lock);
}
/**
* Checks shopping cart products quantities
*
* @param kEvent $event
* @return bool
*/
- function CheckQuantites(&$event)
+ function CheckQuantites($event)
{
if ( $this->OnRecalculateItems($event) ) { // if something has changed in the order
if ( $this->Application->isAdminUser ) {
if ( $this->UseTempTables($event) ) {
$event->redirect = 'in-commerce/orders/orders_edit_items';
}
}
else {
$event->redirect = $this->Application->GetVar('viewcart_template');
}
return false;
}
return true;
}
- function DoPlaceOrder(&$event)
+ function DoPlaceOrder($event)
{
$order =& $event->getObject();
$table_prefix = $this->TablePrefix($event);
$this->LockTables($event);
if (!$this->CheckQuantites($event)) return false;
//everything is fine - we could reserve items
$this->ReserveItems($event);
$this->SplitOrder($event, $order);
return true;
}
- function &queryOrderItems(&$event, $table_prefix)
+ function &queryOrderItems($event, $table_prefix)
{
$order =& $event->getObject();
$ord_id = $order->GetId();
// TABLE_PREFIX and $table_prefix are NOT the same !!!
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' SELECT
BackOrderFlag, '.
$table_prefix.'OrderItems.OrderItemId, '.
$table_prefix.'OrderItems.Quantity, '.
$table_prefix.'OrderItems.QuantityReserved,
IF('.TABLE_PREFIX.'Products.InventoryStatus = 2, '.$poc_table.'.QtyInStock, '.TABLE_PREFIX.'Products.QtyInStock) AS QtyInStock, '.
TABLE_PREFIX.'Products.QtyInStockMin, '.
$table_prefix.'OrderItems.ProductId, '.
TABLE_PREFIX.'Products.InventoryStatus,'.
$table_prefix.'OrderItems.OptionsSalt AS CombinationCRC
FROM '.$table_prefix.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Products ON '.TABLE_PREFIX.'Products.ProductId = '.$table_prefix.'OrderItems.ProductId
LEFT JOIN '.$poc_table.' ON ('.$poc_table.'.CombinationCRC = '.$table_prefix.'OrderItems.OptionsSalt) AND ('.$poc_table.'.ProductId = '.$table_prefix.'OrderItems.ProductId)
WHERE OrderId = '.$ord_id.' AND '.TABLE_PREFIX.'Products.Type = 1
ORDER BY BackOrderFlag ASC';
$items = $this->Conn->Query($query);
return $items;
}
- function ReserveItems(&$event)
+ function ReserveItems($event)
{
$table_prefix = $this->TablePrefix($event);
$items =& $this->queryOrderItems($event, $table_prefix);
foreach ($items as $an_item) {
if (!$an_item['InventoryStatus']) {
$to_reserve = $an_item['Quantity'] - $an_item['QuantityReserved'];
}
else {
if ($an_item['BackOrderFlag'] > 0) { // we don't need to reserve if it's backordered item
$to_reserve = 0;
}
else {
$to_reserve = min($an_item['Quantity']-$an_item['QuantityReserved'], $an_item['QtyInStock']-$an_item['QtyInStockMin']); //it should be equal, but just in case
}
$to_backorder = $an_item['BackOrderFlag'] > 0 ? $an_item['Quantity']-$an_item['QuantityReserved'] : 0;
}
if ($to_backorder < 0) $to_backorder = 0; //just in case
$query = ' UPDATE '.$table_prefix.'OrderItems
SET QuantityReserved = IF(QuantityReserved IS NULL, '.$to_reserve.', QuantityReserved + '.$to_reserve.')
WHERE OrderItemId = '.$an_item['OrderItemId'];
$this->Conn->Query($query);
if (!$an_item['InventoryStatus']) continue;
$update_clause = ' QtyInStock = QtyInStock - '.$to_reserve.',
QtyReserved = QtyReserved + '.$to_reserve.',
QtyBackOrdered = QtyBackOrdered + '.$to_backorder;
if ($an_item['InventoryStatus'] == 1) {
// inventory by product, then update it's quantities
$query = ' UPDATE '.TABLE_PREFIX.'Products
SET '.$update_clause.'
WHERE ProductId = '.$an_item['ProductId'];
}
else {
// inventory = 2 -> by product option combinations
$poc_idfield = $this->Application->getUnitOption('poc', 'IDField');
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' UPDATE '.$poc_table.'
SET '.$update_clause.'
WHERE (ProductId = '.$an_item['ProductId'].') AND (CombinationCRC = '.$an_item['CombinationCRC'].')';
}
$this->Conn->Query($query);
}
}
- function FreeItems(&$event)
+ function FreeItems($event)
{
$table_prefix = $this->TablePrefix($event);
$items =& $this->queryOrderItems($event, $table_prefix);
foreach ($items as $an_item) {
$to_free = $an_item['QuantityReserved'];
if ($an_item['InventoryStatus']) {
if ($an_item['BackOrderFlag'] > 0) { // we don't need to free if it's backordered item
$to_free = 0;
}
// what's not reserved goes to backorder in stock for orderitems marked with BackOrderFlag
$to_backorder_free = $an_item['BackOrderFlag'] > 0 ? $an_item['Quantity'] - $an_item['QuantityReserved'] : 0;
if ($to_backorder_free < 0) $to_backorder_free = 0; //just in case
$update_clause = ' QtyInStock = QtyInStock + '.$to_free.',
QtyReserved = QtyReserved - '.$to_free.',
QtyBackOrdered = QtyBackOrdered - '.$to_backorder_free;
if ($an_item['InventoryStatus'] == 1) {
// inventory by product
$query = ' UPDATE '.TABLE_PREFIX.'Products
SET '.$update_clause.'
WHERE ProductId = '.$an_item['ProductId'];
}
else {
// inventory by option combinations
$poc_idfield = $this->Application->getUnitOption('poc', 'IDField');
$poc_table = $this->Application->getUnitOption('poc', 'TableName');
$query = ' UPDATE '.$poc_table.'
SET '.$update_clause.'
WHERE (ProductId = '.$an_item['ProductId'].') AND (CombinationCRC = '.$an_item['CombinationCRC'].')';
}
$this->Conn->Query($query);
}
$query = ' UPDATE '.$table_prefix.'OrderItems
SET QuantityReserved = IF(QuantityReserved IS NULL, 0, QuantityReserved - '.$to_free.')
WHERE OrderItemId = '.$an_item['OrderItemId'];
$this->Conn->Query($query);
}
}
/**
* Enter description here...
*
* @param kEvent $event
* @param OrdersItem $object
*/
- function SplitOrder(&$event, &$object)
+ function SplitOrder($event, &$object)
{
$affiliate_event = new kEvent('affil:OnOrderApprove');
$affiliate_event->setEventParam('Order_PrefixSpecial', $object->getPrefixSpecial() );
$this->Application->HandleEvent($affiliate_event);
$table_prefix = $this->TablePrefix($event);
$order =& $object;
$ord_id = $order->GetId();
$shipping_option = $order->GetDBField('ShippingOption');
$backorder_select = $shipping_option == 0 ? '0' : 'oi.BackOrderFlag';
// setting PackageNum to 0 for Non-tangible items, for tangibles first package num is always 1
$query = ' SELECT oi.OrderItemId
FROM ' . $table_prefix . 'OrderItems oi
LEFT JOIN ' . TABLE_PREFIX . 'Products p ON p.ProductId = oi.ProductId
WHERE p.Type > 1 AND oi.OrderId = ' . $ord_id;
$non_tangibles = $this->Conn->GetCol($query);
if ($non_tangibles) {
$query = ' UPDATE ' . $table_prefix . 'OrderItems
SET PackageNum = 0
WHERE OrderItemId IN (' . implode(',', $non_tangibles) . ')';
$this->Conn->Query($query);
}
// grouping_data:
// 0 => Product Type
// 1 => if NOT tangibale and NOT downloadable - OrderItemId,
// 2 => ProductId
// 3 => Shipping PackageNum
$query = 'SELECT
'.$backorder_select.' AS BackOrderFlagCalc,
PackageNum,
ProductName,
ShippingTypeId,
CONCAT('.TABLE_PREFIX.'Products.Type,
"_",
IF ('.TABLE_PREFIX.'Products.Type NOT IN ('.PRODUCT_TYPE_DOWNLOADABLE.','.PRODUCT_TYPE_TANGIBLE.'),
CONCAT(OrderItemId, "_", '.TABLE_PREFIX.'Products.ProductId),
""),
"_",
PackageNum
) AS Grouping,
SUM(Quantity) AS TotalItems,
SUM('.$table_prefix.'OrderItems.Weight*Quantity) AS TotalWeight,
SUM(Price * Quantity) AS TotalAmount,
SUM(QuantityReserved) AS TotalReserved,
'.TABLE_PREFIX.'Products.Type AS ProductType
FROM '.$table_prefix.'OrderItems
LEFT JOIN '.TABLE_PREFIX.'Products
ON '.TABLE_PREFIX.'Products.ProductId = '.$table_prefix.'OrderItems.ProductId
WHERE OrderId = '.$ord_id.'
GROUP BY BackOrderFlagCalc, Grouping
ORDER BY BackOrderFlagCalc ASC, PackageNum ASC, ProductType ASC';
$sub_orders = $this->Conn->Query($query);
$processed_sub_orders = Array();
// in case of recurring billing this will not be 0 as usual
//$first_sub_number = ($event->Special == 'recurring') ? $object->getNextSubNumber() - 1 : 0;
$first_sub_number = $object->GetDBField('SubNumber');
$next_sub_number = $first_sub_number;
$group = 1;
$order_has_gift = $order->GetDBField('GiftCertificateDiscount') > 0 ? 1 : 0;
$skip_types = Array (PRODUCT_TYPE_TANGIBLE, PRODUCT_TYPE_DOWNLOADABLE);
foreach ($sub_orders as $sub_order_data) {
$sub_order =& $this->Application->recallObject('ord.-sub'.$next_sub_number, 'ord');
/* @var $sub_order OrdersItem */
if ($this->UseTempTables($event) && $next_sub_number == 0) {
$sub_order =& $order;
}
$sub_order->SetDBFieldsFromHash($order->GetFieldValues());
$sub_order->SetDBField('SubNumber', $next_sub_number);
$sub_order->SetDBField('SubTotal', $sub_order_data['TotalAmount']);
$grouping_data = explode('_', $sub_order_data['Grouping']);
$named_grouping_data['Type'] = $grouping_data[0];
if (!in_array($named_grouping_data['Type'], $skip_types)) {
$named_grouping_data['OrderItemId'] = $grouping_data[1];
$named_grouping_data['ProductId'] = $grouping_data[2];
$named_grouping_data['PackageNum'] = $grouping_data[3];
}
else {
$named_grouping_data['PackageNum'] = $grouping_data[2];
}
if ($named_grouping_data['Type'] == PRODUCT_TYPE_TANGIBLE) {
$sub_order->SetDBField('ShippingCost', getArrayValue( unserialize($order->GetDBField('ShippingInfo')), $sub_order_data['PackageNum'], 'TotalCost') );
$sub_order->SetDBField('InsuranceFee', getArrayValue( unserialize($order->GetDBField('ShippingInfo')), $sub_order_data['PackageNum'], 'InsuranceFee') );
$sub_order->SetDBField('ShippingInfo', serialize(Array(1 => getArrayValue( unserialize($order->GetDBField('ShippingInfo')), $sub_order_data['PackageNum']))));
}
else {
$sub_order->SetDBField('ShippingCost', 0);
$sub_order->SetDBField('InsuranceFee', 0);
$sub_order->SetDBField('ShippingInfo', ''); //otherwise orders w/o shipping wills still have shipping info!
}
$amount_percent = $sub_order->getTotalAmount() * 100 / $order->getTotalAmount();
// proportional affiliate commission splitting
if ($order->GetDBField('AffiliateCommission') > 0) {
$sub_order->SetDBField('AffiliateCommission', $order->GetDBField('AffiliateCommission') * $amount_percent / 100 );
}
$amount_percent = ($sub_order->GetDBField('SubTotal') + $sub_order->GetDBField('ShippingCost')) * 100 / ($order->GetDBField('SubTotal') + $order->GetDBField('ShippingCost'));
if ($order->GetDBField('ProcessingFee') > 0) {
$sub_order->SetDBField('ProcessingFee', round($order->GetDBField('ProcessingFee') * $amount_percent / 100, 2));
}
$sub_order->RecalculateTax();
$original_amount = $sub_order->GetDBField('SubTotal') + $sub_order->GetDBField('ShippingCost') + $sub_order->GetDBField('VAT') + $sub_order->GetDBField('ProcessingFee') + $sub_order->GetDBField('InsuranceFee') - $sub_order->GetDBField('GiftCertificateDiscount');
$sub_order->SetDBField('OriginalAmount', $original_amount);
if ($named_grouping_data['Type'] == 1 && ($sub_order_data['BackOrderFlagCalc'] > 0
||
($sub_order_data['TotalItems'] != $sub_order_data['TotalReserved'])) ) {
$sub_order->SetDBField('Status', ORDER_STATUS_BACKORDERS);
if ($event->Special != 'recurring') { // just in case if admin uses tangible backordered products in recurring orders
$email_event_user =& $this->Application->EmailEventUser('BACKORDER.ADD', $sub_order->GetDBField('PortalUserId'), $this->OrderEmailParams($sub_order));
$email_event_admin =& $this->Application->EmailEventAdmin('BACKORDER.ADD');
}
}
else {
switch ($named_grouping_data['Type']) {
case PRODUCT_TYPE_DOWNLOADABLE:
$sql = 'SELECT oi.*
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE (OrderId = %s) AND (p.Type = '.PRODUCT_TYPE_DOWNLOADABLE.')';
$downl_products = $this->Conn->Query( sprintf($sql, $ord_id) );
$product_ids = Array();
foreach ($downl_products as $downl_product) {
$this->raiseProductEvent('Approve', $downl_product['ProductId'], $downl_product, $next_sub_number);
$product_ids[] = $downl_product['ProductId'];
}
break;
case PRODUCT_TYPE_TANGIBLE:
$sql = 'SELECT '.$backorder_select.' AS BackOrderFlagCalc, oi.*
FROM '.TABLE_PREFIX.'OrderItems oi
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = oi.ProductId
WHERE (OrderId = %s) AND (BackOrderFlagCalc = 0) AND (p.Type = '.PRODUCT_TYPE_TANGIBLE.')';
$products = $this->Conn->Query( sprintf($sql, $ord_id) );
foreach ($products as $product) {
$this->raiseProductEvent('Approve', $product['ProductId'], $product, $next_sub_number);
}
break;
default:
$order_item_fields = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'OrderItems WHERE OrderItemId = '.$named_grouping_data['OrderItemId']);
$this->raiseProductEvent('Approve', $named_grouping_data['ProductId'], $order_item_fields, $next_sub_number);
break;
}
$sub_order->SetDBField('Status', $named_grouping_data['Type'] == PRODUCT_TYPE_TANGIBLE ? ORDER_STATUS_TOSHIP : ORDER_STATUS_PROCESSED);
}
if ($next_sub_number == $first_sub_number) {
$sub_order->SetId($order->GetId());
$sub_order->Update();
}
else {
$sub_order->Create();
}
switch ($named_grouping_data['Type']) {
case PRODUCT_TYPE_TANGIBLE:
$query = 'UPDATE '.$table_prefix.'OrderItems SET OrderId = %s WHERE OrderId = %s AND PackageNum = %s';
$query = sprintf($query, $sub_order->GetId(), $ord_id, $sub_order_data['PackageNum']);
break;
case PRODUCT_TYPE_DOWNLOADABLE:
$query = 'UPDATE '.$table_prefix.'OrderItems SET OrderId = %s WHERE OrderId = %s AND ProductId IN (%s)';
$query = sprintf($query, $sub_order->GetId(), $ord_id, implode(',', $product_ids) );
break;
default:
$query = 'UPDATE '.$table_prefix.'OrderItems SET OrderId = %s WHERE OrderId = %s AND OrderItemId = %s';
$query = sprintf($query, $sub_order->GetId(), $ord_id, $named_grouping_data['OrderItemId']);
break;
}
$this->Conn->Query($query);
if ($order_has_gift) {
// gift certificate can be applied only after items are assigned to suborder
$sub_order->RecalculateGift($event);
$original_amount = $sub_order->GetDBField('SubTotal') + $sub_order->GetDBField('ShippingCost') + $sub_order->GetDBField('VAT') + $sub_order->GetDBField('ProcessingFee') + $sub_order->GetDBField('InsuranceFee') - $sub_order->GetDBField('GiftCertificateDiscount');
$sub_order->SetDBField('OriginalAmount', $original_amount);
$sub_order->Update();
}
$processed_sub_orders[] = $sub_order->GetID();
$next_sub_number++;
$group++;
}
foreach ($processed_sub_orders as $sub_id) {
// update DiscountTotal field
$sql = 'SELECT SUM(ROUND(FlatPrice-Price,2)*Quantity) FROM '.$table_prefix.'OrderItems WHERE OrderId = '.$sub_id;
$discount_total = $this->Conn->GetOne($sql);
$sql = 'UPDATE '.$sub_order->TableName.'
SET DiscountTotal = '.$this->Conn->qstr($discount_total).'
WHERE OrderId = '.$sub_id;
$this->Conn->Query($sql);
}
}
/**
* Call products linked event when spefcfic action is made to product in order
*
* @param string $event_type type of event to get from product ProcessingData = {Approve,Deny,CompleteOrder}
* @param int $product_id ID of product to gather processing data from
* @param Array $order_item_fields OrderItems table record fields (with needed product & order in it)
*/
function raiseProductEvent($event_type, $product_id, $order_item_fields, $next_sub_number=null)
{
$sql = 'SELECT ProcessingData
FROM '.TABLE_PREFIX.'Products
WHERE ProductId = '.$product_id;
$processing_data = $this->Conn->GetOne($sql);
if ($processing_data) {
$processing_data = unserialize($processing_data);
$event_key = getArrayValue($processing_data, $event_type.'Event');
// if requested type of event is defined for product, only then process it
if ($event_key) {
$event = new kEvent($event_key);
$event->setEventParam('field_values', $order_item_fields);
$event->setEventParam('next_sub_number', $next_sub_number);
$this->Application->HandleEvent($event);
}
}
}
function OptionsSalt($options, $comb_only=false)
{
$helper =& $this->Application->recallObject('kProductOptionsHelper');
return $helper->OptionsSalt($options, $comb_only);
}
/**
* Enter description here...
*
* @param kEvent $event
* @param int $item_id
*/
- function AddItemToOrder(&$event, $item_id, $qty = null, $package_num = null)
+ function AddItemToOrder($event, $item_id, $qty = null, $package_num = null)
{
if (!isset($qty)) {
$qty = 1;
}
// Loading product to add
$product =& $this->Application->recallObject('p.toadd', null, Array('skip_autoload' => true));
/* @var $product kDBItem */
$product->Load($item_id);
$object =& $this->Application->recallObject('orditems.-item', null, Array('skip_autoload' => true));
/* @var $object kDBItem */
$order =& $this->Application->recallObject('ord');
/* @var $order kDBItem */
if (!$order->isLoaded() && !$this->Application->isAdmin) {
// no order was created before -> create one now
if ($this->_createNewCart($event)) {
$this->LoadItem($event);
}
}
if (!$order->isLoaded()) {
// was unable to create new order
return false;
}
$item_data = $event->getEventParam('ItemData');
$item_data = $item_data ? unserialize($item_data) : Array ();
$options = getArrayValue($item_data, 'Options');
if ( !$this->CheckOptions($event, $options, $item_id, $qty, $product->GetDBField('OptionsSelectionMode')) ) {
return;
}
$manager =& $this->Application->recallObject('OrderManager');
/* @var $manager OrderManager */
$manager->setOrder($order);
$manager->addProduct($product, $event->getEventParam('ItemData'), $qty, $package_num);
- $this->Application->HandleEvent($ord_event, 'ord:OnRecalculateItems');
+ $this->Application->HandleEvent(new kEvent('ord:OnRecalculateItems'));
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function UpdateShippingTotal(&$event)
+ function UpdateShippingTotal($event)
{
if ( $this->Application->GetVar('ebay_notification') == 1 ) {
// TODO: get rid of this "if"
return;
}
$object =& $event->getObject();
/* @var $object OrdersItem */
$shipping_total = $insurance_fee = 0;
$shipping_info = $object->GetDBField('ShippingInfo') ? unserialize($object->GetDBField('ShippingInfo')) : false;
if ( is_array($shipping_info) ) {
foreach ($shipping_info as $a_shipping) {
// $id_elements = explode('_', $a_shipping['ShippingTypeId']);
$shipping_total += $a_shipping['TotalCost'];
$insurance_fee += $a_shipping['InsuranceFee'];
}
}
$object->SetDBField('ShippingCost', $shipping_total);
$object->SetDBField('InsuranceFee', $insurance_fee);
// no need to update, it will be called in calling method
$this->RecalculateTax($event);
}
/**
* Recompile shopping cart, splitting or grouping orders and backorders depending on total quantities.
* First it counts total qty for each ProductId, and then creates order for available items
* and backorder for others. It also updates the sub-total for the order
*
* @param kEvent $event
* @return bool Returns true if items splitting/grouping were changed
*/
- function OnRecalculateItems(&$event)
+ function OnRecalculateItems($event)
{
if (is_object($event->MasterEvent) && ($event->MasterEvent->status != kEvent::erSUCCESS)) {
// e.g. master order update failed, don't recalculate order products
return ;
}
$order =& $event->getObject();
/* @var $order OrdersItem */
if ( !$order->isLoaded() ) {
$this->LoadItem($event); // try to load
}
$ord_id = (int)$order->GetID();
if ( !$order->isLoaded() ) return; //order has not been created yet
if( $order->GetDBField('Status') != ORDER_STATUS_INCOMPLETE )
{
return;
}
$manager =& $this->Application->recallObject('OrderManager');
/* @var $manager OrderManager */
$manager->setOrder($order);
$result = $manager->calculate();
if ( $order->GetDBField('CouponId') && $order->GetDBField('CouponDiscount') == 0 ) {
$this->RemoveCoupon($order);
$order->setCheckoutError(OrderCheckoutErrorType::COUPON, OrderCheckoutError::COUPON_REMOVED_AUTOMATICALLY);
}
if ( $result ) {
$this->UpdateShippingOption($event);
}
$this->UpdateShippingTotal($event);
$this->RecalculateProcessingFee($event);
$this->RecalculateTax($event);
$this->RecalculateGift($event);
if ( $event->Name != 'OnAfterItemUpdate' ) {
$order->Update();
}
$event->setEventParam('RecalculateChangedCart', $result);
if ( is_object($event->MasterEvent) ) {
$event->MasterEvent->setEventParam('RecalculateChangedCart', $result);
}
/*if ( $result && !getArrayValue($event->redirect_params, 'checkout_error') ) {
$event->SetRedirectParam('checkout_error', OrderCheckoutError::STATE_CHANGED);
}*/
if ( $result && is_object($event->MasterEvent) && $event->MasterEvent->Name == 'OnUserLogin' ) {
$shop_cart_template = $this->Application->GetVar('shop_cart_template');
if ( $shop_cart_template && is_object($event->MasterEvent->MasterEvent) ) {
// $event->MasterEvent->MasterEvent->SetRedirectParam('checkout_error', OrderCheckoutError::CHANGED_AFTER_LOGIN);
$event->MasterEvent->MasterEvent->redirect = $shop_cart_template;
}
}
return $result;
}
/* function GetShippingCost($user_country_id, $user_state_id, $user_zip, $weight, $items, $amount, $shipping_type)
{
$this->Application->recallObject('ShippingQuoteEngine');
$shipping_h =& $this->Application->recallObject('CustomShippingQuoteEngine');
$query = $shipping_h->QueryShippingCost($user_country_id, $user_state_id, $user_zip, $weight, $items, $amount, $shipping_type);
$cost = $this->Conn->GetRow($query);
return $cost['TotalCost'];
}*/
/**
* Return product pricing id for given product, if not passed - return primary pricing ID
*
* @param int $product_id ProductId
* @return float
*/
function GetPricingId($product_id, $item_data) {
if (!is_array($item_data)) {
$item_data = unserialize($item_data);
}
$price_id = getArrayValue($item_data, 'PricingId');
if (!$price_id) {
$price_id = $this->Application->GetVar('pr_id');
}
if (!$price_id){
$price_id = $this->Conn->GetOne('SELECT PriceId FROM '.TABLE_PREFIX.'ProductsPricing WHERE ProductId='.$product_id.' AND IsPrimary=1');
}
return $price_id;
}
- function UpdateShippingOption(&$event)
+ function UpdateShippingOption($event)
{
$object =& $event->getObject();
$shipping_option = $object->GetDBField('ShippingOption');
if($shipping_option == '') return;
$table_prefix = $this->TablePrefix($event);
if ($shipping_option == 1 || $shipping_option == 0) { // backorder separately
$query = 'UPDATE '.$table_prefix.'OrderItems SET BackOrderFlag = 1 WHERE OrderId = '.$object->GetId().' AND BackOrderFlag > 1';
$this->Conn->Query($query);
}
if ($shipping_option == 2) {
$query = 'SELECT * FROM '.$table_prefix.'OrderItems WHERE OrderId = '.$object->GetId().' AND BackOrderFlag >= 1 ORDER By ProductName asc';
$items = $this->Conn->Query($query);
$backorder_flag = 2;
foreach ($items as $an_item) {
$query = 'UPDATE '.$table_prefix.'OrderItems SET BackOrderFlag = '.$backorder_flag.' WHERE OrderItemId = '.$an_item['OrderItemId'];
$this->Conn->Query($query);
$backorder_flag++;
}
}
}
/**
* Updates shipping types
*
* @param kEvent $event
* @return bool
*/
- function UpdateShippingTypes(&$event)
+ function UpdateShippingTypes($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
$ord_id = $object->GetID();
$order_info = $this->Application->GetVar('ord');
$shipping_ids = getArrayValue($order_info, $ord_id, 'ShippingTypeId');
if (!$shipping_ids) {
return;
}
$ret = true;
$shipping_types = Array();
$last_shippings = unserialize( $this->Application->RecallVar('LastShippings') );
$template = $this->Application->GetVar('t');
$shipping_templates = Array ('in-commerce/checkout/shipping', 'in-commerce/orders/orders_edit_shipping');
$quote_engine_collector =& $this->Application->recallObject('ShippingQuoteCollector');
/* @var $quote_engine_collector ShippingQuoteCollector */
foreach ($shipping_ids as $package => $id) {
// try to validate
$shipping_types[$package] = $last_shippings[$package][$id];
$sqe_class_name = $quote_engine_collector->GetClassByType($shipping_types, $package);
if (($object->GetDBField('ShippingType') == 0) && ($sqe_class_name !== false) && in_array($template, $shipping_templates)) {
$shipping_quote_engine =& $this->Application->recallObject($sqe_class_name);
/* @var $shipping_quote_engine ShippingQuoteEngine */
// USPS related part
// TODO: remove USPS condition from here
// set first of found shippings just to check if any errors are returned
$current_usps_shipping_types = unserialize($this->Application->RecallVar('current_usps_shipping_types'));
$object->SetDBField('ShippingInfo', serialize( Array($package => $current_usps_shipping_types[$id])) );
$sqe_data = $shipping_quote_engine->MakeOrder($object, true);
if ( $sqe_data ) {
if ( !isset($sqe_data['error_number']) ) {
// update only international shipping
if ( $object->GetDBField('ShippingCountry') != 'USA') {
$shipping_types[$package]['TotalCost'] = $sqe_data['Postage'];
}
}
else {
$ret = false;
$this->Application->StoreVar('sqe_error', $sqe_data['error_description']);
}
}
$object->SetDBField('ShippingInfo', '');
}
}
$object->SetDBField('ShippingInfo', serialize($shipping_types));
return $ret;
}
/*function shipOrder(&$order_items)
{
$product_object =& $this->Application->recallObject('p', null, Array('skip_autoload' => true));
$order_item =& $this->Application->recallObject('orditems.-item');
while( !$order_items->EOL() )
{
$rec = $order_items->getCurrentRecord();
$order_item->SetDBFieldsFromHash($rec);
$order_item->SetId($rec['OrderItemId']);
$order_item->SetDBField('QuantityReserved', 0);
$order_item->Update();
$order_items->GoNext();
}
return true;
}*/
- function RecalculateTax(&$event)
+ function RecalculateTax($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) {
return;
}
$object->RecalculateTax();
}
- function RecalculateProcessingFee(&$event)
+ function RecalculateProcessingFee($event)
{
$object =& $event->getObject();
// Do not reset processing fee while orders are being split (see SplitOrder)
if (preg_match("/^-sub/", $object->Special)) return;
if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) return; //no changes for orders other than incomple or pending
$pt = $object->GetDBField('PaymentType');
$processing_fee = $this->Conn->GetOne('SELECT ProcessingFee FROM '.$this->Application->getUnitOption('pt', 'TableName').' WHERE PaymentTypeId = '.$pt);
$object->SetDBField( 'ProcessingFee', $processing_fee );
$this->UpdateTotals($event);
}
- function UpdateTotals(&$event)
+ function UpdateTotals($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
$object->UpdateTotals();
}
- /*function CalculateDiscount(&$event)
+ /*function CalculateDiscount($event)
{
$object =& $event->getObject();
$coupon =& $this->Application->recallObject('coup', null, Array('skip_autoload' => true));
if(!$coupon->Load( $object->GetDBField('CouponId'), 'CouponId' ))
{
return false;
}
$sql = 'SELECT Price * Quantity AS Amount, ProductId FROM '.$this->Application->getUnitOption('orditems', 'TableName').'
WHERE OrderId = '.$object->GetDBField('OrderId');
$orditems = $this->Conn->GetCol($sql, 'ProductId');
$sql = 'SELECT coupi.ItemType, p.ProductId FROM '.$this->Application->getUnitOption('coupi', 'TableName').' coupi
LEFT JOIN '.$this->Application->getUnitOption('p', 'TableName').' p
ON coupi.ItemResourceId = p.ResourceId
WHERE CouponId = '.$object->GetDBField('CouponId');
$discounts = $this->Conn->GetCol($sql, 'ProductId');
$discount_amount = 0;
foreach($orditems as $product_id => $amount)
{
if(isset($discounts[$product_id]) || array_search('0', $discounts, true) !== false)
{
switch($coupon->GetDBField('Type'))
{
case 1:
$discount_amount += $coupon->GetDBField('Amount') < $amount ? $coupon->GetDBField('Amount') : $amount;
break;
case 2:
$discount_amount += $amount * $coupon->GetDBField('Amount') / 100;
break;
default:
}
break;
}
}
$object->SetDBField('CouponDiscount', $discount_amount);
return $discount_amount;
}*/
/**
* Jumps to selected order in order's list from search tab
*
* @param kEvent $event
*/
- function OnGoToOrder(&$event)
+ function OnGoToOrder($event)
{
$id = array_shift( $this->StoreSelectedIDs($event) );
$id_field = $this->Application->getUnitOption($event->Prefix,'IDField');
$table = $this->Application->getUnitOption($event->Prefix,'TableName');
$sql = 'SELECT Status FROM %s WHERE %s = %s';
$order_status = $this->Conn->GetOne( sprintf($sql, $table, $id_field, $id) );
$prefix_special = $event->Prefix.'.'.$this->getSpecialByType($order_status);
$orders_list =& $this->Application->recallObject($prefix_special, $event->Prefix.'_List', Array('per_page'=>-1) );
/* @var $orders_list kDBList */
$orders_list->Query();
foreach ($orders_list->Records as $row_num => $record) {
if ( $record[$id_field] == $id ) {
break;
}
}
$per_page = $this->getPerPage( new kEvent($prefix_special.':OnDummy') );
$page = ceil( ($row_num+1) / $per_page );
$this->Application->StoreVar($prefix_special.'_Page', $page);
$event->redirect = 'in-commerce/orders/orders_'.$this->getSpecialByType($order_status).'_list';
}
/**
* Reset's any selected order state to pending
*
* @param kEvent $event
*/
- function OnResetToPending(&$event)
+ function OnResetToPending($event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( $items_info ) {
foreach ($items_info as $id => $field_values) {
$object->Load($id);
$object->SetDBField('Status', ORDER_STATUS_PENDING);
if ( $object->Update() ) {
$event->status = kEvent::erSUCCESS;
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
* Creates list from items selected in grid
*
* @param kEvent $event
*/
- function OnLoadSelected(&$event)
+ function OnLoadSelected($event)
{
$event->setPseudoClass('_List');
$object =& $event->getObject( Array('selected_only' => true) );
$event->redirect = false;
}
/**
* Return orders list, that will expire in time specified
*
* @param int $pre_expiration timestamp
* @return Array
*/
function getRecurringOrders($pre_expiration)
{
$ord_table = $this->Application->getUnitOption('ord', 'TableName');
$ord_idfield = $this->Application->getUnitOption('ord', 'IDField');
$processing_allowed = Array(ORDER_STATUS_PROCESSED, ORDER_STATUS_ARCHIVED);
$sql = 'SELECT '.$ord_idfield.', PortalUserId, GroupId, NextCharge
FROM '.$ord_table.'
WHERE (IsRecurringBilling = 1) AND (NextCharge < '.$pre_expiration.') AND Status IN ('.implode(',', $processing_allowed).')';
return $this->Conn->Query($sql, $ord_idfield);
}
/**
* [SCHEDULED TASK] Checks what orders should expire and renew automatically (if such flag set)
*
* @param kEvent $event
*/
- function OnCheckRecurringOrders(&$event)
+ function OnCheckRecurringOrders($event)
{
$skip_clause = Array();
$ord_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$ord_idfield = $this->Application->getUnitOption($event->Prefix, 'IDField');
$pre_expiration = adodb_mktime() + $this->Application->ConfigValue('Comm_RecurringChargeInverval') * 3600 * 24;
$to_charge = $this->getRecurringOrders($pre_expiration);
if ($to_charge) {
$order_ids = Array();
foreach ($to_charge as $order_id => $record) {
// skip virtual users (e.g. root, guest, etc.) & invalid subscriptions (with no group specified, no next charge, but Recurring flag set)
if (!$record['PortalUserId'] || !$record['GroupId'] || !$record['NextCharge']) continue;
$order_ids[] = $order_id;
// prevent duplicate user+group pairs
$skip_clause[ 'PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'] ] = $order_id;
}
// process only valid orders
$temp_handler =& $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
$cloned_order_ids = $temp_handler->CloneItems($event->Prefix, 'recurring', $order_ids);
$order =& $this->Application->recallObject($event->Prefix.'.recurring', null, Array('skip_autoload' => true));
foreach ($cloned_order_ids as $order_id) {
$order->Load($order_id);
$this->Application->HandleEvent($complete_event, $event->Prefix.'.recurring:OnCompleteOrder' );
if ($complete_event->status == kEvent::erSUCCESS) {
//send recurring ok email
$email_event_user =& $this->Application->EmailEventUser('ORDER.RECURRING.PROCESSED', $order->GetDBField('PortalUserId'), $this->OrderEmailParams($order));
$email_event_admin =& $this->Application->EmailEventAdmin('ORDER.RECURRING.PROCESSED');
}
else {
//send Recurring failed event
$order->SetDBField('Status', ORDER_STATUS_DENIED);
$order->Update();
$email_event_user =& $this->Application->EmailEventUser('ORDER.RECURRING.DENIED', $order->GetDBField('PortalUserId'), $this->OrderEmailParams($order));
$email_event_admin =& $this->Application->EmailEventAdmin('ORDER.RECURRING.DENIED');
}
}
// remove recurring flag from all orders found, not to select them next time script runs
$sql = 'UPDATE '.$ord_table.'
SET IsRecurringBilling = 0
WHERE '.$ord_idfield.' IN ('.implode(',', array_keys($to_charge)).')';
$this->Conn->Query($sql);
}
if ( !is_object($event->MasterEvent) ) {
// not called as hook
return ;
}
$pre_expiration = adodb_mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24;
$to_charge = $this->getRecurringOrders($pre_expiration);
foreach ($to_charge as $order_id => $record) {
// skip virtual users (e.g. root, guest, etc.) & invalid subscriptions (with no group specified, no next charge, but Recurring flag set)
if (!$record['PortalUserId'] || !$record['GroupId'] || !$record['NextCharge']) continue;
// prevent duplicate user+group pairs
$skip_clause[ 'PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'] ] = $order_id;
}
$skip_clause = array_flip($skip_clause);
$event->MasterEvent->setEventParam('skip_clause', $skip_clause);
}
- function OnGeneratePDF(&$event)
+ function OnGeneratePDF($event)
{
$this->OnLoadSelected($event);
$this->Application->InitParser();
$o = $this->Application->ParseBlock(array('name'=>'in-commerce/orders/orders_pdf'));
$file_helper =& $this->Application->recallObject('FileHelper');
/* @var $file_helper FileHelper */
$file_helper->CheckFolder(EXPORT_PATH);
$htmlFile = EXPORT_PATH . '/tmp.html';
$fh = fopen($htmlFile, 'w');
fwrite($fh, $o);
fclose($fh);
// return;
// require_once (FULL_PATH.'html2pdf/PDFEncryptor.php');
// Full path to the file to be converted
// $htmlFile = dirname(__FILE__) . '/test.html';
// The default domain for images that use a relative path
// (you'll need to change the paths in the test.html page
// to an image on your server)
$defaultDomain = DOMAIN;
// Full path to the PDF we are creating
$pdfFile = EXPORT_PATH . '/tmp.pdf';
// Remove old one, just to make sure we are making it afresh
@unlink($pdfFile);
$pdf_helper =& $this->Application->recallObject('kPDFHelper');
$pdf_helper->FileToFile($htmlFile, $pdfFile);
return ;
// DOM PDF VERSION
/*require_once(FULL_PATH.'/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->load_html_file($htmlFile);
if ( isset($base_path) ) {
$dompdf->set_base_path($base_path);
}
$dompdf->set_paper($paper, $orientation);
$dompdf->render();
file_put_contents($pdfFile, $dompdf->output());
return ;*/
// Instnatiate the class with our variables
require_once (FULL_PATH.'/html2pdf/HTML_ToPDF.php');
$pdf = new HTML_ToPDF($htmlFile, $defaultDomain, $pdfFile);
$pdf->setHtml2Ps('/usr/bin/html2ps');
$pdf->setPs2Pdf('/usr/bin/ps2pdf');
$pdf->setGetUrl('/usr/local/bin/curl -i');
// Set headers/footers
$pdf->setHeader('color', 'black');
$pdf->setFooter('left', '');
$pdf->setFooter('right', '$D');
$pdf->setDefaultPath(BASE_PATH.'/kernel/admin_templates/');
$result = $pdf->convert();
// Check if the result was an error
if (PEAR::isError($result)) {
$this->Application->ApplicationDie($result->getMessage());
}
else {
$download_url = rtrim($this->Application->BaseURL(), '/') . EXPORT_BASE_PATH . '/tmp.pdf';
echo "PDF file created successfully: $result";
echo '<br />Click <a href="' . $download_url . '">here</a> to view the PDF file.';
}
}
/**
* Occurs, when config was parsed, allows to change config data dynamically
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
if (defined('IS_INSTALL') && IS_INSTALL) {
return ;
}
$order_number = (int)$this->Application->ConfigValue('Comm_Order_Number_Format_P');
$order_sub_number = (int)$this->Application->ConfigValue('Comm_Order_Number_Format_S');
$calc_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
foreach ($calc_fields as $special => $fields) {
$calc_fields[$special]['OrderNumber'] = str_replace('6', $order_number, $calc_fields[$special]['OrderNumber']);
$calc_fields[$special]['OrderNumber'] = str_replace('3', $order_sub_number, $calc_fields[$special]['OrderNumber']);
}
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calc_fields);
$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
$fields['Number']['format'] = str_replace('%06d', '%0'.$order_number.'d', $fields['Number']['format']);
$fields['SubNumber']['format'] = str_replace('%03d', '%0'.$order_sub_number.'d', $fields['SubNumber']['format']);
$site_helper =& $this->Application->recallObject('SiteHelper');
/* @var $site_helper SiteHelper */
$fields['BillingCountry']['default'] = $site_helper->getDefaultCountry('Billing');
$fields['ShippingCountry']['default'] = $site_helper->getDefaultCountry('Shipping');
if (!$this->Application->isAdminUser) {
$user_groups = explode(',', $this->Application->RecallVar('UserGroups'));
$default_group = $this->Application->ConfigValue('User_LoggedInGroup');
if (!in_array($default_group, $user_groups)){
$user_groups[] = $default_group;
}
$sql_part = '';
// limit payment types by domain
$payment_types = $this->Application->siteDomainField('PaymentTypes');
if (strlen($payment_types)) {
$payment_types = explode('|', substr($payment_types, 1, -1));
$sql_part .= ' AND PaymentTypeId IN (' . implode(',', $payment_types) . ')';
}
// limit payment types by user group
$sql_part .= ' AND (PortalGroups LIKE "%%,'.implode(',%%" OR PortalGroups LIKE "%%,', $user_groups).',%%")';
$fields['PaymentType']['options_sql'] = str_replace(
'ORDER BY ',
$sql_part . ' ORDER BY ',
$fields['PaymentType']['options_sql']
);
}
$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
}
/**
* Allows configuring export options
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeExportBegin(kEvent &$event)
+ protected function OnBeforeExportBegin(kEvent $event)
{
parent::OnBeforeExportBegin($event);
$options = $event->getEventParam('options');
$items_list =& $this->Application->recallObject($event->Prefix . '.' . $this->Application->RecallVar('export_oroginal_special'), $event->Prefix . '_List');
/* @var $items_list kDBList */
$items_list->SetPerPage(-1);
if ( $options['export_ids'] != '' ) {
$items_list->AddFilter('export_ids', $items_list->TableName . '.' . $items_list->IDField . ' IN (' . implode(',', $options['export_ids']) . ')');
}
$options['ForceCountSQL'] = $items_list->getCountSQL($items_list->GetSelectSQL(true, false));
$options['ForceSelectSQL'] = $items_list->GetSelectSQL();
$event->setEventParam('options', $options);
$object =& $this->Application->recallObject($event->Prefix . '.export');
/* @var $object kDBItem */
$object->SetField('Number', 999999);
$object->SetField('SubNumber', 999);
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
* @access protected
*/
- public function getCustomExportColumns(kEvent &$event)
+ public function getCustomExportColumns(kEvent $event)
{
$columns = parent::getCustomExportColumns($event);
$new_columns = Array (
'__VIRTUAL__CustomerName' => 'CustomerName',
'__VIRTUAL__TotalAmount' => 'TotalAmount',
'__VIRTUAL__AmountWithoutVAT' => 'AmountWithoutVAT',
'__VIRTUAL__SubtotalWithDiscount' => 'SubtotalWithDiscount',
'__VIRTUAL__SubtotalWithoutDiscount' => 'SubtotalWithoutDiscount',
'__VIRTUAL__OrderNumber' => 'OrderNumber',
);
return array_merge($columns, $new_columns);
}
/**
* 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(kEvent &$event)
+ protected function OnSave(kEvent $event)
{
parent::OnSave($event);
if ( $event->status != kEvent::erSUCCESS ) {
return ;
}
$copied_ids = unserialize($this->Application->RecallVar($event->Prefix . '_copied_ids' . $this->Application->GetVar('wid'), serialize(Array ())));
foreach ($copied_ids as $id) {
$an_event = new kEvent($this->Prefix . ':Dummy');
$this->Application->SetVar($this->Prefix . '_id', $id);
$this->Application->SetVar($this->Prefix . '_mode', ''); // this is to fool ReserveItems to use live table
$this->ReserveItems($an_event);
}
}
/**
* Occurs before an item is copied to live table (after all foreign keys have been updated)
* Id of item being copied is passed as event' 'id' param
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeCopyToLive(kEvent &$event)
+ protected function OnBeforeCopyToLive(kEvent $event)
{
parent::OnBeforeCopyToLive($event);
$id = $event->getEventParam('id');
$copied_ids = unserialize($this->Application->RecallVar($event->Prefix . '_copied_ids' . $this->Application->GetVar('wid'), serialize(array ())));
array_push($copied_ids, $id);
$this->Application->StoreVar($event->Prefix . '_copied_ids' . $this->Application->GetVar('wid'), serialize($copied_ids));
}
/**
* Checks, that currently loaded item is allowed for viewing (non permission-based)
*
* @param kEvent $event
* @return bool
* @access protected
*/
- protected function checkItemStatus(kEvent &$event)
+ protected function checkItemStatus(kEvent $event)
{
if ( $this->Application->isAdminUser ) {
return true;
}
$object =& $event->getObject();
/* @var $object kDBItem */
if ( !$object->isLoaded() ) {
return true;
}
return $object->GetDBField('PortalUserId') == $this->Application->RecallVar('user_id');
}
// ===== Gift Certificates Related =====
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnApplyGiftCertificate(&$event)
+ function OnApplyGiftCertificate($event)
{
$code = $this->Application->GetVar('giftcert_code');
if ( $code == '' ) {
return;
}
$object =& $event->getObject();
/* @var $object OrdersItem */
$gift_certificate =& $this->Application->recallObject('gc', null, Array ('skip_autoload' => true));
/* @var $gift_certificate kDBItem */
$gift_certificate->Load($code, 'Code');
if ( !$gift_certificate->isLoaded() ) {
$event->status = kEvent::erFAIL;
$object->setCheckoutError(OrderCheckoutErrorType::GIFT_CERTIFICATE, OrderCheckoutError::GC_CODE_INVALID);
$event->redirect = false; // check!!!
return;
}
$debit = $gift_certificate->GetDBField('Debit');
$expire_date = $gift_certificate->GetDBField('Expiration');
if ( $gift_certificate->GetDBField('Status') != 1 || ($expire_date && $expire_date < adodb_mktime()) || ($debit <= 0) ) {
$event->status = kEvent::erFAIL;
$object->setCheckoutError(OrderCheckoutErrorType::GIFT_CERTIFICATE, OrderCheckoutError::GC_CODE_EXPIRED);
$event->redirect = false;
return;
}
$object->SetDBField('GiftCertificateId', $gift_certificate->GetDBField('GiftCertificateId'));
$object->Update();
$object->setCheckoutError(OrderCheckoutErrorType::GIFT_CERTIFICATE, OrderCheckoutError::GC_APPLIED);
}
/**
* Removes gift certificate from order
*
* @param kEvent $event
* @deprecated
*/
- function OnRemoveGiftCertificate(&$event)
+ function OnRemoveGiftCertificate($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
$this->RemoveGiftCertificate($object);
$object->setCheckoutError(OrderCheckoutErrorType::GIFT_CERTIFICATE, OrderCheckoutError::GC_REMOVED);
$event->CallSubEvent('OnRecalculateItems');
}
function RemoveGiftCertificate(&$object)
{
$object->RemoveGiftCertificate();
}
- function RecalculateGift(&$event)
+ function RecalculateGift($event)
{
$object =& $event->getObject();
/* @var $object OrdersItem */
if ($object->GetDBField('Status') > ORDER_STATUS_PENDING) {
return ;
}
$object->RecalculateGift($event);
}
function GetWholeOrderGiftCertificateDiscount($gift_certificate_id)
{
if (!$gift_certificate_id) {
return 0;
}
$sql = 'SELECT Debit
FROM '.TABLE_PREFIX.'GiftCertificates
WHERE GiftCertificateId = '.$gift_certificate_id;
return $this->Conn->GetOne($sql);
}
/**
* Downloads shipping tracking bar code, that was already generated by USPS service
*
* @param kEvent $event
*/
- function OnDownloadLabel(&$event)
+ function OnDownloadLabel($event)
{
$event->status = kEvent::erSTOP;
ini_set('memory_limit', '300M');
ini_set('max_execution_time', '0');
$object =& $event->getObject();
/* @var $object kDBItem */
$file = $object->GetDBField('ShippingTracking') . '.pdf';
$full_path = USPS_LABEL_FOLDER . $file;
if ( !file_exists($full_path) || !is_file($full_path) ) {
return;
}
header('Content-type: ' . kUtil::mimeContentType($full_path));
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile($full_path);
}
/**
* Occurs before validation attempt
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemValidate(kEvent &$event)
+ protected function OnBeforeItemValidate(kEvent $event)
{
parent::OnBeforeItemValidate($event);
$create_account = $this->Application->GetVar('create_account');
$object =& $event->getObject();
/* @var $object kDBItem */
$required_fields = Array ('UserPassword', 'UserPassword_plain', 'VerifyUserPassword', 'VerifyUserPassword_plain');
$object->setRequired($required_fields, $create_account);
$billing_email = $object->GetDBField('BillingEmail');
if ( $create_account && $object->GetDBField('PortalUserId') == USER_GUEST && $billing_email ) {
// check that e-mail available
$sql = 'SELECT PortalUserId
FROM ' . TABLE_PREFIX . 'Users
WHERE Email = ' . $this->Conn->qstr($billing_email);
$user_id = $this->Conn->GetOne($sql);
if ( $user_id ) {
$object->SetError('BillingEmail', 'unique');
}
}
}
/**
* Performs order update and returns results in format, needed by FormManager
*
* @param kEvent $event
*/
- function OnUpdateAjax(&$event)
+ function OnUpdateAjax($event)
{
$ajax_form_helper =& $this->Application->recallObject('AjaxFormHelper');
/* @var $ajax_form_helper AjaxFormHelper */
$ajax_form_helper->transitEvent($event, 'OnUpdate');
}
}
\ No newline at end of file
Index: branches/5.2.x/units/orders/orders_item.php
===================================================================
--- branches/5.2.x/units/orders/orders_item.php (revision 15133)
+++ branches/5.2.x/units/orders/orders_item.php (revision 15134)
@@ -1,381 +1,381 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class OrdersItem extends kDBItem
{
/**
* Sets item' fields corresponding to elements in passed $hash values.
*
* The function sets current item fields to values passed in $hash, by matching $hash keys with field names
* of current item. If current item' fields are unknown {@link kDBItem::PrepareFields()} is called before actually setting the fields
*
* @param Array $hash
* @param Array $skip_fields Optional param, field names in target object to skip, other fields will be set
* @param Array $set_fields Optional param, field names in target object to set, other fields will be skipped
* @return void
* @access public
*/
public function SetFieldsFromHash($hash, $skip_fields = Array (), $set_fields = Array ())
{
parent::SetFieldsFromHash($hash, $skip_fields, $set_fields);
$options = $this->GetFieldOptions('PaymentCCExpDate');
if ( $this->GetDirtyField($options['month_field']) || $this->GetDirtyField($options['year_field']) ) {
$this->SetDirtyField('PaymentCCExpDate', 0);
$this->SetField('PaymentCCExpDate', 0);
}
}
/**
* Returns gateway data based on payment type used in order
*
* @param int $pt_id
* @return Array
* @access public
*/
public function getGatewayData($pt_id = null)
{
// get Gateway fields
if ( !isset($pt_id) || !$pt_id ) {
$pt_id = $this->GetDBField('PaymentType');
if ( !$pt_id ) {
// no Payment Type Id found for this order - escape SQL fatal below
return false;
}
}
$pt_table = $this->Application->getUnitOption('pt', 'TableName');
$sql = 'SELECT GatewayId
FROM %s
WHERE PaymentTypeId = %s';
$gw_id = $this->Conn->GetOne(sprintf($sql, $pt_table, $pt_id));
$sql = 'SELECT *
FROM %s
WHERE GatewayId = %s';
$ret = $this->Conn->GetRow(sprintf($sql, TABLE_PREFIX . 'Gateways', $gw_id));
// get Gateway parameters based on payment type
$gwf_table = $this->Application->getUnitOption('gwf', 'TableName');
$gwfv_table = $this->Application->getUnitOption('gwfv', 'TableName');
$sql = 'SELECT gwfv.Value, gwf.SystemFieldName
FROM %s gwf
LEFT JOIN %s gwfv ON gwf.GWConfigFieldId = gwfv.GWConfigFieldId
WHERE gwfv.PaymentTypeId = %s AND gwf.GatewayId = %s';
$ret['gw_params'] = $this->Conn->GetCol(sprintf($sql, $gwf_table, $gwfv_table, $pt_id, $gw_id), 'SystemFieldName');
$ret['gw_params']['gateway_id'] = $gw_id;
if ( $this->GetDBField('IsRecurringBilling') && $this->Application->ConfigValue('Comm_AutoProcessRecurringOrders') ) {
if ( isset($ret['gw_params']['shipping_control']) ) {
$ret['gw_params']['shipping_control'] = SHIPPING_CONTROL_DIRECT;
}
}
return $ret;
}
/**
* Checks if tangible items are present in order
*
* @return bool
*/
function HasTangibleItems()
{
$sql = 'SELECT COUNT(*)
FROM '.TABLE_PREFIX.'OrderItems orditems
LEFT JOIN '.TABLE_PREFIX.'Products p ON p.ProductId = orditems.ProductId
WHERE (orditems.OrderId = '.$this->GetID().') AND (p.Type = '.PRODUCT_TYPE_TANGIBLE.')';
return $this->Conn->GetOne($sql) ? true : false;
}
/**
* Calculates tax value of order items based on billing & shipping country specified
*
* @return double
*/
function getTaxPercent()
{
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$shipping_country_id = $cs_helper->getCountryStateId($this->GetDBField('ShippingCountry'), DESTINATION_TYPE_COUNTRY);
$shipping_state_id = $cs_helper->getCountryStateId($this->GetDBField('ShippingState'), DESTINATION_TYPE_STATE);
$shipping_zip = (string) $this->GetDBField('ShippingZip');
$billing_country_id = $cs_helper->getCountryStateId($this->GetDBField('BillingCountry'), DESTINATION_TYPE_COUNTRY);
$billing_state_id = $cs_helper->getCountryStateId($this->GetDBField('BillingState'), DESTINATION_TYPE_STATE);
$billing_zip = (string) $this->GetDBField('BillingZip');
/*
$dest_ids = array_diff( array_unique( Array( $shipping_country_id, $shipping_state_id, $billing_country_id, $billing_state_id ) ), Array(0) );
$dest_values = array_diff( array_unique( Array( $this->Conn->qstr($shipping_zip), $this->Conn->qstr($billing_zip) ) ), Array('\'\'') );
*/
$tax = false;
$sql = 'SELECT tx.*
FROM '.$this->Application->getUnitOption('tax', 'TableName').' tx
LEFT JOIN '.$this->Application->getUnitOption('taxdst', 'TableName').' txd ON tx.TaxZoneId = txd.TaxZoneId
WHERE
( txd.StdDestId IN ('.$shipping_country_id.','.$shipping_state_id.')
AND
( (txd.DestValue = "" OR txd.DestValue IS NULL)
OR
txd.DestValue = '.$this->Conn->qstr($shipping_zip).'
)
)
OR
( txd.StdDestId IN ('.$billing_country_id.','.$billing_state_id.')
AND
( (txd.DestValue = "" OR txd.DestValue IS NULL)
OR
txd.DestValue = '.$this->Conn->qstr($billing_zip).'
)
)
ORDER BY tx.TaxValue DESC';
$tax = $this->Conn->GetRow($sql);
if ($tax == false) {
$tax['TaxValue'] = 0;
$tax['ApplyToShipping'] = 0;
$tax['ApplyToProcessing'] = 0;
}
return $tax;
}
function RecalculateTax()
{
$tax = $this->getTaxPercent();
$this->SetDBField('VATPercent', $tax['TaxValue']);
$this->SetDBField('ShippingTaxable', $tax['ApplyToShipping']);
$this->SetDBField('ProcessingTaxable', $tax['ApplyToProcessing']);
$this->UpdateTotals();
if ( !$this->GetDBField('VATIncluded') ) {
$subtotal = $this->GetDBField('AmountWithoutVAT');
$tax_exempt = $this->getTaxExempt();
if ( $tax_exempt ) {
$subtotal -= $tax_exempt;
}
$this->SetDBField('VAT', round($subtotal * $tax['TaxValue'] / 100, 2));
$this->UpdateTotals();
}
}
/**
* Returns order amount, that is excluded from tax calculations
*
* @return float
* @access protected
*/
protected function getTaxExempt()
{
$sql = 'SELECT SUM(oi.Quantity * oi.Price)
FROM ' . TABLE_PREFIX . 'OrderItems AS oi
LEFT JOIN ' . TABLE_PREFIX . 'Products AS p ON p.ProductId = oi.ProductId
WHERE p.Type = 6 AND oi.OrderId = ' . $this->GetDBField('OrderId');
return $this->Conn->GetOne($sql);
}
function UpdateTotals()
{
$total = 0;
$total += $this->GetDBField('SubTotal');
if ( $this->GetDBField('ShippingTaxable') ) {
$total += $this->GetDBField('ShippingCost');
}
if ( $this->GetDBField('ProcessingTaxable') ) {
$total += $this->GetDBField('ProcessingFee');
}
if ( $this->GetDBField('VATIncluded') ) {
$tax_exempt = $this->getTaxExempt();
$vat_percent = $this->GetDBField('VATPercent');
$this->SetDBField('VAT', round(($total - $tax_exempt) * $vat_percent / (100 + $vat_percent), 2));
$this->SetDBField('AmountWithoutVAT', $total - $this->GetDBField('VAT'));
}
else {
$this->SetDBField('AmountWithoutVAT', $total);
$total += $this->GetDBField('VAT');
}
if ( !$this->GetDBField('ShippingTaxable') ) {
$total += $this->GetDBField('ShippingCost');
}
if ( !$this->GetDBField('ProcessingTaxable') ) {
$total += $this->GetDBField('ProcessingFee');
}
$total += $this->GetDBField('InsuranceFee');
$this->SetDBField('TotalAmount', $total);
}
function getTotalAmount()
{
return $this->GetDBField('SubTotal') +
$this->GetDBField('ShippingCost') +
($this->GetDBField('VATIncluded') ? 0 : $this->GetDBField('VAT')) +
$this->GetDBField('ProcessingFee') +
$this->GetDBField('InsuranceFee') -
$this->GetDBField('GiftCertificateDiscount');
}
function requireCreditCard()
{
$sql = 'SELECT RequireCCFields
FROM ' . $this->Application->getUnitOption('pt', 'TableName') . ' pt
LEFT JOIN '.TABLE_PREFIX.'Gateways gw ON gw.GatewayId = pt.GatewayId
WHERE pt.PaymentTypeId = ' . $this->GetDBField('PaymentType');
return $this->Conn->GetOne($sql);
}
function getNextSubNumber()
{
$table = $this->Application->GetLiveName($this->TableName);
$sql = 'SELECT MAX(SubNumber) FROM '.$table.' WHERE Number = '.$this->GetDBField('Number');
return $this->Conn->GetOne($sql) + 1;
}
function ResetAddress($prefix)
{
$fields = Array('To','Company','Phone','Fax','Email','Address1','Address2','City','State','Zip','Country');
foreach($fields as $field)
{
$this->SetDBField($prefix.$field, $this->Fields[$prefix.$field]['default']);
}
}
function IsProfileAddress($address_type)
{
return $this->Application->GetVar($this->Prefix.'_IsProfileAddress');
}
// ===== Gift Certificates Related =====
- function RecalculateGift(&$event)
+ function RecalculateGift($event)
{
$gc_id = $this->GetDBField('GiftCertificateId');
if ($gc_id < 1) {
return;
}
$gc =& $this->Application->recallObject('gc', null, Array('skip_autoload' => true));
/* @var $gc kDBItem */
$gc->Load($gc_id);
if ($gc->GetDBField('Status') == gcDISABLED) {
// disabled GC
$this->SetDBField('GiftCertificateId', 0);
$this->SetDBField('GiftCertificateDiscount', 0);
// disabled
return;
}
$debit = $gc->GetDBField('Debit') + $this->GetDBField('GiftCertificateDiscount');
$this->UpdateTotals();
$total = $this->GetDBField('TotalAmount');
$gift_certificate_discount = $debit >= $total ? $total : $debit;
$this->SetDBField('TotalAmount', $total - $gift_certificate_discount);
$this->GetDBField('GiftCertificateDiscount', $gift_certificate_discount);
$debit -= $gift_certificate_discount;
$gc->SetDBField('Debit', $debit);
$gc->SetDBField('Status', $debit > 0 ? gcENABLED : gcUSED);
$gc->Update();
if ($gift_certificate_discount == 0) {
$this->RemoveGiftCertificate($object);
$this->setCheckoutError(OrderCheckoutErrorType::GIFT_CERTIFICATE, OrderCheckoutError::GC_REMOVED_AUTOMATICALLY);
}
$this->SetDBField('GiftCertificateDiscount', $gift_certificate_discount);
}
function RemoveGiftCertificate()
{
$gc_id = $this->GetDBField('GiftCertificateId');
$gc =& $this->Application->recallObject('gc', null, Array('skip_autoload' => true));
/* @var $gc kDBItem */
$gc->Load($gc_id);
$debit = $gc->GetDBField('Debit') + $this->GetDBField('GiftCertificateDiscount');
if ($gc->isLoaded() && ($debit > 0)) {
$gc->SetDBField('Debit', $debit);
$gc->SetDBField('Status', gcENABLED);
$gc->Update();
}
$this->SetDBField('GiftCertificateId', 0);
$this->SetDBField('GiftCertificateDiscount', 0);
}
/**
* Sets checkout error
*
* @param int $error_type = {product,coupon,gc}
* @param int $error_code
* @param int $product_id - {ProductId}:{OptionsSalt}:{BackOrderFlag}:{FieldName}
*/
function setCheckoutError($error_type, $error_code, $product_id = null)
{
$errors = $this->Application->RecallVar('checkout_errors');
$errors = $errors ? unserialize($errors) : Array ();
if ( isset($product_id) ) {
$error_type .= ':' . $product_id;
// any error takes priority over FIELD_UPDATE_SUCCESS error
if ( isset($errors[$error_type]) && $error_code == OrderCheckoutError::FIELD_UPDATE_SUCCESS ) {
return ;
}
}
if ( is_numeric($error_code) ) {
$errors[$error_type] = $error_code;
}
else {
unset($errors[$error_type]);
}
if ( $this->Application->isDebugMode() ) {
$this->Application->Debugger->appendHTML('CO_ERROR: ' . $error_type . ' - ' . $error_code);
}
$this->Application->StoreVar('checkout_errors', serialize($errors));
}
}
\ No newline at end of file
Index: branches/5.2.x/units/orders/order_validator.php
===================================================================
--- branches/5.2.x/units/orders/order_validator.php (revision 15133)
+++ branches/5.2.x/units/orders/order_validator.php (revision 15134)
@@ -1,247 +1,247 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2011 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 OrderValidator extends kValidator {
- public function __construct($application = null)
+ public function __construct()
{
- parent::__construct($application);
+ parent::__construct();
$this->ErrorMsgs['credit_card_validation_error'] = '!lu_cc_validation_error!';
$this->ErrorMsgs['credit_card_expired'] = '!lu_cc_expired!';
}
/**
* Return error message for field
*
* @param string $field
* @return string
* @access public
*/
public function GetErrorMsg($field, $force_escape = null)
{
if ( $field != 'OrderNumber' ) {
return parent::GetErrorMsg($field, $force_escape);
}
$number['error'] = parent::GetErrorMsg('Number', $force_escape);
$number['pseudo'] = $this->GetErrorPseudo('Number');
$subnumber['error'] = parent::GetErrorMsg('SubNumber', $force_escape);
$subnumber['pseudo'] = $this->GetErrorPseudo('SubNumber');
// if pseudo match & not empty -> return 1st
// if one of pseudos not empty -> return it
// if we got one pseudo "bad_type" and other pseudo "required", then return "bad_type" error message
if ( $number['pseudo'] && ($number['pseudo'] == $subnumber['pseudo']) ) {
return $number['error'];
}
if ( $number['pseudo'] && !$subnumber['pseudo'] ) {
return $number['error'];
}
if ( !$number['pseudo'] && $subnumber['pseudo'] ) {
return $subnumber['error'];
}
if ( $number['pseudo'] == 'bad_type' ) {
return $number['error'];
}
if ( $subnumber['pseudo'] == 'bad_type' ) {
return $subnumber['error'];
}
return '';
/*$msg = '[' . $number_error . '(' . $number_pseudo . ')] [' . $subnumber_error . '] (' . $subnumber_pseudo . ')';
return $msg;*/
}
/**
* Check field value by user-defined alghoritm
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
*/
function CustomValidation($field, $params)
{
// TODO: move to OrdersEventHandler OR extend kValidator class
$res = true;
$res = $res && $this->ValidateCCNumber($field, $params);
$res = $res && $this->ValidateCCExpiration($field, $params);
return $res;
}
/**
* Check if field value is valid credit card number against credit card type specified
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateCCNumber($field, $params)
{
$value = $this->dataSource->GetDBField($field);
$cardtype_field = getArrayValue($params, 'cardtype_field');
if ( !$cardtype_field || !$value || !$this->dataSource->requireCreditCard() ) {
return true;
}
if ( $this->Application->ConfigValue('Comm_MaskProcessedCreditCards') ) {
$mask_found = strpos($value, str_repeat('X', 4)) !== false;
if ( $this->Application->isAdminUser && $mask_found ) {
// masked card numbers always appear valid in admin
return true;
}
}
if (defined('DEBUG_MODE') && kUtil::constOn('DBG_PAYMENT_GW')) {
$gw_data = $this->dataSource->getGatewayData();
$this->Application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $this->Application->recallObject( $gw_data['ClassName'] );
$test_numbers = $gateway_object->GetTestCCNumbers();
if ( in_array($value, $test_numbers) ) {
return true;
}
}
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
// '1' => 'Visa','2' => 'Mastercard', '3' => 'Amex', '4' => 'Discover', 5 => 'Diners Club', 6 => 'JBC'
// Innocent until proven guilty
$cc_valid = true;
// Get rid of any non-digits
$value = preg_replace('/[^\d]/', '', $value);
// Perform card-specific checks, if applicable
switch( $this->dataSource->GetDBField($cardtype_field) )
{
case 2: // MasterCard
$cc_valid = preg_match('/^5[1-5].{14}$/', $value);
break;
case 1: // Visa
$cc_valid = preg_match('/^4.{15}$|^4.{12}$/', $value);
break;
case 3: // American Express
$cc_valid = preg_match('/^3[47].{13}$/', $value);
break;
case 4: // Discover
$cc_valid = preg_match('/^6011.{12}$/', $value);
break;
case 5: // Diners Club
$cc_valid = preg_match('/^30[0-5].{11}$|^3[68].{12}$/', $value);
break;
case 6: // JBC
$cc_valid = preg_match('/^3.{15}$|^2131|1800.{11}$/', $value);
break;
default:
$this->SetError($error_field, 'credit_card_validation_error');
return false;
break;
}
// The Luhn formula works right to left, so reverse the number.
$value = strrev($value);
$total = 0;
for($x = 0; $x < strlen($value); $x++)
{
$digit = substr($value, $x, 1);
// If it's an odd digit, double it
if( $x / 2 != floor($x/2) )
{
$digit *= 2;
// If the result is two digits, add them
if( strlen($digit) == 2 )
{
$digit = substr($digit, 0, 1) + substr($digit, 1, 1);
}
}
// Add the current digit, doubled and added if applicable, to the Total
$total += $digit;
}
// If it passed (or bypassed) the card-specific check and the Total is
// evenly divisible by 10, it's cool!
if ($cc_valid && $total % 10 == 0) {
return true;
}
$this->SetError($error_field, 'credit_card_validation_error');
return false;
}
/**
* Check if field value is non-expired credit card expiration date
*
* @param string $field field name
* @param Array $params field options from config
* @return bool
* @access private
*/
function ValidateCCExpiration($field, $params)
{
$formatter = getArrayValue($params, 'formatter');
if ( ($formatter != 'kCCDateFormatter') || !$this->dataSource->requireCreditCard() ) {
return true;
}
if ( !$this->Application->isAdminUser ) {
// validate expiration date only for front
if ( preg_match('/([\d]{2})\/([\d]{2})/', $this->dataSource->GetDBField($field), $rets) ) {
$month = $rets[1];
$year = $rets[2];
$now_date = adodb_mktime(0, 0, 0, adodb_date('m'), adodb_date('d'), adodb_date('Y') );
$day_count = adodb_date('t', adodb_mktime(0, 0, 0, $month, 1, $year) );
$cc_date = adodb_mktime(23, 59, 59, $month, $day_count, $year);
if ($cc_date < $now_date) {
$error_field = isset($params['error_field']) ? $params['error_field'] : $field;
$this->SetError($error_field, 'credit_card_expired');
return false;
}
}
}
return true;
}
}
\ No newline at end of file
Index: branches/5.2.x/units/orders/orders_config.php
===================================================================
--- branches/5.2.x/units/orders/orders_config.php (revision 15133)
+++ branches/5.2.x/units/orders/orders_config.php (revision 15134)
@@ -1,594 +1,594 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'ord',
'ItemClass' => Array ('class' => 'OrdersItem', 'file' => 'orders_item.php', 'build_event' => 'OnItemBuild'),
'ListClass' => Array ('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
'EventHandlerClass' => Array ('class' => 'OrdersEventHandler', 'file' => 'orders_event_handler.php', 'build_event' => 'OnBuild'),
'TagProcessorClass' => Array ('class' => 'OrdersTagProcessor', 'file' => 'orders_tag_processor.php', 'build_event' => 'OnBuild'),
'ValidatorClass' => 'OrderValidator',
'AutoLoad' => true,
'RegisterClasses' => Array (
Array ('pseudo' => 'OrderCalculator', 'class' => 'OrderCalculator', 'file' => 'order_calculator.php', 'build_event' => ''),
Array ('pseudo' => 'OrderManager', 'class' => 'OrderManager', 'file' => 'order_manager.php', 'build_event' => ''),
- Array ('pseudo' => 'OrderValidator', 'class' => 'OrderValidator', 'file' => 'order_validator.php', 'build_event' => '', 'require_classes' => 'kValidator'),
+ Array ('pseudo' => 'OrderValidator', 'class' => 'OrderValidator', 'file' => 'order_validator.php', 'build_event' => ''),
),
'Hooks' => Array (
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'ord',
'HookToSpecial' => '',
'HookToEvent' => Array ( 'OnPreSave' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnRecalculateItems',
),
Array(
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => '',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnUpdateCart', 'OnUpdateCartJSON', 'OnCheckout' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnApplyCoupon',
),
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => '',
'HookToSpecial' => '',
'HookToEvent' => Array( 'OnUpdateCart', 'OnUpdateCartJSON', 'OnCheckout' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnApplyGiftCertificate',
),
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array ( 'OnCreate' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnUserCreate',
),
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array ('OnCheckExpiredMembership'),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnCheckRecurringOrders',
),
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array ( 'OnAfterLogin' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnUserLogin',
),
Array (
'Mode' => hBEFORE, // before because OnInpLogin is called after real in-portal login and uses data from hooks
'Conditional' => false,
'HookToPrefix' => 'u',
'HookToSpecial' => '',
'HookToEvent' => Array ( 'OnInpLogin' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnUserLogin',
),
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'adm',
'HookToSpecial' => '*',
'HookToEvent' => Array('OnStartup'),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnRestoreOrder',
),
),
'AggregateTags' => Array (
Array (
'AggregateTo' => 'orditems',
'AggregatedTagName' => 'LinkRemoveFromCart',
'LocalTagName' => 'Orditems_LinkRemoveFromCart',
),
Array (
'AggregateTo' => 'orditems',
'AggregatedTagName' => 'ProductLink',
'LocalTagName' => 'Orderitems_ProductLink',
),
Array (
'AggregateTo' => 'orditems',
'AggregatedTagName' => 'ProductExists',
'LocalTagName' => 'Orderitems_ProductExists',
),
),
'QueryString' => Array (
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'IDField' => 'OrderId',
'StatusField' => Array ('Status'), // field, that is affected by Approve/Decline events
'ViewMenuPhrase' => 'la_title_Orders',
'CatalogTabIcon' => 'icon16_item.png',
'TitleField' => 'OrderNumber',
'TitlePresets' => Array (
'default' => Array (
'new_status_labels' => Array ('ord' => '!la_title_Adding_Order!'),
'edit_status_labels' => Array ('ord' => '!la_title_Editing_Order!'),
'new_titlefield' => Array ('ord' => '!la_title_New_Order!'),
),
'orders_incomplete' => Array ( 'prefixes' => Array ('ord.incomplete_List'),
'format' => "!la_title_IncompleteOrders!",
),
'orders_pending' => Array ( 'prefixes' => Array ('ord.pending_List'),
'format' => "!la_title_PendingOrders!",
),
'orders_backorders' => Array ( 'prefixes' => Array ('ord.backorders_List'),
'format' => "!la_title_BackOrders!",
),
'orders_toship' => Array ( 'prefixes' => Array ('ord.toship_List'),
'format' => "!la_title_OrdersToShip!",
),
'orders_processed' => Array ( 'prefixes' => Array ('ord.processed_List'),
'format' => "!la_title_OrdersProcessed!",
),
'orders_returns' => Array ( 'prefixes' => Array ('ord.returns_List'),
'format' => "!la_title_OrdersReturns!",
),
'orders_denied' => Array ( 'prefixes' => Array ('ord.denied_List'),
'format' => "!la_title_OrdersDenied!",
),
'orders_archived' => Array ( 'prefixes' => Array ('ord.archived_List'),
'format' => "!la_title_OrdersArchived!",
),
'orders_search' => Array ( 'prefixes' => Array ('ord.search_List'),
'format' => "!la_title_OrdersSearch!",
),
'orders_edit_general' => Array ('prefixes' => Array ('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_General!"),
'orders_edit_billing' => Array ('prefixes' => Array ('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderBilling!"),
'orders_edit_shipping' => Array ('prefixes' => Array ('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderShipping!"),
'orders_edit_items' => Array ('prefixes' => Array ('ord', 'orditems_List'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderItems!"),
'orders_edit_preview' => Array ('prefixes' => Array ('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderPreview!"),
'orders_gw_result' => Array ('prefixes' => Array ('ord'), 'format' => "!la_title_OrderGWResult!"),
'orders_export' => Array ('format' => '!la_title_OrdersExport!'),
'orders_product_edit' => Array ('format' => '!la_title_Editing_Order_Item!'),
),
'EditTabPresets' => Array (
'Default' => Array (
'general' => Array ('title' => 'la_tab_General', 't' => 'in-commerce/orders/orders_edit', 'priority' => 1),
'items' => Array ('title' => 'la_tab_Items', 't' => 'in-commerce/orders/orders_edit_items', 'priority' => 2),
'shipping' => Array ('title' => 'la_tab_Shipping', 't' => 'in-commerce/orders/orders_edit_shipping', 'priority' => 3),
'billing' => Array ('title' => 'la_tab_Billing', 't' => 'in-commerce/orders/orders_edit_billing', 'priority' => 4),
'preview' => Array ('title' => 'la_tab_Preview', 't' => 'in-commerce/orders/orders_edit_preview', 'priority' => 5),
),
),
'PermSection' => Array ('main' => 'in-commerce:orders'),
'Sections' => Array (
'in-commerce:orders' => Array (
'parent' => 'in-commerce',
'icon' => 'in-commerce:orders',
'label' => 'la_tab_Orders',
'url' => Array ('t' => 'in-commerce/orders/orders_pending_list', 'pass' => 'm'),
'permissions' => Array ('view', 'add', 'edit', 'delete', 'advanced:approve', 'advanced:deny', 'advanced:archive', 'advanced:place', 'advanced:process', 'advanced:ship', 'advanced:reset_to_pending'),
'priority' => 1,
'type' => stTREE,
),
),
'SectionAdjustments' => Array (
'in-portal:visits' => Array (
'url' => Array ('t' => 'in-commerce/visits/visits_list_incommerce', 'pass' => 'm'),
),
),
'StatisticsInfo' => Array (
'pending' => Array (
'icon' => 'core:icon16_item.png',
'label' => 'la_title_Orders',
'js_url' => "#url#",
'url' => Array ('t' => 'in-commerce/orders/orders_pending_list', 'pass' => 'm'),
'status' => ORDER_STATUS_PENDING,
),
),
'TableName' => TABLE_PREFIX . 'Orders',
'CalculatedFields' => Array (
'' => Array (
'CustomerName' => 'IF( ISNULL(u.Username), IF (%1$s.PortalUserId = ' . USER_ROOT . ', \'root\', IF (%1$s.PortalUserId = ' . USER_GUEST . ', \'Guest\', \'n/a\')), CONCAT(u.FirstName,\' \',u.LastName) )',
'Username' => 'IF( ISNULL(u.Username),\'root\',u.Username)',
'OrderNumber' => 'CONCAT(LPAD(Number,6,"0"),\'-\',LPAD(SubNumber,3,"0") )',
'SubtotalWithoutDiscount' => '(SubTotal + DiscountTotal)',
'SubtotalWithDiscount' => '(SubTotal)',
'AmountWithoutVAT' => '(SubTotal+IF(ShippingTaxable=1, ShippingCost, 0)+IF(ProcessingTaxable=1, ProcessingFee, 0)-IF(VATIncluded=1,VAT,0))',
'TotalAmount' => 'SubTotal+ShippingCost+IF(VATIncluded=1,0,VAT)+ProcessingFee+InsuranceFee-GiftCertificateDiscount',
'CouponCode' => 'pc.Code',
'CouponName' => 'pc.Name',
'AffiliateUser' => 'IF( LENGTH(au.Username),au.Username,\'!la_None!\')',
'AffiliatePortalUserId' => 'af.PortalUserId',
'GiftCertificateCode' => 'gc.Code',
'GiftCertificateRecipient' => 'gc.Recipient',
'ShippingSubTotal' => '%1$s.ShippingCost + %1$s.InsuranceFee',
),
'myorders' => Array (
'OrderNumber' => 'CONCAT(LPAD(Number,6,"0"),\'-\',LPAD(SubNumber,3,"0") )',
'SubtotalWithoutDiscount' => '(SubTotal + DiscountTotal)',
'SubtotalWithDiscount' => '(SubTotal)',
'AmountWithoutVAT' => '(SubTotal+IF(ShippingTaxable=1, ShippingCost, 0)+IF(ProcessingTaxable=1, ProcessingFee, 0)-IF(VATIncluded=1,VAT,0))',
'TotalAmount' => 'SubTotal+ShippingCost+IF(VATIncluded=1,0,VAT)+ProcessingFee+InsuranceFee-GiftCertificateDiscount',
/*'ItemsCount' => 'COUNT(%1$s.OrderId)',*/
'ShippingSubTotal' => '%1$s.ShippingCost + %1$s.InsuranceFee',
),
),
// %1$s - table name of object
// %2$s - calculated fields
'ListSQLs' => Array (
'' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Users u ON %1$s.PortalUserId = u.PortalUserId
LEFT JOIN '.TABLE_PREFIX.'ProductsCoupons pc ON %1$s.CouponId = pc.CouponId
LEFT JOIN '.TABLE_PREFIX.'GiftCertificates gc ON %1$s.GiftCertificateId = gc.GiftCertificateId
LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId
LEFT JOIN '.TABLE_PREFIX.'Users au ON af.PortalUserId = au.PortalUserId',
'myorders' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Users u ON %1$s.PortalUserId = u.PortalUserId',
// LEFT JOIN '.TABLE_PREFIX.'OrderItems ON %1$s.OrderId = '.TABLE_PREFIX.'OrderItems.OrderId',
),
'ItemSQLs' => Array (
'' => ' SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'Users u ON %1$s.PortalUserId = u.PortalUserId
LEFT JOIN '.TABLE_PREFIX.'ProductsCoupons pc ON %1$s.CouponId = pc.CouponId
LEFT JOIN '.TABLE_PREFIX.'GiftCertificates gc ON %1$s.GiftCertificateId = gc.GiftCertificateId
LEFT JOIN '.TABLE_PREFIX.'Affiliates af ON %1$s.AffiliateId = af.AffiliateId
LEFT JOIN '.TABLE_PREFIX.'Users au ON af.PortalUserId = au.PortalUserId',
),
'SubItems' => Array ('orditems'),
'ListSortings' => Array (
'' => Array (
'Sorting' => Array ('OrderDate' => 'desc'),
)
),
'Fields' => Array (
'OrderId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0, 'filter_type' => 'equals'),
'Number' => Array ('type' => 'int', 'required' =>1, 'formatter' => 'kFormatter', 'unique' =>Array ('SubNumber'), 'format' => '%06d', 'max_value_inc'>999999, 'not_null' => 1, 'default' => 0),
'SubNumber' => Array ('type' => 'int', 'required' =>1, 'formatter' => 'kFormatter', 'unique' =>Array ('Number'), 'format' => '%03d', 'max_value_inc'>999, 'not_null' => 1, 'default' => 0),
'Status' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' =>Array (0=> 'la_Incomplete',1=> 'la_Pending',2=> 'la_BackOrders',3=> 'la_ToShip',4=> 'la_Processed',5=> 'la_Denied',6=> 'la_Archived'), 'use_phrases' =>1, 'not_null' => 1, 'default' => 0, 'filter_type' => 'equals'),
'OnHold' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'), 'use_phrases' => 1,
'not_null' => 1, 'default' => 0,
),
'OrderDate' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'required' => 1, 'default' => '#NOW#'),
'PortalUserId' =>Array ('type' => 'int', 'formatter' => 'kLEFTFormatter', 'error_msgs' => Array ('invalid_option' => '!la_error_UserNotFound!'), 'options' =>Array (USER_ROOT => 'root', USER_GUEST => 'Guest'), 'left_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'Users WHERE `%s` = \'%s\'', 'left_key_field' => 'PortalUserId', 'left_title_field' => 'Username', 'required' =>1, 'not_null' =>1, 'default' =>-1),
'OrderIP' => Array ('type' => 'string', 'not_null' => 1, 'default' => '', 'filter_type' => 'like'),
'UserComment' => Array ('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => NULL),
'AdminComment' => Array ('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => NULL),
'BillingTo' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingCompany' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingPhone' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingFax' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingEmail' => Array (
'type' => 'string',
'formatter' => 'kFormatter',
'regexp' => '/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i',
'error_msgs' => Array ('invalid_format' => '!la_invalid_email!', 'unique' => '!lu_email_already_exist!'),
'not_null' => 1, 'default' => '',
),
'BillingAddress1' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingAddress2' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingCity' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingState' => Array (
'type' => 'string',
'formatter' => 'kOptionsFormatter',
'options' => Array (),
'option_key_field' => 'DestAbbr',
'option_title_field' => 'Translation',
'not_null' => 1, 'default' => '',
),
'BillingZip' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'BillingCountry' => Array(
'type' => 'string',
'formatter' => 'kOptionsFormatter',
'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
FROM '.TABLE_PREFIX.'CountryStates
WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
ORDER BY Name',
'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => 'USA'
),
'VAT' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'not_null' =>1, 'default' => '0', 'format' => '%01.2f'),
'VATPercent' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'not_null' =>1, 'default' => '0', 'format' => '%01.3f'),
'VATIncluded' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'), 'use_phrases' => 1,
'not_null' => 1, 'default' => 0,
),
'PaymentType' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options_sql' => 'SELECT %s
FROM ' . TABLE_PREFIX . 'PaymentTypes
WHERE Status = 1
ORDER BY Priority DESC, Name ASC',
'option_key_field' => 'PaymentTypeId', 'option_title_field' => 'Description',
'not_null' => 1, 'default' => 0
),
'PaymentAccount' => Array ('type' => 'string', 'not_null' => 1, 'cardtype_field' => 'PaymentCardType', 'default' => '', 'filter_type' => 'like'),
'PaymentNameOnCard' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'PaymentCCExpDate' => Array ('type' => 'string', 'formatter' => 'kCCDateFormatter', 'month_field' => 'PaymentCCExpMonth', 'year_field' => 'PaymentCCExpYear', 'not_null' => 1, 'default' => ''),
'PaymentCardType' => Array ('type' => 'string', 'not_null' => 1, 'formatter' => 'kOptionsFormatter', 'options' => Array ('' => '', '1' => 'Visa', '2' => 'Mastercard', '3' => 'Amex', '4' => 'Discover', '5' => 'Diners Club', '6' => 'JBC'), 'default' => ''),
'PaymentExpires' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => '#NOW#'),
'ShippingTo' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingCompany' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingPhone' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingFax' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingEmail' => Array (
'type' => 'string',
'formatter' => 'kFormatter',
'regexp' => '/^(' . REGEX_EMAIL_USER . '@' . REGEX_EMAIL_DOMAIN . ')$/i',
'error_msgs' => Array ('invalid_format' => '!la_invalid_email!'),
'not_null' => 1, 'default' => '',
),
'ShippingAddress1' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingAddress2' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingCity' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingState' => Array (
'type' => 'string', 'formatter' => 'kOptionsFormatter',
'options' => Array (),
'option_key_field' => 'DestAbbr', 'option_title_field' => 'Translation',
'not_null' => 1, 'default' => ''),
'ShippingZip' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingCountry' => Array(
'type' => 'string', 'formatter' => 'kOptionsFormatter',
'options_sql' => ' SELECT IF(l%2$s_Name = "", l%3$s_Name, l%2$s_Name) AS Name, IsoCode
FROM '.TABLE_PREFIX.'CountryStates
WHERE Type = ' . DESTINATION_TYPE_COUNTRY . '
ORDER BY Name',
'option_key_field' => 'IsoCode', 'option_title_field' => 'Name',
'not_null' => 1, 'default' => 'USA'
),
'ShippingType' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options_sql' => 'SELECT %s
FROM ' . TABLE_PREFIX . 'ShippingType
WHERE Status = 1',
'option_key_field' => 'ShippingID',
'option_title_field' => 'Name',
'not_null' => 1, 'default' => 0,
),
'ShippingCost' => Array ('type' => 'double', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00'),
'ShippingCustomerAccount' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingTracking' => Array ('type' => 'string', 'not_null' => 1, 'default' => ''),
'ShippingDate' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => null),
'SubTotal' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00'),
'ReturnTotal' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00'),
'CostTotal' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00'),
'OriginalAmount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00'),
'ShippingOption' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (
0 => 'la_ship_all_together', 1 => 'la_ship_backorder_separately', 2 => 'la_ship_backorders_upon_avail',
),
'use_phrases' => 1, 'not_null' => 1, 'default' => 0,
),
'ShippingGroupOption' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'use_phrases' => 1,
'options' => Array (0 => 'la_opt_AutoGroupShipments', 1 => 'la_opt_ManualGroupShipments'),
'not_null' => 1, 'default' => 0,
),
'GiftCertificateId' => Array ('type' => 'int', 'default' => null),
'GiftCertificateDiscount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00',),
'ShippingInfo' => Array ('type' => 'string', 'default' => NULL),
'CouponId' => Array ('type' => 'int', 'default' => null),
'CouponDiscount' => Array ('type' => 'float', 'not_null' => 1, 'default' => '0.00', 'formatter' => 'kFormatter', 'format' => '%01.2f'),
'DiscountTotal' => Array ('type' => 'float', 'not_null' => 1, 'default' => '0.00', 'formatter' => 'kFormatter', 'format' => '%01.2f'),
'TransactionStatus' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_opt_Invalid', 1 => 'la_opt_Verified', 2 => 'la_opt_Penging'),
'use_phrases' =>1, 'not_null' => 1, 'default' => 2,
),
'GWResult1' => Array ('type' => 'string', 'formatter' => 'kSerializedFormatter', 'default' => NULL),
'GWResult2' => Array ('type' => 'string', 'formatter' => 'kSerializedFormatter', 'default' => NULL),
'AffiliateId' => Array ('type' => 'int', 'formatter' => 'kLEFTFormatter', 'error_msgs' => Array ('invalid_option' => '!la_error_UserNotFound!'), 'options' => Array (0 => 'lu_None'), 'left_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'Affiliates af LEFT JOIN '.TABLE_PREFIX.'Users pu ON pu.PortalUserId = af.PortalUserId WHERE `%s` = \'%s\'', 'left_key_field' => 'AffiliateId', 'left_title_field' => 'Username', 'not_null' =>1, 'default' =>0),
'VisitId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'AffiliateCommission' => Array ('type' => 'double', 'formatter' => 'kFormatter', 'format' => '%.02f', 'not_null' => 1, 'default' => '0.0000'),
'ProcessingFee' => Array ('type' => 'double', 'formatter' => 'kFormatter', 'format' => '%.02f', 'not_null' => '0', 'default' => '0.0000'),
'InsuranceFee' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'not_null' => 1, 'default' => '0.00'),
'ShippingTaxable' => Array ('type' => 'int', 'not_null' => 0, 'default' => 0),
'ProcessingTaxable' => Array ('type' => 'int', 'not_null' => 0, 'default' => 0),
'IsRecurringBilling' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes',), 'use_phrases' => 1,
'default' => 0, 'not_null' => 1,
),
'ChargeOnNextApprove' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes',), 'use_phrases' => 1,
'default' => 0, 'not_null' => 1,
),
'NextCharge' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => null),
'GroupId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'GoogleOrderNumber' => Array ('type' => 'string', 'default' => NULL), // MySQL BIGINT UNSIGNED = 8 Bytes, PHP int = 4 Bytes -> threat as string
),
'VirtualFields' => Array (
'CustomerName' => Array ('type' => 'string', 'default' => '', 'filter_type' => 'like'),
'TotalAmount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'default' => '0.00'),
'AmountWithoutVAT' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'default' => '0.00'),
'SubtotalWithDiscount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'default' => '0.00'),
'SubtotalWithoutDiscount' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'default' => '0.00'),
'ShippingSubTotal' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%01.2f', 'default' => '0.00'),
'OrderNumber' => Array ('type' => 'string', 'default' => '', 'filter_type' => 'like'),
'CouponCode' => Array ('type' => 'string', 'default' => ''),
'CouponName' => Array ('type' => 'string', 'default' => ''),
'GiftCertificateCode' => Array ('type' => 'string', 'default' => ''),
'GiftCertificateRecipient' => Array ('type' => 'string', 'default' => ''),
// for ResetToUser
'UserTo' => Array ('type' => 'string', 'default' => ''),
'UserCompany' => Array ('type' => 'string', 'default' => ''),
'UserPhone' => Array ('type' => 'string', 'default' => ''),
'UserFax' => Array ('type' => 'string', 'default' => ''),
'UserEmail' => Array ('type' => 'string', 'default' => ''),
'UserAddress1' => Array ('type' => 'string', 'default' => ''),
'UserAddress2' => Array ('type' => 'string', 'default' => ''),
'UserCity' => Array ('type' => 'string', 'default' => ''),
'UserState' => Array ('type' => 'string', 'default' => ''),
'UserZip' => Array ('type' => 'string', 'default' => ''),
'UserCountry' => Array ('type' => 'string', 'default' => ''),
// for Search
'Username' => Array ('type' => 'string', 'filter_type' => 'like', 'default' => ''),
'HasBackOrders' => Array ('type' => 'int', 'default' => 0),
'PaymentCVV2' => Array ('type' => 'string', 'default' => ''),
'AffiliateUser' => Array ('type' => 'string', 'filter_type' => 'like', 'default' => ''),
'AffiliatePortalUserId' => Array ('type' => 'int', 'default' => 0),
// export related fields: begin
'ExportFormat' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'CSV', /*2 => 'XML'*/), 'default' => 1),
'ExportFilename' => Array ('type' => 'string', 'default' => ''),
'FieldsSeparatedBy' => Array ('type' => 'string', 'default' => ','),
'FieldsEnclosedBy' => Array ('type' => 'string', 'default' => '"'),
'LineEndings' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'Windows', 2 => 'UNIX'), 'default' => 1),
'LineEndingsInside' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'CRLF', 2 => 'LF'), 'default' => 2),
'IncludeFieldTitles' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'),
'use_phrases' => 1, 'default' => 1,
),
'ExportColumns' => Array ('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array (), 'default' => ''),
'AvailableColumns' => Array ('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array (), 'default' => ''),
'ExportPresets' => Array ('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array (), 'default' => ''),
'ExportSavePreset' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'),
'use_phrases' => 1, 'default' => 0,
),
'ExportPresetName' => Array ('type' => 'string', 'default' => ''),
// export related fields: end
// for "one step checkout"
'UserPassword' => Array (
'type' => 'string',
'formatter' => 'kPasswordFormatter', 'encryption_method' => 'md5', 'verify_field' => 'VerifyUserPassword',
'skip_empty' => 1, 'default' => 'd41d8cd98f00b204e9800998ecf8427e'
),
// for "Shipping Info" step during Checkout
'ShippingTypeId' => Array ('type' => 'array', 'default' => ''),
),
'Grids' => Array (
'Default' => Array (
'Icons' => Array (
'default' => 'icon16_item.png',
1 => 'icon16_pending.png',
5 => 'icon16_disabled.png',
'module' => 'core',
),
'Fields' => Array (
'OrderId' => Array ('title' => 'column:la_fld_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 70, ),
'OrderNumber' => Array ( 'data_block' => 'grid_ordernumber_td', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'OrderDate' => Array ( 'title' => 'la_col_OrderDate', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_date_range_filter', 'width' => 140, ),
'CustomerName' => Array ( 'title' => 'la_col_CustomerName', 'data_block' => 'grid_userlink_td', 'user_field' => 'PortalUserId', 'filter_block' => 'grid_like_filter', 'width' => 140, ),
'PaymentType' => Array ( 'data_block' => 'grid_billinglink_td', 'filter_block' => 'grid_options_filter', 'width' => 140, ),
'TotalAmount' => Array ( 'data_block' => 'grid_previewlink_td', 'filter_block' => 'grid_range_filter', 'width' => 140, ),
'AffiliateUser' => Array ( 'data_block' => 'grid_userlink_td', 'user_field' => 'AffiliatePortalUserId', 'filter_block' => 'grid_like_filter', 'width' => 140, ),
'OnHold' => Array ('filter_block' => 'grid_options_filter', 'width' => 100, ),
),
),
'Search' => Array (
'Icons' => Array (
'default' => 'icon16_item.png',
1 => 'icon16_pending.png',
5 => 'icon16_disabled.png',
'module' => 'core',
),
'Fields' => Array (
'OrderId' => Array ('title' => 'column:la_fld_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 70, ),
'OrderNumber' => Array ('data_block' => 'grid_ordernumber_td', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'Status' => Array ('filter_block' => 'grid_options_filter', 'filter_block' => 'grid_options_filter', 'width' => 100, ),
'OrderDate' => Array ('title' => 'la_col_OrderDate', 'filter_block' => 'grid_date_range_filter', 'width' => 140, ),
'CustomerName' => Array ('title' => 'la_col_CustomerName', 'data_block' => 'grid_userlink_td', 'user_field' => 'PortalUserId', 'filter_block' => 'grid_like_filter'),
'PaymentType' => Array ('data_block' => 'grid_billinglink_td', 'filter_block' => 'grid_options_filter'),
'TotalAmount' => Array ('data_block' => 'grid_previewlink_td', 'filter_block' => 'grid_range_filter'),
'AffiliateUser' => Array ('data_block' => 'grid_userlink_td', 'user_field' => 'AffiliatePortalUserId', 'filter_block' => 'grid_user_like_filter'),
'OrderIP' => Array ('filter_block' => 'grid_like_filter'),
'Username' => Array ('filter_block' => 'grid_user_like_filter'),
'PaymentAccount' => Array ('title' => 'column:la_fld_CreditCardNumber', 'filter_block' => 'grid_like_filter'),
),
),
),
);
\ 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 15133)
+++ branches/5.2.x/units/affiliate_plans_brackets/affiliate_plans_brackets_event_handler.php (revision 15134)
@@ -1,123 +1,123 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
class AffiliatePlansBracketsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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)
+ 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)
+ 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)
+ 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');
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $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');
/* @var $brackets_helper kBracketsHelper */
$brackets_helper->InitHelper('FromAmount', 'ToAmount', Array ('Percent' => ''));
$brackets_helper->replaceInfinity($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnPreSaveBrackets(&$event)
+ function OnPreSaveBrackets($event)
{
$brackets_helper =& $this->Application->recallObject('BracketsHelper');
/* @var $brackets_helper kBracketsHelper */
$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 15133)
+++ branches/5.2.x/units/currencies/currencies_event_handler.php (revision 15134)
@@ -1,322 +1,322 @@
<?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 standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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),
'OnItemBuild' => Array ('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* 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
* @access public
*/
- public function getPassedID(kEvent &$event)
+ public function getPassedID(kEvent $event)
{
if ( $event->Special == 'current' ) {
return Array ('ISO' => $this->Application->RecallVar('curr_iso'));
}
return parent::getPassedID($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnSetPrimary(&$event)
+ function OnSetPrimary($event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$event->status = kEvent::erFAIL;
return;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('IsPrimary', 1);
$object->Update();
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @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');
$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');
$this->Conn->Query($sql);
}
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
if ( $event->Special == 'active' ) {
$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) . ')');
}
}
/**
* 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(kEvent &$event)
+ protected function OnSave(kEvent $event)
{
$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)
+ function OnDisableUnused($event)
{
$unused_ids = $this->Application->GetVar('unused_ids');
if ( $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)
+ 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)
+ 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();
}
}
/**
* Allows to change currency to given one
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnChangeCurrency(&$event)
+ protected 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);
$passed = explode(',', $this->Application->GetVar('passed'));
$prefix_index = array_search($event->getPrefixSpecial(), $passed);
if ( $prefix_index !== false ) {
unset($passed[$prefix_index]);
$this->Application->SetVar('passed', implode(',', $passed));
}
}
/**
* Changes default module to custom (when available)
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $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 15133)
+++ branches/5.2.x/units/products/products_event_handler.php (revision 15134)
@@ -1,1591 +1,1591 @@
<?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 standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
// front
'OnCancelAction' => Array('self' => true),
'OnRateProduct' => Array('self' => true),
'OnClearRecent' => Array('self' => true),
'OnRecommendProduct' => Array('self' => true),
'OnAddToCompare' => Array('self' => true),
'OnRemoveFromCompare' => Array('self' => true),
'OnCancelCompare' => 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);
}
/**
* Define alternative event processing method names
*
* @return void
* @see kEventHandler::$eventMethods
* @access protected
*/
protected 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
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$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));
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)
+ function InventoryAction($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$field_values = $this->getSubmittedFields($event);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
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)
+ 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' );
}
}
}
/**
* 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(kEvent &$event)
+ protected function OnBeforeDeleteFromLive(kEvent $event)
{
parent::OnBeforeDeleteFromLive($event);
$product =& $this->Application->recallObject($event->Prefix . '.itemlive', null, Array ('skip_autoload' => true));
/* @var $product kCatDBItem */
$product->SwitchToLive();
$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));
/* @var $temp kCatDBItem */
$temp->SwitchToTemp();
$temp->Load($id);
$temp->SetDBFieldsFromHash($product->GetFieldValues(), Array ('QtyInStock', 'QtyReserved', 'QtyBackOrdered', 'QtyOnOrder'));
$temp->Update();
}
/**
* Removes any information about current/selected ids
* from Application variables and Session
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function clearSelectedIDs(kEvent &$event)
+ protected function clearSelectedIDs(kEvent $event)
{
parent::clearSelectedIDs($event);
$this->Application->SetVar('inventory_actions', $this->Application->RecallVar('inventory_actions'));
$this->Application->RemoveVar('inventory_actions');
}
/**
* 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(kEvent &$event)
+ protected function OnSave(kEvent $event)
{
parent::OnSave($event);
if ( $event->status == kEvent::erSUCCESS ) {
$this->RunScheduledInventoryActions($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(kEvent &$event)
+ protected function OnPreCreate(kEvent $event)
{
parent::onPreCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('Type', $this->Application->GetVar($event->getPrefixSpecial(true) . '_new_type'));
}
/**
* Saves edited item in temp table and loads
* item with passed id in current template
* Used in Prev/Next buttons
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnPreSaveAndGo(kEvent &$event)
+ protected function OnPreSaveAndGo(kEvent $event)
{
$event->CallSubEvent('OnPreSave');
$this->LoadItem($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$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)
+ function getTypeClauses($event)
{
$types = $event->getEventParam('types');
$types = $types ? explode(',', $types) : Array ();
$except_types = $event->getEventParam('except');
$except_types = $except_types ? explode(',', $except_types) : Array ();
$object =& $event->getObject();
/* @var $object kDBList */
$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
// compare products: begin
if ( in_array('compare', $types) || in_array('compare', $except_types) ) {
$compare_products = $this->getCompareProducts();
if ( $compare_products ) {
$compare_products = $this->Conn->qstrArray($compare_products);
$type_clauses['compare']['include'] = '%1$s.ProductId IN (' . implode(',', $compare_products) . ') AND PrimaryCat = 1';
$type_clauses['compare']['except'] = '%1$s.ProductId NOT IN (' . implode(',', $compare_products) . ') AND PrimaryCat = 1';
}
else {
$type_clauses['compare']['include'] = '0';
$type_clauses['compare']['except'] = '1';
}
$type_clauses['compare']['having_filter'] = false;
if ( $event->getEventParam('per_page') === false ) {
$event->setEventParam('per_page', $this->Application->ConfigValue('MaxCompareProducts'));
}
}
// compare products: end
// products already in shopping cart: begin
if ( in_array('in_cart', $types) || in_array('in_cart', $except_types) ) {
$order_id = $this->Application->RecallVar('ord_id');
if ( $order_id ) {
$sql = 'SELECT ProductId
FROM ' . TABLE_PREFIX . 'OrderItems
WHERE OrderId = ' . $order_id;
$in_cart = $this->Conn->GetCol($sql);
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 ( in_array('my_downloads', $types) || in_array('my_downloads', $except_types) ) {
$user_id = $this->Application->RecallVar('user_id');
$sql = 'SELECT ProductId
FROM ' . TABLE_PREFIX . 'UserFileAccess
WHERE PortalUserId = ' . $user_id;
$my_downloads = $user_id > 0 ? $this->Conn->GetCol($sql) : 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 ( in_array('wish_list', $types) || in_array('wish_list', $except_types) ) {
$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 ( in_array('content', $types) || in_array('content', $except_types) ) {
$object->removeFilter('category_filter');
$object->AddGroupByField('%1$s.ProductId');
$object_product =& $this->Application->recallObject($event->Prefix);
/* @var $object_product ProductsItem */
$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 > ' . adodb_mktime());
}
return $type_clauses;
}
- function OnClearRecent(&$event)
+ function OnClearRecent($event)
{
$this->Application->RemoveVar('recent_products');
}
/**
* Occurs, when user rates a product
*
* @param kEvent $event
*/
- function OnRateProduct(&$event)
+ function OnRateProduct($event)
{
$event->SetRedirectParam('pass', 'all,p');
$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)
+ function OnCancelAction($event)
{
$event->SetRedirectParam('pass', 'all,p');
$event->redirect = $this->Application->GetVar('cancel_template');
}
/**
* Enter description here...
*
* @param kEvent $event
*/
- function OnRecommendProduct(&$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'));
$event->redirect = $this->Application->GetVar('template_success');
}
else {
// $event->setRedirectParams(Array('opener' => 's', 'pass' => 'all'));
// $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)
+ 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)
+ function OnDeleteListingType($event)
{
$listing_type =& $event->MasterEvent->getObject();
/* @var $listing_type kDBItem */
$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)
+ 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 . 'UserGroupRelations
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 . 'UserGroupRelations', '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)
+ 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){
+ 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);
}
}
}
/**
* 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
*/
- protected function OnPreSave(kEvent &$event)
+ protected function OnPreSave(kEvent $event)
{
$this->CheckRequiredOptions($event);
parent::OnPreSave($event);
}
/**
* Set new price to ProductsPricing
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemCreate(kEvent &$event)
+ protected function OnAfterItemCreate(kEvent $event)
{
parent::OnAfterItemCreate($event);
$this->_updateProductPrice($event);
}
/**
* Set new price to ProductsPricing
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemUpdate(kEvent &$event)
+ protected function OnAfterItemUpdate(kEvent $event)
{
parent::OnAfterItemUpdate($event);
$this->_updateProductPrice($event);
}
/**
* Updates product's primary price based on Price virtual field value
*
* @param kEvent $event
*/
- function _updateProductPrice(&$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)
+ 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();
}
}
/**
* Occurs after deleting item, id of deleted item
* is stored as 'id' param of event
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemDelete(kEvent &$event)
+ protected function OnAfterItemDelete(kEvent $event)
{
parent::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
*/
/**
* Load price from temp table if product mode is temp table
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemLoad(kEvent &$event)
+ protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object ProductsItem */
$a_pricing = $object->getPrimaryPricing();
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)
+ 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)
+ 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)
+ 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)
+ function OnSaveItems($event)
{
//$event->CallSubEvent('OnUpdate');
$event->redirect = false;
//$event->setRedirectParams(Array ('opener' => 's', 'pass' => 'all,p'));
}
/**
* Removes product from package
*
* @param kEvent $event
*/
- function OnRemovePackageItem(&$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);
}
/**
* Occurs before deleting item, id of item being
* deleted is stored as 'id' event param
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemDelete(kEvent &$event)
+ protected function OnBeforeItemDelete(kEvent $event)
{
parent::OnBeforeItemDelete($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$sql = 'SELECT COUNT(*)
FROM ' . TABLE_PREFIX . 'Products
WHERE PackageContent LIKE "%|' . $object->GetID() . '%"';
$product_includes_in = $this->Conn->GetOne($sql);
if ( $product_includes_in > 0 ) {
$event->status = kEvent::erFAIL;
}
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
* @access protected
*/
- public function getCustomExportColumns(kEvent &$event)
+ public function getCustomExportColumns(kEvent $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)
+ function setCustomExportColumns($event)
{
parent::setCustomExportColumns($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$this->setPrimaryPrice($object->GetID(), (double)$object->GetDBField('Price'), Array ('Cost' => (double)$object->GetDBField('Cost')));
}
- function OnPreSaveAndOpenPopup(&$event)
+ function OnPreSaveAndOpenPopup($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$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->SetRedirectParam('pass', 'all');
$event->SetRedirectParam($event->getPrefixSpecial(true) . '_id', $object->GetID());
}
/**
* 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
* @access public
*/
- public function getPassedID(kEvent &$event)
+ public function getPassedID(kEvent $event)
{
if ( $this->Application->isAdminUser ) {
$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));
/* @var $ord_item OrdersItem */
if ( $ord_item->GetDBField('ProductId') ) {
$passed = $ord_item->GetDBField('ProductId');
}
}
return $passed;
}
/**
* Occurs, when config was parsed, allows to change config data dynamically
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
if (!$this->Application->LoggedIn()) {
return ;
}
$user_id = $this->Application->RecallVar('user_id');
$sql = 'SELECT PrimaryGroupId
FROM ' . TABLE_PREFIX . 'Users
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
* @return void
* @access protected
*/
- protected function OnEdit(kEvent &$event)
+ protected function OnEdit(kEvent $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)
+ 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
* @return void
* @access protected
*/
- protected function OnCloneSubItem(kEvent &$event)
+ protected function OnCloneSubItem(kEvent $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);
}
}
/**
* Adds product to comparison list
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAddToCompare(kEvent &$event)
+ protected function OnAddToCompare(kEvent $event)
{
$products = $this->getCompareProducts();
$product_id = (int)$this->Application->GetVar($event->Prefix . '_id');
if ( $product_id ) {
$max_products = $this->Application->ConfigValue('MaxCompareProducts');
if ( count($products) < $max_products ) {
$products[] = $product_id;
$this->Application->Session->SetCookie('compare_products', implode('|', array_unique($products)));
$event->SetRedirectParam('result', 'added');
}
else {
$event->SetRedirectParam('result', 'error');
}
}
$event->SetRedirectParam('pass', 'm,p');
}
/**
* Adds product to comparison list
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnRemoveFromCompare(kEvent &$event)
+ protected function OnRemoveFromCompare(kEvent $event)
{
$products = $this->getCompareProducts();
$product_id = (int)$this->Application->GetVar($event->Prefix . '_id');
if ( $product_id && in_array($product_id, $products) ) {
$products = array_diff($products, Array ($product_id));
$this->Application->Session->SetCookie('compare_products', implode('|', array_unique($products)));
$event->SetRedirectParam('result', 'removed');
}
$event->SetRedirectParam('pass', 'm,p');
}
/**
* Cancels product compare
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnCancelCompare(kEvent &$event)
+ protected function OnCancelCompare(kEvent $event)
{
$this->Application->Session->SetCookie('compare_products', '', -1);
$event->SetRedirectParam('result', 'all_removed');
}
/**
* Returns products, that needs to be compared with each other
*
* @return Array
* @access protected
*/
protected function getCompareProducts()
{
$products = $this->Application->GetVarDirect('compare_products', 'Cookie');
$products = $products ? explode('|', $products) : Array ();
return $products;
}
}
\ No newline at end of file
Index: branches/5.2.x/units/products/products_config.php
===================================================================
--- branches/5.2.x/units/products/products_config.php (revision 15133)
+++ branches/5.2.x/units/products/products_config.php (revision 15134)
@@ -1,698 +1,698 @@
<?php
/**
* @version $Id$
* @package In-Commerce
* @copyright Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/
defined('FULL_PATH') or die('restricted access!');
$config = Array (
'Prefix' => 'p',
- 'ItemClass' => Array ('class' => 'ProductsItem', 'file' => 'products_item.php', 'require_classes' => Array ('kCatDBItem'), 'build_event' => 'OnItemBuild'),
+ 'ItemClass' => Array ('class' => 'ProductsItem', 'file' => 'products_item.php', 'build_event' => 'OnItemBuild'),
'ListClass' => Array ('class' => 'kCatDBList', 'file' => '', 'build_event' => 'OnListBuild'),
- 'EventHandlerClass' => Array ('class' => 'ProductsEventHandler', 'file' => 'products_event_handler.php', 'require_classes' => Array ('kCatDBEventHandler'), 'build_event' => 'OnBuild'),
- 'TagProcessorClass' => Array ('class' => 'ProductsTagProcessor', 'file' => 'products_tag_processor.php', 'require_classes' => Array ('kCatDBTagProcessor'), 'build_event' => 'OnBuild'),
+ 'EventHandlerClass' => Array ('class' => 'ProductsEventHandler', 'file' => 'products_event_handler.php', 'build_event' => 'OnBuild'),
+ 'TagProcessorClass' => Array ('class' => 'ProductsTagProcessor', 'file' => 'products_tag_processor.php', 'build_event' => 'OnBuild'),
'AutoLoad' => true,
'QueryString' => Array (
1 => 'id',
2 => 'Page',
3 => 'PerPage',
4 => 'event',
5 => 'mode',
),
'CatalogItem' => true,
'AdminTemplatePath' => 'products',
'AdminTemplatePrefix' => 'products_',
'SearchConfigPostfix' => 'products',
'ConfigPriority' => 0,
'RewritePriority' => 104,
'RewriteListener' => 'CategoryItemRewrite:RewriteListener',
'Hooks' => Array (
// for subscription products: access group is saved before changing pricings
Array (
'Mode' => hAFTER,
'Conditional' => true,
'HookToPrefix' => 'pr',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnNew', 'OnAfterItemLoad'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnPreSave',
),
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'lst',
'HookToSpecial' => '',
'HookToEvent' => Array ( 'OnBeforeCopyToLive' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnSaveVirtualProduct',
),
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'lst',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnAfterItemDelete'),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnDeleteListingType',
),
Array (
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'lst',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnAfterConfigRead'),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnModifyPaidListingConfig',
),
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => 'file',
'HookToSpecial' => '',
'HookToEvent' => Array ( 'OnNew', 'OnEdit' ),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnPreSave',
),
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => '',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnAfterConfigRead'),
'DoPrefix' => 'cdata',
'DoSpecial' => '*',
'DoEvent' => 'OnDefineCustomFields',
),
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => 'rev',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnAfterConfigRead'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnCloneSubItem',
),
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => 'fav',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnAfterConfigRead'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnCloneSubItem',
),
Array (
'Mode' => hBEFORE,
'Conditional' => false,
'HookToPrefix' => 'ci',
'HookToSpecial' => '*',
'HookToEvent' => Array ('OnAfterConfigRead'),
'DoPrefix' => '',
'DoSpecial' => '*',
'DoEvent' => 'OnCloneSubItem',
),
),
'IDField' => 'ProductId',
'StatusField' => Array ('Status'), // field, that is affected by Approve/Decline events
'TitleField' => 'Name', // field, used in bluebar when editing existing item
'ItemType' => 11, // this is used when relation to product is added from in-portal and via-versa
'ViewMenuPhrase' => 'la_text_Products',
'CatalogTabIcon' => 'in-commerce:icon16_products.png',
'ItemPropertyMappings' => Array (
'NewDays' => 'Product_NewDays', // number of days item to be NEW
'MinPopVotes' => 'Product_MinPopVotes', // minimum number of votes for an item to be POP
'MinPopRating' => 'Product_MinPopRating', // minimum rating for an item to be POP
'MaxHotNumber' => 'Product_MaxHotNumber', // maximum number of HOT (top seller) items
'HotLimit' => 'Product_HotLimit', // variable name in inp_Cache table
'ClickField' => 'Hits', // item click count is stored here (in item table)
),
'TitlePhrase' => 'la_text_Product',
'TitlePresets' => Array (
'default' => Array ( 'new_status_labels' => Array ('p' => '!la_title_Adding_Product!'),
'edit_status_labels' => Array ('p' => '!la_title_Editing_Product!'),
'new_titlefield' => Array ('p' => '!la_title_NewProduct!'),
),
'product_list' =>Array ( 'prefixes' => Array ('c_List', 'p_List'),
'tag_params' => Array ('c' => Array ('per_page' =>-1)),
'format' => "!la_title_Categories! (#c_recordcount#) - !la_title_Products! (#p_recordcount#)",
),
'products_edit' =>Array ( 'prefixes' => Array ('p'),
'new_titlefield' => Array ('p' => '!la_title_NewProduct!'),
'format' => "#p_status# '#p_titlefield#' - !la_title_General!",
),
'inventory' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# - '#p_titlefield#' - !la_title_Product_Inventory!"),
'pricing' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Product_Pricing!"),
'access_pricing' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Product_AccessPricing!"),
'access' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Product_Access!"),
'files' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Product_Files!"),
'options' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Product_Options!"),
'categories' => Array ('prefixes' => Array ('p', 'p-ci_List'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Categories!"),
'relations' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Relations!"),
'content' => Array ('prefixes' => Array ('p', 'p.content_List'), 'tag_params' => Array ('p.content' => Array ('types' => 'content', 'live_table' =>true)), 'format' => "#p_status# '#p_titlefield#' - !la_title_Product_PackageContent!"),
'images' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Images!"),
'reviews' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Reviews!"),
'products_custom' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Custom!"),
'images_edit' => Array ( 'prefixes' => Array ('p', 'img'),
'new_status_labels' => Array ('img' => '!la_title_Adding_Image!'),
'edit_status_labels' => Array ('img' => '!la_title_Editing_Image!'),
'new_titlefield' => Array ('img' => '!la_title_New_Image!'),
'format' => "#p_status# '#p_titlefield#' - #img_status# '#img_titlefield#'",
),
'pricing_edit' => Array ( 'prefixes' => Array ('p', 'pr'),
'new_status_labels' => Array ('pr' =>"!la_title_Adding_PriceBracket! '!la_title_New_PriceBracket!'"),
'edit_status_labels' => Array ('pr' => '!la_title_Editing_PriceBracket!'),
'format' => "#p_status# '#p_titlefield#' - #pr_status#",
),
'options_edit' => Array ( 'prefixes' => Array ('p', 'po'),
'new_status_labels' => Array ('po' =>"!la_title_Adding_Option!"),
'edit_status_labels' => Array ('po' => '!la_title_Editing_Option!'),
'new_titlefield' => Array ('po' => '!la_title_New_Option!'),
'format' => "#p_status# '#p_titlefield#' - #po_status# '#po_titlefield#'",
),
'options_combinations' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_ManagingOptionCombinations!"),
'shipping_options' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_ManagingShippingOptions!"),
'file_edit' => Array ( 'prefixes' => Array ('p', 'file'),
'new_status_labels' => Array ('file' =>"!la_title_Adding_File!"),
'edit_status_labels' => Array ('file' => '!la_title_Editing_File!'),
'new_titlefield' => Array ('file' => '!la_title_New_File!'),
'format' => "#p_status# '#p_titlefield#' - #file_status# '#file_titlefield#'",
),
'relations_edit' => Array ( 'prefixes' => Array ('p', 'rel'),
'new_status_labels' => Array ('rel' =>"!la_title_Adding_Relationship! '!la_title_New_Relationship!'"),
'edit_status_labels' => Array ('rel' => '!la_title_Editing_Relationship!'),
'format' => "#p_status# '#p_titlefield#' - #rel_status#",
),
'reviews_edit' => Array ( 'prefixes' => Array ('p', 'rev'),
'new_status_labels' => Array ('rev' =>"!la_title_Adding_Review! '!la_title_New_Review!'"),
'edit_status_labels' => Array ('rev' => '!la_title_Editing_Review!'),
'format' => "#p_status# '#p_titlefield#' - #rev_status#",
),
'products_export' => Array ('format' => '!la_title_ProductsExport!'),
'products_import' => Array ('format' => '!la_title_ImportProducts!'),
'tree_in-commerce' => Array ('format' => '!la_Text_Version! '.$this->Application->findModule('Name', 'In-Commerce', 'Version')),
),
'EditTabPresets' => Array (
'Default' => Array (
'general' => Array ('title' => 'la_tab_General', 't' => 'in-commerce/products/products_edit', 'priority' => 1),
'inventory' => Array ('title' => 'la_tab_Inventory', 't' => 'in-commerce/products/products_inventory', 'priority' => 2),
'access_and_pricing' => Array ('title' => 'la_tab_AccessAndPricing', 't' => 'in-commerce/products/products_access', 'priority' => 3),
'pricing' => Array ('title' => 'la_tab_Pricing', 't' => 'in-commerce/products/products_pricing', 'priority' => 4),
// 'pricing2' => Array ('title' => 'la_tab_Pricing', 't' => 'in-commerce/products/products_access_pricing', 'priority' => 5),
'files_and_pricing' => Array ('title' => 'la_tab_FilesAndPricing', 't' => 'in-commerce/products/products_files', 'priority' => 6),
'options' => Array ('title' => 'la_tab_Options', 't' => 'in-commerce/products/products_options', 'priority' => 7),
'categories' => Array ('title' => 'la_tab_Categories', 't' => 'in-commerce/products/products_categories', 'priority' => 8),
'relations' => Array ('title' => 'la_tab_Relations', 't' => 'in-commerce/products/products_relations', 'priority' => 9),
'package_content' => Array ('title' => 'la_tab_PackageContent', 't' => 'in-commerce/products/products_packagecontent', 'priority' => 10),
'images' => Array ('title' => 'la_tab_Images', 't' => 'in-commerce/products/products_images', 'priority' => 11),
'reviews' => Array ('title' => 'la_tab_Reviews', 't' => 'in-commerce/products/products_reviews', 'priority' => 12),
'custom' => Array ('title' => 'la_tab_Custom', 't' => 'in-commerce/products/products_custom', 'priority' => 13),
),
),
'PermItemPrefix' => 'PRODUCT',
'PermTabText' => 'In-Commerce',
'PermSection' => Array ('main' => 'CATEGORY:in-commerce:products_list', 'search' => 'in-commerce:search', 'custom' => 'in-commerce:configuration_custom'),
'Sections' => Array (
'in-commerce' => Array (
'parent' => 'in-portal:root',
'icon' => 'ecommerce',
'label' => 'la_title_In-Commerce',
'url' => Array ('t' => 'index', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array ('view'),
'priority' => 2.1,
'container' => true,
'type' => stTREE,
),
'in-commerce:products' => Array (
'parent' => 'in-portal:site',
'icon' => 'products',
'label' => 'la_tab_Products',
'url' => Array ('t' => 'catalog/advanced_view', 'anchor' => 'tab-p.showall', 'pass' => 'm'),
'onclick' => 'setCatalogTab(\'p.showall\')',
'permissions' => Array ('view'),
'priority' => 3.2,
'type' => stTREE,
),
// product settings
'in-commerce:setting_folder' => Array (
'parent' => 'in-portal:system',
'icon' => 'conf_ecommerce',
'label' => 'la_title_In-Commerce',
'use_parent_header' => 1,
'url' => Array ('t' => 'index', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array ('view'),
'priority' => 3.1,
'container' => true,
'type' => stTREE,
),
'in-commerce:general' => Array (
'parent' => 'in-commerce:setting_folder',
'icon' => 'conf_ecommerce_general',
'label' => 'la_tab_GeneralSettings',
'url' => Array ('t' => 'config/config_general', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array ('view', 'edit'),
'priority' => 1,
'type' => stTREE,
),
'in-commerce:output' => Array (
'parent' => 'in-commerce:setting_folder',
'icon' => 'core:conf_output',
'label' => 'la_tab_ConfigOutput',
'url' => Array ('t' => 'config/config_universal', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array ('view', 'edit'),
'priority' => 2,
'type' => stTREE,
),
'in-commerce:search' => Array (
'parent' => 'in-commerce:setting_folder',
'icon' => 'core:conf_search',
'label' => 'la_tab_ConfigSearch',
'url' => Array ('t' => 'config/config_search', 'module_key' => 'products', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array ('view', 'edit'),
'priority' => 7,
'type' => stTREE,
),
'in-commerce:configuration_custom' => Array (
'parent' => 'in-commerce:setting_folder',
'icon' => 'core:conf_customfields',
'label' => 'la_tab_ConfigCustom',
'url' => Array ('t' => 'custom_fields/custom_fields_list', 'cf_type' => 11, 'pass_section' => true, 'pass' => 'm,cf'),
'permissions' => Array ('view', 'add', 'edit', 'delete'),
'priority' => 8,
'type' => stTREE,
),
'in-commerce:contacts' => Array (
'parent' => 'in-commerce:setting_folder',
'icon' => 'conf_contact_info',
'label' => 'la_tab_ConfigContacts',
'url' => Array ('t' => 'config/config_universal', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array ('view', 'edit'),
'priority' => 10,
'type' => stTREE,
),
),
'FilterMenu' => Array (
'Groups' => Array (
Array ('mode' => 'AND', 'filters' => Array ('show_new'), 'type' => kDBList::HAVING_FILTER),
Array ('mode' => 'AND', 'filters' => Array ('show_hot'), 'type' => kDBList::HAVING_FILTER),
Array ('mode' => 'AND', 'filters' => Array ('show_pop'), 'type' => kDBList::HAVING_FILTER),
Array ('mode' => 'AND', 'filters' => Array ('show_pick'), 'type' => kDBList::WHERE_FILTER),
),
'Filters' => Array (
'show_new' => Array ('label' => 'la_Text_New', 'on_sql' => '', 'off_sql' => '`IsNew` != 1' ),
'show_hot' => Array ('label' => 'la_Text_TopSellers', 'on_sql' => '', 'off_sql' => '`IsHot` != 1' ),
'show_pop' => Array ('label' => 'la_Text_Pop', 'on_sql' => '', 'off_sql' => '`IsPop` != 1' ),
'show_pick' => Array ('label' => 'la_prompt_EditorsPick', 'on_sql' => '', 'off_sql' => '%1$s.`EditorsPick` != 1' ),
)
),
'TableName' => TABLE_PREFIX . 'Products',
'CustomDataTableName' => TABLE_PREFIX . 'ProductsCustomData',
'CalculatedFields' => Array (
'' => Array (
'AltName' => 'img.AltName',
'SameImages' => 'img.SameImages',
'LocalThumb' => 'img.LocalThumb',
'ThumbPath' => 'img.ThumbPath',
'ThumbUrl' => 'img.ThumbUrl',
'LocalImage' => 'img.LocalImage',
'LocalPath' => 'img.LocalPath',
'FullUrl' => 'img.Url',
'Price' => 'COALESCE(pricing.Price, 0)',
'Cost' => 'COALESCE(pricing.Cost, 0)',
'PrimaryCat' => TABLE_PREFIX.'%3$sCategoryItems.PrimaryCat',
'CategoryId' => TABLE_PREFIX.'%3$sCategoryItems.CategoryId',
'ParentPath' => TABLE_PREFIX.'Categories.ParentPath',
'Manufacturer' => TABLE_PREFIX.'Manufacturers.Name',
'Filename' => TABLE_PREFIX.'%3$sCategoryItems.Filename',
'CategoryFilename' => TABLE_PREFIX.'Categories.NamedParentPath',
'FileSize' => 'files.Size',
'FilePath' => 'files.FilePath',
'FileVersion' => 'files.Version',
),
'showall' => Array (
'Price' => 'COALESCE(pricing.Price, 0)',
'Manufacturer' => TABLE_PREFIX.'Manufacturers.Name',
'PrimaryCat' => TABLE_PREFIX.'%3$sCategoryItems.PrimaryCat',
'CategoryId' => TABLE_PREFIX.'%3$sCategoryItems.CategoryId',
'FileSize' => 'files.Size',
'FilePath' => 'files.FilePath',
'FileVersion' => 'files.Version',
'Filename' => TABLE_PREFIX.'%3$sCategoryItems.Filename',
'CategoryFilename' => TABLE_PREFIX.'Categories.NamedParentPath',
),
),
'CacheModRewrite' => true,
'ListSQLs' => Array (
'' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'UserGroups ON '.TABLE_PREFIX.'UserGroups.GroupId = %1$s.AccessGroupId
LEFT JOIN '.TABLE_PREFIX.'%3$sCategoryItems ON '.TABLE_PREFIX.'%3$sCategoryItems.ItemResourceId = %1$s.ResourceId
LEFT JOIN '.TABLE_PREFIX.'Categories ON '.TABLE_PREFIX.'Categories.CategoryId = '.TABLE_PREFIX.'%3$sCategoryItems.CategoryId
LEFT JOIN '.TABLE_PREFIX.'%3$sCatalogImages img ON img.ResourceId = %1$s.ResourceId AND img.DefaultImg = 1
LEFT JOIN '.TABLE_PREFIX.'%3$sProductFiles files ON files.ProductId = %1$s.ProductId AND files.IsPrimary = 1
LEFT JOIN '.TABLE_PREFIX.'%3$sProductsPricing pricing ON pricing.ProductId = %1$s.ProductId AND pricing.IsPrimary = 1
LEFT JOIN '.TABLE_PREFIX.'Manufacturers ON '.TABLE_PREFIX.'Manufacturers.ManufacturerId = %1$s.ManufacturerId
LEFT JOIN '.TABLE_PREFIX.'CategoryPermissionsCache perm ON perm.CategoryId = '.TABLE_PREFIX.'%3$sCategoryItems.CategoryId
LEFT JOIN '.TABLE_PREFIX.'%3$sProductsCustomData cust ON %1$s.ResourceId = cust.ResourceId',
'showall' => 'SELECT %1$s.* %2$s FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'%3$sProductsPricing pricing ON pricing.ProductId = %1$s.ProductId AND pricing.IsPrimary = 1
LEFT JOIN '.TABLE_PREFIX.'%3$sProductFiles files ON files.ProductId = %1$s.ProductId AND files.IsPrimary = 1
LEFT JOIN '.TABLE_PREFIX.'Manufacturers ON '.TABLE_PREFIX.'Manufacturers.ManufacturerId = %1$s.ManufacturerId
LEFT JOIN '.TABLE_PREFIX.'%3$sCategoryItems ON '.TABLE_PREFIX.'%3$sCategoryItems.ItemResourceId = %1$s.ResourceId
LEFT JOIN '.TABLE_PREFIX.'Categories ON '.TABLE_PREFIX.'Categories.CategoryId = '.TABLE_PREFIX.'%3$sCategoryItems.CategoryId
LEFT JOIN '.TABLE_PREFIX.'CategoryPermissionsCache perm ON perm.CategoryId = '.TABLE_PREFIX.'%3$sCategoryItems.CategoryId
LEFT JOIN '.TABLE_PREFIX.'%3$sProductsCustomData cust ON %1$s.ResourceId = cust.ResourceId',
), // key - special, value - list select sql
'ListSortings' => Array (
'' => Array (
'ForcedSorting' => Array ('EditorsPick' => 'desc', 'Priority' => 'desc'),
'Sorting' => Array ('Name' => 'asc'),
)
),
'ItemSQLs' => Array ( '' => ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'UserGroups pg ON pg.GroupId = %1$s.AccessGroupId
LEFT JOIN '.TABLE_PREFIX.'%3$sCategoryItems ON '.TABLE_PREFIX.'%3$sCategoryItems.ItemResourceId = %1$s.ResourceId
LEFT JOIN '.TABLE_PREFIX.'Categories ON '.TABLE_PREFIX.'Categories.CategoryId = '.TABLE_PREFIX.'%3$sCategoryItems.CategoryId
LEFT JOIN '.TABLE_PREFIX.'%3$sCatalogImages img ON img.ResourceId = %1$s.ResourceId AND img.DefaultImg = 1
LEFT JOIN '.TABLE_PREFIX.'%3$sProductFiles files ON files.ProductId = %1$s.ProductId AND files.IsPrimary = 1
LEFT JOIN '.TABLE_PREFIX.'%3$sProductsPricing pricing ON pricing.ProductId = %1$s.ProductId AND pricing.IsPrimary = 1
LEFT JOIN '.TABLE_PREFIX.'Manufacturers ON '.TABLE_PREFIX.'Manufacturers.ManufacturerId = %1$s.ManufacturerId
LEFT JOIN '.TABLE_PREFIX.'%3$sProductsCustomData cust ON %1$s.ResourceId = cust.ResourceId',
),
'SubItems' => Array ('pr', 'rev', 'img', 'po', 'poc', 'p-ci', 'rel', 'file', 'p-cdata', 'p-fav'),
'Fields' => Array (
'ProductId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0,),
'Name' => Array ('type' => 'string', 'formatter' => 'kMultiLanguage', 'required' => 1, 'max_len' =>255, 'default' => ''),
'AutomaticFilename' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'),
'use_phrases' => 1, 'not_null' => 1, 'default' => 1,
),
'SKU' => Array ('type' => 'string', 'required' => 1, 'max_len' =>255, 'error_msgs' => Array ('required' => 'Please fill in'), 'default' => NULL),
'Description' => Array ('type' => 'string', 'formatter' => 'kMultiLanguage', 'using_fck' => 1, 'default' => NULL),
'DescriptionExcerpt' => Array ('type' => 'string', 'formatter' => 'kMultiLanguage', 'using_fck' => 1, 'default' => NULL),
'Weight' => Array ('type' => 'float', 'min_value_exc' => 0, 'formatter' => 'kUnitFormatter', 'format' => '%0.2f', 'default' => NULL),
'MSRP' => Array ('type' => 'float', 'min_value_inc' => 0, 'formatter' => 'kFormatter', 'format' => '%0.2f', 'default' => NULL),
'ManufacturerId' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'Manufacturers ORDER BY Name', 'option_key_field' => 'ManufacturerId', 'option_title_field' => 'Name', 'not_null' => 1, 'default' => 0),
'Status' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'la_Active', 2 => 'la_Pending', 0 => 'la_Disabled'), 'use_phrases' => 1,
'default' => 2, 'not_null' => 1,
),
'BackOrder' => Array ('type' => 'int', 'not_null' => 1, 'options' => Array ( 2 => 'la_Auto', 1 => 'la_Always', 0 => 'la_Never' ), 'use_phrases' => 1, 'default' => 2 ),
'BackOrderDate' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'error_msgs' => Array ('bad_date_format' => 'Please use the following date format: %s'), 'default' => NULL),
'NewItem' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array ( 2 => 'la_Auto', 1 => 'la_Always', 0 => 'la_Never' ), 'use_phrases' => 1, 'not_null' => 1, 'default' => 2 ),
'HotItem' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array ( 2 => 'la_Auto', 1 => 'la_Always', 0 => 'la_Never' ), 'use_phrases' => 1, 'not_null' => 1, 'default' => 2 ),
'PopItem' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array ( 2 => 'la_Auto', 1 => 'la_Always', 0 => 'la_Never' ), 'use_phrases' => 1, 'not_null' => 1, 'default' => 2 ),
'EditorsPick' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1,
'not_null' => 1, 'default' => 0,
),
'Featured' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1,
'not_null' => 1, 'default' => 0,
),
'OnSale' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1,
'not_null' => 1, 'default' => 0,
),
'Priority' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'CachedRating' => Array ('type' => 'string', 'not_null' => 1, 'formatter' => 'kFormatter', 'default' => 0),
'CachedVotesQty' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'Hits' => Array ('type' => 'double', 'formatter' => 'kFormatter', 'format' => '%d', 'not_null' => 1, 'default' => 0),
'CreatedOn' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => '#NOW#'),
'Expire' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' =>null),
'Type' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter', 'use_phrases' => 1,
'options' => Array (
PRODUCT_TYPE_TANGIBLE => 'la_product_tangible',
PRODUCT_TYPE_SUBSCRIPTION => 'la_product_subscription',
PRODUCT_TYPE_SERVICE => 'la_product_service',
PRODUCT_TYPE_DOWNLOADABLE => 'la_product_downloadable',
/* PRODUCT_TYPE_PACKAGE => 'la_product_package', */
),
'not_null' => 1, 'default' => 1,
),
'Modified' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => '#NOW#'),
'ModifiedById' => Array ('type' => 'int', 'default' => NULL),
'CreatedById' => Array (
'type' => 'int',
'formatter' => 'kLEFTFormatter',
'options' => Array (USER_ROOT => 'root', USER_GUEST => 'Guest'),
'left_sql' => 'SELECT %s FROM ' . TABLE_PREFIX . 'Users
WHERE `%s` = \'%s\'',
'left_key_field' => 'PortalUserId',
'left_title_field' => 'Username',
'error_msgs' => Array ('invalid_option' => '!la_error_UserNotFound!'),
'sample_value' => 'Guest', 'required' => 1, 'default' => NULL,
),
'ResourceId' => Array ('type' => 'int', 'default' => null),
'CachedReviewsQty' => Array ('type' => 'int', 'formatter' => 'kFormatter', 'format' => '%d', 'not_null' => 1, 'default' => 0),
'InventoryStatus' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (0 => 'la_Disabled', 1 => 'la_by_product', 2 => 'la_by_options'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 0),
'QtyInStock' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'QtyInStockMin' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'QtyReserved' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'QtyBackOrdered' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'QtyOnOrder' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'InventoryComment' => Array ('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => null),
'Qty' => Array ('type' => 'int', 'formatter' => 'kFormatter', 'regexp' => '/^[\d]+$/', 'error_msgs' => Array ('invalid_format' => '!la_invalid_integer!')),
'AccessGroupId' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'UserGroups WHERE System!=1 AND Personal !=1 ORDER BY Name', 'option_key_field' => 'GroupId', 'option_title_field' => 'Name', 'default' => NULL),
'AccessDuration' => Array ('type' => 'int', 'default' => NULL),
'AccessDurationType' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'use_phrases' => 1, 'options' =>Array (1 => 'la_opt_sec', 2 => 'la_opt_min', 3 => 'la_opt_hour', 4 => 'la_opt_day', 5 => 'la_opt_week', 6 => 'la_opt_month', 7 => 'la_opt_year' ), 'default' => NULL,),
'AccessStart' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => NULL),
'AccessEnd' => Array ('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => NULL,),
'OptionsSelectionMode' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'use_phrases' => 1, 'options' =>Array (0 => 'la_opt_Selection', 1 => 'la_opt_List'), 'default' => 0),
'HasRequiredOptions' => Array ('type' => 'int', 'default' => 0, 'not_null' => 1),
'Virtual' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'ProcessingData' => Array ('type' => 'string', 'default' => ''),
'PackageContent' => Array ('type' => 'string', 'default' => NULL),
'IsRecurringBilling' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'),
'use_phrases' => 1, 'not_null' => 1, 'default' => 0,
),
//'PayPalRecurring' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1, 'not_null' => '1', 'default' => '0'),
'ShippingMode' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'use_phrases' => 1, 'options' =>Array (0 => 'la_shipping_AnyAndSelected', 1 => 'la_shipping_Limited'), 'not_null' => 1, 'default' =>0),
'ProcessingData' => Array ('type' => 'string', 'default' => null),
'ShippingLimitation' => Array ('type' => 'string', 'default' => NULL),
'AssignedCoupon' =>
Array ('type' => 'int', 'not_null' => 1, 'default' => 0,
'formatter' => 'kLEFTFormatter',
'options' => Array (0 => 'None'),
'left_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'ProductsCoupons WHERE `%s` = \'%s\'',
'left_key_field' => 'CouponId',
'left_title_field' => 'Name'),
'MinQtyFreePromoShipping' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
'MetaKeywords' => Array ('type' => 'string', 'default' => null),
'MetaDescription' => Array ('type' => 'string', 'formatter' => 'kFormatter', 'using_fck' => 1, 'default' => null),
),
'VirtualFields' => Array (
'Qty' => Array ('type' => 'int', 'formatter' => 'kFormatter', 'regexp' => '/^[\d]+$/', 'default' => 0),
'Price' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => NULL),
'Cost' => Array ('type' => 'float', 'formatter' => 'kFormatter', 'format' => '%.2f', 'default' => NULL),
'CategoryFilename' => Array ('type' => 'string', 'default' => ''),
'PrimaryCat' => Array ('type' => 'int', 'default' => 0),
'IsHot' => Array ('type' => 'int', 'default' => 0),
'IsNew' => Array ('type' => 'int', 'default' => 0),
'IsPop' => Array ('type' => 'int', 'default' => 0),
'Manufacturer' => Array ('type' => 'string', 'default' => ''),
// export related fields: begin
'CategoryId' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (), 'default' => 0),
'ExportFormat' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'CSV', /*2 => 'XML'*/), 'default' => 1),
'ExportFilename' => Array ('type' => 'string', 'default' => ''),
'FieldsSeparatedBy' => Array ('type' => 'string', 'default' => ','),
'FieldsEnclosedBy' => Array ('type' => 'string', 'default' => '"'),
'LineEndings' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'Windows', 2 => 'UNIX'), 'default' => 1),
'LineEndingsInside' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'CRLF', 2 => 'LF'), 'default' => 2),
'IncludeFieldTitles' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'),
'use_phrases' => 1, 'default' => 1,
),
'ExportColumns' => Array ('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array (), 'default' => ''),
'AvailableColumns' => Array ('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array (), 'default' => ''),
'CategoryFormat' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_MixedCategoryPath', 2 => 'la_SeparatedCategoryPath'), 'use_phrases' => 1, 'default' => 1),
'CategorySeparator' => Array ('type' => 'string', 'default' => ':'),
'IsBaseCategory' => Array (
'type' => 'int',
'formatter' => 'kOptionsFormatter',
'options' => Array (0 => 'la_No', 1 => 'la_Yes'),
'use_phrases' => 1, 'default' => 0,
),
// export related fields: end
// import related fields: begin
'FieldTitles' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Automatic', 2 => 'la_Manual'), 'use_phrases' => 1, 'default' => 1),
'ImportSource' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Upload', 2 => 'la_Local'), 'use_phrases' => 1, 'default' => 2),
'ImportFilename' => Array ('type' => 'string', 'formatter' => 'kUploadFormatter', 'max_size' => MAX_UPLOAD_SIZE, 'upload_dir' => EXPORT_BASE_PATH . '/', 'default' => ''),
'ImportLocalFilename' => Array ('type' => 'string', 'formatter' => 'kOptionsFormatter', 'default' => ''),
'CheckDuplicatesMethod' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_IDField', 2 => 'la_OtherFields'), 'use_phrases' => 1, 'default' => 1),
'ReplaceDuplicates' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (0 => 'la_No', 1 => 'la_Yes'), 'use_phrases' => 1, 'default' => 0),
'DuplicateCheckFields' => Array ('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array ('Name' => 'NAME'), 'default' => '|Name|'),
'SkipFirstRow' => Array ('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1, 'default' => 1),
// import related fields: end
'ThumbnailImage' => Array ('type' => 'string', 'default' => ''),
'FullImage' => Array ('type' => 'string', 'default' => ''),
'ImageAlt' => Array ('type' => 'string', 'default' => ''),
'Filename' => Array ('type' => 'string', 'default' => ''),
'CachedNavbar' => Array ('type' => 'string', 'default' => ''),
'ParentPath' => Array ('type' => 'string', 'default' => ''),
'FileSize' => Array ('type' => 'int', 'formatter' => 'kFilesizeFormatter', 'default' => 0),
'FilePath' => Array ('type' => 'string', 'default' => ''),
'FileVersion' => Array ('type' => 'string', 'default' => ''),
// for primary image
'AltName' => Array ('type' => 'string', 'default' => ''),
'SameImages' => Array ('type' => 'string', 'default' => ''),
'LocalThumb' => Array ('type' => 'string', 'default' => ''),
'ThumbPath' => Array ('type' => 'string', 'default' => ''),
'ThumbUrl' => Array ('type' => 'string', 'default' => ''),
'LocalImage' => Array ('type' => 'string', 'default' => ''),
'LocalPath' => Array ('type' => 'string', 'default' => ''),
'FullUrl' => Array ('type' => 'string', 'default' => ''),
),
'Grids' => Array (
'Default' => Array (
'Icons' => Array (
'default' => 'icon16_product.png',
0 => 'icon16_product_disabled.png',
1 => 'icon16_product.png',
2 => 'icon16_product_pending.png',
'NEW' => 'icon16_product_new.png',
),
'Fields' => Array (
'ProductId' => Array ( 'title' => 'column:la_fld_Id', 'data_block' => 'grid_checkbox_td', 'filter_block' => 'grid_range_filter', 'width' => 60, ),
'SKU' => Array ( 'title' => 'la_col_ProductSKU', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'Name' => Array ( 'title' => 'la_col_ProductName', 'data_block' => 'grid_catitem_td', 'filter_block' => 'grid_like_filter', 'width' => 150, ),
'Priority' => Array('filter_block' => 'grid_range_filter', 'width' => 65),
'Type' => Array ('title' => 'column:la_fld_ProductType', 'filter_block' => 'grid_options_filter', 'width' => 80, ),
'Manufacturer' => Array ('filter_block' => 'grid_like_filter', 'width' => 100, ),
'Price' => Array ('filter_block' => 'grid_range_filter', 'width' => 70, ),
'Status' => Array ('filter_block' => 'grid_options_filter', 'width' => 70, ),
'QtyInStock' => Array ('title' => 'column:la_fld_Qty', 'data_block' => 'qty_td', 'filter_block' => 'grid_range_filter', 'width' => 80, ),
'QtyBackOrdered' => Array ('title' => 'column:la_fld_QtyBackOrdered', 'filter_block' => 'grid_range_filter', 'width' => 80, ),
'OnSale' => Array ('title' => 'column:la_fld_OnSale', 'filter_block' => 'grid_options_filter', 'width' => 70, ),
/*'Weight' => Array ( 'title' => 'la_col_ProductWeight', 'filter_block' => 'grid_range_filter', 'width' => 150, ),
'CreatedOn' => Array ( 'title' => 'la_col_ProductCreatedOn', 'filter_block' => 'grid_date_range_filter', 'width' => 150, ),
'BackOrderDate' => Array ( 'title' => 'la_col_ProductBackOrderDate', 'filter_block' => 'grid_date_range_filter', 'width' => 150, ),*/
),
),
'Radio' => Array (
'Icons' => Array (
'default' => 'icon16_product.png',
0 => 'icon16_product_disabled.png',
1 => 'icon16_product.png',
2 => 'icon16_product_pending.png',
'NEW' => 'icon16_product_new.png',
),
'Selector' => 'radio',
'Fields' => Array (
'ProductId' => Array ( 'title' => 'column:la_fld_Id', 'data_block' => 'grid_radio_td', 'filter_block' => 'grid_range_filter', 'width' => 60, ),
'SKU' => Array ( 'title' => 'la_col_ProductSKU', 'filter_block' => 'grid_like_filter', 'width' => 100, ),
'Name' => Array ( 'title' => 'la_col_ProductName', 'data_block' => 'grid_catitem_td', 'filter_block' => 'grid_like_filter', 'width' => 150, ),
'Priority' => Array('filter_block' => 'grid_range_filter', 'width' => 65),
'Type' => Array ('title' => 'column:la_fld_ProductType', 'filter_block' => 'grid_options_filter', 'width' => 80, ),
'Manufacturer' => Array ('filter_block' => 'grid_like_filter', 'width' => 100, ),
'Price' => Array ('filter_block' => 'grid_range_filter', 'width' => 70, ),
'Status' => Array ('filter_block' => 'grid_options_filter', 'width' => 70, ),
'QtyInStock' => Array ('title' => 'column:la_fld_Qty', 'data_block' => 'qty_td', 'filter_block' => 'grid_range_filter', 'width' => 80, ),
'QtyBackOrdered' => Array ('title' => 'column:la_fld_QtyBackOrdered', 'filter_block' => 'grid_range_filter', 'width' => 80, ),
),
),
),
'ConfigMapping' => Array (
'PerPage' => 'Comm_Perpage_Products',
'ShortListPerPage' => 'Comm_Perpage_Products_Short',
'ForceEditorPick' => 'products_EditorPicksAboveRegular',
'DefaultSorting1Field' => 'product_OrderProductsBy',
'DefaultSorting2Field' => 'product_OrderProductsThenBy',
'DefaultSorting1Dir' => 'product_OrderProductsByDir',
'DefaultSorting2Dir' => 'product_OrderProductsThenByDir',
'RatingDelayValue' => 'product_RatingDelay_Value',
'RatingDelayInterval' => 'product_RatingDelay_Interval',
),
);
Index: branches/5.2.x/units/coupon_items/coupon_items_event_handler.php
===================================================================
--- branches/5.2.x/units/coupon_items/coupon_items_event_handler.php (revision 15133)
+++ branches/5.2.x/units/coupon_items/coupon_items_event_handler.php (revision 15134)
@@ -1,111 +1,111 @@
<?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 CouponItemsEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnEntireOrder' => Array ('subitem' => 'add|edit'),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Adds products from selected categories and their sub-categories and directly selected products to coupon items with duplicate checking
*
* @param kEvent $event
*/
- function OnProcessSelected(&$event)
+ function OnProcessSelected($event)
{
// uses another handler event, because does the same stuff but on different table
$di_handler =& $this->Application->recallObject('di_EventHandler');
$di_handler->OnProcessSelected($event);
}
/**
* Allows to set discount on entire order
*
* @param kEvent $event
* @todo get parent item id through $object->getLinkedInfo()['ParentId']
* @access public
*/
- function OnEntireOrder(&$event)
+ function OnEntireOrder($event)
{
$object =& $event->GetObject();
$sql = 'DELETE FROM '.$object->TableName.' WHERE CouponId='.$this->Application->GetVar('coup_id');
$this->Conn->Query($sql);
$object->SetDBField('CouponId', $this->Application->GetVar('coup_id'));
$object->SetDBField('ItemResourceId', -1);
$object->SetDBField('ItemType', 0);
if ( $object->Create() ) {
$this->customProcessing($event, 'after');
$event->status = kEvent::erSUCCESS;
$event->SetRedirectParam('opener', 's'); //stay!
}
else {
$event->status = kEvent::erFAIL;
$this->Application->SetVar($event->getPrefixSpecial().'_SaveEvent','OnCreate');
$object->setID(0);
}
}
/**
* Deletes discount items where hooked item (product) is used
*
* @param kEvent $event
*/
- function OnDeleteCouponItem(&$event)
+ function OnDeleteCouponItem($event)
{
$main_object =& $event->MasterEvent->getObject();
$resource_id = $main_object->GetDBField('ResourceId');
$table = $this->Application->getUnitOption($event->Prefix,'TableName');
$sql = 'DELETE FROM '.$table.' WHERE ItemResourceId = '.$resource_id;
$this->Conn->Query($sql);
}
/**
* Makes ItemName calculated field from primary language
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $event)
{
parent::OnAfterConfigRead($event);
$calculated_fields = $this->Application->getUnitOption($event->Prefix, 'CalculatedFields');
$language_id = $this->Application->GetVar('m_lang');
$primary_language_id = $this->Application->GetDefaultLanguageId();
$calculated_fields['']['ItemName'] = 'COALESCE(p.l' . $language_id . '_Name, p.l' . $primary_language_id . '_Name)';
$this->Application->setUnitOption($event->Prefix, 'CalculatedFields', $calculated_fields);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/affiliates/affiliates_event_handler.php
===================================================================
--- branches/5.2.x/units/affiliates/affiliates_event_handler.php (revision 15133)
+++ branches/5.2.x/units/affiliates/affiliates_event_handler.php (revision 15134)
@@ -1,659 +1,663 @@
<?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 AffiliatesEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnItemBuild' => Array ('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* Checks user permission to execute given $event
*
* @param kEvent $event
* @return bool
* @access public
*/
- public function CheckPermission(kEvent &$event)
+ public function CheckPermission(kEvent $event)
{
if ( $event->Name == 'OnBecomeAffiliate' || $event->Name == 'OnChangePaymentType' ) {
return $this->Application->LoggedIn() && $this->Application->ConfigValue('Comm_RegisterAsAffiliate');
}
return parent::CheckPermission($event);
}
/**
* Allows to get ID of affiliate record, associated with currently logged-in user
*
* @param kEvent $event
* @return int
* @access public
*/
- public function getPassedID(kEvent &$event)
+ public function getPassedID(kEvent $event)
{
if ( $event->Special == 'user' ) {
$event->setEventParam('raise_warnings', 0);
$sql = 'SELECT ' . $this->Application->getUnitOption($event->Prefix, 'IDField') . '
FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
WHERE PortalUserId = ' . (int)$this->Application->RecallVar('user_id');
$id = $this->Conn->GetOne($sql);
if ( $id ) {
return $id;
}
}
return parent::getPassedID($event);
}
/**
* Generate new affiliate code
*
* @param kEvent $event
* @return string
*/
- function generateAffiliateCode(&$event)
+ function generateAffiliateCode($event)
{
// accepts 1 - 36
$number_length = 11;
$num_chars = Array( '1'=>'a','2'=>'b','3'=>'c','4'=>'d','5'=>'e','6'=>'f',
'7'=>'g','8'=>'h','9'=>'i','10'=>'j','11'=>'k','12'=>'l',
'13'=>'m','14'=>'n','15'=>'o','16'=>'p','17'=>'q','18'=>'r',
'19'=>'s','20'=>'t','21'=>'u','22'=>'v','23'=>'w','24'=>'x',
'25'=>'y','26'=>'z','27'=>'0','28'=>'1','29'=>'2','30'=>'3',
'31'=>'4','32'=>'5','33'=>'6','34'=>'7','35'=>'8','36'=>'9');
$ret = '';
for($i=1; $i<=$number_length; $i++)
{
mt_srand((double)microtime() * 1000000);
$num = mt_rand(1,36);
$ret .= $num_chars[$num];
}
$ret = strtoupper($ret);
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$sql = 'SELECT %s FROM %s WHERE AffiliateCode = %s';
$code_found = $this->Conn->GetOne( sprintf($sql, $id_field, $table, $this->Conn->qstr($ret) ) );
if($code_found) return $this->generateAffiliateCode($event);
return $ret;
}
/**
* Creates new affiliate code when new affiliate is created
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('AffiliateCode', $this->generateAffiliateCode($event));
if ( $object->getFormName() == 'registration' ) {
if ( $this->Application->LoggedIn() ) {
$object->SetDBField('PortalUserId', $this->Application->RecallVar('user_id'));
}
$object->SetDBField('AffiliatePlanId', $this->_getPrimaryAffiliatePlan());
}
}
/**
* Ensures, that user can only update his affiliate record
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
if ( !$this->Application->isAdmin ) {
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('PortalUserId', $object->GetOriginalField('PortalUserId'));
if ( $object->GetDBField('PortalUserId') != $this->Application->RecallVar('user_id') ) {
$object->SetError('PortalUserId', 'not_owner');
}
}
}
/**
* [HOOK] Stores affiliate id using method from Config (session or cookie) if correct code is present in url
*
* @param kEvent $event
* @return bool
*/
- function OnStoreAffiliate(&$event)
+ function OnStoreAffiliate($event)
{
+ if ( defined('IS_INSTALL') && IS_INSTALL ) {
+ return;
+ }
+
$object =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true));
/* @var $object kDBItem */
$affiliate_storage_method = $this->Application->ConfigValue('Comm_AffiliateStorageMethod');
$affiliate = $this->Application->GetVar('affiliate');
if ( $affiliate ) {
$object->Load($affiliate, 'AffiliateCode');
}
elseif ( $affiliate_storage_method == 2 ) {
$affiliate_id = $this->Application->GetVar('affiliate_id');
$object->Load($affiliate_id);
}
if ( $object->isLoaded() && ($object->GetDBField('Status') == 1) ) {
// user is found with such email
$affiliate_user =& $this->Application->recallObject('u.affiliate', null, Array ('skip_autoload' => true));
/* @var $affiliate_user UsersItem */
$affiliate_user->Load($object->GetDBField('PortalUserId'));
if ( $affiliate_user->GetDBField('Status') == 1 ) {
$affiliate_id = $object->GetDBField('AffiliateId');
$this->Application->setVisitField('AffiliateId', $affiliate_id);
if ( $affiliate_storage_method == 1 ) {
$this->Application->StoreVar('affiliate_id', $affiliate_id); // per session
}
else {
// in cookie
$this->Application->Session->SetCookie('affiliate_id', $affiliate_id, $this->getCookieExpiration());
}
}
}
}
/**
* Returns affiliate cookie expiration date
*
* @return int
*/
function getCookieExpiration()
{
$expire = $this->Application->ConfigValue('Comm_AffiliateCookieDuration'); // days
return adodb_mktime() + $expire * 24 * 60 * 60;
}
/**
* Calculate what amount is earned by affiliate based on it's affiliate plan & store it
*
* @param kEvent $event
* @author Alex
*/
- function OnOrderApprove(&$event)
+ function OnOrderApprove($event)
{
$order =& $this->Application->recallObject($event->getEventParam('Order_PrefixSpecial'));
/* @var $order OrdersItem */
$affiliate_id = $order->GetDBField('AffiliateId');
if ( !$affiliate_id ) {
return false;
}
$object =& $event->getObject(Array ('ship_autoload' => true));
/* @var $object kDBItem */
if ( $object->Load($affiliate_id) ) {
$affiliate_plan =& $this->Application->recallObject('ap', null, Array ('skip_autoload' => true));
/* @var $affiliate_plan kDBItem */
$affiliate_plan->Load($object->GetDBField('AffiliatePlanId'));
if ( $affiliate_plan->isLoaded() ) {
$sql = 'SELECT SUM(Quantity) FROM %s WHERE OrderId = %s';
$orderitems_table = $this->Application->getUnitOption('orditems', 'TableName');
$items_sold = $this->Conn->GetOne(sprintf($sql, $orderitems_table, $order->GetID()));
$object->SetDBField('AccumulatedAmount', $object->GetDBField('AccumulatedAmount') + $order->GetDBField('TotalAmount'));
$object->SetDBField('ItemsSold', $object->GetDBField('ItemsSold') + $items_sold);
switch ($affiliate_plan->GetDBField('PlanType')) {
case 1: // by amount
$value = $object->GetDBField('AccumulatedAmount');
break;
case 2: // by items sold (count)
$value = $object->GetDBField('ItemsSold');
break;
}
$apb_table = $this->Application->getUnitOption('apbrackets', 'TableName');
$sql = 'SELECT Percent FROM %1$s WHERE (%2$s >= FromAmount) AND ( (%2$s <= ToAmount) OR (ToAmount = -1) ) AND (AffiliatePlanId = %3$s)';
$commission_percent = $this->Conn->GetOne(sprintf($sql, $apb_table, $this->Conn->qstr($value), $affiliate_plan->GetID()));
// process only orders of current affiliate from period start to this order date
$period_ends = $order->GetDBField('OrderDate');
$period_starts = $this->getPeriodStartTS($period_ends, $affiliate_plan->GetDBField('ResetInterval'));
$sql = 'SELECT AffiliateCommission, (SubTotal+ShippingCost+VAT) AS TotalAmount, OrderId
FROM ' . $order->TableName . '
WHERE OrderDate >= %s AND OrderDate <= %s AND AffiliateId = ' . $affiliate_id;
$amount_to_pay_before = 0;
$amount_to_pay_after = 0;
$order_update_sql = 'UPDATE ' . $order->TableName . ' SET AffiliateCommission = %s WHERE ' . $order->IDField . ' = %s';
$orders = $this->Conn->Query(sprintf($sql, $period_starts, $period_ends), 'OrderId');
if ( $orders ) {
foreach ($orders as $order_id => $order_data) {
$amount_to_pay_before += $order_data['AffiliateCommission'];
$commission = $order_data['TotalAmount'] * ($commission_percent / 100);
$this->Conn->Query(sprintf($order_update_sql, $this->Conn->qstr($commission), $order_id));
$amount_to_pay_after += $commission;
}
}
$object->SetDBField('AmountToPay', $object->GetDBField('AmountToPay') - $amount_to_pay_before + $amount_to_pay_after);
$object->SetDBField('LastOrderDate_date', $order->GetDBField('OrderDate_date'));
$object->SetDBField('LastOrderDate_time', $order->GetDBField('OrderDate_time'));
$object->Update();
$order->SetDBField('AffiliateCommission', $commission); // set last commission to this order, because ApproveEvent was called for him
}
}
}
/**
* [HOOK] Validates affiliate fields on user registration form
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnValidateAffiliate(&$event)
+ protected function OnValidateAffiliate($event)
{
if ( $this->Application->GetVar('RegisterAsAffiliate') != 'on' || $event->MasterEvent->status != kEvent::erSUCCESS ) {
return;
}
$object =& $event->getObject( Array('form_name' => 'registration', 'skip_autoload' => true) );
/* @var $object kDBItem */
$field_values = $this->getSubmittedFields($event);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
$object->setID(0);
if ( !$object->Validate() ) {
$user =& $event->MasterEvent->getObject();
/* @var $user kDBItem */
$user->Validate();
$event->MasterEvent->status = kEvent::erFAIL;
}
}
/**
* [AFTER HOOK] to u:OnCreate
*
* @param kEvent $event
*/
- function OnRegisterAffiliate(&$event)
+ function OnRegisterAffiliate($event)
{
if ( $this->Application->GetVar('RegisterAsAffiliate') != 'on' || $event->MasterEvent->status != kEvent::erSUCCESS ) {
return;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$user =& $event->MasterEvent->getObject();
/* @var $user UsersItem */
$object->SetDBField('PortalUserId', $user->GetID());
if ( $object->Create() ) {
$this->Application->EmailEventUser('AFFILIATE.REGISTER', $user->GetID());
$this->Application->EmailEventAdmin('AFFILIATE.REGISTER');
}
}
/**
* Returns primary affiliate plan
*
* @return int
* @access protected
*/
protected function _getPrimaryAffiliatePlan()
{
$sql = 'SELECT AffiliatePlanId
FROM ' . $this->Application->getUnitOption('ap', 'TableName') . '
WHERE IsPrimary = 1';
return (int)$this->Conn->GetOne($sql);
}
/**
* Creates affiliate record for logged-in user
*
* @param kEvent $event
*/
- function OnBecomeAffiliate(&$event)
+ function OnBecomeAffiliate($event)
{
$object =& $event->getObject( Array('form_name' => 'registration', 'skip_autoload' => true) );
/* @var $object UsersItem */
$event->CallSubEvent('OnCreate');
if ( $event->status == kEvent::erSUCCESS ) {
$event->SetRedirectParam('opener', 's');
$next_template = $this->Application->GetVar('next_template');
if ( $next_template ) {
$event->redirect = $next_template;
}
}
}
/**
* Change affiliate payment type of affiliate record associated with logged-in user
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnChangePaymentType(&$event)
+ protected function OnChangePaymentType($event)
{
$event->CallSubEvent('OnUpdate');
if ( $event->status == kEvent::erSUCCESS ) {
$object =& $event->getObject();
/* @var $object kDBItem */
$this->Application->EmailEventUser('AFFILIATE.PAYMENT.TYPE.CHANGED', $object->GetDBField('PortalUserId'));
$this->Application->EmailEventAdmin('AFFILIATE.PAYMENT.TYPE.CHANGED');
$next_template = $this->Application->GetVar('next_template');
if ( $next_template ) {
$event->redirect = $this->Application->GetVar('next_template');
}
$event->SetRedirectParam('opener', 's');
}
}
/**
* If new payments made, then send email about that
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeDeleteFromLive(kEvent &$event)
+ protected function OnBeforeDeleteFromLive(kEvent $event)
{
parent::OnBeforeDeleteFromLive($event);
$payment_object =& $this->Application->recallObject('apayments', 'apayments', Array ('skip_autoload' => true));
/* @var $payment_object kDBItem */
$id = $event->getEventParam('id');
$ap_table = $this->Application->getUnitOption('apayments', 'TableName');
$sql = 'SELECT AffiliatePaymentId
FROM ' . $ap_table . '
WHERE AffiliateId = ' . $id;
$live_ids = $this->Conn->GetCol($sql);
$sql = 'SELECT AffiliatePaymentId
FROM ' . $payment_object->TableName . '
WHERE AffiliateId = ' . $id;
$temp_ids = $this->Conn->GetCol($sql);
$new_ids = array_diff($temp_ids, $live_ids);
foreach ($new_ids as $payment_id) {
$payment_object->Load($payment_id);
$this->Application->EmailEventUser('AFFILIATE.PAYMENT', $payment_object->GetDBField('PortalUserId'));
$this->Application->EmailEventAdmin('AFFILIATE.PAYMENT');
}
$object =& $event->getObject();
/* @var $object kDBItem */
$passed_id = $event->getEventParam('id');
if ( $object->GetID() != $passed_id ) {
$object->Load($passed_id);
}
$sql = 'SELECT Status
FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
WHERE ' . $object->IDField . ' = ' . $object->GetID();
$old_status = $this->Conn->GetOne($sql);
if ( $old_status == 2 && $object->GetDBField('Status') == 1 ) {
$this->Application->EmailEventUser('AFFILIATE.REGISTRATION.APPROVED', $object->GetDBField('PortalUserId'));
$this->Application->EmailEventAdmin('AFFILIATE.REGISTRATION.APPROVED');
}
}
/**
* [HOOK] Resets statistics (accumulated amount & items sold) for affiliates based on ResetInterval in their plan
*
* @param kEvent $event
* @author Alex
*/
- function OnResetStatistics(&$event)
+ function OnResetStatistics($event)
{
if ( defined('IS_INSTALL') && IS_INSTALL ) {
return;
}
$intervals = Array (86400 => 'la_day', 604800 => 'la_week', 2628000 => 'la_month', 7884000 => 'la_quartely', 31536000 => 'la_year');
$affiliates_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$affiliate_plan_table = $this->Application->getUnitOption('ap', 'TableName');
$base_time = adodb_mktime();
$where_clause = Array ();
foreach ($intervals as $interval_length => $interval_description) {
$start_timestamp = $this->getPeriodStartTS($base_time, $interval_length);
$where_clause[] = 'ap.ResetInterval = ' . $interval_length . ' AND LastOrderDate < ' . $start_timestamp;
}
$sql = 'SELECT AffiliateId
FROM ' . $affiliates_table . ' a
LEFT JOIN ' . $affiliate_plan_table . ' ap ON a.AffiliatePlanId = ap.AffiliatePlanId
WHERE (' . implode(') OR (', $where_clause) . ')';
$affiliate_ids = $this->Conn->GetCol($sql);
if ( !$affiliate_ids ) {
return;
}
if ( defined('DEBUG_MODE') && DEBUG_MODE && $this->Application->isDebugMode() ) {
$this->Application->Debugger->appendHTML('Affiliates Pending Totals Reset: ');
$this->Application->Debugger->dumpVars($affiliate_ids);
}
$fields_hash = Array (
'AccumulatedAmount' => 0,
'ItemsSold' => 0,
'LastOrderDate' => $base_time,
);
$this->Conn->doUpdate($fields_hash, $affiliates_table, 'AffiliateId IN (' . implode(',', $affiliate_ids) . ')');
}
/**
* Returns calendar period start timestamp based on current timestamp ($base_time) and $period_length
*
* @param int $base_time
* @param int $period_length
* @return int
* @author Alex
*/
function getPeriodStartTS($base_time, $period_length)
{
$start_timestamp = 0;
switch ($period_length) {
case 86400: // day
$start_timestamp = adodb_mktime(0, 0, 0, adodb_date('m', $base_time), adodb_date('d', $base_time), adodb_date('Y', $base_time));
break;
case 604800: // week
$day_seconds = 86400;
$first_week_day = $this->Application->ConfigValue('FirstDayOfWeek');
$morning = adodb_mktime(0, 0, 0, adodb_date('m', $base_time), adodb_date('d', $base_time), adodb_date('Y', $base_time));
$week_day = adodb_date('w', $morning);
if ( $week_day == $first_week_day ) {
// if it is already first week day, then don't search for previous week day
$day_diff = 0;
}
else {
// this way, because sunday is 0, but not 7 as it should be
$day_diff = $week_day != 0 ? $week_day - $first_week_day : 7 - $first_week_day;
}
$start_timestamp = $morning - $day_diff * $day_seconds;
break;
case 2628000: // month
$start_timestamp = adodb_mktime(0, 0, 0, adodb_date('m', $base_time), 1, adodb_date('Y', $base_time));
break;
case 7884000: // quartal
$first_quartal_month = (ceil(adodb_date('m', $base_time) / 3) - 1) * 3 + 1;
$start_timestamp = adodb_mktime(0, 0, 0, $first_quartal_month, 1, adodb_date('Y', $base_time));
break;
case 31536000:
$start_timestamp = adodb_mktime(0, 0, 0, 1, 1, adodb_date('Y', $base_time));
break;
}
return $start_timestamp;
}
/**
* Apply same processing to each item being selected in grid
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function iterateItems(kEvent &$event)
+ protected function iterateItems(kEvent $event)
{
if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
$event->status = kEvent::erFAIL;
return;
}
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$ids = $this->StoreSelectedIDs($event);
if ( $ids ) {
$status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField'));
foreach ($ids as $id) {
$object->Load($id);
switch ($event->Name) {
case 'OnMassApprove':
$object->SetDBField($status_field, 1);
break;
case 'OnMassDecline':
$object->SetDBField($status_field, 0);
break;
case 'OnMassMoveUp':
$object->SetDBField('Priority', $object->GetDBField('Priority') + 1);
break;
case 'OnMassMoveDown':
$object->SetDBField('Priority', $object->GetDBField('Priority') - 1);
break;
}
if ( $object->Update() ) {
switch ($event->Name) {
case 'OnMassApprove':
$this->Application->EmailEventUser('AFFILIATE.REGISTRATION.APPROVED', $object->GetDBField('PortalUserId'));
$this->Application->EmailEventAdmin('AFFILIATE.REGISTRATION.APPROVED');
break;
case 'OnMassDecline':
$this->Application->EmailEventUser('AFFILIATE.REGISTRATION.DENIED', $object->GetDBField('PortalUserId'));
$this->Application->EmailEventAdmin('AFFILIATE.REGISTRATION.DENIED');
break;
}
$event->status = kEvent::erSUCCESS;
$event->SetRedirectParam('opener', 's'); //stay!
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
* Checks that user in affiliate record matches current user
* (non permission-based)
*
* @param kEvent $event
* @return bool
* @access protected
*/
- protected function checkItemStatus(kEvent &$event)
+ protected function checkItemStatus(kEvent $event)
{
if ( $this->Application->isAdminUser ) {
return true;
}
$object =& $event->getObject();
/* @var $object kDBItem */
if ( !$object->isLoaded() ) {
return true;
}
return $object->GetDBField('PortalUserId') == $this->Application->RecallVar('user_id');
}
}
\ 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 15133)
+++ branches/5.2.x/units/taxesdestinations/taxes_dst_event_handler.php (revision 15134)
@@ -1,173 +1,174 @@
<?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)
+ function OnSaveDestinations($event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
$tax_object =& $this->Application->recallObject('tax');
/* @var $tax_object kDBItem */
$std_dest_id = $this->Application->GetVar('StatesCountry');
if ( $items_info ) {
$taxdest =& $this->Application->recallObject($event->getPrefixSpecial(true), null);
/* @var $taxdest kDBItem */
$parent_info =& $object->GetLinkedInfo();
$queryDel = "DELETE FROM " . $object->TableName . " WHERE TaxZoneId=" . $parent_info['ParentId'];
$this->Conn->Query($queryDel);
foreach ($items_info as $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 new kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnCreate(kEvent &$event)
+ protected function OnCreate(kEvent $event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
foreach ($items_info as $field_values) {
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if ( $object->Create() ) {
$this->customProcessing($event, 'after');
}
else {
$event->status = kEvent::erFAIL;
$event->redirect = false;
$this->Application->SetVar($event->getPrefixSpecial() . '_SaveEvent', 'OnCreate');
$object->setID(0);
}
}
}
/**
* Apply custom processing to item
*
* @param kEvent $event
* @param string $type
* @return void
* @access protected
*/
- protected function customProcessing(kEvent &$event, $type)
+ protected function customProcessing(kEvent $event, $type)
{
switch ($type) {
case 'before':
$object =& $event->getObject();
/* @var $object kDBItem */
$events = $this->Application->GetVar('events');
if ( $events['tax'] == 'OnUpdate' ) {
$object->SetDBField('TaxZoneId', $this->Application->GetVar('tax_id'));
}
$tax_object =& $this->Application->recallObject('tax');
/* @var $tax_object kDBItem */
if ( $tax_object->GetDBField('Type') == 3 ) {
$tax_object->SetDBField('StdDestId', $this->Application->GetVar('StatesCountry'));
}
break;
}
}
/**
*
*
* @param kEvent $event
*/
- function OnZoneUpdate(&$event) {
+ function OnZoneUpdate($event) {
- $object = &$event->getObject();
+ $object =& $event->getObject();
+ /* @var $object kDBItem */
$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 15133)
+++ branches/5.2.x/units/discounts/discounts_event_handler.php (revision 15134)
@@ -1,58 +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 {
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->itemChanged($event);
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->itemChanged($event);
}
/**
* Occurs before item changed
*
* @param kEvent $event
*/
- function itemChanged(&$event)
+ function itemChanged($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 15133)
+++ branches/5.2.x/units/order_items/order_items_event_handler.php (revision 15134)
@@ -1,370 +1,370 @@
<?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 standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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)
+ 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));
/* @var $product_object ProductsItem */
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',
'pass' => 'm,ord,p',
);
$this->Application->EventManager->openerStackPush('in-commerce/orders/order_product_edit', $url_params);
}
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);
}
}
}
$event->SetRedirectParam('opener', 'u');
}
/**
* Updates subtotal field in order record.
* Only for "Items" tab in "Orders -> Order Edit" in Admin
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnUpdate(kEvent &$event)
+ protected function OnUpdate(kEvent $event)
{
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ( !$items_info ) {
return;
}
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
$table_info = $object->getLinkedInfo();
$main_object =& $this->Application->recallObject($table_info['ParentPrefix']);
/* @var $main_object OrdersItem */
foreach ($items_info as $id => $field_values) {
$object->Clear(); // otherwise validation errors will be passed to next object
$object->Load($id);
$object->SetFieldsFromHash($field_values, $this->getRequestProtectedFields($field_values));
$this->customProcessing($event, 'before');
if ( $object->Update($id) ) {
$this->customProcessing($event, 'after');
$event->status = kEvent::erSUCCESS;
}
else {
$oi_string = $object->GetDBField('ProductId') . ':' . $object->GetDBField('OptionsSalt') . ':' . $object->GetDBField('BackOrderFlag');
$field_errors = $object->GetFieldErrors();
foreach ($field_errors as $field => $error_params) {
$error_msg = $object->GetErrorMsg($field);
if ( $error_msg ) {
$main_object->setCheckoutError(OrderCheckoutErrorType::PRODUCT, OrderCheckoutError::FIELD_UPDATE_ERROR, $oi_string . ':' . $field);
}
}
$event->status = kEvent::erFAIL;
$event->redirect = false;
// break;
}
}
if ( $this->Application->GetVar('t') != 'in-commerce/orders/orders_edit_items' ) {
return;
}
$sub_total = $this->getSubTotal($items_info);
if ( $sub_total !== false ) {
$main_object->SetDBField('SubTotal', $sub_total);
}
$main_object->SetDBField('ReturnTotal', $this->getReturnTotal($items_info));
$main_object->Update();
}
/**
* Remembers what fields were changed
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnAfterItemUpdate(kEvent &$event)
+ protected function OnAfterItemUpdate(kEvent $event)
{
parent::OnAfterItemUpdate($event);
if ( $this->Application->isAdmin ) {
return;
}
$object =& $event->getObject();
/* @var $object kDBItem */
$changed_fields = $object->GetChangedFields();
if ( $changed_fields ) {
$table_info = $object->getLinkedInfo();
$main_object =& $this->Application->recallObject($table_info['ParentPrefix']);
/* @var $main_object OrdersItem */
$oi_string = $object->GetDBField('ProductId') . ':' . $object->GetDBField('OptionsSalt') . ':' . $object->GetDBField('BackOrderFlag');
foreach ($changed_fields as $changed_field => $change_info) {
$error_code = OrderCheckoutError::FIELD_UPDATE_SUCCESS;
if ( $changed_field == 'ItemData' ) {
$item_data_old = unserialize($change_info['old']);
$item_data_new = unserialize($change_info['new']);
if ( $item_data_old['DiscountId'] != $item_data_new['DiscountId'] || $item_data_old['DiscountType'] != $item_data_new['DiscountType'] ) {
if ( $item_data_new['DiscountId'] > 0 ) {
$error_code = $item_data_new['DiscountType'] == 'discount' ? OrderCheckoutError::DISCOUNT_APPLIED : OrderCheckoutError::COUPON_APPLIED;
}
else {
$error_code = $item_data_old['DiscountType'] == 'discount' ? OrderCheckoutError::DISCOUNT_REMOVED : OrderCheckoutError::COUPON_REMOVED;
}
}
if ( $error_code == OrderCheckoutError::DISCOUNT_APPLIED || $error_code == OrderCheckoutError::DISCOUNT_REMOVED ) {
// set general error too
$main_object->setCheckoutError(OrderCheckoutErrorType::DISCOUNT, $error_code);
}
}
elseif ( $changed_field == 'Quantity' && $this->Application->isDebugMode() ) {
// here is how qty is changed:
// OLD QTY -> NEW QTY
// RECALCULATE
// NEW QTY = IN_STOCK_QTY
// NEW ORDER ITEM with LEFTOVER QTY
$this->Application->Debugger->appendTrace();
$this->Application->Debugger->appendHTML('QTY_CHANGE (' . $oi_string . '): ' . $change_info['old'] . ' => ' . $change_info['new']);
}
$main_object->setCheckoutError(OrderCheckoutErrorType::PRODUCT, $error_code, $oi_string . ':' . $changed_field);
}
}
}
/**
* 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)
+ function OnSaveItems($event)
{
$event->CallSubEvent('OnUpdate');
$event->redirect = false;
$event->SetRedirectParam('opener', 's');
$event->SetRedirectParam('pass', 'all');
}
/**
* Occurs after 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 OnAfterClone(kEvent &$event)
+ protected function OnAfterClone(kEvent $event)
{
parent::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);
}
/**
* 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(kEvent &$event)
+ protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$item_info = $object->GetDBField('ItemData');
if ( $item_info ) {
$item_info = unserialize($item_info);
$object->SetDBField('DiscountType', getArrayValue($item_info, 'DiscountType'));
$object->SetDBField('DiscountId', getArrayValue($item_info, 'DiscountId'));
}
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
$object =& $event->getObject();
/* @var $object kDBList */
$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
* @access protected
*/
- protected function checkItemStatus(kEvent &$event)
+ protected function checkItemStatus(kEvent $event)
{
if ( $this->Application->isAdmin ) {
return true;
}
$object =& $event->getObject();
/* @var $object kDBItem */
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 15133)
+++ branches/5.2.x/units/addresses/addresses_event_handler.php (revision 15134)
@@ -1,458 +1,458 @@
<?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 {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected 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);
}
/**
* Returns special of main item for linking with sub-item
*
* @param kEvent $event
* @return string
* @access protected
*/
- protected function getMainSpecial(kEvent &$event)
+ protected function getMainSpecial(kEvent $event)
{
return '';
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @return void
* @access protected
* @see kDBEventHandler::OnListBuild()
*/
- protected function SetCustomQuery(kEvent &$event)
+ protected function SetCustomQuery(kEvent $event)
{
parent::SetCustomQuery($event);
if ( $this->Application->isAdminUser ) {
return;
}
$object =& $event->getObject();
/* @var $object kDBList */
$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
*/
protected 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
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
if ( !$object->isLoaded() || !$this->checkItemStatus($event) ) {
// not trivially loaded object OR not current user address
$event->status = 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');
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnUpdate(kEvent &$event)
+ protected function OnUpdate(kEvent $event)
{
parent::OnUpdate($event);
$this->setNextTemplate($event);
}
/**
* Creates new kDBItem
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnCreate(kEvent &$event)
+ protected function OnCreate(kEvent $event)
{
parent::OnCreate($event);
$this->setNextTemplate($event);
}
/**
* Sets next template to be shown after address is added/updated
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function setNextTemplate(kEvent &$event)
+ protected function setNextTemplate(kEvent $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
*/
- protected function OnAfterItemLoad(kEvent &$event)
+ protected function OnAfterItemLoad(kEvent $event)
{
parent::OnAfterItemLoad($event);
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
$cs_helper->PopulateStates($event, 'State', 'Country');
}
/**
* [HOOK] Update Users table when address marked as ProfileAddress is changed via addr prefix object
*
* @param kEvent $event
* @return bool
* @access protected
*/
- protected function OnUpdateProfileAddress(kEvent &$event)
+ protected function OnUpdateProfileAddress(kEvent $event)
{
$object =& $event->getObject(Array ('skip_autoload' => true));
/* @var $object kDBItem */
if ( !$this->Application->isAdmin ) {
$address_id = $this->getOrderAddressId();
if ( !$address_id ) {
return true;
}
$object->Load($address_id);
}
if ( !$object->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 =& $this->Application->recallObject($this->Application->isAdmin ? 'u' : 'u.current');
/* @var $user UsersItem */
$user->setName( $object->GetDBField('To') );
foreach ($field_map as $src_field => $dst_field) {
if ( $dst_field == 1 ) {
$dst_field = $src_field;
}
$user->SetDBField($dst_field, $object->GetDBField($src_field));
}
return $user->Update();
}
/**
* Returns ID of address, that is selected in address dropdown on shipping/billing step of checkout
*
* @return int
* @access protected
*/
protected function getOrderAddressId()
{
$ret = false;
if ( $this->Application->GetVar('billing_address_id') > 0 ) {
$ret = $this->Application->GetVar('billing_address_id');
}
elseif ( $this->Application->GetVar('shipping_address_id') > 0 ) {
$ret = $this->Application->GetVar('shipping_address_id');
}
return $ret;
}
/**
* [HOOK] Create user profile address based on Users table data
*
* @param kEvent $event
* @return bool
* @access protected
*/
- protected function OnUpdateUserProfile(kEvent &$event)
+ protected function OnUpdateUserProfile(kEvent $event)
{
$user =& $event->MasterEvent->getObject();
/* @var $user UsersItem */
$load_keys = Array ('PortalUserId' => $user->GetID(), 'IsProfileAddress' => 1);
$object =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true));
/* @var $object kDBItem */
$object->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'));
$object->SetDBField('To', $full_name);
$object->SetDBField('IsProfileAddress', 1);
foreach ($field_map as $dst_field => $src_field) {
if ( $src_field == 1 ) {
$src_field = $dst_field;
}
$object->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 ' . $object->TableName . '
WHERE PortalUserId = ' . $user->GetID();
$address_status = $this->Conn->GetRow($sql);
if ( !$address_status['HasBilling'] ) {
$object->SetDBField('LastUsedAsBilling', 1);
}
if ( !$address_status['HasShipping'] ) {
$object->SetDBField('LastUsedAsShipping', 1);
}
return $object->isLoaded() ? $object->Update() : $object->Create();
}
/**
* Checks if user trying to manipulate address that he Owns (exception for Admins)
* (non permission-based)
*
* @param kEvent $event
* @return bool
* @access protected
*/
- protected function checkItemStatus(kEvent &$event)
+ protected function checkItemStatus(kEvent $event)
{
if ( $this->Application->isAdminUser ) {
return true;
}
if ( !$this->Application->LoggedIn() ) {
return false;
}
$object =& $event->getObject();
/* @var $object kDBItem */
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
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
if ( !$this->Application->LoggedIn() ) {
$event->status = kEvent::erPERM_FAIL;
return ;
}
$object =& $event->getObject();
/* @var $object kDBItem */
if ( !$this->Application->isAdmin ) {
$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');
}
/**
* Occurs before deleting item, id of item being
* deleted is stored as 'id' event param
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemDelete(kEvent &$event)
+ protected function OnBeforeItemDelete(kEvent $event)
{
parent::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
* @return void
* @access protected
*/
- protected function OnAfterConfigRead(kEvent &$event)
+ protected function OnAfterConfigRead(kEvent $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);
}
/**
* [HOOK] Creates user addresses editing tab
*
* @param kEvent $event
*/
- function OnModifyUsersConfig(&$event)
+ function OnModifyUsersConfig($event)
{
$title_presets = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'TitlePresets');
$title_presets['user_edit_addresses'] = Array (
'prefixes' => Array ('u', $event->Prefix . '_List'),
'format' => "#u_status# '#u_titlefield#' - !la_title_Addresses! (#" . $event->Prefix . "_recordcount#)"
);
$title_presets['user_address_edit'] = Array (
'prefixes' => Array ('u', $event->Prefix),
'new_status_labels' => Array ($event->Prefix => '!la_title_AddingAddress!'),
'edit_status_labels' => Array ($event->Prefix => '!la_title_EditingAddress!'),
'new_titlefield' => Array ($event->Prefix => '!la_title_NewAddress!'),
'format' => "#u_status# '#u_titlefield#' - #{$event->Prefix}_status#"
);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'TitlePresets', $title_presets);
$edit_tab_presets = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'EditTabPresets');
$edit_tab_presets['Default'][] = Array (
'title' => 'la_tab_Addresses', 't' => 'in-commerce/users/user_edit_addresses', 'priority' => 6
);
$this->Application->setUnitOption($event->MasterEvent->Prefix, 'EditTabPresets', $edit_tab_presets);
}
}
\ No newline at end of file
Index: branches/5.2.x/units/gift_certificates/gift_certificates_eh.php
===================================================================
--- branches/5.2.x/units/gift_certificates/gift_certificates_eh.php (revision 15133)
+++ branches/5.2.x/units/gift_certificates/gift_certificates_eh.php (revision 15134)
@@ -1,201 +1,201 @@
<?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 GiftCertificateEventHandler extends kDBEventHandler {
/**
* Allows to override standard permission mapping
*
* @return void
* @access protected
* @see kEventHandler::$permMapping
*/
protected function mapPermissions()
{
parent::mapPermissions();
$permissions = Array (
'OnItemBuild' => Array ('self' => true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
/**
* 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(kEvent &$event)
+ protected function OnPreCreate(kEvent $event)
{
parent::OnPreCreate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$exp_date = adodb_mktime();
$default_duration = $this->Application->ConfigValue('Comm_DefaultCouponDuration');
if ( $default_duration ) {
$exp_date += (int)$default_duration * 86400;
}
$object->SetDBField('Expiration_date', $exp_date);
}
/**
* Occurs before updating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemUpdate(kEvent &$event)
+ protected function OnBeforeItemUpdate(kEvent $event)
{
parent::OnBeforeItemUpdate($event);
$this->itemChanged($event);
}
/**
* Occurs before creating item
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnBeforeItemCreate(kEvent &$event)
+ protected function OnBeforeItemCreate(kEvent $event)
{
parent::OnBeforeItemCreate($event);
$this->itemChanged($event);
$object =& $event->getObject();
/* @var $object kDBItem */
$object->SetDBField('Debit', $object->GetDBField('Amount'));
}
/**
* Occurs before item is changed
*
* @param kEvent $event
*/
- function itemChanged(&$event)
+ function itemChanged($event)
{
$object =& $event->getObject();
/* @var $object kDBItem */
$amount = abs($object->GetDBField('Amount'));
$debit = abs($object->GetDBField('Debit'));
if ( $debit > $amount ) {
$debit = $amount;
}
$object->SetDBField('Amount', $amount);
$object->SetDBField('Debit', $debit);
if ( $object->GetDBField('SendVia') == 1 ) {
// by postal mail
if ( $this->Application->GetVar('email_certificate') == 0 ) {
$object->setRequired('RecipientEmail', false);
}
$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
/* @var $cs_helper kCountryStatesHelper */
if ( !$cs_helper->CountryHasStates($object->GetDBField('RecipientCountry')) ) {
$object->setRequired('RecipientState', false);
}
$cs_helper->CheckStateField($event, 'RecipientState', 'RecipientCountry');
}
else {
$non_required_fields = Array (
'RecipientState', 'RecipientCity', 'RecipientCountry', 'RecipientZipcode',
'RecipientAddress1', 'RecipientFirstname', 'RecipientLastname'
);
$object->setRequired($non_required_fields, false);
}
}
/**
* Print current gift certificate
*
* @param kEvent $event
* @return void
* @access protected
*/
- protected function OnSave(kEvent &$event)
+ protected function OnSave(kEvent $event)
{
parent::OnSave($event);
if ( $event->status != kEvent::erSUCCESS || !$this->Application->GetVar('print_certificate') ) {
return ;
}
$object =& $event->getObject();
/* @var $object kDBItem */
// get object id by unique field Code
$sql = 'SELECT ' . $object->IDField . '
FROM ' . $this->Application->GetLiveName($object->TableName) . '
WHERE Code = ' . $this->Conn->qstr( $object->GetDBField('Code') );
$id = $this->Conn->GetOne($sql);
$this->Application->StoreVar('print_certificate_id', $id);
}
/**
* Email selected gift certificate
*
* @param kEvent $event
*/
- function OnEmailGiftCertificate(&$event)
+ function OnEmailGiftCertificate($event)
{
$ids = $this->StoreSelectedIDs($event);
if (!$ids) {
return ;
}
$object =& $event->getObject( Array ('skip_autoload' => true) );
/* @var $object kDBItem */
foreach ($ids as $id) {
$object->Load($id);
$send_params = Array (
'from_email' => $this->Application->ConfigValue('DefaultEmailSender'),
'from_name' => $object->GetDBField('Purchaser'),
'to_email' => $object->GetDBField('RecipientEmail'),
'to_name' => $object->GetDBField('Recipient'),
'message' => $object->GetDBField('Message'),
'amount' => $object->GetField('Amount'),
'gifcert_id' => $object->GetDBField('Code'),
);
$this->Application->EmailEventUser('USER.GIFTCERTIFICATE', null, $send_params);
$this->Application->EmailEventAdmin('USER.GIFTCERTIFICATE', null, $send_params);
}
$this->clearSelectedIDs($event);
}
}
\ No newline at end of file
Index: branches/5.2.x/gw_notify.php
===================================================================
--- branches/5.2.x/gw_notify.php (revision 15133)
+++ branches/5.2.x/gw_notify.php (revision 15134)
@@ -1,64 +1,63 @@
<?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.
*/
define('GW_NOTIFY', 1);
define('FULL_PATH', realpath(dirname(__FILE__) . '/../..'));
include_once(FULL_PATH . '/core/kernel/startup.php');
$application =& kApplication::Instance();
$application->Init();
// for debugging payment gateway notifications, don't remove
/*$fh = fopen((defined('RESTRICTED') ? RESTRICTED : WRITEABLE) . '/gw.log', 'a');
fwrite ($fh, "\n\n".date('d/m/y h:i:s').":\n");
foreach ($_REQUEST as $key => $val) {
fwrite($fh, "<input type=\"text\" name=\"$key\" value=\"$val\">\n");
}
fclose($fh);*/
$db =& $application->GetADODBConnection();
$application->setUnitOption('ord','AutoLoad',false);
$order =& $application->recallObject('ord');
$order_id = $application->GetVar('order_id');
if ($order_id) {
$order->Load($order_id);
}
$gw_data = $order->getGatewayData($application->GetVar('payment_type_id'));
$application->registerClass( $gw_data['ClassName'], GW_CLASS_PATH.'/'.$gw_data['ClassFile'] );
$gateway_object =& $application->recallObject( $gw_data['ClassName'] );
$transaction_status = $gateway_object->processNotification($gw_data['gw_params']);
$sql = 'UPDATE %s SET GWResult1 = %s WHERE %s = %s';
$sql = sprintf($sql, $order->TableName, $db->qstr($gateway_object->getGWResponce()), $order->IDField, $order->GetID() );
$db->Query($sql);
$order->SetDBField('GWResult1', $gateway_object->getGWResponce() );
$sql = 'UPDATE %s SET TransactionStatus = %s WHERE %s = %s';
$db->Query( sprintf($sql, $order->TableName, $transaction_status, $order->IDField, $order->GetID()) );
$order->SetDBField('TransactionStatus', $transaction_status);
if($transaction_status == 1)
{
- $dummy_var = '10';
- $application->HandleEvent($dummy_var, 'ord:OnCompleteOrder');
+ $application->HandleEvent(new kEvent('ord:OnCompleteOrder'));
}
else {
$application->StoreVar('gw_error', $gateway_object->getErrorMsg());
}
$application->Done();
\ No newline at end of file

Event Timeline