Page Menu
Home
In-Portal Phabricator
Search
Configure Global Search
Log In
Files
F1058781
in-portal
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Thu, Jul 10, 9:33 PM
Size
130 KB
Mime Type
text/x-diff
Expires
Sat, Jul 12, 9:33 PM (3 h, 2 m)
Engine
blob
Format
Raw Data
Handle
683808
Attached To
rINP In-Portal
in-portal
View Options
Index: trunk/kernel/units/categories/categories_tag_processor.php
===================================================================
--- trunk/kernel/units/categories/categories_tag_processor.php (revision 3590)
+++ trunk/kernel/units/categories/categories_tag_processor.php (revision 3591)
@@ -1,282 +1,290 @@
<?php
class CategoriesTagProcessor extends kDBTagProcessor {
function &GetList($params)
{
$special = $this->BuildListSpecial($params);
$prefix_special = $this->Prefix.'.'.$special;
$this->Special = $special;
$params['skip_counting'] = true;
$list =& $this->Application->recallObject( $prefix_special, $this->Prefix.'_List',$params);
// $list->clearFilters();
// $list->addFilter('parent_filter', 'ParentId = '.$parent_cat_id, WHERE_FILTER, FLT_SYSTEM);
//unset($params['skip_counting']);
$this->Application->HandleEvent($event, $prefix_special.':SetPagination', $params );
$list->Query();
return $list;
}
function SubCatCount($params)
{
$cat_object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$sql = ' SELECT COUNT(*) - 1
FROM '.$cat_object->TableName.'
WHERE ParentPath LIKE "'.$cat_object->GetDBField('ParentPath').'%"';
return $this->Conn->GetOne($sql);
}
function IsNew($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$ret = $object->GetDBField('IsNew') ? 1 : 0;
return $ret;
}
function IsPick($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$ret = $object->GetDBField('EditorsPick') ? 1 : 0;
return $ret;
}
function ItemIcon($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$status = $object->GetDBField('Status');
if($status == 1)
{
$ret = $object->GetDBField('IsNew') ? 'icon16_cat_new.gif' : 'icon16_cat.gif';
}
else
{
$ret = $status ? 'icon16_cat_pending.gif' : 'icon16_cat_disabled.gif';
}
return $ret;
}
function ItemCount($params)
{
$cat_object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$ci_table = $this->Application->getUnitOption('ci','TableName');
$sql = ' SELECT COUNT(*)
FROM '.$cat_object->TableName.' c
LEFT JOIN '.$ci_table.' ci
ON c.CategoryId=ci.CategoryId
WHERE c.ParentPath LIKE "'.$cat_object->GetDBField('ParentPath').'%"
AND NOT (ci.CategoryId IS NULL)';
return $this->Conn->GetOne($sql);
}
function ListCategories($params)
{
return $this->PrintList2($params);
}
function RootCategoryName($params)
{
$root_phrase = $this->Application->ConfigValue('Root_Name');
$ret = $this->Application->Phrase($root_phrase);
return $ret;
}
function CheckModuleRoot($params)
{
$module_name = getArrayValue($params, 'module') ? $params['module'] : 'In-Commerce';
$module = $this->Application->recallObject('mod.'.$module_name);
$module_root_cat = $module->GetDBField('RootCat');
- if ($this->Application->GetVar('m_cat_id') == $module_root_cat) {
+ $additional_cats = $this->SelectParam($params, 'add_cats');
+ if ($additional_cats) {
+ $additional_cats = explode(',', $additional_cats);
+ }
+ else {
+ $additional_cats = array();
+ }
+
+ if ($this->Application->GetVar('m_cat_id') == $module_root_cat || in_array($this->Application->GetVar('m_cat_id'), $additional_cats)) {
$home_template = getArrayValue($params, 'home_template');
if (!$home_template) return;
$this->Application->Redirect($home_template, Array('pass'=>'all'));
};
}
function CategoryPath($params)
{
$module_name = getArrayValue($params, 'module') ? $params['module'] : 'In-Commerce';
$module = $this->Application->recallObject('mod.'.$module_name);
$module_root_cat = $module->GetDBField('RootCat');
$block_params['current'] = 0;
$block_params['separator'] = $params['separator'];
if(!isset($params['cat_id']))
{
$params['cat_id'] = getArrayValue($params, 'cat_id') ? $params['cat_id'] : $this->Application->GetVar('m_cat_id');
$block_params['current'] = 1;
}
$product_id = $this->Application->GetVar('p_id');
if ($product_id) {
$block_params['current'] = 0;
}
$block_params['is_module_root'] = ($params['cat_id'] == $module_root_cat) ? 1 : 0;
if($params['cat_id'] == 0)
{
$block_params['name'] = $this->SelectParam($params, 'root_cat_render_as,block_root_cat,rootcatblock');
return $this->Application->ParseBlock($block_params);
}
else
{
$block_params['name'] = $this->SelectParam($params,'render_as,block');
// $cat_object = &$this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix.'_List' );
$sql = 'SELECT CategoryId, ParentId, Name FROM '.$this->Application->getUnitOption($this->Prefix, 'TableName').'
WHERE CategoryId='.$params['cat_id'];
$res = $this->Conn->GetRow($sql);
$block_params['cat_name'] = $res['Name'];
$block_params['cat_id'] = $res['CategoryId'];
$parent_params = $params;
$parent_params['cat_id'] = $res['ParentId'];
// which block to parse as current ?
if ($block_params['is_module_root'] == 1) { // module root
$block_params['name'] = $this->SelectParam($params, 'module_root_render_as,block_module_root,rootmoduleblock');
}
if ($block_params['current'] == 1) { // current cat (label)
$block_params['name'] = $this->SelectParam($params, 'current_render_as,block_current,currentblock');
}
$this->Application->SetVar($this->Prefix.'_id', $res['CategoryId']);
$current_cat = $this->Application->ParseBlock($block_params, 1);
$this->Application->SetVar($this->Prefix.'_id', $res['ParentId']);
$parent_cat = $this->CategoryPath($parent_params);
return $parent_cat.$current_cat;
}
}
function CurrentCategoryName($params){
$cat_object = &$this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix.'_List' );
$cat_id = $this->Application->GetVar("m_cat_id");
$sql = 'SELECT Name FROM '.$cat_object->TableName.' WHERE CategoryId='.$cat_id;
return $this->Conn->GetOne($sql);
}
function InitMainPrefix($params)
{
if($main_prefix = $this->Application->GetVar('main_prefix'))
{
$this->Application->StoreVar('selector_main_prefix', $main_prefix);
}
}
function CategoryLink($params)
{
// 'p_id'=>'0', ??
$params = array_merge(array('pass'=>'m'), $params);
$cat_id = getArrayValue($params,'cat_id');
if ($cat_id === false) {
// $cat_id = $this->Application->Parser->GetParam('cat_id');
$cat_id = $this->Application->GetVar($this->Prefix.'_id');
}
if($cat_id == 'Root')
{
$object =& $this->Application->recallObject('mod.'.$params['module']);
$params['m_cat_id'] = $object->GetDBField('RootCat');
unset($params['module']);
}
else{
$params['m_cat_id'] = $cat_id;
}
unset($params['cat_id']);
$main_processor =& $this->Application->recallObject('m_TagProcessor');
return $main_processor->T($params);
}
function CategoryList($params)
{
//$object =& $this->Application->recallObject( $this->getPrefixSpecial() , $this->Prefix.'_List', $params );
$object =& $this->GetList($params);
if ($object->RecordsCount == 0)
{
if (isset($params['block_no_cats'])) {
$params['name'] = $params['block_no_cats'];
return $this->Application->ParseBlock($params);
}
else {
return '';
}
}
if(isset($params['block']))
{
return $this->PrintList($params);
}
else
{
$params['block'] = $params['block_main'];
$params['row_start_block'] = $params['block_row_start'];
$params['row_end_block'] = $params['block_row_end'];
return $this->PrintList2($params);
}
}
function Meta($params)
{
$name = getArrayValue($params, 'name');
$object =& $this->Application->recallObject($this->Prefix.'.-item');
$field = $object->GetField('Meta'.$name);
if ($field) return $field;
switch ($name) {
case 'Description':
$conf = 'Category_MetaDesc';
break;
case 'Keywords':
$conf = 'Category_MetaKey';
break;
}
return $this->Application->ConfigValue($conf);
}
function BuildListSpecial($params)
{
if ( isset($params['parent_cat_id']) ) {
$parent_cat_id = $params['parent_cat_id'];
}
else {
$parent_cat_id = $this->Application->GetVar($this->Prefix.'_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
if (!$parent_cat_id) {
$parent_cat_id = 0;
}
}
$types = $this->SelectParam($params, 'types');
$except = $this->SelectParam($params, 'except');
if ($types.$except.$parent_cat_id == '') {
return parent::BuildListSpecial($params);
}
$special = crc32($types.$except.$parent_cat_id);
return $special;
}
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/units/categories/categories_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/kernel/units/general/cat_event_handler.php
===================================================================
--- trunk/kernel/units/general/cat_event_handler.php (revision 3590)
+++ trunk/kernel/units/general/cat_event_handler.php (revision 3591)
@@ -1,1407 +1,1407 @@
<?php
$application =& kApplication::Instance();
$application->Factory->includeClassFile('kDBEventHandler');
class kCatDBEventHandler extends InpDBEventHandler {
function OnCopy(&$event)
{
$object = $event->getObject();
$this->StoreSelectedIDs($event);
$ids = $this->getSelectedIDs($event);
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard', implode(',', $ids));
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard_mode', 'copy');
$this->Application->StoreVar('ClipBoard', 'COPY-0.'.$object->TableName.'.ResourceId=0');
$event->redirect_params = Array('opener' => 's', 'pass_events'=>true); //do not go up - STAY
}
function OnCut(&$event)
{
$object = $event->getObject();
$this->StoreSelectedIDs($event);
$ids = $this->getSelectedIDs($event);
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard', implode(',', $ids));
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard_mode', 'cut');
$this->Application->StoreVar('ClipBoard', 'CUT-0.'.$object->TableName.'.ResourceId=0');
$event->redirect_params = Array('opener' => 's', 'pass_events'=>true); //do not go up - STAY
}
function OnPaste(&$event)
{
$ids = $this->Application->RecallVar($event->getPrefixSpecial().'_clipboard');
if ($ids == '') {
$event->redirect = false;
return;
}
//recalling by different name, because we may get kDBList, if we recall just by prefix
$object =& $this->Application->recallObject($event->getPrefixSpecial().'.item', $event->Prefix);
$this->prepareObject($object, $event);
if ($this->Application->RecallVar($event->getPrefixSpecial().'_clipboard_mode') == 'copy') {
$ids_arr = explode(',', $ids);
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
if($ids_arr)
{
$temp->CloneItems($event->Prefix, $event->Special, $ids_arr);
}
}
else { // mode == cut
$ids_arr = explode(',', $ids);
foreach ($ids_arr as $id) {
$object->Load($id);
$object->MoveToCat();
}
}
$event->status = erSUCCESS;
}
/**
* Occurs when pasting category
*
* @param kEvent $event
*/
function OnCatPaste(&$event)
{
$inp_clipboard = $this->Application->RecallVar('ClipBoard');
$inp_clipboard = explode('-', $inp_clipboard, 2);
if($inp_clipboard[0] == 'COPY')
{
$saved_cat_id = $this->Application->GetVar('m_cat_id');
$cat_ids = $event->getEventParam('cat_ids');
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$ids_sql = 'SELECT '.$id_field.' FROM '.$table.' WHERE ResourceId IN (%s)';
$resource_ids_sql = 'SELECT ItemResourceId FROM '.TABLE_PREFIX.'CategoryItems WHERE CategoryId = %s AND PrimaryCat = 1';
$this->Application->setUnitOption($event->Prefix,'AutoLoad', false);
$object =& $this->Application->recallObject($event->Prefix.'.item', $event->Prefix);
foreach($cat_ids as $source_cat => $dest_cat)
{
$item_resource_ids = $this->Conn->GetCol( sprintf($resource_ids_sql, $source_cat) );
if(!$item_resource_ids) continue;
$this->Application->SetVar('m_cat_id', $dest_cat);
$item_ids = $this->Conn->GetCol( sprintf($ids_sql, implode(',', $item_resource_ids) ) );
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
if($item_ids) $temp->CloneItems($event->Prefix, $event->Special, $item_ids);
}
$this->Application->setUnitOption($event->Prefix,'AutoLoad', true);
$this->Application->SetVar('m_cat_id', $saved_cat_id);
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveAndOpenTranslator(&$event)
{
$this->Application->SetVar('allow_translation', true);
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
// $url = $this->Application->HREF($t, '', Array('pass'=>'all', $event->getPrefixSpecial(true).'_id' => $object->GetId()));
// $field = $this->Application->GetVar('translator_field');
$cf_id = $this->Application->GetVar('translator_cf_id');
if($cf_id)
{
$cv =& $this->Application->recallObject('cv.-item', null, Array('skip_autoload' => true) );
$load_params = Array('CustomFieldId' => $cf_id, 'ResourceId'=> $object->GetDBField('ResourceId') );
if( !$cv->Load($load_params) )
{
$cv->SetFieldsFromHash($load_params);
$cv->Create();
}
$this->Application->SetVar('cv_id', $cv->getID() );
}
$event->redirect = $this->Application->GetVar('translator_t');
$event->redirect_params = Array('pass'=>'all,trans,'.$this->Application->GetVar('translator_prefixes'),
$event->getPrefixSpecial(true).'_id' => $object->GetId(),
'trans_event'=>'OnLoad',
'trans_prefix'=> $this->Application->GetVar('translator_prefixes'),
'trans_field'=>$this->Application->GetVar('translator_field'),
'trans_multi_line'=>$this->Application->GetVar('translator_multi_line'),
);
// 1. SAVE LAST TEMPLATE TO SESSION
$last_template = $this->Application->RecallVar('last_template');
preg_match('/index4\.php\|'.$this->Application->GetSID().'-(.*):/U', $last_template, $rets);
// $this->Application->StoreVar('return_template', $rets[1]);
$this->Application->StoreVar('return_template', $this->Application->GetVar('t'));
//$after_script = "openTranslator('".$event->getPrefixSpecial()."', '".$field."', '".$url."', '".$wnd_name."')";
}
// $this->Application->SetVar('after_script', $after_script);
// $event->redirect = false;
}
/**
* Apply scope clause
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
$object =& $event->getObject();
if ($event->Special != 'showall') {
if ( $event->getEventParam('parent_cat_id') ) {
$parent_cat_id = $event->getEventParam('parent_cat_id');
}
else {
$parent_cat_id = $this->Application->GetVar('c_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
if (!$parent_cat_id) {
$parent_cat_id = 0;
}
}
if ((string) $parent_cat_id != 'any') {
if ($event->getEventParam('recursive')) {
$current_path = $this->Conn->GetOne('SELECT ParentPath FROM '.TABLE_PREFIX.'Category WHERE CategoryId='.$parent_cat_id);
$subcats = $this->Conn->GetCol('SELECT CategoryId FROM '.TABLE_PREFIX.'Category WHERE ParentPath LIKE "'.$current_path.'%" ');
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId IN ('.implode(', ', $subcats).')');
}
else {
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId = '.$parent_cat_id );
}
}
}
else {
$object->addFilter('primary_filter', 'PrimaryCat = 1');
}
$view_perm = 1;
$object->addFilter('perm_filter', 'perm.PermId = '.$view_perm);
if ( !$this->Application->IsAdmin() )
{
$groups = explode( ',', $this->Application->RecallVar('UserGroups') );
foreach($groups as $group)
{
$view_filters[] = 'FIND_IN_SET('.$group.', perm.acl) || ((NOT FIND_IN_SET('.$group.',perm.dacl)) AND perm.acl=\'\')';
}
$view_filter = implode(' OR ', $view_filters);
$object->addFilter('perm_filter2', $view_filter);
$object->addFilter('status_filter', $object->TableName.'.Status = 1');
}
/*$list_type = $event->getEventParam('ListType');
switch($list_type)
{
case 'favorites':
$fav_table = $this->Application->getUnitOption('fav','TableName');
$user_id =& $this->Application->GetVar('u_id');
$sql = 'SELECT DISTINCT f.ResourceId
FROM '.$fav_table.' f
LEFT JOIN '.$object->TableName.' p ON p.ResourceId = f.ResourceId
WHERE f.PortalUserId = '.$user_id;
$ids = $this->Conn->GetCol($sql);
if(!$ids) $ids = Array(-1);
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.PrimaryCat = 1');
$object->addFilter('favorites_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')');
break;
case 'search':
$search_results_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = ' SELECT DISTINCT ResourceId
FROM '.$search_results_table.'
WHERE ItemType=11';
$ids = $this->Conn->GetCol($sql);
if(!$ids) $ids = Array(-1);
$object->addFilter('search_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')');
break;
} */
}
/**
* Adds calculates fields for item statuses
*
* @param kCatDBItem $object
* @param kEvent $event
*/
function prepareObject(&$object, &$event)
{
$this->prepareItemStatuses($event);
if ($event->Special == 'export' || $event->Special == 'import')
{
$this->prepareExportColumns($event);
}
}
/**
* Creates calculated fields for all item statuses based on config settings
*
* @param kEvent $event
*/
function prepareItemStatuses(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$property_mappings = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
$new_days_var = getArrayValue($property_mappings, 'NewDays');
if($new_days_var)
{
$object->addCalculatedField('IsNew', ' IF(%1$s.NewItem = 2,
IF(%1$s.CreatedOn >= (UNIX_TIMESTAMP() - '.
$this->Application->ConfigValue($new_days_var).
'*3600*24), 1, 0),
%1$s.NewItem
)');
}
$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
if($hot_limit_var)
{
$sql = 'SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName = "'.$hot_limit_var.'"';
$hot_limit = $this->Conn->GetOne($sql);
if($hot_limit === false) $hot_limit = $this->CalculateHotLimit($event);
$object->addCalculatedField('IsHot', ' IF(%1$s.HotItem = 2,
IF(%1$s.Hits >= '.$hot_limit.', 1, 0),
%1$s.HotItem
)');
}
$votes2pop_var = getArrayValue($property_mappings, 'VotesToPop');
$rating2pop_var = getArrayValue($property_mappings, 'RatingToPop');
if($votes2pop_var && $rating2pop_var)
{
$object->addCalculatedField('IsPop', ' IF(%1$s.PopItem = 2,
IF(%1$s.CachedVotesQty >= '.
$this->Application->ConfigValue($votes2pop_var).
' AND %1$s.CachedRating >= '.
$this->Application->ConfigValue($rating2pop_var).
', 1, 0),
%1$s.PopItem)');
}
}
function CalculateHotLimit(&$event)
{
$property_mappings = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
$hot_count_var = getArrayValue($property_mappings, 'HotCount');
$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
if($hot_count_var && $hot_limit_var)
{
$last_hot = $this->Application->ConfigValue($hot_count_var) - 1;
$sql = 'SELECT Hits FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
ORDER BY Hits DESC
LIMIT '.$last_hot.', 1';
$res = $this->Conn->GetCol($sql);
$hot_limit = (double)array_shift($res);
$this->Conn->Query('REPLACE INTO '.TABLE_PREFIX.'Cache VALUES ("'.$hot_limit_var.'", "'.$hot_limit.'", '.adodb_mktime().')');
return $hot_limit;
}
return 0;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
if( $this->Application->IsAdmin() && ($this->Application->GetVar('Hits_original') !== false) &&
floor($this->Application->GetVar('Hits_original')) != $object->GetDBField('Hits') )
{
$sql = 'SELECT MAX(Hits) FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
WHERE FLOOR(Hits) = '.$object->GetDBField('Hits');
$hits = ( $res = $this->Conn->GetOne($sql) ) ? $res + 0.000001 : $object->GetDBField('Hits');
$object->SetDBField('Hits', $hits);
}
}
function OnAfterItemUpdate(&$event)
{
$this->CalculateHotLimit($event);
}
/**
* Makes simple search for products
* based on keywords string
*
* @param kEvent $event
* @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!!
*/
function OnSimpleSearch(&$event)
{
if($this->Application->GetVar('INPORTAL_ON') && !($this->Application->GetVar('Action') == 'm_simple_search'))
{
return;
}
$event->redirect = false;
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$keywords = trim($this->Application->GetVar('keywords'));
if( !$this->Application->GetVar('INPORTAL_ON') )
{
$keywords = unhtmlentities($keywords);
}
$query_object =& $this->Application->recallObject('HTTPQuery');
$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
if(!isset($query_object->Get['keywords']) &&
!isset($query_object->Post['keywords']) &&
$this->Conn->Query($sql))
{
return; // used when navigating by pages or changing sorting in search results
}
if(!$keywords || strlen($keywords) < $this->Application->ConfigValue('Search_MinKeyword_Length'))
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table);
$this->Application->SetVar('keywords_too_short', 1);
return; // if no or too short keyword entered, doing nothing
}
$this->Application->StoreVar('keywords', $keywords);
$keywords = strtr($keywords, Array('%' => '\\%', '_' => '\\_'));
$event->setPseudoClass('_List');
$object =& $event->getObject();
$this->Application->SetVar($event->getPrefixSpecial().'_Page', 1);
$lang = $this->Application->GetVar('m_lang');
$product_table = $this->Application->getUnitOption('p', 'TableName');
$sql = ' SELECT * FROM '.$this->Application->getUnitOption('confs', 'TableName').'
WHERE ModuleName="In-Commerce"
AND SimpleSearch=1';
$search_config = $this->Conn->Query($sql, 'FieldName');
$field_list = array_keys($search_config);
$join_clauses = Array();
// field processing
$weight_sum = 0;
foreach($field_list as $key => $field)
{
$options = $object->getFieldOptions($field);
$local_table = TABLE_PREFIX.$search_config[$field]['TableName'];
$weight_sum += $search_config[$field]['Priority']; // counting weight sum; used when making relevance clause
// processing multilingual fields
if($options['formatter'] == 'kMultiLanguage')
{
$field_list[$key] = 'l'.$lang.'_'.$field;
}
// processing fields from other tables
if($foreign_field = $search_config[$field]['ForeignField'])
{
$exploded = explode(':', $foreign_field, 2);
if($exploded[0] == 'CALC')
{
unset($field_list[$key]);
continue; // ignoring having type clauses in simple search
/*$user_object =& $this->Application->recallObject('u');
$user_groups = $user_object->GetDBField('PortalUserId') ?
implode(',', $this->Conn->GetCol(' SELECT GroupId
FROM '.TABLE_PREFIX.'UserGroup
WHERE PortalUserId='.$user_object->GetDBField('PortalUserId'))) : 0;
$having_list[$key] = str_replace('{PREFIX}', TABLE_PREFIX, $exploded[1]);
$join_clause = str_replace('{PREFIX}', TABLE_PREFIX, $search_config[$field]['JoinClause']);
$join_clause = str_replace('{USER_GROUPS}', $user_groups, $join_clause);
$join_clause = ' LEFT JOIN '.$join_clause;
$join_clauses[] = $join_clause;*/
}
else
{
$exploded = explode('.', $foreign_field);
$foreign_table = TABLE_PREFIX.$exploded[0];
if($search_config[$field]['CustomFieldId']) {
$exploded[1] = 'l'.$lang.'_'.$exploded[1];
}
$alias_counter++;
$alias = 't'.$alias_counter;
$field_list[$key] = $alias.'.'.$exploded[1];
$join_clause = str_replace('{ForeignTable}', $alias, $search_config[$field]['JoinClause']);
$join_clause = str_replace('{LocalTable}', $product_table, $join_clause);
if($search_config[$field]['CustomFieldId'])
{
$join_clause .= ' AND '.$alias.'.CustomFieldId='.$search_config[$field]['CustomFieldId'];
}
$join_clauses[] = ' LEFT JOIN '.$foreign_table.' '.$alias.'
ON '.$join_clause;
}
}
else
{
// processing fields from local table
$field_list[$key] = $local_table.'.'.$field_list[$key];
}
}
// keyword string processing
$normal_keywords = Array();
$plus_keywords = Array();
$minus_keywords = Array();
for($i = 0; $i < strlen($keywords); $i++)
{
if(substr($keywords, $i, 1) == ' ') continue;
$extra_skip = 0;
switch(substr($keywords, $i, 1))
{
case '+':
if(substr($keywords, $i + 1, 1) == '"')
{
$keyword_start = $i + 2;
$keyword_end = strpos($keywords, '"', $i + 2);
$extra_skip = 2;
}
else
{
$keyword_start = $i + 1;
$keyword_end = strpos($keywords, ' ', $i + 1);
$extra_skip = 0;
}
$target_array =& $plus_keywords;
break;
case '-':
if(substr($keywords, $i + 1, 1) == '"')
{
$keyword_start = $i + 2;
$keyword_end = strpos($keywords, '"', $i + 2);
$extra_skip = 2;
}
else
{
$keyword_start = $i + 1;
$keyword_end = strpos($keywords, ' ', $i + 1);
$extra_skip = 0;
}
$target_array =& $minus_keywords;
break;
case '"':
$keyword_start = $i + 1;
$keyword_end = strpos($keywords, '"', $i + 1);
$extra_skip = 1;
$target_array =& $normal_keywords;
break;
default:
$keyword_start = $i;
$keyword_end = strpos($keywords, ' ', $i + 1);
$target_array =& $normal_keywords;
}
if($keyword_end === false)
{
$keyword_end = strlen($keywords);
}
$keyword_length = $keyword_end - $keyword_start;
$keyword = substr($keywords, $keyword_start, $keyword_length);
if(strlen($keyword) >= $this->Application->ConfigValue('Search_MinKeyword_Length'))
{
$target_array[] = addcslashes($keyword, '"');
}
$i += $keyword_length + $extra_skip;
}
// preparing conditions
$normal_conditions = Array();
$plus_conditions = Array();
$minus_conditions = Array();
foreach($normal_keywords as $keyword)
{
$normal_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $field_list).' LIKE "%'.$keyword.'%"';
}
foreach($plus_keywords as $keyword)
{
$plus_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $field_list).' LIKE "%'.$keyword.'%"';
}
foreach($minus_keywords as $keyword)
{
foreach($field_list as $field)
{
$condition[] = $field.' NOT LIKE "%'.$keyword.'%" OR '.$field.' IS NULL';
}
$minus_conditions[] = '('.implode(') AND (', $condition).')';
}
// building where clause
if($normal_conditions)
{
$where_clause = '('.implode(') OR (', $normal_conditions).')';
}
else
{
$where_clause = '1';
}
if($plus_conditions)
{
$where_clause = '('.$where_clause.') AND ('.implode(') AND (', $plus_conditions).')';
}
if($minus_conditions)
{
$where_clause = '('.$where_clause.') AND ('.implode(') AND (', $minus_conditions).')';
}
$where_clause = $where_clause.' AND '.$product_table.'.Status=1';
if($this->Application->GetVar('Action') == 'm_simple_subsearch') // subsearch, In-portal
{
if( $event->getEventParam('ResultIds') )
{
$where_clause .= ' AND '.$product_table.'.ResourceId IN ('.implode(',', $event->specificParams['ResultIds']).')';
}
}
if( $event->MasterEvent && $event->MasterEvent->Name == 'OnListBuild' ) // subsearch, k4
{
if( $event->MasterEvent->getEventParam('ResultIds') )
{
$where_clause .= ' AND '.$product_table.'.ResourceId IN ('.implode(',', $event->MasterEvent->getEventParam('ResultIds')).')';
}
}
// building having clause
// making relevance clause
$positive_words = array_merge($normal_keywords, $plus_keywords);
$this->Application->StoreVar('highlight_keywords', serialize($positive_words));
$revelance_parts = Array();
reset($search_config);
foreach($field_list as $field)
{
$config_elem = each($search_config);
$weight = $search_config[$field]['Priority'];
$revelance_parts[] = 'IF('.$field.' LIKE "%'.implode(' ', $positive_words).'%", '.$weight_sum.', 0)';
foreach($positive_words as $keyword)
{
$revelance_parts[] = 'IF('.$field.' LIKE "%'.$keyword.'%", '.$config_elem['value']['Priority'].', 0)';
}
}
$rel_keywords = $this->Application->ConfigValue('SearchRel_DefaultKeyword_products') / 100;
$rel_pop = $this->Application->ConfigValue('SearchRel_DefaultPop_products') / 100;
$rel_rating = $this->Application->ConfigValue('SearchRel_DefaultRating_products') / 100;
$relevance_clause = '('.implode(' + ', $revelance_parts).') / '.$weight_sum.' * '.$rel_keywords;
$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
// building final search query
if( !$this->Application->GetVar('INPORTAL_ON') )
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); // erase old search table if clean k4 event
}
if($this->Conn->Query('SHOW TABLES LIKE "'.$search_table.'"'))
{
$select_intro = 'INSERT INTO '.$search_table.' (Relevance, ItemId, ResourceId, ItemType, EdPick) ';
}
else
{
$select_intro = 'CREATE TABLE '.$search_table.' AS ';
}
$sql = $select_intro.' SELECT '.$relevance_clause.' AS Relevance,
'.$product_table.'.ProductId AS ItemId,
'.$product_table.'.ResourceId,
11 AS ItemType,
'.$product_table.'.EditorsPick AS EdPick
FROM '.$object->TableName.'
'.implode(' ', $join_clauses).'
WHERE '.$where_clause.'
GROUP BY '.$product_table.'.ProductId';
$res = $this->Conn->Query($sql);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSubSearch(&$event)
{
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
if($this->Conn->Query($sql))
{
$sql = 'SELECT DISTINCT ResourceId FROM '.$search_table;
$ids = $this->Conn->GetCol($sql);
}
$event->setEventParam('ResultIds', $ids);
$event->CallSubEvent('OnSimpleSearch');
}
/**
* Enter description here...
*
* @param kEvent $event
* @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!!
*/
function OnAdvancedSearch(&$event)
{
$query_object =& $this->Application->recallObject('HTTPQuery');
if(!isset($query_object->Post['andor']))
{
return; // used when navigating by pages or changing sorting in search results
}
$this->Application->RemoveVar('keywords');
$this->Application->RemoveVar('Search_Keywords');
$sql = ' SELECT * FROM '.$this->Application->getUnitOption('confs', 'TableName').'
WHERE ModuleName="In-Commerce"
AND AdvancedSearch=1';
$search_config = $this->Conn->Query($sql);
$lang = $this->Application->GetVar('m_lang');
$object =& $event->getObject();
$object->SetPage(1);
$user_object =& $this->Application->recallObject('u');
$product_table = $this->Application->getUnitOption('p', 'TableName');
$keywords = $this->Application->GetVar('value');
$verbs = $this->Application->GetVar('verb');
$glues = $this->Application->GetVar('andor');
$and_conditions = Array();
$or_conditions = Array();
$and_having_conditions = Array();
$or_having_conditions = Array();
$join_clauses = Array();
$highlight_keywords = Array();
$relevance_parts = Array();
$condition_patterns = Array( 'any' => '%s LIKE %s',
'contains' => '%s LIKE %s',
'notcontains' => '(NOT (%1$s LIKE %2$s) OR %1$s IS NULL)',
'is' => '%s = %s',
'isnot' => '(%1$s != %2$s OR %1$s IS NULL)');
$alias_counter = 0;
$weight_sum = 0;
// processing fields and preparing conditions
foreach($search_config as $record)
{
$field = $record['FieldName'];
$join_clause = '';
$condition_mode = 'WHERE';
// field processing
$options = $object->getFieldOptions($field);
$local_table = TABLE_PREFIX.$record['TableName'];
$weight_sum += $record['Priority']; // counting weight sum; used when making relevance clause
// processing multilingual fields
if($options['formatter'] == 'kMultiLanguage')
{
$field_name = 'l'.$lang.'_'.$field;
}
else
{
$field_name = $field;
}
// processing fields from other tables
if($foreign_field = $record['ForeignField'])
{
$exploded = explode(':', $foreign_field, 2);
if($exploded[0] == 'CALC')
{
$user_groups = $user_object->GetDBField('PortalUserId') ?
implode(',', $this->Conn->GetCol(' SELECT GroupId
FROM '.TABLE_PREFIX.'UserGroup
WHERE PortalUserId='.$user_object->GetDBField('PortalUserId'))) : 0;
$field_name = str_replace('{PREFIX}', TABLE_PREFIX, $exploded[1]);
$join_clause = str_replace('{PREFIX}', TABLE_PREFIX, $record['JoinClause']);
$join_clause = str_replace('{USER_GROUPS}', $user_groups, $join_clause);
$join_clause = ' LEFT JOIN '.$join_clause;
$condition_mode = 'HAVING';
}
else
{
$exploded = explode('.', $foreign_field);
$foreign_table = TABLE_PREFIX.$exploded[0];
- if($search_config[$field]['CustomFieldId']) {
+ if($record['CustomFieldId']) {
$exploded[1] = 'l'.$lang.'_'.$exploded[1];
}
$alias_counter++;
$alias = 't'.$alias_counter;
$field_name = $alias.'.'.$exploded[1];
$join_clause = str_replace('{ForeignTable}', $alias, $record['JoinClause']);
$join_clause = str_replace('{LocalTable}', $product_table, $join_clause);
if($record['CustomFieldId'])
{
$join_clause .= ' AND '.$alias.'.CustomFieldId='.$record['CustomFieldId'];
}
$join_clause = ' LEFT JOIN '.$foreign_table.' '.$alias.'
ON '.$join_clause;
}
}
else
{
// processing fields from local table
$field_name = $local_table.'.'.$field_name;
}
$condition = '';
switch($record['FieldType'])
{
case 'text':
if( !$this->Application->GetVar('INPORTAL_ON') )
{
$keywords[$field] = unhtmlentities( $keywords[$field] );
}
if(strlen($keywords[$field]) >= $this->Application->ConfigValue('Search_MinKeyword_Length'))
{
$highlight_keywords[] = $keywords[$field];
if( in_array($verbs[$field], Array('any', 'contains', 'notcontains')) )
{
$keywords[$field] = '%'.strtr($keywords[$field], Array('%' => '\\%', '_' => '\\_')).'%';
}
$condition = sprintf( $condition_patterns[$verbs[$field]],
$field_name,
$this->Conn->qstr( $keywords[$field] ));
}
break;
case 'boolean':
if($keywords[$field] != -1)
{
$property_mappings = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
switch($field)
{
case 'HotItem':
$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
if($hot_limit_var)
{
$sql = 'SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName="'.$hot_limit_var.'"';
$hot_limit = (int)$this->Conn->GetOne($sql);
$condition = 'IF('.$product_table.'.HotItem = 2,
IF('.$product_table.'.Hits >= '.
$hot_limit.
', 1, 0), '.$product_table.'.HotItem) = '.$keywords[$field];
}
break;
case 'PopItem':
$votes2pop_var = getArrayValue($property_mappings, 'VotesToPop');
$rating2pop_var = getArrayValue($property_mappings, 'RatingToPop');
if($votes2pop_var && $rating2pop_var)
{
$condition = 'IF('.$product_table.'.PopItem = 2, IF('.$product_table.'.CachedVotesQty >= '.
$this->Application->ConfigValue($votes2pop_var).
' AND '.$product_table.'.CachedRating >= '.
$this->Application->ConfigValue($rating2pop_var).
', 1, 0), '.$product_table.'.PopItem) = '.$keywords[$field];
}
break;
case 'NewItem':
$new_days_var = getArrayValue($property_mappings, 'NewDays');
if($new_days_var)
{
$condition = 'IF('.$product_table.'.NewItem = 2,
IF('.$product_table.'.CreatedOn >= (UNIX_TIMESTAMP() - '.
$this->Application->ConfigValue($new_days_var).
'*3600*24), 1, 0), '.$product_table.'.NewItem) = '.$keywords[$field];
}
break;
case 'EditorsPick':
$condition = $product_table.'.EditorsPick = '.$keywords[$field];
break;
}
}
break;
case 'range':
$range_conditions = Array();
if($keywords[$field.'_from'] && !preg_match("/[^0-9]/i", $keywords[$field.'_from']))
{
$range_conditions[] = $field_name.' >= '.$keywords[$field.'_from'];
}
if($keywords[$field.'_to'] && !preg_match("/[^0-9]/i", $keywords[$field.'_to']))
{
$range_conditions[] = $field_name.' <= '.$keywords[$field.'_to'];
}
if($range_conditions)
{
$condition = implode(' AND ', $range_conditions);
}
break;
case 'date':
if($keywords[$field])
{
if( in_array($keywords[$field], Array('today', 'yesterday')) )
{
$current_time = getdate();
$day_begin = adodb_mktime(0, 0, 0, $current_time['mon'], $current_time['mday'], $current_time['year']);
$time_mapping = Array('today' => $day_begin, 'yesterday' => ($day_begin - 86400));
$min_time = $time_mapping[$keywords[$field]];
}
else
{
$time_mapping = Array( 'last_week' => 604800, 'last_month' => 2628000,
'last_3_months' => 7884000, 'last_6_months' => 15768000,
'last_year' => 31536000
);
$min_time = adodb_mktime() - $time_mapping[$keywords[$field]];
}
$condition = $field_name.' > '.$min_time;
}
break;
}
if($condition)
{
if($join_clause)
{
$join_clauses[] = $join_clause;
}
$relevance_parts[] = 'IF('.$condition.', '.$record['Priority'].', 0)';
if($glues[$field] == 1) // and
{
if($condition_mode == 'WHERE')
{
$and_conditions[] = $condition;
}
else
{
$and_having_conditions[] = $condition;
}
}
else // or
{
if($condition_mode == 'WHERE')
{
$or_conditions[] = $condition;
}
else
{
$or_having_conditions[] = $condition;
}
}
}
}
$this->Application->StoreVar('highlight_keywords', serialize($highlight_keywords));
// making relevance clause
if($relevance_parts)
{
$rel_keywords = $this->Application->ConfigValue('SearchRel_DefaultKeyword_products') / 100;
$rel_pop = $this->Application->ConfigValue('SearchRel_DefaultPop_products') / 100;
$rel_rating = $this->Application->ConfigValue('SearchRel_DefaultRating_products') / 100;
$relevance_clause = '('.implode(' + ', $relevance_parts).') / '.$weight_sum.' * '.$rel_keywords;
$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
}
else
{
$relevance_clause = '0';
}
// building having clause
if($or_having_conditions)
{
$and_having_conditions[] = '('.implode(' OR ', $or_having_conditions).')';
}
$having_clause = implode(' AND ', $and_having_conditions);
$having_clause = $having_clause ? ' HAVING '.$having_clause : '';
// building where clause
if($or_conditions)
{
$and_conditions[] = '('.implode(' OR ', $or_conditions).')';
}
// $and_conditions[] = $product_table.'.Status = 1';
$where_clause = implode(' AND ', $and_conditions);
if(!$where_clause)
{
if($having_clause)
{
$where_clause = '1';
}
else
{
$where_clause = '0';
$this->Application->SetVar('adv_search_error', 1);
}
}
$where_clause .= ' AND '.$product_table.'.Status = 1';
// building final search query
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table);
$sql = ' CREATE TABLE '.$search_table.'
SELECT '.$relevance_clause.' AS Relevance,
'.$product_table.'.ProductId AS ItemId,
'.$product_table.'.ResourceId AS ResourceId,
11 AS ItemType,
'.$product_table.'.EditorsPick AS EdPick
FROM '.$product_table.'
'.implode(' ', $join_clauses).'
WHERE '.$where_clause.'
GROUP BY '.$product_table.'.ProductId'.
$having_clause;
$res = $this->Conn->Query($sql);
}
/**
* Set's correct page for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetPagination(&$event)
{
// get PerPage (forced -> session -> config -> 10)
$per_page = $this->getPerPage($event);
$object =& $event->getObject();
$object->SetPerPage($per_page);
$this->Application->StoreVarDefault($event->getPrefixSpecial().'_Page', 1);
$page = $this->Application->GetVar($event->getPrefixSpecial().'_Page');
if (!$page)
{
$page = $this->Application->GetVar($event->getPrefixSpecial(true).'_Page');
}
if (!$page)
{
if( $this->Application->RewriteURLs() )
{
$page = $this->Application->GetVar($event->Prefix.'_Page');
if (!$page)
{
$page = $this->Application->RecallVar($event->Prefix.'_Page');
}
if($page) $this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
else
{
$page = $this->Application->RecallVar($event->getPrefixSpecial().'_Page');
}
}
else {
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
// $page = $this->Application->GetLinkedVar($event->getPrefixSpecial(true).'_Page', $event->getPrefixSpecial().'_Page');
if( !$event->getEventParam('skip_counting') )
{
$pages = $object->GetTotalPages();
if($page > $pages)
{
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', 1);
$page = 1;
}
}
/*$cur_per_page = $per_page;
$per_page = $event->getEventParam('per_page');
if ($per_page == 'list_next') {
$cur_page = $page;
$object =& $this->Application->recallObject($event->Prefix);
$object->SetPerPage(1);
$cur_item_index = $object->CurrentIndex;
$page = ($cur_page-1) * $cur_per_page + $cur_item_index + 1;
$object->SetPerPage(1);
}*/
$object->SetPage($page);
}
/* === RELATED TO IMPORT/EXPORT: BEGIN === */
/**
* Returns module folder
*
* @param kEvent $event
* @return string
*/
function getModuleFolder(&$event)
{
return $this->Application->getUnitOption($event->Prefix, 'ModuleFolder');
}
/**
* Shows export dialog
*
* @param kEvent $event
*/
function OnExport(&$event)
{
$selected_ids = $this->Application->GetVar('linklist');
$selected_cats_ids = $this->Application->GetVar('export_categories');
$this->Application->StoreVar($event->Prefix.'_export_ids', $selected_ids ? implode(',', $selected_ids) : '' );
$this->Application->StoreVar($event->Prefix.'_export_cats_ids', $selected_cats_ids);
$event->redirect = $this->getModuleFolder($event).'/export';
$redirect_params = Array( 'm_opener' => 'd',
'index_file' => 'index4.php',
$this->Prefix.'.export_event' => 'OnNew',
'pass' => 'all,'.$this->Prefix.'.export');
$event->setRedirectParams($redirect_params);
}
/**
* Export form validation & processing
*
* @param kEvent $event
*/
function OnExportBegin(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if (!$items_info)
{
$items_info = unserialize( $this->Application->RecallVar($event->getPrefixSpecial().'_ItemsInfo') );
}
list($item_id, $field_values) = each($items_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$object->setID($item_id);
$this->setRequiredFields($event);
$export_object =& $this->Application->recallObject('CatItemExportHelper');
// save export/import options
if ($event->Special == 'export')
{
$export_ids = $this->Application->RecallVar($event->Prefix.'_export_ids');
$export_cats_ids = $this->Application->RecallVar($event->Prefix.'_export_cats_ids');
// used for multistep export
$field_values['export_ids'] = $export_ids ? explode(',', $export_ids) : false;
$field_values['export_cats_ids'] = $export_cats_ids ? explode(',', $export_cats_ids) : Array( $this->Application->GetVar('m_cat_id') );
}
$field_values['ExportColumns'] = $field_values['ExportColumns'] ? explode('|', substr($field_values['ExportColumns'], 1, -1) ) : Array();
$field_values['start_from'] = 0;
$this->Application->StoreVar($event->getPrefixSpecial().'_options', serialize($field_values) );
if( $export_object->verifyOptions($event) )
{
$this->doExport($event);
}
else
{
$event->status = erFAIL;
$event->redirect = false;
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function doExport(&$event)
{
if ($event->Name == 'OnExportBegin')
{
$done_percent = 0;
}
else {
$export_options = unserialize($this->Application->RecallVar($event->getPrefixSpecial().'_options'));
$done_percent = round($export_options['start_from'] * 100 / $export_options['total_records'], 0);
}
$block_params = Array( 'name' => $this->getModuleFolder($event).'/'.$event->Special.'_progress',
'percent_done' => $done_percent,
'percent_left' => 100 - $done_percent);
$this->Application->InitParser();
$this->Application->setUnitOption($event->Prefix, 'AutoLoad', false);
echo $this->Application->ParseBlock($block_params);
flush();
$export_object =& $this->Application->recallObject('CatItemExportHelper');
$action_method = 'perform'.ucfirst($event->Special);
$field_values = $export_object->$action_method($event);
if ($field_values['start_from'] == $field_values['total_records'])
{
if ($event->Special == 'import') {
$this->Application->StoreVar('PermCache_UpdateRequired', 1);
$event->SetRedirectParam('index_file', 'category/category_maint.php');
}
else {
$event->redirect = $this->getModuleFolder($event).'/'.$event->Special.'_finish';
}
}
else {
$event->redirect = $this->getModuleFolder($event).'/'.$event->Special.'_progress';
$redirect_params = Array($event->getPrefixSpecial().'_event' => 'OnExportProgress', 'pass' => 'm,'.$event->getPrefixSpecial());
$event->setRedirectParams($redirect_params);
}
}
/**
* Next export steps
*
* @param kEvent $event
*/
function OnExportProgress(&$event)
{
$this->doExport($event);
}
/**
* Sets correct available & export fields
*
* @param kEvent $event
*/
function prepareExportColumns(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$available_columns = Array();
// category field (mixed)
$available_columns['__CATEGORY__CategoryPath'] = 'CategoryPath';
if ($event->Special == 'import') {
// category field (separated fields)
$max_level = $this->Application->ConfigValue('MaxImportCategoryLevels');
$i = 0;
while ($i < $max_level) {
$available_columns['__CATEGORY__Category'.($i + 1)] = 'Category'.($i + 1);
$i++;
}
}
// db fields
$fields = array_keys($object->Fields);
foreach ($fields as $field_name)
{
if (!$object->SkipField($field_name))
{
$available_columns[$field_name] = $field_name;
}
}
// custom fields
$fields = array_keys($object->CustomFields);
foreach ($fields as $field_name)
{
$available_columns['__CUSTOM__'.$field_name] = $field_name;
}
// columns already in use
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info)
{
list($item_id, $field_values) = each($items_info);
$export_keys = $field_values['ExportColumns'];
$export_keys = $export_keys ? explode('|', substr($export_keys, 1, -1) ) : Array();
}
else {
$export_keys = Array();
}
$export_columns = Array();
foreach ($export_keys as $field_key)
{
$field_name = $this->getExportField($field_key);
$export_columns[$field_key] = $field_name;
unset($available_columns[$field_key]);
}
$options = $object->GetFieldOptions('ExportColumns');
$options['options'] = $export_columns;
$object->SetFieldOptions('ExportColumns', $options);
$options = $object->GetFieldOptions('AvailableColumns');
$options['options'] = $available_columns;
$object->SetFieldOptions('AvailableColumns', $options);
if ($event->Special == 'import')
{
$import_filenames = Array();
if ($folder_handle = opendir(EXPORT_PATH)) {
while (false !== ($file = readdir($folder_handle))) {
if ( substr($file, 0, 1) == '.' || strtolower($file) == 'cvs' || strtolower($file) == 'dummy' || filesize(EXPORT_PATH.'/'.$file) == 0) continue;
$file_size = formatSize( filesize(EXPORT_PATH.'/'.$file) );
$import_filenames[$file] = $file.' ('.$file_size.')';
}
closedir($folder_handle);
}
$options = $object->GetFieldOptions('ImportLocalFilename');
$options['options'] = $import_filenames;
$object->SetFieldOptions('ImportLocalFilename', $options);
}
}
// ImportLocalFilename
function getExportField($field_key)
{
$prepends = Array('__CUSTOM__', '__CATEGORY__');
foreach ($prepends as $prepend)
{
if (substr($field_key, 0, strlen($prepend) ) == $prepend)
{
$field_key = substr($field_key, strlen($prepend), strlen($field_key) );
break;
}
}
return $field_key;
}
/**
* Shows export dialog
*
* @param kEvent $event
*/
function OnImport(&$event)
{
$event->redirect = $this->getModuleFolder($event).'/import';
$redirect_params = Array( 'm_opener' => 'd',
'index_file' => 'index4.php',
$this->Prefix.'.import_event' => 'OnNew',
'pass' => 'all,'.$this->Prefix.'.import');
$event->setRedirectParams($redirect_params);
}
/**
* Prepares item for import/export operations
*
* @param kEvent $event
*/
function OnNew(&$event)
{
parent::OnNew($event);
if ($event->Special != 'import' && $event->Special != 'export') return ;
$this->setRequiredFields($event);
}
/**
* set required fields based on import or export params
*
* @param kEvent $event
*/
function setRequiredFields(&$event)
{
$required_fields['common'] = Array('FieldsSeparatedBy', 'FieldsEnclosedBy', 'LineEndings', 'CategoryFormat');
$required_fields['export'] = Array('ExportFormat', 'ExportFilename','ExportColumns');
$required_fields['import'] = Array('FieldTitles', 'ImportSource', 'CheckDuplicatesMethod'); // ImportFilename, ImportLocalFilename
$object =& $event->getObject();
if ($event->Special == 'import')
{
$import_source = Array(1 => 'ImportFilename', 2 => 'ImportLocalFilename');
$used_field = $import_source[ $object->GetDBField('ImportSource') ];
$required_fields[$event->Special][] = $used_field;
$object->Fields[$used_field]['error_field'] = 'ImportSource';
if ($object->GetDBField('FieldTitles') == 2) $required_fields[$event->Special][] = 'ExportColumns'; // manual field titles
}
$required_fields = array_merge($required_fields['common'], $required_fields[$event->Special]);
foreach ($required_fields as $required_field) {
$object->setRequired($required_field, true);
}
}
/**
* Saves selected category as new import category
*
* @param kEvent $event
*/
function OnSelectItems(&$event)
{
$items_info = $this->Application->GetVar('c');
if ($items_info)
{
$selected_categories = array_keys($items_info);
$cat_id = array_shift($selected_categories);
$sql = 'SELECT CategoryId FROM '.TABLE_PREFIX.'Category WHERE ResourceId = '.$cat_id;
$cat_id = $this->Conn->GetOne($sql);
}
else {
$cat_id = 0;
}
$this->Application->StoreVar('ImportCategory', $cat_id);
$this->Application->StoreVar($event->getPrefixSpecial().'_ForceNotValid', 1); // not to loose import/export values on form refresh
$this->Application->SetVar($event->getPrefixSpecial().'_id', 0);
$this->Application->SetVar($event->getPrefixSpecial().'_event', 'OnExportBegin');
$passed = $this->Application->GetVar('passed');
$this->Application->SetVar('passed', $passed.','.$event->getPrefixSpecial());
$event->setEventParam('pass_events', true);
$this->finalizePopup($event, null, $this->getModuleFolder($event).'/'.$event->Special);
}
/**
* Saves Import/Export settings to session
*
* @param kEvent $event
*/
function OnSaveSettings(&$event)
{
$event->redirect = false;
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info) {
$this->Application->StoreVar($event->getPrefixSpecial().'_ItemsInfo', serialize($items_info));
}
}
/* === RELATED TO IMPORT/EXPORT: END === */
}
?>
\ No newline at end of file
Property changes on: trunk/kernel/units/general/cat_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.20
\ No newline at end of property
+1.21
\ No newline at end of property
Index: trunk/core/kernel/processors/main_processor.php
===================================================================
--- trunk/core/kernel/processors/main_processor.php (revision 3590)
+++ trunk/core/kernel/processors/main_processor.php (revision 3591)
@@ -1,813 +1,823 @@
<?php
class kMainTagProcessor extends TagProcessor {
function Init($prefix,$special)
{
parent::Init($prefix,$special);
$actions =& $this->Application->recallObject('kActions');
$actions->Set('t', $this->Application->GetVar('t'));
$actions->Set('sid', $this->Application->GetSID());
$actions->Set('m_opener', $this->Application->GetVar('m_opener') );
}
/**
* Used to handle calls where tag name
* match with existing php function name
*
* @param Tag $tag
* @return string
*/
function ProcessTag(&$tag)
{
if ($tag->Tag=='include') $tag->Tag='MyInclude';
return parent::ProcessTag($tag);
}
/**
* Creates <base href ..> HTML tag for all templates
* affects future css, js files and href params of links
*
* @return string
* @access public
*/
function Base_Ref()
{
$url = $this->Application->BaseURL().substr(THEMES_PATH,1).'/';
return '<base href="'.$url.'" />';
}
/**
* Returns base url for web-site
*
* @return string
* @access public
*/
function BaseURL()
{
return $this->Application->BaseURL();
}
function TemplatesBase($params)
{
return $this->Application->BaseURL().THEMES_PATH;
}
function ProjectBase($params)
{
return $this->Application->BaseURL();
}
/*function Base($params)
{
return $this->Application->BaseURL().$params['add'];
}*/
/**
* Used to create link to any template.
* use "pass" paramter if "t" tag to specify
* prefix & special of object to be represented
* in resulting url
*
* @param Array $params
* @return string
* @access public
*/
function T($params)
{
//by default link to current template
$t = $this->SelectParam($params, 't,template');
unset($params['t']);
unset($params['template']);
$prefix=isset($params['prefix']) ? $params['prefix'] : ''; unset($params['prefix']);
$index_file = isset($params['index_file']) ? $params['index_file'] : null; unset($params['index_file']);
return $this->Application->HREF($t, $prefix, $params, $index_file);
}
function Link($params)
{
if (isset($params['template'])) {
$params['t'] = $params['template'];
unset($params['template']);
}
if (!isset($params['pass']) && !isset($params['no_pass'])) $params['pass'] = 'm';
if (isset($params['no_pass'])) unset($params['no_pass']);
if( $this->Application->GetVar('admin') ) $params['admin'] = 1;
return $this->T($params);
}
function Env($params)
{
$t = $params['template'];
unset($params['template']);
return $this->Application->BuildEnv($t, $params, 'm', null, false);
}
function FormAction($params)
{
return $this->Application->ProcessParsedTag('m', 't', Array( 'pass'=>'all,m' ) );
}
/*// NEEDS TEST
function Config($params)
{
return $this->Application->ConfigOption($params['var']);
}
function Object($params)
{
$name = $params['name'];
$method = $params['method'];
$tmp =& $this->Application->recallObject($name);
if ($tmp != null) {
if (method_exists($tmp, $method))
return $tmp->$method($params);
else
echo "Method $method does not exist in object ".get_class($tmp)." named $name<br>";
}
else
echo "Object $name does not exist in the appliaction<br>";
}*/
/**
* Tag, that always returns true.
* For parser testing purposes
*
* @param Array $params
* @return bool
* @access public
*/
function True($params)
{
return true;
}
/**
* Tag, that always returns false.
* For parser testing purposes
*
* @param Array $params
* @return bool
* @access public
*/
function False($params)
{
return false;
}
/**
* Returns block parameter by name
*
* @param Array $params
* @return stirng
* @access public
*/
function Param($params)
{
//$parser =& $this->Application->recallObject('TemplateParser');
$res = $this->Application->Parser->GetParam($params['name']);
if ($res === false) $res = '';
if (isset($params['plus']))
$res += $params['plus'];
return $res;
}
/**
* Compares block parameter with value specified
*
* @param Array $params
* @return bool
* @access public
*/
function ParamEquals($params)
{
//$parser =& $this->Application->recallObject('TemplateParser');
$name = $this->SelectParam($params, 'name,var,param');
$value = $params['value'];
return ($this->Application->Parser->GetParam($name) == $value);
}
/*function PHP_Self($params)
{
return $HTTP_SERVER_VARS['PHP_SELF'];
}
*/
/**
* Returns session variable value by name
*
* @param Array $params
* @return string
* @access public
*/
function Recall($params)
{
$ret = $this->Application->RecallVar( $this->SelectParam($params,'name,var,param') );
$ret = ($ret === false && isset($params['no_null'])) ? '' : $ret;
if( getArrayValue($params,'special') || getArrayValue($params,'htmlchars')) $ret = htmlspecialchars($ret);
if ( getArrayValue($params, 'urlencode') ) $ret = urlencode($ret);
return $ret;
}
// bad style to store something from template to session !!! (by Alex)
// Used here only to test how session works, nothing more
function Store($params)
{
//echo"Store $params[name]<br>";
$name = $params['name'];
$value = $params['value'];
$this->Application->StoreVar($name,$value);
}
/**
* Sets application variable value(-s)
*
* @param Array $params
* @access public
*/
function Set($params)
{
foreach ($params as $param => $value) {
$this->Application->SetVar($param, $value);
}
}
/**
* Increment application variable
* specified by number specified
*
* @param Array $params
* @access public
*/
function Inc($params)
{
$this->Application->SetVar($params['param'], $this->Application->GetVar($params['param']) + $params['by']);
}
/**
* Retrieves application variable
* value by name
*
* @param Array $params
* @return string
* @access public
*/
function Get($params)
{
$ret = $this->Application->GetVar($this->SelectParam($params, 'name,var,param'), EMPTY_ON_NULL);
return getArrayValue($params, 'htmlchars') ? htmlspecialchars($ret) : $ret;
}
/**
* Retrieves application constant
* value by name
*
* @param Array $params
* @return string
* @access public
*/
function GetConst($params)
{
return defined($this->SelectParam($params, 'name,const')) ? constant($this->SelectParam($params, 'name,const,param')) : '';
}
/**
* Retrieves configuration variable value by name
*
* @param Array $params
* @return string
* @access public
*/
function GetConfig($params)
{
$config_name = $this->SelectParam($params, 'name,var');
$ret = $this->Application->ConfigValue($config_name);
if( getArrayValue($params, 'escape') ) $ret = addslashes($ret);
return $ret;
}
function ConfigEquals($params)
{
$option = $this->SelectParam($params, 'name,option,var');
return $this->Application->ConfigValue($option) == getArrayValue($params, 'value');
}
/**
* Creates all hidden fields
* needed for kernel_form
*
* @param Array $params
* @return string
* @access public
*/
function DumpSystemInfo($params)
{
$actions =& $this->Application->recallObject('kActions');
$actions->Set('t', $this->Application->GetVar('t') );
$params = $actions->GetParams();
$o='';
foreach ($params AS $name => $val)
{
$o .= "<input type='hidden' name='$name' id='$name' value='$val'>\n";
}
return $o;
}
function GetFormHiddens($params)
{
$sid = $this->Application->GetSID();
$t = $this->SelectParam($params, 'template,t');
unset($params['template']);
$env = $this->Application->BuildEnv($t, $params, 'm', null, false);
$o = '';
if ( $this->Application->RewriteURLs() )
{
$session =& $this->Application->recallObject('Session');
if ($session->NeedQueryString()) {
$o .= "<input type='hidden' name='sid' id='sid' value='$sid'>\n";
}
}
else {
$o .= "<input type='hidden' name='env' id='env' value='$env'>\n";
}
return $o;
}
function Odd_Even($params)
{
$odd = $params['odd'];
$even = $params['even'];
if (!isset($params['var'])) {
$var = 'odd_even';
}
else {
$var = $params['var'];
}
if ($this->Application->GetVar($var) == 'even') {
if (!isset($params['readonly']) || !$params['readonly']) {
$this->Application->SetVar($var, 'odd');
}
return $even;
}
else {
if (!isset($params['readonly']) || !$params['readonly']) {
$this->Application->SetVar($var, 'even');
}
return $odd;
}
}
/**
* Returns phrase translation by name
*
* @param Array $params
* @return string
* @access public
*/
function Phrase($params)
{
// m:phrase name="phrase_name" default="Tr-alala" updated="2004-01-29 12:49"
if (array_key_exists('default', $params)) return $params['default']; //backward compatibility
return $this->Application->Phrase($this->SelectParam($params, 'label,name,title'));
}
// for tabs
function is_active($params)
{
$test_templ = $this->SelectParam($params, 'templ,template,t');
if ( !getArrayValue($params,'allow_empty') )
{
$if_true=getArrayValue($params,'true') ? $params['true'] : 1;
$if_false=getArrayValue($params,'false') ? $params['false'] : 0;
}
else
{
$if_true=$params['true'];
$if_false=$params['false'];
}
if ( preg_match("/^".str_replace('/', '\/', $test_templ)."/", $this->Application->GetVar('t'))) {
return $if_true;
}
else {
return $if_false;
}
}
function IsNotActive($params)
{
return !$this->is_active($params);
}
function IsActive($params)
{
return $this->is_active($params);
}
function is_t_active($params)
{
return $this->is_active($params);
}
function CurrentTemplate($params)
{
return $this->is_active($params);
}
/**
* Checks if session variable
* specified by name value match
* value passed as parameter
*
* @param Array $params
* @return string
* @access public
*/
function RecallEquals($params)
{
$name = $params['var'];
$value = $params['value'];
return ($this->Application->RecallVar($name) == $value);
}
/**
* Checks if application variable
* specified by name value match
* value passed as parameter
*
* @param Array $params
* @return bool
* @access public
*/
function GetEquals($params)
{
$name = $this->SelectParam($params, 'var,name,param');
$value = $params['value'];
if ($this->Application->GetVar($name) == $value) {
return 1;
}
}
/**
* Includes template
* and returns it's
* parsed version
*
* @param Array $params
* @return string
* @access public
*/
function MyInclude($params)
{
$BlockParser =& $this->Application->makeClass('TemplateParser');
$BlockParser->SetParams($params);
$parser =& $this->Application->Parser;
$this->Application->Parser =& $BlockParser;
$t = $this->SelectParam($params, 't,template,block,name');
$t = eregi_replace("\.tpl$", '', $t);
$templates_cache =& $this->Application->recallObject('TemplatesCache');
$res = $BlockParser->Parse( $templates_cache->GetTemplateBody($t), $t );
if ( !$BlockParser->DataExists && (isset($params['data_exists']) || isset($params['block_no_data'])) ) {
if ($block_no_data = getArrayValue($params, 'block_no_data')) {
$res = $BlockParser->Parse(
$templates_cache->GetTemplateBody($block_no_data, $silent),
$t
);
}
else {
$res = '';
}
}
$this->Application->Parser =& $parser;
$this->Application->Parser->DataExists = $this->Application->Parser->DataExists || $BlockParser->DataExists;
return $res;
}
/*function Kernel_Scripts($params)
{
return '<script type="text/javascript" src="'.PROTOCOL.SERVER_NAME.BASE_PATH.'/kernel3/js/grid.js"></script>';
}*/
/*function GetUserPermission($params)
{
// echo"GetUserPermission $params[name]";
if ($this->Application->RecallVar('user_type') == 1)
return 1;
else {
$perm_name = $params[name];
$aPermissions = unserialize($this->Application->RecallVar('user_permissions'));
if ($aPermissions)
return $aPermissions[$perm_name];
}
}*/
/**
* Set's parser block param value
*
* @param Array $params
* @access public
*/
function AddParam($params)
{
$parser =& $this->Application->Parser; // recallObject('TemplateParser');
foreach ($params as $param => $value) {
$this->Application->SetVar($param, $value);
$parser->SetParam($param, $value);
$parser->AddParam('/\$'.$param.'/', $value);
}
}
/*function ParseToVar($params)
{
$var = $params['var'];
$tagdata = $params['tag'];
$parser =& $this->Application->Parser; //recallObject('TemplateParser');
$res = $this->Application->ProcessTag($tagdata);
$parser->SetParam($var, $res);
$parser->AddParam('/\$'.$var.'/', $res);
return '';
}*/
/*function TagNotEmpty($params)
{
$tagdata = $params['tag'];
$res = $this->Application->ProcessTag($tagdata);
return $res != '';
}*/
/*function TagEmpty($params)
{
return !$this->TagNotEmpty($params);
}*/
/**
* Parses block and returns result
*
* @param Array $params
* @return string
* @access public
*/
function ParseBlock($params)
{
$parser =& $this->Application->Parser; // recallObject('TemplateParser');
return $parser->ParseBlock($params);
}
function RenderElement($params)
{
return $this->ParseBlock($params);
}
/**
* Checks if debug mode is on
*
* @return bool
* @access public
*/
function IsDebugMode()
{
return $this->Application->isDebugMode();
}
function MassParse($params)
{
$qty = $params['qty'];
$block = $params['block'];
$mode = $params['mode'];
$o = '';
if ($mode == 'func') {
$func = create_function('$params', '
$o = \'<tr>\';
$o.= \'<td>a\'.$params[\'param1\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param2\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param3\'].\'</td>\';
$o.= \'<td>a\'.$params[\'param4\'].\'</td>\';
$o.= \'</tr>\';
return $o;
');
for ($i=1; $i<$qty; $i++) {
$block_params['param1'] = rand(1, 10000);
$block_params['param2'] = rand(1, 10000);
$block_params['param3'] = rand(1, 10000);
$block_params['param4'] = rand(1, 10000);
$o .= $func($block_params);
}
return $o;
}
$block_params['name'] = $block;
for ($i=0; $i<$qty; $i++) {
$block_params['param1'] = rand(1, 10000);
$block_params['param2'] = rand(1, 10000);
$block_params['param3'] = rand(1, 10000);
$block_params['param4'] = rand(1, 10000);
$block_params['passed'] = $params['passed'];
$block_params['prefix'] = 'm';
$o.= $this->Application->ParseBlock($block_params, 1);
}
return $o;
}
function AfterScript($params)
{
$after_script = $this->Application->GetVar('after_script');
if ( $after_script ) {
return '<script type="text/javascript">'.$after_script.'</script>';
}
return '';
}
function LoggedIn($params)
{
return $this->Application->LoggedIn();
}
/**
* Checks if user is logged in and if not redirects it to template passed
*
* @param Array $params
*/
function RequireLogin($params)
{
if($permission_groups = getArrayValue($params, 'permissions'))
{
$permission_groups = explode('|', $permission_groups);
$group_has_permission = false;
foreach($permission_groups as $permission_group)
{
$permissions = explode(',', $permission_group);
$has_permission = true;
foreach($permissions as $permission)
{
$has_permission = $has_permission && $this->Application->CheckPermission($permission);
}
$group_has_permission = $group_has_permission || $has_permission;
if($group_has_permission)
{
return;
}
}
if( !$this->Application->LoggedIn() )
{
$t = $this->Application->GetVar('t');
$this->Application->Redirect( $params['login_template'], Array('next_template'=>$t) );
}
else
{
$this->Application->Redirect( $params['no_permissions_template'] );
}
}
$condition = getArrayValue($params,'condition');
if(!$condition)
{
$condition = true;
}
else
{
if( substr($condition,0,1) == '!' )
{
$condition = !$this->Application->ConfigValue( substr($condition,1) );
}
else
{
$condition = $this->Application->ConfigValue($condition);
}
+ }
+ $group = $this->SelectParam($params, 'group');
+ $group_access = true;
+ if ($group) {
+ $conn =& $this->Application->DB;
+ $group_id = $conn->GetOne('SELECT GroupId FROM '.TABLE_PREFIX.'PortalGroup WHERE Name = '.$conn->qstr($group));
+ if ($group_id) {
+ $groups = explode(',', $this->Application->RecallVar('UserGroups'));
+ $group_access = in_array($group_id, $groups);
+ }
}
- if( !$this->Application->LoggedIn() && $condition )
+ if( (!$this->Application->LoggedIn() || !$group_access) && $condition )
{
$t = $this->Application->GetVar('t');
$this->Application->Redirect( $params['login_template'], Array('next_template'=>$t) );
}
}
/**
* Checks if SSL is on and redirects to SSL URL if needed
* If SSL_URL is not defined in config - the tag does not do anything
* If for_logged_in_only="1" exits if user is not logged in.
* If called without params forces https right away. If called with by_config="1" checks the
* Require SSL setting from General Config and if it is ON forces https
*
* @param unknown_type $params
*/
function CheckSSL($params)
{
$ssl = $this->Application->ConfigValue('SSL_URL');
if (!$ssl) return; //SSL URL is not set - no way to require SSL
$require = false;
if ($params['mode'] == 'required') {
$require = true;
if (isset($params['for_logged_in_only']) && $params['for_logged_in_only'] && !$this->Application->LoggedIn()) {
$require = false;
}
if (isset($params['condition'])) {
if (!$this->Application->ConfigValue($params['condition'])) {
$require = false;
}
}
}
-
+
$http_query =& $this->Application->recallObject('HTTPQuery');
$pass = $http_query->getRedirectParams();
if ($require) {
if (PROTOCOL == 'https://') {
$this->Application->SetVar('__KEEP_SSL__', 1);
return;
}
$this->Application->Redirect('', array_merge_recursive2($pass, Array('__SSL__' => 1)));
}
else {
if (PROTOCOL == 'https://' && $this->Application->ConfigValue('Force_HTTP_When_SSL_Not_Required')) {
if ($this->Application->GetVar('__KEEP_SSL__')) return;
$this->Application->Redirect('', array_merge_recursive2($pass, Array('__SSL__' => 0)));
}
}
}
function SaveReturnScript($params)
{
// admin/save_redirect.php?do=
$url = str_replace($this->Application->BaseURL(), '', $this->T($params) );
$url = explode('?', $url, 2);
$url = 'save_redirect.php?'.$url[1].'&do='.$url[0];
$this->Application->StoreVar('ReturnScript', $url);
}
function ConstOn($params)
{
$name = $this->SelectParam($params,'name,const');
return $this->Application->isDebugMode() && dbg_ConstOn($name);
}
function SetDefaultCategory($params)
{
$module_name = $params['module'];
$module =& $this->Application->recallObject('mod.'.$module_name);
$this->Application->SetVar('m_cat_id', $module->GetDBField('RootCat') );
}
/*
function Login($params)
{
$user_prefix = 'users';
$this->parser->registerprefix($user_prefix);
$user_class = $this->parser->processors[$user_prefix]->item_class;
$candidate = new $user_class(NULL, $this->parser->processors[$user_prefix]);
//print_pre($this->Session->Property);
$special = array_shift($params);
//echo"$special<br>";
$candidate_id = $candidate->Login($this->Session->GetProperty('username'), $this->Session->GetProperty('password'), $special);
if ($candidate_id !== false) {
$this->Session->SetField('user_id', $candidate_id);
$this->Session->Update();
$this->Session->AfterLogin();
$this->parser->register_prefix('m');
$template = array_shift($params);
if ($template == '') $template = 'index';
$location = $this->parser->do_process_tag('m', 't', Array($template));
header("Location: $location");
exit;
}
elseif ($this->Session->GetProperty('username') != '') {
$this->Session->SetProperty('login_error', 'Incorrect username or password');
}
}
*/
}
?>
Property changes on: trunk/core/kernel/processors/main_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.29
\ No newline at end of property
+1.30
\ No newline at end of property
Index: trunk/core/units/categories/categories_tag_processor.php
===================================================================
--- trunk/core/units/categories/categories_tag_processor.php (revision 3590)
+++ trunk/core/units/categories/categories_tag_processor.php (revision 3591)
@@ -1,282 +1,290 @@
<?php
class CategoriesTagProcessor extends kDBTagProcessor {
function &GetList($params)
{
$special = $this->BuildListSpecial($params);
$prefix_special = $this->Prefix.'.'.$special;
$this->Special = $special;
$params['skip_counting'] = true;
$list =& $this->Application->recallObject( $prefix_special, $this->Prefix.'_List',$params);
// $list->clearFilters();
// $list->addFilter('parent_filter', 'ParentId = '.$parent_cat_id, WHERE_FILTER, FLT_SYSTEM);
//unset($params['skip_counting']);
$this->Application->HandleEvent($event, $prefix_special.':SetPagination', $params );
$list->Query();
return $list;
}
function SubCatCount($params)
{
$cat_object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$sql = ' SELECT COUNT(*) - 1
FROM '.$cat_object->TableName.'
WHERE ParentPath LIKE "'.$cat_object->GetDBField('ParentPath').'%"';
return $this->Conn->GetOne($sql);
}
function IsNew($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$ret = $object->GetDBField('IsNew') ? 1 : 0;
return $ret;
}
function IsPick($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$ret = $object->GetDBField('EditorsPick') ? 1 : 0;
return $ret;
}
function ItemIcon($params)
{
$object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params);
$status = $object->GetDBField('Status');
if($status == 1)
{
$ret = $object->GetDBField('IsNew') ? 'icon16_cat_new.gif' : 'icon16_cat.gif';
}
else
{
$ret = $status ? 'icon16_cat_pending.gif' : 'icon16_cat_disabled.gif';
}
return $ret;
}
function ItemCount($params)
{
$cat_object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params);
$ci_table = $this->Application->getUnitOption('ci','TableName');
$sql = ' SELECT COUNT(*)
FROM '.$cat_object->TableName.' c
LEFT JOIN '.$ci_table.' ci
ON c.CategoryId=ci.CategoryId
WHERE c.ParentPath LIKE "'.$cat_object->GetDBField('ParentPath').'%"
AND NOT (ci.CategoryId IS NULL)';
return $this->Conn->GetOne($sql);
}
function ListCategories($params)
{
return $this->PrintList2($params);
}
function RootCategoryName($params)
{
$root_phrase = $this->Application->ConfigValue('Root_Name');
$ret = $this->Application->Phrase($root_phrase);
return $ret;
}
function CheckModuleRoot($params)
{
$module_name = getArrayValue($params, 'module') ? $params['module'] : 'In-Commerce';
$module = $this->Application->recallObject('mod.'.$module_name);
$module_root_cat = $module->GetDBField('RootCat');
- if ($this->Application->GetVar('m_cat_id') == $module_root_cat) {
+ $additional_cats = $this->SelectParam($params, 'add_cats');
+ if ($additional_cats) {
+ $additional_cats = explode(',', $additional_cats);
+ }
+ else {
+ $additional_cats = array();
+ }
+
+ if ($this->Application->GetVar('m_cat_id') == $module_root_cat || in_array($this->Application->GetVar('m_cat_id'), $additional_cats)) {
$home_template = getArrayValue($params, 'home_template');
if (!$home_template) return;
$this->Application->Redirect($home_template, Array('pass'=>'all'));
};
}
function CategoryPath($params)
{
$module_name = getArrayValue($params, 'module') ? $params['module'] : 'In-Commerce';
$module = $this->Application->recallObject('mod.'.$module_name);
$module_root_cat = $module->GetDBField('RootCat');
$block_params['current'] = 0;
$block_params['separator'] = $params['separator'];
if(!isset($params['cat_id']))
{
$params['cat_id'] = getArrayValue($params, 'cat_id') ? $params['cat_id'] : $this->Application->GetVar('m_cat_id');
$block_params['current'] = 1;
}
$product_id = $this->Application->GetVar('p_id');
if ($product_id) {
$block_params['current'] = 0;
}
$block_params['is_module_root'] = ($params['cat_id'] == $module_root_cat) ? 1 : 0;
if($params['cat_id'] == 0)
{
$block_params['name'] = $this->SelectParam($params, 'root_cat_render_as,block_root_cat,rootcatblock');
return $this->Application->ParseBlock($block_params);
}
else
{
$block_params['name'] = $this->SelectParam($params,'render_as,block');
// $cat_object = &$this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix.'_List' );
$sql = 'SELECT CategoryId, ParentId, Name FROM '.$this->Application->getUnitOption($this->Prefix, 'TableName').'
WHERE CategoryId='.$params['cat_id'];
$res = $this->Conn->GetRow($sql);
$block_params['cat_name'] = $res['Name'];
$block_params['cat_id'] = $res['CategoryId'];
$parent_params = $params;
$parent_params['cat_id'] = $res['ParentId'];
// which block to parse as current ?
if ($block_params['is_module_root'] == 1) { // module root
$block_params['name'] = $this->SelectParam($params, 'module_root_render_as,block_module_root,rootmoduleblock');
}
if ($block_params['current'] == 1) { // current cat (label)
$block_params['name'] = $this->SelectParam($params, 'current_render_as,block_current,currentblock');
}
$this->Application->SetVar($this->Prefix.'_id', $res['CategoryId']);
$current_cat = $this->Application->ParseBlock($block_params, 1);
$this->Application->SetVar($this->Prefix.'_id', $res['ParentId']);
$parent_cat = $this->CategoryPath($parent_params);
return $parent_cat.$current_cat;
}
}
function CurrentCategoryName($params){
$cat_object = &$this->Application->recallObject( $this->getPrefixSpecial(), $this->Prefix.'_List' );
$cat_id = $this->Application->GetVar("m_cat_id");
$sql = 'SELECT Name FROM '.$cat_object->TableName.' WHERE CategoryId='.$cat_id;
return $this->Conn->GetOne($sql);
}
function InitMainPrefix($params)
{
if($main_prefix = $this->Application->GetVar('main_prefix'))
{
$this->Application->StoreVar('selector_main_prefix', $main_prefix);
}
}
function CategoryLink($params)
{
// 'p_id'=>'0', ??
$params = array_merge(array('pass'=>'m'), $params);
$cat_id = getArrayValue($params,'cat_id');
if ($cat_id === false) {
// $cat_id = $this->Application->Parser->GetParam('cat_id');
$cat_id = $this->Application->GetVar($this->Prefix.'_id');
}
if($cat_id == 'Root')
{
$object =& $this->Application->recallObject('mod.'.$params['module']);
$params['m_cat_id'] = $object->GetDBField('RootCat');
unset($params['module']);
}
else{
$params['m_cat_id'] = $cat_id;
}
unset($params['cat_id']);
$main_processor =& $this->Application->recallObject('m_TagProcessor');
return $main_processor->T($params);
}
function CategoryList($params)
{
//$object =& $this->Application->recallObject( $this->getPrefixSpecial() , $this->Prefix.'_List', $params );
$object =& $this->GetList($params);
if ($object->RecordsCount == 0)
{
if (isset($params['block_no_cats'])) {
$params['name'] = $params['block_no_cats'];
return $this->Application->ParseBlock($params);
}
else {
return '';
}
}
if(isset($params['block']))
{
return $this->PrintList($params);
}
else
{
$params['block'] = $params['block_main'];
$params['row_start_block'] = $params['block_row_start'];
$params['row_end_block'] = $params['block_row_end'];
return $this->PrintList2($params);
}
}
function Meta($params)
{
$name = getArrayValue($params, 'name');
$object =& $this->Application->recallObject($this->Prefix.'.-item');
$field = $object->GetField('Meta'.$name);
if ($field) return $field;
switch ($name) {
case 'Description':
$conf = 'Category_MetaDesc';
break;
case 'Keywords':
$conf = 'Category_MetaKey';
break;
}
return $this->Application->ConfigValue($conf);
}
function BuildListSpecial($params)
{
if ( isset($params['parent_cat_id']) ) {
$parent_cat_id = $params['parent_cat_id'];
}
else {
$parent_cat_id = $this->Application->GetVar($this->Prefix.'_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
if (!$parent_cat_id) {
$parent_cat_id = 0;
}
}
$types = $this->SelectParam($params, 'types');
$except = $this->SelectParam($params, 'except');
if ($types.$except.$parent_cat_id == '') {
return parent::BuildListSpecial($params);
}
$special = crc32($types.$except.$parent_cat_id);
return $special;
}
}
?>
\ No newline at end of file
Property changes on: trunk/core/units/categories/categories_tag_processor.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/core/units/general/cat_event_handler.php
===================================================================
--- trunk/core/units/general/cat_event_handler.php (revision 3590)
+++ trunk/core/units/general/cat_event_handler.php (revision 3591)
@@ -1,1407 +1,1407 @@
<?php
$application =& kApplication::Instance();
$application->Factory->includeClassFile('kDBEventHandler');
class kCatDBEventHandler extends InpDBEventHandler {
function OnCopy(&$event)
{
$object = $event->getObject();
$this->StoreSelectedIDs($event);
$ids = $this->getSelectedIDs($event);
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard', implode(',', $ids));
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard_mode', 'copy');
$this->Application->StoreVar('ClipBoard', 'COPY-0.'.$object->TableName.'.ResourceId=0');
$event->redirect_params = Array('opener' => 's', 'pass_events'=>true); //do not go up - STAY
}
function OnCut(&$event)
{
$object = $event->getObject();
$this->StoreSelectedIDs($event);
$ids = $this->getSelectedIDs($event);
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard', implode(',', $ids));
$this->Application->StoreVar($event->getPrefixSpecial().'_clipboard_mode', 'cut');
$this->Application->StoreVar('ClipBoard', 'CUT-0.'.$object->TableName.'.ResourceId=0');
$event->redirect_params = Array('opener' => 's', 'pass_events'=>true); //do not go up - STAY
}
function OnPaste(&$event)
{
$ids = $this->Application->RecallVar($event->getPrefixSpecial().'_clipboard');
if ($ids == '') {
$event->redirect = false;
return;
}
//recalling by different name, because we may get kDBList, if we recall just by prefix
$object =& $this->Application->recallObject($event->getPrefixSpecial().'.item', $event->Prefix);
$this->prepareObject($object, $event);
if ($this->Application->RecallVar($event->getPrefixSpecial().'_clipboard_mode') == 'copy') {
$ids_arr = explode(',', $ids);
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
if($ids_arr)
{
$temp->CloneItems($event->Prefix, $event->Special, $ids_arr);
}
}
else { // mode == cut
$ids_arr = explode(',', $ids);
foreach ($ids_arr as $id) {
$object->Load($id);
$object->MoveToCat();
}
}
$event->status = erSUCCESS;
}
/**
* Occurs when pasting category
*
* @param kEvent $event
*/
function OnCatPaste(&$event)
{
$inp_clipboard = $this->Application->RecallVar('ClipBoard');
$inp_clipboard = explode('-', $inp_clipboard, 2);
if($inp_clipboard[0] == 'COPY')
{
$saved_cat_id = $this->Application->GetVar('m_cat_id');
$cat_ids = $event->getEventParam('cat_ids');
$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
$table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$ids_sql = 'SELECT '.$id_field.' FROM '.$table.' WHERE ResourceId IN (%s)';
$resource_ids_sql = 'SELECT ItemResourceId FROM '.TABLE_PREFIX.'CategoryItems WHERE CategoryId = %s AND PrimaryCat = 1';
$this->Application->setUnitOption($event->Prefix,'AutoLoad', false);
$object =& $this->Application->recallObject($event->Prefix.'.item', $event->Prefix);
foreach($cat_ids as $source_cat => $dest_cat)
{
$item_resource_ids = $this->Conn->GetCol( sprintf($resource_ids_sql, $source_cat) );
if(!$item_resource_ids) continue;
$this->Application->SetVar('m_cat_id', $dest_cat);
$item_ids = $this->Conn->GetCol( sprintf($ids_sql, implode(',', $item_resource_ids) ) );
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
if($item_ids) $temp->CloneItems($event->Prefix, $event->Special, $item_ids);
}
$this->Application->setUnitOption($event->Prefix,'AutoLoad', true);
$this->Application->SetVar('m_cat_id', $saved_cat_id);
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveAndOpenTranslator(&$event)
{
$this->Application->SetVar('allow_translation', true);
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
// $url = $this->Application->HREF($t, '', Array('pass'=>'all', $event->getPrefixSpecial(true).'_id' => $object->GetId()));
// $field = $this->Application->GetVar('translator_field');
$cf_id = $this->Application->GetVar('translator_cf_id');
if($cf_id)
{
$cv =& $this->Application->recallObject('cv.-item', null, Array('skip_autoload' => true) );
$load_params = Array('CustomFieldId' => $cf_id, 'ResourceId'=> $object->GetDBField('ResourceId') );
if( !$cv->Load($load_params) )
{
$cv->SetFieldsFromHash($load_params);
$cv->Create();
}
$this->Application->SetVar('cv_id', $cv->getID() );
}
$event->redirect = $this->Application->GetVar('translator_t');
$event->redirect_params = Array('pass'=>'all,trans,'.$this->Application->GetVar('translator_prefixes'),
$event->getPrefixSpecial(true).'_id' => $object->GetId(),
'trans_event'=>'OnLoad',
'trans_prefix'=> $this->Application->GetVar('translator_prefixes'),
'trans_field'=>$this->Application->GetVar('translator_field'),
'trans_multi_line'=>$this->Application->GetVar('translator_multi_line'),
);
// 1. SAVE LAST TEMPLATE TO SESSION
$last_template = $this->Application->RecallVar('last_template');
preg_match('/index4\.php\|'.$this->Application->GetSID().'-(.*):/U', $last_template, $rets);
// $this->Application->StoreVar('return_template', $rets[1]);
$this->Application->StoreVar('return_template', $this->Application->GetVar('t'));
//$after_script = "openTranslator('".$event->getPrefixSpecial()."', '".$field."', '".$url."', '".$wnd_name."')";
}
// $this->Application->SetVar('after_script', $after_script);
// $event->redirect = false;
}
/**
* Apply scope clause
*
* @param kEvent $event
*/
function SetCustomQuery(&$event)
{
$object =& $event->getObject();
if ($event->Special != 'showall') {
if ( $event->getEventParam('parent_cat_id') ) {
$parent_cat_id = $event->getEventParam('parent_cat_id');
}
else {
$parent_cat_id = $this->Application->GetVar('c_id');
if (!$parent_cat_id) {
$parent_cat_id = $this->Application->GetVar('m_cat_id');
}
if (!$parent_cat_id) {
$parent_cat_id = 0;
}
}
if ((string) $parent_cat_id != 'any') {
if ($event->getEventParam('recursive')) {
$current_path = $this->Conn->GetOne('SELECT ParentPath FROM '.TABLE_PREFIX.'Category WHERE CategoryId='.$parent_cat_id);
$subcats = $this->Conn->GetCol('SELECT CategoryId FROM '.TABLE_PREFIX.'Category WHERE ParentPath LIKE "'.$current_path.'%" ');
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId IN ('.implode(', ', $subcats).')');
}
else {
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId = '.$parent_cat_id );
}
}
}
else {
$object->addFilter('primary_filter', 'PrimaryCat = 1');
}
$view_perm = 1;
$object->addFilter('perm_filter', 'perm.PermId = '.$view_perm);
if ( !$this->Application->IsAdmin() )
{
$groups = explode( ',', $this->Application->RecallVar('UserGroups') );
foreach($groups as $group)
{
$view_filters[] = 'FIND_IN_SET('.$group.', perm.acl) || ((NOT FIND_IN_SET('.$group.',perm.dacl)) AND perm.acl=\'\')';
}
$view_filter = implode(' OR ', $view_filters);
$object->addFilter('perm_filter2', $view_filter);
$object->addFilter('status_filter', $object->TableName.'.Status = 1');
}
/*$list_type = $event->getEventParam('ListType');
switch($list_type)
{
case 'favorites':
$fav_table = $this->Application->getUnitOption('fav','TableName');
$user_id =& $this->Application->GetVar('u_id');
$sql = 'SELECT DISTINCT f.ResourceId
FROM '.$fav_table.' f
LEFT JOIN '.$object->TableName.' p ON p.ResourceId = f.ResourceId
WHERE f.PortalUserId = '.$user_id;
$ids = $this->Conn->GetCol($sql);
if(!$ids) $ids = Array(-1);
$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.PrimaryCat = 1');
$object->addFilter('favorites_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')');
break;
case 'search':
$search_results_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = ' SELECT DISTINCT ResourceId
FROM '.$search_results_table.'
WHERE ItemType=11';
$ids = $this->Conn->GetCol($sql);
if(!$ids) $ids = Array(-1);
$object->addFilter('search_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')');
break;
} */
}
/**
* Adds calculates fields for item statuses
*
* @param kCatDBItem $object
* @param kEvent $event
*/
function prepareObject(&$object, &$event)
{
$this->prepareItemStatuses($event);
if ($event->Special == 'export' || $event->Special == 'import')
{
$this->prepareExportColumns($event);
}
}
/**
* Creates calculated fields for all item statuses based on config settings
*
* @param kEvent $event
*/
function prepareItemStatuses(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$property_mappings = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
$new_days_var = getArrayValue($property_mappings, 'NewDays');
if($new_days_var)
{
$object->addCalculatedField('IsNew', ' IF(%1$s.NewItem = 2,
IF(%1$s.CreatedOn >= (UNIX_TIMESTAMP() - '.
$this->Application->ConfigValue($new_days_var).
'*3600*24), 1, 0),
%1$s.NewItem
)');
}
$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
if($hot_limit_var)
{
$sql = 'SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName = "'.$hot_limit_var.'"';
$hot_limit = $this->Conn->GetOne($sql);
if($hot_limit === false) $hot_limit = $this->CalculateHotLimit($event);
$object->addCalculatedField('IsHot', ' IF(%1$s.HotItem = 2,
IF(%1$s.Hits >= '.$hot_limit.', 1, 0),
%1$s.HotItem
)');
}
$votes2pop_var = getArrayValue($property_mappings, 'VotesToPop');
$rating2pop_var = getArrayValue($property_mappings, 'RatingToPop');
if($votes2pop_var && $rating2pop_var)
{
$object->addCalculatedField('IsPop', ' IF(%1$s.PopItem = 2,
IF(%1$s.CachedVotesQty >= '.
$this->Application->ConfigValue($votes2pop_var).
' AND %1$s.CachedRating >= '.
$this->Application->ConfigValue($rating2pop_var).
', 1, 0),
%1$s.PopItem)');
}
}
function CalculateHotLimit(&$event)
{
$property_mappings = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
$hot_count_var = getArrayValue($property_mappings, 'HotCount');
$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
if($hot_count_var && $hot_limit_var)
{
$last_hot = $this->Application->ConfigValue($hot_count_var) - 1;
$sql = 'SELECT Hits FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
ORDER BY Hits DESC
LIMIT '.$last_hot.', 1';
$res = $this->Conn->GetCol($sql);
$hot_limit = (double)array_shift($res);
$this->Conn->Query('REPLACE INTO '.TABLE_PREFIX.'Cache VALUES ("'.$hot_limit_var.'", "'.$hot_limit.'", '.adodb_mktime().')');
return $hot_limit;
}
return 0;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
$object =& $event->getObject();
if( $this->Application->IsAdmin() && ($this->Application->GetVar('Hits_original') !== false) &&
floor($this->Application->GetVar('Hits_original')) != $object->GetDBField('Hits') )
{
$sql = 'SELECT MAX(Hits) FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
WHERE FLOOR(Hits) = '.$object->GetDBField('Hits');
$hits = ( $res = $this->Conn->GetOne($sql) ) ? $res + 0.000001 : $object->GetDBField('Hits');
$object->SetDBField('Hits', $hits);
}
}
function OnAfterItemUpdate(&$event)
{
$this->CalculateHotLimit($event);
}
/**
* Makes simple search for products
* based on keywords string
*
* @param kEvent $event
* @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!!
*/
function OnSimpleSearch(&$event)
{
if($this->Application->GetVar('INPORTAL_ON') && !($this->Application->GetVar('Action') == 'm_simple_search'))
{
return;
}
$event->redirect = false;
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$keywords = trim($this->Application->GetVar('keywords'));
if( !$this->Application->GetVar('INPORTAL_ON') )
{
$keywords = unhtmlentities($keywords);
}
$query_object =& $this->Application->recallObject('HTTPQuery');
$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
if(!isset($query_object->Get['keywords']) &&
!isset($query_object->Post['keywords']) &&
$this->Conn->Query($sql))
{
return; // used when navigating by pages or changing sorting in search results
}
if(!$keywords || strlen($keywords) < $this->Application->ConfigValue('Search_MinKeyword_Length'))
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table);
$this->Application->SetVar('keywords_too_short', 1);
return; // if no or too short keyword entered, doing nothing
}
$this->Application->StoreVar('keywords', $keywords);
$keywords = strtr($keywords, Array('%' => '\\%', '_' => '\\_'));
$event->setPseudoClass('_List');
$object =& $event->getObject();
$this->Application->SetVar($event->getPrefixSpecial().'_Page', 1);
$lang = $this->Application->GetVar('m_lang');
$product_table = $this->Application->getUnitOption('p', 'TableName');
$sql = ' SELECT * FROM '.$this->Application->getUnitOption('confs', 'TableName').'
WHERE ModuleName="In-Commerce"
AND SimpleSearch=1';
$search_config = $this->Conn->Query($sql, 'FieldName');
$field_list = array_keys($search_config);
$join_clauses = Array();
// field processing
$weight_sum = 0;
foreach($field_list as $key => $field)
{
$options = $object->getFieldOptions($field);
$local_table = TABLE_PREFIX.$search_config[$field]['TableName'];
$weight_sum += $search_config[$field]['Priority']; // counting weight sum; used when making relevance clause
// processing multilingual fields
if($options['formatter'] == 'kMultiLanguage')
{
$field_list[$key] = 'l'.$lang.'_'.$field;
}
// processing fields from other tables
if($foreign_field = $search_config[$field]['ForeignField'])
{
$exploded = explode(':', $foreign_field, 2);
if($exploded[0] == 'CALC')
{
unset($field_list[$key]);
continue; // ignoring having type clauses in simple search
/*$user_object =& $this->Application->recallObject('u');
$user_groups = $user_object->GetDBField('PortalUserId') ?
implode(',', $this->Conn->GetCol(' SELECT GroupId
FROM '.TABLE_PREFIX.'UserGroup
WHERE PortalUserId='.$user_object->GetDBField('PortalUserId'))) : 0;
$having_list[$key] = str_replace('{PREFIX}', TABLE_PREFIX, $exploded[1]);
$join_clause = str_replace('{PREFIX}', TABLE_PREFIX, $search_config[$field]['JoinClause']);
$join_clause = str_replace('{USER_GROUPS}', $user_groups, $join_clause);
$join_clause = ' LEFT JOIN '.$join_clause;
$join_clauses[] = $join_clause;*/
}
else
{
$exploded = explode('.', $foreign_field);
$foreign_table = TABLE_PREFIX.$exploded[0];
if($search_config[$field]['CustomFieldId']) {
$exploded[1] = 'l'.$lang.'_'.$exploded[1];
}
$alias_counter++;
$alias = 't'.$alias_counter;
$field_list[$key] = $alias.'.'.$exploded[1];
$join_clause = str_replace('{ForeignTable}', $alias, $search_config[$field]['JoinClause']);
$join_clause = str_replace('{LocalTable}', $product_table, $join_clause);
if($search_config[$field]['CustomFieldId'])
{
$join_clause .= ' AND '.$alias.'.CustomFieldId='.$search_config[$field]['CustomFieldId'];
}
$join_clauses[] = ' LEFT JOIN '.$foreign_table.' '.$alias.'
ON '.$join_clause;
}
}
else
{
// processing fields from local table
$field_list[$key] = $local_table.'.'.$field_list[$key];
}
}
// keyword string processing
$normal_keywords = Array();
$plus_keywords = Array();
$minus_keywords = Array();
for($i = 0; $i < strlen($keywords); $i++)
{
if(substr($keywords, $i, 1) == ' ') continue;
$extra_skip = 0;
switch(substr($keywords, $i, 1))
{
case '+':
if(substr($keywords, $i + 1, 1) == '"')
{
$keyword_start = $i + 2;
$keyword_end = strpos($keywords, '"', $i + 2);
$extra_skip = 2;
}
else
{
$keyword_start = $i + 1;
$keyword_end = strpos($keywords, ' ', $i + 1);
$extra_skip = 0;
}
$target_array =& $plus_keywords;
break;
case '-':
if(substr($keywords, $i + 1, 1) == '"')
{
$keyword_start = $i + 2;
$keyword_end = strpos($keywords, '"', $i + 2);
$extra_skip = 2;
}
else
{
$keyword_start = $i + 1;
$keyword_end = strpos($keywords, ' ', $i + 1);
$extra_skip = 0;
}
$target_array =& $minus_keywords;
break;
case '"':
$keyword_start = $i + 1;
$keyword_end = strpos($keywords, '"', $i + 1);
$extra_skip = 1;
$target_array =& $normal_keywords;
break;
default:
$keyword_start = $i;
$keyword_end = strpos($keywords, ' ', $i + 1);
$target_array =& $normal_keywords;
}
if($keyword_end === false)
{
$keyword_end = strlen($keywords);
}
$keyword_length = $keyword_end - $keyword_start;
$keyword = substr($keywords, $keyword_start, $keyword_length);
if(strlen($keyword) >= $this->Application->ConfigValue('Search_MinKeyword_Length'))
{
$target_array[] = addcslashes($keyword, '"');
}
$i += $keyword_length + $extra_skip;
}
// preparing conditions
$normal_conditions = Array();
$plus_conditions = Array();
$minus_conditions = Array();
foreach($normal_keywords as $keyword)
{
$normal_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $field_list).' LIKE "%'.$keyword.'%"';
}
foreach($plus_keywords as $keyword)
{
$plus_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $field_list).' LIKE "%'.$keyword.'%"';
}
foreach($minus_keywords as $keyword)
{
foreach($field_list as $field)
{
$condition[] = $field.' NOT LIKE "%'.$keyword.'%" OR '.$field.' IS NULL';
}
$minus_conditions[] = '('.implode(') AND (', $condition).')';
}
// building where clause
if($normal_conditions)
{
$where_clause = '('.implode(') OR (', $normal_conditions).')';
}
else
{
$where_clause = '1';
}
if($plus_conditions)
{
$where_clause = '('.$where_clause.') AND ('.implode(') AND (', $plus_conditions).')';
}
if($minus_conditions)
{
$where_clause = '('.$where_clause.') AND ('.implode(') AND (', $minus_conditions).')';
}
$where_clause = $where_clause.' AND '.$product_table.'.Status=1';
if($this->Application->GetVar('Action') == 'm_simple_subsearch') // subsearch, In-portal
{
if( $event->getEventParam('ResultIds') )
{
$where_clause .= ' AND '.$product_table.'.ResourceId IN ('.implode(',', $event->specificParams['ResultIds']).')';
}
}
if( $event->MasterEvent && $event->MasterEvent->Name == 'OnListBuild' ) // subsearch, k4
{
if( $event->MasterEvent->getEventParam('ResultIds') )
{
$where_clause .= ' AND '.$product_table.'.ResourceId IN ('.implode(',', $event->MasterEvent->getEventParam('ResultIds')).')';
}
}
// building having clause
// making relevance clause
$positive_words = array_merge($normal_keywords, $plus_keywords);
$this->Application->StoreVar('highlight_keywords', serialize($positive_words));
$revelance_parts = Array();
reset($search_config);
foreach($field_list as $field)
{
$config_elem = each($search_config);
$weight = $search_config[$field]['Priority'];
$revelance_parts[] = 'IF('.$field.' LIKE "%'.implode(' ', $positive_words).'%", '.$weight_sum.', 0)';
foreach($positive_words as $keyword)
{
$revelance_parts[] = 'IF('.$field.' LIKE "%'.$keyword.'%", '.$config_elem['value']['Priority'].', 0)';
}
}
$rel_keywords = $this->Application->ConfigValue('SearchRel_DefaultKeyword_products') / 100;
$rel_pop = $this->Application->ConfigValue('SearchRel_DefaultPop_products') / 100;
$rel_rating = $this->Application->ConfigValue('SearchRel_DefaultRating_products') / 100;
$relevance_clause = '('.implode(' + ', $revelance_parts).') / '.$weight_sum.' * '.$rel_keywords;
$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
// building final search query
if( !$this->Application->GetVar('INPORTAL_ON') )
{
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); // erase old search table if clean k4 event
}
if($this->Conn->Query('SHOW TABLES LIKE "'.$search_table.'"'))
{
$select_intro = 'INSERT INTO '.$search_table.' (Relevance, ItemId, ResourceId, ItemType, EdPick) ';
}
else
{
$select_intro = 'CREATE TABLE '.$search_table.' AS ';
}
$sql = $select_intro.' SELECT '.$relevance_clause.' AS Relevance,
'.$product_table.'.ProductId AS ItemId,
'.$product_table.'.ResourceId,
11 AS ItemType,
'.$product_table.'.EditorsPick AS EdPick
FROM '.$object->TableName.'
'.implode(' ', $join_clauses).'
WHERE '.$where_clause.'
GROUP BY '.$product_table.'.ProductId';
$res = $this->Conn->Query($sql);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSubSearch(&$event)
{
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
if($this->Conn->Query($sql))
{
$sql = 'SELECT DISTINCT ResourceId FROM '.$search_table;
$ids = $this->Conn->GetCol($sql);
}
$event->setEventParam('ResultIds', $ids);
$event->CallSubEvent('OnSimpleSearch');
}
/**
* Enter description here...
*
* @param kEvent $event
* @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!!
*/
function OnAdvancedSearch(&$event)
{
$query_object =& $this->Application->recallObject('HTTPQuery');
if(!isset($query_object->Post['andor']))
{
return; // used when navigating by pages or changing sorting in search results
}
$this->Application->RemoveVar('keywords');
$this->Application->RemoveVar('Search_Keywords');
$sql = ' SELECT * FROM '.$this->Application->getUnitOption('confs', 'TableName').'
WHERE ModuleName="In-Commerce"
AND AdvancedSearch=1';
$search_config = $this->Conn->Query($sql);
$lang = $this->Application->GetVar('m_lang');
$object =& $event->getObject();
$object->SetPage(1);
$user_object =& $this->Application->recallObject('u');
$product_table = $this->Application->getUnitOption('p', 'TableName');
$keywords = $this->Application->GetVar('value');
$verbs = $this->Application->GetVar('verb');
$glues = $this->Application->GetVar('andor');
$and_conditions = Array();
$or_conditions = Array();
$and_having_conditions = Array();
$or_having_conditions = Array();
$join_clauses = Array();
$highlight_keywords = Array();
$relevance_parts = Array();
$condition_patterns = Array( 'any' => '%s LIKE %s',
'contains' => '%s LIKE %s',
'notcontains' => '(NOT (%1$s LIKE %2$s) OR %1$s IS NULL)',
'is' => '%s = %s',
'isnot' => '(%1$s != %2$s OR %1$s IS NULL)');
$alias_counter = 0;
$weight_sum = 0;
// processing fields and preparing conditions
foreach($search_config as $record)
{
$field = $record['FieldName'];
$join_clause = '';
$condition_mode = 'WHERE';
// field processing
$options = $object->getFieldOptions($field);
$local_table = TABLE_PREFIX.$record['TableName'];
$weight_sum += $record['Priority']; // counting weight sum; used when making relevance clause
// processing multilingual fields
if($options['formatter'] == 'kMultiLanguage')
{
$field_name = 'l'.$lang.'_'.$field;
}
else
{
$field_name = $field;
}
// processing fields from other tables
if($foreign_field = $record['ForeignField'])
{
$exploded = explode(':', $foreign_field, 2);
if($exploded[0] == 'CALC')
{
$user_groups = $user_object->GetDBField('PortalUserId') ?
implode(',', $this->Conn->GetCol(' SELECT GroupId
FROM '.TABLE_PREFIX.'UserGroup
WHERE PortalUserId='.$user_object->GetDBField('PortalUserId'))) : 0;
$field_name = str_replace('{PREFIX}', TABLE_PREFIX, $exploded[1]);
$join_clause = str_replace('{PREFIX}', TABLE_PREFIX, $record['JoinClause']);
$join_clause = str_replace('{USER_GROUPS}', $user_groups, $join_clause);
$join_clause = ' LEFT JOIN '.$join_clause;
$condition_mode = 'HAVING';
}
else
{
$exploded = explode('.', $foreign_field);
$foreign_table = TABLE_PREFIX.$exploded[0];
- if($search_config[$field]['CustomFieldId']) {
+ if($record['CustomFieldId']) {
$exploded[1] = 'l'.$lang.'_'.$exploded[1];
}
$alias_counter++;
$alias = 't'.$alias_counter;
$field_name = $alias.'.'.$exploded[1];
$join_clause = str_replace('{ForeignTable}', $alias, $record['JoinClause']);
$join_clause = str_replace('{LocalTable}', $product_table, $join_clause);
if($record['CustomFieldId'])
{
$join_clause .= ' AND '.$alias.'.CustomFieldId='.$record['CustomFieldId'];
}
$join_clause = ' LEFT JOIN '.$foreign_table.' '.$alias.'
ON '.$join_clause;
}
}
else
{
// processing fields from local table
$field_name = $local_table.'.'.$field_name;
}
$condition = '';
switch($record['FieldType'])
{
case 'text':
if( !$this->Application->GetVar('INPORTAL_ON') )
{
$keywords[$field] = unhtmlentities( $keywords[$field] );
}
if(strlen($keywords[$field]) >= $this->Application->ConfigValue('Search_MinKeyword_Length'))
{
$highlight_keywords[] = $keywords[$field];
if( in_array($verbs[$field], Array('any', 'contains', 'notcontains')) )
{
$keywords[$field] = '%'.strtr($keywords[$field], Array('%' => '\\%', '_' => '\\_')).'%';
}
$condition = sprintf( $condition_patterns[$verbs[$field]],
$field_name,
$this->Conn->qstr( $keywords[$field] ));
}
break;
case 'boolean':
if($keywords[$field] != -1)
{
$property_mappings = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
switch($field)
{
case 'HotItem':
$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
if($hot_limit_var)
{
$sql = 'SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName="'.$hot_limit_var.'"';
$hot_limit = (int)$this->Conn->GetOne($sql);
$condition = 'IF('.$product_table.'.HotItem = 2,
IF('.$product_table.'.Hits >= '.
$hot_limit.
', 1, 0), '.$product_table.'.HotItem) = '.$keywords[$field];
}
break;
case 'PopItem':
$votes2pop_var = getArrayValue($property_mappings, 'VotesToPop');
$rating2pop_var = getArrayValue($property_mappings, 'RatingToPop');
if($votes2pop_var && $rating2pop_var)
{
$condition = 'IF('.$product_table.'.PopItem = 2, IF('.$product_table.'.CachedVotesQty >= '.
$this->Application->ConfigValue($votes2pop_var).
' AND '.$product_table.'.CachedRating >= '.
$this->Application->ConfigValue($rating2pop_var).
', 1, 0), '.$product_table.'.PopItem) = '.$keywords[$field];
}
break;
case 'NewItem':
$new_days_var = getArrayValue($property_mappings, 'NewDays');
if($new_days_var)
{
$condition = 'IF('.$product_table.'.NewItem = 2,
IF('.$product_table.'.CreatedOn >= (UNIX_TIMESTAMP() - '.
$this->Application->ConfigValue($new_days_var).
'*3600*24), 1, 0), '.$product_table.'.NewItem) = '.$keywords[$field];
}
break;
case 'EditorsPick':
$condition = $product_table.'.EditorsPick = '.$keywords[$field];
break;
}
}
break;
case 'range':
$range_conditions = Array();
if($keywords[$field.'_from'] && !preg_match("/[^0-9]/i", $keywords[$field.'_from']))
{
$range_conditions[] = $field_name.' >= '.$keywords[$field.'_from'];
}
if($keywords[$field.'_to'] && !preg_match("/[^0-9]/i", $keywords[$field.'_to']))
{
$range_conditions[] = $field_name.' <= '.$keywords[$field.'_to'];
}
if($range_conditions)
{
$condition = implode(' AND ', $range_conditions);
}
break;
case 'date':
if($keywords[$field])
{
if( in_array($keywords[$field], Array('today', 'yesterday')) )
{
$current_time = getdate();
$day_begin = adodb_mktime(0, 0, 0, $current_time['mon'], $current_time['mday'], $current_time['year']);
$time_mapping = Array('today' => $day_begin, 'yesterday' => ($day_begin - 86400));
$min_time = $time_mapping[$keywords[$field]];
}
else
{
$time_mapping = Array( 'last_week' => 604800, 'last_month' => 2628000,
'last_3_months' => 7884000, 'last_6_months' => 15768000,
'last_year' => 31536000
);
$min_time = adodb_mktime() - $time_mapping[$keywords[$field]];
}
$condition = $field_name.' > '.$min_time;
}
break;
}
if($condition)
{
if($join_clause)
{
$join_clauses[] = $join_clause;
}
$relevance_parts[] = 'IF('.$condition.', '.$record['Priority'].', 0)';
if($glues[$field] == 1) // and
{
if($condition_mode == 'WHERE')
{
$and_conditions[] = $condition;
}
else
{
$and_having_conditions[] = $condition;
}
}
else // or
{
if($condition_mode == 'WHERE')
{
$or_conditions[] = $condition;
}
else
{
$or_having_conditions[] = $condition;
}
}
}
}
$this->Application->StoreVar('highlight_keywords', serialize($highlight_keywords));
// making relevance clause
if($relevance_parts)
{
$rel_keywords = $this->Application->ConfigValue('SearchRel_DefaultKeyword_products') / 100;
$rel_pop = $this->Application->ConfigValue('SearchRel_DefaultPop_products') / 100;
$rel_rating = $this->Application->ConfigValue('SearchRel_DefaultRating_products') / 100;
$relevance_clause = '('.implode(' + ', $relevance_parts).') / '.$weight_sum.' * '.$rel_keywords;
$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
}
else
{
$relevance_clause = '0';
}
// building having clause
if($or_having_conditions)
{
$and_having_conditions[] = '('.implode(' OR ', $or_having_conditions).')';
}
$having_clause = implode(' AND ', $and_having_conditions);
$having_clause = $having_clause ? ' HAVING '.$having_clause : '';
// building where clause
if($or_conditions)
{
$and_conditions[] = '('.implode(' OR ', $or_conditions).')';
}
// $and_conditions[] = $product_table.'.Status = 1';
$where_clause = implode(' AND ', $and_conditions);
if(!$where_clause)
{
if($having_clause)
{
$where_clause = '1';
}
else
{
$where_clause = '0';
$this->Application->SetVar('adv_search_error', 1);
}
}
$where_clause .= ' AND '.$product_table.'.Status = 1';
// building final search query
$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table);
$sql = ' CREATE TABLE '.$search_table.'
SELECT '.$relevance_clause.' AS Relevance,
'.$product_table.'.ProductId AS ItemId,
'.$product_table.'.ResourceId AS ResourceId,
11 AS ItemType,
'.$product_table.'.EditorsPick AS EdPick
FROM '.$product_table.'
'.implode(' ', $join_clauses).'
WHERE '.$where_clause.'
GROUP BY '.$product_table.'.ProductId'.
$having_clause;
$res = $this->Conn->Query($sql);
}
/**
* Set's correct page for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetPagination(&$event)
{
// get PerPage (forced -> session -> config -> 10)
$per_page = $this->getPerPage($event);
$object =& $event->getObject();
$object->SetPerPage($per_page);
$this->Application->StoreVarDefault($event->getPrefixSpecial().'_Page', 1);
$page = $this->Application->GetVar($event->getPrefixSpecial().'_Page');
if (!$page)
{
$page = $this->Application->GetVar($event->getPrefixSpecial(true).'_Page');
}
if (!$page)
{
if( $this->Application->RewriteURLs() )
{
$page = $this->Application->GetVar($event->Prefix.'_Page');
if (!$page)
{
$page = $this->Application->RecallVar($event->Prefix.'_Page');
}
if($page) $this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
else
{
$page = $this->Application->RecallVar($event->getPrefixSpecial().'_Page');
}
}
else {
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page);
}
// $page = $this->Application->GetLinkedVar($event->getPrefixSpecial(true).'_Page', $event->getPrefixSpecial().'_Page');
if( !$event->getEventParam('skip_counting') )
{
$pages = $object->GetTotalPages();
if($page > $pages)
{
$this->Application->StoreVar($event->getPrefixSpecial().'_Page', 1);
$page = 1;
}
}
/*$cur_per_page = $per_page;
$per_page = $event->getEventParam('per_page');
if ($per_page == 'list_next') {
$cur_page = $page;
$object =& $this->Application->recallObject($event->Prefix);
$object->SetPerPage(1);
$cur_item_index = $object->CurrentIndex;
$page = ($cur_page-1) * $cur_per_page + $cur_item_index + 1;
$object->SetPerPage(1);
}*/
$object->SetPage($page);
}
/* === RELATED TO IMPORT/EXPORT: BEGIN === */
/**
* Returns module folder
*
* @param kEvent $event
* @return string
*/
function getModuleFolder(&$event)
{
return $this->Application->getUnitOption($event->Prefix, 'ModuleFolder');
}
/**
* Shows export dialog
*
* @param kEvent $event
*/
function OnExport(&$event)
{
$selected_ids = $this->Application->GetVar('linklist');
$selected_cats_ids = $this->Application->GetVar('export_categories');
$this->Application->StoreVar($event->Prefix.'_export_ids', $selected_ids ? implode(',', $selected_ids) : '' );
$this->Application->StoreVar($event->Prefix.'_export_cats_ids', $selected_cats_ids);
$event->redirect = $this->getModuleFolder($event).'/export';
$redirect_params = Array( 'm_opener' => 'd',
'index_file' => 'index4.php',
$this->Prefix.'.export_event' => 'OnNew',
'pass' => 'all,'.$this->Prefix.'.export');
$event->setRedirectParams($redirect_params);
}
/**
* Export form validation & processing
*
* @param kEvent $event
*/
function OnExportBegin(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if (!$items_info)
{
$items_info = unserialize( $this->Application->RecallVar($event->getPrefixSpecial().'_ItemsInfo') );
}
list($item_id, $field_values) = each($items_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$object->setID($item_id);
$this->setRequiredFields($event);
$export_object =& $this->Application->recallObject('CatItemExportHelper');
// save export/import options
if ($event->Special == 'export')
{
$export_ids = $this->Application->RecallVar($event->Prefix.'_export_ids');
$export_cats_ids = $this->Application->RecallVar($event->Prefix.'_export_cats_ids');
// used for multistep export
$field_values['export_ids'] = $export_ids ? explode(',', $export_ids) : false;
$field_values['export_cats_ids'] = $export_cats_ids ? explode(',', $export_cats_ids) : Array( $this->Application->GetVar('m_cat_id') );
}
$field_values['ExportColumns'] = $field_values['ExportColumns'] ? explode('|', substr($field_values['ExportColumns'], 1, -1) ) : Array();
$field_values['start_from'] = 0;
$this->Application->StoreVar($event->getPrefixSpecial().'_options', serialize($field_values) );
if( $export_object->verifyOptions($event) )
{
$this->doExport($event);
}
else
{
$event->status = erFAIL;
$event->redirect = false;
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function doExport(&$event)
{
if ($event->Name == 'OnExportBegin')
{
$done_percent = 0;
}
else {
$export_options = unserialize($this->Application->RecallVar($event->getPrefixSpecial().'_options'));
$done_percent = round($export_options['start_from'] * 100 / $export_options['total_records'], 0);
}
$block_params = Array( 'name' => $this->getModuleFolder($event).'/'.$event->Special.'_progress',
'percent_done' => $done_percent,
'percent_left' => 100 - $done_percent);
$this->Application->InitParser();
$this->Application->setUnitOption($event->Prefix, 'AutoLoad', false);
echo $this->Application->ParseBlock($block_params);
flush();
$export_object =& $this->Application->recallObject('CatItemExportHelper');
$action_method = 'perform'.ucfirst($event->Special);
$field_values = $export_object->$action_method($event);
if ($field_values['start_from'] == $field_values['total_records'])
{
if ($event->Special == 'import') {
$this->Application->StoreVar('PermCache_UpdateRequired', 1);
$event->SetRedirectParam('index_file', 'category/category_maint.php');
}
else {
$event->redirect = $this->getModuleFolder($event).'/'.$event->Special.'_finish';
}
}
else {
$event->redirect = $this->getModuleFolder($event).'/'.$event->Special.'_progress';
$redirect_params = Array($event->getPrefixSpecial().'_event' => 'OnExportProgress', 'pass' => 'm,'.$event->getPrefixSpecial());
$event->setRedirectParams($redirect_params);
}
}
/**
* Next export steps
*
* @param kEvent $event
*/
function OnExportProgress(&$event)
{
$this->doExport($event);
}
/**
* Sets correct available & export fields
*
* @param kEvent $event
*/
function prepareExportColumns(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$available_columns = Array();
// category field (mixed)
$available_columns['__CATEGORY__CategoryPath'] = 'CategoryPath';
if ($event->Special == 'import') {
// category field (separated fields)
$max_level = $this->Application->ConfigValue('MaxImportCategoryLevels');
$i = 0;
while ($i < $max_level) {
$available_columns['__CATEGORY__Category'.($i + 1)] = 'Category'.($i + 1);
$i++;
}
}
// db fields
$fields = array_keys($object->Fields);
foreach ($fields as $field_name)
{
if (!$object->SkipField($field_name))
{
$available_columns[$field_name] = $field_name;
}
}
// custom fields
$fields = array_keys($object->CustomFields);
foreach ($fields as $field_name)
{
$available_columns['__CUSTOM__'.$field_name] = $field_name;
}
// columns already in use
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info)
{
list($item_id, $field_values) = each($items_info);
$export_keys = $field_values['ExportColumns'];
$export_keys = $export_keys ? explode('|', substr($export_keys, 1, -1) ) : Array();
}
else {
$export_keys = Array();
}
$export_columns = Array();
foreach ($export_keys as $field_key)
{
$field_name = $this->getExportField($field_key);
$export_columns[$field_key] = $field_name;
unset($available_columns[$field_key]);
}
$options = $object->GetFieldOptions('ExportColumns');
$options['options'] = $export_columns;
$object->SetFieldOptions('ExportColumns', $options);
$options = $object->GetFieldOptions('AvailableColumns');
$options['options'] = $available_columns;
$object->SetFieldOptions('AvailableColumns', $options);
if ($event->Special == 'import')
{
$import_filenames = Array();
if ($folder_handle = opendir(EXPORT_PATH)) {
while (false !== ($file = readdir($folder_handle))) {
if ( substr($file, 0, 1) == '.' || strtolower($file) == 'cvs' || strtolower($file) == 'dummy' || filesize(EXPORT_PATH.'/'.$file) == 0) continue;
$file_size = formatSize( filesize(EXPORT_PATH.'/'.$file) );
$import_filenames[$file] = $file.' ('.$file_size.')';
}
closedir($folder_handle);
}
$options = $object->GetFieldOptions('ImportLocalFilename');
$options['options'] = $import_filenames;
$object->SetFieldOptions('ImportLocalFilename', $options);
}
}
// ImportLocalFilename
function getExportField($field_key)
{
$prepends = Array('__CUSTOM__', '__CATEGORY__');
foreach ($prepends as $prepend)
{
if (substr($field_key, 0, strlen($prepend) ) == $prepend)
{
$field_key = substr($field_key, strlen($prepend), strlen($field_key) );
break;
}
}
return $field_key;
}
/**
* Shows export dialog
*
* @param kEvent $event
*/
function OnImport(&$event)
{
$event->redirect = $this->getModuleFolder($event).'/import';
$redirect_params = Array( 'm_opener' => 'd',
'index_file' => 'index4.php',
$this->Prefix.'.import_event' => 'OnNew',
'pass' => 'all,'.$this->Prefix.'.import');
$event->setRedirectParams($redirect_params);
}
/**
* Prepares item for import/export operations
*
* @param kEvent $event
*/
function OnNew(&$event)
{
parent::OnNew($event);
if ($event->Special != 'import' && $event->Special != 'export') return ;
$this->setRequiredFields($event);
}
/**
* set required fields based on import or export params
*
* @param kEvent $event
*/
function setRequiredFields(&$event)
{
$required_fields['common'] = Array('FieldsSeparatedBy', 'FieldsEnclosedBy', 'LineEndings', 'CategoryFormat');
$required_fields['export'] = Array('ExportFormat', 'ExportFilename','ExportColumns');
$required_fields['import'] = Array('FieldTitles', 'ImportSource', 'CheckDuplicatesMethod'); // ImportFilename, ImportLocalFilename
$object =& $event->getObject();
if ($event->Special == 'import')
{
$import_source = Array(1 => 'ImportFilename', 2 => 'ImportLocalFilename');
$used_field = $import_source[ $object->GetDBField('ImportSource') ];
$required_fields[$event->Special][] = $used_field;
$object->Fields[$used_field]['error_field'] = 'ImportSource';
if ($object->GetDBField('FieldTitles') == 2) $required_fields[$event->Special][] = 'ExportColumns'; // manual field titles
}
$required_fields = array_merge($required_fields['common'], $required_fields[$event->Special]);
foreach ($required_fields as $required_field) {
$object->setRequired($required_field, true);
}
}
/**
* Saves selected category as new import category
*
* @param kEvent $event
*/
function OnSelectItems(&$event)
{
$items_info = $this->Application->GetVar('c');
if ($items_info)
{
$selected_categories = array_keys($items_info);
$cat_id = array_shift($selected_categories);
$sql = 'SELECT CategoryId FROM '.TABLE_PREFIX.'Category WHERE ResourceId = '.$cat_id;
$cat_id = $this->Conn->GetOne($sql);
}
else {
$cat_id = 0;
}
$this->Application->StoreVar('ImportCategory', $cat_id);
$this->Application->StoreVar($event->getPrefixSpecial().'_ForceNotValid', 1); // not to loose import/export values on form refresh
$this->Application->SetVar($event->getPrefixSpecial().'_id', 0);
$this->Application->SetVar($event->getPrefixSpecial().'_event', 'OnExportBegin');
$passed = $this->Application->GetVar('passed');
$this->Application->SetVar('passed', $passed.','.$event->getPrefixSpecial());
$event->setEventParam('pass_events', true);
$this->finalizePopup($event, null, $this->getModuleFolder($event).'/'.$event->Special);
}
/**
* Saves Import/Export settings to session
*
* @param kEvent $event
*/
function OnSaveSettings(&$event)
{
$event->redirect = false;
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info) {
$this->Application->StoreVar($event->getPrefixSpecial().'_ItemsInfo', serialize($items_info));
}
}
/* === RELATED TO IMPORT/EXPORT: END === */
}
?>
\ No newline at end of file
Property changes on: trunk/core/units/general/cat_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.20
\ No newline at end of property
+1.21
\ No newline at end of property
Event Timeline
Log In to Comment