Index: branches/5.2.x/core/kernel/db/cat_event_handler.php
===================================================================
--- branches/5.2.x/core/kernel/db/cat_event_handler.php	(revision 14643)
+++ branches/5.2.x/core/kernel/db/cat_event_handler.php	(revision 14644)
@@ -1,2814 +1,2814 @@
 <?php
 /**
 * @version	$Id$
 * @package	In-Portal
 * @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
 * @license      GNU/GPL
 * In-Portal is Open Source software.
 * This means that this software may have been modified pursuant
 * the GNU General Public License, and as distributed it includes
 * or is derivative of works licensed under the GNU General Public License
 * or other free or open source software licenses.
 * See http://www.in-portal.org/license for copyright notices and details.
 */
 
 defined('FULL_PATH') or die('restricted access!');
 
 class kCatDBEventHandler extends kDBEventHandler {
 
 	/**
 	 * Allows to override standart permission mapping
 	 *
 	 */
 	function mapPermissions()
 	{
 		parent::mapPermissions();
 		$permissions = Array(
 			'OnSaveSettings' => Array ('self' => 'add|edit|advanced:import'),
 			'OnResetSettings' => Array ('self' => 'add|edit|advanced:import'),
 			'OnBeforeDeleteOriginal' => Array ('self' => 'edit|advanced:approve'),
 
 			'OnCopy' => Array ('self' => true),
 			'OnDownloadFile' => Array ('self' => 'view'),
 			'OnCancelAction' => Array ('self' => true),
 			'OnItemBuild' => Array ('self' => true),
 			'OnMakeVote' => Array ('self' => true),
 		);
 
 		$this->permMapping = array_merge($this->permMapping, $permissions);
 	}
 
 	/**
 	 * Load item if id is available
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	function LoadItem(&$event)
 	{
 		$object =& $event->getObject();
 		/* @var $object kDBItem */
 
 		$id = $this->getPassedID($event);
 
 		if ( $object->Load($id) ) {
 			$actions =& $this->Application->recallObject('kActions');
 			/* @var $actions Params */
 
 			$actions->Set($event->getPrefixSpecial() . '_id', $object->GetID());
 
 			$use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
-			
+
 			if ( $use_pending_editing && $event->Special != 'original' ) {
 				$this->Application->SetVar($event->Prefix . '.original_id', $object->GetDBField('OrgId'));
 			}
 		}
 		else {
 			$object->setID($id);
 		}
 	}
 
 	/**
 	 * Checks user permission to execute given $event
 	 *
 	 * @param kEvent $event
 	 * @return bool
 	 * @access public
 	 */
 	public function CheckPermission(&$event)
 	{
 		if (!$this->Application->isAdmin) {
 			if ($event->Name == 'OnSetSortingDirect') {
 				// allow sorting on front event without view permission
 				return true;
 			}
 		}
 
 		if ($event->Name == 'OnExport') {
 			// save category_id before doing export
 			$this->Application->LinkVar('m_cat_id');
 		}
 
 		if (in_array($event->Name, $this->_getMassPermissionEvents())) {
 			$items = $this->_getPermissionCheckInfo($event);
 
 			$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 			/* @var $perm_helper kPermissionsHelper */
 
 			if (($event->Name == 'OnSave') && array_key_exists(0, $items)) {
 				// adding new item (ID = 0)
 				$perm_value = $perm_helper->AddCheckPermission($items[0]['CategoryId'], $event->Prefix) > 0;
 			}
 			else {
 				// leave only items, that can be edited
 				$ids = Array ();
 				$check_method = in_array($event->Name, Array ('OnMassDelete', 'OnCut')) ? 'DeleteCheckPermission' : 'ModifyCheckPermission';
 				foreach ($items as $item_id => $item_data) {
 					if ($perm_helper->$check_method($item_data['CreatedById'], $item_data['CategoryId'], $event->Prefix) > 0) {
 						$ids[] = $item_id;
 					}
 				}
 
 				if (!$ids) {
 					// no items left for editing -> no permission
 					return $perm_helper->finalizePermissionCheck($event, false);
 				}
 
 				$perm_value = true;
 				$event->setEventParam('ids', $ids); // will be used later by "kDBEventHandler::StoreSelectedIDs" method
 			}
 
 			return $perm_helper->finalizePermissionCheck($event, $perm_value);
 		}
 
 		$export_events = Array ('OnSaveSettings', 'OnResetSettings', 'OnExportBegin');
 		if (in_array($event->Name, $export_events)) {
 			// when import settings before selecting target import category
 			return $this->Application->CheckPermission('in-portal:main_import.view');
 		}
 
 		if ($event->Name == 'OnProcessSelected') {
 			if ($this->Application->RecallVar('dst_field') == 'ImportCategory') {
 				// when selecting target import category
 				return $this->Application->CheckPermission('in-portal:main_import.view');
 			}
 		}
 
 		return parent::CheckPermission($event);
 	}
 
 	/**
 	 * Returns events, that require item-based (not just event-name based) permission check
 	 *
 	 * @return Array
 	 */
 	function _getMassPermissionEvents()
 	{
 		return Array (
 			'OnEdit', 'OnSave', 'OnMassDelete', 'OnMassApprove',
 			'OnMassDecline', 'OnMassMoveUp', 'OnMassMoveDown',
 			'OnCut',
 		);
 	}
 
 	/**
 	 * Returns category item IDs, that require permission checking
 	 *
 	 * @param kEvent $event
 	 * @return string
 	 */
 	function _getPermissionCheckIDs(&$event)
 	{
 		if ($event->Name == 'OnSave') {
 			$selected_ids = implode(',', $this->getSelectedIDs($event, true));
 			if (!$selected_ids) {
 				$selected_ids = 0; // when saving newly created item (OnPreCreate -> OnPreSave -> OnSave)
 			}
 		}
 		else {
 			// OnEdit, OnMassDelete events, when items are checked in grid
 			$selected_ids = implode(',', $this->StoreSelectedIDs($event));
 		}
 
 		return $selected_ids;
 	}
 
 	/**
 	 * Returns information used in permission checking
 	 *
 	 * @param kEvent $event
 	 * @return Array
 	 */
 	function _getPermissionCheckInfo(&$event)
 	{
 		$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 		/* @var $perm_helper kPermissionsHelper */
 
 		// when saving data from temp table to live table check by data from temp table
 		$item_ids = $this->_getPermissionCheckIDs($event);
 		$items = $perm_helper->GetCategoryItemData($event->Prefix, $item_ids, $event->Name == 'OnSave');
 
 		if (!$items) {
 			// when item not present in temp table, then permission is not checked, because there are no data in db to check
 			$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
 			list ($id, $fields_hash) = each($items_info);
 
 			if (array_key_exists('CategoryId', $fields_hash)) {
 				$item_category = $fields_hash['CategoryId'];
 			}
 			else {
 				$item_category = $this->Application->GetVar('m_cat_id');
 			}
 
 			$items[$id] = Array (
 				'CreatedById' => $this->Application->RecallVar('use_id'),
 				'CategoryId' => $item_category,
 			);
 		}
 
 		return $items;
 	}
 
 	/**
 	 * Add selected items to clipboard with mode = COPY (CLONE)
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnCopy(&$event)
 	{
 		$this->Application->RemoveVar('clipboard');
 
 		$clipboard_helper =& $this->Application->recallObject('ClipboardHelper');
 		/* @var $clipboard_helper kClipboardHelper */
 
 		$clipboard_helper->setClipboard($event, 'copy', $this->StoreSelectedIDs($event));
 		$this->clearSelectedIDs($event);
 	}
 
 	/**
 	 * Add selected items to clipboard with mode = CUT
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnCut(&$event)
 	{
 		$this->Application->RemoveVar('clipboard');
 		$clipboard_helper =& $this->Application->recallObject('ClipboardHelper');
 		/* @var $clipboard_helper kClipboardHelper */
 
 		$clipboard_helper->setClipboard($event, 'cut', $this->StoreSelectedIDs($event));
 		$this->clearSelectedIDs($event);
 	}
 
 	/**
 	 * Checks permission for OnPaste event
 	 *
 	 * @param kEvent $event
 	 * @return bool
 	 */
 	function _checkPastePermission(&$event)
 	{
 		$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 		/* @var $perm_helper kPermissionsHelper */
 
 		$category_id = $this->Application->GetVar('m_cat_id');
 		if ($perm_helper->AddCheckPermission($category_id, $event->Prefix) == 0) {
 			// no items left for editing -> no permission
 			return $perm_helper->finalizePermissionCheck($event, false);
 		}
 
 		return true;
 	}
 
 	/**
 	 * Performs category item paste
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnPaste(&$event)
 	{
 		if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) || !$this->_checkPastePermission($event) ) {
 			$event->status = kEvent::erFAIL;
 			return;
 		}
 
 		$clipboard_data = $event->getEventParam('clipboard_data');
 
 		if ( !$clipboard_data['cut'] && !$clipboard_data['copy'] ) {
 			return;
 		}
 
 		if ( $clipboard_data['copy'] ) {
 			$temp =& $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler');
 			/* @var $temp kTempTablesHandler */
 
 			$this->Application->SetVar('ResetCatBeforeClone', 1); // used in "kCatDBEventHandler::OnBeforeClone"
 			$temp->CloneItems($event->Prefix, $event->Special, $clipboard_data['copy']);
 		}
 
 		if ( $clipboard_data['cut'] ) {
 			$object =& $this->Application->recallObject($event->getPrefixSpecial() . '.item', $event->Prefix, Array ('skip_autoload' => true));
 			/* @var $object kCatDBItem */
 
 			foreach ($clipboard_data['cut'] as $id) {
 				$object->Load($id);
 				$object->MoveToCat();
 			}
 		}
 	}
 
 	/**
 	 * Deletes all selected items.
 	 * Automatically recurse into sub-items using temp handler, and deletes sub-items
 	 * by calling its Delete method if sub-item has AutoDelete set to true in its config file
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnMassDelete(&$event)
 	{
 		if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
 			$event->status = kEvent::erFAIL;
 			return;
 		}
 
 		$ids = $this->StoreSelectedIDs($event);
 
 		$to_delete = Array ();
 
 		if ( $recycle_bin = $this->Application->ConfigValue('RecycleBinFolder') ) {
 			$rb =& $this->Application->recallObject('c.recycle', null, array ('skip_autoload' => true));
 			/* @var $rb CategoriesItem */
 
 			$rb->Load($recycle_bin);
 
 			$object =& $this->Application->recallObject($event->Prefix . '.recycleitem', null, Array ('skip_autoload' => true));
 			/* @var $object kCatDBItem */
 
 			foreach ($ids as $id) {
 				$object->Load($id);
 
 				if ( preg_match('/^' . preg_quote($rb->GetDBField('ParentPath'), '/') . '/', $object->GetDBField('ParentPath')) ) {
 					$to_delete[] = $id;
 					continue;
 				}
 
 				$object->MoveToCat($recycle_bin);
 			}
 
 			$ids = $to_delete;
 		}
 
 		$temp_handler =& $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler');
 		/* @var $temp_handler kTempTablesHandler */
 
 		$event->setEventParam('ids', $ids);
 		$this->customProcessing($event, 'before');
 		$ids = $event->getEventParam('ids');
 
 		if ( $ids ) {
 			$temp_handler->DeleteItems($event->Prefix, $event->Special, $ids);
 		}
 
 		$this->clearSelectedIDs($event);
 	}
 
 
 	/**
 	 * Return type clauses for list bulding on front
 	 *
 	 * @param kEvent $event
 	 * @return Array
 	 */
 	function getTypeClauses(&$event)
 	{
 		$types = $event->getEventParam('types');
 		$types = $types ? explode(',', $types) : Array ();
 
 		$except_types = $event->getEventParam('except');
 		$except_types = $except_types ? explode(',', $except_types) : Array ();
 
 		$type_clauses = Array();
 
 		$user_id = $this->Application->RecallVar('user_id');
 		$owner_field = $this->getOwnerField($event->Prefix);
 
 		$type_clauses['my_items']['include'] = '%1$s.'.$owner_field.' = '.$user_id;
 		$type_clauses['my_items']['except'] = '%1$s.'.$owner_field.' <> '.$user_id;
 		$type_clauses['my_items']['having_filter'] = false;
 
 		$type_clauses['pick']['include'] = '%1$s.EditorsPick = 1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
 		$type_clauses['pick']['except'] = '%1$s.EditorsPick! = 1 AND '.TABLE_PREFIX.'CategoryItems.PrimaryCat = 1';
 		$type_clauses['pick']['having_filter'] = false;
 
 		$type_clauses['hot']['include'] = '`IsHot` = 1 AND PrimaryCat = 1';
 		$type_clauses['hot']['except'] = '`IsHot`! = 1 AND PrimaryCat = 1';
 		$type_clauses['hot']['having_filter'] = true;
 
 		$type_clauses['pop']['include'] = '`IsPop` = 1 AND PrimaryCat = 1';
 		$type_clauses['pop']['except'] = '`IsPop`! = 1 AND PrimaryCat = 1';
 		$type_clauses['pop']['having_filter'] = true;
 
 		$type_clauses['new']['include'] = '`IsNew` = 1 AND PrimaryCat = 1';
 		$type_clauses['new']['except'] = '`IsNew`! = 1 AND PrimaryCat = 1';
 		$type_clauses['new']['having_filter'] = true;
 
 		$type_clauses['displayed']['include'] = '';
 		$displayed = $this->Application->GetVar($event->Prefix.'_displayed_ids');
 		if ($displayed) {
 			$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
 			$type_clauses['displayed']['except'] = '%1$s.'.$id_field.' NOT IN ('.$displayed.')';
 		}
 		else {
 			$type_clauses['displayed']['except'] = '';
 		}
 		$type_clauses['displayed']['having_filter'] = false;
 
 		if (in_array('search', $types) || in_array('search', $except_types)) {
 			$event_mapping = Array (
 				'simple'		=>	'OnSimpleSearch',
 				'subsearch'		=>	'OnSubSearch',
 				'advanced'		=>	'OnAdvancedSearch'
 			);
 
 			$type = $this->Application->GetVar('search_type', 'simple');
 
 			if ($keywords = $event->getEventParam('keyword_string')) {
 				// processing keyword_string param of ListProducts tag
 				$this->Application->SetVar('keywords', $keywords);
 				$type = 'simple';
 			}
 
 			$search_event = $event_mapping[$type];
 			$this->$search_event($event);
 
 			$object =& $event->getObject();
 			/* @var $object kDBList */
 
 			$search_sql = '	FROM ' . TABLE_PREFIX . 'ses_' . $this->Application->GetSID() . '_' . TABLE_PREFIX . 'Search
 							search_result LEFT JOIN %1$s ON %1$s.ResourceId = search_result.ResourceId';
-			$sql = str_replace('FROM %1$s', $search_sql, $object->SelectClause);
+			$sql = str_replace('FROM %1$s', $search_sql, $object->GetPlainSelectSQL());
 
 			$object->SetSelectSQL($sql);
 
 			$object->addCalculatedField('Relevance', 'search_result.Relevance');
 			$object->AddOrderField('search_result.Relevance', 'desc', true);
 
 			$type_clauses['search']['include'] = 'PrimaryCat = 1 AND ('.TABLE_PREFIX.'Category.Status = '.STATUS_ACTIVE.')';
 			$type_clauses['search']['except'] = 'PrimaryCat = 1 AND ('.TABLE_PREFIX.'Category.Status = '.STATUS_ACTIVE.')';
 			$type_clauses['search']['having_filter'] = false;
 		}
 
 		if (in_array('related', $types) || in_array('related', $except_types)) {
 
 			$related_to = $event->getEventParam('related_to');
 			if (!$related_to) {
 				$related_prefix = $event->Prefix;
 			}
 			else {
 				$sql = 'SELECT Prefix
 						FROM '.TABLE_PREFIX.'ItemTypes
 						WHERE ItemName = '.$this->Conn->qstr($related_to);
 				$related_prefix = $this->Conn->GetOne($sql);
 			}
 
 			$rel_table = $this->Application->getUnitOption('rel', 'TableName');
 			$item_type = (int)$this->Application->getUnitOption($event->Prefix, 'ItemType');
 
 			if ($item_type == 0) {
 				trigger_error('<strong>ItemType</strong> not defined for prefix <strong>' . $event->Prefix . '</strong>', E_USER_WARNING);
 			}
 
 			// process case, then this list is called inside another list
 			$prefix_special = $event->getEventParam('PrefixSpecial');
 			if (!$prefix_special) {
 				$prefix_special = $this->Application->Parser->GetParam('PrefixSpecial');
 			}
 
 			$id = false;
 			if ($prefix_special !== false) {
 				$processed_prefix = $this->Application->processPrefix($prefix_special);
 				if ($processed_prefix['prefix'] == $related_prefix) {
 					// printing related categories within list of items (not on details page)
 					$list =& $this->Application->recallObject($prefix_special);
 					/* @var $list kDBList */
 
 					$id = $list->GetID();
 				}
 			}
 
 			if ($id === false) {
 				// printing related categories for single item (possibly on details page)
 				if ($related_prefix == 'c') {
 					$id = $this->Application->GetVar('m_cat_id');
 				}
 				else {
 					$id = $this->Application->GetVar($related_prefix . '_id');
 				}
 			}
 
 			$p_item =& $this->Application->recallObject($related_prefix.'.current', null, Array('skip_autoload' => true));
 			/* @var $p_item kCatDBItem */
-			
+
 			$p_item->Load( (int)$id );
 
 			$p_resource_id = $p_item->GetDBField('ResourceId');
 
 			$sql = 'SELECT SourceId, TargetId FROM '.$rel_table.'
 					WHERE
 						(Enabled = 1)
 						AND (
 								(Type = 0 AND SourceId = '.$p_resource_id.' AND TargetType = '.$item_type.')
 								OR
 								(Type = 1
 									AND (
 											(SourceId = '.$p_resource_id.' AND TargetType = '.$item_type.')
 											OR
 											(TargetId = '.$p_resource_id.' AND SourceType = '.$item_type.')
 										)
 								)
 						)';
 
 			$related_ids_array = $this->Conn->Query($sql);
 			$related_ids = Array();
 
 			foreach ($related_ids_array as $key => $record) {
 				$related_ids[] = $record[ $record['SourceId'] == $p_resource_id ? 'TargetId' : 'SourceId' ];
 			}
 
 			if (count($related_ids) > 0) {
 				$type_clauses['related']['include'] = '%1$s.ResourceId IN ('.implode(',', $related_ids).') AND PrimaryCat = 1';
 				$type_clauses['related']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $related_ids).') AND PrimaryCat = 1';
 			}
 			else {
 				$type_clauses['related']['include'] = '0';
 				$type_clauses['related']['except'] = '1';
 			}
 			$type_clauses['related']['having_filter'] = false;
 		}
 
 		if (in_array('favorites', $types) || in_array('favorites', $except_types)) {
 			$sql = 'SELECT ResourceId
 					FROM '.$this->Application->getUnitOption('fav', 'TableName').'
 					WHERE PortalUserId = '.$this->Application->RecallVar('user_id');
 			$favorite_ids = $this->Conn->GetCol($sql);
 			if ($favorite_ids) {
 				$type_clauses['favorites']['include'] = '%1$s.ResourceId IN ('.implode(',', $favorite_ids).') AND PrimaryCat = 1';
 				$type_clauses['favorites']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $favorite_ids).') AND PrimaryCat = 1';
 			}
 			else {
 				$type_clauses['favorites']['include'] = 0;
 				$type_clauses['favorites']['except'] = 1;
 			}
 			$type_clauses['favorites']['having_filter'] = false;
 		}
 
 		return $type_clauses;
 	}
 
 	/**
 	 * Returns SQL clause, that will help to select only data from specified category & it's children
 	 *
 	 * @param int $category_id
 	 * @return string
 	 */
 	function getCategoryLimitClause($category_id)
 	{
 		if (!$category_id) {
 			return false;
 		}
 
 		$tree_indexes = $this->Application->getTreeIndex($category_id);
 		if (!$tree_indexes) {
 			// id of non-existing category was given
 			return 'FALSE';
 		}
 
 		return TABLE_PREFIX.'Category.TreeLeft BETWEEN '.$tree_indexes['TreeLeft'].' AND '.$tree_indexes['TreeRight'];
 	}
 
 	/**
 	 * Apply any custom changes to list's sql query
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 * @see kDBEventHandler::OnListBuild()
 	 */
 	protected function SetCustomQuery(&$event)
 	{
 		parent::SetCustomQuery($event);
 
 		$object =& $event->getObject();
 		/* @var $object kDBList */
 
 		// add category filter if needed
 		if ($event->Special != 'showall' && $event->Special != 'user') {
 			if ($event->getEventParam('parent_cat_id') !== false) {
 				$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 ("$parent_cat_id" == '0') {
 				// replace "0" category with "Content" category id (this way template
 				$parent_cat_id = $this->Application->getBaseCategory();
 			}
 
 			if ((string)$parent_cat_id != 'any') {
 				if ($event->getEventParam('recursive')) {
 					$filter_clause = $this->getCategoryLimitClause($parent_cat_id);
 					if ($filter_clause !== false) {
 						$object->addFilter('category_filter', $filter_clause);
 					}
 
 					$object->addFilter('primary_filter', 'PrimaryCat = 1');
 				}
 				else {
 					$object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId = '.$parent_cat_id );
 				}
 			}
 			else {
 				$object->addFilter('primary_filter', 'PrimaryCat = 1');
 			}
 		}
 		else {
 			$object->addFilter('primary_filter', 'PrimaryCat = 1');
 
 			// if using recycle bin don't show items from there
 			$recycle_bin = $this->Application->ConfigValue('RecycleBinFolder');
 			if ($recycle_bin) {
 				$object->addFilter('recyclebin_filter', TABLE_PREFIX.'CategoryItems.CategoryId <> '.$recycle_bin);
 			}
 		}
 
 		if ($event->Special == 'user') {
 			$editable_user = $this->Application->GetVar('u_id');
 			$object->addFilter('owner_filter', '%1$s.'.$this->getOwnerField($event->Prefix).' = '.$editable_user);
 		}
 
 		// add permission filter
 		if ($this->Application->RecallVar('user_id') == USER_ROOT) {
 			// for "root" CATEGORY.VIEW permission is checked for items lists too
 			$view_perm = 1;
 		}
 		else {
 			// for any real user itemlist view permission is checked instead of CATEGORY.VIEW
 			$count_helper =& $this->Application->recallObject('CountHelper');
 			/* @var $count_helper kCountHelper */
 
 			list ($view_perm, $view_filter) = $count_helper->GetPermissionClause($event->Prefix, 'perm');
 			$object->addFilter('perm_filter2', $view_filter);
 		}
 
 		$object->addFilter('perm_filter', 'perm.PermId = '.$view_perm);
 
 
 		$types = $event->getEventParam('types');
 		$this->applyItemStatusFilter($object, $types);
 
 		$except_types = $event->getEventParam('except');
 		$type_clauses = $this->getTypeClauses($event);
 
 		$search_helper =& $this->Application->recallObject('SearchHelper');
 		/* @var $search_helper kSearchHelper */
 
 		$search_helper->SetComplexFilter($event, $type_clauses, $types, $except_types);
 	}
 
 	/**
 	 * Adds filter that filters out items with non-required statuses
 	 *
 	 * @param kDBList $object
 	 * @param string $types
 	 */
 	function applyItemStatusFilter(&$object, $types)
 	{
 		// Link1 (before modifications) [Status = 1, OrgId = NULL], Link2 (after modifications) [Status = -2, OrgId = Link1_ID]
 		$pending_editing = $this->Application->getUnitOption($object->Prefix, 'UsePendingEditing');
 
 		if (!$this->Application->isAdminUser) {
 			$types = explode(',', $types);
 			if (in_array('my_items', $types)) {
 				$allow_statuses = Array (STATUS_ACTIVE, STATUS_PENDING, STATUS_PENDING_EDITING);
 				$object->addFilter('status_filter', '%1$s.Status IN ('.implode(',', $allow_statuses).')');
 
 				if ($pending_editing) {
 					$user_id = $this->Application->RecallVar('user_id');
 					$this->applyPendingEditingFilter($object, $user_id);
 				}
 			}
 			else {
 				$object->addFilter('status_filter', '(%1$s.Status = ' . STATUS_ACTIVE . ') AND (' . TABLE_PREFIX . 'Category.Status = ' . STATUS_ACTIVE . ')');
 				if ($pending_editing) {
 					// if category item uses pending editing abilities, then in no cases show pending copies on front
 					$object->addFilter('original_filter', '%1$s.OrgId = 0 OR %1$s.OrgId IS NULL');
 				}
 			}
 		}
 		else {
 			if ($pending_editing) {
 				$this->applyPendingEditingFilter($object);
 			}
 		}
 	}
 
 	/**
 	 * Adds filter, that removes live items if they have pending editing copies
 	 *
 	 * @param kDBList $object
 	 * @param int $user_id
 	 */
 	function applyPendingEditingFilter(&$object, $user_id = null)
 	{
 		$sql = 'SELECT OrgId
 				FROM '.$object->TableName.'
 				WHERE Status = '.STATUS_PENDING_EDITING.' AND OrgId IS NOT NULL';
 
 		if (isset($user_id)) {
 			$owner_field = $this->getOwnerField($object->Prefix);
 			$sql .= ' AND '.$owner_field.' = '.$user_id;
 		}
 
 		$pending_ids = $this->Conn->GetCol($sql);
 		if ($pending_ids) {
 			$object->addFilter('no_original_filter', '%1$s.'.$object->IDField.' NOT IN ('.implode(',', $pending_ids).')');
 		}
 	}
 
 	/**
 	 * Adds calculates fields for item statuses
 	 *
 	 * @param kDBItem|kDBList $object
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function prepareObject(&$object, &$event)
 	{
 		$this->prepareItemStatuses($event);
 
 		$object->addCalculatedField('CachedNavbar', 'l'.$this->Application->GetVar('m_lang').'_CachedNavbar');
 
 		if ($event->Special == 'export' || $event->Special == 'import') {
 			$export_helper =& $this->Application->recallObject('CatItemExportHelper');
 			/* @var $export_helper kCatDBItemExportHelper */
-			
+
 			$export_helper->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_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
 		if (!$property_map) {
 			return ;
 		}
 
 		// new items
 		$object->addCalculatedField('IsNew', '	IF(%1$s.NewItem = 2,
 													IF(%1$s.CreatedOn >= (UNIX_TIMESTAMP() - '.
 														$this->Application->ConfigValue($property_map['NewDays']).
 														'*3600*24), 1, 0),
 													%1$s.NewItem
 												)');
 
 		// hot items (cache updated every hour)
 		if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
 			$serial_name = $this->Application->incrementCacheSerial($event->Prefix, null, false);
 			$hot_limit = $this->Application->getCache($property_map['HotLimit'] . '[%' . $serial_name . '%]');
 		}
 		else {
 			$hot_limit = $this->Application->getDBCache($property_map['HotLimit']);
 		}
 
 		if ($hot_limit === false) {
 			$hot_limit = $this->CalculateHotLimit($event);
 		}
 
 		$object->addCalculatedField('IsHot', '	IF(%1$s.HotItem = 2,
 													IF(%1$s.'.$property_map['ClickField'].' >= '.$hot_limit.', 1, 0),
 													%1$s.HotItem
 												)');
 
 		// popular items
 		$object->addCalculatedField('IsPop', '	IF(%1$s.PopItem = 2,
 													IF(%1$s.CachedVotesQty >= '.
 														$this->Application->ConfigValue($property_map['MinPopVotes']).
 														' AND %1$s.CachedRating >= '.
 														$this->Application->ConfigValue($property_map['MinPopRating']).
 														', 1, 0),
 													%1$s.PopItem)');
 
 	}
 
 	/**
 	 * Calculates hot limit for current item's table
-	 * 
+	 *
 	 * @param kEvent $event
 	 * @return float
 	 * @access protected
 	 */
 	protected function CalculateHotLimit(&$event)
 	{
 		$property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
 
 		if ( !$property_map ) {
 			return 0.00;
 		}
 
 		$click_field = $property_map['ClickField'];
 
 		$last_hot = $this->Application->ConfigValue($property_map['MaxHotNumber']) - 1;
 		$sql = 'SELECT ' . $click_field . '
 				FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
 				ORDER BY ' . $click_field . ' DESC
 				LIMIT ' . $last_hot . ', 1';
 		$res = $this->Conn->GetCol($sql);
 		$hot_limit = (double)array_shift($res);
 
 		if ( $this->Application->isCachingType(CACHING_TYPE_MEMORY) ) {
 			$serial_name = $this->Application->incrementCacheSerial($event->Prefix, null, false);
 			$this->Application->setCache($property_map['HotLimit'] . '[%' . $serial_name . '%]', $hot_limit);
 		}
 		else {
 			$this->Application->setDBCache($property_map['HotLimit'], $hot_limit, 3600);
 		}
 
 		return $hot_limit;
 	}
 
 	/**
 	 * Moves item to preferred category, updates item hits
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnBeforeItemUpdate(&$event)
 	{
 		parent::OnBeforeItemUpdate($event);
 
 		$object =& $event->getObject();
 		/* @var $object kCatDBItem */
 
 		// update hits field
 		$property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings');
 		if ( $property_map ) {
 			$click_field = $property_map['ClickField'];
 
 			if ( $this->Application->isAdminUser && ($this->Application->GetVar($click_field . '_original') !== false) && floor($this->Application->GetVar($click_field . '_original')) != $object->GetDBField($click_field) ) {
 				$sql = 'SELECT MAX(' . $click_field . ')
 						FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
 						WHERE FLOOR(' . $click_field . ') = ' . $object->GetDBField($click_field);
 				$hits = ($res = $this->Conn->GetOne($sql)) ? $res + 0.000001 : $object->GetDBField($click_field);
 
 				$object->SetDBField($click_field, $hits);
 			}
 		}
 
 		// change category
 		$target_category = $object->GetDBField('CategoryId');
 		if ( $object->GetOriginalField('CategoryId') != $target_category ) {
 			$object->MoveToCat($target_category);
 		}
 	}
 
 	/**
 	 * Occurs after loading item, 'id' parameter
 	 * allows to get id of item that was loaded
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnAfterItemLoad(&$event)
 	{
 		parent::OnAfterItemLoad($event);
 
 		$special = substr($event->Special, -6);
 
 		$object =& $event->getObject();
 		/* @var $object kCatDBItem */
 
 		if ( $special == 'import' || $special == 'export' ) {
 			$image_data = $object->getPrimaryImageData();
 
 			if ( $image_data ) {
 				$thumbnail_image = $image_data[$image_data['LocalThumb'] ? 'ThumbPath' : 'ThumbUrl'];
 				if ( $image_data['SameImages'] ) {
 					$full_image = '';
 				}
 				else {
 					$full_image = $image_data[$image_data['LocalImage'] ? 'LocalPath' : 'Url'];
 				}
 
 				$object->SetDBField('ThumbnailImage', $thumbnail_image);
 				$object->SetDBField('FullImage', $full_image);
 				$object->SetDBField('ImageAlt', $image_data['AltName']);
 			}
 		}
 
 		// substituting pending status value for pending editing
 		if ( $object->HasField('OrgId') && $object->GetDBField('OrgId') > 0 && $object->GetDBField('Status') == -2 ) {
 			$new_options = Array ();
 			$options = $object->GetFieldOption('Status', 'options', false, Array ());
 
 			foreach ($options as $key => $val) {
 				if ( $key == 2 ) {
 					$key = -2;
 				}
 
 				$new_options[$key] = $val;
 			}
 
 			$object->SetFieldOption('Status', 'options', $new_options);
 		}
 
 		if ( !$this->Application->isAdmin ) {
 			// linking existing images for item with virtual fields
 			$image_helper =& $this->Application->recallObject('ImageHelper');
 			/* @var $image_helper ImageHelper */
 
 			$image_helper->LoadItemImages($object);
 
 			// linking existing files for item with virtual fields
 			$file_helper =& $this->Application->recallObject('FileHelper');
 			/* @var $file_helper FileHelper */
 
 			$file_helper->LoadItemFiles($object);
 		}
 
 		if ( $object->isVirtualField('MoreCategories') ) {
 			// set item's additional categories to virtual field (used in editing)
 			$item_categories = $this->getItemCategories($object->GetDBField('ResourceId'));
 			$object->SetDBField('MoreCategories', $item_categories ? '|' . implode('|', $item_categories) . '|' : '');
 		}
 	}
 
 	/**
 	 * Occurs after updating item
 	 *
 	 * @param kEvent $event
 	 * @access public
 	 */
 	function OnAfterItemUpdate(&$event)
 	{
 		$this->CalculateHotLimit($event);
 
 		if ( substr($event->Special, -6) == 'import' ) {
 			$this->setCustomExportColumns($event);
 		}
 
 		$object =& $event->getObject();
 		/* @var $object kCatDBItem */
 
 		if ( !$this->Application->isAdmin ) {
 			$image_helper =& $this->Application->recallObject('ImageHelper');
 			/* @var $image_helper ImageHelper */
 
 			// process image upload in virtual fields
 			$image_helper->SaveItemImages($object);
 
 			$file_helper =& $this->Application->recallObject('FileHelper');
 			/* @var $file_helper FileHelper */
 
 			// process file upload in virtual fields
 			$file_helper->SaveItemFiles($object);
 
 			if ( $event->Special != '-item' ) {
 				// don't touch categories during cloning
 				$this->processAdditionalCategories($object, 'update');
 			}
 		}
 
 		$recycle_bin = $this->Application->ConfigValue('RecycleBinFolder');
 
 		if ( $this->Application->isAdminUser && $recycle_bin ) {
 			$sql = 'SELECT CategoryId
 					FROM ' . $this->Application->getUnitOption('ci', 'TableName') . '
 					WHERE ItemResourceId = ' . $object->GetDBField('ResourceId') . ' AND PrimaryCat = 1';
 			$primary_category = $this->Conn->GetOne($sql);
 
 			if ( $primary_category == $recycle_bin ) {
 				$event->CallSubEvent('OnAfterItemDelete');
 			}
 		}
 	}
 
 	/**
 	 * Sets values for import process
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnAfterItemCreate(&$event)
 	{
 		parent::OnAfterItemCreate($event);
 
 		if ( substr($event->Special, -6) == 'import' ) {
 			$this->setCustomExportColumns($event);
 		}
 
 		if ( !$this->Application->isAdmin ) {
 			$object =& $event->getObject();
 			/* @var $object kCatDBItem */
 
 			$image_helper =& $this->Application->recallObject('ImageHelper');
 			/* @var $image_helper ImageHelper */
 
 			// process image upload in virtual fields
 			$image_helper->SaveItemImages($object);
 
 			$file_helper =& $this->Application->recallObject('FileHelper');
 			/* @var $file_helper FileHelper */
 
 			// process file upload in virtual fields
 			$file_helper->SaveItemFiles($object);
 
 			if ( $event->Special != '-item' ) {
 				// don't touch categories during cloning
 				$this->processAdditionalCategories($object, 'create');
 			}
 		}
 	}
 
 	/**
 	 * Make record to search log
 	 *
 	 * @param string $keywords
 	 * @param int $search_type 0 - simple search, 1 - advanced search
 	 */
 	function saveToSearchLog($keywords, $search_type = 0)
 	{
 		// don't save keywords for each module separately, just one time
 		// static variable can't help here, because each module uses it's own class instance !
 		if (!$this->Application->GetVar('search_logged')) {
 			$sql = 'UPDATE '.TABLE_PREFIX.'SearchLog
 					SET Indices = Indices + 1
 					WHERE Keyword = '.$this->Conn->qstr($keywords).' AND SearchType = '.$search_type; // 0 - simple search, 1 - advanced search
 	        $this->Conn->Query($sql);
 	        if ($this->Conn->getAffectedRows() == 0) {
 	            $fields_hash = Array('Keyword' => $keywords, 'Indices' => 1, 'SearchType' => $search_type);
 	        	$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'SearchLog');
 	        }
 
 	        $this->Application->SetVar('search_logged', 1);
 		}
 	}
 
 	/**
 	 * Makes simple search for category items
 	 * based on keywords string
 	 *
 	 * @param kEvent $event
 	 */
 	function OnSimpleSearch(&$event)
 	{
 		$event->redirect = false;
 		$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
 
 		$keywords = kUtil::unhtmlentities( trim($this->Application->GetVar('keywords')) );
 
 		$query_object =& $this->Application->recallObject('HTTPQuery');
 		/* @var $query_object kHTTPQuery */
-		
+
 		$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);
 
 		$this->saveToSearchLog($keywords, 0); // 0 - simple search, 1 - advanced search
 
 		$event->setPseudoClass('_List');
 
 		$object =& $event->getObject();
 		/* @var $object kDBList */
 
 		$this->Application->SetVar($event->getPrefixSpecial().'_Page', 1);
 		$lang = $this->Application->GetVar('m_lang');
 		$items_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
 		$module_name = $this->Application->findModule('Var', $event->Prefix, 'Name');
 
 		$sql = 'SELECT *
 				FROM ' . $this->Application->getUnitOption('confs', 'TableName') . '
 				WHERE ModuleName = ' . $this->Conn->qstr($module_name) . ' AND SimpleSearch = 1';
 		$search_config = $this->Conn->Query($sql, 'FieldName');
 
 		$field_list = array_keys($search_config);
 
 		$join_clauses = Array();
 
 		// field processing
 		$weight_sum = 0;
 
 		$alias_counter = 0;
 
 		$custom_fields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
 		if ($custom_fields) {
 			$custom_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName');
 			$join_clauses[] = '	LEFT JOIN '.$custom_table.' custom_data ON '.$items_table.'.ResourceId = custom_data.ResourceId';
 		}
 
 		// what field in search config becomes what field in sql (key - new field, value - old field (from searchconfig table))
 		$search_config_map = Array();
 
 		foreach ($field_list as $key => $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 ( $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage' ) {
+			if ( !$search_config[$field]['CustomFieldId'] && $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage' ) {
 				$field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field;
 				$field_list[$key] = 'l'.$lang.'_'.$field;
 
 				if (!isset($search_config[$field]['ForeignField'])) {
 					$field_list[$key.'_primary'] = $local_table.'.'.$field_list[$key.'_primary'];
 					$search_config_map[ $field_list[$key.'_primary'] ] = $field;
 				}
 			}
 
 			// processing fields from other tables
 			if ($foreign_field = $search_config[$field]['ForeignField']) {
 				$exploded = explode(':', $foreign_field, 2);
 				if ($exploded[0] == 'CALC') {
 					// ignoring having type clauses in simple search
 					unset($field_list[$key]);
 					continue;
 				}
 				else {
 					$multi_lingual = false;
 					if ($exploded[0] == 'MULTI') {
 						$multi_lingual = true;
 						$foreign_field = $exploded[1];
 					}
 
 					$exploded = explode('.', $foreign_field);	// format: table.field_name
 					$foreign_table = TABLE_PREFIX.$exploded[0];
 
 					$alias_counter++;
 					$alias = 't'.$alias_counter;
 
 					if ($multi_lingual) {
 						$field_list[$key] = $alias.'.'.'l'.$lang.'_'.$exploded[1];
 						$field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field;
 						$search_config_map[ $field_list[$key] ] = $field;
 						$search_config_map[ $field_list[$key.'_primary'] ] = $field;
 					}
 					else {
 						$field_list[$key] = $alias.'.'.$exploded[1];
 						$search_config_map[ $field_list[$key] ] = $field;
 					}
 
 					$join_clause = str_replace('{ForeignTable}', $alias, $search_config[$field]['JoinClause']);
 					$join_clause = str_replace('{LocalTable}', $items_table, $join_clause);
 
 					$join_clauses[] = '	LEFT JOIN '.$foreign_table.' '.$alias.'
 										ON '.$join_clause;
 				}
 			}
 			else {
 				// processing fields from local table
 				if ($search_config[$field]['CustomFieldId']) {
 					$local_table = 'custom_data';
 
 					// search by custom field value on current language
 					$custom_field_id = array_search($field_list[$key], $custom_fields);
 					$field_list[$key] = 'l'.$lang.'_cust_'.$custom_field_id;
 
 					// search by custom field value on primary language
 					$field_list[$key.'_primary'] = $local_table.'.l'.$this->Application->GetDefaultLanguageId().'_cust_'.$custom_field_id;
 					$search_config_map[ $field_list[$key.'_primary'] ] = $field;
 				}
 
 				$field_list[$key] = $local_table.'.'.$field_list[$key];
 				$search_config_map[ $field_list[$key] ] = $field;
 			}
 		}
 
 		// keyword string processing
 		$search_helper =& $this->Application->recallObject('SearchHelper');
 		/* @var $search_helper kSearchHelper */
 
 		$where_clause = Array ();
 		foreach ($field_list as $field) {
 			if (preg_match('/^' . preg_quote($items_table, '/') . '\.(.*)/', $field, $regs)) {
 				// local real field
 				$filter_data = $search_helper->getSearchClause($object, $regs[1], $keywords, false);
 				if ($filter_data) {
 					$where_clause[] = $filter_data['value'];
 				}
 			}
 			elseif (preg_match('/^custom_data\.(.*)/', $field, $regs)) {
 				$custom_field_name = 'cust_' . $search_config_map[$field];
 				$filter_data = $search_helper->getSearchClause($object, $custom_field_name, $keywords, false);
 				if ($filter_data) {
 					$where_clause[] = str_replace('`' . $custom_field_name . '`', $field, $filter_data['value']);
 				}
 			}
 			else {
 				$where_clause[] = $search_helper->buildWhereClause($keywords, Array ($field));
 			}
 		}
 
 		$where_clause = '((' . implode(') OR (', $where_clause) . '))'; // 2 braces for next clauses, see below!
 
 		$search_scope = $this->Application->GetVar('search_scope');
 		if ($search_scope == 'category') {
 			$category_id = $this->Application->GetVar('m_cat_id');
 			$category_filter = $this->getCategoryLimitClause($category_id);
 			if ($category_filter !== false) {
 				$join_clauses[] = ' LEFT JOIN '.TABLE_PREFIX.'CategoryItems ON '.TABLE_PREFIX.'CategoryItems.ItemResourceId = '.$items_table.'.ResourceId';
 				$join_clauses[] = ' LEFT JOIN '.TABLE_PREFIX.'Category ON '.TABLE_PREFIX.'Category.CategoryId = '.TABLE_PREFIX.'CategoryItems.CategoryId';
 
 				$where_clause = '('.$this->getCategoryLimitClause($category_id).') AND '.$where_clause;
 			}
 		}
 
 		$where_clause = $where_clause . ' AND (' . $items_table . '.Status = ' . STATUS_ACTIVE . ')';
 
 		if ($event->MasterEvent && $event->MasterEvent->Name == 'OnListBuild') {
 			if ($event->MasterEvent->getEventParam('ResultIds')) {
 				$where_clause .= ' AND '.$items_table.'.ResourceId IN ('.implode(',', $event->MasterEvent->getEventParam('ResultIds')).')';
 			}
 		}
 
 		// making relevance clause
 		$positive_words = $search_helper->getPositiveKeywords($keywords);
 		$this->Application->StoreVar('highlight_keywords', serialize($positive_words));
 		$revelance_parts = Array();
 		reset($search_config);
 
 		foreach ($positive_words as $keyword_index => $positive_word) {
 			$positive_word = $search_helper->transformWildcards($positive_word);
 			$positive_words[$keyword_index] = $this->Conn->escape($positive_word);
 		}
 
 		foreach ($field_list as $field) {
 
 			if (!array_key_exists($field, $search_config_map)) {
 				$map_key = $search_config_map[$items_table . '.' . $field];
 			}
 			else {
 				$map_key = $search_config_map[$field];
 			}
 
 			$config_elem = $search_config[ $map_key ];
 			$weight = $config_elem['Priority'];
 
 			// search by whole words only ([[:<:]] - word boundary)
 			/*$revelance_parts[] = 'IF('.$field.' REGEXP "[[:<:]]('.implode(' ', $positive_words).')[[:>:]]", '.$weight.', 0)';
 			foreach ($positive_words as $keyword) {
 				$revelance_parts[] = 'IF('.$field.' REGEXP "[[:<:]]('.$keyword.')[[:>:]]", '.$weight.', 0)';
 			}*/
 
 			// search by partial word matches too
 			$revelance_parts[] = 'IF('.$field.' LIKE "%'.implode(' ', $positive_words).'%", '.$weight_sum.', 0)';
 			foreach ($positive_words as $keyword) {
 				$revelance_parts[] = 'IF('.$field.' LIKE "%'.$keyword.'%", '.$weight.', 0)';
 			}
 		}
 
 		$revelance_parts = array_unique($revelance_parts);
 
 		$conf_postfix = $this->Application->getUnitOption($event->Prefix, 'SearchConfigPostfix');
 		$rel_keywords	= $this->Application->ConfigValue('SearchRel_Keyword_'.$conf_postfix)	/ 100;
 		$rel_pop		= $this->Application->ConfigValue('SearchRel_Pop_'.$conf_postfix)		/ 100;
 		$rel_rating		= $this->Application->ConfigValue('SearchRel_Rating_'.$conf_postfix)	/ 100;
 		$relevance_clause = '('.implode(' + ', $revelance_parts).') / '.$weight_sum.' * '.$rel_keywords;
 		if ($rel_pop && $object->isField('Hits')) {
 			$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
 		}
 		if ($rel_rating && $object->isField('CachedRating')) {
 			$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
 		}
 
 		// building final search query
 		if (!$this->Application->GetVar('do_not_drop_search_table')) {
 			$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); // erase old search table if clean k4 event
 			$this->Application->SetVar('do_not_drop_search_table', true);
 		}
 
 
 		$search_table_exists = $this->Conn->Query('SHOW TABLES LIKE "'.$search_table.'"');
 		if ($search_table_exists) {
 			$select_intro = 'INSERT INTO '.$search_table.' (Relevance, ItemId, ResourceId, ItemType, EdPick) ';
 		}
 		else {
 			$select_intro = 'CREATE TABLE '.$search_table.' AS ';
 		}
 
 		$edpick_clause = $this->Application->getUnitOption($event->Prefix.'.EditorsPick', 'Fields') ? $items_table.'.EditorsPick' : '0';
 
 
 		$sql = $select_intro.' SELECT '.$relevance_clause.' AS Relevance,
 							'.$items_table.'.'.$this->Application->getUnitOption($event->Prefix, 'IDField').' AS ItemId,
 							'.$items_table.'.ResourceId,
 							'.$this->Application->getUnitOption($event->Prefix, 'ItemType').' AS ItemType,
 							 '.$edpick_clause.' AS EdPick
 					FROM '.$object->TableName.'
 					'.implode(' ', $join_clauses).'
 					WHERE '.$where_clause.'
 					GROUP BY '.$items_table.'.'.$this->Application->getUnitOption($event->Prefix, 'IDField').' ORDER BY Relevance DESC';
 
 		$res = $this->Conn->Query($sql);
 
 		if ( !$search_table_exists ) {
 			$sql = 'ALTER TABLE ' . $search_table . '
 					ADD INDEX (ResourceId),
 					ADD INDEX (Relevance)';
 			$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');
 		/* @var $query_object kHTTPQuery */
 
 		if ( !isset($query_object->Post['andor']) ) {
 			// used when navigating by pages or changing sorting in search results
 			return;
 		}
 
 		$this->Application->RemoveVar('keywords');
 		$this->Application->RemoveVar('Search_Keywords');
 
 		$module_name = $this->Application->findModule('Var', $event->Prefix, 'Name');
 
 		$sql = 'SELECT *
 				FROM '.$this->Application->getUnitOption('confs', 'TableName').'
 				WHERE (ModuleName = '.$this->Conn->qstr($module_name).') AND (AdvancedSearch = 1)';
 		$search_config = $this->Conn->Query($sql);
 
 		$lang = $this->Application->GetVar('m_lang');
 
 		$object =& $event->getObject();
 		/* @var $object kDBList */
 
 		$object->SetPage(1);
 
 		$items_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
 
 		$search_keywords = $this->Application->GetVar('value'); // will not be changed
 
 		$keywords = $this->Application->GetVar('value'); // will be changed down there
 		$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();
 
 		$alias_counter = 0;
 
 		$custom_fields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
 		if ($custom_fields) {
 			$custom_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName');
 			$join_clauses[] = '	LEFT JOIN '.$custom_table.' custom_data ON '.$items_table.'.ResourceId = custom_data.ResourceId';
 		}
 
 		$search_log = '';
 		$weight_sum = 0;
 
 		// processing fields and preparing conditions
 		foreach ($search_config as $record) {
 			$field = $record['FieldName'];
 			$join_clause = '';
 			$condition_mode = 'WHERE';
 
 			// field processing
 			$local_table = TABLE_PREFIX.$record['TableName'];
 			$weight_sum += $record['Priority']; // counting weight sum; used when making relevance clause
 
 			// processing multilingual fields
 			if ( $object->GetFieldOption($field, '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 = $this->Application->RecallVar('UserGroups');
 					$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($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}', $items_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
 				if ($record['CustomFieldId']) {
 					$local_table = 'custom_data';
 					$field_name = 'l'.$lang.'_cust_'.array_search($field_name, $custom_fields);
 				}
 
 				$field_name = $local_table.'.'.$field_name;
 			}
 
 			$condition = $this->getAdvancedSearchCondition($field_name, $record, $keywords, $verbs, $highlight_keywords);
 			if ($record['CustomFieldId'] && strlen($condition)) {
 				// search in primary value of custom field + value in current language
 				$field_name = $local_table.'.'.'l'.$this->Application->GetDefaultLanguageId().'_cust_'.array_search($field, $custom_fields);
 				$primary_condition = $this->getAdvancedSearchCondition($field_name, $record, $keywords, $verbs, $highlight_keywords);
 				$condition = '('.$condition.' OR '.$primary_condition.')';
 			}
 
 			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;
 					}
 				}
 
 				// create search log record
 				$search_log_data = Array('search_config' => $record, 'verb' => getArrayValue($verbs, $field), 'value' => ($record['FieldType'] == 'range') ? $search_keywords[$field.'_from'].'|'.$search_keywords[$field.'_to'] : $search_keywords[$field]);
 				$search_log[] = $this->Application->Phrase('la_Field').' "'.$this->getHuman('Field', $search_log_data).'" '.$this->getHuman('Verb', $search_log_data).' '.$this->Application->Phrase('la_Value').' '.$this->getHuman('Value', $search_log_data).' '.$this->Application->Phrase($glues[$field] == 1 ? 'lu_And' : 'lu_Or');
 			}
 		}
 
 		if ($search_log) {
 			$search_log = implode('<br />', $search_log);
 	    	$search_log = preg_replace('/(.*) '.preg_quote($this->Application->Phrase('lu_and'), '/').'|'.preg_quote($this->Application->Phrase('lu_or'), '/').'$/is', '\\1', $search_log);
 	    	$this->saveToSearchLog($search_log, 1); // advanced search
 		}
 
 		$this->Application->StoreVar('highlight_keywords', serialize($highlight_keywords));
 
 		// making relevance clause
 		if($relevance_parts)
 		{
 			$conf_postfix = $this->Application->getUnitOption($event->Prefix, 'SearchConfigPostfix');
 			$rel_keywords	= $this->Application->ConfigValue('SearchRel_Keyword_'.$conf_postfix)	/ 100;
 			$rel_pop		= $this->Application->ConfigValue('SearchRel_Pop_'.$conf_postfix)		/ 100;
 			$rel_rating		= $this->Application->ConfigValue('SearchRel_Rating_'.$conf_postfix)	/ 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[] = $items_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 '.$items_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);
 
 		$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
 		$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
 		$pick_field = isset($fields['EditorsPick']) ? $items_table.'.EditorsPick' : '0';
 
 		$sql = '	CREATE TABLE '.$search_table.'
 					SELECT 	'.$relevance_clause.' AS Relevance,
 							'.$items_table.'.'.$id_field.' AS ItemId,
 							'.$items_table.'.ResourceId AS ResourceId,
 							11 AS ItemType,
 							'.$pick_field.' AS EdPick
 					FROM '.$items_table.'
 					'.implode(' ', $join_clauses).'
 					WHERE '.$where_clause.'
 					GROUP BY '.$items_table.'.'.$id_field.
 					$having_clause;
 
 		$res = $this->Conn->Query($sql);
 	}
 
 	function getAdvancedSearchCondition($field_name, $record, $keywords, $verbs, &$highlight_keywords)
 	{
 		$field = $record['FieldName'];
 
 		$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)'
 		);
 
 		$condition = '';
 		switch ($record['FieldType']) {
 			case 'select':
 				$keywords[$field] = kUtil::unhtmlentities( $keywords[$field] );
 				if ($keywords[$field]) {
 					$condition = sprintf($condition_patterns['is'], $field_name, $this->Conn->qstr( $keywords[$field] ));
 				}
 				break;
 
 			case 'multiselect':
 				$keywords[$field] = kUtil::unhtmlentities( $keywords[$field] );
 				if ($keywords[$field]) {
 					$condition = Array ();
 					$values = explode('|', substr($keywords[$field], 1, -1));
 					foreach ($values as $selected_value) {
 						$condition[] = sprintf($condition_patterns['contains'], $field_name, $this->Conn->qstr('%|'.$selected_value.'|%'));
 					}
 					$condition = '('.implode(' OR ', $condition).')';
 				}
 				break;
 
 			case 'text':
 				$keywords[$field] = kUtil::unhtmlentities( $keywords[$field] );
 
 				if (mb_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($this->Prefix, 'ItemPropertyMappings');
 					$items_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
 
 					switch ($field) {
 						case 'HotItem':
 							$hot_limit_var = getArrayValue($property_mappings, 'HotLimit');
 							if ($hot_limit_var) {
 								$hot_limit = (int)$this->Application->getDBCache($hot_limit_var);
 
 								$condition = 	'IF('.$items_table.'.HotItem = 2,
 												IF('.$items_table.'.Hits >= '.
 												$hot_limit.
 												', 1, 0), '.$items_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('.$items_table.'.PopItem = 2, IF('.$items_table.'.CachedVotesQty >= '.
 												$this->Application->ConfigValue($votes2pop_var).
 												' AND '.$items_table.'.CachedRating >= '.
 												$this->Application->ConfigValue($rating2pop_var).
 												', 1, 0), '.$items_table.'.PopItem) = '.$keywords[$field];
 							}
 							break;
 
 						case 'NewItem':
 							$new_days_var = getArrayValue($property_mappings, 'NewDays');
 							if ($new_days_var) {
 								$condition = 	'IF('.$items_table.'.NewItem = 2,
 												IF('.$items_table.'.CreatedOn >= (UNIX_TIMESTAMP() - '.
 												$this->Application->ConfigValue($new_days_var).
 												'*3600*24), 1, 0), '.$items_table.'.NewItem) = '.$keywords[$field];
 							}
 							break;
 
 						case 'EditorsPick':
 							$condition = $items_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;
 		}
 
 		return $condition;
 	}
 
 	/**
 	 * Returns human readable representation of searched data to be placed in search log
 	 * @param string $type
 	 * @param Array $search_data
 	 * @return string
 	 * @access protected
 	 */
 	protected function getHuman($type, $search_data)
 	{
 		// all 3 variables are retrieved from $search_data array
 		/* @var $search_config Array */
 		/* @var $verb string */
 		/* @var $value string */
 
 		$type = ucfirst(strtolower($type));
 		extract($search_data);
 
 		switch ($type) {
 			case 'Field':
 				return $this->Application->Phrase($search_config['DisplayName']);
 				break;
 
 			case 'Verb':
 				return $verb ? $this->Application->Phrase('lu_advsearch_'.$verb) : '';
 				break;
 
 			case 'Value':
 				switch ($search_config['FieldType']) {
 					case 'date':
 						$values = Array(0 => 'lu_comm_Any', 'today' => 'lu_comm_Today',
 										'yesterday' => 'lu_comm_Yesterday', 'last_week' => 'lu_comm_LastWeek',
 										'last_month' => 'lu_comm_LastMonth', 'last_3_months' => 'lu_comm_Last3Months',
 										'last_6_months' => 'lu_comm_Last6Months', 'last_year' => 'lu_comm_LastYear');
 						$ret = $this->Application->Phrase($values[$value]);
 						break;
 
 					case 'range':
 						$value = explode('|', $value);
 						return $this->Application->Phrase('lu_comm_From').' "'.$value[0].'" '.$this->Application->Phrase('lu_comm_To').' "'.$value[1].'"';
 						break;
 
 					case 'boolean':
 						$values = Array(1 => 'lu_comm_Yes', 0 => 'lu_comm_No', -1 => 'lu_comm_Both');
 						$ret = $this->Application->Phrase($values[$value]);
 						break;
 
 					default:
 						$ret = $value;
 						break;
 
 				}
 				return '"'.$ret.'"';
 				break;
 		}
 
 		return '';
 	}
 
 	/**
 	 * Set's correct page for list
 	 * based on data provided with event
 	 *
 	 * @param kEvent $event
 	 * @access private
 	 * @see OnListBuild
 	 */
 	function SetPagination(&$event)
 	{
 		$object =& $event->getObject();
 		/* @var $object kDBList */
 
 		// get PerPage (forced -> session -> config -> 10)
 		$object->SetPerPage( $this->getPerPage($event) );
 
 		// main lists on Front-End have special get parameter for page
 		$page = $object->isMainList() ? $this->Application->GetVar('page') : false;
 
 		if (!$page) {
 			// page is given in "env" variable for given prefix
 			$page = $this->Application->GetVar($event->getPrefixSpecial() . '_Page');
 		}
 
 		if (!$page && $event->Special) {
 			// when not part of env, then variables like "prefix.special_Page" are
 			// replaced (by PHP) with "prefix_special_Page", so check for that too
 			$page = $this->Application->GetVar($event->getPrefixSpecial(true) . '_Page');
 		}
 
 		if (!$object->isMainList()) {
 			// main lists doesn't use session for page storing
 			$this->Application->StoreVarDefault($event->getPrefixSpecial() . '_Page', 1, true); // true for optional
 
 			if (!$page) {
 				if ($this->Application->RewriteURLs()) {
 					// when page not found by prefix+special, then try to search it without special at all
 					$page = $this->Application->GetVar($event->Prefix . '_Page');
 
 					if (!$page) {
 						// page not found in request -> get from session
 						$page = $this->Application->RecallVar($event->Prefix . '_Page');
 					}
 
 					if ($page) {
 						// page found in request -> store in session
 						$this->Application->StoreVar($event->getPrefixSpecial() . '_Page', $page, true); //true for optional
 					}
 				}
 				else {
 					// page not found in request -> get from session
 					$page = $this->Application->RecallVar($event->getPrefixSpecial() . '_Page');
 				}
 			}
 			else {
 				// page found in request -> store in session
 				$this->Application->StoreVar($event->getPrefixSpecial() . '_Page', $page, true); //true for optional
 			}
 
 			if ( !$event->getEventParam('skip_counting') ) {
 				// when stored page is larger, then maximal list page number
 				// (such case is also processed in kDBList::Query method)
 				$pages = $object->GetTotalPages();
 
 				if ($page > $pages) {
 					$page = 1;
 					$this->Application->StoreVar($event->getPrefixSpecial().'_Page', 1, true);
 				}
 			}
 		}
 
 		$object->SetPage($page);
 	}
 
 /* === RELATED TO IMPORT/EXPORT: BEGIN === */
 
 	/**
 	 * Shows export dialog
 	 *
 	 * @param kEvent $event
 	 */
 	function OnExport(&$event)
 	{
 		$selected_ids = $this->StoreSelectedIDs($event);
 		if (implode(',', $selected_ids) == '') {
 			// K4 fix when no ids found bad selected ids array is formed
 			$selected_ids = false;
 		}
 
 		$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);
 
 		$export_helper =& $this->Application->recallObject('CatItemExportHelper');
 		/* @var $export_helper kCatDBItemExportHelper */
 
 		$redirect_params = Array (
 			$this->Prefix.'.export_event' => 'OnNew',
 			'pass' => 'all,'.$this->Prefix.'.export'
 		);
 
 		$event->setRedirectParams($redirect_params);
 	}
 
 	/**
 	 * Performs each export step & displays progress percent
 	 *
 	 * @param kEvent $event
 	 */
 	function OnExportProgress(&$event)
 	{
 		$export_object =& $this->Application->recallObject('CatItemExportHelper');
 		/* @var $export_object kCatDBItemExportHelper */
 
 		$event = new kEvent($event->getPrefixSpecial().':OnDummy');
 
 		$action_method = 'perform'.ucfirst($event->Special);
 		$field_values = $export_object->$action_method($event);
 
 		// finish code is done from JS now
 		if ($field_values['start_from'] == $field_values['total_records']) {
 			if ($event->Special == 'import') {
 				$this->Application->StoreVar('PermCache_UpdateRequired', 1);
 				$url_params = Array(
 					't' => 'catalog/catalog',
 					'm_cat_id' => $this->Application->RecallVar('ImportCategory'),
 					'anchor' => 'tab-' . $event->Prefix,
 				);
 				$this->Application->EventManager->openerStackChange($url_params);
 
 				$event->SetRedirectParam('opener', 'u');
 			}
 			elseif ($event->Special == 'export') {
 				$event->redirect = $export_object->getModuleName($event) . '/' . $event->Special . '_finish';
 				$event->SetRedirectParam('pass', 'all');
 			}
 
 			return ;
 		}
 
 		$export_options = $export_object->loadOptions($event);
 		echo $export_options['start_from']  * 100 / $export_options['total_records'];
 
 		$event->status = kEvent::erSTOP;
 	}
 
 	/**
 	 * Returns specific to each item type columns only
 	 *
 	 * @param kEvent $event
 	 * @return Array
 	 */
 	function getCustomExportColumns(&$event)
 	{
 		return Array(	'__VIRTUAL__ThumbnailImage'	=>	'ThumbnailImage',
 						'__VIRTUAL__FullImage' 		=>	'FullImage',
 						'__VIRTUAL__ImageAlt'		=>	'ImageAlt');
 	}
 
 	/**
 	 * Sets non standart virtual fields (e.g. to other tables)
 	 *
 	 * @param kEvent $event
 	 */
 	function setCustomExportColumns(&$event)
 	{
 		$this->restorePrimaryImage($event);
 	}
 
 	/**
 	 * Create/Update primary image record in info found in imported data
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function restorePrimaryImage(&$event)
 	{
 		$object =& $event->getObject();
 		/* @var $object kCatDBItem */
 
 		$has_image_info = $object->GetDBField('ImageAlt') && ($object->GetDBField('ThumbnailImage') || $object->GetDBField('FullImage'));
 		if ( !$has_image_info ) {
 			return ;
 		}
 
 		$image_data = $object->getPrimaryImageData();
 
 		$image =& $this->Application->recallObject('img', null, Array ('skip_autoload' => true));
 		/* @var $image kDBItem */
 
 		if ( $image_data ) {
 			$image->Load($image_data['ImageId']);
 		}
 		else {
 			$image->Clear();
 			$image->SetDBField('Name', 'main');
 			$image->SetDBField('DefaultImg', 1);
 			$image->SetDBField('ResourceId', $object->GetDBField('ResourceId'));
 		}
 
 		$image->SetDBField('AltName', $object->GetDBField('ImageAlt'));
 
 		if ( $object->GetDBField('ThumbnailImage') ) {
 			$thumbnail_field = $this->isURL($object->GetDBField('ThumbnailImage')) ? 'ThumbUrl' : 'ThumbPath';
 			$image->SetDBField($thumbnail_field, $object->GetDBField('ThumbnailImage'));
 			$image->SetDBField('LocalThumb', $thumbnail_field == 'ThumbPath' ? 1 : 0);
 		}
 
 		if ( !$object->GetDBField('FullImage') ) {
 			$image->SetDBField('SameImages', 1);
 		}
 		else {
 			$image->SetDBField('SameImages', 0);
 			$full_field = $this->isURL($object->GetDBField('FullImage')) ? 'Url' : 'LocalPath';
 			$image->SetDBField($full_field, $object->GetDBField('FullImage'));
 			$image->SetDBField('LocalImage', $full_field == 'LocalPath' ? 1 : 0);
 		}
 
 		if ( $image->isLoaded() ) {
 			$image->Update();
 		}
 		else {
 			$image->Create();
 		}
 	}
 
 	function isURL($path)
 	{
 		return preg_match('#(http|https)://(.*)#', $path);
 	}
 
 	/**
 	 * Prepares item for import/export operations
 	 *
 	 * @param kEvent $event
 	 */
 	function OnNew(&$event)
 	{
 		parent::OnNew($event);
 
 		if ( $event->Special == 'import' || $event->Special == 'export' ) {
 			$export_helper =& $this->Application->recallObject('CatItemExportHelper');
 			/* @var $export_helper kCatDBItemExportHelper */
 
 			$export_helper->setRequiredFields($event);
 		}
 	}
 
 	/**
 	 * Process items selected in item_selector
 	 *
 	 * @param kEvent $event
 	 */
 	function OnProcessSelected(&$event)
 	{
 		$dst_field = $this->Application->RecallVar('dst_field');
 		$selected_ids = $this->Application->GetVar('selected_ids');
 
 		if ( $dst_field == 'ItemCategory' ) {
 			// Item Edit -> Categories Tab -> New Categories
 			$object =& $event->getObject();
 			/* @var $object kCatDBItem */
 
 			$category_ids = explode(',', $selected_ids['c']);
 			foreach ($category_ids as $category_id) {
 				$object->assignToCategory($category_id);
 			}
 		}
 
 		if ($dst_field == 'ImportCategory') {
 			// Tools -> Import -> Item Import -> Select Import Category
 			$this->Application->StoreVar('ImportCategory', $selected_ids['c']);
 
 			$url_params = Array (
 				$event->getPrefixSpecial() . '_id' => 0,
 				$event->getPrefixSpecial() . '_event' => 'OnExportBegin',
 			);
 
 			$this->Application->EventManager->openerStackChange($url_params);
 		}
 
 		$event->SetRedirectParam('opener', 'u');
 	}
 
 	/**
 	 * 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 ) {
 			list($id, $field_values) = each($items_info);
 
 			$object =& $event->getObject(Array ('skip_autoload' => true));
 			/* @var $object kDBItem */
 
 			$object->SetFieldsFromHash($field_values);
 			$field_values['ImportFilename'] = $object->GetDBField('ImportFilename'); //if upload formatter has renamed the file during moving !!!
 			$field_values['ImportSource'] = 2;
 			$field_values['ImportLocalFilename'] = $object->GetDBField('ImportFilename');
 			$items_info[$id] = $field_values;
 
 			$this->Application->StoreVar($event->getPrefixSpecial() . '_ItemsInfo', serialize($items_info));
 		}
 	}
 
 	/**
 	 * Saves Import/Export settings to session
 	 *
 	 * @param kEvent $event
 	 */
 	function OnResetSettings(&$event)
 	{
 		$this->Application->StoreVar('ImportCategory', $this->Application->getBaseCategory());
 	}
 
 	/**
 	 * Cancels item editing
 	 * @param kEvent $event
 	 * @return void
 	 * @todo Used?
 	 */
 	function OnCancelAction(&$event)
 	{
 		$event->setRedirectParams(Array ('pass' => 'all,' . $event->getPrefixSpecial()), true);
 		$event->redirect = $this->Application->GetVar('cancel_template');
 	}
 
 /* === RELATED TO IMPORT/EXPORT: END === */
 
 	/**
 	 * Stores item's owner login into separate field together with id
 	 *
 	 * @param kEvent $event
 	 * @param string $id_field
 	 * @param string $cached_field
 	 */
 	function cacheItemOwner(&$event, $id_field, $cached_field)
 	{
 		$object =& $event->getObject();
 		/* @var $object kDBItem */
 
 		$user_id = $object->GetDBField($id_field);
 		$options = $object->GetFieldOptions($id_field);
-		
+
 		if ( isset($options['options'][$user_id]) ) {
 			$object->SetDBField($cached_field, $options['options'][$user_id]);
 		}
 		else {
 			$id_field = $this->Application->getUnitOption('u', 'IDField');
 			$table_name = $this->Application->getUnitOption('u', 'TableName');
 
 			$sql = 'SELECT Login
 					FROM ' . $table_name . '
 					WHERE ' . $id_field . ' = ' . $user_id;
 			$object->SetDBField($cached_field, $this->Conn->GetOne($sql));
 		}
 	}
 
 	/**
 	 * Saves edited item into temp table
 	 * If there is no id, new item is created in temp table
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnPreSave(&$event)
 	{
 		parent::OnPreSave($event);
 
 		$use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
 
 		if ( $event->status == kEvent::erSUCCESS && $use_pending_editing ) {
 			// decision: clone or not clone
 
 			$object =& $event->getObject();
 			/* @var $object kCatDBItem */
 
 			if ( $object->GetID() == 0 || $object->GetDBField('OrgId') > 0 ) {
 				// new items or cloned items shouldn't be cloned again
 				return ;
 			}
 
 			$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 			/* @var $perm_helper kPermissionsHelper */
-			
+
 			$owner_field = $this->getOwnerField($event->Prefix);
 
 			if ( $perm_helper->ModifyCheckPermission($object->GetDBField($owner_field), $object->GetDBField('CategoryId'), $event->Prefix) == 2 ) {
 
 				// 1. clone original item
 				$temp_handler =& $this->Application->recallObject($event->getPrefixSpecial() . '_TempHandler', 'kTempTablesHandler');
 				/* @var $temp_handler kTempTablesHandler */
 
 				$cloned_ids = $temp_handler->CloneItems($event->Prefix, $event->Special, Array ($object->GetID()), null, null, null, true);
 				$ci_table = $this->Application->GetTempName(TABLE_PREFIX . 'CategoryItems');
 
 				// 2. delete record from CategoryItems (about cloned item) that was automatically created during call of Create method of kCatDBItem
 				$sql = 'SELECT ResourceId
 						FROM ' . $object->TableName . '
 						WHERE ' . $object->IDField . ' = ' . $cloned_ids[0];
 				$clone_resource_id = $this->Conn->GetOne($sql);
 
 				$sql = 'DELETE FROM ' . $ci_table . '
 						WHERE ItemResourceId = ' . $clone_resource_id . ' AND PrimaryCat = 1';
 				$this->Conn->Query($sql);
 
 				// 3. copy main item categoryitems to cloned item
 				$sql = '	INSERT INTO ' . $ci_table . ' (CategoryId, ItemResourceId, PrimaryCat, ItemPrefix, Filename)
 							SELECT CategoryId, ' . $clone_resource_id . ' AS ItemResourceId, PrimaryCat, ItemPrefix, Filename
 							FROM ' . $ci_table . '
 							WHERE ItemResourceId = ' . $object->GetDBField('ResourceId');
 				$this->Conn->Query($sql);
 
 				// 4. put cloned id to OrgId field of item being cloned
 				$sql = 'UPDATE ' . $object->TableName . '
 						SET OrgId = ' . $object->GetID() . '
 						WHERE ' . $object->IDField . ' = ' . $cloned_ids[0];
 				$this->Conn->Query($sql);
 
 				// 5. substitute id of item being cloned with clone id
 				$this->Application->SetVar($event->getPrefixSpecial() . '_id', $cloned_ids[0]);
 
 				$selected_ids = $this->getSelectedIDs($event, true);
 				$selected_ids[ array_search($object->GetID(), $selected_ids) ] = $cloned_ids[0];
 				$this->StoreSelectedIDs($event, $selected_ids);
 
 				// 6. delete original item from temp table
 				$temp_handler->DeleteItems($event->Prefix, $event->Special, Array ($object->GetID()));
 			}
 		}
 	}
 
 	/**
 	 * Sets item's owner field
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnPreCreate(&$event)
 	{
 		parent::OnPreCreate($event);
 
 		if ( $event->status != kEvent::erSUCCESS ) {
 			return ;
 		}
 
 		$object =& $event->getObject();
 		/* @var $object kDBItem */
 
 		$owner_field = $this->getOwnerField($event->Prefix);
 		$object->SetDBField($owner_field, $this->Application->RecallVar('user_id'));
 	}
 
 	/**
 	 * Occures before original item of item in pending editing got deleted (for hooking only)
 	 *
 	 * @param kEvent $event
 	 */
 	function OnBeforeDeleteOriginal(&$event)
 	{
 
 	}
 
 	/**
 	 * Occurs before an item has been cloned
 	 * Id of newly created item is passed as event' 'id' param
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnBeforeClone(&$event)
 	{
 		parent::OnBeforeClone($event);
 
 		if ( $this->Application->GetVar('ResetCatBeforeClone') ) {
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			$object->SetDBField('CategoryId', null);
 		}
 	}
 
 	/**
 	 * Set status for new category item based on user permission in category
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function OnBeforeItemCreate(&$event)
 	{
 		parent::OnBeforeItemCreate($event);
 
 		$object =& $event->getObject();
 		/* @var $object kCatDBItem */
 
 		$is_admin = $this->Application->isAdminUser;
 		$owner_field = $this->getOwnerField($event->Prefix);
 
 		if ( (!$object->IsTempTable() && !$is_admin) || ($is_admin && !$object->GetDBField($owner_field)) ) {
 			// Front-end OR owner not specified -> set to currently logged-in user
 			$object->SetDBField($owner_field, $this->Application->RecallVar('user_id'));
 		}
 
 		if ( $object->Validate() ) {
 			$object->SetDBField('ResourceId', $this->Application->NextResourceId());
 		}
 
 		if ( !$this->Application->isAdmin ) {
 			$this->setItemStatusByPermission($event);
 		}
 	}
 
 	/**
 	 * Sets category item status based on user permissions (only on Front-end)
 	 *
 	 * @param kEvent $event
 	 */
 	function setItemStatusByPermission(&$event)
 	{
 		$use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
 
 		if (!$use_pending_editing) {
 			return ;
 		}
 
 		$object =& $event->getObject();
 		/* @var $object kCatDBItem */
 
 		$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 		/* @var $perm_helper kPermissionsHelper */
 
 		$primary_category = $object->GetDBField('CategoryId') > 0 ? $object->GetDBField('CategoryId') : $this->Application->GetVar('m_cat_id');
 		$item_status = $perm_helper->AddCheckPermission($primary_category, $event->Prefix);
 
 		if ($item_status == STATUS_DISABLED) {
 			$event->status = kEvent::erFAIL;
 		}
 		else {
 			$object->SetDBField('Status', $item_status);
 		}
 	}
 
 	/**
 	 * Creates category item & redirects to confirmation template (front-end only)
 	 *
 	 * @param kEvent $event
 	 */
 	function OnCreate(&$event)
 	{
 		parent::OnCreate($event);
 		$this->SetFrontRedirectTemplate($event, 'suggest');
 	}
 
 	/**
 	 * Returns item's categories (allows to exclude primary category)
 	 *
 	 * @param int $resource_id
 	 * @param bool $with_primary
 	 * @return Array
 	 */
 	function getItemCategories($resource_id, $with_primary = false)
 	{
 		$sql = 'SELECT CategoryId
 				FROM '.TABLE_PREFIX.'CategoryItems
 				WHERE (ItemResourceId = '.$resource_id.')';
 
 		if (!$with_primary) {
 			$sql .= ' AND (PrimaryCat = 0)';
 		}
 
 		return $this->Conn->GetCol($sql);
 	}
 
 	/**
 	 * Adds new and removes old additional categories from category item
 	 *
 	 * @param kCatDBItem $object
 	 */
 	function processAdditionalCategories(&$object, $mode)
 	{
 		if ( !$object->isVirtualField('MoreCategories') ) {
 			// given category item doesn't require such type of processing
 			return ;
 		}
 
 		$process_categories = $object->GetDBField('MoreCategories');
 		if ($process_categories === '') {
 			// field was not in submit & have default value (when no categories submitted, then value is null)
 			return ;
 		}
 
 		if ($mode == 'create') {
 			// prevents first additional category to become primary
 			$object->assignPrimaryCategory();
 		}
 
 		$process_categories = $process_categories ? explode('|', substr($process_categories, 1, -1)) : Array ();
 		$existing_categories = $this->getItemCategories($object->GetDBField('ResourceId'));
 
 		$add_categories = array_diff($process_categories, $existing_categories);
 		foreach ($add_categories as $category_id) {
 			$object->assignToCategory($category_id);
 		}
 
 		$remove_categories = array_diff($existing_categories, $process_categories);
 		foreach ($remove_categories as $category_id) {
 			$object->removeFromCategory($category_id);
 		}
 	}
 
 	/**
 	 * Creates category item & redirects to confirmation template (front-end only)
 	 *
 	 * @param kEvent $event
 	 */
 	function OnUpdate(&$event)
 	{
 		$use_pending = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
 		if ($this->Application->isAdminUser || !$use_pending) {
 			parent::OnUpdate($event);
 			$this->SetFrontRedirectTemplate($event, 'modify');
 			return ;
 		}
 
 		$object =& $event->getObject(Array('skip_autoload' => true));
 		/* @var $object kCatDBItem */
 
 		$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
 		if ($items_info) {
 			$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 			/* @var $perm_helper kPermissionsHelper */
 
 			$temp_handler =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
 			/* @var $temp_handler kTempTablesHandler */
 
 			$owner_field = $this->getOwnerField($event->Prefix);
 
 			$file_helper =& $this->Application->recallObject('FileHelper');
 			/* @var $file_helper FileHelper */
 
 			foreach ($items_info as $id => $field_values) {
 				$object->Load($id);
 				$edit_perm = $perm_helper->ModifyCheckPermission($object->GetDBField($owner_field), $object->GetDBField('CategoryId'), $event->Prefix);
 
 				if ($use_pending && !$object->GetDBField('OrgId') && ($edit_perm == STATUS_PENDING)) {
 					// pending editing enabled + not pending copy -> get/create pending copy & save changes to it
 					$original_id = $object->GetID();
 					$original_resource_id = $object->GetDBField('ResourceId');
 					$file_helper->PreserveItemFiles($field_values);
 
 					$object->Load($original_id, 'OrgId');
 					if (!$object->isLoaded()) {
 						// 1. user has no pending copy of live item -> clone live item
 						$cloned_ids = $temp_handler->CloneItems($event->Prefix, $event->Special, Array($original_id), null, null, null, true);
 
 						$object->Load($cloned_ids[0]);
 						$object->SetFieldsFromHash($field_values);
 
 						// 1a. delete record from CategoryItems (about cloned item) that was automatically created during call of Create method of kCatDBItem
 						$ci_table = $this->Application->getUnitOption('ci', 'TableName');
 						$sql = 'DELETE FROM '.$ci_table.'
 								WHERE ItemResourceId = '.$object->GetDBField('ResourceId').' AND PrimaryCat = 1';
 						$this->Conn->Query($sql);
 
 						// 1b. copy main item categoryitems to cloned item
 						$sql = 'INSERT INTO '.$ci_table.' (CategoryId, ItemResourceId, PrimaryCat, ItemPrefix, Filename)
 								SELECT CategoryId, '.$object->GetDBField('ResourceId').' AS ItemResourceId, PrimaryCat, ItemPrefix, Filename
 								FROM '.$ci_table.'
 								WHERE ItemResourceId = '.$original_resource_id;
 						$this->Conn->Query($sql);
 
 						// 1c. put cloned id to OrgId field of item being cloned
 						$object->SetDBField('Status', STATUS_PENDING_EDITING);
 						$object->SetDBField('OrgId', $original_id);
 					}
 					else {
 						// 2. user has pending copy of live item -> just update field values
 						$object->SetFieldsFromHash($field_values);
 					}
 
 					// update id in request (used for redirect in mod-rewrite mode)
 					$this->Application->SetVar($event->getPrefixSpecial().'_id', $object->GetID());
 				}
 				else {
 					// 3. already editing pending copy -> just update field values
 					$object->SetFieldsFromHash($field_values);
 				}
 
 				if ($object->Update()) {
 					$event->status = kEvent::erSUCCESS;
 				}
 				else {
 					$event->status = kEvent::erFAIL;
 					$event->redirect = false;
 					break;
 				}
 			}
 		}
 
 		$this->SetFrontRedirectTemplate($event, 'modify');
 	}
 
 	/**
 	 * Sets next template to one required for front-end after adding/modifying item
 	 *
 	 * @param kEvent $event
 	 * @param string $template_key - {suggest,modify}
 	 */
 	function SetFrontRedirectTemplate(&$event, $template_key)
 	{
 		if ($this->Application->isAdminUser || $event->status != kEvent::erSUCCESS) {
 			return ;
 		}
 
 		// prepare redirect template
 		$object =& $event->getObject();
 		$is_active = ($object->GetDBField('Status') == STATUS_ACTIVE);
 
 		$next_template = $is_active ? 'confirm_template' : 'pending_confirm_template';
 		$event->redirect = $this->Application->GetVar($template_key.'_'.$next_template);
 		$event->SetRedirectParam('opener', 's');
 
 		// send email events
 		$perm_prefix = $this->Application->getUnitOption($event->Prefix, 'PermItemPrefix');
 		$owner_field = $this->getOwnerField($event->Prefix);
 		$owner_id = $object->GetDBField($owner_field);
 
 		switch ($event->Name) {
 			case 'OnCreate':
 				$event_suffix = $is_active ? 'ADD' : 'ADD.PENDING';
 				$this->Application->EmailEventAdmin($perm_prefix.'.'.$event_suffix); // there are no ADD.PENDING event for admin :(
 				$this->Application->EmailEventUser($perm_prefix.'.'.$event_suffix, $owner_id);
 				break;
 
 			case 'OnUpdate':
 				$event_suffix = $is_active ? 'MODIFY' : 'MODIFY.PENDING';
 				$user_id = is_numeric( $object->GetDBField('ModifiedById') ) ? $object->GetDBField('ModifiedById') : $owner_id;
 				$this->Application->EmailEventAdmin($perm_prefix.'.'.$event_suffix); // there are no ADD.PENDING event for admin :(
 				$this->Application->EmailEventUser($perm_prefix.'.'.$event_suffix, $user_id);
 				break;
 		}
 	}
 
 	/**
 	 * Apply same processing to each item being selected in grid
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access protected
 	 */
 	protected function iterateItems(&$event)
 	{
 		if ( $event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline' ) {
 			parent::iterateItems($event);
 		}
 
 		if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
 			$event->status = kEvent::erFAIL;
 			return ;
 		}
 
 		$object =& $event->getObject(Array ('skip_autoload' => true));
 		/* @var $object kCatDBItem */
 
 		$ids = $this->StoreSelectedIDs($event);
 
 		if ( $ids ) {
 			foreach ($ids as $id) {
 				$ret = true;
 				$object->Load($id);
 
 				switch ( $event->Name ) {
 					case 'OnMassApprove':
 						$ret = $object->ApproveChanges();
 						break;
 
 					case 'OnMassDecline':
 						$ret = $object->DeclineChanges();
 						break;
 				}
 
 				if ( !$ret ) {
 					$event->status = kEvent::erFAIL;
 					$event->redirect = false;
 					break;
 				}
 			}
 		}
 
 		$this->clearSelectedIDs($event);
 	}
 
 	/**
 	 * Deletes items & preserves clean env
 	 *
 	 * @param kEvent $event
 	 */
 	function OnDelete(&$event)
 	{
 		parent::OnDelete($event);
 
 		if ($event->status == kEvent::erSUCCESS && !$this->Application->isAdmin) {
 			$event->SetRedirectParam('pass', 'm');
 			$event->SetRedirectParam('m_cat_id', 0);
 		}
 	}
 
 	/**
 	 * Checks, that currently loaded item is allowed for viewing (non permission-based)
 	 *
 	 * @param kEvent $event
 	 * @return bool
 	 */
 	function checkItemStatus(&$event)
 	{
 		$object =& $event->getObject();
 		if (!$object->isLoaded()) {
 			$this->_errorNotFound($event);
 
 			return true;
 		}
 
 		$status = $object->GetDBField('Status');
 		$user_id = $this->Application->RecallVar('user_id');
 		$owner_field = $this->getOwnerField($event->Prefix);
 
 		if (($status == STATUS_PENDING_EDITING || $status == STATUS_PENDING) && ($object->GetDBField($owner_field) == $user_id)) {
 			return true;
 		}
 
 		return $status == STATUS_ACTIVE;
 	}
 
 	/**
 	 * Set's correct sorting for list
 	 * based on data provided with event
 	 *
 	 * @param kEvent $event
 	 * @access private
 	 * @see OnListBuild
 	 */
 	function SetSorting(&$event)
 	{
 		if (!$this->Application->isAdmin) {
 			$event->setEventParam('same_special', true);
 		}
 
 		parent::SetSorting($event);
 	}
 
 	/**
 	 * Returns current per-page setting for list
 	 *
 	 * @param kEvent $event
 	 * @return int
 	 */
 	function getPerPage(&$event)
 	{
 		if (!$this->Application->isAdmin) {
 			$event->setEventParam('same_special', true);
 		}
 
 		return parent::getPerPage($event);
 	}
 
 	function getOwnerField($prefix)
 	{
 		$owner_field = $this->Application->getUnitOption($prefix, 'OwnerField');
 		if (!$owner_field) {
 			$owner_field = 'CreatedById';
 		}
 
 		return $owner_field;
 	}
 
 	/**
 	 * Creates virtual image fields for item
 	 *
 	 * @param kEvent $event
 	 */
 	function OnAfterConfigRead(&$event)
 	{
 		parent::OnAfterConfigRead($event);
 
 		if (defined('IS_INSTALL') && IS_INSTALL) {
 			return ;
 		}
 
 		if ( !$this->Application->isAdmin ) {
 			$file_helper =& $this->Application->recallObject('FileHelper');
 			/* @var $file_helper FileHelper */
 
 			$file_helper->createItemFiles($event->Prefix, true); // create image fields
 			$file_helper->createItemFiles($event->Prefix, false); // create file fields
 		}
 
 		$this->changeSortings($event);
 
 		// add grids for advanced view (with primary category column)
 		$grids = $this->Application->getUnitOption($this->Prefix, 'Grids');
 		$process_grids = Array ('Default', 'Radio');
 		foreach ($process_grids as $process_grid) {
 			$grid_data = $grids[$process_grid];
 			$grid_data['Fields']['CachedNavbar'] = Array ('title' => 'la_col_Path', 'data_block' => 'grid_primary_category_td', 'filter_block' => 'grid_like_filter');
 			$grids[$process_grid . 'ShowAll'] = $grid_data;
 		}
 		$this->Application->setUnitOption($this->Prefix, 'Grids', $grids);
 
 		// add options for CategoryId field (quick way to select item's primary category)
 		$category_helper =& $this->Application->recallObject('CategoryHelper');
 		/* @var $category_helper CategoryHelper */
 
 		$virtual_fields = $this->Application->getUnitOption($event->Prefix, 'VirtualFields');
 
 		$virtual_fields['CategoryId']['default'] = (int)$this->Application->GetVar('m_cat_id');
 		$virtual_fields['CategoryId']['options'] = $category_helper->getStructureTreeAsOptions();
 
 		$this->Application->setUnitOption($event->Prefix, 'VirtualFields', $virtual_fields);
 	}
 
 	function changeSortings(&$event)
 	{
 		$remove_sortings = Array ();
 
 		if ( !$this->Application->isAdmin ) {
 			// remove Pick sorting on Front-end, when not required
 			$config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping', Array ());
 
 			if ( !isset($config_mapping['ForceEditorPick']) || !$this->Application->ConfigValue($config_mapping['ForceEditorPick']) ) {
 				$remove_sortings[] = 'EditorsPick';
 			}
 		}
 		else {
 			// remove all forced sortings in Admin Console
 			$remove_sortings = array_merge($remove_sortings, Array ('Priority', 'EditorsPick'));
 		}
 
 		if ( !$remove_sortings ) {
 			return;
 		}
 
 		$list_sortings = $this->Application->getUnitOption($event->Prefix, 'ListSortings', Array ());
 		/* @var $list_sortings Array */
 
 		foreach ($list_sortings as $special => $sorting_fields) {
 			foreach ($remove_sortings as $sorting_field) {
 				unset($list_sortings[$special]['ForcedSorting'][$sorting_field]);
 			}
 		}
 
 		$this->Application->setUnitOption($event->Prefix, 'ListSortings', $list_sortings);
 	}
 
 	/**
 	 * Returns file contents associated with item
 	 *
 	 * @param kEvent $event
 	 */
 	function OnDownloadFile(&$event)
 	{
 		$object =& $event->getObject();
 		/* @var $object kCatDBItem */
 
 		$event->status = kEvent::erSTOP;
 
 		$field = $this->Application->GetVar('field');
 		if (!preg_match('/^File([\d]+)/', $field)) {
 			return ;
 		}
 
 		$file_helper =& $this->Application->recallObject('FileHelper');
 		/* @var $file_helper FileHelper */
 
 		$filename = $object->GetField($field, 'full_path');
 		$file_helper->DownloadFile($filename);
 	}
 
 	/**
 	 * Saves user's vote
 	 *
 	 * @param kEvent $event
 	 */
 	function OnMakeVote(&$event)
 	{
 		$event->status = kEvent::erSTOP;
 
 		if ($this->Application->GetVar('ajax') != 'yes') {
 			// this is supposed to call from AJAX only
 			return ;
 		}
 
 		$rating_helper =& $this->Application->recallObject('RatingHelper');
 		/* @var $rating_helper RatingHelper */
 
 		$object =& $event->getObject( Array ('skip_autoload' => true) );
 		/* @var $object kCatDBItem */
 
 		$object->Load( $this->Application->GetVar('id') );
 
 		echo $rating_helper->makeVote($object);
 	}
 
 	/**
 	 * [HOOK] Allows to add cloned subitem to given prefix
 	 *
 	 * @param kEvent $event
 	 */
 	function OnCloneSubItem(&$event)
 	{
 		parent::OnCloneSubItem($event);
 
 		if ($event->MasterEvent->Prefix == 'fav') {
 			$clones = $this->Application->getUnitOption($event->MasterEvent->Prefix, 'Clones');
 			$subitem_prefix = $event->Prefix . '-' . $event->MasterEvent->Prefix;
 
 			$clones[$subitem_prefix]['ParentTableKey'] = 'ResourceId';
 			$clones[$subitem_prefix]['ForeignKey'] = 'ResourceId';
 
 			$this->Application->setUnitOption($event->MasterEvent->Prefix, 'Clones', $clones);
 		}
 	}
 }
\ No newline at end of file
Index: branches/5.2.x/core/kernel/kbase.php
===================================================================
--- branches/5.2.x/core/kernel/kbase.php	(revision 14643)
+++ branches/5.2.x/core/kernel/kbase.php	(revision 14644)
@@ -1,1055 +1,1068 @@
 <?php
 /**
 * @version	$Id$
 * @package	In-Portal
 * @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
 * @license      GNU/GPL
 * In-Portal is Open Source software.
 * This means that this software may have been modified pursuant
 * the GNU General Public License, and as distributed it includes
 * or is derivative of works licensed under the GNU General Public License
 * or other free or open source software licenses.
 * See http://www.in-portal.org/license for copyright notices and details.
 */
 
 //defined('FULL_PATH') or die('restricted access!');
 
 /**
 * Base
 *
 */
 class kBase {
 
 	/**
 	* Reference to global kApplication instance
 	*
 	* @var kApplication
 	* @access protected
 	*/
 	protected $Application = null;
 
 	/**
 	* Connection to database
 	*
 	* @var kDBConnection
 	* @access protected
 	*/
 	protected $Conn = null;
 
 	/**
 	 * Prefix, used during object creation
 	 *
 	 * @var string
 	 * @access public
 	 */
 	public $Prefix = '';
 
 	/**
 	 * Special, used during object creation
 	 *
 	 * @var string
 	 * @access public
 	 */
 	public $Special = '';
 
 	/**
 	 * Joined prefix and special, usually taken directly from
 	 * tag beeing processed, to use in kApplication::recallObject method
 	 *
 	 * @var string
 	 * @access protected
 	 * @see kApplication::recallObject
 	 */
 	protected $prefixSpecial = '';
 
 	/**
 	 * Set's references to kApplication and kDBConnection class instances
 	 *
 	 * @return kBase
 	 * @access public
 	 * @see kApplication
 	 * @see kDBConnection
 	 */
 	public function __construct($application = null)
 	{
 		if (!isset($application)) {
 			$this->Application =& kApplication::Instance();
 		}
 		else {
 			$this->Application =& $application;
 		}
 
 		$this->Conn =& $this->Application->GetADODBConnection();
 	}
 
 	/**
 	 * Set's prefix and special
 	 *
 	 * @param string $prefix
 	 * @param string $special
 	 * @access public
 	 */
 	public function Init($prefix, $special)
 	{
 		$prefix = explode('_', $prefix, 2);
 		$this->Prefix = $prefix[0];
 		$this->Special = $special;
 
 		$this->prefixSpecial = rtrim($this->Prefix . '.' . $this->Special, '.');
 	}
 
 	/**
 	 * Returns prefix and special (when present) joined by a "."
 	 *
 	 * @return string
 	 * @access public
 	 */
 	public function getPrefixSpecial()
 	{
 		return $this->prefixSpecial;
 	}
 }
 
 class kHelper extends kBase {
 
 	/**
 	 * Performs helper initialization
 	 *
 	 * @access public
 	 */
 	public function InitHelper()
 	{
 
 	}
 
 	/**
 	 * Append prefix and special to tag
 	 * params (get them from tagname) like
 	 * they were really passed as params
 	 *
 	 * @param string $prefix_special
 	 * @param Array $tag_params
 	 * @return Array
 	 * @access protected
 	 */
 	protected function prepareTagParams($prefix_special, $tag_params = Array())
 	{
 		$parts = explode('.', $prefix_special);
 
 		$ret = $tag_params;
 		$ret['Prefix'] = $parts[0];
 		$ret['Special'] = count($parts) > 1 ? $parts[1] : '';
 		$ret['PrefixSpecial'] = $prefix_special;
 
 		return $ret;
 	}
 }
 
 abstract class kDBBase extends kBase {
 
 	/**
 	* Name of primary key field for the unit
 	*
 	* @var string
 	* @access public
 	* @see kDBBase::TableName
 	*/
 	public $IDField = '';
 
 	/**
 	* Unit's database table name
 	*
 	* @var string
 	* @access public
 	*/
 	public $TableName = '';
 
 	/**
 	 * Form name, used for validation
 	 *
 	 * @var string
 	 */
 	protected $formName = '';
 
 	/**
 	 * Final form configuration
 	 *
 	 * @var Array
 	 */
 	protected $formConfig = Array ();
 
 	/**
 	* SELECT, FROM, JOIN parts of SELECT query (no filters, no limit, no ordering)
 	*
 	* @var string
 	* @access protected
 	*/
 	protected $SelectClause = '';
 
 	/**
 	* Unit fields definitions (fields from database plus virtual fields)
 	*
 	* @var Array
 	* @access protected
 	*/
 	protected $Fields = Array ();
 
 	/**
 	 * Mapping between unit custom field IDs and their names
 	 *
 	 * @var Array
 	 * @access protected
 	 */
 	protected $customFields = Array ();
 
 	/**
 	 * Unit virtual field definitions
 	 *
 	 * @var Array
 	 * @access protected
+	 * @see kDBBase::getVirtualFields()
+	 * @see kDBBase::setVirtualFields()
 	 */
 	protected $VirtualFields = Array ();
 
 	/**
 	 * Fields that need to be queried using custom expression, e.g. IF(...) AS value
 	 *
 	 * @var Array
 	 * @access protected
 	 */
 	protected $CalculatedFields = Array ();
 
 
 	/**
 	 * Fields that contain aggregated functions, e.g. COUNT, SUM, etc.
 	 *
 	 * @var Array
 	 * @access protected
 	 */
 	protected $AggregatedCalculatedFields = Array ();
 
 	/**
 	 * Tells, that multilingual fields sould not be populated by default.
 	 * Can be overriden from kDBBase::Configure method
 	 *
 	 * @var bool
 	 * @access protected
 	 */
 	protected $populateMultiLangFields = false;
 
 	/**
 	 * Event, that was used to create this object
 	 *
 	 * @var kEvent
 	 * @access protected
 	 */
 	protected $parentEvent = null;
 
 	/**
 	 * Sets new parent event to the object
 	 *
 	 * @param kEvent $event
 	 * @return void
 	 * @access public
 	 */
 	public function setParentEvent(&$event)
 	{
 		$this->parentEvent =& $event;
 	}
 
 	/**
 	 * Set object' TableName to LIVE table, defined in unit config
 	 *
 	 * @access public
 	 */
 	public function SwitchToLive()
 	{
 		$this->TableName = $this->Application->getUnitOption($this->Prefix, 'TableName');
 	}
 
 	/**
 	 * Set object' TableName to TEMP table created based on table, defined in unit config
 	 *
 	 * @access public
 	 */
 	public function SwitchToTemp()
 	{
 		$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
 		$this->TableName = $this->Application->GetTempName($table_name, 'prefix:' . $this->Prefix);
 	}
 
 	/**
 	 * Checks if object uses temp table
 	 *
 	 * @return bool
 	 * @access public
 	 */
 	public function IsTempTable()
 	{
 		return $this->Application->IsTempTable($this->TableName);
 	}
 
 	/**
 	* Sets SELECT part of list' query
 	*
 	* @param string $sql SELECT and FROM [JOIN] part of the query up to WHERE
 	* @access public
 	*/
 	public function SetSelectSQL($sql)
 	{
 		$this->SelectClause = $sql;
 	}
 
 	/**
+	 * Returns object select clause without any transformations
+	 *
+	 * @return string
+	 * @access public
+	 */
+	public function GetPlainSelectSQL()
+	{
+		return $this->SelectClause;
+	}
+
+	/**
 	 * Returns SELECT part of list' query.
-	 * 1. Occurences of "%1$s" and "%s" are replaced to kDBBase::TableName
-	 * 2. Occurences of "%3$s" are replaced to temp table prefix (only for table, using TABLE_PREFIX)
+	 * 1. Occurrences of "%1$s" and "%s" are replaced to kDBBase::TableName
+	 * 2. Occurrences of "%3$s" are replaced to temp table prefix (only for table, using TABLE_PREFIX)
 	 *
 	 * @param string $base_query given base query will override unit default select query
-	 * @param bool $replace_table replace all possible occurences
+	 * @param bool $replace_table replace all possible occurrences
 	 * @return string
 	 * @access public
 	 * @see kDBBase::replaceModePrefix
 	 */
 	public function GetSelectSQL($base_query = null, $replace_table = true)
 	{
 		if (!isset($base_query)) {
 			$base_query = $this->SelectClause;
 		}
 
 		if (!$replace_table) {
 			return $base_query;
 		}
 
 		$query = str_replace(Array('%1$s', '%s'), $this->TableName, $base_query);
 
 		return $this->replaceModePrefix($query);
 	}
 
 	/**
-	 * Allows substables to be in same mode as main item (e.g. LEFT JOINED ones)
+	 * Allows sub-stables to be in same mode as main item (e.g. LEFT JOINED ones)
 	 *
 	 * @param string $query
 	 * @return string
 	 * @access protected
 	 */
 	protected function replaceModePrefix($query)
 	{
 		$live_table = substr($this->Application->GetLiveName($this->TableName), strlen(TABLE_PREFIX));
 
 		if (preg_match('/'.preg_quote(TABLE_PREFIX, '/').'(.*)'.preg_quote($live_table, '/').'/', $this->TableName, $rets)) {
 			// will only happen, when table has a prefix (like in K4)
 			return str_replace('%3$s', $rets[1], $query);
 		}
 
 		// will happen, when K3 table without prefix is used
 		return $query;
 	}
 
 	/**
 	 * Sets calculated fields
 	 *
 	 * @param Array $fields
 	 * @access public
 	 */
 	public function setCalculatedFields($fields)
 	{
 		$this->CalculatedFields = $fields;
 	}
 
 	/**
 	 * Adds calculated field declaration to object.
 	 *
 	 * @param string $name
 	 * @param string $sql_clause
 	 * @access public
 	 */
 	public function addCalculatedField($name, $sql_clause)
 	{
 		$this->CalculatedFields[$name] = $sql_clause;
 	}
 
 	/**
 	 * Returns required mixing of aggregated & non-aggregated calculated fields
 	 *
 	 * @param int $aggregated 0 - having + aggregated, 1 - having only, 2 - aggregated only
 	 * @return Array
 	 * @access public
 	 */
 	public function getCalculatedFields($aggregated = 1)
 	{
 		switch ($aggregated) {
 			case 0:
 				$fields = array_merge($this->CalculatedFields, $this->AggregatedCalculatedFields);
 				break;
 
 			case 1:
 				$fields = $this->CalculatedFields;
 				break;
 
 			case 2:
 				$fields = $this->AggregatedCalculatedFields; // TODO: never used
 				break;
 
 			default:
 				$fields = Array();
 				break;
 		}
 
 		return $fields;
 	}
 
 	/**
 	 * Checks, that given field is a calculated field
 	 *
 	 * @param string $field
 	 * @return bool
 	 * @access public
 	 */
 	public function isCalculatedField($field)
 	{
 		return array_key_exists($field, $this->CalculatedFields);
 	}
 
 	/**
 	 * Insert calculated fields sql into query in place of %2$s,
 	 * return processed query.
 	 *
 	 * @param string $query
 	 * @param int $aggregated 0 - having + aggregated, 1 - having only, 2 - aggregated only
 	 * @return string
 	 * @access protected
 	 */
 	protected function addCalculatedFields($query, $aggregated = 1)
 	{
 		$fields = $this->getCalculatedFields($aggregated);
 		if ($fields) {
 			$sql = Array ();
 			$fields = str_replace('%2$s', $this->Application->GetVar('m_lang'), $fields);
 
 			foreach ($fields as $field_name => $field_expression) {
 				$sql[] = '('.$field_expression.') AS `'.$field_name.'`';
 			}
 			$sql = implode(',',$sql);
 
 			return $this->Application->ReplaceLanguageTags( str_replace('%2$s', ','.$sql, $query) );
 		}
 
 		return str_replace('%2$s', '', $query);
 	}
 
 	/**
 	 * Performs initial object configuration, which includes setting the following:
 	 * - primary key and table name
 	 * - field definitions (including field modifiers, formatters, default values)
 	 *
 	 * @param bool $populate_ml_fields create all ml fields from db in config or not
 	 * @param string $form_name form name for validation
 	 * @access public
 	 */
 	public function Configure($populate_ml_fields = null, $form_name = null)
 	{
 		if ( isset($populate_ml_fields) ) {
 			$this->populateMultiLangFields = $populate_ml_fields;
 		}
 
 		$this->IDField = $this->Application->getUnitOption($this->Prefix, 'IDField');
 		$this->TableName = $this->Application->getUnitOption($this->Prefix, 'TableName');
 
 		$this->initForm($form_name);
 		$this->defineFields();
 
 		$this->ApplyFieldModifiers(); // should be called only after all fields definitions been set
 		$this->prepareConfigOptions(); // this should go last, but before setDefaultValues, order is significant!
 
 		// only set on first call of method
 		if ( isset($populate_ml_fields) ) {
 			$this->SetDefaultValues();
 		}
 	}
 
 	/**
 	 * Adjusts object accoding to given form name
 	 *
 	 */
 	protected function initForm($form_name = null)
 	{
 		$forms = $this->Application->getUnitOption($this->Prefix, 'Forms', Array ());
 
 		$this->formName = $form_name;
 		$this->formConfig = isset($forms['default']) ? $forms['default'] : Array ();
 
 		if ( !$this->formName ) {
 			return ;
 		}
 
 		if ( !isset($forms[$this->formName]) ) {
 			trigger_error('Form "<strong>' . $this->formName . '</strong>" isn\'t declared in "<strong>' . $this->Prefix . '</strong>" unit config.', E_USER_NOTICE);
 		}
 		else {
 			$this->formConfig = kUtil::array_merge_recursive($this->formConfig, $forms[$this->formName]);
 		}
 	}
 
 	/**
 	 * Add field definitions from all possible sources
 	 * Used field sources: database fields, custom fields, virtual fields, calculated fields, aggregated calculated fields
 	 *
 	 * @access protected
 	 */
 	protected function defineFields()
 	{
 		$this->Fields = $this->getFormOption('Fields', Array ());
 		$this->customFields = $this->getFormOption('CustomFields', Array());
 
 		$this->setVirtualFields( $this->getFormOption('VirtualFields', Array ()) );
 
 		$calculated_fields = $this->getFormOption('CalculatedFields', Array());
 		$this->CalculatedFields = $this->getFieldsBySpecial($calculated_fields);
 
 		$aggregated_calculated_fields = $this->getFormOption('AggregatedCalculatedFields', Array());
 		$this->AggregatedCalculatedFields = $this->getFieldsBySpecial($aggregated_calculated_fields);
 	}
 
 	/**
 	 * Returns form name, used for validation
 	 *
 	 * @return string
 	 */
 	public function getFormName()
 	{
 		return $this->formName;
 	}
 
 	/**
 	 * Reads unit (specified by $prefix) option specified by $option and applies form change to it
 	 *
 	 * @param string $option
 	 * @param mixed $default
 	 * @return string
 	 * @access public
 	 */
 	public function getFormOption($option, $default = false)
 	{
 		$ret = $this->Application->getUnitOption($this->Prefix, $option, $default);
 
 		if ( isset($this->formConfig[$option]) ) {
 			$ret = kUtil::array_merge_recursive($ret, $this->formConfig[$option]);
 		}
 
 		return $ret;
 	}
 
 	/**
 	 * Only exteracts fields, that match current object Special
 	 *
 	 * @param Array $fields
 	 * @return Array
 	 * @access protected
 	 */
 	protected function getFieldsBySpecial($fields)
 	{
 		if ( array_key_exists($this->Special, $fields) ) {
 			return $fields[$this->Special];
 		}
 
 		return array_key_exists('', $fields) ? $fields[''] : Array();
 	}
 
 	/**
 	 * Sets aggeregated calculated fields
 	 *
 	 * @param Array $fields
 	 * @access public
 	 */
 	public function setAggregatedCalculatedFields($fields)
 	{
 		$this->AggregatedCalculatedFields = $fields;
 	}
 
 	/**
 	 * Set's field names from table from config
 	 *
 	 * @param Array $fields
 	 * @access public
 	 */
 	public function setCustomFields($fields)
 	{
 		$this->customFields = $fields;
 	}
 
 	/**
 	 * Returns custom fields information from table from config
 	 *
 	 * @return Array
 	 * @access public
 	 */
 	public function getCustomFields()
 	{
 		return $this->customFields;
 	}
 
 	/**
 	 * Set's fields information from table from config
 	 *
 	 * @param Array $fields
 	 * @access public
 	 */
 	public function setFields($fields)
 	{
 		$this->Fields = $fields;
 	}
 
 	/**
 	 * Returns fields information from table from config
 	 *
 	 * @return Array
 	 * @access public
 	 */
 	public function getFields()
 	{
 		return $this->Fields;
 	}
 
 	/**
 	 * Checks, that given field exists
 	 *
 	 * @param string $field
 	 * @return bool
 	 * @access public
 	 */
 	public function isField($field)
 	{
 		return array_key_exists($field, $this->Fields);
 	}
 
 	/**
 	 * Override field options with ones defined in submit via "field_modfiers" array (common for all prefixes)
 	 *
 	 * @param Array $field_modifiers
 	 * @return void
 	 * @access public
 	 * @author Alex
 	 */
 	public function ApplyFieldModifiers($field_modifiers = null)
 	{
 		$allowed_modifiers = Array ('required', 'multiple');
 
 		if ( $this->Application->isAdminUser ) {
 			// can change upload dir on the fly (admin only!)
 			$allowed_modifiers[] = 'upload_dir';
 		}
 
 		if ( !isset($field_modifiers) ) {
 			$field_modifiers = $this->Application->GetVar('field_modifiers');
 			if ( !$field_modifiers ) {
 				// no field modifiers
 				return ;
 			}
 
 			$field_modifiers = getArrayValue($field_modifiers, $this->getPrefixSpecial());
 		}
 
 		if ( !$field_modifiers ) {
 			// no field modifiers for current prefix_special
 			return ;
 		}
 
 		foreach ($field_modifiers as $field => $field_options) {
 			foreach ($field_options as $option_name => $option_value) {
 				if ( !in_array(strtolower($option_name), $allowed_modifiers) ) {
 					continue;
 				}
 
 				$this->Fields[$field][$option_name] = $option_value;
 			}
 		}
 	}
 
 	/**
 	 * Set fields (+options) for fields that physically doesn't exist in database
 	 *
 	 * @param Array $fields
 	 * @access public
 	 */
 	public function setVirtualFields($fields)
 	{
 		if ($fields) {
 			$this->VirtualFields = $fields;
 			$this->Fields = array_merge($this->VirtualFields, $this->Fields);
 		}
 	}
 
 	/**
 	 * Returns virtual fields
 	 *
 	 * @return Array
 	 * @access public
 	 */
 	public function getVirtualFields()
 	{
 		return $this->VirtualFields;
 	}
 
 	/**
 	 * Checks, that given field is a virtual field
 	 *
 	 * @param string $field
 	 * @return bool
 	 * @access public
 	 */
 	public function isVirtualField($field)
 	{
 		return array_key_exists($field, $this->VirtualFields);
 	}
 
 	/**
 	 * Performs additional initialization for field default values
 	 *
 	 * @access protected
 	 */
 	protected function SetDefaultValues()
 	{
 		foreach ($this->Fields as $field => $options) {
 			if ( array_key_exists('default', $options) && $options['default'] === '#NOW#' ) {
 				$this->Fields[$field]['default'] = adodb_mktime();
 			}
 		}
 	}
 
 	/**
 	 * Overwrites field definition in unit config
 	 *
 	 * @param string $field
 	 * @param Array $options
 	 * @param bool $is_virtual
 	 * @access public
 	 */
 	public function SetFieldOptions($field, $options, $is_virtual = false)
 	{
 		if ($is_virtual) {
 			$this->VirtualFields[$field] = $options;
 			$this->Fields = array_merge($this->VirtualFields, $this->Fields);
 		}
 		else {
 			$this->Fields[$field] = $options;
 		}
 	}
 
 	/**
 	 * Changes/sets given option's value in given field definiton
 	 *
 	 * @param string $field
 	 * @param string $option_name
 	 * @param mixed $option_value
 	 * @param bool $is_virtual
 	 * @access public
 	 */
 	public function SetFieldOption($field, $option_name, $option_value, $is_virtual = false)
 	{
 		if ($is_virtual) {
 			$this->VirtualFields[$field][$option_name] = $option_value;
 		}
 
 		$this->Fields[$field][$option_name] = $option_value;
 	}
 
 	/**
 	 * Returns field definition from unit config.
 	 * Also executes sql from "options_sql" field option to form "options" field option
 	 *
 	 * @param string $field
 	 * @param bool $is_virtual
 	 * @return Array
 	 * @access public
 	 */
 	public function GetFieldOptions($field, $is_virtual = false)
 	{
 		$property_name = $is_virtual ? 'VirtualFields' : 'Fields';
 
 		if ( !array_key_exists($field, $this->$property_name) ) {
 			return Array ();
 		}
 
 		if (!$is_virtual) {
 			if (!array_key_exists('options_prepared', $this->Fields[$field]) || !$this->Fields[$field]['options_prepared']) {
 				// executes "options_sql" from field definition, only when field options are accessed (late binding)
 				$this->PrepareFieldOptions($field);
 				$this->Fields[$field]['options_prepared'] = true;
 			}
 		}
 
 		return $this->{$property_name}[$field];
 	}
 
 	/**
 	 * Returns field option
 	 *
 	 * @param string $field
 	 * @param string $option_name
 	 * @param string $is_virtual
 	 * @param string $default
 	 * @return string
 	 * @access public
 	 */
 	public function GetFieldOption($field, $option_name, $is_virtual = false, $default = false)
 	{
 		$field_options = $this->GetFieldOptions($field, $is_virtual);
 
 		if ( !$field_options && strpos($field, '#') === false ) {
 			// we use "#FIELD_NAME#" as field for InputName tag in JavaScript, so ignore it
 			$form_name = $this->getFormName();
 			trigger_error('Field "<strong>' . $field . '</strong>" is not defined' . ($form_name ? ' on "<strong>' . $this->getFormName() . '</strong>" form' : '') . ' in "<strong>' . $this->Prefix . '</strong>" unit config', E_USER_WARNING);
 
 			return false;
 		}
 
 		return array_key_exists($option_name, $field_options) ? $field_options[$option_name] : $default;
 	}
 
 	/**
 	 * Returns formatted field value
 	 *
 	 * @param string $name
 	 * @param string $format
 	 *
 	 * @return string
 	 * @access protected
 	 */
 	public function GetField($name, $format = null)
 	{
 		$formatter_class = $this->GetFieldOption($name, 'formatter');
 
 		if ( $formatter_class ) {
 			$value = ($formatter_class == 'kMultiLanguage') && !preg_match('/^l[0-9]+_/', $name) ? '' : $this->GetDBField($name);
 
 			$formatter =& $this->Application->recallObject($formatter_class);
 			/* @var $formatter kFormatter */
 
 			return $formatter->Format($value, $name, $this, $format);
 		}
 
 		return $this->GetDBField($name);
 	}
 
 	/**
 	 * Returns unformatted field value
 	 *
 	 * @param string $field
 	 * @return string
 	 * @access protected
 	 */
 	abstract protected function GetDBField($field);
 
 	/**
 	 * Checks of object has given field
 	 *
 	 * @param string $name
 	 * @return bool
 	 * @access protected
 	 */
 	abstract protected function HasField($name);
 
 	/**
 	 * Returns field values
 	 *
 	 * @return Array
 	 * @access protected
 	 */
 	abstract protected function GetFieldValues();
 
 	/**
 	 * Populates values of sub-fields, based on formatters, set to mater fields
 	 *
 	 * @param Array $fields
 	 * @access public
 	 * @todo Maybe should not be publicly accessible
 	 */
 	public function UpdateFormattersSubFields($fields = null)
 	{
 		if ( !is_array($fields) ) {
 			$fields = array_keys($this->Fields);
 		}
 
 		foreach ($fields as $field) {
 			if ( isset($this->Fields[$field]['formatter']) ) {
 				$formatter =& $this->Application->recallObject($this->Fields[$field]['formatter']);
 				/* @var $formatter kFormatter */
 
 				$formatter->UpdateSubFields($field, $this->GetDBField($field), $this->Fields[$field], $this);
 			}
 		}
 	}
 
 	/**
 	 * Use formatters, specified in field declarations to perform additional field initialization in unit config
 	 *
 	 * @access protected
 	 */
 	protected function prepareConfigOptions()
 	{
 		$field_names = array_keys($this->Fields);
 
 		foreach ($field_names as $field_name) {
 			if ( !array_key_exists('formatter', $this->Fields[$field_name]) ) {
 				continue;
 			}
 
 			$formatter =& $this->Application->recallObject( $this->Fields[$field_name]['formatter'] );
 			/* @var $formatter kFormatter */
 
 			$formatter->PrepareOptions($field_name, $this->Fields[$field_name], $this);
 		}
 	}
 
 	/**
 	 * Escapes fields only, not expressions
 	 *
 	 * @param string $field_expr
 	 * @return string
 	 * @access protected
 	 */
 	protected function escapeField($field_expr)
 	{
 		return preg_match('/[.(]/', $field_expr) ? $field_expr : '`' . $field_expr . '`';
 	}
 
 	/**
 	 * Replaces current language id in given field options
 	 *
 	 * @param string $field_name
 	 * @param Array $field_option_names
 	 * @access protected
 	 */
 	protected function _replaceLanguageId($field_name, $field_option_names)
 	{
 		// don't use GetVar('m_lang') since it's always equals to default language on editing form in admin
 		$current_language_id = $this->Application->Phrases->LanguageId;
 		$primary_language_id = $this->Application->GetDefaultLanguageId();
 
 		$field_options =& $this->Fields[$field_name];
 		foreach ($field_option_names as $option_name) {
 			$field_options[$option_name] = str_replace('%2$s', $current_language_id, $field_options[$option_name]);
 			$field_options[$option_name] = str_replace('%3$s', $primary_language_id, $field_options[$option_name]);
 		}
 	}
 
 	/**
 	 * Transforms "options_sql" field option into valid "options" array for given field
 	 *
 	 * @param string $field_name
 	 * @access protected
 	 */
 	protected function PrepareFieldOptions($field_name)
 	{
 		$field_options =& $this->Fields[$field_name];
 		if (array_key_exists('options_sql', $field_options) ) {
 			// get options based on given sql
 			$replace_options = Array ('option_title_field', 'option_key_field', 'options_sql');
 			$this->_replaceLanguageId($field_name, $replace_options);
 
 			$select_clause = $this->escapeField($field_options['option_title_field']) . ',' . $this->escapeField($field_options['option_key_field']);
 			$sql = sprintf($field_options['options_sql'], $select_clause);
 
 			if (array_key_exists('serial_name', $field_options)) {
 				// try to cache option sql on serial basis
 				$cache_key = 'sql_' . crc32($sql) . '[%' . $field_options['serial_name'] . '%]';
 				$dynamic_options = $this->Application->getCache($cache_key);
 
 				if ($dynamic_options === false) {
 					$this->Conn->nextQueryCachable = true;
 					$dynamic_options = $this->Conn->GetCol($sql, preg_replace('/^.*?\./', '', $field_options['option_key_field']));
 					$this->Application->setCache($cache_key, $dynamic_options);
 				}
 			}
 			else {
 				// don't cache options sql
 				$dynamic_options = $this->Conn->GetCol($sql, preg_replace('/^.*?\./', '', $field_options['option_key_field']));
 			}
 
 			$options_hash = array_key_exists('options', $field_options) ? $field_options['options'] : Array ();
 			$field_options['options'] = kUtil::array_merge_recursive($options_hash, $dynamic_options); // because of numeric keys
 		}
 	}
 
 	/**
 	 * Returns ID of currently processed record
 	 *
 	 * @return int
 	 * @access public
 	 */
 	public function GetID()
 	{
 		return $this->GetDBField($this->IDField);
 	}
 
 	/**
 	 * Allows kDBTagProcessor.SectionTitle to detect if it's editing or new item creation
 	 *
 	 * @return bool
 	 * @access public
 	 */
 	public function IsNewItem()
 	{
 		return $this->GetID() ? false : true;
 	}
 
 	/**
 	 * Returns parent table information
 	 *
 	 * @param string $special special of main item
 	 * @param bool $guess_special if object retrieved with specified special is not loaded, then try not to use special
 	 * @return Array
 	 * @access public
 	 */
 	public function getLinkedInfo($special = '', $guess_special = false)
 	{
 		$parent_prefix = $this->Application->getUnitOption($this->Prefix, 'ParentPrefix');
 		if ($parent_prefix) {
 			// if this is linked table, then set id from main table
 			$table_info = Array (
 				'TableName' => $this->Application->getUnitOption($this->Prefix,'TableName'),
 				'IdField' => $this->Application->getUnitOption($this->Prefix,'IDField'),
 				'ForeignKey' => $this->Application->getUnitOption($this->Prefix,'ForeignKey'),
 				'ParentTableKey' => $this->Application->getUnitOption($this->Prefix,'ParentTableKey'),
 				'ParentPrefix' => $parent_prefix
 			);
 
 			if (is_array($table_info['ForeignKey'])) {
 					$table_info['ForeignKey'] = getArrayValue($table_info, 'ForeignKey', $parent_prefix);
 			}
 
 			if (is_array($table_info['ParentTableKey'])) {
 				$table_info['ParentTableKey'] = getArrayValue($table_info, 'ParentTableKey', $parent_prefix);
 			}
 
 			$main_object =& $this->Application->recallObject($parent_prefix.'.'.$special, null, Array ('raise_warnings' => 0));
 			/* @var $main_object kDBItem */
 
 			if (!$main_object->isLoaded() && $guess_special) {
 				$main_object =& $this->Application->recallObject($parent_prefix);
 			}
 
 			return array_merge($table_info, Array('ParentId'=> $main_object->GetDBField( $table_info['ParentTableKey'] ) ) );
 		}
 
 		return false;
 	}
 
 	/**
 	 * Returns true, when list/item was queried/loaded
 	 *
 	 * @return bool
 	 * @access protected
 	 */
 	abstract protected function isLoaded();
 
 	/**
 	 * Returns specified field value from all selected rows.
 	 * Don't affect current record index
 	 *
 	 * @param string $field
 	 * @return Array
 	 * @access protected
 	 */
 	abstract protected function GetCol($field);
 }
\ No newline at end of file
Index: branches/5.2.x/core/units/categories/categories_event_handler.php
===================================================================
--- branches/5.2.x/core/units/categories/categories_event_handler.php	(revision 14643)
+++ branches/5.2.x/core/units/categories/categories_event_handler.php	(revision 14644)
@@ -1,2485 +1,2485 @@
 <?php
 /**
 * @version	$Id$
 * @package	In-Portal
 * @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
 * @license      GNU/GPL
 * In-Portal is Open Source software.
 * This means that this software may have been modified pursuant
 * the GNU General Public License, and as distributed it includes
 * or is derivative of works licensed under the GNU General Public License
 * or other free or open source software licenses.
 * See http://www.in-portal.org/license for copyright notices and details.
 */
 
 	defined('FULL_PATH') or die('restricted access!');
 
 	class CategoriesEventHandler extends kDBEventHandler {
 
 		/**
 		 * Allows to override standart permission mapping
 		 *
 		 */
 		function mapPermissions()
 		{
 			parent::mapPermissions();
 
 			$permissions = Array (
 				'OnRebuildCache' => Array ('self' => 'add|edit'),
 				'OnCopy' => Array ('self' => true),
 				'OnCut' => Array ('self' => 'edit'),
 				'OnPasteClipboard' => Array ('self' => true),
 				'OnPaste' => Array ('self' => 'add|edit', 'subitem' => 'edit'),
 
 				'OnRecalculatePriorities' => Array ('self' => 'add|edit'), // category ordering
 				'OnItemBuild' => Array ('self' => true), // always allow to view individual categories (regardless of CATEGORY.VIEW right)
 				'OnUpdatePreviewBlock' => Array ('self' => true), // for FCKEditor integration
 			);
 
 			$this->permMapping = array_merge($this->permMapping, $permissions);
 		}
 
 		/**
 		 * Categories are sorted using special sorting event
 		 *
 		 */
 		function mapEvents()
 		{
 			parent::mapEvents();
 
 			$events_map = Array (
 				'OnMassMoveUp' => 'OnChangePriority',
 				'OnMassMoveDown' => 'OnChangePriority',
 			);
 
 			$this->eventMethods = array_merge($this->eventMethods, $events_map);
 		}
 
 		/**
 		 * Checks user permission to execute given $event
 		 *
 		 * @param kEvent $event
 		 * @return bool
 		 * @access public
 		 */
 		public function CheckPermission(&$event)
 		{
 			if ($event->Name == 'OnResetCMSMenuCache') {
 				// events from "Tools -> System Tools" section are controlled via that section "edit" permission
 
 				$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 				/* @var $perm_helper kPermissionsHelper */
 
 				$perm_value = $this->Application->CheckPermission('in-portal:service.edit');
 
 				return $perm_helper->finalizePermissionCheck($event, $perm_value);
 			}
 
 			if (!$this->Application->isAdmin) {
 				if ($event->Name == 'OnSetSortingDirect') {
 					// allow sorting on front event without view permission
 					return true;
 				}
 
 				if ($event->Name == 'OnItemBuild') {
 					$category_id = $this->getPassedID($event);
 					if ($category_id == 0) {
 						return true;
 					}
 				}
 			}
 
 			if (in_array($event->Name, $this->_getMassPermissionEvents())) {
 				$items = $this->_getPermissionCheckInfo($event);
 
 				$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 				/* @var $perm_helper kPermissionsHelper */
 
 				if (($event->Name == 'OnSave') && array_key_exists(0, $items)) {
 					// adding new item (ID = 0)
 					$perm_value = $perm_helper->AddCheckPermission($items[0]['ParentId'], $event->Prefix) > 0;
 				}
 				else {
 					// leave only items, that can be edited
 					$ids = Array ();
 					$check_method = in_array($event->Name, Array ('OnMassDelete', 'OnCut')) ? 'DeleteCheckPermission' : 'ModifyCheckPermission';
 					foreach ($items as $item_id => $item_data) {
 						if ($perm_helper->$check_method($item_data['CreatedById'], $item_data['ParentId'], $event->Prefix) > 0) {
 							$ids[] = $item_id;
 						}
 					}
 
 					if (!$ids) {
 						// no items left for editing -> no permission
 						return $perm_helper->finalizePermissionCheck($event, false);
 					}
 
 					$perm_value = true;
 					$event->setEventParam('ids', $ids); // will be used later by "kDBEventHandler::StoreSelectedIDs" method
 				}
 
 				return $perm_helper->finalizePermissionCheck($event, $perm_value);
 			}
 
 			if ($event->Name == 'OnRecalculatePriorities') {
 				$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 				/* @var $perm_helper kPermissionsHelper */
 
 				$category_id = $this->Application->GetVar('m_cat_id');
 
 				return $perm_helper->AddCheckPermission($category_id, $event->Prefix) || $perm_helper->ModifyCheckPermission(0, $category_id, $event->Prefix);
 			}
 
 			if ($event->Name == 'OnPasteClipboard') {
 				// forces permission check to work by current category for "Paste In Category" operation
 				$category_id = $this->Application->GetVar('m_cat_id');
 				$this->Application->SetVar('c_id', $category_id);
 			}
 
 			return parent::CheckPermission($event);
 		}
 
 		/**
 		 * Returns events, that require item-based (not just event-name based) permission check
 		 *
 		 * @return Array
 		 */
 		function _getMassPermissionEvents()
 		{
 			return Array (
 				'OnEdit', 'OnSave', 'OnMassDelete', 'OnMassApprove',
 				'OnMassDecline', 'OnMassMoveUp', 'OnMassMoveDown',
 				'OnCut',
 			);
 		}
 
 		/**
 		 * Returns category item IDs, that require permission checking
 		 *
 		 * @param kEvent $event
 		 * @return string
 		 */
 		function _getPermissionCheckIDs(&$event)
 		{
 			if ($event->Name == 'OnSave') {
 				$selected_ids = implode(',', $this->getSelectedIDs($event, true));
 				if (!$selected_ids) {
 					$selected_ids = 0; // when saving newly created item (OnPreCreate -> OnPreSave -> OnSave)
 				}
 			}
 			else {
 				// OnEdit, OnMassDelete events, when items are checked in grid
 				$selected_ids = implode(',', $this->StoreSelectedIDs($event));
 			}
 
 			return $selected_ids;
 		}
 
 		/**
 		 * Returns information used in permission checking
 		 *
 		 * @param kEvent $event
 		 * @return Array
 		 */
 		function _getPermissionCheckInfo(&$event)
 		{
 			// when saving data from temp table to live table check by data from temp table
 			$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
 			$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
 
 			if ($event->Name == 'OnSave') {
 				$table_name = $this->Application->GetTempName($table_name, 'prefix:' . $event->Prefix);
 			}
 
 			$sql = 'SELECT ' . $id_field . ', CreatedById, ParentId
 					FROM ' . $table_name . '
 					WHERE ' . $id_field . ' IN (' . $this->_getPermissionCheckIDs($event) . ')';
 			$items = $this->Conn->Query($sql, $id_field);
 
 			if (!$items) {
 				// when creating new category, then no IDs are stored in session
 				$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
 				list ($id, $fields_hash) = each($items_info);
 
 				if (array_key_exists('ParentId', $fields_hash)) {
 					$item_category = $fields_hash['ParentId'];
 				}
 				else {
 					$item_category = $this->Application->RecallVar('m_cat_id'); // saved in c:OnPreCreate event permission checking
 				}
 
 				$items[$id] = Array (
 					'CreatedById' => $this->Application->RecallVar('user_id'),
 					'ParentId' => $item_category,
 				);
 			}
 
 			return $items;
 		}
 
 		/**
 		 * Set's mark, that root category is edited
 		 *
 		 * @param kEvent $event
 		 */
 		function OnEdit(&$event)
 		{
 			$category_id = $this->Application->GetVar($event->getPrefixSpecial() . '_id');
 			$home_category = $this->Application->getBaseCategory();
 
 			$this->Application->StoreVar('IsRootCategory_'.$this->Application->GetVar('m_wid'), ($category_id === '0') || ($category_id == $home_category));
 
 			parent::OnEdit($event);
 
 			if ($event->status == kEvent::erSUCCESS) {
 				// keep "Section Properties" link (in browse modes) clean
 				$this->Application->DeleteVar('admin');
 			}
 		}
 
 		/**
 		 * Adds selected link to listing
 		 *
 		 * @param kEvent $event
 		 */
 		function OnProcessSelected(&$event)
 		{
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			$selected_ids = $this->Application->GetVar('selected_ids');
 
 			$this->RemoveRequiredFields($object);
 			$object->SetDBField($this->Application->RecallVar('dst_field'), $selected_ids['c']);
 			$object->Update();
 
 			$this->finalizePopup($event);
 		}
 
 		/**
 		 * Apply system filter to categories list
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 * @see kDBEventHandler::OnListBuild()
 		 */
 		protected function SetCustomQuery(&$event)
 		{
 			parent::SetCustomQuery($event);
 
 			$object =& $event->getObject();
 			/* @var $object kDBList */
 
 			// don't show "Content" category in advanced view
 			$object->addFilter('system_categories', '%1$s.Status <> 4');
 
 			// show system templates from current theme only + all virtual templates
 			$object->addFilter('theme_filter', '%1$s.ThemeId = ' . $this->_getCurrentThemeId() . ' OR %1$s.ThemeId = 0');
 
 			if ($event->Special == 'showall') {
 				// if using recycle bin don't show categories from there
 				$recycle_bin = $this->Application->ConfigValue('RecycleBinFolder');
 				if ($recycle_bin) {
 					$sql = 'SELECT TreeLeft, TreeRight
 							FROM '.TABLE_PREFIX.'Category
 							WHERE CategoryId = '.$recycle_bin;
 					$tree_indexes = $this->Conn->GetRow($sql);
 
 					$object->addFilter('recyclebin_filter', '%1$s.TreeLeft < '.$tree_indexes['TreeLeft'].' OR %1$s.TreeLeft > '.$tree_indexes['TreeRight']);
 				}
 			}
 
 			if ($event->getEventParam('parent_cat_id') !== false) {
 				$parent_cat_id = $event->getEventParam('parent_cat_id');
 
 				if ("$parent_cat_id" == 'Root') {
 					$module_name = $event->getEventParam('module') ? $event->getEventParam('module') : 'In-Commerce';
 					$parent_cat_id = $this->Application->findModule('Name', $module_name, 'RootCat');
 				}
 			}
 			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 ("$parent_cat_id" == '0') {
 				// replace "0" category with "Content" category id (this way template
 				$parent_cat_id = $this->Application->getBaseCategory();
 			}
 
 			if ("$parent_cat_id" != 'any') {
 				if ($event->getEventParam('recursive')) {
 					if ($parent_cat_id > 0) {
 						// not "Home" category
 						$tree_indexes = $this->Application->getTreeIndex($parent_cat_id);
 
 						$object->addFilter('parent_filter', TABLE_PREFIX.'Category.TreeLeft BETWEEN '.$tree_indexes['TreeLeft'].' AND '.$tree_indexes['TreeRight']);
 					}
 				}
 				else {
 					$object->addFilter('parent_filter', '%1$s.ParentId = '.$parent_cat_id);
 				}
 			}
 
 			$object->addFilter('perm_filter', TABLE_PREFIX . 'PermCache.PermId = 1'); // check for CATEGORY.VIEW permission
 			if ($this->Application->RecallVar('user_id') != USER_ROOT) {
 				// apply permission filters to all users except "root"
 				$groups = explode(',',$this->Application->RecallVar('UserGroups'));
 				foreach ($groups as $group) {
 					$view_filters[] = 'FIND_IN_SET('.$group.', ' . TABLE_PREFIX . 'PermCache.ACL)';
 				}
 				$view_filter = implode(' OR ', $view_filters);
 				$object->addFilter('perm_filter2', $view_filter);
 			}
 
 			if (!$this->Application->isAdminUser)	{
 				// apply status filter only on front
 				$object->addFilter('status_filter', $object->TableName.'.Status = 1');
 			}
 
 			// process "types" and "except" parameters
 			$type_clauses = Array();
 
 			$types = $event->getEventParam('types');
 			$types = $types ? explode(',', $types) : Array ();
 
 			$except_types = $event->getEventParam('except');
 			$except_types = $except_types ? explode(',', $except_types) : Array ();
 
 			if (in_array('related', $types) || in_array('related', $except_types)) {
 				$related_to = $event->getEventParam('related_to');
 				if (!$related_to) {
 					$related_prefix = $event->Prefix;
 				}
 				else {
 					$sql = 'SELECT Prefix
 							FROM '.TABLE_PREFIX.'ItemTypes
 							WHERE ItemName = '.$this->Conn->qstr($related_to);
 					$related_prefix = $this->Conn->GetOne($sql);
 				}
 
 				$rel_table = $this->Application->getUnitOption('rel', 'TableName');
 				$item_type = (int)$this->Application->getUnitOption($event->Prefix, 'ItemType');
 
 				if ($item_type == 0) {
 					trigger_error('<strong>ItemType</strong> not defined for prefix <strong>' . $event->Prefix . '</strong>', E_USER_WARNING);
 				}
 
 				// process case, then this list is called inside another list
 				$prefix_special = $event->getEventParam('PrefixSpecial');
 				if (!$prefix_special) {
 					$prefix_special = $this->Application->Parser->GetParam('PrefixSpecial');
 				}
 
 				$id = false;
 				if ($prefix_special !== false) {
 					$processed_prefix = $this->Application->processPrefix($prefix_special);
 					if ($processed_prefix['prefix'] == $related_prefix) {
 						// printing related categories within list of items (not on details page)
 						$list =& $this->Application->recallObject($prefix_special);
 						/* @var $list kDBList */
 
 						$id = $list->GetID();
 					}
 				}
 
 				if ($id === false) {
 					// printing related categories for single item (possibly on details page)
 					if ($related_prefix == 'c') {
 						$id = $this->Application->GetVar('m_cat_id');
 					}
 					else {
 						$id = $this->Application->GetVar($related_prefix . '_id');
 					}
 				}
 
 				$p_item =& $this->Application->recallObject($related_prefix . '.current', null, Array('skip_autoload' => true));
 				/* @var $p_item kCatDBItem */
 
 				$p_item->Load( (int)$id );
 
 				$p_resource_id = $p_item->GetDBField('ResourceId');
 
 				$sql = 'SELECT SourceId, TargetId FROM '.$rel_table.'
 						WHERE
 							(Enabled = 1)
 							AND (
 									(Type = 0 AND SourceId = '.$p_resource_id.' AND TargetType = '.$item_type.')
 									OR
 									(Type = 1
 										AND (
 												(SourceId = '.$p_resource_id.' AND TargetType = '.$item_type.')
 												OR
 												(TargetId = '.$p_resource_id.' AND SourceType = '.$item_type.')
 											)
 									)
 							)';
 
 				$related_ids_array = $this->Conn->Query($sql);
 				$related_ids = Array();
 
 				foreach ($related_ids_array as $key => $record) {
 					$related_ids[] = $record[ $record['SourceId'] == $p_resource_id ? 'TargetId' : 'SourceId' ];
 				}
 
 				if (count($related_ids) > 0) {
 					$type_clauses['related']['include'] = '%1$s.ResourceId IN ('.implode(',', $related_ids).')';
 					$type_clauses['related']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $related_ids).')';
 				}
 				else {
 					$type_clauses['related']['include'] = '0';
 					$type_clauses['related']['except'] = '1';
 				}
 
 				$type_clauses['related']['having_filter'] = false;
 			}
 
 			if (in_array('category_related', $type_clauses)) {
 				$object->removeFilter('parent_filter');
 				$resource_id = $this->Conn->GetOne('
 								SELECT ResourceId FROM '.$this->Application->getUnitOption($event->Prefix, 'TableName').'
 								WHERE CategoryId = '.$parent_cat_id
 							);
 
 				$sql = 'SELECT DISTINCT(TargetId) FROM '.TABLE_PREFIX.'Relationship
 						WHERE SourceId = '.$resource_id.' AND SourceType = 1';
 				$related_cats = $this->Conn->GetCol($sql);
 				$related_cats = is_array($related_cats) ? $related_cats : Array();
 
 				$sql = 'SELECT DISTINCT(SourceId) FROM '.TABLE_PREFIX.'Relationship
 						WHERE TargetId = '.$resource_id.' AND TargetType = 1 AND Type = 1';
 				$related_cats2 = $this->Conn->GetCol($sql);
 				$related_cats2 = is_array($related_cats2) ? $related_cats2 : Array();
 				$related_cats = array_unique( array_merge( $related_cats2, $related_cats ) );
 
 				if ($related_cats) {
 					$type_clauses['category_related']['include'] = '%1$s.ResourceId IN ('.implode(',', $related_cats).')';
 					$type_clauses['category_related']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $related_cats).')';
 				}
 				else
 				{
 					$type_clauses['category_related']['include'] = '0';
 					$type_clauses['category_related']['except'] = '1';
 				}
 				$type_clauses['category_related']['having_filter'] = false;
 			}
 
 			if (in_array('product_related', $types)) {
 				$object->removeFilter('parent_filter');
 
 				$product_id = $event->getEventParam('product_id') ? $event->getEventParam('product_id') : $this->Application->GetVar('p_id');
 				$resource_id = $this->Conn->GetOne('
 								SELECT ResourceId FROM '.$this->Application->getUnitOption('p', 'TableName').'
 								WHERE ProductId = '.$product_id
 							);
 
 				$sql = 'SELECT DISTINCT(TargetId) FROM '.TABLE_PREFIX.'Relationship
 						WHERE SourceId = '.$resource_id.' AND TargetType = 1';
 				$related_cats = $this->Conn->GetCol($sql);
 				$related_cats = is_array($related_cats) ? $related_cats : Array();
 				$sql = 'SELECT DISTINCT(SourceId) FROM '.TABLE_PREFIX.'Relationship
 						WHERE TargetId = '.$resource_id.' AND SourceType = 1 AND Type = 1';
 				$related_cats2 = $this->Conn->GetCol($sql);
 				$related_cats2 = is_array($related_cats2) ? $related_cats2 : Array();
 				$related_cats = array_unique( array_merge( $related_cats2, $related_cats ) );
 
 				if ($related_cats) {
 					$type_clauses['product_related']['include'] = '%1$s.ResourceId IN ('.implode(',', $related_cats).')';
 					$type_clauses['product_related']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $related_cats).')';
 				}
 				else {
 					$type_clauses['product_related']['include'] = '0';
 					$type_clauses['product_related']['except'] = '1';
 				}
 
 				$type_clauses['product_related']['having_filter'] = false;
 			}
 
 			$type_clauses['menu']['include'] = '%1$s.IsMenu = 1';
 			$type_clauses['menu']['except'] = '%1$s.IsMenu = 0';
 			$type_clauses['menu']['having_filter'] = false;
 
 			if (in_array('search', $types) || in_array('search', $except_types)) {
 				$event_mapping = Array (
 					'simple'		=>	'OnSimpleSearch',
 					'subsearch'		=>	'OnSubSearch',
 					'advanced'		=>	'OnAdvancedSearch'
 				);
 
 				$type = $this->Application->GetVar('search_type', 'simple');
 
 				if ($keywords = $event->getEventParam('keyword_string')) {
 					// processing keyword_string param of ListProducts tag
 					$this->Application->SetVar('keywords', $keywords);
 					$type = 'simple';
 				}
 
 				$search_event = $event_mapping[$type];
 				$this->$search_event($event);
 
 				$object =& $event->getObject();
 				/* @var $object kDBList */
 
 				$search_sql = '	FROM ' . TABLE_PREFIX . 'ses_' . $this->Application->GetSID() . '_' . TABLE_PREFIX . 'Search
 								search_result LEFT JOIN %1$s ON %1$s.ResourceId = search_result.ResourceId';
-				$sql = str_replace('FROM %1$s', $search_sql, $object->SelectClause);
+				$sql = str_replace('FROM %1$s', $search_sql, $object->GetPlainSelectSQL());
 
 				$object->SetSelectSQL($sql);
 
 				$object->addCalculatedField('Relevance', 'search_result.Relevance');
 				$object->AddOrderField('search_result.Relevance', 'desc', true);
 
 				$type_clauses['search']['include'] = '1';
 				$type_clauses['search']['except'] = '0';
 				$type_clauses['search']['having_filter'] = false;
 			}
 
 			$search_helper =& $this->Application->recallObject('SearchHelper');
 			/* @var $search_helper kSearchHelper */
 
 			$search_helper->SetComplexFilter($event, $type_clauses, implode(',', $types), implode(',', $except_types));
 		}
 
 		/**
 		 * Returns current theme id
 		 *
 		 * @return int
 		 */
 		function _getCurrentThemeId()
 		{
 			$themes_helper =& $this->Application->recallObject('ThemesHelper');
 			/* @var $themes_helper kThemesHelper */
 
 			return (int)$themes_helper->getCurrentThemeId();
 		}
 
 		/**
 		 * Enter description here...
 		 *
 		 * @param kEvent $event
 		 * @return int
 		 */
 		function getPassedID(&$event)
 		{
 			if (($event->Special == 'page') || ($event->Special == '-virtual') || ($event->Prefix == 'st')) {
 				return $this->_getPassedStructureID($event);
 			}
 
 			if ($this->Application->isAdmin) {
 				return parent::getPassedID($event);
 			}
 
 			return $this->Application->GetVar('m_cat_id');
 		}
 
 		/**
 		 * Enter description here...
 		 *
 		 * @param kEvent $event
 		 * @return int
 		 */
 		function _getPassedStructureID(&$event)
 		{
 			static $page_by_template = Array ();
 
 			if ($event->Special == 'current') {
 				return $this->Application->GetVar('m_cat_id');
 			}
 
 			$event->setEventParam('raise_warnings', 0);
 
 			$page_id = parent::getPassedID($event);
 
 			if ($page_id === false) {
 				$template = $event->getEventParam('page');
 				if (!$template) {
 					$template = $this->Application->GetVar('t');
 				}
 
 				// bug: when template contains "-" symbols (or others, that stripDisallowed will replace) it's not found
 				if (!array_key_exists($template, $page_by_template)) {
 					$sql = 'SELECT ' . $this->Application->getUnitOption($event->Prefix, 'IDField') . '
 							FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
 							WHERE
 								(
 									(NamedParentPath = ' . $this->Conn->qstr($template) . ') OR
 									(NamedParentPath = ' . $this->Conn->qstr('Content/' . $template) . ') OR
 									(`Type` = ' . PAGE_TYPE_TEMPLATE . ' AND CachedTemplate = ' . $this->Conn->qstr($template) . ')
 								) AND (ThemeId = ' . $this->_getCurrentThemeId() . ' OR ThemeId = 0)';
 
 					$page_id = $this->Conn->GetOne($sql);
 				}
 				else {
 					$page_id = $page_by_template[$template];
 				}
 
 				if ($page_id === false && EDITING_MODE) {
 					// create missing pages, when in editing mode
 					$object =& $this->Application->recallObject($this->Prefix . '.rebuild', null, Array('skip_autoload' => true));
 					/* @var $object CategoriesItem */
 
 					$created = $this->_prepareAutoPage($object, $template, null, SMS_MODE_AUTO); // create virtual (not system!) page
 					if ($created) {
 						if ($this->Application->ConfigValue('QuickCategoryPermissionRebuild') || !$this->Application->isAdmin) {
 							$updater =& $this->Application->makeClass('kPermCacheUpdater');
 							/* @var $updater kPermCacheUpdater */
 
 							$updater->OneStepRun();
 						}
 
 						$this->_resetMenuCache();
 
 						$this->Application->RemoveVar('PermCache_UpdateRequired');
 
 						$page_id = $object->GetID();
 						$this->Application->SetVar('m_cat_id', $page_id);
 					}
 				}
 
 				if ($page_id) {
 					$page_by_template[$template] = $page_id;
 				}
 			}
 
 			if (!$page_id && !$this->Application->isAdmin) {
 				$page_id = $this->Application->GetVar('m_cat_id');
 			}
 
 			return $page_id;
 		}
 
 		function ParentGetPassedId(&$event)
 		{
 			return parent::GetPassedId($event);
 		}
 
 		/**
 		 * Adds calculates fields for item statuses
 		 *
 		 * @param kCatDBItem $object
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function prepareObject(&$object, &$event)
 		{
 			if ($event->Special != '-virtual') {
 				$object =& $event->getObject( Array('skip_autoload' => true) );
 
 				$object->addCalculatedField(
 					'IsNew',
 					'	IF(%1$s.NewItem = 2,
 							IF(%1$s.CreatedOn >= (UNIX_TIMESTAMP() - '.
 								$this->Application->ConfigValue('Category_DaysNew').
 								'*3600*24), 1, 0),
 							%1$s.NewItem
 					)');
 			}
 		}
 
 		/**
 		 * Set correct parent path for newly created categories
 		 *
 		 * @param kEvent $event
 		 */
 		function OnAfterCopyToLive(&$event)
 		{
 			$object =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('skip_autoload' => true, 'live_table' => true));
 			/* @var $object CategoriesItem */
 
 			$parent_path = false;
 			$object->Load( $event->getEventParam('id') );
 
 			if ( $event->getEventParam('temp_id') == 0 ) {
 				if ( $object->isLoaded() ) {
 					// update path only for real categories (not including "Home" root category)
 					$fields_hash = Array ('ParentPath' => $object->buildParentPath());
 					$this->Conn->doUpdate($fields_hash, $object->TableName, 'CategoryId = ' . $object->GetID());
 					$parent_path = $fields_hash['ParentPath'];
 				}
 			}
 			else {
 				$parent_path = $object->GetDBField('ParentPath');
 			}
 
 			if ( $parent_path ) {
 				$cache_updater =& $this->Application->makeClass('kPermCacheUpdater', Array (null, $parent_path));
 				/* @var $cache_updater kPermCacheUpdater */
 
 				$cache_updater->OneStepRun();
 			}
 		}
 
 		/**
 		 * Set cache modification mark if needed
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnBeforeDeleteFromLive(&$event)
 		{
 			parent::OnBeforeDeleteFromLive($event);
 
 			$id = $event->getEventParam('id');
 
 			// loading anyway, because this object is needed by "c-perm:OnBeforeDeleteFromLive" event
 			$temp_object =& $event->getObject(Array ('skip_autoload' => true));
 			/* @var $temp_object CategoriesItem */
 
 			$temp_object->Load($id);
 
 			if ( $id == 0 ) {
 				if ( $temp_object->isLoaded() ) {
 					// new category -> update cache (not loaded when "Home" category)
 					$this->Application->StoreVar('PermCache_UpdateRequired', 1);
 				}
 
 				return ;
 			}
 
 			// existing category was edited, check if in-cache fields are modified
 			$live_object =& $this->Application->recallObject($event->Prefix . '.-item', null, Array ('live_table' => true, 'skip_autoload' => true));
 			/* @var $live_object CategoriesItem */
 
 			$live_object->Load($id);
 			$cached_fields = Array ('l' . $this->Application->GetDefaultLanguageId() . '_Name', 'Filename', 'Template', 'ParentId', 'Priority');
 
 			foreach ($cached_fields as $cached_field) {
 				if ( $live_object->GetDBField($cached_field) != $temp_object->GetDBField($cached_field) ) {
 					// use session instead of REQUEST because of permission editing in category can contain
 					// multiple submits, that changes data before OnSave event occurs
 					$this->Application->StoreVar('PermCache_UpdateRequired', 1);
 					break;
 				}
 			}
 		}
 
 		/**
 		 * Calls kDBEventHandler::OnSave original event
 		 * Used in proj-cms:StructureEventHandler->OnSave
 		 *
 		 * @param kEvent $event
 		 */
 		function parentOnSave(&$event)
 		{
 			parent::OnSave($event);
 		}
 
 		/**
 		 * Reset root-category flag when new category is created
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnPreCreate(&$event)
 		{
 			// 1. for permission editing of Home category
 			$this->Application->RemoveVar('IsRootCategory_' . $this->Application->GetVar('m_wid'));
 
 			parent::OnPreCreate($event);
 
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			// 2. preset template
 			$category_id = $this->Application->GetVar('m_cat_id');
 			$root_category = $this->Application->getBaseCategory();
 
 			if ( $category_id == $root_category ) {
 				$object->SetDBField('Template', $this->_getDefaultDesign());
 			}
 
 			// 3. set default owner
 			$object->SetDBField('CreatedById', $this->Application->RecallVar('user_id'));
 		}
 
 		/**
 		 * Checks cache update mark and redirect to cache if needed
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnSave(&$event)
 		{
 			// get data from live table before it is overwritten by parent OnSave method call
 			$ids = $this->getSelectedIDs($event, true);
 			$is_editing = implode('', $ids);
 			$old_statuses = $is_editing ? $this->_getCategoryStatus($ids) : Array ();
 
 			$object =& $event->getObject();
 			/* @var $object CategoriesItem */
 
 			parent::OnSave($event);
 
 			if ( $event->status != kEvent::erSUCCESS ) {
 				return;
 			}
 
 			if ( $this->Application->RecallVar('PermCache_UpdateRequired') ) {
 				$this->Application->RemoveVar('IsRootCategory_' . $this->Application->GetVar('m_wid'));
 			}
 
 			$this->Application->StoreVar('RefreshStructureTree', 1);
 			$this->_resetMenuCache();
 
 			if ( $is_editing ) {
 				// send email event to category owner, when it's status is changed (from admin)
 				$object->SwitchToLive();
 				$new_statuses = $this->_getCategoryStatus($ids);
 				$process_statuses = Array (STATUS_ACTIVE, STATUS_DISABLED);
 
 				foreach ($new_statuses as $category_id => $new_status) {
 					if ( $new_status != $old_statuses[$category_id] && in_array($new_status, $process_statuses) ) {
 						$object->Load($category_id);
 						$email_event = $new_status == STATUS_ACTIVE ? 'CATEGORY.APPROVE' : 'CATEGORY.DENY';
 						$this->Application->EmailEventUser($email_event, $object->GetDBField('CreatedById'));
 					}
 				}
 			}
 		}
 
 		/**
 		 * Returns statuses of given categories
 		 *
 		 * @param Array $category_ids
 		 * @return Array
 		 */
 		function _getCategoryStatus($category_ids)
 		{
 			$id_field = $this->Application->getUnitOption($this->Prefix, 'IDField');
 			$table_name = $this->Application->getUnitOption($this->Prefix, 'TableName');
 
 			$sql = 'SELECT Status, ' . $id_field . '
 					FROM ' . $table_name . '
 					WHERE ' . $id_field . ' IN (' . implode(',', $category_ids) . ')';
 			return $this->Conn->GetCol($sql, $id_field);
 		}
 
 		/**
 		 * Creates a new item in temp table and
 		 * stores item id in App vars and Session on success
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnPreSaveCreated(&$event)
 		{
 			$object =& $event->getObject( Array ('skip_autoload' => true) );
 			/* @var $object CategoriesItem */
 
 			if ( $object->IsRoot() ) {
 				// don't create root category while saving permissions
 				return;
 			}
 
 			parent::OnPreSaveCreated($event);
 		}
 
 		/**
 		 * Deletes sym link to other category
 		 *
 		 * @param kEvent $event
 		 */
 		function OnAfterItemDelete(&$event)
 		{
 			parent::OnAfterItemDelete($event);
 
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			$sql = 'UPDATE '.$object->TableName.'
 					SET SymLinkCategoryId = NULL
 					WHERE SymLinkCategoryId = '.$object->GetID();
 
 			$this->Conn->Query($sql);
 		}
 
 		/**
 		 * Exclude root categories from deleting
 		 *
 		 * @param kEvent $event
 		 * @param string $type
 		 * @return void
 		 * @access protected
 		 */
 		protected function customProcessing(&$event, $type)
 		{
 			if ( $event->Name == 'OnMassDelete' && $type == 'before' ) {
 				$ids = $event->getEventParam('ids');
 				if ( !$ids || $this->Application->ConfigValue('AllowDeleteRootCats') ) {
 					return;
 				}
 
 				$root_categories = Array ();
 
 				// get module root categories and exclude them
 				foreach ($this->Application->ModuleInfo as $module_info) {
 					$root_categories[] = $module_info['RootCat'];
 				}
 
 				$root_categories = array_unique($root_categories);
 
 				if ( $root_categories && array_intersect($ids, $root_categories) ) {
 					$event->setEventParam('ids', array_diff($ids, $root_categories));
 					$this->Application->StoreVar('root_delete_error', 1);
 				}
 			}
 		}
 
 		/**
 		 * Checks, that given template exists (physically) in given theme
 		 *
 		 * @param string $template
 		 * @param int $theme_id
 		 * @return bool
 		 */
 		function _templateFound($template, $theme_id = null)
 		{
 			static $init_made = false;
 
 			if (!$init_made) {
 				$this->Application->InitParser(true);
 				$init_made = true;
 			}
 
 			if (!isset($theme_id)) {
 				$theme_id = $this->_getCurrentThemeId();
 			}
 
 			$theme_name = $this->_getThemeName($theme_id);
 
 			return $this->Application->TemplatesCache->TemplateExists('theme:' . $theme_name . '/' . $template);
 		}
 
 		/**
 		 * Removes ".tpl" in template path
 		 *
 		 * @param string $template
 		 * @return string
 		 */
 		function _stripTemplateExtension($template)
 		{
 	//		return preg_replace('/\.[^.\\\\\\/]*$/', '', $template);
 
 			return preg_replace('/^[\\/]{0,1}(.*)\.tpl$/', "$1", $template);
 		}
 
 		/**
 		 * Deletes all selected items.
 		 * Automatically recurse into sub-items using temp handler, and deletes sub-items
 		 * by calling its Delete method if sub-item has AutoDelete set to true in its config file
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnMassDelete(&$event)
 		{
 			if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
 				$event->status = kEvent::erFAIL;
 				return ;
 			}
 
 			$to_delete = Array ();
 			$ids = $this->StoreSelectedIDs($event);
 
 			if ( $recycle_bin = $this->Application->ConfigValue('RecycleBinFolder') ) {
 				$rb =& $this->Application->recallObject('c.recycle', null, Array ('skip_autoload' => true));
 				/* @var $rb CategoriesItem */
 
 				$rb->Load($recycle_bin);
 
 				$cat =& $event->getObject(Array ('skip_autoload' => true));
 				/* @var $cat CategoriesItem */
 
 				foreach ($ids as $id) {
 					$cat->Load($id);
 					if ( preg_match('/^' . preg_quote($rb->GetDBField('ParentPath'), '/') . '/', $cat->GetDBField('ParentPath')) ) {
 						$to_delete[] = $id;
 						continue;
 					}
 					$cat->SetDBField('ParentId', $recycle_bin);
 					$cat->Update();
 				}
 				$ids = $to_delete;
 				$event->redirect = 'categories/cache_updater';
 			}
 
 			$event->setEventParam('ids', $ids);
 			$this->customProcessing($event, 'before');
 			$ids = $event->getEventParam('ids');
 
 			if ( $ids ) {
 				$recursive_helper =& $this->Application->recallObject('RecursiveHelper');
 				/* @var $recursive_helper kRecursiveHelper */
 
 				foreach ($ids as $id) {
 					$recursive_helper->DeleteCategory($id, $event->Prefix);
 				}
 			}
 			$this->clearSelectedIDs($event);
 
 			$this->Application->StoreVar('RefreshStructureTree', 1);
 			$this->_resetMenuCache();
 		}
 
 		/**
 		 * Add selected items to clipboard with mode = COPY (CLONE)
 		 *
 		 * @param kEvent $event
 		 */
 		function OnCopy(&$event)
 		{
 			$this->Application->RemoveVar('clipboard');
 
 			$clipboard_helper =& $this->Application->recallObject('ClipboardHelper');
 			/* @var $clipboard_helper kClipboardHelper */
 
 			$clipboard_helper->setClipboard($event, 'copy', $this->StoreSelectedIDs($event));
 			$this->clearSelectedIDs($event);
 		}
 
 		/**
 		 * Add selected items to clipboard with mode = CUT
 		 *
 		 * @param kEvent $event
 		 */
 		function OnCut(&$event)
 		{
 			$this->Application->RemoveVar('clipboard');
 
 			$clipboard_helper =& $this->Application->recallObject('ClipboardHelper');
 			/* @var $clipboard_helper kClipboardHelper */
 
 			$clipboard_helper->setClipboard($event, 'cut', $this->StoreSelectedIDs($event));
 			$this->clearSelectedIDs($event);
 		}
 
 		/**
 		 * Controls all item paste operations. Can occur only with filled clipbord.
 		 *
 		 * @param kEvent $event
 		 */
 		function OnPasteClipboard(&$event)
 		{
 			$clipboard = unserialize( $this->Application->RecallVar('clipboard') );
 			foreach ($clipboard as $prefix => $clipboard_data) {
 				$paste_event = new kEvent($prefix.':OnPaste', Array('clipboard_data' => $clipboard_data));
 				$this->Application->HandleEvent($paste_event);
 
 				$event->copyFrom($paste_event);
 			}
 		}
 
 		/**
 		 * Checks permission for OnPaste event
 		 *
 		 * @param kEvent $event
 		 * @return bool
 		 */
 		function _checkPastePermission(&$event)
 		{
 			$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 			/* @var $perm_helper kPermissionsHelper */
 
 			$category_id = $this->Application->GetVar('m_cat_id');
 			if ($perm_helper->AddCheckPermission($category_id, $event->Prefix) == 0) {
 				// no items left for editing -> no permission
 				return $perm_helper->finalizePermissionCheck($event, false);
 			}
 
 			return true;
 		}
 
 		/**
 		 * Paste categories with sub-items from clipboard
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnPaste(&$event)
 		{
 			if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) || !$this->_checkPastePermission($event) ) {
 				$event->status = kEvent::erFAIL;
 				return;
 			}
 
 			$clipboard_data = $event->getEventParam('clipboard_data');
 
 			if ( !$clipboard_data['cut'] && !$clipboard_data['copy'] ) {
 				return;
 			}
 
 			// 1. get ParentId of moved category(-es) before it gets updated!!!)
 			$source_category_id = 0;
 			$id_field = $this->Application->getUnitOption($event->Prefix, 'IDField');
 			$table_name = $this->Application->getUnitOption($event->Prefix, 'TableName');
 
 			if ( $clipboard_data['cut'] ) {
 				$sql = 'SELECT ParentId
 						FROM ' . $table_name . '
 						WHERE ' . $id_field . ' = ' . $clipboard_data['cut'][0];
 				$source_category_id = $this->Conn->GetOne($sql);
 			}
 
 			$recursive_helper =& $this->Application->recallObject('RecursiveHelper');
 			/* @var $recursive_helper kRecursiveHelper */
 
 			if ( $clipboard_data['cut'] ) {
 				$recursive_helper->MoveCategories($clipboard_data['cut'], $this->Application->GetVar('m_cat_id'));
 			}
 
 			if ( $clipboard_data['copy'] ) {
 				// don't allow to copy/paste system OR theme-linked virtual pages
 
 				$sql = 'SELECT ' . $id_field . '
 						FROM ' . $table_name . '
 						WHERE ' . $id_field . ' IN (' . implode(',', $clipboard_data['copy']) . ') AND (`Type` = ' . PAGE_TYPE_VIRTUAL . ') AND (ThemeId = 0)';
 				$allowed_ids = $this->Conn->GetCol($sql);
 
 				if ( !$allowed_ids ) {
 					return;
 				}
 
 				foreach ($allowed_ids as $id) {
 					$recursive_helper->PasteCategory($id, $event->Prefix);
 				}
 			}
 
 			$priority_helper =& $this->Application->recallObject('PriorityHelper');
 			/* @var $priority_helper kPriorityHelper */
 
 			if ( $clipboard_data['cut'] ) {
 				$ids = $priority_helper->recalculatePriorities($event, 'ParentId = ' . $source_category_id);
 
 				if ( $ids ) {
 					$priority_helper->massUpdateChanged($event->Prefix, $ids);
 				}
 			}
 
 			// recalculate priorities of newly pasted categories in destination category
 			$parent_id = $this->Application->GetVar('m_cat_id');
 			$ids = $priority_helper->recalculatePriorities($event, 'ParentId = ' . $parent_id);
 
 			if ( $ids ) {
 				$priority_helper->massUpdateChanged($event->Prefix, $ids);
 			}
 
 			if ( $clipboard_data['cut'] || $clipboard_data['copy'] ) {
 				// rebuild with progress bar
 				if ( $this->Application->ConfigValue('QuickCategoryPermissionRebuild') ) {
 					$updater =& $this->Application->makeClass('kPermCacheUpdater');
 					/* @var $updater kPermCacheUpdater */
 
 					$updater->OneStepRun();
 				}
 				else {
 					$event->redirect = 'categories/cache_updater';
 				}
 
 				$this->_resetMenuCache();
 				$this->Application->StoreVar('RefreshStructureTree', 1);
 			}
 		}
 
 		/**
 		 * 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';
 
 				$object =& $this->Application->recallObject($event->Prefix.'.item', $event->Prefix, Array('skip_autoload' => true));
 
 				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->SetVar('m_cat_id', $saved_cat_id);
 			}
 		}*/
 
 		/**
 		 * Cleares clipboard content
 		 *
 		 * @param kEvent $event
 		 */
 		function OnClearClipboard(&$event)
 		{
 			$this->Application->RemoveVar('clipboard');
 		}
 
 		/**
 		 * Sets correct status for new categories created on front-end
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnBeforeItemCreate(&$event)
 		{
 			parent::OnBeforeItemCreate($event);
 
 			$this->_beforeItemChange($event);
 
 			if ( $this->Application->isAdminUser || $event->Prefix == 'st' ) {
 				// don't check category permissions when auto-creating structure pages
 				return ;
 			}
 
 			$perm_helper =& $this->Application->recallObject('PermissionsHelper');
 			/* @var $perm_helper kPermissionsHelper */
 
 			$new_status = false;
 			$category_id = $this->Application->GetVar('m_cat_id');
 
 			if ( $perm_helper->CheckPermission('CATEGORY.ADD', 0, $category_id) ) {
 				$new_status = STATUS_ACTIVE;
 			}
 			else {
 				if ( $perm_helper->CheckPermission('CATEGORY.ADD.PENDING', 0, $category_id) ) {
 					$new_status = STATUS_PENDING;
 				}
 			}
 
 			if ( $new_status ) {
 				$object =& $event->getObject();
 				/* @var $object kDBItem */
 
 				$object->SetDBField('Status', $new_status);
 
 				// don't forget to set Priority for suggested from Front-End categories
 				$min_priority = $this->_getNextPriority($object->GetDBField('ParentId'), $object->TableName);
 				$object->SetDBField('Priority', $min_priority);
 			}
 			else {
 				$event->status = kEvent::erPERM_FAIL;
 				return ;
 			}
 		}
 
 		/**
 		 * Returns next available priority for given category from given table
 		 *
 		 * @param int $category_id
 		 * @param string $table_name
 		 * @return int
 		 */
 		function _getNextPriority($category_id, $table_name)
 		{
 			$sql = 'SELECT MIN(Priority)
 					FROM ' . $table_name . '
 					WHERE ParentId = ' . $category_id;
 			return (int)$this->Conn->GetOne($sql) - 1;
 		}
 
 		/**
 		 * Sets correct status for new categories created on front-end
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnBeforeItemUpdate(&$event)
 		{
 			parent::OnBeforeItemUpdate($event);
 
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			if ( $object->GetChangedFields() ) {
 				$object->SetDBField('ModifiedById', $this->Application->RecallVar('user_id'));
 			}
 
 			$this->_beforeItemChange($event);
 		}
 
 		/**
 		 * Performs redirect to correct suggest confirmation template
 		 *
 		 * @param kEvent $event
 		 */
 		function OnCreate(&$event)
 		{
 			parent::OnCreate($event);
 
 			if ($this->Application->isAdminUser || $event->status != kEvent::erSUCCESS) {
 				// don't sent email or rebuild cache directly after category is created by admin
 				return ;
 			}
 
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			$cache_updater =& $this->Application->makeClass('kPermCacheUpdater', Array (null, $object->GetDBField('ParentPath')));
 			/* @var $cache_updater kPermCacheUpdater */
 
 			$cache_updater->OneStepRun();
 
 			$is_active = ($object->GetDBField('Status') == STATUS_ACTIVE);
 
 			$next_template = $is_active ? 'suggest_confirm_template' : 'suggest_pending_confirm_template';
 			$event->redirect = $this->Application->GetVar($next_template);
 			$event->SetRedirectParam('opener', 's');
 
 			// send email events
 			$perm_prefix = $this->Application->getUnitOption($event->Prefix, 'PermItemPrefix');
 
 			$event_suffix = $is_active ? 'ADD' : 'ADD.PENDING';
 			$this->Application->EmailEventAdmin($perm_prefix.'.'.$event_suffix);
 			$this->Application->EmailEventUser($perm_prefix.'.'.$event_suffix, $object->GetDBField('CreatedById'));
 		}
 
 		/**
 		 * Returns current per-page setting for list
 		 *
 		 * @param kEvent $event
 		 * @return int
 		 */
 		function getPerPage(&$event)
 		{
 			if (!$this->Application->isAdmin) {
 				$event->setEventParam('same_special', true);
 			}
 
 			return parent::getPerPage($event);
 		}
 
 		/**
 		 * Set's correct page for list
 		 * based on data provided with event
 		 *
 		 * @param kEvent $event
 		 * @access private
 		 * @see OnListBuild
 		 */
 		function SetPagination(&$event)
 		{
 			parent::SetPagination($event);
 
 			if ( !$this->Application->isAdmin ) {
 				$page_var = $event->getEventParam('page_var');
 
 				if ( $page_var !== false ) {
 					$page = $this->Application->GetVar($page_var);
 
 					if ( is_numeric($page) ) {
 						$object =& $event->getObject();
 						/* @var $object kDBList */
 
 						$object->SetPage($page);
 					}
 				}
 			}
 		}
 
 		/**
 		 * Apply same processing to each item being selected in grid
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function iterateItems(&$event)
 		{
 			if ( $event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline' ) {
 				parent::iterateItems($event);
 			}
 
 			if ( $this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1) ) {
 				$event->status = kEvent::erFAIL;
 				return;
 			}
 
 			$object =& $event->getObject(Array ('skip_autoload' => true));
 			/* @var $object CategoriesItem */
 
 			$ids = $this->StoreSelectedIDs($event);
 
 			if ( $ids ) {
 				$propagate_category_status = $this->Application->GetVar('propagate_category_status');
 				$status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') );
 
 				foreach ($ids as $id) {
 					$object->Load($id);
 					$object->SetDBField($status_field, $event->Name == 'OnMassApprove' ? 1 : 0);
 
 					if ( $object->Update() ) {
 						if ( $propagate_category_status ) {
 							$sql = 'UPDATE ' . $object->TableName . '
 									SET ' . $status_field . ' = ' . $object->GetDBField($status_field) . '
 									WHERE TreeLeft BETWEEN ' . $object->GetDBField('TreeLeft') . ' AND ' . $object->GetDBField('TreeRight');
 							$this->Conn->Query($sql);
 						}
 
 						$event->status = kEvent::erSUCCESS;
 
 						$email_event = $event->Name == 'OnMassApprove' ? 'CATEGORY.APPROVE' : 'CATEGORY.DENY';
 						$this->Application->EmailEventUser($email_event, $object->GetDBField('CreatedById'));
 					}
 					else {
 						$event->status = kEvent::erFAIL;
 						$event->redirect = false;
 						break;
 					}
 				}
 			}
 
 			$this->clearSelectedIDs($event);
 			$this->Application->StoreVar('RefreshStructureTree', 1);
 		}
 
 		/**
 		 * Checks, that currently loaded item is allowed for viewing (non permission-based)
 		 *
 		 * @param kEvent $event
 		 * @return bool
 		 */
 		function checkItemStatus(&$event)
 		{
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			if ( !$object->isLoaded() ) {
 				return true;
 			}
 
 			if ( $object->GetDBField('Status') != STATUS_ACTIVE && $object->GetDBField('Status') != 4 ) {
 				if ( !$object->GetDBField('DirectLinkEnabled') || !$object->GetDBField('DirectLinkAuthKey') ) {
 					return false;
 				}
 
 				return $this->Application->GetVar('authkey') == $object->GetDBField('DirectLinkAuthKey');
 			}
 
 			return true;
 		}
 
 		// ============= for cms page processing =======================
 
 		/**
 		 * Returns default design template
 		 *
 		 * @return string
 		 */
 		function _getDefaultDesign()
 		{
 			$default_design = trim($this->Application->ConfigValue('cms_DefaultDesign'), '/');
 
 			if (!$default_design) {
 				// theme-based alias for default design
 				return '#default_design#';
 			}
 
 			if (strpos($default_design, '#') === false) {
 				// real template, not alias, so prefix with "/"
 				return '/' . $default_design;
 			}
 
 			// alias
 			return $default_design;
 		}
 
 		/**
 		 * Returns default design based on given virtual template (used from kApplication::Run)
 		 *
 		 * @param string $t
 		 * @return string
 		 * @access public
 		 */
 		public function GetDesignTemplate($t = null)
 		{
 			if ( !isset($t) ) {
 				$t = $this->Application->GetVar('t');
 			}
 
 			$page =& $this->Application->recallObject($this->Prefix . '.-virtual', null, Array ('page' => $t));
 			/* @var $page CategoriesItem */
 
 			if ( $page->isLoaded() ) {
 				$real_t = $page->GetDBField('CachedTemplate');
 				$this->Application->SetVar('m_cat_id', $page->GetDBField('CategoryId'));
 
 				if ( $page->GetDBField('FormId') ) {
 					$this->Application->SetVar('form_id', $page->GetDBField('FormId'));
 				}
 			}
 			else {
 				$not_found = $this->Application->ConfigValue('ErrorTemplate');
 				$real_t = $not_found ? $not_found : 'error_notfound';
 
 				$themes_helper =& $this->Application->recallObject('ThemesHelper');
 				/* @var $themes_helper kThemesHelper */
 
 				$theme_id = $this->Application->GetVar('m_theme');
 				$category_id = $themes_helper->getPageByTemplate($real_t, $theme_id);
 				$this->Application->SetVar('m_cat_id', $category_id);
 
 				header('HTTP/1.0 404 Not Found');
 			}
 
 			// replace alias in form #alias_name# to actual template used in this theme
 			$theme =& $this->Application->recallObject('theme.current');
 			/* @var $theme kDBItem */
 
 			$template = $theme->GetField('TemplateAliases', $real_t);
 
 			if ( $template ) {
 				return $template;
 			}
 
 			return $real_t;
 		}
 
 		/**
 		 * Sets category id based on found template (used from kApplication::Run)
 		 *
 		 * @deprecated
 		 */
 		/*function SetCatByTemplate()
 		{
 			$t = $this->Application->GetVar('t');
 			$page =& $this->Application->recallObject($this->Prefix . '.-virtual');
 
 			if ($page->isLoaded()) {
 				$this->Application->SetVar('m_cat_id', $page->GetDBField('CategoryId') );
 			}
 		}*/
 
 		/**
 		 * Prepares template paths
 		 *
 		 * @param kEvent $event
 		 */
 		function _beforeItemChange(&$event)
 		{
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			$now = adodb_mktime();
 
 			if ( !$this->Application->isDebugMode() && strpos($event->Special, 'rebuild') === false ) {
 				$object->SetDBField('Type', $object->GetOriginalField('Type'));
 				$object->SetDBField('Protected', $object->GetOriginalField('Protected'));
 
 				if ( $object->GetDBField('Protected') ) {
 					// some fields are read-only for protected pages, when debug mode is off
 					$object->SetDBField('AutomaticFilename', $object->GetOriginalField('AutomaticFilename'));
 					$object->SetDBField('Filename', $object->GetOriginalField('Filename'));
 					$object->SetDBField('Status', $object->GetOriginalField('Status'));
 				}
 			}
 
 			if ($object->GetChangedFields()) {
 				$object->SetDBField('Modified_date', $now);
 				$object->SetDBField('Modified_time', $now);
 			}
 
 			$object->setRequired('PageCacheKey', $object->GetDBField('OverridePageCacheKey'));
 			$object->SetDBField('Template', $this->_stripTemplateExtension( $object->GetDBField('Template') ));
 
 			if ($object->GetDBField('Type') == PAGE_TYPE_TEMPLATE) {
 				if (!$this->_templateFound($object->GetDBField('Template'), $object->GetDBField('ThemeId'))) {
 					$object->SetError('Template', 'template_file_missing', 'la_error_TemplateFileMissing');
 				}
 			}
 
 			$this->_saveTitleField($object, 'Title');
 			$this->_saveTitleField($object, 'MenuTitle');
 
 			$root_category = $this->Application->getBaseCategory();
 
 			if ( file_exists(FULL_PATH . '/themes') && ($object->GetDBField('ParentId') == $root_category) && ($object->GetDBField('Template') == CATEGORY_TEMPLATE_INHERIT) ) {
 				// there are themes + creating top level category
 				$object->SetError('Template', 'no_inherit');
 			}
 
 			if ( !$this->Application->isAdminUser && $object->isVirtualField('cust_RssSource') ) {
 				// only administrator can set/change "cust_RssSource" field
 
 				if ($object->GetDBField('cust_RssSource') != $object->GetOriginalField('cust_RssSource')) {
 					$object->SetError('cust_RssSource', 'not_allowed', 'la_error_OperationNotAllowed');
 				}
 			}
 
 			if ( !$object->GetDBField('DirectLinkAuthKey') ) {
 				$key_parts = Array (
 					$object->GetID(),
 					$object->GetDBField('ParentId'),
 					$object->GetField('Name'),
 					'b38'
 				);
 
 				$object->SetDBField('DirectLinkAuthKey', substr( md5( implode(':', $key_parts) ), 0, 20 ));
 			}
 		}
 
 		/**
 		 * Sets page name to requested field in case when:
 		 * 1. page was auto created (through theme file rebuld)
 		 * 2. requested field is emtpy
 		 *
 		 * @param kDBItem $object
 		 * @param string $field
 		 * @author Alex
 		 */
 		function _saveTitleField(&$object, $field)
 		{
 			$value = $object->GetField($field, 'no_default'); // current value of target field
 
 			$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
 			/* @var $ml_formatter kMultiLanguage */
 
 			$src_field = $ml_formatter->LangFieldName('Name');
 			$dst_field = $ml_formatter->LangFieldName($field);
 
 			$dst_field_not_changed = $object->GetOriginalField($dst_field) == $value;
 
 			if ($value == '' || preg_match('/^_Auto: (.*)/', $value) || (($object->GetOriginalField($src_field) == $value) && $dst_field_not_changed)) {
 				// target field is empty OR target field value starts with "_Auto: " OR (source field value
 				// before change was equals to current target field value AND target field value wasn't changed)
 				$object->SetField($dst_field, $object->GetField($src_field));
 			}
 		}
 
 		/**
 		 * Don't allow to delete system pages, when not in debug mode
 		 *
 		 * @param kEvent $event
 		 */
 		function OnBeforeItemDelete(&$event)
 		{
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			if ( $object->GetDBField('Protected') && !$this->Application->isDebugMode() ) {
 				$event->status = kEvent::erFAIL;
 			}
 		}
 
 		/**
 		 * Creates category based on given TPL file
 		 *
 		 * @param CategoriesItem $object
 		 * @param string $template
 		 * @param int $theme_id
 		 * @param int $system_mode
 		 * @param array $template_info
 		 * @return bool
 		 */
 		function _prepareAutoPage(&$object, $template, $theme_id = null, $system_mode = SMS_MODE_AUTO, $template_info = Array ())
 		{
 			$template = $this->_stripTemplateExtension($template);
 
 			if ($system_mode == SMS_MODE_AUTO) {
 				$page_type = $this->_templateFound($template, $theme_id) ? PAGE_TYPE_TEMPLATE : PAGE_TYPE_VIRTUAL;
 			}
 			else {
 				$page_type = $system_mode == SMS_MODE_FORCE ? PAGE_TYPE_TEMPLATE : PAGE_TYPE_VIRTUAL;
 			}
 
 			if (($page_type == PAGE_TYPE_TEMPLATE) && ($template_info === false)) {
 				// do not autocreate system pages, when browsing through site
 				return false;
 			}
 
 			if (!isset($theme_id)) {
 				$theme_id = $this->_getCurrentThemeId();
 			}
 
 			$root_category = $this->Application->getBaseCategory();
 			$page_category = $this->Application->GetVar('m_cat_id');
 			if (!$page_category) {
 				$page_category = $root_category;
 				$this->Application->SetVar('m_cat_id', $page_category);
 			}
 
 			if (($page_type == PAGE_TYPE_VIRTUAL) && (strpos($template, '/') !== false)) {
 				// virtual page, but have "/" in template path -> create it's path
 				$category_path = explode('/', $template);
 				$template = array_pop($category_path);
 
 				$page_category = $this->_getParentCategoryFromPath($category_path, $root_category, $theme_id);
 			}
 
 			$page_name = ($page_type == PAGE_TYPE_TEMPLATE) ? '_Auto: ' . $template : $template;
 			$page_description = '';
 
 			if ($page_type == PAGE_TYPE_TEMPLATE) {
 				$design_template = strtolower($template); // leading "/" not added !
 				if ($template_info) {
 					if (array_key_exists('name', $template_info) && $template_info['name']) {
 						$page_name = $template_info['name'];
 					}
 
 					if (array_key_exists('desc', $template_info) && $template_info['desc']) {
 						$page_description = $template_info['desc'];
 					}
 
 					if (array_key_exists('section', $template_info) && $template_info['section']) {
 						// this will override any global "m_cat_id"
 						$page_category = $this->_getParentCategoryFromPath(explode('||', $template_info['section']), $root_category, $theme_id);
 					}
 				}
 			}
 			else {
 				$design_template = $this->_getDefaultDesign(); // leading "/" added !
 			}
 
 			$object->Clear();
 			$object->SetDBField('ParentId', $page_category);
 			$object->SetDBField('Type', $page_type);
 			$object->SetDBField('Protected', 1); // $page_type == PAGE_TYPE_TEMPLATE
 
 			$object->SetDBField('IsMenu', 0);
 			$object->SetDBField('ThemeId', $theme_id);
 
 			// put all templates to then end of list (in their category)
 			$min_priority = $this->_getNextPriority($page_category, $object->TableName);
 			$object->SetDBField('Priority', $min_priority);
 
 			$object->SetDBField('Template', $design_template);
 			$object->SetDBField('CachedTemplate', $design_template);
 
 			$primary_language = $this->Application->GetDefaultLanguageId();
 			$current_language = $this->Application->GetVar('m_lang');
 			$object->SetDBField('l' . $primary_language . '_Name', $page_name);
 			$object->SetDBField('l' . $current_language . '_Name', $page_name);
 			$object->SetDBField('l' . $primary_language . '_Description', $page_description);
 			$object->SetDBField('l' . $current_language . '_Description', $page_description);
 
 			return $object->Create();
 		}
 
 		function _getParentCategoryFromPath($category_path, $base_category, $theme_id = null)
 		{
 			static $category_ids = Array ();
 
 			if (!$category_path) {
 				return $base_category;
 			}
 
 			if (array_key_exists(implode('||', $category_path), $category_ids)) {
 				return $category_ids[ implode('||', $category_path) ];
 			}
 
 			$backup_category_id = $this->Application->GetVar('m_cat_id');
 
 			$object =& $this->Application->recallObject($this->Prefix . '.rebuild-path', null, Array ('skip_autoload' => true));
 			/* @var $object kDBItem */
 
 			$parent_id = $base_category;
 
 			$filenames_helper =& $this->Application->recallObject('FilenamesHelper');
 			/* @var $filenames_helper kFilenamesHelper */
 
 			$safe_category_path = array_map(Array (&$filenames_helper, 'replaceSequences'), $category_path);
 
 			foreach ($category_path as $category_order => $category_name) {
 				$this->Application->SetVar('m_cat_id', $parent_id);
 
 				// get virtual category first, when possible
 				$sql = 'SELECT ' . $object->IDField . '
 						FROM ' . $object->TableName . '
 						WHERE
 							(
 								Filename = ' . $this->Conn->qstr($safe_category_path[$category_order]) . ' OR
 								Filename = ' . $this->Conn->qstr( $filenames_helper->replaceSequences('_Auto: ' . $category_name) ) . '
 							) AND
 							(ParentId = ' . $parent_id . ') AND
 							(ThemeId = 0 OR ThemeId = ' . $theme_id . ')
 						ORDER BY ThemeId ASC';
 				$parent_id = $this->Conn->GetOne($sql);
 
 				if ($parent_id === false) {
 					// page not found
 					$template = implode('/', array_slice($safe_category_path, 0, $category_order + 1));
 
 					// don't process system templates in sub-categories
 					$system = $this->_templateFound($template, $theme_id) && (strpos($template, '/') === false);
 
 					if (!$this->_prepareAutoPage($object, $category_name, $theme_id, $system ? SMS_MODE_FORCE : false)) {
 						// page was not created
 						break;
 					}
 
 					$parent_id = $object->GetID();
 				}
 			}
 
 			$this->Application->SetVar('m_cat_id', $backup_category_id);
 			$category_ids[ implode('||', $category_path) ] = $parent_id;
 
 			return $parent_id;
 		}
 
 		/**
 		 * Returns theme name by it's id. Used in structure page creation.
 		 *
 		 * @param int $theme_id
 		 * @return string
 		 */
 		function _getThemeName($theme_id)
 		{
 			static $themes = null;
 
 			if (!isset($themes)) {
 				$id_field = $this->Application->getUnitOption('theme', 'IDField');
 				$table_name = $this->Application->getUnitOption('theme', 'TableName');
 
 				$sql = 'SELECT Name, ' . $id_field . '
 						FROM ' . $table_name . '
 						WHERE Enabled = 1';
 				$themes = $this->Conn->GetCol($sql, $id_field);
 			}
 
 			return array_key_exists($theme_id, $themes) ? $themes[$theme_id] : false;
 		}
 
 		/**
 		 * Resets SMS-menu cache
 		 *
 		 * @param kEvent $event
 		 */
 		function OnResetCMSMenuCache(&$event)
 		{
 			if ($this->Application->GetVar('ajax') == 'yes') {
 				$event->status = kEvent::erSTOP;
 			}
 
 			$this->_resetMenuCache();
 			$event->SetRedirectParam('action_completed', 1);
 		}
 
 		function _resetMenuCache()
 		{
 			// reset cms menu cache (all variables are automatically rebuild, when missing)
 			if ($this->Application->isCachingType(CACHING_TYPE_MEMORY)) {
 				$this->Application->rebuildCache('master:cms_menu', kCache::REBUILD_LATER, CacheSettings::$cmsMenuRebuildTime);
 				$this->Application->rebuildCache('master:StructureTree', kCache::REBUILD_LATER, CacheSettings::$structureTreeRebuildTime);
 				$this->Application->rebuildCache('master:template_mapping', kCache::REBUILD_LATER, CacheSettings::$templateMappingRebuildTime);
 			}
 			else {
 				$this->Application->rebuildDBCache('cms_menu', kCache::REBUILD_LATER, CacheSettings::$cmsMenuRebuildTime);
 				$this->Application->rebuildDBCache('StructureTree', kCache::REBUILD_LATER, CacheSettings::$structureTreeRebuildTime);
 				$this->Application->rebuildDBCache('template_mapping', kCache::REBUILD_LATER, CacheSettings::$templateMappingRebuildTime);
 			}
 		}
 
 		/**
 		 * Updates structure config
 		 *
 		 * @param kEvent $event
 		 */
 		function OnAfterConfigRead(&$event)
 		{
 			parent::OnAfterConfigRead($event);
 
 			if (defined('IS_INSTALL') && IS_INSTALL) {
 				// skip any processing, because Category table doesn't exists until install is finished
 				return ;
 			}
 
 			$site_config_helper =& $this->Application->recallObject('SiteConfigHelper');
 			/* @var $site_config_helper SiteConfigHelper */
 
 			$settings = $site_config_helper->getSettings();
 
 			$root_category = $this->Application->getBaseCategory();
 
 			// set root category
 			$section_ajustments = $this->Application->getUnitOption($event->Prefix, 'SectionAdjustments');
 
 			$section_ajustments['in-portal:browse'] = Array (
 				'url' => Array ('m_cat_id' => $root_category),
 				'late_load' => Array ('m_cat_id' => $root_category),
 				'onclick' => 'checkCatalog(' . $root_category . ')',
 			);
 
 			$section_ajustments['in-portal:browse_site'] = Array (
 				'url' => Array ('editing_mode' => $settings['default_editing_mode']),
 			);
 
 			$this->Application->setUnitOption($event->Prefix, 'SectionAdjustments', $section_ajustments);
 
 			// prepare structure dropdown
 			$category_helper =& $this->Application->recallObject('CategoryHelper');
 			/* @var $category_helper CategoryHelper */
 
 			$fields = $this->Application->getUnitOption($event->Prefix, 'Fields');
 
 			$fields['ParentId']['default'] = (int)$this->Application->GetVar('m_cat_id');
 			$fields['ParentId']['options'] = $category_helper->getStructureTreeAsOptions();
 
 			// limit design list by theme
 			$design_folders = Array ('tf.FilePath = "/designs"', 'tf.FilePath = "/platform/designs"');
 			foreach ($this->Application->ModuleInfo as $module_name => $module_info) {
 				$design_folders[] = 'tf.FilePath = "/' . $module_info['TemplatePath'] . 'designs"';
 			}
 			$design_folders = array_unique($design_folders);
 
 			$theme_id = $this->_getCurrentThemeId();
 			$design_sql = $fields['Template']['options_sql'];
 			$design_sql = str_replace('(tf.FilePath = "/designs")', '(' . implode(' OR ', $design_folders) . ')' . ' AND (t.ThemeId = ' . $theme_id . ')', $design_sql);
 			$fields['Template']['options_sql'] = $design_sql;
 
 			// adds "Inherit From Parent" option to "Template" field
 			$fields['Template']['options'] = Array (CATEGORY_TEMPLATE_INHERIT => $this->Application->Phrase('la_opt_InheritFromParent'));
 
 			$this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
 
 			if ($this->Application->isAdmin) {
 				// don't sort by Front-End sorting fields
 				$config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
 				$remove_keys = Array ('DefaultSorting1Field', 'DefaultSorting2Field', 'DefaultSorting1Dir', 'DefaultSorting2Dir');
 				foreach ($remove_keys as $remove_key) {
 					unset($config_mapping[$remove_key]);
 				}
 				$this->Application->setUnitOption($event->Prefix, 'ConfigMapping', $config_mapping);
 			}
 			else {
 				// sort by parent path on Front-End only
 				$list_sortings = $this->Application->getUnitOption($event->Prefix, 'ListSortings', Array ());
 				$list_sortings['']['ForcedSorting'] = Array ("CurrentSort" => 'asc');
 				$this->Application->setUnitOption($event->Prefix, 'ListSortings', $list_sortings);
 			}
 
 			// add grids for advanced view (with primary category column)
 			$grids = $this->Application->getUnitOption($this->Prefix, 'Grids');
 			$process_grids = Array ('Default', 'Radio');
 			foreach ($process_grids as $process_grid) {
 				$grid_data = $grids[$process_grid];
 				$grid_data['Fields']['CachedNavbar'] = Array ('title' => 'la_col_Path', 'data_block' => 'grid_parent_category_td', 'filter_block' => 'grid_like_filter');
 				$grids[$process_grid . 'ShowAll'] = $grid_data;
 			}
 			$this->Application->setUnitOption($this->Prefix, 'Grids', $grids);
 		}
 
 		/**
 		 * Removes this item and it's children (recursive) from structure dropdown
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function OnAfterItemLoad(&$event)
 		{
 			parent::OnAfterItemLoad($event);
 
 			if ( !$this->Application->isAdmin ) {
 				// calculate priorities dropdown only for admin
 				return;
 			}
 
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			// remove this category & it's children from dropdown
 			$sql = 'SELECT ' . $object->IDField . '
 					FROM ' . $this->Application->getUnitOption($event->Prefix, 'TableName') . '
 					WHERE ParentPath LIKE "' . $object->GetDBField('ParentPath') . '%"';
 			$remove_categories = $this->Conn->GetCol($sql);
 
 			$options = $object->GetFieldOption('ParentId', 'options');
 			foreach ($remove_categories as $remove_category) {
 				unset($options[$remove_category]);
 			}
 			$object->SetFieldOption('ParentId', 'options', $options);
 		}
 
 		/**
 		 * Enter description here...
 		 *
 		 * @param kEvent $event
 		 */
 		function OnAfterRebuildThemes(&$event)
 		{
 			$sql = 'SELECT t.ThemeId, CONCAT( tf.FilePath, \'/\', tf.FileName ) AS Path, tf.FileMetaInfo
 					FROM '.TABLE_PREFIX.'ThemeFiles AS tf
 					LEFT JOIN '.TABLE_PREFIX.'Theme AS t ON t.ThemeId = tf.ThemeId
 					WHERE t.Enabled = 1 AND tf.FileType = 1
 					AND (
 						SELECT COUNT(CategoryId)
 						FROM ' . TABLE_PREFIX . 'Category c
 						WHERE CONCAT(\'/\', c.Template, \'.tpl\') = CONCAT( tf.FilePath, \'/\', tf.FileName ) AND (c.ThemeId = t.ThemeId)
 					) = 0 ';
 			$files = $this->Conn->Query($sql, 'Path');
 			if (!$files) {
 				// all possible pages are already created
 				return ;
 			}
 
 			set_time_limit(0);
 			ini_set('memory_limit', -1);
 
 			$dummy =& $this->Application->recallObject($event->Prefix . '.rebuild', null, Array ('skip_autoload' => true));
 			/* @var $dummy kDBItem */
 
 			$error_count = 0;
 			foreach ($files as $a_file => $file_info) {
 				$status = $this->_prepareAutoPage($dummy, $a_file, $file_info['ThemeId'], SMS_MODE_FORCE, unserialize($file_info['FileMetaInfo'])); // create system page
 				if (!$status) {
 					$error_count++;
 				}
 			}
 
 			if ($this->Application->ConfigValue('QuickCategoryPermissionRebuild')) {
 				$updater =& $this->Application->makeClass('kPermCacheUpdater');
 				/* @var $updater kPermCacheUpdater */
 
 				$updater->OneStepRun();
 			}
 
 			$this->_resetMenuCache();
 
 			if ($error_count) {
 				// allow user to review error after structure page creation
 				$event->MasterEvent->redirect = false;
 			}
 		}
 
 		/**
 		 * Processes OnMassMoveUp, OnMassMoveDown events
 		 *
 		 * @param kEvent $event
 		 */
 		function OnChangePriority(&$event)
 		{
 			$this->Application->SetVar('priority_prefix', $event->getPrefixSpecial());
 			$event->CallSubEvent('priority:' . $event->Name);
 
 			$this->Application->StoreVar('RefreshStructureTree', 1);
 			$this->_resetMenuCache();
 		}
 
 		/**
 		 * Completely recalculates priorities in current category
 		 *
 		 * @param kEvent $event
 		 */
 		function OnRecalculatePriorities(&$event)
 		{
 			if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
 				$event->status = kEvent::erFAIL;
 				return;
 			}
 
 			$this->Application->SetVar('priority_prefix', $event->getPrefixSpecial());
 			$event->CallSubEvent('priority:' . $event->Name);
 
 			$this->_resetMenuCache();
 		}
 
 		/**
 		 * Update Preview Block for FCKEditor
 		 *
 		 * @param kEvent $event
 		 */
 		function OnUpdatePreviewBlock(&$event)
 		{
 			$event->status = kEvent::erSTOP;
 			$string = kUtil::unhtmlentities($this->Application->GetVar('preview_content'));
 
 			$category_helper =& $this->Application->recallObject('CategoryHelper');
 			/* @var $category_helper CategoryHelper */
 
 			$string = $category_helper->replacePageIds($string);
 
 			$this->Application->StoreVar('_editor_preview_content_', $string);
 		}
 
 		/**
 		 * Makes simple search for categories
 		 * based on keywords string
 		 *
 		 * @param kEvent $event
 		 */
 		function OnSimpleSearch(&$event)
 		{
 			$event->redirect = false;
 			$search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search';
 
 			$keywords = kUtil::unhtmlentities( trim($this->Application->GetVar('keywords')) );
 
 			$query_object =& $this->Application->recallObject('HTTPQuery');
 			/* @var $query_object kHTTPQuery */
 
 			$sql = 'SHOW TABLES LIKE "'.$search_table.'"';
 
 			if ( !isset($query_object->Get['keywords']) && !isset($query_object->Post['keywords']) && $this->Conn->Query($sql) ) {
 				// used when navigating by pages or changing sorting in search results
 				return;
 			}
 
 			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);
 
 			$this->saveToSearchLog($keywords, 0); // 0 - simple search, 1 - advanced search
 
 			$keywords = strtr($keywords, Array('%' => '\\%', '_' => '\\_'));
 
 			$event->setPseudoClass('_List');
 
 			$object =& $event->getObject();
 			/* @var $object kDBList */
 
 			$this->Application->SetVar($event->getPrefixSpecial().'_Page', 1);
 			$lang = $this->Application->GetVar('m_lang');
 			$items_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
 			$module_name = 'In-Portal';
 
 			$sql = 'SELECT *
 					FROM ' . $this->Application->getUnitOption('confs', 'TableName') . '
 					WHERE ModuleName = ' . $this->Conn->qstr($module_name) . ' AND SimpleSearch = 1';
 			$search_config = $this->Conn->Query($sql, 'FieldName');
 
 			$field_list = array_keys($search_config);
 
 			$join_clauses = Array();
 
 			// field processing
 			$weight_sum = 0;
 
 			$alias_counter = 0;
 
 			$custom_fields = $this->Application->getUnitOption($event->Prefix, 'CustomFields');
 			if ($custom_fields) {
 				$custom_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName');
 				$join_clauses[] = '	LEFT JOIN '.$custom_table.' custom_data ON '.$items_table.'.ResourceId = custom_data.ResourceId';
 			}
 
 			// what field in search config becomes what field in sql (key - new field, value - old field (from searchconfig table))
 			$search_config_map = Array();
 
 			foreach ($field_list as $key => $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 ( $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage' ) {
+				if ( !$search_config[$field]['CustomFieldId'] && $object->GetFieldOption($field, 'formatter') == 'kMultiLanguage' ) {
 					$field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field;
 					$field_list[$key] = 'l'.$lang.'_'.$field;
 
 					if (!isset($search_config[$field]['ForeignField'])) {
 						$field_list[$key.'_primary'] = $local_table.'.'.$field_list[$key.'_primary'];
 						$search_config_map[ $field_list[$key.'_primary'] ] = $field;
 					}
 				}
 
 				// processing fields from other tables
 				if ($foreign_field = $search_config[$field]['ForeignField']) {
 					$exploded = explode(':', $foreign_field, 2);
 					if ($exploded[0] == 'CALC') {
 						// ignoring having type clauses in simple search
 						unset($field_list[$key]);
 						continue;
 					}
 					else {
 						$multi_lingual = false;
 						if ($exploded[0] == 'MULTI') {
 							$multi_lingual = true;
 							$foreign_field = $exploded[1];
 						}
 
 						$exploded = explode('.', $foreign_field);	// format: table.field_name
 						$foreign_table = TABLE_PREFIX.$exploded[0];
 
 						$alias_counter++;
 						$alias = 't'.$alias_counter;
 
 						if ($multi_lingual) {
 							$field_list[$key] = $alias.'.'.'l'.$lang.'_'.$exploded[1];
 							$field_list[$key.'_primary'] = 'l'.$this->Application->GetDefaultLanguageId().'_'.$field;
 							$search_config_map[ $field_list[$key] ] = $field;
 							$search_config_map[ $field_list[$key.'_primary'] ] = $field;
 						}
 						else {
 							$field_list[$key] = $alias.'.'.$exploded[1];
 							$search_config_map[ $field_list[$key] ] = $field;
 						}
 
 						$join_clause = str_replace('{ForeignTable}', $alias, $search_config[$field]['JoinClause']);
 						$join_clause = str_replace('{LocalTable}', $items_table, $join_clause);
 
 						$join_clauses[] = '	LEFT JOIN '.$foreign_table.' '.$alias.'
 											ON '.$join_clause;
 					}
 				}
 				else {
 					// processing fields from local table
 					if ($search_config[$field]['CustomFieldId']) {
 						$local_table = 'custom_data';
 
 						// search by custom field value on current language
 						$custom_field_id = array_search($field_list[$key], $custom_fields);
 						$field_list[$key] = 'l'.$lang.'_cust_'.$custom_field_id;
 
 						// search by custom field value on primary language
 						$field_list[$key.'_primary'] = $local_table.'.l'.$this->Application->GetDefaultLanguageId().'_cust_'.$custom_field_id;
 						$search_config_map[ $field_list[$key.'_primary'] ] = $field;
 					}
 
 					$field_list[$key] = $local_table.'.'.$field_list[$key];
 					$search_config_map[ $field_list[$key] ] = $field;
 				}
 			}
 
 			// keyword string processing
 			$search_helper =& $this->Application->recallObject('SearchHelper');
 			/* @var $search_helper kSearchHelper */
 
 			$where_clause = Array ();
 			foreach ($field_list as $field) {
 				if (preg_match('/^' . preg_quote($items_table, '/') . '\.(.*)/', $field, $regs)) {
 					// local real field
 					$filter_data = $search_helper->getSearchClause($object, $regs[1], $keywords, false);
 					if ($filter_data) {
 						$where_clause[] = $filter_data['value'];
 					}
 				}
 				elseif (preg_match('/^custom_data\.(.*)/', $field, $regs)) {
 					$custom_field_name = 'cust_' . $search_config_map[$field];
 					$filter_data = $search_helper->getSearchClause($object, $custom_field_name, $keywords, false);
 					if ($filter_data) {
 						$where_clause[] = str_replace('`' . $custom_field_name . '`', $field, $filter_data['value']);
 					}
 				}
 				else {
 					$where_clause[] = $search_helper->buildWhereClause($keywords, Array ($field));
 				}
 			}
 
 			$where_clause = '((' . implode(') OR (', $where_clause) . '))'; // 2 braces for next clauses, see below!
 
 			$where_clause = $where_clause . ' AND (' . $items_table . '.Status = ' . STATUS_ACTIVE . ')';
 
 			if ($event->MasterEvent && $event->MasterEvent->Name == 'OnListBuild') {
 				if ($event->MasterEvent->getEventParam('ResultIds')) {
 					$where_clause .= ' AND '.$items_table.'.ResourceId IN ('.implode(',', $event->MasterEvent->getEventParam('ResultIds')).')';
 				}
 			}
 
 			// exclude template based sections from search results (ie. registration)
 			if ( $this->Application->ConfigValue('ExcludeTemplateSectionsFromSearch') ) {
 				$where_clause .= ' AND ' . $items_table . '.ThemeId = 0';
 			}
 
 			// making relevance clause
 			$positive_words = $search_helper->getPositiveKeywords($keywords);
 			$this->Application->StoreVar('highlight_keywords', serialize($positive_words));
 			$revelance_parts = Array();
 			reset($search_config);
 
 			foreach ($positive_words as $keyword_index => $positive_word) {
 				$positive_word = $search_helper->transformWildcards($positive_word);
 				$positive_words[$keyword_index] = $this->Conn->escape($positive_word);
 			}
 
 			foreach ($field_list as $field) {
 
 				if (!array_key_exists($field, $search_config_map)) {
 					$map_key = $search_config_map[$items_table . '.' . $field];
 				}
 				else {
 					$map_key = $search_config_map[$field];
 				}
 
 				$config_elem = $search_config[ $map_key ];
 				$weight = $config_elem['Priority'];
 
 				// search by whole words only ([[:<:]] - word boundary)
 				/*$revelance_parts[] = 'IF('.$field.' REGEXP "[[:<:]]('.implode(' ', $positive_words).')[[:>:]]", '.$weight.', 0)';
 				foreach ($positive_words as $keyword) {
 					$revelance_parts[] = 'IF('.$field.' REGEXP "[[:<:]]('.$keyword.')[[:>:]]", '.$weight.', 0)';
 				}*/
 
 				// search by partial word matches too
 				$revelance_parts[] = 'IF('.$field.' LIKE "%'.implode(' ', $positive_words).'%", '.$weight_sum.', 0)';
 				foreach ($positive_words as $keyword) {
 					$revelance_parts[] = 'IF('.$field.' LIKE "%'.$keyword.'%", '.$weight.', 0)';
 				}
 			}
 
 			$revelance_parts = array_unique($revelance_parts);
 
 			$conf_postfix = $this->Application->getUnitOption($event->Prefix, 'SearchConfigPostfix');
 			$rel_keywords	= $this->Application->ConfigValue('SearchRel_Keyword_'.$conf_postfix)	/ 100;
 			$rel_pop		= $this->Application->ConfigValue('SearchRel_Pop_'.$conf_postfix)		/ 100;
 			$rel_rating		= $this->Application->ConfigValue('SearchRel_Rating_'.$conf_postfix)	/ 100;
 			$relevance_clause = '('.implode(' + ', $revelance_parts).') / '.$weight_sum.' * '.$rel_keywords;
 			if ($rel_pop && $object->isField('Hits')) {
 				$relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop;
 			}
 			if ($rel_rating && $object->isField('CachedRating')) {
 				$relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating;
 			}
 
 			// building final search query
 			if (!$this->Application->GetVar('do_not_drop_search_table')) {
 				$this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); // erase old search table if clean k4 event
 				$this->Application->SetVar('do_not_drop_search_table', true);
 			}
 
 
 			$search_table_exists = $this->Conn->Query('SHOW TABLES LIKE "'.$search_table.'"');
 			if ($search_table_exists) {
 				$select_intro = 'INSERT INTO '.$search_table.' (Relevance, ItemId, ResourceId, ItemType, EdPick) ';
 			}
 			else {
 				$select_intro = 'CREATE TABLE '.$search_table.' AS ';
 			}
 
 			$edpick_clause = $this->Application->getUnitOption($event->Prefix.'.EditorsPick', 'Fields') ? $items_table.'.EditorsPick' : '0';
 
 
 			$sql = $select_intro.' SELECT '.$relevance_clause.' AS Relevance,
 								'.$items_table.'.'.$this->Application->getUnitOption($event->Prefix, 'IDField').' AS ItemId,
 								'.$items_table.'.ResourceId,
 								'.$this->Application->getUnitOption($event->Prefix, 'ItemType').' AS ItemType,
 								 '.$edpick_clause.' AS EdPick
 						FROM '.$object->TableName.'
 						'.implode(' ', $join_clauses).'
 						WHERE '.$where_clause.'
 						GROUP BY '.$items_table.'.'.$this->Application->getUnitOption($event->Prefix, 'IDField').' ORDER BY Relevance DESC';
 
 			$res = $this->Conn->Query($sql);
 
 			if ( !$search_table_exists ) {
 				$sql = 'ALTER TABLE ' . $search_table . '
 						ADD INDEX (ResourceId),
 						ADD INDEX (Relevance)';
 				$this->Conn->Query($sql);
 			}
 		}
 
 		/**
 		 * Make record to search log
 		 *
 		 * @param string $keywords
 		 * @param int $search_type 0 - simple search, 1 - advanced search
 		 */
 		function saveToSearchLog($keywords, $search_type = 0)
 		{
 			// don't save keywords for each module separately, just one time
 			// static variable can't help here, because each module uses it's own class instance !
 			if (!$this->Application->GetVar('search_logged')) {
 				$sql = 'UPDATE '.TABLE_PREFIX.'SearchLog
 						SET Indices = Indices + 1
 						WHERE Keyword = '.$this->Conn->qstr($keywords).' AND SearchType = '.$search_type; // 0 - simple search, 1 - advanced search
 		        $this->Conn->Query($sql);
 		        if ($this->Conn->getAffectedRows() == 0) {
 		            $fields_hash = Array('Keyword' => $keywords, 'Indices' => 1, 'SearchType' => $search_type);
 		        	$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'SearchLog');
 		        }
 
 		        $this->Application->SetVar('search_logged', 1);
 			}
 		}
 
 		/**
 		 * Load item if id is available
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @access protected
 		 */
 		protected function LoadItem(&$event)
 		{
 			if ( $event->Special != '-virtual' ) {
 				parent::LoadItem($event);
 				return;
 			}
 
 			$object =& $event->getObject();
 			/* @var $object kDBItem */
 
 			$id = $this->getPassedID($event);
 
 			if ( $object->isLoaded() && !is_array($id) && ($object->GetID() == $id) ) {
 				// object is already loaded by same id
 				return;
 			}
 
 			if ( $object->Load($id, null, true) ) {
 				$actions =& $this->Application->recallObject('kActions');
 				/* @var $actions Params */
 
 				$actions->Set($event->getPrefixSpecial() . '_id', $object->GetID());
 			}
 			else {
 				$object->setID($id);
 			}
 		}
 
 		/**
 		 * Returns constrain for priority calculations
 		 *
 		 * @param kEvent $event
 		 * @return void
 		 * @see PriorityEventHandler
 		 * @access protected
 		 */
 		protected function OnGetConstrainInfo(&$event)
 		{
 			$contarain = ''; // for OnSave
 
 			$event_name = $event->getEventParam('original_event');
 			$actual_event_name = $event->getEventParam('actual_event');
 
 			if ( $actual_event_name == 'OnSavePriorityChanges' || $event_name == 'OnAfterItemLoad' || $event_name == 'OnAfterItemDelete' ) {
 				$object =& $event->getObject();
 				/* @var $object kDBItem */
 
 				$contarain = 'ParentId = ' . $object->GetDBField('ParentId');
 			}
 			elseif ( $actual_event_name == 'OnPreparePriorities' ) {
 				$contarain = 'ParentId = ' . $this->Application->GetVar('m_cat_id');
 			}
 			elseif ( $event_name == 'OnSave' ) {
 				$contarain = '';
 			}
 			else {
 				$contarain = 'ParentId = ' . $this->Application->GetVar('m_cat_id');
 			}
 
 			$event->setEventParam('constrain_info', Array ($contarain, ''));
 		}
 	}
\ No newline at end of file