Index: trunk/kernel/units/groups/groups_config.php =================================================================== diff -u -N --- trunk/kernel/units/groups/groups_config.php (revision 6093) +++ trunk/kernel/units/groups/groups_config.php (revision 0) @@ -1,135 +0,0 @@ - 'g', - - 'ItemClass' => Array('class' => 'GroupsItem', 'file' => 'groups_item.php', 'build_event' => 'OnItemBuild'), - 'ListClass' => Array('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'), - 'EventHandlerClass' => Array('class' => 'GroupsEventHandler', 'file' => 'groups_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class' => 'kDBTagProcessor', 'file' => '','build_event'=>'OnBuild'), - - 'AutoLoad' => true, - - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - 4 => 'mode', - ), - - 'IDField' => 'GroupId', - - 'StatusField' => Array('Enabled'), - - 'TitleField' => 'Name', - - 'TitlePresets' => Array( - 'default' => Array( 'new_status_labels' => Array('g' => '!la_title_Adding_Group!'), - 'edit_status_labels' => Array('g' => '!la_title_Editing_Group!'), - 'new_titlefield' => Array('g' => '!la_title_New_Group!'), - ), - - 'groups_list' => Array('prefixes' => Array('g_List'), 'format' => "!la_title_Groups! (#g_recordcount#)"), - - 'groups_edit' => Array('prefixes' => Array('g'), 'format' => "#g_status# '#g_titlefield#' - !la_title_General!"), - - 'groups_edit_users' => Array('prefixes' => Array('g', 'g-ug_List'), 'format' => "#g_status# '#g_titlefield#' - !la_title_Users! (#g-ug_recordcount#)" ), - - 'groups_edit_permissions' => Array('prefixes' => Array('g'), 'format' => "#g_status# '#g_titlefield#' - !la_title_Permissions!" ), - - 'groups_edit_additional_permissions' => Array('prefixes' => Array('g'), 'format' => "#g_status# '#g_titlefield#' - !la_title_AdditionalPermissions!" ), - - 'groups_select' => Array('prefixes' => Array('g_List'), 'format' => "!la_title_Groups! (#g_recordcount#) - !la_title_SelectGroup!"), - ), - - 'PermSection' => Array('main' => 'in-portal:user_groups'), - - 'Sections' => Array( - 'in-portal:user_groups' => Array( - 'parent' => 'in-portal:users', - 'icon' => 'usergroups', - 'label' => 'la_tab_User_Groups', - 'url' => Array('t' => 'groups/groups_list', 'pass' => 'm'), - 'permissions' => Array('view', 'add', 'edit', 'delete', 'advanced:send_email', 'advanced:manage_permissions'), - 'priority' => 2, - 'type' => stTREE, - ), - ), - - 'TableName' => TABLE_PREFIX.'PortalGroup', - - 'ListSQLs' => Array( - '' => ' - SELECT %1$s.* %2$s FROM %1$s', - 'total' => ' - SELECT %1$s.* %2$s FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'UserGroup ug ON ug.GroupId = %1$s.GroupId', - ), - - 'ItemSQLs' => Array('' => ' - SELECT %1$s.* %2$s FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'UserGroup ug ON ug.GroupId = %1$s.GroupId'), - - 'ListSortings' => Array( - '' => Array( - 'Sorting' => Array('Name' => 'asc'), - ) - ), - - 'SubItems' => Array('g-perm', /*'g-ug'*/), - 'CalculatedFields' => Array( - 'total' => Array( - 'UserCount' => 'COUNT(ug.PortalUserId)', - ), - ), - - 'Fields' => Array ( - 'GroupId' => Array(), - 'Name' => Array('type' => 'string', 'not_null' => '1', 'required' => 1, 'default' => ''), - 'Description' => Array('type' => 'string','default' => ''), - 'CreatedOn' => Array('type' => 'double', 'formatter' => 'kDateFormatter', 'not_null' => '1','default' => '#NOW#'), - 'System' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'Personal' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'Enabled' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'la_Enabled', 0 => 'la_Disabled'), 'use_phrases' => 1, 'not_null' => '1','default' => 1), - 'ResourceId' => Array('type' => 'int','not_null' => '1','default' => '0'), - ), - - 'VirtualFields' => Array( - 'UserCount' => Array('type' => 'int', 'default' => 0), - ), - - 'Grids' => Array( - 'Default' => Array( - 'Icons' => Array(1 => 'icon16_group.gif', 0 => 'icon16_group_disabled.gif'), - 'Fields' => Array( - 'GroupId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_checkbox_td'), - 'Name' => Array('title' => 'la_col_GroupName'), - 'UserCount' => Array('title' => 'la_col_UserCount'), - ), - ), - - 'Radio' => Array( - 'Icons' => Array(1 => 'icon16_group.gif', 0 => 'icon16_group_disabled.gif'), - 'Fields' => Array( - 'GroupId' => Array('title' => 'la_col_Id', 'data_block' => 'grid_radio_td'), - 'Name' => Array('title' => 'la_col_GroupName'), - 'Description' => Array('title' => 'la_col_Description'), - ), - ), - - /*'GroupSelector' => Array( - 'Icons' => Array(0 => 'icon16_user_disabled.gif', 1 => 'icon16_user.gif', 2 => 'icon16_user_pending.gif'), - 'Fields' => Array( - 'Login' => Array('title' => 'la_col_Username', 'data_block' => 'grid_radio_td'), - 'LastName' => Array( 'title'=>'la_col_LastName'), - 'FirstName' => Array( 'title'=>'la_col_FirstName'), - 'Email' => Array( 'title'=>'la_col_Email'), - 'PrimaryGroup' => Array( 'title'=>'la_col_PrimaryGroup'), - 'CreatedOn_formatted' => Array('title' => 'la_col_CreatedOn', 'sort_field' => 'CreatedOn'), - ), - ),*/ - ), - - ); - -?> \ No newline at end of file Index: trunk/kernel/units/groups/groups_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/groups/groups_event_handler.php (revision 6625) +++ trunk/kernel/units/groups/groups_event_handler.php (revision 0) @@ -1,19 +0,0 @@ -Special == 'total') { - $object =& $event->getObject(); - $object->AddGroupByField('%1$s.GroupId'); - } - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/groups/groups_item.php =================================================================== diff -u -N --- trunk/kernel/units/groups/groups_item.php (revision 5186) +++ trunk/kernel/units/groups/groups_item.php (revision 0) @@ -1,23 +0,0 @@ -Validate()) return false; - $this->SetDBField('ResourceId', $this->Application->NextResourceId()); - - return parent::Create(); - } - - function Update($id = null, $system_update = false) - { - $this->VirtualFields['ResourceId'] = Array(); - $ret = parent::Update($id, $system_update); - unset($this->VirtualFields['ResourceId']); - - return $ret; - } -} - -?> \ No newline at end of file Index: trunk/kernel/units/visits/visits_event_handler.php =================================================================== diff -u -N -r4758 -r6629 --- trunk/kernel/units/visits/visits_event_handler.php (.../visits_event_handler.php) (revision 4758) +++ trunk/kernel/units/visits/visits_event_handler.php (.../visits_event_handler.php) (revision 6629) @@ -1,6 +1,6 @@ Array('subitem' => 'add|edit'), - 'OnSaveAndClose' => Array('subitem' => 'add|edit'), - ); - $this->permMapping = array_merge($this->permMapping, $permissions); - } - - /** - * Check permission of item, that being translated - * - * @param kEvent $event - */ - function CheckPermission(&$event) - { - list($prefix, $field) = $this->getPrefixAndField($event); - - $top_prefix = $this->Application->GetTopmostPrefix($prefix); - $event->setEventParam('top_prefix', $top_prefix); - return parent::CheckPermission($event); - } - - - /** - * Returns prefix and field being translated - * - * @param kEvent $event - */ - function getPrefixAndField(&$event) - { - $field = $this->Application->GetVar($event->getPrefixSpecial(true).'_field'); - - if (strpos($field,':') !== false) { - list($prefix, $field) = explode(':', $field); - } - else { - $prefix = $this->Application->GetVar($event->getPrefixSpecial(true).'_prefix'); - } - return Array($prefix, $field); - } - - function OnLoad(&$event) - { - list($obj_prefix, $field) = $this->getPrefixAndField($event); - - $object =& $this->Application->recallObject($obj_prefix); - $translator =& $this->Application->recallObject($event->getPrefixSpecial()); - - $def_lang = $this->Application->GetDefaultLanguageId(); - - $current_lang = $translator->GetDBField('Language'); - if (!$current_lang) $current_lang = $this->Application->RecallVar('trans_lang'); - if (!$current_lang) $current_lang = $this->Application->GetVar('m_lang'); - /*if ($current_lang == $def_lang) { - $current_lang = $def_lang + 1; - }*/ - $this->Application->StoreVar('trans_lang', $current_lang); //remember translation language for user friendlyness - - $translator->SetID(1); - $translator->SetDBField('Original', $object->GetDBField('l'.$this->Application->GetVar('m_lang').'_'.$field)); - $translator->SetDBField('Language', $current_lang); - $translator->SetDBField('SwitchLanguage', $current_lang); - - $translator->SetDBField('Translation', $object->GetDBField('l'.$current_lang.'_'.$field)); - - $cur_lang =& $this->Application->recallObject('lang.current'); - $cur_lang->Load($current_lang); - - $translator->SetDBField('Charset', $cur_lang->GetDBField('Charset')); - - $event->redirect = false; - } - - function OnSaveAndClose(&$event) - { - $event->CallSubEvent('OnPreSave'); - $this->finalizePopup($event); - } - - function OnPreSave(&$event) - { - $translator =& $this->Application->recallObject($event->getPrefixSpecial()); - - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if($items_info) $field_values = array_shift($items_info); - - $translator->SetFieldsFromHash($field_values); - - list($obj_prefix, $field) = $this->getPrefixAndField($event); - - $object =& $this->Application->recallObject($obj_prefix); - - $lang = $translator->GetDBField('Language'); - $object->Fields['l'.$lang.'_'.$field] = Array(); - $object->SetDBField('l'.$lang.'_'.$field, $translator->GetDBField('Translation')); - $this->RemoveRequiredFields($object); - $object->Update(); - } - - function OnChangeLanguage(&$event) - { - $event->CallSubEvent('OnPreSave'); - $translator =& $this->Application->recallObject($event->getPrefixSpecial()); - $translator->SetDBField('Language', $translator->GetDBField('SwitchLanguage')); - $event->CallSubEvent('OnLoad'); - $event->redirect = false; - } - - } - - -?> \ No newline at end of file Index: trunk/kernel/units/translator/translator_config.php =================================================================== diff -u -N --- trunk/kernel/units/translator/translator_config.php (revision 4785) +++ trunk/kernel/units/translator/translator_config.php (revision 0) @@ -1,52 +0,0 @@ - 'trans', - 'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'TranslatorEventHandler','file'=>'translator_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'), - 'AutoLoad' => false, - 'hooks' => Array(), - 'QueryString' => Array( - 1 => 'prefix', - 2 => 'field', - 3 => 'multi_line', - 4 => 'event', - ), - 'IDField' => 'N/A', - - 'TitleField' => 'Translator', - - 'TitlePhrase' => 'la_text_Translation', - - 'TitlePresets' => Array( - 'default' => Array( - 'new_status_labels' => Array('trans'=>'!la_title_Adding_Order!'), - 'edit_status_labels' => Array('trans'=>'!la_title_Editing_Order!'), - 'new_titlefield' => Array('trans'=>'!la_title_New_Order!'), - ), - - 'trans_edit' => Array('prefixes' => Array('trans'), 'format' => '!la_title_EditingTranslation!'), - - ), - /* - 'TableName' => 'N/A', - - 'ListSQLs' => Array( ''=>'SELECT * FROM %s',), - - 'ItemSQLs' => Array( ''=>'SELECT * FROM %s',),*/ - - 'Fields' => Array( - ), - - 'VirtualFields' => Array( - 'Original' => Array(), - 'Language' => Array(), - 'SwitchLanguage' => Array('formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'Language', 'option_key_field' => 'LanguageId','option_title_field' => 'PackName'), - 'Translation' => Array(), - ), - 'Grids' => Array(), - ); - -?> \ No newline at end of file Index: trunk/kernel/units/configuration/configuration_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/configuration/configuration_event_handler.php (revision 6625) +++ trunk/kernel/units/configuration/configuration_event_handler.php (revision 0) @@ -1,192 +0,0 @@ -setEventParam('PermSection', $this->Application->GetVar('section')); - return parent::CheckPermission($event); - } - - - /** - * Apply any custom changes to list's sql query - * - * @param kEvent $event - * @access protected - * @see OnListBuild - */ - function SetCustomQuery(&$event) - { - $object =& $event->getObject(); - - $module = $this->Application->GetVar('module'); - $section = $this->Application->GetVar('section'); - - $object->addFilter('module_filter', '%1$s.ModuleOwner = '.$this->Conn->qstr($module)); - $object->addFilter('section_filter', '%1$s.Section = '.$this->Conn->qstr($section)); - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnBeforeItemUpdate(&$event) - { - $object =& $event->getObject(); - - // if password field is empty, then don't update - if ($object->GetDBField('element_type') == 'password') { - if (trim($object->GetDBField('VariableValue')) == '') { - $field_options = $object->GetFieldOptions('VariableValue'); - $field_options['skip_empty'] = 1; - $object->SetFieldOptions('VariableValue', $field_options); - }else { - $password_formatter =& $this->Application->recallObject('kPasswordFormatter'); - $object->SetDBField('VariableValue', $password_formatter->EncryptPassword($object->GetDBField('VariableValue'), 'b38')); - } - } - - $field_values = $this->Application->GetVar($event->getPrefixSpecial(true)); - - $state_country_hash = Array( - 'Comm_State' => 'Comm_Country', - 'Comm_Shipping_State' => 'Comm_Shipping_Country' - ); - - $field_name = $object->GetDBField('VariableName'); - if (isset($state_country_hash[$field_name])) { - // if this is state field - $check_state = $object->GetDBField('VariableValue'); - $check_country = $field_values[ $state_country_hash[$field_name] ]['VariableValue']; - - if (!($check_country && $check_state)) { - return true; - } - - $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); - $state_iso = $cs_helper->CheckState($check_state, $check_country); - if ($state_iso !== false) { - $object->SetDBField('VariableValue', $state_iso); - } - else - { - $errormsgs = $this->Application->GetVar('errormsgs'); - $errors = !$errormsgs || !isset($errormsgs[$event->Prefix_Special]) ? Array() : $errormsgs[$event->Prefix_Special]; - - $errors[$field_name] = 'la_InvalidState'; - $errormsgs[$event->Prefix_Special] = $errors; - - $this->Application->SetVar('errormsgs', $errormsgs); - $event->status = erFAIL; - } - } - - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnAfterItemUpdate(&$event) - { - $object =& $event->getObject(); - if ($object->GetDBField('element_type') == 'password') { - if (trim($object->GetDBField('VariableValue')) == '') { - $field_options = $object->GetFieldOptions('VariableValue'); - unset($field_options['skip_empty']); - $object->SetFieldOptions('VariableValue', $field_options); - } - } - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnUpdate(&$event) - { - if (!$this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { - - // 1. save user selected module root category - $items_info = $this->Application->GetVar($event->getPrefixSpecial(true)); - $new_category_id = getArrayValue($items_info, 'ModuleRootCategory', 'VariableValue'); - if ($new_category_id) { - unset($items_info['ModuleRootCategory']); - $this->Application->SetVar($event->getPrefixSpecial(true), $items_info); - } - - parent::OnUpdate($event); - - if ($event->status == erSUCCESS && $new_category_id !== false) { - // root category was submitted - $module = $this->Application->GetVar('module'); - $root_category_id = $this->Application->findModule('Name', $module, 'RootCat'); - - if ($root_category_id != $new_category_id) { - // root category differs from one in db - $fields_hash = Array('RootCat' => $new_category_id); - $this->Conn->doUpdate($fields_hash, TABLE_PREFIX.'Modules', 'Name = '.$this->Conn->qstr($module)); - } - } - - if ($event->status == erSUCCESS) { // reset cache - $this->Application->UnitConfigReader->ResetParsedData(); - } - } - - if ($this->Application->GetVar('errormsgs')) { - // because we have list out there, and this is item - $this->Application->removeObject($event->getPrefixSpecial()); - $event->redirect = false; - } - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - /*function OnChangeCountry(&$event) - { - $event->setPseudoClass('_List'); - $object = &$event->getObject( Array('per_page'=>-1) ); - $object->Query(); - $array_records =& $object->Records; - foreach($array_records as $i=>$record){ - if ($record['VariableName']=='Comm_Country'){ - $values = $this->Application->GetVar('conf'); - $array_records[$i]['VariableValue'] = $values['Comm_Country']['VariableValue']; - } - } - - $event->redirect_params = Array('opener' => 's', 'pass'=>'all,conf'); //stay! - $event->redirect = false; - }*/ - - /** - * Process items from selector (selected_ids var, key - prefix, value - comma separated ids) - * - * @param kEvent $event - */ - function OnProcessSelected(&$event) - { - $selected_ids = $this->Application->GetVar('selected_ids'); - $this->Application->StoreVar('ModuleRootCategory', $selected_ids['c']); - $this->finalizePopup($event); - } - - } - - - -?> \ No newline at end of file Index: trunk/kernel/units/configuration/configuration_tag_processor.php =================================================================== diff -u -N --- trunk/kernel/units/configuration/configuration_tag_processor.php (revision 6093) +++ trunk/kernel/units/configuration/configuration_tag_processor.php (revision 0) @@ -1,183 +0,0 @@ -Application->LinkVar('module_key'); - } - - /** - * Prints list content using block specified - * - * @param Array $params - * @return string - * @access public - */ - function PrintList($params) - { - $list =& $this->GetList($params); - $id_field = $this->Application->getUnitOption($this->Prefix,'IDField'); - - $list->Query(); - $o = ''; - $list->GoFirst(); - - $block_params=$this->prepareTagParams($params); -// $block_params['name'] = $this->SelectParam($params, 'render_as,block'); - $block_params['pass_params'] = 'true'; - $block_params['IdField'] = $list->IDField; - - $prev_heading = ''; - $next_block = $params['full_block']; - $this->groupRecords($list->Records, 'heading'); - $field_values = $this->Application->GetVar($this->getPrefixSpecial(true)); - - while (!$list->EOL()) - { - $this->Application->SetVar( $this->getPrefixSpecial().'_id', $list->GetDBField($id_field) ); // for edit/delete links using GET - - // using 2 blocks for drawing o row in case if current & next record titles match - $next_item_prompt = $list->CurrentIndex + 1 < $list->RecordsCount ? $list->Records[$list->CurrentIndex + 1]['prompt'] : ''; - $this_item_prompt = $list->GetDBField('prompt'); - - if ($next_item_prompt == $this_item_prompt) { - $curr_block = $params['half_block1']; - $next_block = $params['half_block2']; - } else { - $curr_block = $next_block; - $next_block = $params['full_block']; - } - - $block_params['name'] = $curr_block; - - $block_params['show_heading'] = ($prev_heading != $list->GetDBField('heading') ) ? 1 : 0; - - // set values from submit if any - if ($field_values) { - $list->SetDBField('VariableValue', $field_values[$list->GetDBField('VariableName')]['VariableValue']); - } - - $o.= $this->Application->ParseBlock($block_params, 1); - $prev_heading = $list->GetDBField('heading'); - $list->GoNext(); - } - - $this->Application->RemoveVar('ModuleRootCategory'); - $this->Application->SetVar( $this->getPrefixSpecial().'_id', ''); - return $o; - } - - function getModuleItemName() - { - $module = $this->Application->GetVar('module'); - $table = $this->Application->getUnitOption('confs', 'TableName'); - - $sql = 'SELECT ConfigHeader - FROM '.$table.' - WHERE ModuleName = '.$this->Conn->qstr($module); - return $this->Conn->GetOne($sql); - } - - function PrintConfList($params) - { - $list =& $this->GetList($params); - $id_field = $this->Application->getUnitOption($this->Prefix, 'IDField'); - - $list->PerPage = -1; - $list->Query(); - $o = ''; - $list->GoFirst(); - - $tmp_row = Array(); - - while (!$list->EOL()) { - $rec = $list->getCurrentRecord(); - $tmp_row[0][$rec['VariableName']] = $rec['VariableValue']; - $tmp_row[0][$rec['VariableName'].'_prompt'] = $rec['prompt']; - $list->GoNext(); - } - - $list->Records = $tmp_row; - - $block_params = $this->prepareTagParams($params); - $block_params['name'] = $this->SelectParam($params, 'render_as,block'); - $block_params['module_key'] = $this->Application->GetVar('module_key'); - $block_params['module_item'] = $this->getModuleItemName(); - $list->GoFirst(); - - return $this->Application->ParseBlock($block_params, 1); - - } - - function ShowRelevance($params) - { - return $this->Application->GetVar('module_key') != '_'; - } - - function ConfigValue($params) - { - return $this->Application->ConfigValue($params['name']); - } - - function Error($params) - { - $object =& $this->Application->recallObject( $this->getPrefixSpecial() ); - $field = $object->GetDBField($params['id_field']); - - $errors = $this->Application->GetVar('errormsgs'); - $errors = $errors[$this->getPrefixSpecial()]; - - if (isset($errors[$field])) { - $msg = $this->Application->Phrase($errors[$field]); - } - else { - $msg = ''; - } - - return $msg; - } - - /** - * Allows to show category path of selected module - * - * @param Array $params - * @return string - */ - function CategoryPath($params) - { - if (!isset($params['cat_id'])) { - $params['cat_id'] = $this->ModuleRootCategory( Array() ); - } - - return $this->Application->ProcessParsedTag('c', 'CategoryPath', $params); - } - - /** - * Shows edit warning in case if module root category changed but not saved - * - * @param Array $params - * @return string - */ - function SaveWarning($params) - { - $temp_category_id = $this->Application->RecallVar('ModuleRootCategory'); - if ($temp_category_id !== false) { - return $this->Application->ParseBlock($params); - } - return ''; - } - - function ModuleRootCategory($params) - { - $category_id = $this->Application->RecallVar('ModuleRootCategory'); - if ($category_id === false) { - $category_id = $this->Application->findModule('Name', $this->Application->GetVar('module'), 'RootCat'); - } - return $category_id; - } -} - -?> \ No newline at end of file Index: trunk/kernel/units/configuration/configuration_config.php =================================================================== diff -u -N --- trunk/kernel/units/configuration/configuration_config.php (revision 5119) +++ trunk/kernel/units/configuration/configuration_config.php (revision 0) @@ -1,78 +0,0 @@ - 'conf', - 'ItemClass' => Array('class'=>'ConfigurationItem','file'=>'configuration.php','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'ConfigurationEventHandler','file'=>'configuration_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'ConfigurationTagProcessor','file'=>'configuration_tag_processor.php','build_event'=>'OnBuild'), - 'AutoLoad' => true, - 'Hooks' => Array(), - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - ), - - 'IDField' => 'VariableName', - - 'TitlePresets' => Array( - 'default' => Array('tag_params' => Array('conf' => Array('per_page' => -1))), - - 'config_list_general' => Array('prefixes' => Array('conf_List'), 'format' => "!la_updating_config!"), - 'config_list_output' => Array('prefixes' => Array('conf_List'), 'format' => "!la_updating_config!"), - 'config_list_contacts' => Array('prefixes' => Array('conf_List'), 'format' => "!la_updating_config!"), - - 'config_list_categories' => Array('prefixes' => Array('conf_List'), 'format' => "!la_updating_config!"), - 'config_list_users' => Array('prefixes' => Array('conf_List'), 'format' => "!la_updating_config!"), - ), - - 'TableName' => TABLE_PREFIX.'ConfigurationValues', - - 'ListSQLs' => Array('' => ' SELECT %1$s.* %2$s - FROM '.TABLE_PREFIX.'ConfigurationAdmin ca - LEFT JOIN %1$s USING(VariableName)'), - - 'ItemSQLs' => Array('' => ' SELECT %1$s.* %2$s - FROM '.TABLE_PREFIX.'ConfigurationAdmin ca - LEFT JOIN %1$s USING(VariableName)'), - - 'ListSortings' => Array( - '' => Array( - 'Sorting' => Array('DisplayOrder' => 'asc', 'GroupDisplayOrder' => 'asc'), - ) - ), - - 'CalculatedFields' => Array ( - '' => Array ( - 'heading' => 'ca.heading', - 'prompt' => 'ca.prompt', - 'element_type' => 'ca.element_type', - 'ValueList' => 'ca.ValueList', - 'DisplayOrder' => 'ca.DisplayOrder', - 'GroupDisplayOrder' => 'ca.GroupDisplayOrder', - 'Install' => 'ca.Install', - ), - ), - - 'Fields' => Array( - 'VariableName' => Array('type' => 'string','not_null' => '1','default' => ''), - 'VariableValue' => array('type'=>'string', 'default'=>''), - 'ModuleOwner' => array('type'=>'string', 'default'=>'In-Portal'), - 'Section' => array('type'=>'string','not_null' => '1','default'=>''), - ), - - 'VirtualFields' => Array( - 'heading' => Array('type' => 'string', 'default' => ''), - 'prompt' => Array('type' => 'string', 'default' => ''), - 'element_type' => Array('type' => 'string', 'not_null' => '1', 'default' => ''), - 'ValueList' => Array('type' => 'string', 'default' => ''), - 'DisplayOrder' => Array('type' => 'double', 'not_null' => '1', 'default' => 0), - 'GroupDisplayOrder' => Array('type' => 'double', 'not_null' => '1', 'default' => 0), - 'Install' => Array('type' => 'int', 'not_null' => '1', 'default' => 1), - ), - - 'Grids' => Array(), - ); - -?> \ No newline at end of file Index: trunk/kernel/units/configuration/configuration.php =================================================================== diff -u -N --- trunk/kernel/units/configuration/configuration.php (revision 4663) +++ trunk/kernel/units/configuration/configuration.php (revision 0) @@ -1,23 +0,0 @@ -Application->GetVar('section'); - $keys_hash[$this->IDField] = $this->ID; - return parent::GetKeyClause($method, $keys_hash); - } - - } - -?> \ No newline at end of file Index: trunk/kernel/units/email_events/email_events_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/email_events/email_events_event_handler.php (revision 6625) +++ trunk/kernel/units/email_events/email_events_event_handler.php (revision 0) @@ -1,271 +0,0 @@ - Array('self' => 'edit'), - 'OnSaveSelected' => Array('self' => 'view'), - ); - $this->permMapping = array_merge($this->permMapping, $permissions); - } - - /** - * Changes permission section to one from REQUEST, not from config - * - * @param kEvent $event - */ - function CheckPermission(&$event) - { - $module = $this->Application->GetVar('module'); - $module = explode(':', $module, 2); - - if (count($module) == 1) { - $main_prefix = $this->Application->findModule('Name', $module[0], 'Var'); - } - else { - $exceptions = Array('Category' => 'c', 'Users' => 'u'); - $main_prefix = $exceptions[ $module[1] ]; - } - $section = $this->Application->getUnitOption($main_prefix.'.email', 'PermSection'); - - $event->setEventParam('PermSection', $section); - return parent::CheckPermission($event); - } - - /** - * Apply any custom changes to list's sql query - * - * @param kEvent $event - * @access protected - * @see OnListBuild - */ - function SetCustomQuery(&$event) - { - if ($event->Special == 'module') { - $object =& $event->getObject(); - $module = $this->Application->GetVar('module'); - $object->addFilter('module_filter', '%1$s.Module = '.$this->Conn->qstr($module)); - } - } - - /** - * Sets status Front-End Only to selected email events - * - * @param kEvent $event - */ - function OnFrontOnly(&$event) - { - $ids = implode(',', $this->StoreSelectedIDs($event)); - - $table_name = $this->Application->getUnitOption($event->Prefix, 'TableName'); - $sql = 'UPDATE '.$table_name.' - SET Enabled = 2 - WHERE EventId IN ('.$ids.')'; - $this->Conn->Query($sql); - } - - /** - * Sets selected user to email events selected - * - * @param kEvent $event - */ - function OnSelectUser(&$event) - { - $items_info = $this->Application->GetVar('u'); - if ($items_info) { - $user_id = array_shift( array_keys($items_info) ); - - $ids = $this->Application->RecallVar($event->getPrefixSpecial().'_selected_ids'); - $id_field = $this->Application->getUnitOption($event->Prefix, 'IDField'); - $table_name = $this->Application->getUnitOption($event->Prefix, 'TableName'); - $sql = 'UPDATE '.$table_name.' - SET '.$this->Application->RecallVar('dst_field').' = '.$user_id.' - WHERE '.$id_field.' IN ('.$ids.')'; - $this->Conn->Query($sql); - } - - $this->finalizePopup($event); - } - - /** - * Saves selected ids to session - * - * @param kEvent $event - */ - function OnSaveSelected(&$event) - { - $this->StoreSelectedIDs($event); - } - - /** - * Raised when email message shoul be sent - * - * @param kEvent $event - */ - function OnEmailEvent(&$event){ - - $email_event = $event->getEventParam('EmailEventName'); - if( strpos($email_event, '_') !== false ) - { - trigger_error('Invalid email event name '.$email_event.'. Use only UPPERCASE characters and dots as email event names', E_USER_ERROR); - } - - $to_user_id = $event->getEventParam('EmailEventToUserId'); - $email_event_type = $event->getEventParam('EmailEventType'); - - $message_object = &$this->Application->recallObject('emailmessages', null, Array('skip_autoload' => true)); - $event_table = $this->Application->getUnitOption('emailevents', 'TableName'); - - $event_object =& $event->getObject( Array('skip_autoload' => true) ); - $event_object->Load(array('Event'=>$email_event, 'Type'=>$email_event_type)); - - $event_id = $event_object->GetDBField('EventId'); - $from_user_id = $event_object->GetDBField('FromUserId'); - $type = $event_object->GetDBField('Type'); - $enabled = $event_object->GetDBField('Enabled'); - - $direct_send_params = $event->getEventParam('DirectSendParams'); - - if ($enabled == 0) return; // disabled event - if ($enabled == 2 && $this->Application->IsAdmin() ) return; // event only for front-end - - if ($type == 1){ - // For type "Admin" recipient is a user from field FromUserId which means From/To user in Email events list - $to_user_id = $from_user_id; - $from_user_id = -1; - } - /* - if (!($to_user_id > 0) && !$direct_send_params){ - // if we can not determine recepient we will not send email - return; - } - */ - //Parse Message Template - $message_object->Load(array('EventId' => $event_id, 'LanguageId' => $this->Application->GetVar('m_lang'))); - $message_type = $message_object->GetDBField('MessageType'); - - $email_object = &$this->Application->recallObject('kEmailMessage'); - $email_object->Clear(); - - // add footer: begin - $sql = 'SELECT em.Template - FROM '.$message_object->TableName.' em - LEFT JOIN '.TABLE_PREFIX.'Events e ON e.EventId = em.EventId - WHERE em.LanguageId = '.$message_object->GetDBField('LanguageId').' AND e.Event = "COMMON.FOOTER"'; - $footer = explode("\n\n", $this->Conn->GetOne($sql)); - $footer = $message_object->GetDBField('MessageType') == 'text' ? $email_object->convertHTMLtoPlain($footer[1]) : $footer[1]; - $message_template = $message_object->GetDBField('Template')."\r\n".$footer; - // add footer: end - - $from_user_object = &$this->Application->recallObject('u.email-from', null, Array('skip_autoload' => true)); - $from_user_object->Load($from_user_id); - // here if we don't have from_user loaded, it takes a default user from config values - if ( $from_user_object->IsLoaded() ) { - $from_user_email = $from_user_object->GetDBField('Email'); - $from_user_name = trim($from_user_object->GetDBField('FirstName').' '.$from_user_object->GetDBField('LastName')); - } - else { - $from_user_email = $this->Application->ConfigValue('Smtp_AdminMailFrom'); - } - - $to_user_object = &$this->Application->recallObject('u.email-to', null, Array('skip_autoload' => true)); - $to_user_object->Load($to_user_id); - $to_user_email = $to_user_object->GetDBField('Email'); - $to_user_name = trim($to_user_object->GetDBField('FirstName').' '.$to_user_object->GetDBField('LastName')); - - if($direct_send_params){ - $to_user_email = ( $direct_send_params['to_email'] ? $direct_send_params['to_email'] : $to_user_email ); - $to_user_name = ( $direct_send_params['to_name'] ? $direct_send_params['to_name'] : $to_user_name ); - $from_user_email = ( $direct_send_params['from_email'] ? $direct_send_params['from_email'] : $from_user_email); - $from_user_name = ( $direct_send_params['from_name'] ? $direct_send_params['from_name'] : $from_user_name ); - $message_body_additional = $direct_send_params['message']; - } - - $to_user_email = $to_user_email ? $to_user_email : $this->Application->ConfigValue('Smtp_AdminMailFrom'); - - $this->Application->makeClass('Template'); - $this->Application->InitParser(); - $parser_params = $this->Application->Parser->Params; - $direct_send_params['message_text'] = $message_body_additional; - $this->Application->Parser->Params = array_merge_recursive2($this->Application->Parser->Params, $direct_send_params); - $message_template = str_replace('Application->Parser->Parse($message_template, 'email_template', 0); - $this->Application->Parser->Params = $parser_params; - - $message_template = str_replace("\r", "", $message_template); - - list($message_headers, $message_body) = explode("\n\n", $message_template, 2); - - - $email_object->setFrom($from_user_email, $from_user_name); - $email_object->setTo($to_user_email, $to_user_name); - $email_object->setSubject('Mail message'); - - $email_object->setHeaders($message_headers); - - if ($message_type == 'html'){ - $email_object->setHTMLBody($message_body); - } - else { - $email_object->setTextBody($message_body); - } - - $smtp_object = &$this->Application->recallObject('kSmtpClient'); - $smtp_object->debug = $this->Application->isDebugMode() && constOn('DBG_SMTP'); - - $smtp_server = $this->Application->ConfigValue('Smtp_Server'); - $smtp_port = $this->Application->ConfigValue('Smtp_Port'); - - $smtp_authenticate = $this->Application->ConfigValue('Smtp_Authenticate'); - if ($smtp_authenticate){ - $smtp_user = $this->Application->ConfigValue('Smtp_User'); - $smtp_pass = $this->Application->ConfigValue('Smtp_Pass'); - }else{ - $smtp_user = ''; - $smtp_pass = ''; - } - - - if ($smtp_server){ - if ($email_object->sendSMTP($smtp_object, $smtp_server, $smtp_user, $smtp_pass, $smtp_authenticate)){ - $event->status=erSUCCESS; - } - else { - $event->status=erFAIL; - } - }else{ - if($email_object->send()){ - $event->status=erSUCCESS; - } - else { - $event->status=erFAIL; - } - } - - if ($event->status == erSUCCESS){ - if (!$from_user_name) { - $from_user_name = strip_tags( $this->Application->ConfigValue('Site_Name') ); - } - $sql = 'INSERT INTO '.TABLE_PREFIX.'EmailLog SET - fromuser = '.$this->Conn->qstr($from_user_name.' ('.$from_user_email.')').', - addressto = '.$this->Conn->qstr($to_user_name.' ('.$to_user_email.')').', - subject = '.$this->Conn->qstr($email_object->Subject).', - timestamp = UNIX_TIMESTAMP(), - event = '.$this->Conn->qstr($email_event); - $this->Conn->Query($sql); - } - - $this->Application->removeObject('u.email-from'); - $this->Application->removeObject('u.email-to'); - return $event; - } - } -?> \ No newline at end of file Index: trunk/kernel/units/email_events/email_events_config.php =================================================================== diff -u -N --- trunk/kernel/units/email_events/email_events_config.php (revision 6583) +++ trunk/kernel/units/email_events/email_events_config.php (revision 0) @@ -1,102 +0,0 @@ - 'emailevents', - 'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'EmailEventsEventsHandler','file'=>'email_events_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'), - 'AutoLoad' => true, - - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - ), - - 'IDField' => 'EventId', - - 'StatusField' => Array('Enabled'), - - 'TitleField' => 'Event', - - 'TitlePresets' => Array( - 'email_settings_list' => Array('prefixes' => Array('emailevents.module_List'), 'format' => '!la_title_EmailSettings! (#emailevents.module_recordcount#)'), - ), - - 'FilterMenu' => Array( - 'Groups' => Array( - Array('mode' => 'AND', 'filters' => Array('show_enabled','show_disabled','show_frontonly'), 'type' => WHERE_FILTER), - ), - 'Filters' => Array( - 'show_enabled' => Array('label' =>'la_Enabled', 'on_sql' => '', 'off_sql' => '%1$s.Enabled != 1' ), - 'show_disabled' => Array('label' => 'la_Disabled', 'on_sql' => '', 'off_sql' => '%1$s.Enabled != 0' ), - 'show_frontonly' => Array('label' => 'la_Text_FrontOnly', 'on_sql' => '', 'off_sql' => '%1$s.Enabled != 2' ), - ) - ), - - 'TableName' => TABLE_PREFIX.'Events', - - 'CalculatedFields' => Array( - '' => Array ( - 'FromUser' => 'u.Login', - ) - ), - - 'ListSQLs' => Array( ''=>' SELECT %1$s.* %2$s - FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON %1$s.FromUserId = u.PortalUserId', - ), // key - special, value - list select sql), - - 'ItemSQLs' => Array( ''=>'SELECT * FROM %s'), - - 'ListSortings' => Array( - '' => Array('Sorting' => Array('Module' => 'asc', 'Description' => 'asc') ), - - 'module' => Array('Sorting' => Array('Description' => 'asc') ), - ), - - 'Fields' => Array( - 'EventId' => Array(), - 'Event' => Array('type' => 'string','not_null' => '1','default' => ''), - 'Enabled' => Array('type'=>'int', 'formatter'=>'kOptionsFormatter', 'options' => Array(1 => 'la_Enabled', 0 => 'la_Disabled', 2 => 'la_Text_FrontOnly'), 'use_phrases' => 1, 'default' => 1, 'not_null' => 1), - 'FromUserId' => Array('formatter' => 'kLEFTFormatter','options' => Array(-1=>'root'), 'left_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'PortalUser WHERE `%s` = \'%s\'', 'left_key_field' => 'PortalUserId', 'left_title_field' => 'Login', 'required'=>1, 'not_null' => 1, 'default' => -1), - 'Module' => Array('type' => 'string','not_null' => '1','default' => ''), - 'Description' => Array('type' => 'string','not_null' => '1','default' => ''), - 'Type' => Array('formatter'=>'kOptionsFormatter', 'options' => Array (1 => 'la_Text_Admin', 0 => 'la_Text_User'), 'use_phrases' => 1, 'default' => 0, 'not_null' => 1), - ), - 'VirtualFields' => Array( - 'FromUser' => Array(), - ), - - 'Grids' => Array( - 'Default' => Array( - 'Icons' => Array('default'=>'icon16_custom.gif'), - 'Fields' => Array( - 'Description' => Array( 'title'=>'la_col_Description', 'data_block' => 'label_grid_checkbox_td'), - 'Event' => Array( 'title'=>'la_col_Event'), - 'Module' => Array( 'title'=>'la_col_Module'), - 'Type' => Array( 'title'=>'la_col_Type'), - 'Enabled' => Array( 'title'=>'la_col_Status'), - ), - - ), - - 'EmailSettings' => Array( - 'Icons' => Array('default'=>'icon16_custom.gif'), - 'Fields' => Array( - 'Description' => Array('title'=>'la_col_Description', 'data_block' => 'label_grid_checkbox_td' ), - 'Type' => Array('title'=>'la_col_Type'), - 'Enabled' => Array('title'=>'la_col_Status'), - 'FromUser' => Array('title'=>'la_col_FromToUser'), - ), - - ), - ), - ); - - if (defined('DEBUG_MODE') && DEBUG_MODE) { - $config['Grids']['EmailSettings']['Fields']['EventId'] = Array('title' => 'la_col_Id'); - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/cat_dblist.php =================================================================== diff -u -N --- trunk/kernel/units/general/cat_dblist.php (revision 1566) +++ trunk/kernel/units/general/cat_dblist.php (revision 0) @@ -1,25 +0,0 @@ -Special) - { - case 'showall': - $this->clearFilters(false,true,false,false); - break; - } - return parent::GetWhereClause($for_counting,$system_filters_only); - }*/ - -} - -?> \ No newline at end of file Index: trunk/kernel/units/general/inp1_parser.php =================================================================== diff -u -N --- trunk/kernel/units/general/inp1_parser.php (revision 6093) +++ trunk/kernel/units/general/inp1_parser.php (revision 0) @@ -1,156 +0,0 @@ -InportalInited) { - //$save_t = $this->Application->GetVar('t'); - $this->InitInPortal(); - $var_list['t'] = $this->cutTPL($var_list['t']); - if($var_list['t'] != $this->Application->GetVar('t')) - { - $get = $_GET; - unset($get['env'], $get['Action'], $get['_mod_rw_url_'], $get['rewrite']); - $this->Application->StoreVar('K4_Template_Referer', $this->Application->GetVar('t') ); - - $this->Application->Redirect($var_list['t'], $get); - } - } - - $var_list['t'] = $this->cutTPL($var_list['t']); - - if ($var_list['t'] != $this->Application->GetVar('t')) { - //$var_list['t'] = rtrim($var_list['t'],'.tpl'); - $t = $var_list['t']; - $this->Application->SetVar('t', $t); - $template_cache =& $this->Application->recallObject('TemplatesCache'); - $template_body = $this->Application->Parser->Parse( $template_cache->GetTemplateBody($t), $t, 0 ); - } - else { - $this->InitParser(); - $template_body = $objTemplate->ParseTemplateFromBuffer($tname, $template_body); - } - return $template_body; - } - - function cutTPL($tname) - { - if( substr($tname,-4) == '.tpl' ) - { - return substr($tname, 0, strlen($tname)-4 ); - } - return $tname; - } - - function InitParser() - { - global $objTemplate, $CurrentTheme, $objThemes, $objLanguageCache, $var_list; - if ($this->InpParsetInited) return true; - - $theme_id = $this->Application->GetVar('m_theme'); - if ($theme_id) { - $CurrentTheme = $objThemes->GetItem($theme_id); - - $timeout = $CurrentTheme->Get('CacheTimeout'); - $objLanguageCache->LoadTemplateCache($var_list['t'], $timeout, $theme_id); - $objLanguageCache->LoadCachedVars($this->Application->GetVar('m_lang')); - - $objTemplate = new clsTemplateList(FULL_PATH.THEMES_PATH.'/'); - } - - $this->InpParsetInited = true; - } - - function InitInPortal() - { - $this->InportalInited = true; - /*global $pathtoroot, $FrontEnd, $indexURL, $rootURL, $secureURL, $var_list, $CurrentTheme, - $objThemes, $objConfig, $m_var_list, $timeout, $objLanguages, $objLanguageCache, - $TemplateRoot, $objTemplate, $html, $objSession, $Errors, $objCatList, $objUsers, - $env, $mod_prefix, $ExtraVars, $timestart, $timeend, $timeout, $sqlcount, $totalsql, - $template_path, $modules_loaded, $mod_root_cats, $objModules, $objItemTypes;*/ - - - global $sec, $usec, $timestart, $pathtoroot, $FrontEnd, $indexURL, $kernel_version, $FormError, - $FormValues, $ItemTables, $KeywordIgnore, $debuglevel, - $LogLevel, $LogFile, $rq_value, $rq_name, $dbg_constMap, $dbg_constValue, $dbg_constName, - $debugger, $g_LogFile, $LogData, $Errors, - $g_DebugMode, $totalsql, $sqlcount, $objConfig, $ItemTypePrefixes, $ItemTagFiles, $objModules, - $objSystemCache, $objBanList, $objItemTypes, $objThemes, $objLanguages, $objImageList, $objFavorites, - $objUsers, $objGroups, $DownloadId, $objPermissions, $objPermCache, $m_var_list, $objCatList, - $objCustomFieldList, $objCustomDataList, $objCountCache, $CRLF, $objMessageList, $objEmailQueue, - $ExtraVars, $adodbConnection, $sql, $rs, $mod_prefix, $modules_loaded, $name, - $template_path, $mod_root_cats, $value, $mod, $ItemTypes, - $ParserFiles, $SessionQueryString, $var_list, $objSession, - $orderByClause, $TemplateRoot, $ip, $UseSession, $Action, $CookieTest, $sessionId, - $var_list_update, $CurrentTheme, $UserID, $objCurrentUser, $objLanguageCache, - $folder_name, $objLinkList, $tag_override, $timeZones, $siteZone, $serverZone, - $lastExpire, $diffZone, $date, $nowDate, $lastExpireDate, $SearchPerformed, - $TotalMessagesSent, $ado, $adminDir, $rootURL, $secureURL, $html, $timeout, - $pathchar, $objTemplate, $objTopicList, $objArticleList, $objPostingList, $objCensorList, - $objSmileys, $objPMList, $SubscribeAddress, $SubscribeError, $SubscribeResult, $application; - - $pathtoroot = $this->Application->IsAdmin() ? '../' : './'; - $pathtoroot = realpath($pathtoroot)."/"; - - if (!file_exists($pathtoroot."config.php")) { - echo "In-Portal is probably not installed, or configuration file is missing.
"; - echo "Please use the installation script to fix the problem.

"; - echo "Go to installation script

"; - flush(); - $this->Application->ApplicationDie(); - } - - //ob_start(); - $FrontEnd=1; - - $indexURL="../../index.php"; //Set to relative URL from the theme directory - - /* initalize the in-portal system */ - include_once(FULL_PATH."/kernel/startup.php"); - - $rootURL="http://".ThisDomain().$objConfig->Get("Site_Path"); - $secureURL = $rootURL; - - if( !$var_list['t'] ) $var_list['t'] = 'index'; - - $this->InitParser(); - - // process referer in session: begin - if (is_object($objSession)) { - $k4_referer = $objSession->GetVariable('K4_Template_Referer'); - if ($k4_referer) { - $_local_t = $k4_referer; - $this->Application->RemoveVar('K4_Template_Referer'); - } - $objSession->SetVariable('Template_Referer', $_local_t); - } - // process referer in session: end - - if ($this->Application->isDebugMode() && $Action) { - $this->Application->Debugger->setHTMLByIndex(1, 'Front Action: '.$Action.'', 'append'); - } - - LogEntry("Output Complete\n"); - $objLanguageCache->SaveTemplateCache(); - LogEntry("Templates Cached\n"); - - $timeend = getmicrotime(); - $diff = $timeend - $timestart; - - LogEntry("\nTotal Queries Executed: $sqlcount in $totalsql seconds\n"); - LogEntry("\nPage Execution Time: $diff seconds\n", true); - if ($LogFile) { - fclose($LogFile); - } - } -} - -?> \ No newline at end of file Index: trunk/kernel/units/general/general_config.php =================================================================== diff -u -N --- trunk/kernel/units/general/general_config.php (revision 6625) +++ trunk/kernel/units/general/general_config.php (revision 0) @@ -1,36 +0,0 @@ - 'm', - 'EventHandlerClass' => Array('class' => 'MainEventHandler', 'file' => 'main_event_handler.php', 'build_event' => 'OnBuild'), - /*'TagProcessorClass' => Array('class'=>'kMainTagProcessor','file'=>'','build_event'=>'OnBuild'),*/ - - 'QueryString' => Array( - 1 => 'cat_id', - 2 => 'cat_page', - 3 => 'lang', - 4 => 'theme', - 5 => 'opener', - ), - 'TitleField' => 'CachedNavbar', - 'TitlePhrase' => 'la_Text_Category', - 'ItemType' => 1, - 'TableName' => TABLE_PREFIX.'Category', - - 'CatalogItem' => true, - - 'PortalStyleEnv' => true, - - 'PermTabText' => 'In-Portal', - 'PermSection' => Array('search' => 'in-portal:configuration_search', 'custom' => 'in-portal:configuration_custom'), - - - 'RegisterClasses' => Array( - Array('class'=>'InpCustomFieldsHelper','pseudo'=>'InpCustomFieldsHelper','file'=>'custom_fields.php','build_event'=>'','require_classes'=>'kHelper'), - Array('class'=>'kCountryStatesHelper','pseudo'=>'CountryStatesHelper','file'=>'country_states.php','build_event'=>'','require_classes'=>'kHelper'), - Array('class'=>'kBracketsHelper','pseudo'=>'BracketsHelper','file'=>'brackets.php','build_event'=>'','require_classes'=>'kHelper'), - Array('class'=>'kXMLHelper','pseudo'=>'kXMLHelper','file'=>'xml_helper.php','build_event'=>'','require_classes'=>'kHelper'), - ), - ); - -?> \ No newline at end of file Index: trunk/kernel/units/general/cat_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/general/cat_event_handler.php (revision 6625) +++ trunk/kernel/units/general/cat_event_handler.php (revision 0) @@ -1,1703 +0,0 @@ -Factory->includeClassFile('kDBEventHandler'); - -class kCatDBEventHandler extends kDBEventHandler { - - /** - * Allows to override standart permission mapping - * - */ - function mapPermissions() - { - parent::mapPermissions(); - $permissions = Array( - 'OnExport' => Array('self' => 'view|advanced:export'), - 'OnExportBegin' => Array('self' => 'view|advanced:export'), - 'OnSaveSettings' => Array('self' => 'add|edit|advanced:import'), - 'OnBeforeDeleteOriginal' => Array('self' => 'edit|advanced:approve'), - - 'OnCancelAction' => Array( 'self' => true), - - ); - $this->permMapping = array_merge($this->permMapping, $permissions); - } - - /** - * Checks permissions of user - * - * @param kEvent $event - */ - 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 ($event->Name == 'OnNew' && preg_match('/(.*)\/import$/', $this->Application->GetVar('t'), $rets)) { - // redirect to item import template, where permission (import) category will be chosen) - $root_category = $this->Application->findModule('Path', $rets[1].'/', 'RootCat'); - $this->Application->StoreVar('m_cat_id', $root_category); - } - - if ($event->Name == 'OnEdit' || $event->Name == 'OnSave') { - // check each id from selected individually and only if all are allowed proceed next - if ($event->Name == 'OnEdit') { - $selected_ids = implode(',', $this->StoreSelectedIDs($event)); - } - else { - $selected_ids = $this->Application->RecallVar($event->getPrefixSpecial().'_selected_ids'); - } - - $id_field = $this->Application->getUnitOption($event->Prefix, 'IDField'); - $table_name = $this->Application->getUnitOption($event->Prefix, 'TableName'); - $sql = 'SELECT '.$id_field.', CreatedById, ci.CategoryId - FROM '.$table_name.' item_table - LEFT JOIN '.$this->Application->getUnitOption('ci', 'TableName').' ci ON ci.ItemResourceId = item_table.ResourceId - WHERE '.$id_field.' IN ('.$selected_ids.') AND (ci.PrimaryCat = 1)'; - $items = $this->Conn->Query($sql, $id_field); - - $perm_value = true; - $perm_helper =& $this->Application->recallObject('PermissionsHelper'); - foreach ($items as $item_id => $item_data) { - if ($perm_helper->ModifyCheckPermission($item_data['CreatedById'], $item_data['CategoryId'], $event->Prefix) == 0) { - // one of items selected has no permission - $perm_value = false; - break; - } - } - - if (!$perm_value) { - $event->status = erPERM_FAIL; - } - - return $perm_value; - } - - return parent::CheckPermission($event); - } - - /** - * 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'); - $clipboard_helper->setClipboard($event, 'copy', $this->StoreSelectedIDs($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'); - $clipboard_helper->setClipboard($event, 'cut', $this->StoreSelectedIDs($event)); - } - - /** - * Performs category item paste - * - * @param kEvent $event - */ - function OnPaste(&$event) - { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { - return; - } - - $clipboard_data = $event->getEventParam('clipboard_data'); - - if (!$clipboard_data['cut'] && !$clipboard_data['copy']) { - return false; - } - - if ($clipboard_data['copy']) { - $temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler'); - $this->Application->SetVar('ResetCatBeforeClone', 1); - $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)); - - foreach ($clipboard_data['cut'] as $id) { - $object->Load($id); - $object->MoveToCat(); - } - } - } - - /** - * Return type clauses for list bulding on front - * - * @param kEvent $event - * @return Array - */ - function getTypeClauses(&$event) - { - $types = $event->getEventParam('types'); - $except_types = $event->getEventParam('except'); - $type_clauses = Array(); - - $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 (strpos($types, 'search') !== false || strpos($except_types, 'search') !== false) { - $event_mapping = Array( - 'simple' => 'OnSimpleSearch', - 'subsearch' => 'OnSubSearch', - 'advanced' => 'OnAdvancedSearch'); - if($this->Application->GetVar('INPORTAL_ON') && $this->Application->GetVar('Action') == 'm_simple_subsearch') - { - $type = 'subsearch'; - } - else - { - $type = $this->Application->GetVar('search_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); - $search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search'; - $sql = 'SHOW TABLES LIKE "'.$search_table.'"'; - if ( $this->Conn->Query($sql) ) { - $search_res_ids = $this->Conn->GetCol('SELECT ResourceId FROM '.$search_table); - } - - if ($search_res_ids) { - $type_clauses['search']['include'] = '%1$s.ResourceId IN ('.implode(',', $search_res_ids).') AND PrimaryCat = 1'; - $type_clauses['search']['except'] = '%1$s.ResourceId NOT IN ('.implode(',', $search_res_ids).') AND PrimaryCat = 1'; - } - else { - $type_clauses['search']['include'] = '0'; - $type_clauses['search']['except'] = '1'; - } - $type_clauses['search']['having_filter'] = false; - } - - if (strpos($types, 'related') !== false || strpos($except_types, 'related') !== false) { - - $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 = $this->Application->getUnitOption($event->Prefix, 'ItemType'); - - $p_item =& $this->Application->recallObject($related_prefix.'.current', null, Array('skip_autoload' => true)); - $p_item->Load( $this->Application->GetVar($related_prefix.'_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; - } - - return $type_clauses; - } - - /** - * Apply filters to list - * - * @param kEvent $event - */ - function SetCustomQuery(&$event) - { - parent::SetCustomQuery($event); - - $object =& $event->getObject(); - - // add category filter if needed - if ($event->Special != 'showall') { - if ( $event->getEventParam('parent_cat_id') ) { - $parent_cat_id = $event->getEventParam('parent_cat_id'); - } - else { - $parent_cat_id = $this->Application->GetVar('c_id'); - if (!$parent_cat_id) { - $parent_cat_id = $this->Application->GetVar('m_cat_id'); - } - if (!$parent_cat_id) { - $parent_cat_id = 0; - } - } - - if ((string) $parent_cat_id != 'any') { - if ($event->getEventParam('recursive')) { - $current_path = $this->Conn->GetOne('SELECT ParentPath FROM '.TABLE_PREFIX.'Category WHERE CategoryId='.$parent_cat_id); - $subcats = $this->Conn->GetCol('SELECT CategoryId FROM '.TABLE_PREFIX.'Category WHERE ParentPath LIKE "'.$current_path.'%" '); - $object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId IN ('.implode(', ', $subcats).')'); - } - else { - $object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.CategoryId = '.$parent_cat_id ); - } - } - } - else { - $object->addFilter('primary_filter', 'PrimaryCat = 1'); - } - - // add permission filter - if ($this->Application->GetVar('u_id') == -1) { - // 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 - $sql = 'SELECT PermissionConfigId - FROM '.TABLE_PREFIX.'PermissionConfig - WHERE PermissionName = "'.$this->Application->getUnitOption($event->Prefix, 'PermItemPrefix').'.VIEW"'; - $view_perm = $this->Conn->GetOne($sql); - - $groups = explode( ',', $this->Application->RecallVar('UserGroups') ); - foreach($groups as $group) - { - $view_filters[] = 'FIND_IN_SET('.$group.', perm.acl)'; - } - $view_filter = implode(' OR ', $view_filters); - $object->addFilter('perm_filter2', $view_filter); - } - - $object->addFilter('perm_filter', 'perm.PermId = '.$view_perm); - - if ( !$this->Application->IsAdmin() ) - { - $object->addFilter('status_filter', $object->TableName.'.Status = 1'); - if ($this->Application->getUnitOption($event->Prefix, 'UsePendingEditing')) { - // 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 ($this->Application->getUnitOption($event->Prefix, 'UsePendingEditing')) { - $pending_ids = $this->Conn->GetCol( - 'SELECT OrgId FROM '.$object->TableName.' - WHERE Status = -2 AND OrgId IS NOT NULL'); - if ($pending_ids) { - $object->addFilter('no_original_filter', '%1$s.'.$object->IDField.' NOT IN ('.implode(',', $pending_ids).')'); - } - } - } - - $types = $event->getEventParam('types'); - $except_types = $event->getEventParam('except'); - $type_clauses = $this->getTypeClauses($event); - - // convert prepared type clauses into list filters - $includes_or_filter =& $this->Application->makeClass('kMultipleFilter'); - $includes_or_filter->setType(FLT_TYPE_OR); - - $excepts_and_filter =& $this->Application->makeClass('kMultipleFilter'); - $excepts_and_filter->setType(FLT_TYPE_AND); - - $includes_or_filter_h =& $this->Application->makeClass('kMultipleFilter'); - $includes_or_filter_h->setType(FLT_TYPE_OR); - - $excepts_and_filter_h =& $this->Application->makeClass('kMultipleFilter'); - $excepts_and_filter_h->setType(FLT_TYPE_AND); - - if ($types) { - $types_array = explode(',', $types); - for ($i = 0; $i < sizeof($types_array); $i++) { - $type = trim($types_array[$i]); - if (isset($type_clauses[$type])) { - if ($type_clauses[$type]['having_filter']) { - $includes_or_filter_h->removeFilter('filter_'.$type); - $includes_or_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['include']); - }else { - $includes_or_filter->removeFilter('filter_'.$type); - $includes_or_filter->addFilter('filter_'.$type, $type_clauses[$type]['include']); - } - } - } - } - - if ($except_types) { - $except_types_array = explode(',', $except_types); - for ($i = 0; $i < sizeof($except_types_array); $i++) { - $type = trim($except_types_array[$i]); - if (isset($type_clauses[$type])) { - if ($type_clauses[$type]['having_filter']) { - $excepts_and_filter_h->removeFilter('filter_'.$type); - $excepts_and_filter_h->addFilter('filter_'.$type, $type_clauses[$type]['except']); - }else { - $excepts_and_filter->removeFilter('filter_'.$type); - $excepts_and_filter->addFilter('filter_'.$type, $type_clauses[$type]['except']); - } - } - } - } - - /*if ( !$this->Application->IsAdmin() ) { - $object->addFilter('expire_filter', '%1$s.Expire IS NULL OR %1$s.Expire > UNIX_TIMESTAMP()'); - }*/ - - /*$list_type = $event->getEventParam('ListType'); - switch($list_type) - { - case 'favorites': - $fav_table = $this->Application->getUnitOption('fav','TableName'); - $user_id =& $this->Application->GetVar('u_id'); - - $sql = 'SELECT DISTINCT f.ResourceId - FROM '.$fav_table.' f - LEFT JOIN '.$object->TableName.' p ON p.ResourceId = f.ResourceId - WHERE f.PortalUserId = '.$user_id; - $ids = $this->Conn->GetCol($sql); - if(!$ids) $ids = Array(-1); - $object->addFilter('category_filter', TABLE_PREFIX.'CategoryItems.PrimaryCat = 1'); - $object->addFilter('favorites_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')'); - break; - case 'search': - $search_results_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search'; - $sql = ' SELECT DISTINCT ResourceId - FROM '.$search_results_table.' - WHERE ItemType=11'; - $ids = $this->Conn->GetCol($sql); - if(!$ids) $ids = Array(-1); - $object->addFilter('search_filter', '%1$s.`ResourceId` IN ('.implode(',',$ids).')'); - break; - } */ - - $object->addFilter('includes_filter', $includes_or_filter); - $object->addFilter('excepts_filter', $excepts_and_filter); - - $object->addFilter('includes_filter_h', $includes_or_filter_h, HAVING_FILTER); - $object->addFilter('excepts_filter_h', $excepts_and_filter_h, HAVING_FILTER); - } - - /** - * Adds calculates fields for item statuses - * - * @param kCatDBItem $object - * @param kEvent $event - */ - 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'); - $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) - $sql = 'SELECT Data - FROM '.TABLE_PREFIX.'Cache - WHERE (VarName = "'.$property_map['HotLimit'].'") AND (Cached >'.(adodb_mktime() - 3600).')'; - $hot_limit = $this->Conn->GetOne($sql); - if ($hot_limit === false) { - $hot_limit = $this->CalculateHotLimit($event); - } - $object->addCalculatedField('IsHot', ' IF(%1$s.HotItem = 2, - IF(%1$s.'.$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)'); - - } - - function CalculateHotLimit(&$event) - { - $property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings'); - if (!$property_map) { - return; - } - $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); - $this->Conn->Query('REPLACE INTO '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("'.$property_map['HotLimit'].'", "'.$hot_limit.'", '.adodb_mktime().')'); - return $hot_limit; - - return 0; - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnBeforeItemUpdate(&$event) - { - $property_map = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings'); - if (!$property_map) { - return; - } - $click_field = $property_map['ClickField']; - - $object =& $event->getObject(); - if( $this->Application->IsAdmin() && ($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); - } - } - - /** - * Load price from temp table if product mode is temp table - * - * @param kEvent $event - */ - function OnAfterItemLoad(&$event) - { - $special = substr($event->Special, -6); - $object =& $event->getObject(); - 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']); - } - } - - //substituiting pending status value for pending editing - if ($object->HasField('OrgId') && $object->GetDBField('OrgId') > 0 && $object->GetDBField('Status') == -2) { - $options = $object->Fields['Status']['options']; - foreach ($options as $key => $val) { - if ($key == 2) $key = -2; - $new_options[$key] = $val; - } - $object->Fields['Status']['options'] = $new_options; - } - - } - - function OnAfterItemUpdate(&$event) - { - $this->CalculateHotLimit($event); - - if ( substr($event->Special, -6) == 'import') { - $this->setCustomExportColumns($event); - } - } - - /** - * sets values for import process - * - * @param kEvent $event - */ - function OnAfterItemCreate(&$event) - { - if ( substr($event->Special, -6) == 'import') { - $this->setCustomExportColumns($event); - } - } - - /** - * Make record to search log - * - * @param string $keywords - * @param int $search_type 0 - simple search, 1 - advanced search - */ - function saveToSearchLog($keywords, $search_type = 0) - { - $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'); - } - } - - /** - * Makes simple search for products - * based on keywords string - * - * @param kEvent $event - * @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!! - */ - function OnSimpleSearch(&$event) - { - if($this->Application->GetVar('INPORTAL_ON') && !($this->Application->GetVar('Action') == 'm_simple_search')) - { - return; - } - - $event->redirect = false; - $search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search'; - - $keywords = unhtmlentities( trim($this->Application->GetVar('keywords')) ); - - $query_object =& $this->Application->recallObject('HTTPQuery'); - $sql = 'SHOW TABLES LIKE "'.$search_table.'"'; - - if(!isset($query_object->Get['keywords']) && - !isset($query_object->Post['keywords']) && - $this->Conn->Query($sql)) - { - return; // used when navigating by pages or changing sorting in search results - } - if(!$keywords || strlen($keywords) < $this->Application->ConfigValue('Search_MinKeyword_Length')) - { - $this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); - $this->Application->SetVar('keywords_too_short', 1); - return; // if no or too short keyword entered, doing nothing - } - - $this->Application->StoreVar('keywords', $keywords); - if (!$this->Application->GetVar('INPORTAL_ON')) { - // don't save search log, because in-portal already saved it - $this->saveToSearchLog($keywords, 0); // 0 - simple search, 1 - advanced search - } - - - $keywords = strtr($keywords, Array('%' => '\\%', '_' => '\\_')); - - $event->setPseudoClass('_List'); - $object =& $event->getObject(); - $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="'.$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) { - $options = $object->getFieldOptions($field); - $local_table = TABLE_PREFIX.$search_config[$field]['TableName']; - $weight_sum += $search_config[$field]['Priority']; // counting weight sum; used when making relevance clause - - // processing multilingual fields - if (getArrayValue($options, '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') - { - unset($field_list[$key]); - continue; // ignoring having type clauses in simple search - /*$user_object =& $this->Application->recallObject('u'); - $user_groups = $this->Application->RecallVar('UserGroups'); - $having_list[$key] = str_replace('{PREFIX}', TABLE_PREFIX, $exploded[1]); - $join_clause = str_replace('{PREFIX}', TABLE_PREFIX, $search_config[$field]['JoinClause']); - $join_clause = str_replace('{USER_GROUPS}', $user_groups, $join_clause); - $join_clause = ' LEFT JOIN '.$join_clause; - $join_clauses[] = $join_clause;*/ - } - else - { - $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'; - $field_list[$key] = 'l'.$lang.'_cust_'.array_search($field_list[$key], $custom_fields); - } - $field_list[$key] = $local_table.'.'.$field_list[$key]; - $search_config_map[ $field_list[$key] ] = $field; - } - } - - // keyword string processing - $search_helper =& $this->Application->recallObject('SearchHelper'); - $where_clause = $search_helper->buildWhereClause($keywords, $field_list); - - $where_clause = $where_clause.' AND '.$items_table.'.Status=1'; - - if($this->Application->GetVar('Action') == 'm_simple_subsearch') // subsearch, In-portal - { - if( $event->getEventParam('ResultIds') ) - { - $where_clause .= ' AND '.$items_table.'.ResourceId IN ('.implode(',', $event->specificParams['ResultIds']).')'; - } - } - if( $event->MasterEvent && $event->MasterEvent->Name == 'OnListBuild' ) // subsearch, k4 - { - 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 ($field_list as $field) { - $config_elem = $search_config[ $search_config_map[$field] ]; - $weight = $config_elem['Priority']; - $revelance_parts[] = 'IF('.$field.' LIKE "%'.implode(' ', $positive_words).'%", '.$weight_sum.', 0)'; - foreach ($positive_words as $keyword) { - $revelance_parts[] = 'IF('.$field.' LIKE "%'.$keyword.'%", '.$weight.', 0)'; - } - } - $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 && isset($object->Fields['Hits'])) { - $relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop; - } - if ($rel_rating && isset($object->Fields['CachedRating'])) { - $relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating; - } - - // building final search query - if (!$this->Application->GetVar('do_not_drop_search_table') && !$this->Application->GetVar('INPORTAL_ON')) { - $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'); - - $res = $this->Conn->Query($sql); - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnSubSearch(&$event) - { - $search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search'; - $sql = 'SHOW TABLES LIKE "'.$search_table.'"'; - if($this->Conn->Query($sql)) - { - $sql = 'SELECT DISTINCT ResourceId FROM '.$search_table; - $ids = $this->Conn->GetCol($sql); - } - $event->setEventParam('ResultIds', $ids); - $event->CallSubEvent('OnSimpleSearch'); - } - - /** - * Enter description here... - * - * @param kEvent $event - * @todo Change all hardcoded Products table & In-Commerce module usage to dynamic usage from item config !!! - */ - function OnAdvancedSearch(&$event) - { - $query_object =& $this->Application->recallObject('HTTPQuery'); - if(!isset($query_object->Post['andor'])) - { - return; // used when navigating by pages or changing sorting in search results - } - - $this->Application->RemoveVar('keywords'); - $this->Application->RemoveVar('Search_Keywords'); - - $sql = ' SELECT * FROM '.$this->Application->getUnitOption('confs', 'TableName').' - WHERE ModuleName="In-Commerce" - AND AdvancedSearch=1'; - $search_config = $this->Conn->Query($sql); - $lang = $this->Application->GetVar('m_lang'); - $object =& $event->getObject(); - $object->SetPage(1); - $user_object =& $this->Application->recallObject('u'); - $product_table = $this->Application->getUnitOption('p', 'TableName'); - - $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(); - - $condition_patterns = Array( 'any' => '%s LIKE %s', - 'contains' => '%s LIKE %s', - 'notcontains' => '(NOT (%1$s LIKE %2$s) OR %1$s IS NULL)', - 'is' => '%s = %s', - 'isnot' => '(%1$s != %2$s OR %1$s IS NULL)'); - - $alias_counter = 0; - - $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 '.$product_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 - - $options = $object->getFieldOptions($field); - $local_table = TABLE_PREFIX.$record['TableName']; - $weight_sum += $record['Priority']; // counting weight sum; used when making relevance clause - - // processing multilingual fields - if (getArrayValue($options, 'formatter') == 'kMultiLanguage') { - $field_name = 'l'.$lang.'_'.$field; - } - else { - $field_name = $field; - } - - // processing fields from other tables - if ($foreign_field = $record['ForeignField']) { - $exploded = explode(':', $foreign_field, 2); - if($exploded[0] == 'CALC') - { - $user_groups = $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}', $product_table, $join_clause); - - if($record['CustomFieldId']) - { - $join_clause .= ' AND '.$alias.'.CustomFieldId='.$record['CustomFieldId']; - } - $join_clause = ' LEFT JOIN '.$foreign_table.' '.$alias.' - ON '.$join_clause; - } - } - else - { - // processing fields from local table - 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 = ''; - switch($record['FieldType']) - { - case 'text': - $keywords[$field] = unhtmlentities( $keywords[$field] ); - - if(strlen($keywords[$field]) >= $this->Application->ConfigValue('Search_MinKeyword_Length')) - { - $highlight_keywords[] = $keywords[$field]; - if( in_array($verbs[$field], Array('any', 'contains', 'notcontains')) ) - { - $keywords[$field] = '%'.strtr($keywords[$field], Array('%' => '\\%', '_' => '\\_')).'%'; - } - $condition = sprintf( $condition_patterns[$verbs[$field]], - $field_name, - $this->Conn->qstr( $keywords[$field] )); - } - break; - case 'boolean': - if($keywords[$field] != -1) - { - $property_mappings = $this->Application->getUnitOption($event->Prefix, 'ItemPropertyMappings'); - switch($field) - { - case 'HotItem': - $hot_limit_var = getArrayValue($property_mappings, 'HotLimit'); - if($hot_limit_var) - { - $sql = 'SELECT Data FROM '.TABLE_PREFIX.'Cache WHERE VarName="'.$hot_limit_var.'"'; - $hot_limit = (int)$this->Conn->GetOne($sql); - $condition = 'IF('.$product_table.'.HotItem = 2, - IF('.$product_table.'.Hits >= '. - $hot_limit. - ', 1, 0), '.$product_table.'.HotItem) = '.$keywords[$field]; - } - break; - case 'PopItem': - $votes2pop_var = getArrayValue($property_mappings, 'VotesToPop'); - $rating2pop_var = getArrayValue($property_mappings, 'RatingToPop'); - if($votes2pop_var && $rating2pop_var) - { - $condition = 'IF('.$product_table.'.PopItem = 2, IF('.$product_table.'.CachedVotesQty >= '. - $this->Application->ConfigValue($votes2pop_var). - ' AND '.$product_table.'.CachedRating >= '. - $this->Application->ConfigValue($rating2pop_var). - ', 1, 0), '.$product_table.'.PopItem) = '.$keywords[$field]; - } - break; - case 'NewItem': - $new_days_var = getArrayValue($property_mappings, 'NewDays'); - if($new_days_var) - { - $condition = 'IF('.$product_table.'.NewItem = 2, - IF('.$product_table.'.CreatedOn >= (UNIX_TIMESTAMP() - '. - $this->Application->ConfigValue($new_days_var). - '*3600*24), 1, 0), '.$product_table.'.NewItem) = '.$keywords[$field]; - } - break; - case 'EditorsPick': - $condition = $product_table.'.EditorsPick = '.$keywords[$field]; - break; - } - } - break; - case 'range': - $range_conditions = Array(); - if($keywords[$field.'_from'] && !preg_match("/[^0-9]/i", $keywords[$field.'_from'])) - { - $range_conditions[] = $field_name.' >= '.$keywords[$field.'_from']; - } - if($keywords[$field.'_to'] && !preg_match("/[^0-9]/i", $keywords[$field.'_to'])) - { - $range_conditions[] = $field_name.' <= '.$keywords[$field.'_to']; - } - if($range_conditions) - { - $condition = implode(' AND ', $range_conditions); - } - break; - case 'date': - if($keywords[$field]) - { - if( in_array($keywords[$field], Array('today', 'yesterday')) ) - { - $current_time = getdate(); - $day_begin = adodb_mktime(0, 0, 0, $current_time['mon'], $current_time['mday'], $current_time['year']); - $time_mapping = Array('today' => $day_begin, 'yesterday' => ($day_begin - 86400)); - $min_time = $time_mapping[$keywords[$field]]; - } - else - { - $time_mapping = Array( 'last_week' => 604800, 'last_month' => 2628000, - 'last_3_months' => 7884000, 'last_6_months' => 15768000, - 'last_year' => 31536000 - ); - $min_time = adodb_mktime() - $time_mapping[$keywords[$field]]; - } - $condition = $field_name.' > '.$min_time; - } - break; - } - - if($condition) - { - if($join_clause) - { - $join_clauses[] = $join_clause; - } - $relevance_parts[] = 'IF('.$condition.', '.$record['Priority'].', 0)'; - if($glues[$field] == 1) // and - { - if($condition_mode == 'WHERE') - { - $and_conditions[] = $condition; - } - else - { - $and_having_conditions[] = $condition; - } - } - else // or - { - if($condition_mode == 'WHERE') - { - $or_conditions[] = $condition; - } - else - { - $or_having_conditions[] = $condition; - } - } - - // 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'); - } - } - - $search_log = implode('
', $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) - { - $rel_keywords = $this->Application->ConfigValue('SearchRel_Keyword_products') / 100; - $rel_pop = $this->Application->ConfigValue('SearchRel_Pop_products') / 100; - $rel_rating = $this->Application->ConfigValue('SearchRel_Rating_products') / 100; - $relevance_clause = '('.implode(' + ', $relevance_parts).') / '.$weight_sum.' * '.$rel_keywords; - $relevance_clause .= ' + (Hits + 1) / (MAX(Hits) + 1) * '.$rel_pop; - $relevance_clause .= ' + (CachedRating + 1) / (MAX(CachedRating) + 1) * '.$rel_rating; - } - else - { - $relevance_clause = '0'; - } - - // building having clause - if($or_having_conditions) - { - $and_having_conditions[] = '('.implode(' OR ', $or_having_conditions).')'; - } - $having_clause = implode(' AND ', $and_having_conditions); - $having_clause = $having_clause ? ' HAVING '.$having_clause : ''; - - // building where clause - if($or_conditions) - { - $and_conditions[] = '('.implode(' OR ', $or_conditions).')'; - } -// $and_conditions[] = $product_table.'.Status = 1'; - $where_clause = implode(' AND ', $and_conditions); - if(!$where_clause) - { - if($having_clause) - { - $where_clause = '1'; - } - else - { - $where_clause = '0'; - $this->Application->SetVar('adv_search_error', 1); - } - } - $where_clause .= ' AND '.$product_table.'.Status = 1'; - - // building final search query - $search_table = TABLE_PREFIX.'ses_'.$this->Application->GetSID().'_'.TABLE_PREFIX.'Search'; - - $this->Conn->Query('DROP TABLE IF EXISTS '.$search_table); - - $sql = ' CREATE TABLE '.$search_table.' - SELECT '.$relevance_clause.' AS Relevance, - '.$product_table.'.ProductId AS ItemId, - '.$product_table.'.ResourceId AS ResourceId, - 11 AS ItemType, - '.$product_table.'.EditorsPick AS EdPick - FROM '.$product_table.' - '.implode(' ', $join_clauses).' - WHERE '.$where_clause.' - GROUP BY '.$product_table.'.ProductId'. - $having_clause; - - $res = $this->Conn->Query($sql); - } - - - function getHuman($type, $search_data) - { - $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; - - case 'text': - $ret = $value; - break; - - } - return '"'.$ret.'"'; - break; - } - } - - - - /** - * Set's correct page for list - * based on data provided with event - * - * @param kEvent $event - * @access private - * @see OnListBuild - */ - function SetPagination(&$event) - { - // get PerPage (forced -> session -> config -> 10) - $per_page = $this->getPerPage($event); - - - $object =& $event->getObject(); - $object->SetPerPage($per_page); - $this->Application->StoreVarDefault($event->getPrefixSpecial().'_Page', 1); - - $page = $this->Application->GetVar($event->getPrefixSpecial().'_Page'); - if (!$page) - { - $page = $this->Application->GetVar($event->getPrefixSpecial(true).'_Page'); - } - - if (!$page) - { - if( $this->Application->RewriteURLs() ) - { - $page = $this->Application->GetVar($event->Prefix.'_Page'); - if (!$page) - { - $page = $this->Application->RecallVar($event->Prefix.'_Page'); - } - if($page) $this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page); - } - else - { - $page = $this->Application->RecallVar($event->getPrefixSpecial().'_Page'); - } - } - else { - $this->Application->StoreVar($event->getPrefixSpecial().'_Page', $page); - } - - if( !$event->getEventParam('skip_counting') ) - { - $pages = $object->GetTotalPages(); - if($page > $pages) - { - $this->Application->StoreVar($event->getPrefixSpecial().'_Page', 1); - $page = 1; - } - } - - /*$cur_per_page = $per_page; - $per_page = $event->getEventParam('per_page'); - if ($per_page == 'list_next') { - - $cur_page = $page; - - $object =& $this->Application->recallObject($event->Prefix); - $object->SetPerPage(1); - $cur_item_index = $object->CurrentIndex; - - $page = ($cur_page-1) * $cur_per_page + $cur_item_index + 1; - $object->SetPerPage(1); - }*/ - - $object->SetPage($page); - } - -/* === RELATED TO IMPORT/EXPORT: BEGIN === */ - - /** - * Shows export dialog - * - * @param kEvent $event - */ - function OnExport(&$event) - { - // use old fasion (in-portal) grid - $selector_name = $this->Application->getUnitOption($event->Prefix, 'CatalogSelectorName'); - if ($selector_name) { - $selected_ids = $this->Application->GetVar($selector_name); - } - else { - $this->StoreSelectedIDs($event); - $selected_ids = $this->getSelectedIDs($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'); - $event->redirect = $export_helper->getModuleFolder($event).'/export'; - - $redirect_params = Array( 'm_opener' => 'd', - $this->Prefix.'.export_event' => 'OnNew', - 'pass' => 'all,'.$this->Prefix.'.export'); - - $event->setRedirectParams($redirect_params); - } - - /** - * 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 - */ - function restorePrimaryImage(&$event) - { - $object =& $event->getObject(); - - $has_image_info = $object->GetDBField('ImageAlt') && ($object->GetDBField('ThumbnailImage') || $object->GetDBField('FullImage')); - if (!$has_image_info) { - return false; - } - - $image_data = $object->getPrimaryImageData(); - - $image =& $this->Application->recallObject('img', null, Array('skip_autoload' => true)); - 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') return ; - $export_helper =& $this->Application->recallObject('CatItemExportHelper'); - $export_helper->setRequiredFields($event); - $this->Application->StoreVar('ImportCategory', 0); - } - - /** - * Process items selected in item_selector - * - * @param kEvent $event - */ - function OnProcessSelected(&$event) - { - $selected_ids = $this->Application->GetVar('selected_ids'); - - $dst_field = $this->Application->RecallVar('dst_field'); - - if ($dst_field == 'ItemCategory') { - // Item Edit -> Categories Tab -> New Categories - $object =& $event->getObject(); - $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']); - $this->Application->StoreVar($event->getPrefixSpecial().'_ForceNotValid', 1); // not to loose import/export values on form refresh - - $this->Application->SetVar($event->getPrefixSpecial().'_id', 0); - $this->Application->SetVar($event->getPrefixSpecial().'_event', 'OnExportBegin'); - - $passed = $this->Application->GetVar('passed'); - $this->Application->SetVar('passed', $passed.','.$event->getPrefixSpecial()); - $event->setEventParam('pass_events', true); - } - - $this->finalizePopup($event); - } - - /** - * 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) ); - $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)); - } - } - - function OnCancelAction(&$event) - { - $event->redirect_params = Array('pass' => 'all,'.$event->GetPrefixSpecial()); - $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(); - - $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 item beeing edited into temp table - * - * @param kEvent $event - */ - function OnPreSave(&$event) - { - parent::OnPreSave($event); - $use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing'); - if ($event->status == erSUCCESS && $use_pending_editing) { - // decision: clone or not clone - - $object =& $event->getObject(); - if ($object->GetID() == 0 || $object->GetDBField('OrgId') > 0) { - // new items or cloned items shouldn't be cloned again - return true; - } - $perm_helper =& $this->Application->recallObject('PermissionsHelper'); - if ($perm_helper->ModifyCheckPermission($object->GetDBField('CreatedById'), $object->GetDBField('CategoryId'), $event->Prefix) == 2) { - - // 1. clone original item - $temp_handler =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', '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 = explode(',', $this->Application->RecallVar($event->getPrefixSpecial().'_selected_ids')); - $selected_ids[ array_search($object->GetID(), $selected_ids) ] = $cloned_ids[0]; - $this->Application->StoreVar($event->getPrefixSpecial().'_selected_ids', implode(',', $selected_ids)); - - // 6. delete original item from temp table - $temp_handler->DeleteItems($event->Prefix, $event->Special, Array($object->GetID())); - } - } - } - - /** - * Sets default expiration based on module setting - * - * @param kEvent $event - */ - function OnPreCreate(&$event) - { - parent::OnPreCreate($event); - - if ($event->status == erSUCCESS) { - $object =& $event->getObject(); - $object->SetDBField('CreatedById', $this->Application->GetVar('u_id')); - } - } - - /** - * Occures before original item of item in pending editing got deleted (for hooking only) - * - * @param kEvent $event - */ - function OnBeforeDeleteOriginal(&$event) - { - - } - - /** - * Occures before an item is cloneded - * Id of ORIGINAL item is passed as event' 'id' param - * Do not call object' Update method in this event, just set needed fields! - * - * @param kEvent $event - */ - function OnBeforeClone(&$event) - { - if ($this->Application->GetVar('ResetCatBeforeClone')) { - $object =& $event->getObject(); - $object->SetDBField('CategoryId', null); - } - } - - /** - * Apply same processing to each item beeing selected in grid - * - * @param kEvent $event - * @access private - */ - function iterateItems(&$event) - { - if ($event->Name != 'OnMassApprove' && $event->Name != 'OnMassDecline') { - return parent::iterateItems($event); - } - - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { - return; - } - - $object =& $event->getObject( Array('skip_autoload' => true) ); - $ids = $this->StoreSelectedIDs($event); - - if ($ids) { - foreach ($ids as $id) { - $object->Load($id); - - switch ($event->Name) { - case 'OnMassApprove': - $ret = $object->ApproveChanges(); - break; - - case 'OnMassDecline': - $ret = $object->DeclineChanges(); - break; - } - - if (!$ret) { - $event->status = erFAIL; - $event->redirect = false; - break; - } - } - } - } -} - -?> \ No newline at end of file Index: trunk/kernel/units/general/cat_dbitem.php =================================================================== diff -u -N --- trunk/kernel/units/general/cat_dbitem.php (revision 6583) +++ trunk/kernel/units/general/cat_dbitem.php (revision 0) @@ -1,461 +0,0 @@ -CategoryPath = Array(); - } - - /** - * Set's prefix and special - * - * @param string $prefix - * @param string $special - * @access public - */ - function Init($prefix, $special, $event_params = null) - { - parent::Init($prefix, $special, $event_params); - $this->usePendingEditing = $this->Application->getUnitOption($this->Prefix, 'UsePendingEditing'); - } - - function Create($force_id=false, $system_create=false) - { - if (!$this->Validate()) return false; - - $this->SetDBField('ResourceId', $this->Application->NextResourceId()); - $this->SetDBField('Modified', adodb_mktime() ); - - if ($this->mode != 't' && !$this->Application->IsAdmin()) { - $this->SetDBField('CreatedById', $this->Application->GetVar('u_id')); - } - - if ($this->useFilenames) { - $this->checkFilename(); - $this->generateFilename(); - } - - $ret = parent::Create(); - if ($ret) { - $primary_category = $this->GetDBField('CategoryId') > 0 ? $this->GetDBField('CategoryId') : $this->Application->GetVar('m_cat_id'); - $fields_hash = Array( - 'CategoryId' => $primary_category, - 'ItemResourceId' => $this->GetField('ResourceId'), - 'PrimaryCat' => 1, - 'ItemPrefix' => $this->Prefix, - 'Filename' => $this->GetDBField('Filename'), - ); - $this->Conn->doInsert($fields_hash, $this->CategoryItemsTable()); - } - return $ret; - } - - function Update($id=null, $system_update=false) - { - $this->VirtualFields['ResourceId'] = Array(); - $this->SetDBField('Modified', adodb_mktime() ); - $this->SetDBField('ModifiedById', $this->Application->GetVar('u_id')); - - if ($this->useFilenames) { - $this->checkFilename(); - $this->generateFilename(); - } - - $ret = parent::Update($id, $system_update); - - if ($ret) { - $filename = $this->useFilenames ? $this->GetDBField('Filename') : ''; - $sql = 'UPDATE '.$this->CategoryItemsTable().' - SET Filename = '.$this->Conn->qstr($filename).' - WHERE ItemResourceId = '.$this->GetDBField('ResourceId'); - $this->Conn->Query($sql); - } - - unset($this->VirtualFields['ResourceId']); - return $ret; - } - - /** - * Returns CategoryItems table based on current item mode (temp/live) - * - * @return string - */ - function CategoryItemsTable() - { - $table = TABLE_PREFIX.'CategoryItems'; - if ($this->Application->IsTempTable($this->TableName)) { - $table = $this->Application->GetTempName($table); - } - - return $table; - } - - - function checkFilename() - { - if( !$this->GetDBField('AutomaticFilename') ) - { - $filename = $this->GetDBField('Filename'); - $this->SetDBField('Filename', $this->stripDisallowed($filename) ); - } - } - - function Copy($cat_id=null) - { - if (!isset($cat_id)) $cat_id = $this->Application->GetVar('m_cat_id'); - $this->NameCopy($cat_id); - return $this->Create($cat_id); - } - - function NameCopy($master=null, $foreign_key=null) - { - $title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField'); - if (!$title_field) return; - - $new_name = $this->GetDBField($title_field); - $cat_id = $this->Application->GetVar('m_cat_id'); - $original_checked = false; - do { - if ( preg_match('/Copy ([0-9]*) *of (.*)/', $new_name, $regs) ) { - $new_name = 'Copy '.( (int)$regs[1] + 1 ).' of '.$regs[2]; - } - elseif ($original_checked) { - $new_name = 'Copy of '.$new_name; - } - $query = 'SELECT '.$title_field.' FROM '.$this->TableName.' - LEFT JOIN '.TABLE_PREFIX.'CategoryItems ON - ('.TABLE_PREFIX.'CategoryItems.ItemResourceId = '.$this->TableName.'.ResourceId) - WHERE ('.TABLE_PREFIX.'CategoryItems.CategoryId = '.$cat_id.') AND '. - $title_field.' = '.$this->Conn->qstr($new_name); - $res = $this->Conn->GetOne($query); - $original_checked = true; - } while ($res !== false); - $this->SetDBField($title_field, $new_name); - } - - function MoveToCat($cat_id=null) - { -// $this->NameCopy(); - $cat_id = $this->Application->GetVar('m_cat_id'); - // check if the product already exists in destination cat - $query = 'SELECT PrimaryCat FROM '.TABLE_PREFIX.'CategoryItems - WHERE CategoryId = '.$cat_id.' AND ItemResourceId = '.$this->GetDBField('ResourceId'); - // if it's not found is_primary will be FALSE, if it's found but not primary it will be int 0 - $is_primary = $this->Conn->GetOne($query); - $exists = $is_primary !== false; - - if ($exists) { // if the Product already exists in destination category - if ($is_primary) return; // do nothing when we paste to primary - // if it's not primary - delete it from destination category, - // as we will move it from current primary below - $query = 'DELETE FROM '.TABLE_PREFIX.'CategoryItems - WHERE ItemResourceId = '.$this->GetDBField('ResourceId').' AND CategoryId = '.$cat_id; - $this->Conn->Query($query); - - } - $query = 'UPDATE '.TABLE_PREFIX.'CategoryItems SET CategoryId = '.$cat_id. - ' WHERE ItemResourceId = '.$this->GetDBField('ResourceId').' AND PrimaryCat = 1'; - $this->Conn->Query($query); - $this->Update(); - } - - // We need to delete CategoryItems record when deleting product - function Delete($id = null) - { - if( isset($id) ) { - $this->setID($id); - } - $this->Load($this->GetID()); - - $ret = parent::Delete(); - if ($ret) { - $query = ' DELETE FROM '.$this->CategoryItemsTable().' - WHERE ItemResourceId = '.$this->GetDBField('ResourceId'); - $this->Conn->Query($query); - } - - return $ret; - } - - /** - * Deletes item from categories - * - * @param Array $delete_category_ids - * @author Alex - */ - function DeleteFromCategories($delete_category_ids) - { - $id_field = $this->Application->getUnitOption($this->Prefix, 'IDField'); // because item was loaded before by ResourceId - - $ci_table = $this->Application->getUnitOption($this->Prefix.'-ci', 'TableName'); - $resource_id = $this->GetDBField('ResourceId'); - - $item_cats_sql = 'SELECT CategoryId FROM %s WHERE ItemResourceId = %s'; - $delete_category_items_sql = 'DELETE FROM %s WHERE ItemResourceId = %s AND CategoryId IN (%s)'; - - $category_ids = $this->Conn->GetCol( sprintf($item_cats_sql, $ci_table, $resource_id) ); - $cats_left = array_diff($category_ids, $delete_category_ids); - if(!$cats_left) - { - $sql = 'SELECT %s FROM %s WHERE ResourceId = %s'; - $ids = $this->Conn->GetCol( sprintf($sql, $id_field, $this->TableName, $resource_id) ); - - $temp =& $this->Application->recallObject($this->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler'); - $temp->DeleteItems($this->Prefix, $this->Special, $ids); - } - else - { - $this->Conn->Query( sprintf($delete_category_items_sql, $ci_table, $resource_id, implode(',', $delete_category_ids) ) ); - - $sql = 'SELECT CategoryId FROM %s WHERE PrimaryCat = 1 AND ItemResourceId = %s'; - $primary_cat_id = $this->Conn->GetCol( sprintf($sql, $ci_table, $resource_id) ); - if( count($primary_cat_id) == 0 ) - { - $sql = 'UPDATE %s SET PrimaryCat = 1 WHERE (CategoryId = %s) AND (ItemResourceId = %s)'; - $this->Conn->Query( sprintf($sql, $ci_table, reset($cats_left), $resource_id ) ); - } - } - } - - /** - * replace not allowed symbols with "_" chars + remove duplicate "_" chars in result - * - * @param string $string - * @return string - */ - function stripDisallowed($filename) - { - $filenames_helper =& $this->Application->recallObject('FilenamesHelper'); - $table = $this->mode == 't' ? $this->Application->GetTempName(TABLE_PREFIX.'CategoryItems') : TABLE_PREFIX.'CategoryItems'; - - return $filenames_helper->stripDisallowed($table, 'ItemResourceId', $this->GetDBField('ResourceId'), $filename); - } - - /* commented out because it's called only from stripDisallowed body, which is moved to helper - - function checkAutoFilename($filename) - { - $filenames_helper =& $this->Application->recallObject('FilenamesHelper'); - return $filenames_helper->checkAutoFilename($this->TableName, $this->IDField, $this->GetID(), $filename); - }*/ - - /** - * Generate item's filename based on it's title field value - * - * @return string - */ - function generateFilename() - { - if ( !$this->GetDBField('AutomaticFilename') && $this->GetDBField('Filename') ) return false; - - $title_field = $this->Application->getUnitOption($this->Prefix, 'TitleField'); - if (preg_match('/l([\d]+)_(.*)/', $title_field, $regs)) { - // if title field is multilingual, then use it's name from primary language - $title_field = 'l'.$this->Application->GetDefaultLanguageId().'_'.$regs[2]; - } - $name = $this->stripDisallowed( $this->GetDBField($title_field) ); - - if ( $name != $this->GetDBField('Filename') ) $this->SetDBField('Filename', $name); - } - - /** - * Check if value is set for required field - * - * @param string $field field name - * @param Array $params field options from config - * @return bool - * @access private - */ - function ValidateRequired($field, $params) - { - $res = true; - $error_field = isset($params['error_field']) ? $params['error_field'] : $field; - if ( getArrayValue($params,'required') ) - { - $res = ( (string) $this->FieldValues[$field] != ''); - } - if (!$res) $this->FieldErrors[$error_field]['pseudo'] = 'required'; - return $res; - } - - /** - * Adds item to other category - * - * @param int $category_id - * @param bool $is_primary - */ - function assignToCategory($category_id, $is_primary = false) - { - $table = $this->mode == 't' ? $this->Application->GetTempName(TABLE_PREFIX.'CategoryItems') : TABLE_PREFIX.'CategoryItems'; - $key_clause = '(ItemResourceId = '.$this->GetDBField('ResourceId').')'; - - // get all cateories, where item is in - $sql = 'SELECT PrimaryCat, CategoryId FROM '.$table.' WHERE '.$key_clause; - $item_categories = $this->Conn->GetCol($sql, 'CategoryId'); - if (!$item_categories) { - $item_categories = Array(); - $primary_found = false; - } - - // find primary category - foreach ($item_categories as $item_category_id => $primary_found) { - if ($primary_found) { - break; - } - } - - if ($primary_found && ($item_category_id == $category_id) && !$is_primary) { - // want to make primary category as non-primary :( - return true; - } - else if (!$primary_found) { - $is_primary = true; - } - - if ($is_primary && $item_categories) { - // reset primary mark from all other categories - $sql = 'UPDATE '.$table.' SET PrimaryCat = 0 WHERE '.$key_clause; - $this->Conn->Query($sql); - } - - // UPDATE & INSERT instead of REPLACE because CategoryItems table has no primary key defined in database - if (isset($item_categories[$category_id])) { - $sql = 'UPDATE '.$table.' SET PrimaryCat = '.($is_primary ? 1 : 0).' WHERE '.$key_clause.' AND (CategoryId = '.$category_id.')'; - $this->Conn->Query($sql); - } - else { - $sql = 'INSERT INTO '.$table.' (CategoryId,ItemResourceId,PrimaryCat,ItemPrefix,Filename) VALUES (%s,%s,%s,%s,%s)'; - $filename = $this->useFilenames ? $this->GetDBField('Filename') : ''; // because some prefixes does not use filenames - $this->Conn->Query( sprintf($sql, $category_id, $this->GetDBField('ResourceId'), $is_primary ? 1 : 0, $this->Conn->qstr($this->Prefix), $this->Conn->qstr($filename)) ); - } - // to ensure filename update after adding to another category - // this is critical since there may be an item with same filename in newly added category! - $this->Update(); - } - - /** - * Removes item from category specified - * - * @param int $category_id - */ - function removeFromCategory($category_id) - { - $sql = 'DELETE FROM '.TABLE_PREFIX.'CategoryItems WHERE (CategoryId = %s) AND (ItemResourceId = %s)'; - $this->Conn->Query( sprintf($sql, $category_id, $this->GetDBField('ResourceId')) ); - } - - /** - * Returns list of columns, that could exist in imported file - * - * @return Array - */ - function getPossibleExportColumns() - { - static $columns = null; - if (!is_array($columns)) { - $columns = array_merge($this->Fields['AvailableColumns']['options'], $this->Fields['ExportColumns']['options']); - } - return $columns; - } - - /** - * Returns item's primary image data - * - * @return Array - */ - function getPrimaryImageData() - { - $sql = 'SELECT * - FROM '.TABLE_PREFIX.'Images - WHERE (ResourceId = '.$this->GetDBField('ResourceId').') AND (DefaultImg = 1)'; - $image_data = $this->Conn->GetRow($sql); - if (!$image_data) { - // 2. no primary image, then get image with name "main" - $sql = 'SELECT * - FROM '.TABLE_PREFIX.'Images - WHERE (ResourceId = '.$this->GetDBField('ResourceId').') AND (Name = "main")'; - $image_data = $this->Conn->GetRow($sql); - } - return $image_data; - } - - function ChangeStatus($new_status) - { - $status_field = array_shift( $this->Application->getUnitOption($this->Prefix,'StatusField') ); - $this->SetDBField($status_field, $new_status); - return $this->Update(); - } - - /** - * Approves changes made to category item - * - * @return bool - */ - function ApproveChanges() - { - $original_id = $this->GetDBField('OrgId'); - - if (!($this->usePendingEditing && $original_id)) { - // non-pending copy of original link - return $this->ChangeStatus(STATUS_ACTIVE); - } - - if ($this->raiseEvent('OnBeforeDeleteOriginal', null, Array('original_id' => $original_id))) { - // delete original item, because changes made in pending copy (this item) got to be approved in this method - $temp_handler =& $this->Application->recallObject($this->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler'); - $temp_handler->DeleteItems($this->Prefix, $this->Special, Array($original_id)); - - $this->SetDBField('OrgId', 0); - return $this->ChangeStatus(STATUS_ACTIVE); - } - - return false; - } - - /** - * Decline changes made to category item - * - * @return bool - */ - function DeclineChanges() - { - $original_id = $this->GetDBField('OrgId'); - - if (!($this->usePendingEditing && $original_id)) { - // non-pending copy of original link - return $this->ChangeStatus(STATUS_DISABLED); - } - - // delete this item, because changes made in pending copy (this item) will be declined in this method - $temp_handler =& $this->Application->recallObject($this->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler'); - $temp_handler->DeleteItems($this->Prefix, $this->Special, Array($this->GetID())); - - // original item is not changed here, because it is already enabled (thrus pending copy is visible to item's owner or admin with permission) - return true; - } -} - -?> \ No newline at end of file Index: trunk/kernel/units/general/custom_fields.php =================================================================== diff -u -N --- trunk/kernel/units/general/custom_fields.php (revision 6093) +++ trunk/kernel/units/general/custom_fields.php (revision 0) @@ -1,93 +0,0 @@ -ParseConfigSQL($values_list), ','); - if (!$optionValuesStr) { - // no options, then return empty array - return Array(); - } - - $optionValuesTmp = explode(',', $optionValuesStr); - $optionValues = Array(); - foreach ($optionValuesTmp as $optionValue) { - list($key, $val) = explode('=', $optionValue); - $val = (substr($val,0,1) == '+') ? substr($val, 1) : $this->Application->Phrase($val); - $optionValues[$key] = $val; - } - return $optionValues; - } - - /** - * Replace SQL's in valueList with appropriate queried values - * - * @param string $valueString - * @return string - * @todo Apply refactoring to embedded vars stuff - */ - function ParseConfigSQL($valueString) - { - $string = trim( str_replace('', TABLE_PREFIX, $valueString) ); - - preg_match_all("|\{(.*)\}|U", $string, $embedded_vars, PREG_SET_ORDER); - - /* - in ValueList now can use globally available variables. - Usage: {$_POST['variable']|what to output if $_POST['variable'] is set} - e.g. $_POST['variable']='Hello' - Will output: what to output if Hello is set - */ - - if ($embedded_vars) { - for ($i = 0; $i < count($embedded_vars); $i++) { - $embedded_var = $embedded_vars[$i][1]; - $embedded_var_src = $embedded_vars[$i][0]; - - list($var_name, $pattern) = explode('|', $embedded_var); - eval('$var_value = (isset('.$var_name.')?'.$var_name.':false);'); - - if ($var_value !== false) { - $pattern = str_replace($var_name, $var_value, $pattern); - $string = str_replace($embedded_var_src, $pattern, $string); - } - else { - $string = str_replace($embedded_var_src, '', $string); - } - } - } - - if (preg_match_all('/(.*?)<\/SQL>/', $string, $regs)) { - $i = 0; - $sql_count = count($regs[0]); - while ($i < $sql_count) { - $string = str_replace(''.$regs[2][$i].'', $this->QueryConfigSQL($regs[2][$i], $regs[1][$i]), $string); - $i++; - } - $string = preg_replace('/(,){2,}/', ',', $string); // trim trailing commas inside string - } - - return $string; - } - - function QueryConfigSQL($sql, $plus = '') - { - $valArray = $this->Conn->Query($sql); - for($i=0; $i \ No newline at end of file Index: trunk/kernel/units/general/inp_ses_storage.php =================================================================== diff -u -N --- trunk/kernel/units/general/inp_ses_storage.php (revision 6428) +++ trunk/kernel/units/general/inp_ses_storage.php (revision 0) @@ -1,125 +0,0 @@ -SessionTimeout = $this->Application->ConfigValue('SessionTimeout'); - - $path = (BASE_PATH == '') ? '/' : BASE_PATH; -// if ( $this->Application->IsAdmin() ) $path = rtrim($path, '/').'/admin'; - $this->SetCookiePath($path); - - $cookie_name = $this->Application->ConfigValue('SessionCookieName'); - if (!$cookie_name) $cookie_name = 'sid'; - if (($this->Application->IsAdmin() && $special !== 'front') || $special == 'admin' ) { // || $this->Application->GetVar('admin') == 1 - $cookie_name = 'adm_'.$cookie_name; - } - $this->SetCookieName($cookie_name); - - $this->SetCookieDomain(SERVER_NAME); - - if( $this->Application->IsAdmin()) // && $this->Application->GetVar('admin') != 1 - { - $mode = constOn('IS_INSTALL') ? smCOOKIES_ONLY : smAUTO; - } - /*elseif ($this->Application->IsAdmin() && $this->Application->GetVar('admin') == 1) { - $mode = smCOOKIES_ONLY; - }*/ - else - { - $ses_mode = $this->Application->ConfigValue('CookieSessions'); - if ($ses_mode == 2) $mode = smAUTO; - if ($ses_mode == 1) $mode = smCOOKIES_ONLY; - if ($ses_mode == 0) $mode = smGET_ONLY; - } - $this->SetMode($mode); - - parent::Init($prefix,$special); - - if( !$this->Application->IsAdmin() && $this->GetField('PortalUserId') <= 0 ) - { - $group_list = $this->Application->ConfigValue('User_GuestGroup').','.$this->Application->ConfigValue('User_LoggedInGroup'); - $this->SetField('GroupId', $this->Application->ConfigValue('User_GuestGroup')); - $this->SetField('GroupList', $group_list); - } - } - } - -class InpSessionStorage extends SessionStorage { - - function Init($prefix,$special) - { - parent::Init($prefix,$special); - $this->setTableName(TABLE_PREFIX.'UserSession'); - $this->SessionDataTable = TABLE_PREFIX.'SessionData'; - $this->setIDField('SessionKey'); - $this->TimestampField = 'LastAccessed'; - $this->DataValueField = 'VariableValue'; - $this->DataVarField = 'VariableName'; - } - - function LocateSession($sid) - { - $res = parent::LocateSession($sid); - if ($res) { - $this->Expiration += $this->SessionTimeout; - } - return $res; - } - - function UpdateSession(&$session) - { - $time = adodb_mktime(); - // Update LastAccessed only if it's newer than 1/10 of session timeout - perfomance optimization to eliminate needless updates on every click - if ($time - $this->DirectVars['LastAccessed'] > $this->SessionTimeout/10) { - $this->SetField($session, $this->TimestampField, $time); - } - } - - - function StoreSession(&$session, $additional_fields = Array()) - { - $fields_hash = Array( 'PortalUserId' => $this->Application->IsAdmin() ? 0 : -2, // Guest - 'Language' => $this->Application->GetDefaultLanguageId(), - 'Theme' => $this->Application->GetDefaultThemeId(), - 'IpAddress' => $_SERVER['REMOTE_ADDR'], - 'GroupList' => $this->Application->ConfigValue('User_GuestGroup'), - 'CurrentTempKey'=> $session->SID, - - ); - - parent::StoreSession($session, $fields_hash); - } - - function GetExpiredSIDs() - { - $query = ' SELECT '.$this->IDField.' FROM '.$this->TableName.' WHERE '.$this->TimestampField.' < '.(adodb_mktime()-$this->SessionTimeout); - $ret = $this->Conn->GetCol($query); - if($ret) { - $this->DeleteEditTables(); - } - return $ret; - - } - - function DeleteEditTables() - { - $tables = $this->Conn->GetCol('SHOW TABLES'); - $mask_edit_table = '/'.TABLE_PREFIX.'ses_(.*)_edit_(.*)/'; - $mask_search_table = '/'.TABLE_PREFIX.'ses_(.*?)_(.*)/'; - - $sql='SELECT COUNT(*) FROM '.$this->TableName.' WHERE '.$this->IDField.' = \'%s\''; - foreach($tables as $table) - { - if( preg_match($mask_edit_table,$table,$rets) || preg_match($mask_search_table,$table,$rets) ) - { - $sid=$rets[1]; - $is_alive = $this->Conn->GetOne( sprintf($sql,$sid) ); - if(!$is_alive) $this->Conn->Query('DROP TABLE IF EXISTS '.$table); - } - } - } -} - -?> \ No newline at end of file Index: trunk/kernel/units/general/country_states.php =================================================================== diff -u -N --- trunk/kernel/units/general/country_states.php (revision 2291) +++ trunk/kernel/units/general/country_states.php (revision 0) @@ -1,101 +0,0 @@ -CountriesWithStates); - } - - /** - * Prepares states dropdown based on country selected - * - * @param kEvent $event - * @param string $state_field - * @param string $country_field - */ - function PopulateStates(&$event, $state_field, $country_field) - { - $object =& $event->getObject(); - $country_abbr = $object->GetDBField($country_field); - - if (!$country_abbr) return; - $country_id = $this->Conn->GetOne('SELECT DestId FROM '.TABLE_PREFIX.'StdDestinations WHERE DestType=1 AND DestAbbr = '.$this->Conn->qstr($country_abbr)); - if (!$country_id) return; - - $query = - 'SELECT p.Translation as DestName, sd.DestAbbr - FROM '.TABLE_PREFIX.'StdDestinations AS sd - LEFT JOIN '.TABLE_PREFIX.'Phrase AS p - ON p.Phrase = sd.DestName - WHERE - DestType=2 AND DestParentId='.$country_id.' - AND - LanguageId = '.$this->Application->GetVar('m_lang').' - ORDER BY Translation'; - - $states = $this->Conn->GetCol($query, 'DestAbbr'); - $object->Fields[$state_field]['options'] = $states; - $object->Fields[$state_field]['options'][''] = ''; - } - - /** - * Returns valid state code for state name and country code passed - * - * @param string $state_name - * @param string $country_code - * @return string - */ - function CheckState($state_name, $country_code) - { - if( !$this->CountryHasStates($country_code) ) return $state_name; - - $sql = 'SELECT sdStates.DestAbbr - FROM '.TABLE_PREFIX.'StdDestinations AS sdStates - LEFT JOIN '.TABLE_PREFIX.'Phrase AS p ON p.Phrase = sdStates.DestName - LEFT JOIN '.TABLE_PREFIX.'StdDestinations AS sdCountries ON sdStates.DestParentId = sdCountries.DestId - WHERE (sdStates.DestType = 2) AND - (sdStates.DestParentId = sdCountries.DestId) AND - (p.LanguageId = %1$s) AND - (sdCountries.DestAbbr = %2$s) AND - ( - (LOWER(sdStates.DestAbbr) = %3$s) OR (LOWER(sdStates.DestAbbr2) = %3$s) OR (LOWER(sdStates.DestName) = %3$s) OR (LOWER(p.Translation) = %3$s) - )'; - - $state_name = trim( strtolower($state_name) ); - $sql = sprintf($sql, $this->Application->GetVar('m_lang'), $this->Conn->qstr($country_code), $this->Conn->qstr($state_name) ); - - return $this->Conn->GetOne($sql); - } - - function CheckStateField(&$event, $state_field, $country_field) - { - - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if($items_info) - { - list($id, $field_values) = each($items_info); - if( isset($field_values[$state_field]) && isset($field_values[$country_field]) ) - { - $user_state = getArrayValue($field_values,$state_field); - $valid_state = $this->CheckState($user_state, getArrayValue($field_values,$country_field) ); - if($valid_state !== false) - { - $field_values[$state_field] = $valid_state; - $items_info[$id] = $field_values; - $this->Application->SetVar( $event->getPrefixSpecial(true), $items_info); - } - else - { - $object =& $event->getObject(); - $object->Fields[$state_field]['options'][$user_state] = $user_state; - $object->SetError($state_field, 'invalid_state', 'la_invalid_state'); - } - } - } - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/brackets.php =================================================================== diff -u -N --- trunk/kernel/units/general/brackets.php (revision 3097) +++ trunk/kernel/units/general/brackets.php (revision 0) @@ -1,349 +0,0 @@ -min_field = $min_field; - $this->max_field = $max_field; - $this->default_values = $default_values; - if(isset($default_start_value)) - { - $this->defaultStartValue = $default_start_value; - } - } - - - /** - * Adds 5 more empty brackets to brackets - * - * @param kEvent $event - */ - function OnMoreBrackets(&$event) - { - $field_values = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - - $object =& $event->getObject(); - - foreach($field_values as $id => $record) - { - if($record[$this->max_field] == '∞') $field_values[$id][$this->max_field] = -1; - } - - $new_id = (int)$this->Conn->GetOne('SELECT MIN('.$object->IDField.') FROM '.$object->TableName); - if($new_id > 0) $new_id = 0; - do - { - $new_id--; - }while( $this->arraySearch($field_values, $object->IDField, $new_id) ); - - - $last_max_qty = $this->Conn->GetOne('SELECT MAX('.$this->max_field.') FROM '.$object->TableName); - $min_qty = $this->Conn->GetOne('SELECT MIN('.$this->max_field.') FROM '.$object->TableName); - - if($min_qty == -1) $last_max_qty = -1; - if(!$last_max_qty) $last_max_qty = $this->defaultStartValue; - - - for($i = $new_id; $i > $new_id - 5; $i--) - { - $field_values[$i][$object->IDField] = $i; - $field_values[$i][$this->min_field] = ($i == $new_id-4 && $last_max_qty != -1) ? $last_max_qty : ''; - $field_values[$i][$this->max_field] = ($i == $new_id-4 && $last_max_qty != -1) ? -1 : ''; - $field_values[$i] = array_merge_recursive2($field_values[$i], $this->default_values); - } - - $event->CallSubEvent('OnPreSaveBrackets'); - - $this->Application->SetVar($event->getPrefixSpecial(true), $field_values); - } - - /** - * Adds infinity bracket - * - * @param kEvent $event - */ - function OnInfinity(&$event) - { - $object =& $event->getObject(); - $infinite_exists = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$object->TableName.' WHERE '.$this->max_field.' = -1'); - $field_values = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - /*if(is_array($field_values)) - { - foreach($field_values as $values) - { - $infinite_exists = $infinite_exists || ($values[$this->max_field] == -1); - } - }*/ - - if($infinite_exists == 0) - { - reset($field_values); - $last_bracket = end($field_values); - $new_id = (int)$this->Conn->GetOne('SELECT MIN('.$object->IDField.') FROM '.$object->TableName); - - $brackets_exist = (int)$this->Conn->GetOne('SELECT COUNT(*) FROM '.$object->TableName); - - if($new_id > 0) $new_id = 0; - do - { - $new_id--; - }while( $this->arraySearch($field_values, $object->IDField, $new_id) ); - - $infinite_bracket[$object->IDField] = $new_id; - $infinite_bracket[$this->min_field] = ($brackets_exist > 0) ? $last_bracket[$this->max_field] : $this->defaultStartValue; - $infinite_bracket[$this->max_field] = '-1'; - $infinite_bracket = array_merge_recursive2($infinite_bracket, $this->default_values); - - $field_values[$new_id] = $infinite_bracket; - reset($field_values); - - $this->Application->SetVar($event->getPrefixSpecial(true), $field_values); - } - } - - /** - * Saves brackets to database - * - * @param kEvent $event - */ - function OnPreSaveBrackets(&$event) - { - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true)); - if($items_info) - { - $object =& $event->getObject(); - - $linked_info = $object->getLinkedInfo(); - $stored_ids = $this->Conn->GetCol('SELECT '.$object->IDField.' FROM '.$object->TableName.' WHERE '.$linked_info['ForeignKey'].' = '.$linked_info['ParentId']); - - uasort($items_info, Array(&$this, 'compareBrackets') ); - - foreach ($items_info as $item_id => $values) - { - - if (in_array($item_id, $stored_ids)) { //if it's already exist - $object->SetDefaultValues(); - $object->Load($item_id); - $object->SetFieldsFromHash($values); - if (!$object->Validate()) { - unset($stored_ids[array_search($item_id, $stored_ids)]); - $event->redirect = false; - continue; - } - if( $object->Update($item_id) ) - { - $event->status = erSUCCESS; - } - else - { - $event->status = erFAIL; - $event->redirect = false; - break; - } - unset( $stored_ids[ array_search($item_id, $stored_ids) ] ); - } - else { - $object->SetDefaultValues(); - $object->SetFieldsFromHash($values); - $object->SetDBField($linked_info['ForeignKey'], $linked_info['ParentId']); - - if( $object->Create() ) - { - $object->setTempID(); - $event->status = erSUCCESS; - } - } - } - - // delete - foreach ($stored_ids as $stored_id) - { - $this->Conn->Query('DELETE FROM '.$object->TableName.' WHERE '.$object->IDField.' = '.$stored_id); - } - - } - } - - function arrangeBrackets(&$event) - { - $object =& $event->getObject(); - - $temp = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - - foreach($temp as $id => $record) - { - if( $record[$this->max_field] == '∞' ) - { - $temp[$id][$this->max_field] = -1; - } - } - - $temp_orig = $temp; - reset($temp); - if( is_array($temp) ) - { - // array to store max values (2nd column) - $end_values = Array(); - - // get minimal value of Min - $first_elem = current($temp); - $start = $first_elem[$this->min_field]; - if(!$start) $start = $this->defaultStartValue; - - foreach($temp as $id => $record) - { - if( - // MAX is less than start - ($record[$this->max_field] <= $start && $record[$this->max_field] != -1) || - // Max is empty - !$record[$this->max_field] || - // Max already defined in $end_values - (array_search($record[$this->max_field], $end_values) !== false) - ) { // then delete from brackets list - unset($temp[$id]); - } - else { // this is when ok - add to end_values list - $end_values[] = $record[$this->max_field]; - } - } - - // sort brackets by 2nd column (Max values) - uasort($temp, Array(&$this, 'compareBrackets') ); - reset($temp); - $first_item = each($temp); - $first_item_key = $first_item['key']; - - $linked_info = $object->getLinkedInfo(); - $sql = 'SELECT %s FROM %s WHERE %s = %s'; - $ids = $this->Conn->GetCol( sprintf($sql, $object->IDField, $object->TableName, $linked_info['ForeignKey'], $linked_info['ParentId']) ); - if( is_array($ids) ) - { - usort($ids, Array(&$this, 'sortBracketIDs') ); - } - - $min_id = min( min($ids) - 1, -1 ); - - foreach($temp as $key => $record) - { - $temp[$key][$this->min_field] = $start; - $start = $temp[$key][$this->max_field]; - } - } - - $this->Application->SetVar($event->getPrefixSpecial(true), $temp); - return $temp; - } - - function compareBrackets($bracket1, $bracket2) // ap_bracket_comp - { - $bracket1_min = $bracket1[$this->min_field]; - $bracket1_max = $bracket1[$this->max_field]; - - $bracket2_min = $bracket2[$this->min_field]; - $bracket2_max = $bracket2[$this->max_field]; - - // limits - if( ($bracket1_min != '') && ($bracket1_max == '') && ($bracket2_min != '') && ($bracket2_max != '') ) return 1; - if( ($bracket1_min != '') && ($bracket1_max == '') && ($bracket2_min == '') && ($bracket2_max == '') ) return -1; - if( ($bracket1_max == '') && ($bracket2_max != '') ) return 1; - if( ($bracket1_max != '') && ($bracket2_max == '') ) return -1; - - - if( ( ($bracket1_max > $bracket2_max) && ($bracket2_max != -1) ) || ( ($bracket1_max == -1) && ($bracket2_max != -1) ) ) - { - return 1; - } - elseif( ($bracket1_max < $bracket2_max) || ( ($bracket2_max == -1) && ($bracket1_max != -1) ) ) - { - return -1; - } - else - { - return 0; - } - } - - function sortBracketIDs($first_id, $second_id) // pr_bracket_id_sort - { - $first_abs = abs($first_id); - $second_abs = abs($second_id); - - $first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs; - $second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs; - - if($first_sign != $second_sign) - { - if($first_id > $second_id) - { - $bigger =& $first_abs; - $smaller =& $second_abs; - } - else - { - $bigger =& $second_abs; - $smaller =& $first_abs; - } - $smaller = $bigger + $smaller; - } - - return ($first_abs > $second_abs) ? 1 : ($first_abs < $second_abs ? -1 : 0); - } - - /** - * Searches through submitted grid data to find record with specific value in specific field - * - * @param Array $records // grid data from REQUEST - * @param string $field - * @param string $value - * @return bool - */ - function arraySearch($records, $field, $value) // check_array - { - foreach ($records as $record) - { - if ($record[$field] == $value) - { - return true; - } - } - return false; - } - - /** - * Replate infinity mark with -1 before saving to db - * - * @param kEvent $event - */ - function replaceInfinity(&$event) - { - $object =& $event->getObject(); - if($object->GetDBField($this->max_field) == '∞') $object->SetDBField($this->max_field, -1); - } - - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/cat_tag_processor.php =================================================================== diff -u -N --- trunk/kernel/units/general/cat_tag_processor.php (revision 6583) +++ trunk/kernel/units/general/cat_tag_processor.php (revision 0) @@ -1,216 +0,0 @@ -PermHelper = $this->Application->recallObject('PermissionsHelper'); - } - - function ItemIcon($params) - { - $object =& $this->Application->recallObject($this->getPrefixSpecial(),$this->Prefix, $params); - - $grids = $this->Application->getUnitOption($this->Prefix,'Grids'); - $icons =& $grids[ $params['grid'] ]['Icons']; - - $status_fields = $this->Application->getUnitOption($this->Prefix,'StatusField'); - if (!$status_fields) return $icons['default']; - - $value = $object->GetDBField($status_fields[0]); // sets base status icon - if ($value == STATUS_ACTIVE) { - if( $object->GetDBField('IsPop') ) $value = 'POP'; - if( $object->GetDBField('IsHot') ) $value = 'HOT'; - if( $object->GetDBField('IsNew') ) $value = 'NEW'; - if( $object->GetDBField('EditorsPick') ) $value = 'PICK'; - } - - return isset($icons[$value]) ? $icons[$value] : $icons['default']; - } - - /** - * Allows to create valid mod-rewrite compatible link to module item - * - * @param Array $params - * @param string $id_prefix - * @return string - */ - function ItemLink($params, $id_prefix) - { - $params = array_merge($params, Array('pass' => 'm,'.$this->Prefix) ); - - $item_id = isset($params[$id_prefix.'_id']) && $params[$id_prefix.'_id']; - if (!$item_id) { - $item_id = $this->Application->GetVar($this->getPrefixSpecial().'_id'); - if (!$item_id) { - $item_id = $this->Application->GetVar($this->Prefix.'_id'); - } - } - $params[$this->Prefix.'_id'] = $item_id; - - $object =& $this->getObject($params); - $params['m_cat_id'] = $object->GetDBField('CategoryId'); - $params['pass_category'] = 1; - - return $this->Application->ProcessParsedTag('m', 't', $params); - } - - function CategoryPath($params) - { - if (!isset($params['cat_id'])) { - $params['cat_id'] = $this->Application->RecallVar($params['session_var'], 0); - } - - return $this->Application->ProcessParsedTag('c', 'CategoryPath', $params); - } - - function BuildListSpecial($params) - { - if ($this->Special != '') return $this->Special; - if ( isset($params['parent_cat_id']) ) { - $parent_cat_id = $params['parent_cat_id']; - } - else { - $parent_cat_id = $this->Application->GetVar('c_id'); - if (!$parent_cat_id) { - $parent_cat_id = $this->Application->GetVar('m_cat_id'); - } - } - - $recursive = isset($params['recursive']); - - $types = $this->SelectParam($params, 'types'); - $except = $this->SelectParam($params, 'except'); - - if ($types.$except.$recursive == '') { - return parent::BuildListSpecial($params); - } - - $special = crc32($parent_cat_id.$types.$except.$recursive); - return $special; - } - - function ExportStatus($params) - { - $export_object =& $this->Application->recallObject('CatItemExportHelper'); - - $event = new kEvent($this->getPrefixSpecial().':OnDummy'); - - $action_method = 'perform'.ucfirst($this->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 ($this->Special == 'import') { - $this->Application->StoreVar('PermCache_UpdateRequired', 1); - $this->Application->Redirect('categories/cache_updater', Array('m_opener' => 'r', 'pass' => 'm', 'continue' => 1, 'no_amp' => 1)); - } - elseif ($this->Special == 'export') { - $template = $this->Application->getUnitOption($this->Prefix, 'ModuleFolder').'/'.$this->Special.'_finish'; - $this->Application->Redirect($template, Array('pass' => 'all')); - } - } - - $export_options = $export_object->loadOptions($event); - return $export_options['start_from'] * 100 / $export_options['total_records']; - } - - function CatalogItemCount($params) - { - $object =& $this->GetList($params); - if (!$object->Counted) { - $object->CountRecs(); - } - return $object->NoFilterCount != $object->RecordsCount ? $object->RecordsCount.' / '.$object->NoFilterCount : $object->RecordsCount; - } - - function ListReviews($params) - { - $prefix = $this->Prefix.'-rev'; - $review_tag_processor =& $this->Application->recallObject($prefix.'.item_TagProcessor'); - return $review_tag_processor->PrintList($params); - } - - function ReviewCount($params) - { - $review_tag_processor =& $this->Application->recallObject('rev.item_TagProcessor'); - return $review_tag_processor->TotalRecords($params); - } - - function InitCatalogTab($params) - { - $tab_params['mode'] = $this->Application->GetVar('tm'); // single/multi selection possible - $tab_params['special'] = $this->Application->GetVar('ts'); // use special for this tab - $tab_params['dependant'] = $this->Application->GetVar('td'); // is grid dependant on categories grid - - // set default params (same as in catalog) - if ($tab_params['mode'] === false) $tab_params['mode'] = 'multi'; - if ($tab_params['special'] === false) $tab_params['special'] = ''; - if ($tab_params['dependant'] === false) $tab_params['dependant'] = 'yes'; - - // pass params to block with tab content - $params['name'] = $params['render_as']; - $params['prefix'] = trim($this->Prefix.'.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.'); - $params['cat_prefix'] = trim('c.'.($tab_params['special'] ? $tab_params['special'] : $this->Special), '.'); - $params['tab_mode'] = $tab_params['mode']; - $params['tab_dependant'] = $tab_params['dependant']; - $params['show_category'] = $tab_params['special'] == 'showall' ? 1 : 0; // this is advanced view -> show category name - - return $this->Application->ParseBlock($params, 1); - } - - /** - * Show CachedNavbar of current item primary category - * - * @param Array $params - * @return string - */ - function CategoryName($params) - { - // show category cachednavbar of - $object =& $this->getObject($params); - $category_id = isset($params['cat_id']) ? $params['cat_id'] : $object->GetDBField('CategoryId'); - - $category_path = $this->Application->getCache('category_paths', $category_id); - if ($category_path === false) { - // not chached - if ($category_id > 0) { - $category_path = trim($this->CategoryName( Array('cat_id' => 0) ).' > '.str_replace('&|&', ' > ', $object->GetDBField('CachedNavbar')), ' > '); - } - else { - $category_path = $this->Application->Phrase( $this->Application->ConfigValue('Root_Name') ); - } - $this->Application->setCache('category_paths', $category_id, $category_path); - } - return $category_path; - } - - /** - * Allows to determine if original value should be shown - * - * @param Array $params - * @return bool - */ - function DisplayOriginal($params) - { - // original id found & greather then zero + show original - $display_original = isset($params['display_original']) && $params['display_original']; - - $object =& $this->getObject($params); - $perm_value = $this->PermHelper->ModifyCheckPermission($object->GetDBField('CreatedById'), $object->GetDBField('CategoryId'), $this->Prefix); - - return $display_original && ($perm_value == 1) && $this->Application->GetVar($this->Prefix.'.original_id'); - } - - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/main_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/general/main_event_handler.php (revision 6428) +++ trunk/kernel/units/general/main_event_handler.php (revision 0) @@ -1,129 +0,0 @@ -Conn =& $this->Application->GetADODBConnection(); - } - - /** - * Created url part for this module - * - * @param kEvent $event - */ - function BuildEnv(&$event) - { - $prefix_special = $event->getPrefixSpecial(); - $url_params = $event->getEventParam('url_params'); - - $query_vars = $this->Application->getUnitOption($event->Prefix, 'QueryString'); - - //if pass events is off and event is not implicity passed - if ( !$event->getEventParam('pass_events') && !isset($url_params[$prefix_special.'_event']) ) - { - $url_params[$prefix_special.'_event'] = ''; // remove event from url if requested - //otherwise it will use value from get_var - } - - if(!$query_vars) return true; - - $processed_params = Array(); - foreach($query_vars as $index => $var_name) - { - //if value passed in params use it, otherwise use current from application - $var_name = $prefix_special.'_'.$var_name; - $processed_params[$var_name] = isset( $url_params[$var_name] ) ? $url_params[$var_name] : $this->Application->GetVar($var_name); - if ( isset($url_params[$var_name]) ) unset( $url_params[$var_name] ); - } - - $ret = ''; - $default_language_id = $this->Application->GetDefaultLanguageId(); - if( $processed_params['m_lang'] && ($processed_params['m_lang'] != $default_language_id) ) - { - $language_name = $this->Application->getCache('language_names', $processed_params['m_lang']); - if ($language_name === false) { - $sql = 'SELECT PackName - FROM '.TABLE_PREFIX.'Language - WHERE LanguageId = '.$processed_params['m_lang']; - $language_name = $this->Conn->GetOne($sql); - $this->Application->setCache('language_names', $processed_params['m_lang'], $language_name); - } - $ret .= $language_name.'/'; - } - - $default_theme_id = $this->Application->GetDefaultThemeId(); - if( $processed_params['m_theme'] && ($processed_params['m_theme'] != $default_theme_id) ) - { - $theme_name = $this->Application->getCache('theme_names', $processed_params['m_theme']); - if ($theme_name === false) { - $sql = 'SELECT Name - FROM '.TABLE_PREFIX.'Theme - WHERE ThemeId = '.$processed_params['m_theme']; - $theme_name = $this->Conn->GetOne($sql); - $this->Application->setCache('theme_names', $processed_params['m_theme'], $theme_name); - - } - $ret .= $theme_name.'/'; - } - - if ($processed_params['m_cat_id'] > 0 && isset($url_params['pass_category']) && $url_params['pass_category']) { - $ret .= $this->Application->getFilename('c', $processed_params['m_cat_id']).'/'; - $url_params['category_processed'] = true; - } - else { -// $url_params['no_category'] = 1; // for debugging - } - unset($url_params['pass_category']); // unset it just in case - - $force_page_adding = false; - if (getArrayValue($url_params, 'reset')) - { - unset($url_params['reset']); - if ($processed_params['m_cat_id']) - { - $processed_params['m_cat_page'] = 1; - $force_page_adding = true; - } - } - - if( $processed_params['m_cat_page'] > 1 || $force_page_adding ) - { - $ret = preg_replace('/(.*)\//', '\\1', $ret).'_'.$processed_params['m_cat_page'].'/'; - } - - $template = getArrayValue($url_params, 't'); - $category_template = $processed_params['m_cat_id'] ? $this->Application->getCache('category_templates', $processed_params['m_cat_id']) : ''; - - // remove template from url if it is category index cached template - if ($template == $category_template || strtolower($template) == '__default__') { - $template = ''; - } - - if ($template) { - $ret .= $template.'/'; - } - unset($url_params['t']); - - $event->setEventParam('url_params', $url_params); - $event->setEventParam('env_string', strtolower($ret) ); - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/cat_dbitem_export.php =================================================================== diff -u -N --- trunk/kernel/units/general/cat_dbitem_export.php (revision 6583) +++ trunk/kernel/units/general/cat_dbitem_export.php (revision 0) @@ -1,1397 +0,0 @@ -cacheTable = TABLE_PREFIX.'ImportCache'; - } - - /** - * Returns value from cache if found or false otherwise - * - * @param string $type - * @param int $key - * @return mixed - */ - function getFromCache($type, $key) - { - return getArrayValue($this->cache, $type, $key); - } - - /** - * Adds value to be cached - * - * @param string $type - * @param int $key - * @param mixed $value - */ - function addToCache($type, $key, $value, $is_new = true) - { -// if (!isset($this->cache[$type])) $this->cache[$type] = Array(); - $this->cache[$type][$key] = $value; - if ($is_new) { - $this->cacheStatus[$type][$key] = true; - } - } - - function storeCache($cache_types) - { - $cache_types = explode(',', $cache_types); - - $values_sql = ''; - foreach ($cache_types as $cache_type) { - $sql_mask = '('.$this->Conn->qstr($cache_type).',%s,%s),'; - $cache = getArrayValue($this->cacheStatus, $cache_type); - if (!$cache) $cache = Array(); - foreach ($cache as $var_name => $cache_status) { - $var_value = $this->cache[$cache_type][$var_name]; - $values_sql .= sprintf($sql_mask, $this->Conn->qstr($var_name), $this->Conn->qstr($var_value) ); - } - } - $values_sql = preg_replace('/(.*),$/', '\\1', $values_sql); - if ($values_sql) { - $sql = 'INSERT INTO '.$this->cacheTable.'(`CacheName`,`VarName`,`VarValue`) VALUES '.$values_sql; - $this->Conn->Query($sql); - } - - } - - function loadCache() - { - $sql = 'SELECT * FROM '.$this->cacheTable; - $records = $this->Conn->Query($sql); - - $this->cache = Array(); - foreach ($records as $record) { - $this->addToCache($record['CacheName'], $record['VarName'], $record['VarValue'], false); - } - } - - /** - * Fill required fields with dummy values - * - * @param kEvent $event - */ - function fillRequiredFields(&$event, &$object, $set_status = false) - { - if ($object == $this->false) { - $object =& $event->getObject(); - } - - $has_empty = false; - $fields = array_keys($object->Fields); - foreach ($fields as $field_name) - { - $field_options =& $object->Fields[$field_name]; - if (isset($object->VirtualFields[$field_name]) || !getArrayValue($field_options, 'required') ) continue; - if ( $object->GetDBField($field_name) ) continue; - - $formatter_class = getArrayValue($field_options, 'formatter'); - if ($formatter_class) // not tested - { - $formatter =& $this->Application->recallObject($formatter_class); - $sample_value = $formatter->GetSample($field_name, $field_options, $object); - } - - $has_empty = true; - $object->SetDBField($field_name, isset($sample_value) && $sample_value ? $sample_value : 'no value'); - } - - if ($set_status && $has_empty) { - $object->SetDBField('Status', 0); - } - } - - /** - * Verifies that all user entered export params are correct - * - * @param kEvent $event - */ - function verifyOptions(&$event) - { - if ($this->Application->RecallVar($event->getPrefixSpecial().'_ForceNotValid')) - { - $this->Application->StoreVar($event->getPrefixSpecial().'_ForceNotValid', 0); - return false; - } - - $this->fillRequiredFields($event, $this->false); - - $object =& $event->getObject(); - $cross_unique_fields = Array('FieldsSeparatedBy', 'FieldsEnclosedBy'); - if (($object->GetDBField('CategoryFormat') == 1) || ($event->Special == 'import')) // in one field - { - $object->setRequired('CategorySeparator', true); - $cross_unique_fields[] = 'CategorySeparator'; - } - - $ret = $object->Validate(); - - // check if cross unique fields has no same values - foreach ($cross_unique_fields as $field_index => $field_name) - { - if (getArrayValue($object->FieldErrors, $field_name, 'pseudo') == 'required') continue; - - $check_fields = $cross_unique_fields; - unset($check_fields[$field_index]); - - foreach ($check_fields as $check_field) - { - if ($object->GetDBField($field_name) == $object->GetDBField($check_field)) - { - $object->SetError($check_field, 'unique'); - } - } - } - - if ($event->Special == 'import') - { - $this->exportOptions = $this->loadOptions($event); - - $automatic_fields = ($object->GetDBField('FieldTitles') == 1); - $object->setRequired('ExportColumns', !$automatic_fields); - $category_prefix = '__CATEGORY__'; - if ( $automatic_fields && ($this->exportOptions['SkipFirstRow']) ) { - $this->openFile($event); - $this->exportOptions['ExportColumns'] = $this->readRecord(); - $this->closeFile(); - - // remove additional (non-parseble columns) - foreach ($this->exportOptions['ExportColumns'] as $field_index => $field_name) { - if (!$this->validateField($field_name, $object)) { - unset($this->exportOptions['ExportColumns'][$field_index]); - } - } - $category_prefix = ''; - } - - // 1. check, that we have column definitions - if (!$this->exportOptions['ExportColumns']) { - $object->setError('ExportColumns', 'required'); - $ret = false; - } - else { - // 1.1. check that all required fields are present in imported file - $missing_columns = Array(); - foreach ($object->Fields as $field_name => $field_options) { - if ($object->SkipField($field_name)) continue; - if (getArrayValue($field_options, 'required') && !in_array($field_name, $this->exportOptions['ExportColumns']) ) { - $missing_columns[] = $field_name; - $object->setError('ExportColumns', 'required_fields_missing', 'la_error_RequiredColumnsMissing'); - $ret = false; - } - } - - if (!$ret && $this->Application->isDebugMode()) { - $this->Application->Debugger->appendHTML('Missing required for import/export:'); - $this->Application->Debugger->dumpVars($missing_columns); - } - } - - - // 2. check, that we have only mixed category field or only separated category fields - $category_found['mixed'] = false; - $category_found['separated'] = false; - - foreach ($this->exportOptions['ExportColumns'] as $import_field) { - if (preg_match('/^'.$category_prefix.'Category(Path|[0-9]+)/', $import_field, $rets)) { - $category_found[$rets[1] == 'Path' ? 'mixed' : 'separated'] = true; - } - } - if ($category_found['mixed'] && $category_found['separated']) { - $object->SetError('ExportColumns', 'unique_category', 'la_error_unique_category_field'); - $ret = false; - } - - // 3. check, that duplicates check fields are selected & present in imported fields - if ($this->exportOptions['ReplaceDuplicates']) { - if ($this->exportOptions['CheckDuplicatesMethod'] == 1) { - $check_fields = Array($object->IDField); - } - else { - $check_fields = $this->exportOptions['DuplicateCheckFields'] ? explode('|', substr($this->exportOptions['DuplicateCheckFields'], 1, -1)) : Array(); - $object =& $event->getObject(); - - $language_id = $this->Application->GetDefaultLanguageId(); - foreach ($check_fields as $index => $check_field) { - foreach ($object->Fields as $field_name => $field_options) { - if ($field_name == 'l'.$language_id.'_'.$check_field) { - $check_fields[$index] = 'l'.$language_id.'_'.$check_field; - break; - } - } - } - } - $this->exportOptions['DuplicateCheckFields'] = $check_fields; - - if (!$check_fields) { - $object->setError('CheckDuplicatesMethod', 'required'); - $ret = false; - } - else { - foreach ($check_fields as $check_field) { - $check_field = preg_replace('/^cust_(.*)/', 'Custom_\\1', $check_field); - if (!in_array($check_field, $this->exportOptions['ExportColumns'])) { - $object->setError('ExportColumns', 'required'); - $ret = false; - break; - } - } - } - } - $this->saveOptions($event); - } - - return $ret; - } - - /** - * Returns filename to read import data from - * - * @return string - */ - function getImportFilename() - { - if ($this->exportOptions['ImportSource'] == 1) - { - $ret = $this->exportOptions['ImportFilename']; // ['name']; commented by Kostja - } - else { - $ret = $this->exportOptions['ImportLocalFilename']; - } - return EXPORT_PATH.'/'.$ret; - } - - /** - * Returns filename to write export data to - * - * @return string - */ - function getExportFilename() - { - return EXPORT_PATH.'/'.$this->exportOptions['ExportFilename'].'.'.$this->getFileExtension(); - } - - /** - * Opens file required for export/import operations - * - * @param kEvent $event - */ - function openFile(&$event) - { - if ($event->Special == 'export') { - $write_mode = ($this->exportOptions['start_from'] == 0) ? 'w' : 'a'; - $this->filePointer = fopen($this->getExportFilename(), $write_mode); - } - else { - $this->filePointer = fopen($this->getImportFilename(), 'r'); - } - - // skip UTF-8 BOM Modifier - $first_chars = fread($this->filePointer, 3); - if (bin2hex($first_chars) != 'efbbbf') { - fseek($this->filePointer, 0); - } - } - - /** - * Closes opened file - * - */ - function closeFile() - { - fclose($this->filePointer); - } - - function getCustomSQL() - { - $ml_formatter =& $this->Application->recallObject('kMultiLanguage'); - - $custom_sql = ''; - foreach ($this->customFields as $custom_id => $custom_name) { - $custom_sql .= 'custom_data.'.$ml_formatter->LangFieldName('cust_'.$custom_id).' AS cust_'.$custom_name.', '; - } - - return preg_replace('/(.*), /', '\\1', $custom_sql); - } - - function getPlainExportSQL($count_only = false) { - if ($count_only && isset($this->exportOptions['ForceCountSQL'])) return $this->exportOptions['ForceCountSQL']; - if (!$count_only && isset($this->exportOptions['ForceSelectSQL'])) return $this->exportOptions['ForceSelectSQL']; - - $items_list =& $this->Application->recallObject($this->curItem->Prefix.'.export-items-list', $this->curItem->Prefix.'_List'); - $items_list->SetPerPage(-1); - return $items_list->GetSelectSQL($count_only); - - - if ($this->exportOptions['export_ids'] === false) - { - // get links from current category & all it's subcategories - $join_clauses = Array(); - - $custom_sql = $this->getCustomSQL(); - if ($custom_sql) { - $custom_table = $this->Application->getUnitOption($this->curItem->Prefix.'-cdata', 'TableName'); - $join_clauses[$custom_table.' custom_data'] = 'custom_data.ResourceId = item_table.ResourceId'; - } - - $sql = 'SELECT item_table.*'.($custom_sql ? ', '.$custom_sql : '').' - FROM '.$this->curItem->TableName.' item_table'; - - foreach ($join_clauses as $table_name => $join_expression) { - $sql .= ' LEFT JOIN '.$table_name.' ON '.$join_expression; - } - $sql .= ' WHERE 1'; - - $sql .= ' ORDER BY item_table.'.$this->curItem->IDField.' ASC'; // NEW - } - else { - // get only selected links - $sql = 'SELECT item_table.* - FROM '.$this->curItem->TableName.' item_table - WHERE '.$this->curItem->IDField.' IN ('.implode(',', $this->exportOptions['export_ids']).')'; - } - - if (!$count_only) - { - $sql .= ' LIMIT '.$this->exportOptions['start_from'].','.EXPORT_STEP; - } - else { - $sql = preg_replace("/^.*SELECT(.*?)FROM(?!_)/is", "SELECT COUNT(*) AS count FROM ", $sql); - } - - return $sql; - } - - function getExportSQL($count_only = false) - { - if (!$this->Application->getUnitOption($this->curItem->Prefix, 'CatalogItem')) { - return $this->GetPlainExportSQL($count_only); // in case this is not a CategoryItem - } - - if ($this->exportOptions['export_ids'] === false) - { - // get links from current category & all it's subcategories - $join_clauses = Array(); - - $custom_sql = $this->getCustomSQL(); - if ($custom_sql) { - $custom_table = $this->Application->getUnitOption($this->curItem->Prefix.'-cdata', 'TableName'); - $join_clauses[$custom_table.' custom_data'] = 'custom_data.ResourceId = item_table.ResourceId'; - } - - $join_clauses[TABLE_PREFIX.'CategoryItems ci'] = 'ci.ItemResourceId = item_table.ResourceId'; - $join_clauses[TABLE_PREFIX.'Category c'] = 'c.CategoryId = ci.CategoryId'; - - $sql = 'SELECT item_table.*, ci.CategoryId'.($custom_sql ? ', '.$custom_sql : '').' - FROM '.$this->curItem->TableName.' item_table'; - - foreach ($join_clauses as $table_name => $join_expression) { - $sql .= ' LEFT JOIN '.$table_name.' ON '.$join_expression; - } - $sql .= ' WHERE '; - - if ($this->exportOptions['export_cats_ids'][0] == 0) - { - $sql .= '1'; - } - else { - foreach ($this->exportOptions['export_cats_ids'] as $category_id) { - $sql .= '(c.ParentPath LIKE "%|'.$category_id.'|%") OR '; - } - $sql = preg_replace('/(.*) OR $/', '\\1', $sql); - } - - $sql .= ' ORDER BY ci.PrimaryCat DESC'; // NEW - } - else { - // get only selected links - $sql = 'SELECT item_table.*, '.$this->exportOptions['export_cats_ids'][0].' AS CategoryId - FROM '.$this->curItem->TableName.' item_table - WHERE '.$this->curItem->IDField.' IN ('.implode(',', $this->exportOptions['export_ids']).')'; - } - - if (!$count_only) - { - $sql .= ' LIMIT '.$this->exportOptions['start_from'].','.EXPORT_STEP; - } - else { - $sql = preg_replace("/^.*SELECT(.*?)FROM(?!_)/is", "SELECT COUNT(*) AS count FROM ", $sql); - } - - return $sql; - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function performExport(&$event) - { - $this->exportOptions = $this->loadOptions($event); - $this->exportFields = $this->exportOptions['ExportColumns']; - $this->curItem =& $event->getObject( Array('skip_autoload' => true) ); - $this->customFields = $this->Application->getUnitOption($event->Prefix, 'CustomFields'); - $this->openFile($event); - - if ($this->exportOptions['start_from'] == 0) // first export step - { - if (!getArrayValue($this->exportOptions, 'IsBaseCategory')) { - $this->exportOptions['IsBaseCategory'] = 0; - } - - if ($this->exportOptions['IsBaseCategory'] ) { - $sql = 'SELECT ParentPath - FROM '.TABLE_PREFIX.'Category - WHERE CategoryId = '.$this->Application->GetVar('m_cat_id'); - $this->exportOptions['BaseLevel'] = substr_count($this->Conn->GetOne($sql), '|') - 1; // level to cut from other categories - } - - // 1. export field titles if required - if ($this->exportOptions['IncludeFieldTitles']) - { - $data_array = Array(); - foreach ($this->exportFields as $export_field) - { - $data_array = array_merge($data_array, $this->getFieldCaption($export_field)); - } - $this->writeRecord($data_array); - } - $this->exportOptions['total_records'] = $this->Conn->GetOne( $this->getExportSQL(true) ); - } - - // 2. export data - $records = $this->Conn->Query( $this->getExportSQL() ); - $records_exported = 0; - foreach ($records as $record_info) { - $this->curItem->Clear(); - $this->curItem->SetDBFieldsFromHash($record_info); - $this->setCurrentID(); - $this->curItem->raiseEvent('OnAfterItemLoad', $this->curItem->GetID() ); - - $data_array = Array(); - foreach ($this->exportFields as $export_field) - { - $data_array = array_merge($data_array, $this->getFieldValue($export_field) ); - } - $this->writeRecord($data_array); - $records_exported++; - } - $this->closeFile(); - - $this->exportOptions['start_from'] += $records_exported; - $this->saveOptions($event); - - return $this->exportOptions; - } - - function getItemFields() - { - // just in case dummy user selected automtic mode & moved columns too :( - return array_merge($this->curItem->Fields['AvailableColumns']['options'], $this->curItem->Fields['ExportColumns']['options']); - } - - /** - * Checks if field really belongs to importable field list - * - * @param string $field_name - * @param kCatDBItem $object - * @return bool - */ - function validateField($field_name, &$object) - { - // 1. convert custom field - $field_name = preg_replace('/^Custom_(.*)/', '__CUSTOM__\\1', $field_name); - - // 2. convert category field (mixed version & serparated version) - $field_name = preg_replace('/^Category(Path|[0-9]+)/', '__CATEGORY__Category\\1', $field_name); - - $valid_fields = $object->getPossibleExportColumns(); - return isset($valid_fields[$field_name]) || isset($valid_fields['__VIRTUAL__'.$field_name]); - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function performImport(&$event) - { - if (!$this->exportOptions) { - // load import options in case if not previously loaded in verification function - $this->exportOptions = $this->loadOptions($event); - } - - $backup_category_id = $this->Application->GetVar('m_cat_id'); - $this->Application->SetVar('m_cat_id', (int)$this->Application->RecallVar('ImportCategory') ); - - $this->openFile($event); - - $bytes_imported = 0; - if ($this->exportOptions['start_from'] == 0) // first export step - { - // 1st time run - if ($this->exportOptions['SkipFirstRow']) { - $this->readRecord(); - $this->exportOptions['start_from'] = ftell($this->filePointer); - $bytes_imported = ftell($this->filePointer); - } - - $current_category_id = $this->Application->GetVar('m_cat_id'); - if ($current_category_id > 0) { - $sql = 'SELECT ParentPath FROM '.TABLE_PREFIX.'Category WHERE CategoryId = '.$current_category_id; - $this->exportOptions['ImportCategoryPath'] = $this->Conn->GetOne($sql); - } - else { - $this->exportOptions['ImportCategoryPath'] = ''; - } - $this->exportOptions['total_records'] = filesize($this->getImportFilename()); - } - else { - $this->loadCache(); - } - - $this->exportFields = $this->exportOptions['ExportColumns']; - $this->addToCache('category_parent_path', $this->Application->GetVar('m_cat_id'), $this->exportOptions['ImportCategoryPath']); - - // 2. import data - $this->dummyCategory =& $this->Application->recallObject('c.-tmpitem', 'c', Array('skip_autoload' => true)); - fseek($this->filePointer, $this->exportOptions['start_from']); - - while (($bytes_imported < IMPORT_CHUNK) && !feof($this->filePointer)) { - $data = $this->readRecord(); - if ($data) { - if ($this->exportOptions['ReplaceDuplicates']) { - // set fields used as keys for replace duplicates code - $this->resetImportObject($event, IMPORT_TEMP, $data); - } - - $this->processCurrentItem($event, $data); - } - $bytes_imported = ftell($this->filePointer) - $this->exportOptions['start_from']; - } - - $this->closeFile(); - $this->Application->SetVar('m_cat_id', $backup_category_id); - - $this->exportOptions['start_from'] += $bytes_imported; - $this->storeCache('new_ids'); - - $this->saveOptions($event); - - if ($this->exportOptions['start_from'] == $this->exportOptions['total_records']) { - $this->Conn->Query('TRUNCATE TABLE '.$this->cacheTable); - } - - return $this->exportOptions; - } - - function setCurrentID() - { - $this->curItem->setID( $this->curItem->GetDBField($this->curItem->IDField) ); - } - - function setFieldValue($field_index, $value) - { - if (empty($value)) { - $value = null; - } - - $field_name = getArrayValue($this->exportFields, $field_index); - if ($field_name == 'ResourceId') { - return false; - } - - if (substr($field_name, 0, 7) == 'Custom_') { - $field_name = 'cust_'.substr($field_name, 7); - $this->curItem->SetField($field_name, $value); - } - elseif ($field_name == 'CategoryPath' || $field_name == '__CATEGORY__CategoryPath') { - $this->curItem->CategoryPath = $value ? explode($this->exportOptions['CategorySeparator'], $value) : Array(); - } - elseif (substr($field_name, 0, 8) == 'Category') { - $this->curItem->CategoryPath[ (int)substr($field_name, 8) - 1 ] = $value; - } - elseif (substr($field_name, 0, 20) == '__CATEGORY__Category') { - $this->curItem->CategoryPath[ (int)substr($field_name, 20) ] = $value; - } - elseif (substr($field_name, 0, 11) == '__VIRTUAL__') { - $field_name = substr($field_name, 11); - $this->curItem->SetField($field_name, $value); - } - else { - $this->curItem->SetField($field_name, $value); - } - - $pseudo_error = getArrayValue($this->curItem->FieldErrors, $field_name, 'pseudo'); - if ($pseudo_error) { - $this->curItem->SetDBField($field_name, null); - unset($this->curItem->FieldErrors[$field_name]); - } - } - - function resetImportObject(&$event, $object_type, $record_data = null) - { - switch ($object_type) { - case IMPORT_TEMP: - $this->curItem =& $event->getObject( Array('skip_autoload' => true) ); - break; - - case IMPORT_LIVE: - $this->curItem =& $this->Application->recallObject($event->Prefix.'.-tmpitem'.$event->Special, $event->Prefix, Array('skip_autoload' => true)); - break; - } - $this->curItem->Clear(); - $this->customFields = $this->Application->getUnitOption($event->Prefix, 'CustomFields'); - - if (isset($record_data)) { - $this->setImportData($record_data); - } - } - - function setImportData($record_data) - { - foreach ($record_data as $field_index => $field_value) { - $this->setFieldValue($field_index, $field_value); - } - $this->setCurrentID(); - } - - - function getItemCategory() - { - static $lang_prefix = null; - $backup_category_id = $this->Application->GetVar('m_cat_id'); - - $category_id = $this->getFromCache('category_names', implode(':', $this->curItem->CategoryPath)); - if ($category_id) { - $this->Application->SetVar('m_cat_id', $category_id); - return $category_id; - } - - if (is_null($lang_prefix)) { - $lang_prefix = 'l'.$this->Application->GetVar('m_lang').'_'; - } - - foreach ($this->curItem->CategoryPath as $category_index => $category_name) { - if (!$category_name) continue; - $category_key = crc32( implode(':', array_slice($this->curItem->CategoryPath, 0, $category_index + 1) ) ); - - $category_id = $this->getFromCache('category_names', $category_key); - if ($category_id === false) { - // get parent category path to search only in it - $current_category_id = $this->Application->GetVar('m_cat_id'); -// $parent_path = $this->getParentPath($current_category_id); - - // get category id from database by name - $sql = 'SELECT CategoryId - FROM '.TABLE_PREFIX.'Category - WHERE ('.$lang_prefix.'Name = '.$this->Conn->qstr($category_name).') AND (ParentId = '.$current_category_id.')'; - $category_id = $this->Conn->GetOne($sql); - - if ($category_id === false) { - // category not in db -> create - $category_fields = Array( $lang_prefix.'Name' => $category_name, $lang_prefix.'Description' => $category_name, - 'Status' => STATUS_ACTIVE, 'ParentId' => $current_category_id, 'AutomaticFilename' => 1 - ); - $this->dummyCategory->SetDBFieldsFromHash($category_fields); - if ($this->dummyCategory->Create()) { - $category_id = $this->dummyCategory->GetID(); - $this->addToCache('category_parent_path', $category_id, $this->dummyCategory->GetDBField('ParentPath')); - $this->addToCache('category_names', $category_key, $category_id); - } - } - else { - $this->addToCache('category_names', $category_key, $category_id); - } - } - - if ($category_id) { - $this->Application->SetVar('m_cat_id', $category_id); - } - } - if (!$this->curItem->CategoryPath) { - $category_id = $backup_category_id; - } - - return $category_id; - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function processCurrentItem(&$event, $record_data) - { - $save_method = 'Create'; - $load_keys = Array(); - - // create/update categories - $backup_category_id = $this->Application->GetVar('m_cat_id'); - - // perform replace duplicates code - if ($this->exportOptions['ReplaceDuplicates']) { - // get replace keys first, then reset current item to empty one - $category_id = $this->getItemCategory(); - if ($this->exportOptions['CheckDuplicatesMethod'] == 1) { - if ($this->curItem->GetID()) { - $load_keys = Array($this->curItem->IDField => $this->curItem->GetID()); - } - } - else { - $key_fields = $this->exportOptions['DuplicateCheckFields']; - foreach ($key_fields as $key_field) { - $load_keys[$key_field] = $this->curItem->GetDBField($key_field); - } - } - - $this->resetImportObject($event, IMPORT_LIVE); - - if (count($load_keys)) { - $where_clause = ''; - foreach ($load_keys as $field_name => $field_value) { - if (preg_match('/^cust_(.*)/', $field_name, $regs)) { - $custom_id = array_search($regs[1], $this->customFields); - $field_name = 'l'.$this->Application->GetVar('m_lang').'_cust_'.$custom_id; - $where_clause .= '(custom_data.`'.$field_name.'` = '.$this->Conn->qstr($field_value).') AND '; - } - else { - $where_clause .= '(item_table.`'.$field_name.'` = '.$this->Conn->qstr($field_value).') AND '; - } - - } - $where_clause = preg_replace('/(.*) AND $/', '\\1', $where_clause); - - $item_id = $this->getFromCache('new_ids', crc32($where_clause)); - if (!$item_id) { - if ($this->exportOptions['CheckDuplicatesMethod'] == 2) { - // by other fields - $parent_path = $this->getParentPath($category_id); - $where_clause = '(c.ParentPath LIKE "'.$parent_path.'%") AND '.$where_clause; - } - - $cdata_table = $this->Application->getUnitOption($event->Prefix.'-cdata', 'TableName'); - $sql = 'SELECT '.$this->curItem->IDField.' - FROM '.$this->curItem->TableName.' item_table - LEFT JOIN '.$cdata_table.' custom_data ON custom_data.ResourceId = item_table.ResourceId - LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON ci.ItemResourceId = item_table.ResourceId - LEFT JOIN '.TABLE_PREFIX.'Category c ON c.CategoryId = ci.CategoryId - WHERE '.$where_clause; - $item_id = $this->Conn->GetOne($sql); - } - $save_method = $item_id && $this->curItem->Load($item_id) ? 'Update' : 'Create'; - if ($save_method == 'Update') { - // replace id from csv file with found id - $record_data[ array_search($this->curItem->IDField, $this->exportFields) ] = $item_id; - } - } - - $this->setImportData($record_data); - } - else { - $this->resetImportObject($event, IMPORT_LIVE, $record_data); - $category_id = $this->getItemCategory(); - } - - // create main record - if ($save_method == 'Create') { - $this->fillRequiredFields($this->false, $this->curItem, true); - } - -// $sql_start = getmicrotime(); - if (!$this->curItem->$save_method()) { - return false; - } -// $sql_end = getmicrotime(); -// $this->saveLog('SQL ['.$save_method.'] Time: '.($sql_end - $sql_start).'s'); - - if ($load_keys && ($save_method == 'Create') && $this->exportOptions['ReplaceDuplicates']) { - // map new id to old id - $this->addToCache('new_ids', crc32($where_clause), $this->curItem->GetID() ); - } - - // assign item to categories - $this->curItem->assignToCategory($category_id, false); - - $this->Application->SetVar('m_cat_id', $backup_category_id); - return true; - } - - /*function saveLog($msg) - { - static $first_time = true; - - $fp = fopen(FULL_PATH.'/sqls.log', $first_time ? 'w' : 'a'); - fwrite($fp, $msg."\n"); - fclose($fp); - - $first_time = false; - }*/ - - /** - * Returns category parent path, if possible, then from cache - * - * @param int $category_id - * @return string - */ - function getParentPath($category_id) - { - $parent_path = $this->getFromCache('category_parent_path', $category_id); - if ($parent_path === false) { - $sql = 'SELECT ParentPath - FROM '.TABLE_PREFIX.'Category - WHERE CategoryId = '.$category_id; - $parent_path = $this->Conn->GetOne($sql); - $this->addToCache('category_parent_path', $category_id, $parent_path); - } - return $parent_path; - } - - function getFileExtension() - { - return $this->exportOptions['ExportFormat'] == 1 ? 'csv' : 'xml'; - } - - function getLineSeparator($option = 'LineEndings') - { - return $this->exportOptions[$option] == 1 ? "\r\n" : "\n"; - } - - /** - * Returns field caption for any exported field - * - * @param string $field - * @return string - */ - function getFieldCaption($field) - { - if (substr($field, 0, 10) == '__CUSTOM__') - { - $ret = 'Custom_'.substr($field, 10, strlen($field) ); - } - elseif (substr($field, 0, 12) == '__CATEGORY__') - { - return $this->getCategoryTitle(); - } - elseif (substr($field, 0, 11) == '__VIRTUAL__') { - $ret = substr($field, 11); - } - else - { - $ret = $field; - } - - return Array($ret); - } - - /** - * Returns requested field value (including custom fields and category fields) - * - * @param string $field - * @return string - */ - function getFieldValue($field) - { - if (substr($field, 0, 10) == '__CUSTOM__') { - $field = 'cust_'.substr($field, 10, strlen($field)); - $ret = $this->curItem->GetField($field); - } - elseif (substr($field, 0, 12) == '__CATEGORY__') { - return $this->getCategoryPath(); - } - elseif (substr($field, 0, 11) == '__VIRTUAL__') { - $field = substr($field, 11); - return $this->curItem->GetField($field); - } - else - { - $ret = $this->curItem->GetField($field); - } - - $ret = str_replace("\r\n", $this->getLineSeparator('LineEndingsInside'), $ret); - return Array($ret); - } - - /** - * Returns category field(-s) caption based on export mode - * - * @return string - */ - function getCategoryTitle() - { - // category path in separated fields - $category_count = $this->getMaxCategoryLevel(); - if ($this->exportOptions['CategoryFormat'] == 1) - { - // category path in one field - return $category_count ? Array('CategoryPath') : Array(); - } - else - { - $i = 0; - $ret = Array(); - while ($i < $category_count) { - $ret[] = 'Category'.($i + 1); - $i++; - } - return $ret; - } - } - - /** - * Returns category path in required format for current link - * - * @return string - */ - function getCategoryPath() - { - $category_id = $this->curItem->GetDBField('CategoryId'); - $category_path = $this->getFromCache('category_path', $category_id); - if (!$category_path) - { - $ml_formatter =& $this->Application->recallObject('kMultiLanguage'); - $sql = 'SELECT '.$ml_formatter->LangFieldName('CachedNavbar').' - FROM '.TABLE_PREFIX.'Category - WHERE CategoryId = '.$category_id; - $category_path = $this->Conn->GetOne($sql); - $category_path = $category_path ? explode('&|&', $category_path) : Array(); - - if ($this->exportOptions['IsBaseCategory']) { - $i = $this->exportOptions['BaseLevel']; - while ($i > 0) { - array_shift($category_path); - $i--; - } - } - - $category_count = $this->getMaxCategoryLevel(); - if ($this->exportOptions['CategoryFormat'] == 1) { - // category path in single field - $category_path = $category_count ? Array( implode($this->exportOptions['CategorySeparator'], $category_path) ) : Array(); - } - else { - // category path in separated fields - $levels_used = count($category_path); - if ($levels_used < $category_count) - { - $i = 0; - while ($i < $category_count - $levels_used) { - $category_path[] = ''; - $i++; - } - } - } - $this->addToCache('category_path', $category_id, $category_path); - } - - return $category_path; - } - - /** - * Get maximal category deep level from links beeing exported - * - * @return int - */ - function getMaxCategoryLevel() - { - static $max_level = -1; - - if ($max_level != -1) - { - return $max_level; - } - - $sql = 'SELECT IF(c.CategoryId IS NULL, 0, MAX( LENGTH(c.ParentPath) - LENGTH( REPLACE(c.ParentPath, "|", "") ) - 1 )) - FROM '.$this->curItem->TableName.' item_table - LEFT JOIN '.TABLE_PREFIX.'CategoryItems ci ON item_table.ResourceId = ci.ItemResourceId - LEFT JOIN '.TABLE_PREFIX.'Category c ON c.CategoryId = ci.CategoryId - WHERE (ci.PrimaryCat = 1) AND '; - - $where_clause = ''; - if ($this->exportOptions['export_ids'] === false) { - // get links from current category & all it's subcategories - if ($this->exportOptions['export_cats_ids'][0] == 0) { - $where_clause = 1; - } - else { - foreach ($this->exportOptions['export_cats_ids'] as $category_id) { - $where_clause .= '(c.ParentPath LIKE "%|'.$category_id.'|%") OR '; - } - $where_clause = preg_replace('/(.*) OR $/', '\\1', $where_clause); - } - } - else { - // get only selected links - $where_clause = $this->curItem->IDField.' IN ('.implode(',', $this->exportOptions['export_ids']).')'; - } - - $max_level = $this->Conn->GetOne($sql.'('.$where_clause.')'); - - if ($this->exportOptions['IsBaseCategory'] ) { - $max_level -= $this->exportOptions['BaseLevel']; - } - - return $max_level; - } - - /** - * Saves one record to export file - * - * @param Array $fields_hash - */ - function writeRecord($fields_hash) - { - fputcsv2($this->filePointer, $fields_hash, $this->exportOptions['FieldsSeparatedBy'], $this->exportOptions['FieldsEnclosedBy'], $this->getLineSeparator() ); - } - - function readRecord() - { - return fgetcsv($this->filePointer, 10000, $this->exportOptions['FieldsSeparatedBy'], $this->exportOptions['FieldsEnclosedBy']); - } - - function saveOptions(&$event, $options = null) - { - if (!isset($options)) { - $options = $this->exportOptions; - } - $this->Application->StoreVar($event->getPrefixSpecial().'_options', serialize($options) ); - } - - function loadOptions(&$event) - { - return unserialize($this->Application->RecallVar($event->getPrefixSpecial().'_options')); - } - - /** - * Sets correct available & export fields - * - * @param kEvent $event - */ - function prepareExportColumns(&$event) - { - $object =& $event->getObject( Array('skip_autoload' => true) ); - - $available_columns = Array(); - - if ($this->Application->getUnitOption($event->Prefix, 'CatalogItem')) { - // category field (mixed) - $available_columns['__CATEGORY__CategoryPath'] = 'CategoryPath'; - - if ($event->Special == 'import') { - // category field (separated fields) - $max_level = $this->Application->ConfigValue('MaxImportCategoryLevels'); - $i = 0; - while ($i < $max_level) { - $available_columns['__CATEGORY__Category'.($i + 1)] = 'Category'.($i + 1); - $i++; - } - } - } - - // db fields - foreach ($object->Fields as $field_name => $field_options) - { - if (!$object->SkipField($field_name)) - { - $available_columns[$field_name] = $field_name.(getArrayValue($field_options, 'required') ? '*' : ''); - } - } - - $handler =& $this->Application->recallObject($event->Prefix.'_EventHandler'); - $available_columns = array_merge_recursive2($available_columns, $handler->getCustomExportColumns($event)); - - // custom fields - foreach ($object->customFields as $custom_id => $custom_name) - { - $available_columns['__CUSTOM__'.$custom_name] = $custom_name; - } - - // columns already in use - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if ($items_info) - { - list($item_id, $field_values) = each($items_info); - $export_keys = $field_values['ExportColumns']; - $export_keys = $export_keys ? explode('|', substr($export_keys, 1, -1) ) : Array(); - } - else { - $export_keys = Array(); - } - - $export_columns = Array(); - foreach ($export_keys as $field_key) - { - $field_name = $this->getExportField($field_key); - $export_columns[$field_key] = $field_name; - unset($available_columns[$field_key]); - } - - $options = $object->GetFieldOptions('ExportColumns'); - $options['options'] = $export_columns; - $object->SetFieldOptions('ExportColumns', $options); - - $options = $object->GetFieldOptions('AvailableColumns'); - $options['options'] = $available_columns; - $object->SetFieldOptions('AvailableColumns', $options); - - $this->updateImportFiles($event); - $this->PrepareExportPresets($event); - } - - function PrepareExportPresets(&$event) - { - $object =& $event->getObject( Array('skip_autoload' => true) ); - $options = $object->GetFieldOptions('ExportPresets'); - - $user =& $this->Application->recallObject('u'); - $export_settings = $user->getPersistantVar('export_settings'); - if (!$export_settings) return ; - $export_settings = unserialize($export_settings); - - if (!isset($export_settings[$event->Prefix])) return ; - - - $export_presets = array(''=>''); - foreach ($export_settings[$event->Prefix] as $key => $val) { - $export_presets[implode('|', $val['ExportColumns'])] = $key; - } - - $options['options'] = $export_presets; - $object->SetFieldOptions('ExportPresets', $options); - } - - function getExportField($field_key) - { - $prepends = Array('__CUSTOM__', '__CATEGORY__'); - foreach ($prepends as $prepend) - { - if (substr($field_key, 0, strlen($prepend) ) == $prepend) - { - $field_key = substr($field_key, strlen($prepend), strlen($field_key) ); - break; - } - } - return $field_key; - } - - /** - * Updates uploaded files list - * - * @param kEvent $event - */ - function updateImportFiles(&$event) - { - if ($event->Special != 'import') { - return false; - } - - $object =& $event->getObject(); - - $import_filenames = Array(); - - if ($folder_handle = opendir(EXPORT_PATH)) { - while (false !== ($file = readdir($folder_handle))) { - if (is_dir(EXPORT_PATH.'/'.$file) || substr($file, 0, 1) == '.' || strtolower($file) == 'cvs' || strtolower($file) == 'dummy' || filesize(EXPORT_PATH.'/'.$file) == 0) continue; - - $file_size = formatSize( filesize(EXPORT_PATH.'/'.$file) ); - $import_filenames[$file] = $file.' ('.$file_size.')'; - } - closedir($folder_handle); - } - - $options = $object->GetFieldOptions('ImportLocalFilename'); - $options['options'] = $import_filenames; - $object->SetFieldOptions('ImportLocalFilename', $options); - } - - /** - * Returns module folder - * - * @param kEvent $event - * @return string - */ - function getModuleFolder(&$event) - { - return $this->Application->getUnitOption($event->Prefix, 'ModuleFolder'); - } - - /** - * Export form validation & processing - * - * @param kEvent $event - */ - function OnExportBegin(&$event) - { - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if (!$items_info) - { - $items_info = unserialize( $this->Application->RecallVar($event->getPrefixSpecial().'_ItemsInfo') ); - $this->Application->SetVar($event->getPrefixSpecial(true), $items_info); - } - - list($item_id, $field_values) = each($items_info); - - $object =& $event->getObject( Array('skip_autoload' => true) ); - $object->SetFieldsFromHash($field_values); - $field_values['ImportFilename'] = $object->GetDBField('ImportFilename'); //if upload formatter has renamed the file during moving !!! - - $object->setID($item_id); - $this->setRequiredFields($event); - - $export_object =& $this->Application->recallObject('CatItemExportHelper'); - - // save export/import options - if ($event->Special == 'export') - { - $export_ids = $this->Application->RecallVar($event->Prefix.'_export_ids'); - $export_cats_ids = $this->Application->RecallVar($event->Prefix.'_export_cats_ids'); - - // used for multistep export - $field_values['export_ids'] = $export_ids ? explode(',', $export_ids) : false; - $field_values['export_cats_ids'] = $export_cats_ids ? explode(',', $export_cats_ids) : Array( $this->Application->GetVar('m_cat_id') ); - } - - $field_values['ExportColumns'] = $field_values['ExportColumns'] ? explode('|', substr($field_values['ExportColumns'], 1, -1) ) : Array(); - $field_values['start_from'] = 0; - - $this->Application->HandleEvent($nevent, $event->Prefix.':OnBeforeExportBegin', array('options'=>$field_values)); - $field_values = $nevent->getEventParam('options'); - - $export_object->saveOptions($event, $field_values); - - if( $export_object->verifyOptions($event) ) - { - if ($object->GetDBField('ExportSavePreset')) { - $name = $object->GetDBField('ExportPresetName'); - $user =& $this->Application->recallObject('u'); - $export_settings = $user->getPersistantVar('export_settings'); - $export_settings = $export_settings ? unserialize($export_settings) : array(); - $export_settings[$event->Prefix][$name] = $field_values; - $user->setPersistantVar('export_settings', serialize($export_settings)); - } - - $progress_t = $this->Application->RecallVar('export_progress_t'); - if ($progress_t) { - $this->Application->RemoveVar('export_progress_t'); - } - else { - $progress_t = $export_object->getModuleFolder($event).'/'.$event->Special.'_progress'; - } - $event->redirect = $progress_t; - } - else - { - // make uploaded file local & change source selection - $filename = getArrayValue($field_values, 'ImportFilename'); - if ($filename) { - $export_object->updateImportFiles($event); - $object->SetDBField('ImportSource', 2); - $field_values['ImportSource'] = 2; - $object->SetDBField('ImportLocalFilename', $filename); - $field_values['ImportLocalFilename'] = $filename; - $export_object->saveOptions($event, $field_values); - } - - $event->status = erFAIL; - $event->redirect = false; - } - } - - /** - * set required fields based on import or export params - * - * @param kEvent $event - */ - function setRequiredFields(&$event) - { - $required_fields['common'] = Array('FieldsSeparatedBy', 'LineEndings', 'CategoryFormat'); - - $required_fields['export'] = Array('ExportFormat', 'ExportFilename','ExportColumns'); - - $object =& $event->getObject(); - if ($object->GetDBField('ExportSavePreset')) { - $required_fields['export'][] = 'ExportPresetName'; - } - - $required_fields['import'] = Array('FieldTitles', 'ImportSource', 'CheckDuplicatesMethod'); // ImportFilename, ImportLocalFilename - - if ($event->Special == 'import') - { - $import_source = Array(1 => 'ImportFilename', 2 => 'ImportLocalFilename'); - $used_field = $import_source[ $object->GetDBField('ImportSource') ]; - - $required_fields[$event->Special][] = $used_field; - $object->Fields[$used_field]['error_field'] = 'ImportSource'; - - if ($object->GetDBField('FieldTitles') == 2) $required_fields[$event->Special][] = 'ExportColumns'; // manual field titles - } - - $required_fields = array_merge($required_fields['common'], $required_fields[$event->Special]); - foreach ($required_fields as $required_field) { - $object->setRequired($required_field, true); - } - } - - } - -?> Index: trunk/kernel/units/general/xml_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/xml_helper.php (revision 6093) +++ trunk/kernel/units/general/xml_helper.php (revision 0) @@ -1,202 +0,0 @@ -Clear(); // in case if Parse method is called more then one time - $xml_parser = xml_parser_create(); - xml_set_element_handler( $xml_parser, Array(&$this, 'startElement'), Array(&$this, 'endElement') ); - xml_set_character_data_handler( $xml_parser, Array(&$this, 'characterData') ); - if (!xml_parse($xml_parser, $xml, 1)) { - $this->RootElement =& new kXMLNode('ERROR', array('code'=>xml_get_error_code($xml_parser),'message'=>xml_error_string(xml_get_error_code($xml_parser)))); - trigger_error(sprintf('XML error: %s at line %d'), - xml_error_string(xml_get_error_code($xml_parser)), - xml_get_current_line_number($xml_parser), E_USER_WARNING); - } - xml_parser_free($xml_parser); - return $this->RootElement; - } - - function startElement(&$Parser, &$Elem, $Attrs) - { - $parent =& $this->CurrentElement; - $this->CurrentElement =& new kXMLNode($Elem, $Attrs); - if (is_null($this->RootElement)) { - $this->RootElement =& $this->CurrentElement; - } - if (!is_null($parent)) { - $parent->AddChild($this->CurrentElement); - } - } - - function characterData($Parser, $Line) - { - $this->CurrentElement->AppendData($Line); - } - - function endElement($Parser, $Elem) - { - if ($this->CurrentElement->Parent != null) { - $this->CurrentElement =& $this->CurrentElement->Parent; - } - } - - function Clear() - { - $this->RootElement = null; - $this->CurrentElement = null; - } -} - -class kXMLNode { - var $Name = null; - var $Attributes = array(); - var $Children = array(); - var $Data = null; - - var $firstChild = null; - var $lastChild = null; - /** - * Parent node - * - * @var kXMLNode - */ - var $Parent = null; - /** - * Node position relative to other nodes of it's parent - * - * @var int - */ - var $Position = 0; - - function kXMLNode($name, $attrs = array()) - { - $this->Name = $name; - $this->Attributes = $attrs; - } - - function SetParent(&$elem) - { - $this->Parent =& $elem; - } - - /** - * Adds new child to current node - * - * @param kXMLNode $a_child - */ - function AddChild(&$a_child) - { - $node_count = count($this->Children); - $a_child->Position = $node_count; - - if ($node_count == 0) { - $this->firstChild =& $a_child; - $this->lastChild =& $a_child; - } - else { - $this->lastChild =& $a_child; - } - - $this->Children[] =& $a_child; - $a_child->SetParent($this); - } - - function AppendData($data) - { - $this->Data .= $data; - } - - function &GetChild($path) - { - $entries = explode('/', strtoupper($path)); - $cur = array_shift($entries); - if ($cur == $this->Name) $cur = array_shift($entries); - if (!$cur) return $this; - if (!isset($this->Children[$cur])) return false; - $left = implode('/', $entries); - if (!$left) return $this->Children[$cur]; - return $this->Children[$cur]->GetChild($left); - } - - function GetChildValue($path) - { - $child =& $this->GetChild($path); - if ($child !== false) { - return $child->Data; - } - } - - function &GetChildByPosition($position) - { - if ($position < count($this->Children) ) { - return $this->Children[$position]; - } - else { - $false = false; - return $false; - } - } - - function &FindChild($name) - { - $name = strtoupper($name); - if ($this->Name == $name) return $this; -// if (isset($this->Children[$name])) return $this->Children[$name]; -// $children = array_keys($this->Children); - foreach ($this->Children as $elem) - { - $child =& $elem->FindChild($name); - if ($child !== false) - { - return $child; - } - } - return false; - } - - function FindChildValue($name, $attr=null) - { - $child =& $this->FindChild($name); - if ($child !== false) { - if (isset($attr)) { - return $child->Attributes[strtoupper($attr)]; - } - return $child->Data; - } - } - - /** - * Returns next node to this, false in case of end list - * - * @return kXMLNode - */ - function &NextSibling() - { - if (!is_null($this->Parent)) { - $ret =& $this->Parent->GetChildByPosition($this->Position + 1); - return $ret; - } - else { - $false = false; - return $false; - } - } -} - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/multilanguage.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/multilanguage.php (revision 6093) +++ trunk/kernel/units/general/helpers/multilanguage.php (revision 0) @@ -1,240 +0,0 @@ -languageCount = $this->getLanguageCount(); - } - - /** - * Returns language count in system (always is divisible by 5) - * - */ - function getLanguageCount() - { - $table_name = $this->Application->getUnitOption('lang', 'TableName'); - $languages_count = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$table_name); - if (!$languages_count) { - // during installation we have not languages, but we need to created custom field columns - $languages_count = 1; - } - return $languages_count + 5 - ( $languages_count % 5 ? ($languages_count % 5) : 5 ); - } - - - function scanTable($mask) - { - $i = 0; - $fields_found = 0; - $fields = array_keys($this->curStructure); - - foreach ($fields as $field_name) { - if (preg_match($mask, $field_name)) { - $fields_found++; - } - } - return $fields_found; - } - - function readTableStructure($table_name, $refresh=false) - { - static $structure_status = Array(); - - if ($refresh || !getArrayValue($structure_status, $table_name)) { - $this->curStructure = $this->Conn->Query('DESCRIBE '.$table_name, 'Field'); - $this->curIndexCount = count($this->Conn->Query('SHOW INDEXES FROM '.$table_name)); - $structure_status[$table_name] = true; - } - } - - /** - * Creates missing multilanguage fields in table by specified prefix - * - * @param string $prefix - * @param bool $refresh Forces config field structure to be re-read from database - */ - function createFields($prefix, $refresh = false) - { - if ($refresh) { - $this->Application->HandleEvent( new kEvent($prefix.':OnCreateCustomFields') ); - } - - $table_name = $this->Application->getUnitOption($prefix, 'TableName'); - $this->curFields = $this->Application->getUnitOption($prefix, 'Fields'); - - if (!($table_name && $this->curFields) ) { - // invalid config found or prefix not found - return true; - } - - $sqls = Array(); - $this->readTableStructure($table_name, $refresh); - - foreach($this->curFields as $field_name => $field_options) - { - if (getArrayValue($field_options, 'formatter') == 'kMultiLanguage') { - if (isset($field_options['master_field'])) { - unset($this->curFields[$field_name]); - continue; - } - - $created_count = $this->getCreatedCount($field_name); - $create_count = $this->languageCount - $created_count; - if ($create_count > 0) { - // `l77_Name` VARCHAR( 255 ) NULL DEFAULT '0'; - $field_mask = Array(); - $field_mask['name'] = 'l%s_'.$field_name; - $field_mask['null'] = getArrayValue($field_options, 'not_null') ? 'NOT NULL' : 'NULL'; - - if ($this->curSourceField) { - $default_value = $this->getFieldParam('Default') != 'NULL' ? $this->Conn->qstr($this->getFieldParam('Default')) : $this->getFieldParam('Default'); - $field_mask['type'] = $this->getFieldParam('Type'); - } - else { - $default_value = is_null($field_options['default']) ? 'NULL' : $this->Conn->qstr($field_options['default']); - $field_mask['type'] = $field_options['db_type']; - } - $field_mask['default'] = 'DEFAULT '.$default_value; - $field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null'].' '.$field_mask['default']; - - $sqls[] = 'ALTER TABLE '.$table_name.( $this->generateAlterSQL($field_mask, $created_count + 1, $create_count) ); - } - } - } - - foreach ($sqls as $sql_query) { - $this->Conn->Query($sql_query); - } - } - - function deleteField($prefix, $custom_id) - { - $table_name = $this->Application->getUnitOption($prefix, 'TableName'); - $sql = 'DESCRIBE '.$table_name.' "l%_cust_'.$custom_id.'"'; - $fields = $this->Conn->GetCol($sql); - - $sql = 'ALTER TABLE '.$table_name.' '; - $sql_template = 'DROP COLUMN %s, '; - foreach ($fields as $field_name) { - $sql .= sprintf($sql_template, $field_name); - } - $sql = preg_replace('/(.*), $/', '\\1', $sql); - $this->Conn->Query($sql); - } - - /** - * Returns parameter requested of current source field - * - * @param string $param_name - * @return string - */ - function getFieldParam($param_name) - { - return $this->curStructure[$this->curSourceField][$param_name]; - } - - function getCreatedCount($field_name) - { - $ret = $this->scanTable('/^l[\d]+_'.preg_quote($field_name, '/').'/'); - if (!$ret) { - // no multilingual fields at all (but we have such field without language prefix) - $original_found = $this->scanTable('/'.preg_quote($field_name, '/').'/'); - $this->curSourceField = $original_found ? $field_name : false; - } - else { - $this->curSourceField = 'l1_'.$field_name; - } - return $ret; - } - /** - * Returns ALTER statement part for adding required fields to table - * - * @param string $field_mask sql mask for creating field with correct definition (type & size) - * @param int $start_index add new fields starting from this index - * @param int $create_count create this much new multilingual field translations - * @return string - */ - function generateAlterSQL($field_mask, $start_index, $create_count) - { - static $single_lang = null; - if (!isset($single_lang)) { - // if single language mode, then create indexes only on primary columns - $table_name = $this->Application->getUnitOption('lang', 'TableName'); - $sql = 'SELECT COUNT(*) - FROM '.$table_name.' - WHERE Enabled = 1'; - // if language count = 0, then assume it's multi language mode - $single_lang = $this->Conn->GetOne($sql) == 1; - } - - $ret = ' '; - $i_count = $start_index + $create_count; - while ($start_index < $i_count) { - list($prev_field,$type) = explode(' ', sprintf($field_mask, $start_index - 1) ); - if (substr($prev_field, 0, 3) == 'l0_') { - $prev_field = substr($prev_field, 3, strlen($prev_field)); - if (!$this->curSourceField) { - // get field name before this one - $fields = array_keys($this->curFields); -// $prev_field = key(end($this->curStructure)); - $prev_field = $fields[array_search($prev_field, $fields) - 1]; - if (getArrayValue($this->curFields[$prev_field], 'formatter') == 'kMultiLanguage') { - $prev_field = 'l'.$this->languageCount.'_'.$prev_field; - } - } - } - - $field_expression = sprintf($field_mask, $start_index); - $ret .= 'ADD COLUMN '.$field_expression.' AFTER `'.$prev_field.'`, '; - - if ($this->curIndexCount < 32 && ($start_index == $this->Application->GetDefaultLanguageId() || !$single_lang)) { - // create index for primary language column + for all others (if multiple languages installed) - list($field_name, $field_params) = explode(' ', $field_expression, 2); - $ret .= 'ADD INDEX (`'.$field_name.'` (5) ), '; - $this->curIndexCount++; - } - - $start_index++; - } - return preg_replace('/, $/',';',$ret); - } - } - - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/search_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/search_helper.php (revision 4228) +++ trunk/kernel/units/general/helpers/search_helper.php (revision 0) @@ -1,87 +0,0 @@ - $kw) $final[$kw] = $res[1][$index]; - $keyword = preg_replace($quotes_re, '', $keyword); - $not_quoted_kw = preg_match_all($no_quotes_re, $keyword, $res); - foreach ($res[2] as $index => $kw) $final[$kw] = $res[1][$index]; - - return $final; - } - - function getPositiveKeywords($keyword) - { - $keywords = $this->splitKeyword($keyword); - - $ret = Array(); - foreach ($keywords as $keyword => $sign) { - if ($sign == '+' || $sign == '') { - $ret[] = $keyword; - } - } - return $ret; - } - - function buildWhereClause($keyword, $fields) - { - $keywords = $this->splitKeyword($keyword); - - $normal_conditions = Array(); - $plus_conditions = Array(); - $minus_conditions = Array(); - - foreach ($keywords as $keyword => $sign) { - switch ($sign) { - case '+': - $plus_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $fields).' LIKE "%'.$keyword.'%"'; - break; - - case '-': - foreach ($fields as $field) { - $condition[] = $field.' NOT LIKE "%'.$keyword.'%" OR '.$field.' IS NULL'; - } - $minus_conditions[] = '('.implode(') AND (', $condition).')'; - break; - - case '': - $normal_conditions[] = implode(' LIKE "%'.$keyword.'%" OR ', $fields).' LIKE "%'.$keyword.'%"'; - break; - } - } - - // building where clause - if ($normal_conditions) { - $where_clause = '('.implode(') OR (', $normal_conditions).')'; - } - else { - $where_clause = '1'; - } - - if ($plus_conditions) { - $where_clause = '('.$where_clause.') AND ('.implode(') AND (', $plus_conditions).')'; - } - - if ($minus_conditions) { - $where_clause = '('.$where_clause.') AND ('.implode(') AND (', $minus_conditions).')'; - } - - return $where_clause; - } - - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/modules.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/modules.php (revision 5168) +++ trunk/kernel/units/general/helpers/modules.php (revision 0) @@ -1,370 +0,0 @@ -_GetModules(); - } - - function getWhereClause() - { - $where_clause = Array('Loaded = 1'); - - if (!$this->Application->IsAdmin()) return implode(' AND ', $where_clause); - - $modules = $this->_GetModules(); - if ($modules) { - foreach ($modules as $module_index => $module) { - $modules[$module_index] = $this->Conn->qstr($module); - } - $where_clause[] = 'Name IN ('.implode(',', $modules).')'; - } - - return implode(' AND ', $where_clause); - } - - function _EnableCookieSID() - { - $session =& $this->Application->recallObject('Session'); - return $session->CookiesEnabled; - } - - function _IsSpider($UserAgent) - { - global $robots; - $lines = file(FULL_PATH.'/robots_list.txt'); - - if (!is_array($robots)) { - $robots = Array(); - for($i = 0; $i < count($lines); $i++) { - $l = $lines[$i]; - $p = explode("\t", $l, 3); - $robots[] = $p[2]; - } - } - return in_array($UserAgent, $robots); - } - - function _MatchIp($ip1, $ip2) - { - $matched = TRUE; - - $ip = explode('.', $ip1); - $MatchIp = explode('.', $ip2); - for ($i = 0; $i < count($ip); $i++) { - if($i == count($MatchIp)) break; - if (trim($ip[$i]) != trim($MatchIp[$i]) || trim($ip[$i]) == '*') { - $matched = FALSE; - break; - } - } - return $matched; - } - - function _IpAccess($IpAddress, $AllowList, $DenyList) - { - $allowed = explode(',', $AllowList); - $denied = explode(',', $DenyList); - - $MatchAllowed = FALSE; - for ($x = 0; $x < count($allowed); $x++) { - $ip = explode('.', $allowed[$x]); - - $MatchAllowed = $this->_MatchIp($IpAddress, $allowed[$x]); - if ($MatchAllowed) - break; - } - $MatchDenied = FALSE; - for ($x = 0; $x < count($denied); $x++) { - $ip = explode('.', $denied[$x]); - - $MatchDenied = $this->_MatchIp($IpAddress, $denied[$x]); - if ($MatchDenied) - break; - } - - $Result = (($MatchAllowed && !$MatchDenied) || (!$MatchAllowed && !$MatchDenied) || - ($MatchAllowed && $MatchDenied)); - return $Result; - } - - /** - * Reads config.php file and parses it - * - */ - function _readConfig() - { - $vars = parse_portal_ini(FULL_PATH.'/config.php'); - - foreach ($vars as $config_key => $config_value) { - $GLOBALS['g_'.$config_key] = $config_value; - } - } - - /** - * Leaves only domain part from hostname (e.g. extract "intechnic.lv" from "test.intechnic.lv") - * Used for admin login license check - * - * @param string $d - * @return string - */ - function _StripDomainHost($d) - { - $IsIp = false; - $dotcount = substr_count($d, '.'); - if ($dotcount == 3) { - $IsIp = true; - for ($x = 0; $x < strlen($d); $x++) { - if (!is_numeric(substr($d, $x, 1)) && substr($d, $x, 1) != '.') - { - $IsIp = false; - break; - } - } - } - - if ($dotcount > 1 && !$IsIp) { - $p = explode('.', $d); - $ret = $p[count($p) - 2].'.'.$p[count($p) - 1]; - } - else { - $ret = $d; - } - return $ret; - } - - /** - * When logging into admin then check only last 2 parts of host name VS domain in license - * - * @param string $user_domain - * @param string $license_domain - * @return int - */ - function _CheckDomain($user_domain, $license_domain) - { - if ($this->Application->IsAdmin()) { - $user_domain = $this->_StripDomainHost($user_domain); - return preg_match('/(.*)'.preg_quote($user_domain, '/').'$/', $license_domain); - } - else { - return preg_match('/(.*)'.preg_quote($license_domain, '/').'$/', $user_domain); - } - } - - /** - * Returns modules list, that are in license - * - * @return Array - */ - function _GetModules() - { - global $i_Keys; - static $modules = null; - - if (isset($modules)) return $modules; - - $this->_readConfig(); - $license = base64_decode($GLOBALS['g_License']); - $this->_ParseLicense($license); - - $modules = Array(); - $domain = $this->_GetDomain(); - if (!$this->_IsLocalSite($domain)) { - for ($x = 0; $x < count($i_Keys); $x++) { - $key = $i_Keys[$x]; - if ($this->_CheckDomain($domain, $key['domain'])) { - // used hostname is subdomain or matches domain from license - $modules = explode(',', $key['mod']); - } - } - } - else { - $modules = array_keys($this->Application->ModuleInfo); - } - - return $modules; - } - - /** - * Allows to determine if module is licensed - * - * @param string $name - * @return bool - */ - function _ModuleLicensed($name) - { - $modules = $this->_GetModules(); - return in_array($name, $modules); - } - - /** - * Returns domain from licences (and direct in case of install script) - * - * @return string - */ - function _GetDomain() - { - return $this->Application->ConfigValue('DomainDetect') ? $_SERVER['HTTP_HOST'] : $GLOBALS['g_Domain']; - } - - function _keyED($txt, $encrypt_key) - { - $encrypt_key = md5($encrypt_key); - $ctr = 0; - $tmp = ''; - for ($i = 0; $i < strlen($txt); $i++) { - if ($ctr == strlen($encrypt_key)) $ctr = 0; - $tmp .= substr($txt, $i, 1) ^ substr($encrypt_key, $ctr, 1); - $ctr++; - } - return $tmp; - } - - - function _decrypt($txt, $key) - { - $txt = $this->_keyED($txt,$key); - $tmp = ''; - for ($i = 0; $i < strlen($txt); $i++) { - $md5 = substr($txt, $i, 1); - $i++; - $tmp .= (substr($txt, $i, 1) ^ $md5); - } - return $tmp; - } - - function LoadFromRemote() - { - return ''; - } - - function DLid() - { - die($GLOBALS['lid']."\n"); - } - - function _LoadLicense($LoadRemote = false) - { - $f = FULL_PATH.'/intechnic.php'; - if ($this->_falseIsLocalSite($f)) $ret = true; - if (file_exists($f)) { - $contents = file($f); - $data = base64_decode($contents[1]); - } - else { - if ($LoadRemote) return $LoadFromRemote; - } - return $data; - } - - function _VerifyKey($domain, $k) - { - $key = md5($domain); - $lkey = substr($key, 0, strlen($key) / 2); - $rkey = substr($key, strlen($key) / 2); - $r = $rkey.$lkey; - if ($k == $r) return true; - return false; - } - - function _ParseLicense($txt) - { - global $i_User, $i_Pswd, $i_Keys; - if (!$this->_falseIsLocalSite($txt)) $nah = false; - $data = $this->_decrypt($txt, 'beagle'); - $i_Keys = Array(); - $lines = explode("\n", $data); - for ($x = 0; $x < count($lines); $x++) { - $l = $lines[$x]; - $p = explode('=', $l, 2); - switch($p[0]) { - case 'Username': - $i_User = $p[1]; - break; - - case 'UserPass': - $i_Pswd = $p[1]; - break; - - default: - if (substr($p[0], 0, 3) == 'key') { - $parts = explode('|', $p[1]); - if ($this->_VerifyKey($parts[0], $parts[1])) { - unset($K); - $k['domain'] = $parts[0]; - $k['key'] = $parts[1]; - $k['desc'] = $parts[2]; - $k['mod'] = $parts[3]; - $i_Keys[] = $k; - } - } - break; - } - } - } - - function _GetObscureValue($i) - { - if ($i == 'x') return 0254; $z = ''; - if ($i == 'z') return 0x7F.'.'; - if ($i == 'c') return '--code--'; - if ($i >= 5 && $i < 7) return $this->_GetObscureValue($z)*$this->_GetObscureValue('e'); - if ($i > 30) return Array(0x6c,0x6f,0x63,0x61,0x6c,0x68,0x6f,0x73,0x74); - if ($i > 20) return 99; - if ($i > 10) return '.'.($this->_GetObscureValue(6.5)+1); - if ($i == 'a') return 0xa; - } - - function _Chr($val) - { - $x = $this->_GetObscureValue(25); - $f = chr($x).chr($x+5).chr($x+15); - return $f($val); - } - - function _IsLocalSite($domain) - { - $ee = $this->_GetObscureValue(35); $yy = ''; - foreach ($ee as $e) $yy .= $this->_Chr($e); - $localb = FALSE; - if(substr($domain,0,3)==$this->_GetObscureValue('x')) - { - $b = substr($domain,0,6); - $p = explode(".",$domain); - $subnet = $p[1]; - if($p[1]>15 && $p[1]<32) - $localb=TRUE; - } - $zz = $this->_GetObscureValue('z').$this->_GetObscureValue(5).'.'.(int)$this->_GetObscureValue(7).$this->_GetObscureValue(12); - $ff = $this->_GetObscureValue('z')+65; - $hh = $ff-0x18; - if($domain==$yy || $domain==$zz || substr($domain,0,7)==$ff.$this->_Chr(46).$hh || - substr($domain,0,3)==$this->_GetObscureValue('a').$this->_Chr(46) || $localb || strpos($domain,".")==0) - { - return TRUE; - } - return FALSE; - } - - function _falseIsLocalSite($domain) - { - $localb = FALSE; - if(substr($domain,0,3)=="172") - { - $b = substr($domain,0,6); - $p = explode(".",$domain); - $subnet = $p[1]; - if($p[1]>15 && $p[1]<32) - $localb=TRUE; - } - if($domain=="localhost" || $domain=="127.0.0.1" || substr($domain,0,7)=="192.168" || - substr($domain,0,3)=="10." || $localb || strpos($domain,".")==0) - { - return TRUE; - } - return FALSE; - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/sections_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/sections_helper.php (revision 6625) +++ trunk/kernel/units/general/helpers/sections_helper.php (revision 0) @@ -1,120 +0,0 @@ -BuildTree(); - } - - /** - * Builds xml for tree in left frame in admin - * - * @param Array $params - */ - function BuildTree() - { - $unit_config_reader = false; - $data = $this->Conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "sections_parsed"'); - if ($data) { - $this->Tree = unserialize($data['Data']); - return ; - } - $this->Application->UnitConfigReader->includeConfigFiles(MODULES_PATH); - $this->Application->UnitConfigReader->AfterConfigRead(); - - $this->Tree = Array(); - if (!$unit_config_reader) { - $unit_config_reader =& $this->Application->recallObject('kUnitConfigReader'); - } - - $prefixes = array_keys($unit_config_reader->configData); - foreach ($prefixes as $prefix) { - $config =& $unit_config_reader->configData[$prefix]; - $sections = getArrayValue($config, 'Sections'); - if (!$sections) continue; - -// echo 'Prefix: ['.$prefix.'] has ['.count($sections).'] sections
'; - - foreach ($sections as $section_name => $section_params) { - // we could also skip not allowed sections here in future - $section_params['SectionPrefix'] = $prefix; - $section_params['url']['m_opener'] = 'r'; - $section_params['url']['no_pass_through'] = 1; - $pass_section = getArrayValue($section_params, 'url', 'pass_section'); - - if ($pass_section) { - unset($section_params['url']['pass_section']); - $section_params['url']['section'] = $section_name; - if (!isset($section_params['url']['module'])) { - $module_name = $this->Application->findModule('Path', $config['ModuleFolder'].'/', 'Name'); - $section_params['url']['module'] = $module_name; - } - } - - if (!isset($section_params['url']['t'])) { - $section_params['url']['t'] = 'index'; - } - - if (!isset($section_params['onclick'])) { - $section_params['onclick'] = 'checkEditMode()'; - } - - if (isset($section_params['icon']) && preg_match('/([^:]+):(.*)/', $section_params['icon'], $regs)) { - $section_params['icon'] = $regs[2]; - $section_params['icon_module'] = $regs[1]; - } - - $current_data = isset($this->Tree[$section_name]) ? $this->Tree[$section_name] : Array(); - $this->Tree[$section_name] = array_merge_recursive2($current_data, $section_params); - - $this->Tree[ $section_params['parent'] ]['children'][ "{$section_params['priority']}" ] = $section_name; - - if ($section_params['type'] == stTAB) { - // if this is tab, then mark parent section as TabOnly - $this->Tree[ $section_params['parent'] ]['tabs_only'] = true; - } - } - } - - $this->Conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("sections_parsed", '.$this->Conn->qstr(serialize($this->Tree)).', '.adodb_mktime().')'); - } - - /** - * Returns details information about section - * - * @param string $section_name - * @return Array - */ - function &getSectionData($section_name) - { - if (isset($this->Tree[$section_name])) { - $ret =& $this->Tree[$section_name]; - } - else { - $ret = Array(); - } - return $ret; - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/permissions_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/permissions_helper.php (revision 6583) +++ trunk/kernel/units/general/helpers/permissions_helper.php (revision 0) @@ -1,468 +0,0 @@ -Application->getUnitOption('perm', 'TableName'); - $perm_table = $this->Application->GetTempName($perm_table); - $sql = 'SELECT * - FROM '.$perm_table.' - WHERE (GroupId = '.$group_id.') AND (CatId = '.$cat_id.') AND (Type = '.$type.')'; - $permissions = $this->Conn->Query($sql, 'Permission'); - - $this->Permissions = Array(); - foreach ($permissions as $perm_name => $perm_options) { - $perm_record['value'] = $perm_options['PermissionValue']; - $perm_record['id'] = $perm_options['PermissionId']; - $this->Permissions[$perm_name] = $perm_record; - } - } - - function getPermissionValue($perm_name) - { - return isset($this->Permissions[$perm_name]) ? $this->Permissions[$perm_name]['value'] : 0; - } - - function getPermissionID($perm_name) - { - return isset($this->Permissions[$perm_name]) ? $this->Permissions[$perm_name]['id'] : 0; - } - - /** - * This is old permission like ADMIN or LOGIN - * - * @param string $section_name - * @param string $perm_name - * @return bool - */ - function isOldPermission($section_name, $perm_name) - { - return $section_name == 'in-portal:root' && $perm_name != 'view'; - } - - /** - * Returns permission names to check based on event name and item prefix (main item or subitem) - * - * @param kEvent $event - * @return Array - */ - function getPermissionByEvent(&$event, $perm_mapping) - { - $top_prefix = $event->getEventParam('top_prefix'); - - $pefix_type = ($top_prefix == $event->Prefix) ? 'self' : 'subitem'; - $perm_mapping = getArrayValue($perm_mapping, $event->Name); - - if (!$perm_mapping[$pefix_type]) { - trigger_error('Permission mappings not defined for event '.$top_prefix.' <- '.$event->Prefix.':'.$event->Name.'', E_USER_ERROR); - } - - if ($perm_mapping[$pefix_type] === true) { - // event is defined in mapping but is not checked by permissions - return true; - } - - return explode('|', $perm_mapping[$pefix_type]); - } - - /** - * Common event permission checking method - * - * @param kEvent $event - */ - function CheckEventPermission(&$event, $perm_mapping) - { - $section = $event->getSection(); - if (preg_match('/^CATEGORY:(.*)/', $section)) { - return $this->CheckEventCategoryPermission($event, $perm_mapping); - } - - $top_prefix = $event->getEventParam('top_prefix'); - $check_perms = $this->getPermissionByEvent($event, $perm_mapping); - - if ($check_perms === true) { - // event is defined in mapping but is not checked by permissions - return true; - } - - $perm_status = false; - foreach ($check_perms as $perm_name) { - // check if at least one of required permissions is set - $perm_name = $section.'.'.$perm_name; - $perm_status = $this->CheckPermission($perm_name, 1); - if (($perm_name == $section.'.add') && $perm_status && ($top_prefix == $event->Prefix)) { - // main item, add permission allowed, but ID is > 0, then deny permission - // how to get id here - } - if ($perm_status) { - return $perm_status; - } - } - - if (!$perm_status) { - if ($this->Application->isDebugMode()) { - // for debugging purposes - $event->SetRedirectParam('section', $section); - $event->SetRedirectParam('main_prefix', $top_prefix); - $event->SetRedirectParam('event_name', $event->Name); - $event->SetRedirectParam('next_template', $this->Application->GetVar('t')); - } - $event->status = erPERM_FAIL; - } - return $perm_status; - } - - /** - * Checks non-system permission on event per category basis - * - * @param kEvent $event - */ - function CheckEventCategoryPermission(&$event, $event_perm_mapping) - { - // mapping between specific permissions and common permissions - $perm_mapping = Array('add' => 'ADD', 'add.pending' => 'ADD.PENDING', 'edit' => 'MODIFY', 'edit.pending' => 'MODIFY.PENDING', 'delete' => 'DELETE', 'view' => 'VIEW'); - - $top_prefix = $event->getEventParam('top_prefix'); - $event_handler =& $this->Application->recallObject($event->Prefix.'_EventHandler'); - if ($event->Prefix != $top_prefix) { - $top_event = new kEvent($top_prefix.':'.$event->Name); - $id = $event_handler->getPassedID($top_event); - } - else { - $id = $event_handler->getPassedID($event); - } - - // 1. get primary category of category item - $id_field = $this->Application->getUnitOption($top_prefix, 'IDField'); - $table_name = $this->Application->getUnitOption($top_prefix, 'TableName'); - $ci_table = $this->Application->getUnitOption('ci', 'TableName'); - - if (!$id) { - // item being created -> check by current (before editing started, saved in OnPreCreate event) category permissions - $category_id = $this->Application->RecallVar('m_cat_id'); - } - elseif ($top_prefix == 'c') { - $category_id = $id; - } - else { - // item being edited -> check by it's primary category permissions - $sql = 'SELECT ci.CategoryId, main_table.CreatedById - FROM '.$table_name.' main_table - LEFT JOIN '.$ci_table.' ci ON ci.ItemResourceId = main_table.ResourceId - WHERE (main_table.'.$id_field.' = '.$id.') AND (ci.PrimaryCat = 1)'; - $item_info = $this->Conn->GetRow($sql); - $category_id = $item_info['CategoryId']; - $owner_id = $item_info['CreatedById']; - } - - $item_prefix = $this->Application->getUnitOption($top_prefix, 'PermItemPrefix'); - - if (substr($event->Name, 0, 9) == 'OnPreSave') { - if ($event_handler->isNewItemCreate($event)) { - return $this->CheckPermission($item_prefix.'.ADD', 0, $category_id) || - $this->CheckPermission($item_prefix.'.ADD.PENDING', 0, $category_id); - } - else { - return $this->CheckPermission($item_prefix.'.ADD', 0, $category_id) || - $this->CheckPermission($item_prefix.'.ADD.PENDING', 0, $category_id) || - $this->ModifyCheckPermission($owner_id, $category_id, $top_prefix); - } - } - - $perm_status = false; - $check_perms = $this->getPermissionByEvent($event, $event_perm_mapping); - - if ($check_perms === true) { - // event is defined in mapping but is not checked by permissions - return true; - } - - foreach ($check_perms as $perm_name) { - // check if at least one of required permissions is set - if (!isset($perm_mapping[$perm_name])) { - // not mapped permission (e.g. advanced:approve) -> skip - continue; - } - $perm_name = $item_prefix.'.'.$perm_mapping[$perm_name]; - $this->showDebug('Event '.$event->Name.' permission(-s): '.$perm_name.'', Array()); - $perm_status = $this->CheckPermission($perm_name, 0, $category_id); - - if ($perm_status) { - return $perm_status; - } - } - - if (!$perm_status) { - $event->SetRedirectParam('index_file', 'index.php'); // because called from browse.php - if ($this->Application->isDebugMode()) { - // for debugging purposes - $event->SetRedirectParam('section', $event->getSection()); - $event->SetRedirectParam('main_prefix', $top_prefix); - $event->SetRedirectParam('event_name', $event->Name); - $event->SetRedirectParam('next_template', $this->Application->GetVar('t')); - } - $event->status = erPERM_FAIL; - } - return $perm_status; - } - - function showDebug($text, $params) - { - return ; - $is_ajax = $this->Application->GetVar('ajax') == 'yes' || isset($params['ajax']) || isset($params['tab_init']); - if (!$this->Application->isDebugMode() || $is_ajax) return true; - echo $text.'
'; - } - - function TagPermissionCheck($params, $tag_name) - { - $perm_prefix = getArrayValue($params, 'perm_prefix'); - $perm_event = getArrayValue($params, 'perm_event'); - $permission_groups = getArrayValue($params, 'permissions'); - - if ($permission_groups) { - // check permissions by permission names in current category - $this->showDebug('Tag '.$tag_name.' permission(-s): '.$permission_groups.'', $params); - $permission_groups = explode('|', $permission_groups); - $group_has_permission = false; - - $perm_category = $this->Application->GetVar('m_cat_id'); - - if ($perm_prefix) { - // use primary category of item with id from {perm_prefix}_id as base for permission checking - $perm_category = $this->getPrimaryCategory($perm_prefix); - } - - foreach ($permission_groups as $permission_group) { - $permissions = explode(',', $permission_group); - $has_permission = true; - foreach ($permissions as $permission) { - $has_permission = $has_permission && $this->CheckPermission($permission, isset($params['system']) && $params['system'] ? 1 : 0, $perm_category); - } - $group_has_permission = $group_has_permission || $has_permission; - - if ($group_has_permission) { - return true; - } - } - return false; - } - elseif ($perm_event) { - // check permission by event name - $this->showDebug('Tag '.$tag_name.' permission_event: '.$perm_event.'', $params); - list($prefix, $event) = explode(':', $perm_event); - $event_handler =& $this->Application->recallObject($prefix.'_EventHandler'); - return $event_handler->CheckPermission( new kEvent($perm_event) ); - } - - return true; - } - - /** - * Returns item's primary category (get item_id from request) - * - * @param string $prefix - * @return int - */ - function getPrimaryCategory($prefix) - { - $id_field = $this->Application->getUnitOption($prefix, 'IDField'); - $table_name = $this->Application->getUnitOption($prefix, 'TableName'); - $id = $this->Application->GetVar($prefix.'_id'); - - if (!$id) return $this->Application->GetVar('m_cat_id'); - - $sql = 'SELECT ResourceId - FROM '.$table_name.' - WHERE '.$id_field.' = '.$id; - $resource_id = $this->Conn->GetOne($sql); - - $sql = 'SELECT CategoryId - FROM '.$this->Application->getUnitOption('ci', 'TableName').' - WHERE ItemResourceId = '.$resource_id.' AND PrimaryCat = 1'; - return $this->Conn->GetOne($sql); - } - - /** - * Returns no permission template to redirect to - * - * @param Array $params - * @return Array - */ - function getPermissionTemplate($params) - { - $t = $this->Application->GetVar('t'); - if ($next_t = getArrayValue($params, 'next_template')) { - $t = $next_t; - } - - if (!$this->Application->LoggedIn()) { - $redirect_template = $params['login_template']; - if (!$redirect_template && $this->Application->IsAdmin()) $redirect_template = 'login'; - $redirect_params = Array('next_template' => $t); - } - else { - if (isset($params['no_permissions_template'])) { - $redirect_template = $params['no_permissions_template']; - } - else { - $redirect_template = $this->Application->IsAdmin() ? 'no_permission' : $this->Application->ConfigValue('NoPermissionTemplate'); - } - - $redirect_params = $this->Application->isDebugMode() ? Array('from_template' => 1, 'perms' => $params[ isset($params['permissions']) ? 'permissions' : 'perm_event'], 'next_template' => $t) : Array(); - } - - if (isset($params['index_file']) && $params['index_file']) { - $redirect_params['index_file'] = $params['index_file']; - } - - return Array($redirect_template, $redirect_params); - } - - /** - * Check current user permissions based on it's group permissions in specified category (for non-system permissions) or just checks if system permission is set - * - * @param string $name permission name - * @param int $cat_id category id, current used if not specified - * @param int $type permission type {1 - system, 0 - per category} - * @return int - */ - function CheckPermission($name, $type = 1, $cat_id = null) - { - $user_id = $this->Application->GetVar('u_id'); - return $this->CheckUserPermission($user_id, $name, $type, $cat_id); - } - - function CheckUserPermission($user_id, $name, $type = 1, $cat_id = null) - { - if ($user_id == -1) { - // "root" is allowed anywhere - return $name == 'SYSTEM_ACCESS.READONLY' ? 0 : 1; - } - - if ($type == 1) { - // "system" permission are always checked per "Home" category (ID = 0) - $cat_id = 0; - } - - if (!isset($cat_id)) { - $cat_id = $this->Application->GetVar('m_cat_id'); - } - - $cache_key = $name.'|'.$type.'|'.$cat_id; - $perm_value = $this->Application->getCache('permissions', $cache_key); - if ($perm_value !== false) { - return $perm_value; - } - - // perm cache is build only based on records in db, that's why if permission is not explicitly denied, then - // that (perm cache creator) code thinks that it is allowed & adds corresponding record and code below will - // return incorrect results - - if (preg_match('/(.*)\.VIEW$/', $name) && ($type == 0)) { - // cached view permission of category: begin - $sql = 'SELECT PermissionConfigId - FROM '.TABLE_PREFIX.'PermissionConfig - WHERE PermissionName = '.$this->Conn->qstr($name); - $perm_id = $this->Conn->GetOne($sql); - - $sql = 'SELECT PermId - FROM '.TABLE_PREFIX.'PermCache - WHERE (PermId = '.$perm_id.') AND (CategoryId = '.$cat_id.')'; - - $view_filters = Array(); - if ($user_id == $this->Application->GetVar('u_id')) { - $groups = explode(',', $this->Application->RecallVar('UserGroups')); - } - else { // checking not current user - $sql = 'SELECT GroupId FROM '.TABLE_PREFIX.'UserGroup - WHERE (PortalUserId = '.$user_id.') AND - ( (MembershipExpires IS NULL) OR ( MembershipExpires >= UNIX_TIMESTAMP() ) )'; - $groups = $this->Conn->GetCol($sql); - array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup') ); - } - foreach ($groups as $group) { - $view_filters[] = 'FIND_IN_SET('.$group.', ACL)'; - } - $sql .= ' AND ('.implode(' OR ', $view_filters).')'; - $perm_value = $this->Conn->GetOne($sql) ? 1 : 0; - - $this->Application->setCache('permissions', $cache_key, $perm_value); - return $perm_value; - // cached view permission of category: end - } - - if ($cat_id == 0) { - $cat_hierarchy = Array(0); - } - else { - $sql = 'SELECT ParentPath - FROM '.$this->Application->getUnitOption('c', 'TableName').' - WHERE CategoryId = '.$cat_id; - $cat_hierarchy = $this->Conn->GetOne($sql); - $cat_hierarchy = explode('|', substr($cat_hierarchy, 1, -1)); - $cat_hierarchy = array_reverse($cat_hierarchy); - array_push($cat_hierarchy, 0); - } - - $perm_value = 0; - $groups = $this->Application->RecallVar('UserGroups'); - foreach ($cat_hierarchy as $category_id) { - $sql = 'SELECT SUM(PermissionValue) - FROM '.TABLE_PREFIX.'Permissions - WHERE Permission = "'.$name.'" AND CatId = '.$category_id.' AND GroupId IN ('.$groups.') AND Type = '.$type; - $res = $this->Conn->GetOne($sql); - if ($res !== false && !is_null($res)) { - $perm_value = $res ? 1 : 0; - break; - } - } - - $this->Application->setCache('permissions', $cache_key, $perm_value); - return $perm_value; - } - - /** - * Allows to check MODIFY & OWNER.MODFY +/- PENDING permission combinations on item - * - * @param int $owner_id user_id, that is owner of the item - * @param int $category_id primary category of item - * @param string $prefix prefix of item - * @return int {0 - no MODIFY permission, 1 - has MODIFY permission, 2 - has MODIFY.PENDING permission} - */ - function ModifyCheckPermission($owner_id, $category_id, $prefix) - { - $perm_prefix = $this->Application->getUnitOption($prefix, 'PermItemPrefix'); - - $live_modify = $this->CheckPermission($perm_prefix.'.MODIFY', ptCATEGORY, $category_id); - if ($live_modify) { - return 1; - } - else if ($this->CheckPermission($perm_prefix.'.MODIFY.PENDING', ptCATEGORY, $category_id)) { - return 2; - } - - if ($owner_id == $this->Application->GetVar('u_id')) { - // user is item's OWNER -> check this permissions first - $live_modify = $this->CheckPermission($perm_prefix.'.OWNER.MODIFY', ptCATEGORY, $category_id); - if ($live_modify) { - return 1; - } - else if ($this->CheckPermission($perm_prefix.'.OWNER.MODIFY.PENDING', ptCATEGORY, $category_id)) { - return 2; - } - } - - return 0; - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/mod_rewrite_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/mod_rewrite_helper.php (revision 6428) +++ trunk/kernel/units/general/helpers/mod_rewrite_helper.php (revision 0) @@ -1,485 +0,0 @@ -HTTPQuery =& $this->Application->recallObject('HTTPQuery'); - } - - function SetDefaultValues(&$vars) - { - $defaults = Array('m_cat_id' => 0, 'm_cat_page' => 1, 'm_opener' => 's'); - foreach ($defaults as $default_key => $default_value) - { - if ($this->HTTPQuery->Get($default_key) == null) { - $vars[$default_key] = $default_value; - } - } - } - - function ProcessLanguage(&$url_parts, &$vars) - { - if (!isset($url_parts[0])) return false; - $res = false; - $url_part = array_shift($url_parts); - - $sql = 'SELECT LanguageId FROM '.TABLE_PREFIX.'Language WHERE LOWER(PackName) = '.$this->Conn->qstr($url_part).' AND Enabled = 1'; - $language_id = $this->Conn->GetOne($sql); - $this->Application->Phrases = new PhrasesCache(); - if($language_id) - { - $vars['m_lang'] = $language_id; - $res = true; - } - -// $this->Application->VerifyLanguageId(); - if (!$res) { - array_unshift($url_parts, $url_part); - } - return $res; - } - - function ProcessTheme(&$url_parts, &$vars) - { - if (!isset($url_parts[0])) return false; - $res = false; - $url_part = array_shift($url_parts); - - $sql = 'SELECT ThemeId FROM '.TABLE_PREFIX.'Theme WHERE LOWER(Name) = '.$this->Conn->qstr($url_part).' AND Enabled = 1'; - $theme_id = $this->Conn->GetOne($sql); - if($theme_id) - { - $vars['m_theme'] = $theme_id; - $res = true; - } -// $this->Application->VerifyThemeId(); // verify anyway - will set default if not found!!! - if (!$res) { - array_unshift($url_parts, $url_part); - } - return $res; - } - - function ProcessCategory(&$url_parts, &$vars) - { - if (!isset($url_parts[0])) return false; - $res = false; - $url_part = array_shift($url_parts); - - $category_id = 0; - $last_category_id = 0; - $category_path = ''; - do - { - $category_path = trim($category_path.'/'.$url_part, '/'); - - if( preg_match('/(.*)_([\d]+)$/', $category_path, $rets) ) - { - $category_path = $rets[1]; - $vars['m_cat_page'] = $rets[2]; - } - - $category_id = $this->Conn->GetOne( - 'SELECT CategoryId - FROM '.TABLE_PREFIX.'Category - WHERE Status = 1 AND NamedParentPath = '.$this->Conn->qstr($category_path)); - if ($category_id !== false) { - $last_category_id = $category_id; - $url_part = array_shift($url_parts); - $res = true; - } - } while ($category_id !== false && $url_part); - $vars['m_cat_id'] = $last_category_id; - - if ($url_part) { - array_unshift($url_parts, $url_part); - } - return $res; - } - - function ProcessPage(&$url_parts, &$vars) - { - if (!is_numeric($url_parts[0]) || count($url_parts) > 1) return false; - - // set module pages for all modules, since we don't know which module will need it - foreach ($this->Application->ModuleInfo as $module_name => $module_data) - { - $vars[ $module_data['Var'].'_id'] = 0; - $vars[ $module_data['Var'].'_Page'] = $url_parts[0]; - $vars[ $module_data['Var'].'_Reviews_Page'] = 0; - } - return true; - } - - function ProcessModuleIndex(&$url_parts, &$vars) - { - if ( count($url_parts) > 1) return false; // if no more parts or only 1 part left - if ( $url_parts && $url_parts[0] == 'index') { // treat index same as no parts - array_shift($url_parts); - } - - if( $url_parts ) { // if parts are left, it can only be module page - if (!is_numeric($url_parts[0])) return false; - $this->ProcessPage($url_parts, $vars); - } - - // try to find CMS index page of the category - if ($this->Application->isModuleEnabled('In-CMS')) { - $sql = 'SELECT p.Path, ci.CategoryId FROM '.TABLE_PREFIX.'Pages AS p - LEFT JOIN '.TABLE_PREFIX.'CategoryItems AS ci - ON ci.ItemResourceId = p.ResourceId - WHERE - p.IsIndex = 1 - AND - p.Status = 1 - AND - CategoryId = '.$vars['m_cat_id'].' - AND - ci.PrimaryCat = 1'; - $template_found = $this->Conn->GetRow($sql); - if ($template_found !== false) { - $vars['t'] = $template_found['Path']; - return true; - } - } - - $sql = 'SELECT CachedCategoryTemplate - FROM '.TABLE_PREFIX.'Category - WHERE CategoryId = '.$vars['m_cat_id']; - $vars['t'] = $this->Conn->GetOne($sql); - if (!$vars['t']) $vars['t'] = 'index'; - return true; - } - - function ProcessModuleItem(&$url_parts, &$vars, $set_t=true) - { - if (preg_match('/^bb_.*/', $url_parts[0])) { - $cat_item = $this->Conn->GetRow(' - SELECT c.ParentPath, c.CategoryId FROM '.TABLE_PREFIX.'Category AS c - WHERE - c.CategoryId = '.$vars['m_cat_id']); - - if ($set_t) { - $item_template = $this->GetItemTemplate($cat_item, 'bb'); - $vars['t'] = $item_template; - } - - $this->Application->HandleEvent($bb_event, 'bb:ParseEnv', Array('url_parts' => $url_parts, 'vars' => $vars)); - $vars = $bb_event->getEventParam('vars'); - return 'bb'; - } - - if (!isset($url_parts[0])) return false; - if ( count($url_parts) != 1 ) return false; - $url_part = array_shift($url_parts); - - // match module reviews page - $page = 1; - if( preg_match('/(.*)_([\d]+)$/', $url_part, $rets) ) - { - $url_part = $rets[1]; - $page = $rets[2]; - } - - // locating the item in CategoryItems by filename to detect its ItemPrefix and its category ParentPath - $cat_item = $this->Conn->GetRow(' - SELECT ci.ItemResourceId, ci.ItemPrefix, c.ParentPath, ci.CategoryId FROM '.TABLE_PREFIX.'CategoryItems AS ci - LEFT JOIN '.TABLE_PREFIX.'Category AS c - ON c.CategoryId = ci.CategoryId - WHERE - ci.CategoryId = '.$vars['m_cat_id'].' - AND - ci.Filename = '.$this->Conn->qstr($url_part)); - - if ($cat_item !== false) { // item found - $module_prefix = $cat_item['ItemPrefix']; - $item_template = $this->GetItemTemplate($cat_item, $module_prefix); - - // converting ResourceId to correpsonding Item id - $module_config = $this->Application->getUnitOptions($module_prefix); - $item_id = $this->Conn->GetOne( - 'SELECT '.$module_config['IDField'].' FROM '.$module_config['TableName'].' - WHERE ResourceId = '.$cat_item['ItemResourceId'] - ); - - if ((!$set_t || $item_template) && $item_id) { - if ($set_t) { - $vars['t'] = $item_template; - } - $vars[ $module_prefix.'_id' ] = $item_id; - $vars[ $module_prefix.'_Reviews_Page' ] = $page; - return $module_prefix; - } - } - array_unshift($url_parts, $url_part); - return false; - } - - function GetItemTemplate($category, $module_prefix) - { - if (!is_array($category)) { - $category = $this->Conn->GetRow(' - SELECT c.ParentPath, c.CategoryId FROM '.TABLE_PREFIX.'Category AS c - WHERE - c.CategoryId = '.$category); - } - $parent_path = implode(',',explode('|', substr($category['ParentPath'], 1, -1))); - - // item template is stored in module' system custom field - need to get that field Id - $item_template_field_id = $this->Conn->GetOne( - 'SELECT CustomFieldId - FROM '.TABLE_PREFIX.'CustomField - WHERE FieldName = '.$this->Conn->qstr($module_prefix.'_ItemTemplate')); - - // looking for item template through cats hierarchy sorted by parent path - $query = 'SELECT ccd.l1_cust_'.$item_template_field_id.', - FIND_IN_SET(c.CategoryId, '.$this->Conn->qstr($parent_path).') AS Ord1, - c.CategoryId, c.Name, ccd.l1_cust_'.$item_template_field_id.' - FROM '.TABLE_PREFIX.'Category AS c - LEFT JOIN '.TABLE_PREFIX.'CategoryCustomData AS ccd - ON ccd.ResourceId = c.ResourceId - WHERE c.CategoryId IN ('.$parent_path.') AND ccd.l1_cust_'.$item_template_field_id.' != \'\' - ORDER BY FIND_IN_SET(c.CategoryId, '.$this->Conn->qstr($parent_path).') DESC'; - $item_template = $this->Conn->GetOne($query); - return $item_template; - } - - function ProcessPhisycalTemplate(&$url_parts, &$vars) - { - if (!isset($url_parts[0])) return false; - - $remaining = array(); - do - { - $template_path = implode('/', $url_parts); - - $t_parts['path'] = dirname($template_path) == '.' ? '' : '/'.dirname($template_path); - $t_parts['file'] = basename($template_path); - - $sql = 'SELECT FileId - FROM '.TABLE_PREFIX.'ThemeFiles - WHERE (FilePath = '.$this->Conn->qstr($t_parts['path']).') AND (FileName = '.$this->Conn->qstr($t_parts['file'].'.tpl').')'; - -// $sql = 'SELECT FileId FROM '.TABLE_PREFIX.'ThemeFiles WHERE CONCAT(FilePath, "/", FileName) = '.$this->Conn->qstr('/'.$template_path.'.tpl'); - $template_found = $this->Conn->GetOne($sql); - if(!$template_found) - { - array_unshift($remaining, array_pop($url_parts)); - } - } while (!$template_found && $url_parts); - - $url_parts = $remaining; - - if ($template_found) { - $vars['t'] = $template_path; - return true; - } - return false; - } - - /** - * Checks if whole url_parts matches a whole In-CMS page - * - * @param array $url_parts - * @return boolean - */ - function ProcessVirtualTemplate(&$url_parts, &$vars) - { - if (!isset($url_parts[0]) || !$this->Application->isModuleEnabled('In-Edit')) return false; - - $template_path = implode('/', $url_parts); - $sql = 'SELECT p.PageId, ci.CategoryId FROM '.TABLE_PREFIX.'Pages AS p - LEFT JOIN '.TABLE_PREFIX.'CategoryItems AS ci - ON ci.ItemResourceId = p.ResourceId - WHERE - Path = '.$this->Conn->qstr($template_path).' - AND - ci.PrimaryCat = 1 - AND - p.Status = 1'; - $template_found = $this->Conn->GetRow($sql); - - if ($template_found) { - $vars['m_cat_id'] = $template_found['CategoryId']; - $vars['t'] = $template_path; - return true; - } - - return false; - } - - function processRewriteURL() - { - $passed = array(); - $url = $this->HTTPQuery->Get('_mod_rw_url_'); - if( substr($url, -5) == '.html' ) $url = substr($url, 0, strlen($url) - 5 ); - - $restored = false; - $cache = $this->Conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "mod_rw_'.md5($url).'"'); - if (false && $cache && $cache['Cached'] > 0) { - $cache = unserialize($cache['Data']); - $vars = $cache['vars']; - $passed = $cache['passed']; - $restored = true; - } - else { - $passed = array(); - $vars = $this->parseRewriteURL($url,$passed); - $cache = array('vars'=>$vars,'passed'=>$passed); - $this->Conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("mod_rw_'.md5($url).'", '.$this->Conn->qstr(serialize($cache)).', '.adodb_mktime().')'); - } - foreach ($vars as $name => $value) - { - $this->HTTPQuery->Set($name,$value); - } -// if ($restored) { - $this->InitAll(); -// } - $this->HTTPQuery->finalizeParsing($passed); - } - - function InitAll() - { -// $this->Application->Phrases = new PhrasesCache(); - $this->Application->VerifyLanguageId(); - $this->Application->Phrases->Init('phrases'); - $this->Application->VerifyThemeId(); - } - - function parseRewriteURL($url, &$passed) - { - $vars = $this->Conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "mod_rw_'.md5($url).'"'); - if (false && $vars && $vars['Cached'] > 0) { - $vars = unserialize($menu['Data']); - return $vars; - } - - $vars = array(); - $url_parts = $url ? explode('/', $url) : Array(); - - $process_module = true; - if($this->HTTPQuery->Get('rewrite') == 'on' || !$url_parts) - { - $this->SetDefaultValues($vars); - } - - if(!$url_parts) - { - $this->InitAll(); - - $vars['t'] = $this->HTTPQuery->getDefaultTemplate(''); - $passed[] = 'm'; - return $vars; - } - else - { - $vars['t'] = ''; - } - - $passed = Array('m'); - $this->ProcessLanguage($url_parts, $vars); - $this->ProcessTheme($url_parts, $vars); - - if ( $this->ProcessVirtualTemplate($url_parts, $vars) ) { - return $vars; - } - - $this->ProcessCategory($url_parts, $vars); - - if ( $this->ProcessModuleIndex($url_parts, $vars) ) { - foreach ($this->Application->ModuleInfo as $module_name => $info) { - $passed[] = $info['Var']; - } - return $vars; - } - if ( $module_prefix = $this->ProcessModuleItem($url_parts, $vars) ) { - $passed[] = $module_prefix; - return $vars; - } - - /*// match module - $next_template = $this->HTTPQuery->Get('next_template'); - if($url_part || $next_template) - { - if($next_template) - { - $next_template_parts = explode('/', $next_template); - $module_folder = array_shift($next_template_parts); - } - else - { - $module_folder = $url_part; - } - - foreach ($this->Application->ModuleInfo as $module_name => $module_data) - { - if( trim($module_data['TemplatePath'], '/') == $module_folder ) - { - $module_prefix = $module_data['Var']; - break; - } - } - }*/ - - if ( $this->ProcessPhisycalTemplate($url_parts, $vars) ) { - if (!$url_parts) { - return $vars; - } - } - - if ( $this->ProcessPage($url_parts, $vars) ) { - return $vars; - } - - if ( $module_prefix = $this->ProcessModuleItem($url_parts, $vars, false) ) { - $passed[] = $module_prefix; - return $vars; - } - - if ( $this->Application->isModuleEnabled('In-Edit') && $this->Application->GetVar('admin') == 1) { - $adm_ses =& $this->Application->recallObject('Session.admin'); - $user = $adm_ses->RecallVar('user_id'); - $perm_helper =& $this->Application->recallObject('PermissionsHelper'); - if ($perm_helper->CheckUserPermission($user, 'PAGE.ADD', 0)) { - $vars['t'] = implode('/', $url_parts); - return $vars; - } - } - - $not_found = $this->Application->ConfigValue('ErrorTemplate'); - $vars['t'] = $not_found ? $not_found : 'error_notfound'; - - header('HTTP/1.0 404 Not Found'); - - return $vars; - -// $this->HTTPQuery->finalizeParsing($passed, $module_params); - - // pass params left to module - - /*$this->Application->Phrases->Init('phrases'); - $passed = Array('m'); - $module_params = Array(); - if ( isset($module_prefix) ) { - $passed[] = $module_prefix; - $module_event = new kEvent($module_prefix.':ParseEnv', Array('url_parts' => $url_parts) ); - if ($process_module) { - $this->Application->HandleEvent($module_event); - } - $item_id = $this->HTTPQuery->Get($module_prefix.'_id'); - $module_params = Array($module_prefix.'_id' => $item_id ? $item_id : '0' ); - - if ($module_event->status == erFAIL) { - $not_found = $this->Application->ConfigValue('ErrorTemplate'); - $this->HTTPQuery->Set('t', $not_found ? $not_found : 'error_notfound' ); - } - } - - $this->HTTPQuery->finalizeParsing($passed, $module_params);*/ - } - - - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/recursive_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/recursive_helper.php (revision 6093) +++ trunk/kernel/units/general/helpers/recursive_helper.php (revision 0) @@ -1,171 +0,0 @@ -Application->getUnitOption('c', 'IDField'); - $table_name = $this->Application->getUnitOption('c', 'TableName'); - - $sql = 'SELECT '.$id_field.' - FROM '.$table_name.' - WHERE ParentId = '.$category_id; - - $sub_categories = $this->Conn->GetCol($sql); - if ($sub_categories) { - foreach ($sub_categories as $sub_category_id) { - $this->DeleteCategory($sub_category_id); - } - } - - $ci_table = $this->Application->getUnitOption('ci', 'TableName'); - // 1. remove category items from this category if it is supplemental (non-primary) category to them - $sql = 'DELETE FROM '.$ci_table.' - WHERE ('.$id_field.' = '.$category_id.') AND (PrimaryCat = 0)'; - $this->Conn->Query($sql); - - $temp_handler =& $this->Application->recallObject('c_TempHandler', 'kTempTablesHandler'); - - // 2. delete items this have this category as primary - $delete_ids = $this->getCategoryItems($category_id, true); - - foreach ($delete_ids as $item_prefix => $resource_ids) { - if (!$item_prefix) { - // not ItemPrefix filled -> old categoryitem linking - continue; - } - $item_ids = $this->GetItemIDs($item_prefix, $resource_ids); - $temp_handler->BuildTables($item_prefix, $item_ids); - $temp_handler->DeleteItems($item_prefix, '', $item_ids); - } - - // 3. delete this category - $temp_handler->BuildTables('c', Array($category_id)); - $temp_handler->DeleteItems('c', '', Array($category_id)); - } - - /** - * Converts resource ids list to id field list for given prefix - * - * @param string $prefix - * @param Array $resource_ids - * @return Array - */ - function GetItemIDs($prefix, $resource_ids) - { - if (!$resource_ids) { - return Array(); - } - - $id_field = $this->Application->getUnitOption($prefix, 'IDField'); - $table_name = $this->Application->getUnitOption($prefix, 'TableName'); - - $sql = 'SELECT '.$id_field.' - FROM '.$table_name.' - WHERE ResourceId IN ('.implode(',', $resource_ids).')'; - return $this->Conn->GetCol($sql); - } - - // moves selected categories to destination category - function MoveCategories($category_ids, $dest_category_id) - { - if (!$category_ids) return ; - - $id_field = $this->Application->getUnitOption('c', 'IDField'); - $table_name = $this->Application->getUnitOption('c', 'TableName'); - - $sql = 'UPDATE '.$table_name.' - SET ParentId = '.$dest_category_id.' - WHERE '.$id_field.' IN ('.implode(',', $category_ids).')'; - $this->Conn->Query($sql); - } - - /** - * Complete cloning or category with subcategories and subitems - * - * @param int $category_id - */ - function PasteCategory($category_id) - { - $backup_category_id = $this->Application->GetVar('m_cat_id'); - - // 1. clone category - $temp_handler =& $this->Application->recallObject('c_TempHandler', 'kTempTablesHandler'); - $temp_handler->BuildTables('c', Array($category_id)); - $new_category_id = array_pop( $temp_handler->CloneItems('c', '', Array($category_id)) ); - $this->Application->SetVar('m_cat_id', $new_category_id); - - $id_field = $this->Application->getUnitOption('c', 'IDField'); - $table_name = $this->Application->getUnitOption('c', 'TableName'); - - // 2. assign supplemental items to current category to new category - $paste_ids = $this->getCategoryItems($category_id, false); - - foreach ($paste_ids as $item_prefix => $resource_ids) { - if (!$item_prefix) { - // not ItemPrefix filled -> old categoryitem linking - continue; - } - - $item_object =& $this->Application->recallObject($item_prefix.'.-item', null, Array('skip_autoload' => true)); - foreach ($resource_ids as $item_resource_id) { - $item_object->Load($item_resource_id, 'ResourceId'); - $item_object->assignToCategory($new_category_id, false); - } - } - - // 3. clone items that have current category as primary - $paste_ids = $this->getCategoryItems($category_id, true); - - foreach ($paste_ids as $item_prefix => $resource_ids) { - if (!$item_prefix) { - // not ItemPrefix filled -> old categoryitem linking - continue; - } - - // 2. clone items from current category (for each prefix separately) - $item_ids = $this->GetItemIDs($item_prefix, $resource_ids); - $temp_handler->BuildTables($item_prefix, $item_ids); - $temp_handler->CloneItems($item_prefix, '', $item_ids); - } - - // 4. do same stuff for each subcategory - $sql = 'SELECT '.$id_field.' - FROM '.$table_name.' - WHERE ParentId = '.$category_id; - - $sub_categories = $this->Conn->GetCol($sql); - if ($sub_categories) { - foreach ($sub_categories as $sub_category_id) { - $this->PasteCategory($sub_category_id); - } - } - - $this->Application->SetVar('m_cat_id', $backup_category_id); - } - - /** - * Returns grouped category items - * - * @param int $category_id - * @param bool $item_primary_category - * @return Array - */ - function getCategoryItems($category_id, $item_primary_category = true) - { - $ci_table = $this->Application->getUnitOption('ci', 'TableName'); - - $sql = 'SELECT ItemPrefix, ItemResourceId - FROM '.$ci_table.' - WHERE (CategoryId = '.$category_id.') AND (PrimaryCat = '.($item_primary_category ? 1 : 0).')'; - $category_items = $this->Conn->GetCol($sql, 'ItemResourceId'); - - $item_ids = Array(); - foreach ($category_items as $resource_id => $item_prefix) { - $item_ids[$item_prefix][] = $resource_id; - } - return $item_ids; - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/general/helpers/helpers_config.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/helpers_config.php (revision 6093) +++ trunk/kernel/units/general/helpers/helpers_config.php (revision 0) @@ -1,18 +0,0 @@ - 'helpers', - 'EventHandlerClass' => Array('class' => 'kEventHandler', 'file' => '', 'build_event' => 'OnBuild'), - - 'RegisterClasses' => Array( - Array('pseudo'=>'kMultiLanguageHelper','class'=>'kMultiLanguageHelper','file'=>'multilanguage.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'SearchHelper','class'=>'kSearchHelper','file'=>'search_helper.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'SectionsHelper','class'=>'kSectionsHelper','file'=>'sections_helper.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'PermissionsHelper','class'=>'kPermissionsHelper','file'=>'permissions_helper.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'ModulesHelper','class'=>'kModulesHelper','file'=>'modules.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'ModRewriteHelper','class'=>'kModRewriteHelper','file'=>'mod_rewrite_helper.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'RecursiveHelper','class'=>'kRecursiveHelper','file'=>'recursive_helper.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'FilenamesHelper','class'=>'kFilenamesHelper','file'=>'filenames_helper.php','build_event'=>'','require_classes'=>'kHelper'), - Array('pseudo'=>'ClipboardHelper','class'=>'kClipboardHelper','file'=>'clipboard_helper.php','build_event'=>'','require_classes'=>'kHelper'), - ), - ); \ No newline at end of file Index: trunk/kernel/units/general/helpers/filenames_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/filenames_helper.php (revision 6583) +++ trunk/kernel/units/general/helpers/filenames_helper.php (revision 0) @@ -1,90 +0,0 @@ -', '|', '`', - '~', '!', '@', '#', '$', '%', '^', '&', '(', ')', '~', - '+', '=', '-', '{', '}', ']', '[', "'", ';', '.', ',', "\r", "\n"); - - $filename = str_replace($not_allowed, '_', $filename); - $filename = preg_replace('/(_+)/', '_', $filename); - $filename = $this->checkAutoFilename($table, $id_field, $item_id, $filename); - - return $filename; - } - - function checkAutoFilename($table, $id_field, $item_id, $filename) - { - if(!$filename) return $filename; - - $item_id = !$item_id ? 0 : $item_id; - - if ($table == TABLE_PREFIX.'CategoryItems') { - $item_categories_cur = $this->Conn->GetCol('SELECT CategoryId FROM '.$table.' WHERE ItemResourceId = '.$item_id); - $item_categories_live = $this->Application->IsTempTable($table) ? $this->Conn->GetCol('SELECT CategoryId FROM '.$this->Application->GetLiveName($table).' WHERE ItemResourceId = '.$item_id) : array(); - - $item_categories = array_unique(array_merge($item_categories_cur, $item_categories_live)); - if (!$item_categories) { - $item_categories = array($this->Application->GetVar('m_cat_id')); // this may happen when creating new item - } - $cat_filter = ' AND CategoryId IN ('.implode(',', $item_categories).')'; - } - else { - $cat_filter = ''; - } - - // check current table (temp or live) - $sql_temp = 'SELECT '.$id_field.' FROM '.$table.' WHERE Filename = '.$this->Conn->qstr($filename).$cat_filter; - $found_temp_ids = $this->Conn->GetCol($sql_temp); - - // check live table if current is temp - if ( $this->Application->IsTempTable($table) ) { - $sql_live = 'SELECT '.$id_field.' FROM '.$this->Application->GetLiveName($table).' WHERE Filename = '.$this->Conn->qstr($filename).$cat_filter; - $found_live_ids = $this->Conn->GetCol($sql_live); - } - else { - $found_live_ids = array(); - } - - $found_item_ids = array_unique( array_merge($found_temp_ids, $found_live_ids) ); - - $has_page = preg_match('/(.*)_([\d]+)([a-z]*)$/', $filename, $rets); - - $duplicates_found = (count($found_item_ids) > 1) || ($found_item_ids && $found_item_ids[0] != $item_id); - if ($duplicates_found || $has_page) // other category has same filename as ours OR we have filename, that ends with _number - { - $append = $duplicates_found ? '_a' : ''; - if($has_page) - { - $filename = $rets[1].'_'.$rets[2]; - $append = $rets[3] ? $rets[3] : '_a'; - } - - // check live & temp table - $sql_cur = 'SELECT '.$id_field.' FROM '.$table.' WHERE (Filename = %s) AND ('.$id_field.' != '.$item_id.')'.$cat_filter; - $sql_live = $this->Application->IsTempTable($table) ? 'SELECT '.$id_field.' FROM '.$this->Application->GetLiveName($table).' WHERE (Filename = %s) AND ('.$id_field.' != '.$item_id.')'.$cat_filter : false; - while ( $this->Conn->GetOne( sprintf($sql_cur, $this->Conn->qstr($filename.$append)) ) > 0 || - ( $sql_live - && - ( $this->Conn->GetOne( sprintf($sql_live, $this->Conn->qstr($filename.$append)) ) > 0 ) - ) - ) - { - if (substr($append, -1) == 'z') $append .= 'a'; - $append = substr($append, 0, strlen($append) - 1) . chr( ord( substr($append, -1) ) + 1 ); - } - - return $filename.$append; - } - - return $filename; - } - -} \ No newline at end of file Index: trunk/kernel/units/general/helpers/clipboard_helper.php =================================================================== diff -u -N --- trunk/kernel/units/general/helpers/clipboard_helper.php (revision 6093) +++ trunk/kernel/units/general/helpers/clipboard_helper.php (revision 0) @@ -1,48 +0,0 @@ -getObject(); - - $clipboard = $this->Application->RecallVar('clipboard'); - $clipboard = $clipboard ? unserialize($clipboard) : Array(); - - $prefix = $event->getPrefixSpecial(); - - // 1. add $ids to mode key for prefix (make sure the unique) - $this_mode_ids =& $clipboard[$prefix][$mode]; - if (!is_array($this_mode_ids)) { - $this_mode_ids = $ids; - } - else { - $this_mode_ids = array_unique( array_merge($this_mode_ids, $ids) ); - } - - // 2. remove that ids from all other modes - $other_mode_ids =& $clipboard[$prefix][$mode == 'cut' ? 'copy' : 'cut']; - if (!is_array($other_mode_ids)) { - $other_mode_ids = Array(); - } - else { - $other_mode_ids = array_diff($other_mode_ids, $this_mode_ids); - } - - $this->Application->StoreVar('clipboard', serialize($clipboard)); - - /*// do not go up - STAY - $event->SetRedirectParam('opener', 's'); - $event->SetRedirectParam('pass_events', true);*/ - } - } - - -?> \ No newline at end of file Index: trunk/kernel/units/user_groups/user_groups_config.php =================================================================== diff -u -N --- trunk/kernel/units/user_groups/user_groups_config.php (revision 6625) +++ trunk/kernel/units/user_groups/user_groups_config.php (revision 0) @@ -1,95 +0,0 @@ - 'ug', - 'Clones' => Array( - 'g-ug' => Array( - 'ParentPrefix' => 'g', - 'ForeignKey' => 'GroupId', - 'ParentTableKey' => 'GroupId', - ), - - 'u-ug' => Array( - 'ParentPrefix' => 'u', - 'ForeignKey' => 'PortalUserId', - 'ParentTableKey' => 'PortalUserId', - ), - - ), - - 'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'kDBEventHandler','file'=>'','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'), - 'AutoLoad' => true, - - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - ), - - 'IDField' => 'GroupId', - 'StatusField' => Array('UserStatus'), - - 'TableName' => TABLE_PREFIX.'UserGroup', - - 'ListSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON %1$s.GroupId = g.GroupId AND %1$s.PrimaryGroup = 1 - LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON u.PortalUserId = %1$s.PortalUserId'), - - 'ItemSQLs' => Array( ''=>' SELECT %1$s.* %2$s FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON %1$s.GroupId = g.GroupId AND %1$s.PrimaryGroup = 1 - LEFT JOIN '.TABLE_PREFIX.'PortalUser u ON u.PortalUserId = %1$s.PortalUserId'), - - 'AutoDelete' => true, - 'AutoClone' => true, - - 'CalculatedFields' => Array( - '' => Array( - 'Login' => 'u.Login', - 'FirstName' => 'u.FirstName', - 'LastName' => 'u.LastName', - 'Email' => 'u.Email', - 'PrimaryGroup' => 'g.Name', - 'CreatedOn' => 'u.CreatedOn', - 'UserStatus' => 'u.Status' - ), - ), - - 'Fields' => Array( - 'PortalUserId' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'GroupId' => Array(), - 'MembershipExpires' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default' => ''), - 'PrimaryGroup' => Array('type' => 'int','not_null' => '1','default' => '1'), - 'ExpirationReminderSent' => Array('type' => 'int','not_null' => '1','default' => '0'), - ), - - 'VirtualFields' => Array( - 'Login' => Array('type' => 'string'), - 'FirstName' => Array('type' => 'string'), - 'LastName' => Array('type' => 'string'), - 'Email' => Array('type' => 'string'), - 'PrimaryGroup' => Array('type' => 'string'), - 'CreatedOn' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'not_null' => 1, 'default' => '#NOW#'), - 'UserStatus' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(1 => 'la_Enabled', 0 => 'la_Disabled', 2 => 'la_Pending'), 'use_phrases' => 1, 'not_null' => '1','default' => 2), - ), - - - 'Grids' => Array( - 'Default' => Array( - 'Icons' => Array(0 => 'icon16_user_disabled.gif', 1 => 'icon16_user.gif', 2 => 'icon16_user_pending.gif'), - 'Fields' => Array( - 'Login' => Array('title' => 'la_col_Username', 'data_block' => 'grid_checkbox_td'), - 'LastName' => Array( 'title'=>'la_col_LastName'), - 'FirstName' => Array( 'title'=>'la_col_FirstName'), - 'Email' => Array( 'title'=>'la_col_Email'), - 'PrimaryGroup' => Array( 'title'=>'la_col_PrimaryGroup'), - 'CreatedOn_formatted' => Array('title' => 'la_col_CreatedOn', 'sort_field' => 'CreatedOn'), - ), - ), - ), - - ); - -?> \ No newline at end of file Index: trunk/kernel/units/users/users_config.php =================================================================== diff -u -N --- trunk/kernel/units/users/users_config.php (revision 4702) +++ trunk/kernel/units/users/users_config.php (revision 0) @@ -1,267 +0,0 @@ - 'u', - 'ItemClass' => Array('class'=>'UsersItem','file'=>'users_item.php','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'UsersEventHandler','file'=>'users_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'UsersTagProcessor','file'=>'users_tag_processor.php','build_event'=>'OnBuild'), - 'RegisterClasses' => Array( - Array('pseudo' => 'UsersSyncronizeManager', 'class' => 'UsersSyncronizeManager', 'file' => 'users_syncronize.php', 'build_event' => ''), - ), - - 'AutoLoad' => true, - 'Hooks' => Array( - Array( - 'Mode' => hAFTER, - 'Conditional' => false, - 'HookToPrefix' => 'u', - 'HookToSpecial' => '', - 'HookToEvent' => Array('OnAfterItemLoad', 'OnBeforeItemCreate', 'OnBeforeItemUpdate', 'OnUpdateAddress'), - 'DoPrefix' => '', - 'DoSpecial' => '', - 'DoEvent' => 'OnPrepareStates', - ), - - Array( - 'Mode' => hBEFORE, - 'Conditional' => false, - 'HookToPrefix' => 'affil', - 'HookToSpecial' => '', - 'HookToEvent' => Array('OnCheckAffiliateAgreement'), - 'DoPrefix' => '', - 'DoSpecial' => '', - 'DoEvent' => 'OnSubstituteSubscriber', - ), - - ), - - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - 4 => 'mode', - ), - - 'RegularEvents' => Array( - 'membership_expiration' => Array('EventName' => 'OnCheckExpiredMembership', 'RunInterval' => 1800, 'Type' => reAFTER), - ), - - 'IDField' => 'PortalUserId', - - 'StatusField' => Array('Status'), - - 'TitleField' => 'Login', - - 'ItemType' => 6, // used for custom fields only (on user's case) - - 'StatisticsInfo' => Array( - 'pending' => Array( - 'icon' => 'icon16_user_pending.gif', - 'label' => 'la_Text_Users', - 'js_url' => "set_persistant_var('User_View', 4, 'users/users_list', '#url#')", - 'url' => Array('t' => 'users/users_list', 'index_file' => 'users/user_list.php', 'pass' => 'm'), - 'status' => STATUS_PENDING, - ), - ), - - 'TitlePresets' => Array( - 'default' => Array( 'new_status_labels' => Array('u'=>'!la_title_Adding_User!'), - 'edit_status_labels' => Array('u'=>'!la_title_Editing_User!'), - 'new_titlefield' => Array('u'=>'!la_title_New_User!'), - ), - - 'users_list' => Array('prefixes' => Array('u_List'), 'format' => "!la_title_Users! (#u_recordcount#)"), - - 'users_edit' => Array('prefixes' => Array('u'), 'format' => "#u_status# '#u_titlefield#' - !la_title_General!"), - - 'users_select' => Array('prefixes' => Array('u_List'), 'format' => "!la_title_Users! (#u_recordcount#) - !la_title_SelectUser!"), - - 'tree_users' => Array('format' => '!la_section_overview!'), - ), - - - 'PermSection' => Array('main' => 'in-portal:user_list', 'email' => 'in-portal:user_email', 'custom' => 'in-portal:user_custom'), - - 'Sections' => Array( - 'in-portal:users' => Array( - 'parent' => 'in-portal:root', - 'icon' => 'community', - 'label' => 'la_tab_Community', - 'url' => Array('t' => 'sections_list', 'pass_section' => true, 'pass' => 'm'), - 'permissions' => Array('view'), - 'priority' => 2, - 'type' => stTREE, - ), - - 'in-portal:user_list' => Array( - 'parent' => 'in-portal:users', - 'icon' => 'users', - 'label' => 'la_tab_User_List', - 'url' => Array('index_file' => 'users/user_list.php', 'pass' => 'm', 'resetpage' => 1), - 'permissions' => Array('view', 'add', 'edit', 'delete', 'advanced:ban', 'advanced:send_email', /*'advanced:add_favorite', 'advanced:remove_favorite',*/), - 'priority' => 1, - 'type' => stTREE, - ), - - 'in-portal:configure_users' => Array( - 'parent' => 'in-portal:users', - 'icon' => 'users_settings', - 'label' => 'la_tab_ConfigSettings', - 'url' => Array('t' => 'config/config_universal', 'module' => 'In-Portal:Users', 'pass_section' => true, 'pass' => 'm'), - 'permissions' => Array('view', 'edit'), - 'priority' => 3, - 'type' => stTREE, - ), - - 'in-portal:user_email' => Array( - 'parent' => 'in-portal:users', - 'icon' => 'settings_email', - 'label' => 'la_tab_ConfigE-mail', - 'url' => Array('t' => 'config/config_email', 'module' => 'In-Portal:Users', 'pass_section' => true, 'pass' => 'm'), - 'permissions' => Array('view', 'edit'), - 'priority' => 4, - 'type' => stTREE, - ), - - 'in-portal:user_custom' => Array( - 'parent' => 'in-portal:users', - 'icon' => 'settings_custom', - 'label' => 'la_tab_ConfigCustom', - 'url' => Array('t' => 'custom_fields/custom_fields_list', 'cf_type' => 6, 'pass_section' => true, 'pass' => 'm,cf'), - 'permissions' => Array('view', 'add', 'edit', 'delete'), - 'priority' => 5, - 'type' => stTREE, - ), - - 'in-portal:user_banlist' => Array( - 'parent' => 'in-portal:users', - 'icon' => 'banlist', - 'label' => 'la_tab_BanList', - 'url' => Array('index_file' => 'config/edit_banlist.php', 'DataType' => 6, 'pass_section' => true, 'pass' => 'm'), - 'permissions' => Array('view', 'add', 'edit', 'delete'), - 'priority' => 6, - 'type' => stTREE, - ), - ), - - 'TableName' => TABLE_PREFIX.'PortalUser', - - 'ListSQLs' => Array( '' => ' SELECT %1$s.* %2$s FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'UserGroup ug ON %1$s.PortalUserId = ug.PortalUserId AND ug.PrimaryGroup = 1 - LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON ug.GroupId = g.GroupId - LEFT JOIN '.TABLE_PREFIX.'%3$sPortalUserCustomData cust ON %1$s.ResourceId = cust.ResourceId', - ), - - 'ItemSQLs' => Array( '' => ' SELECT %1$s.* %2$s FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'UserGroup ug ON %1$s.PortalUserId = ug.PortalUserId AND ug.PrimaryGroup = 1 - LEFT JOIN '.TABLE_PREFIX.'PortalGroup g ON ug.GroupId = g.GroupId - LEFT JOIN '.TABLE_PREFIX.'%3$sPortalUserCustomData cust ON %1$s.ResourceId = cust.ResourceId', - ), - - 'ListSortings' => Array( - '' => Array( - 'Sorting' => Array('Login' => 'asc'), - ) - ), - - 'SubItems' => Array('addr', 'u-cdata', 'u-ug', 'fav'), - - 'FilterMenu' => Array( - 'Groups' => Array( - Array('mode' => 'AND', 'filters' => Array(0,1,2), 'type' => WHERE_FILTER), - ), - - 'Filters' => Array( - 0 => Array('label' =>'la_Enabled', 'on_sql' => '', 'off_sql' => '%1$s.Status != 1' ), - 1 => Array('label' => 'la_Disabled', 'on_sql' => '', 'off_sql' => '%1$s.Status != 0' ), - 2 => Array('label' => 'la_Pending', 'on_sql' => '', 'off_sql' => '%1$s.Status != 2' ), - ) - ), - - 'CalculatedFields' => Array( - '' => Array( - 'PrimaryGroup' => 'g.Name', - ), - ), - - 'Fields' => Array - ( - 'PortalUserId' => Array(), - 'Login' => Array('type' => 'string', 'unique'=>Array('Login'), 'default' => '','required'=>1, 'error_msgs' => Array('unique'=>'!lu_user_already_exist!')), - 'Password' => Array('type' => 'string', 'formatter' => 'kPasswordFormatter', 'encryption_method' => 'md5', 'verify_field' => 'VerifyPassword', 'skip_empty' => 1, 'default' => md5('') ), - 'FirstName' => Array('type' => 'string','default' => ''), - 'LastName' => Array('type' => 'string','default' => ''), - 'Company' => Array('type' => 'string','not_null' => '1','default' => ''), - 'Email' => Array('type' => 'string', 'formatter'=>'kFormatter', 'regexp'=>'/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/', 'unique'=>Array('Email'), 'not_null' => '1', 'required'=>1, 'default' => '', 'error_msgs' => Array('invalid_format'=>'!la_invalid_email!', 'unique'=>'!lu_email_already_exist!') ), - 'CreatedOn' => Array('type'=>'int', 'formatter' => 'kDateFormatter', 'default' => '#NOW#', 'not_null' => '1' ), - 'Phone' => Array('type' => 'string','default' => ''), - 'Fax' => Array('type' => 'string','not_null' => '1','default' => ''), - 'Street' => Array('type' => 'string','default' => ''), - 'Street2' => Array('type' => 'string', 'not_null' => '1', 'default' => ''), - 'City' => Array('type' => 'string','default' => ''), - 'State' => Array('formatter'=>'kOptionsFormatter', - 'options' => Array(), - 'option_key_field'=>'DestAbbr','option_title_field'=>'Translation', - 'not_null' => '1','default' => ''), - 'Zip' => Array('type' => 'string','default' => ''), - 'Country' => Array('formatter'=>'kOptionsFormatter', - 'options_sql'=>'SELECT %1$s - FROM '.TABLE_PREFIX.'StdDestinations - LEFT JOIN '.TABLE_PREFIX.'Phrase - ON '.TABLE_PREFIX.'Phrase.Phrase = '.TABLE_PREFIX.'StdDestinations.DestName - WHERE - DestType=1 - AND - LanguageId = %2$s - ORDER BY Translation', - 'option_key_field'=>'DestAbbr','option_title_field'=>'Translation', - 'not_null' => '1','default' => ''), - 'ResourceId' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'Status' => Array('type' => 'int', 'formatter'=>'kOptionsFormatter', 'options'=>Array(1=>'la_Enabled', 0=>'la_Disabled', 2=>'la_Pending'), 'use_phrases'=>1, 'not_null' => '1','default' => 2), - 'Modified' => Array('type' => 'int', 'formatter'=>'kDateFormatter', 'not_null' => '1', 'default' => '#NOW#' ), - 'dob' => Array('type'=>'int', 'formatter' => 'kDateFormatter', 'not_null' => '1', 'default' => '', 'required'=>1), - 'tz' => Array('type' => 'int','default' => ''), - 'ip' => Array('type' => 'string','default' => ''), - 'IsBanned' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'PassResetTime' => Array('type' => 'int','default' => ''), - 'PwResetConfirm' => Array('type' => 'string','default' => ''), - 'PwRequestTime' => Array('type' => 'int','default' => ''), - 'MinPwResetDelay' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array('300' => '5', '600' => '10', '900' => '15', '1800' => '30', '3600' => '60'), 'use_phrases' => 0, 'not_null' => '1', 'default' => 30), - ), - - 'VirtualFields' => Array( - 'ValidateLogin' => Array('type'=>'string','default'=>''), - 'SubscribeEmail' => Array('type'=>'string','default'=>''), - 'PrimaryGroup' => Array('type' => 'string', 'default' => ''), - ), - - 'Grids' => Array( - 'Default' => Array( - 'Icons' => Array(0 => 'icon16_user_disabled.gif', 1 => 'icon16_user.gif', 2 => 'icon16_user_pending.gif'), - 'Fields' => Array( - 'Login' => Array('title' => 'la_col_Username', 'data_block' => 'grid_checkbox_td'), - 'LastName' => Array( 'title'=>'la_col_LastName'), - 'FirstName' => Array( 'title'=>'la_col_FirstName'), - 'Email' => Array( 'title'=>'la_col_Email'), - 'PrimaryGroup' => Array( 'title'=>'la_col_PrimaryGroup'), - 'CreatedOn_formatted' => Array('title' => 'la_col_CreatedOn', 'sort_field' => 'CreatedOn'), - ), - ), - - 'UserSelector' => Array( - 'Icons' => Array(0 => 'icon16_user_disabled.gif', 1 => 'icon16_user.gif', 2 => 'icon16_user_pending.gif'), - 'Fields' => Array( - 'Login' => Array('title' => 'la_col_Username', 'data_block' => 'grid_radio_td'), - 'LastName' => Array( 'title'=>'la_col_LastName'), - 'FirstName' => Array( 'title'=>'la_col_FirstName'), - 'Email' => Array( 'title'=>'la_col_Email'), - 'PrimaryGroup' => Array( 'title'=>'la_col_PrimaryGroup'), - 'CreatedOn_formatted' => Array('title' => 'la_col_CreatedOn', 'sort_field' => 'CreatedOn'), - ), - ), - ), - - ); - -?> \ No newline at end of file Index: trunk/kernel/units/users/users_tag_processor.php =================================================================== diff -u -N --- trunk/kernel/units/users/users_tag_processor.php (revision 6093) +++ trunk/kernel/units/users/users_tag_processor.php (revision 0) @@ -1,182 +0,0 @@ - 'all,m,u', 'u_event' => 'OnLogout', 'm_cat_id'=>0); - $logout_template = $this->SelectParam($params, 'template,t'); - return $this->Application->HREF($logout_template, '', $pass); - } - - function UseUsernames($params) - { - return $this->Application->ConfigValue('Email_As_Login') != 1; - } - - function RegistrationEnabled($params) - { - return $this->Application->ConfigValue('User_Allow_New') != 2; - } - - function SuggestRegister($params) - { - return !$this->Application->LoggedIn() && !$this->Application->ConfigValue('Comm_RequireLoginBeforeCheckout') && $this->RegistrationEnabled($params); - } - - function ConfirmPasswordLink($params) - { - //global $m_var_list_update, $var_list_update, $objSession, $objConfig; - - $template = "forgotpw_reset_result"; - - $tmp_user_id = $this->Application->RecallVar("tmp_user_id"); - - $saved_denerated_code = $this->Application->GetVar('saved_denerated_code'); - if ($saved_denerated_code){ - $code = $saved_denerated_code; - } - else { - $code = md5($this->GenerateCode()); - $this->Application->SetVar('saved_denerated_code', $code); - } - - - - $sql = 'UPDATE '.TABLE_PREFIX.'PortalUser SET PwResetConfirm="'.$code.'", PwRequestTime='.adodb_mktime().' WHERE PortalUserId='.$tmp_user_id; - - $this->Conn->Query($sql); - - $params = array_merge($params, array('pass'=>'m', 'user_key'=>$code)); - - $main_processor =& $this->Application->recallObject('m_TagProcessor'); - - return $main_processor->T($params); - - } - - function GenerateCode() - { - list($usec, $sec) = explode(" ",microtime()); - - $id_part_1 = substr($usec, 4, 4); - $id_part_2 = mt_rand(1,9); - $id_part_3 = substr($sec, 6, 4); - $digit_one = substr($id_part_1, 0, 1); - if ($digit_one == 0) { - $digit_one = mt_rand(1,9); - $id_part_1 = ereg_replace("^0","",$id_part_1); - $id_part_1=$digit_one.$id_part_1; - } - return $id_part_1.$id_part_2.$id_part_3; - } - - function ForgottenPassword($params){ - return $this->Application->GetVar('ForgottenPassword'); - } - - function TestCodeIsValid($param){ - - $passed_key = $this->Application->GetVar('user_key'); - - $user_object = &$this->Application->recallObject('u.forgot'); - $user_current_object = &$this->Application->recallObject('u'); - - if (strlen(trim($passed_key)) == 0) { - - $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); - $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_is_not_valid'; - return false; - } - - - if($user_object->Load(array('PwResetConfirm'=>$passed_key))) - { - $exp_time = $user_object->GetDBField('PwRequestTime') + 3600; - if ($exp_time > adodb_mktime()) - { - - - } else { - $user_current_object->ErrorMsgs['code_expired'] = $this->Application->Phrase('lu_code_expired'); - $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_expired'; - return false; - - } - } else { - $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); - $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_is_not_valid'; - return false; - - } - - return true; - } - - /** - * Returns sitem administrator email - * - * @param Array $params - * @return string - */ - function SiteAdminEmail($params) - { - return $this->Application->ConfigValue('Smtp_AdminMailFrom'); - } - - function AffiliatePaymentTypeChecked($params) - { - static $checked = false; - - if( $this->Application->GetVar('PaymentTypeId') ) - { - $apt_object =& $this->Application->recallObject('apt.active'); - if( $this->Application->GetVar('PaymentTypeId') == $apt_object->GetDBField('PaymentTypeId') ) - { - return 1; - } - else - { - return 0; - } - } - - if(!$checked) - { - $checked = true; - return 1; - } - else - { - return 0; - } - } - - function HasError($params) - { - $res = parent::HasError($params); - if($this->SelectParam($params,'field,fields') == 'any') - { - $res = $res || $this->Application->GetVar('MustAgreeToTerms'); // need to do it not put module fields into kernel ! (noticed by Alex) - $res = $res || $this->Application->GetVar('SSNRequiredError'); - } - return $res; - } - - /** - * Returns login name of user - * - * @param Array $params - */ - function LoginName($params) - { - $object =& $this->getObject($params); - return $object->GetID() != -1 ? $object->GetDBField('Login') : 'root'; - } - - } - - - -?> \ No newline at end of file Index: trunk/kernel/units/users/users_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/users/users_event_handler.php (revision 6625) +++ trunk/kernel/units/users/users_event_handler.php (revision 0) @@ -1,1035 +0,0 @@ - Array('self' => 'view'), // because setting to logged in user only - - // front - 'OnRefreshForm' => Array('self' => true), - - 'OnForgotPassword' => Array('self' => true), - 'OnResetPassword' => Array('self' => true), - 'OnResetPasswordConfirmed' => Array('self' => true), - - 'OnSubscribeQuery' => Array('self' => true), - 'OnSubscribeUser' => Array('self' => true), - - 'OnRecommend' => Array('self' => true), - ); - $this->permMapping = array_merge($this->permMapping, $permissions); - } - - /** - * Checks permissions of user - * - * @param kEvent $event - */ - function CheckPermission(&$event) - { - if ($event->Name == 'OnLogin' || $event->Name == 'OnLogout') { - // permission is checked in OnLogin event directly - return true; - } - - if (!$this->Application->IsAdmin()) { - $user_id = $this->Application->GetVar('u_id'); - $items_info = $this->Application->GetVar($event->getPrefixSpecial(true)); - - if ($event->Name == 'OnCreate' && $user_id == -2) { - // "Guest" can create new users - return true; - } - - if ($event->Name == 'OnUpdate' && $user_id > 0) { - $user_dummy =& $this->Application->recallObject($event->Prefix.'.-item', null, Array('skip_autoload' => true)); - foreach ($items_info as $id => $field_values) { - if ($id != $user_id) { - // registered users can update their record only - return false; - } - - $user_dummy->Load($id); - $status_field = array_shift($this->Application->getUnitOption($event->Prefix, 'StatusField')); - - if ($user_dummy->GetDBField($status_field) != STATUS_ACTIVE) { - // not active user is not allowed to update his record (he could not activate himself manually) - return false; - } - - if (isset($field_values[$status_field]) && $user_dummy->GetDBField($status_field) != $field_values[$status_field]) { - // user can't change status by himself - return false; - } - } - return true; - } - - if ($event->Name == 'OnUpdate' && $user_id <= 0) { - // guests are not allowed to update their record, because they don't have it :) - return false; - } - } - - return parent::CheckPermission($event); - } - - function OnSessionExpire() - { - if( $this->Application->IsAdmin() ) { - $this->Application->Redirect('index', Array('expired' => 1), '', 'index.php'); - } - else { - $http_query =& $this->Application->recallObject('HTTPQuery'); - $get = $http_query->getRedirectParams(); - - $t = $this->Application->GetVar('t'); - $get['js_redirect'] = $this->Application->ConfigValue('UseJSRedirect'); - $this->Application->Redirect($t ? $t : 'index', $get); - } - } - - /** - * Checks user data and logs it in if allowed - * - * @param kEvent $event - */ - function OnLogin(&$event) - { - $object =& $this->Application->recallObject('u', null, Array('skip_autoload' => true)); - - $password = $this->Application->GetVar('password'); - if(!$password) - { - $object->SetError('ValidateLogin', 'blank_password', 'lu_blank_password'); - $event->status = erFAIL; - return false; - } - - $email_as_login = $this->Application->ConfigValue('Email_As_Login'); - list($login_field, $submit_field) = $email_as_login && !$this->Application->IsAdmin() ? Array('Email', 'email') : Array('Login', 'login'); - $login_value = $this->Application->GetVar($submit_field); - - if ($this->Application->IsAdmin() && ($login_value == 'root')) { - // logging in "root" (admin only) - $root_password = $this->Application->ConfigValue('RootPass'); - $password_formatter =& $this->Application->recallObject('kPasswordFormatter'); - $test = $password_formatter->EncryptPassword($password, 'b38'); - if ($root_password != $test) { - $object->SetError('ValidateLogin', 'invalid_password', 'lu_invalid_password'); - $event->status = erFAIL; - return false; - } - elseif ($this->checkLoginPermission($login_value)) { - $user_id = -1; - $object->Load($user_id); - $object->SetDBField('Login', $login_value); - - $session =& $this->Application->recallObject('Session'); - $session->SetField('PortalUserId', $user_id); -// $session->SetField('GroupList', implode(',', $groups) ); - $this->Application->SetVar('u_id', $user_id); - $this->Application->StoreVar('user_id', $user_id); - - $this->processLoginRedirect($event, $password); - return true; - } - else { - $object->SetError('ValidateLogin', 'invalid_license', 'la_invalid_license'); - $event->status = erFAIL; - return false; - } - } - - /*$sql = 'SELECT PortalUserId FROM '.$object->TableName.' WHERE (%s = %s) AND (Password = MD5(%s))'; - $user_id = $this->Conn->GetOne( sprintf($sql, $login_field, $this->Conn->qstr($login_value), $this->Conn->qstr($password) ) );*/ - - $sql = 'SELECT PortalUserId FROM '.$object->TableName.' WHERE (Email = %1$s OR Login = %1$s) AND (Password = MD5(%2$s))'; - $user_id = $this->Conn->GetOne( sprintf($sql, $this->Conn->qstr($login_value), $this->Conn->qstr($password) ) ); - - if ($user_id) { - $object->Load($user_id); - if ($object->GetDBField('Status') == STATUS_ACTIVE) { - $groups = $object->getMembershipGroups(true); - if(!$groups) $groups = Array(); - array_push($groups, $this->Application->ConfigValue('User_LoggedInGroup') ); - $this->Application->StoreVar( 'UserGroups', implode(',', $groups) ); - - if ($this->checkLoginPermission($login_value)) { - $session =& $this->Application->recallObject('Session'); - $session->SetField('PortalUserId', $user_id); - $session->SetField('GroupList', implode(',', $groups) ); - $this->Application->SetVar('u_id', $user_id); - $this->Application->StoreVar('user_id', $user_id); - $this->Application->setVisitField('PortalUserId', $user_id); - - $this_login = (int)$object->getPersistantVar('ThisLogin'); - $object->setPersistantVar('LastLogin', $this_login); - $object->setPersistantVar('ThisLogin', adodb_mktime()); - } - else { - $object->Load(-2); - $object->SetError('ValidateLogin', 'no_permission', 'lu_no_permissions'); - $event->status = erFAIL; - } - - $this->processLoginRedirect($event, $password); - } - else { - $event->redirect = $this->Application->GetVar('pending_disabled_template'); - } - } - else - { - $object->SetID(-2); - $object->SetError('ValidateLogin', 'invalid_password', 'lu_invalid_password'); - $event->status = erFAIL; - } - } - - /** - * Enter description here... - * - * @param string $user_name - * @return bool - */ - function checkLoginPermission($user_name) - { - $ret = true; - if ($this->Application->IsAdmin()) { - $modules_helper =& $this->Application->recallObject('ModulesHelper'); - if ($user_name != 'root') { - // root is virtual user, so allow him to login to admin in any case - $ret = $this->Application->CheckPermission('ADMIN', 1); - } - $ret = $ret && $modules_helper->checkLogin(); - } - else { - $ret = $this->Application->CheckPermission('LOGIN', 1); - } - return $ret; - } - - /** - * Process all required data and redirect logged-in user - * - * @param kEvent $event - */ - function processLoginRedirect(&$event, $password) - { - $object =& $event->getObject(); - - $next_template = $this->Application->GetVar('next_template'); - if ($next_template == '_ses_redirect') { - $location = $this->Application->BaseURL().$this->Application->RecallVar($next_template); - if( $this->Application->isDebugMode() && constOn('DBG_REDIRECT') ) - { - $this->Application->Debugger->appendTrace(); - echo "Debug output above!!! Proceed to redirect: $location
"; - } - else { - header('Location: '.$location); - } - - $session =& $this->Application->recallObject('Session'); - $session->SaveData(); - exit; - } - - if ($next_template) { - $event->redirect = $next_template; - } - - if ($this->Application->ConfigValue('UseJSRedirect')) { - $event->SetRedirectParam('js_redirect', 1); - } - - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LoginUser', $object->GetDBField('Login'), $password); - } - - /** - * Called when user logs in using old in-portal - * - * @param kEvent $event - */ - function OnInpLogin(&$event) - { - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LoginUser', $event->getEventParam('user'), $event->getEventParam('pass') ); - - if ($event->redirect && is_string($event->redirect)) { - // some real template specified instead of true - $this->Application->Redirect($event->redirect, $event->redirect_params); - } - } - - /** - * Called when user logs in using old in-portal - * - * @param kEvent $event - */ - function OnInpLogout(&$event) - { - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LogoutUser'); - } - - function OnLogout(&$event) - { - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('LogoutUser'); - - $session =& $this->Application->recallObject('Session'); - $session->SetField('PortalUserId', -2); - $this->Application->SetVar('u_id', -2); - $this->Application->StoreVar('user_id', -2); - $object =& $this->Application->recallObject('u'); - $object->Load(-2); - - $this->Application->DestroySession(); - - $group_list = $this->Application->ConfigValue('User_GuestGroup').','.$this->Application->ConfigValue('User_LoggedInGroup'); - $session->SetField('GroupList', $group_list); - $this->Application->StoreVar('UserGroups', $group_list); - - if ($this->Application->ConfigValue('UseJSRedirect')) { - $event->SetRedirectParam('js_redirect', 1); - } - } - - /** - * Prefill states dropdown with correct values - * - * @param kEvent $event - * @access public - */ - function OnPrepareStates(&$event) - { - $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); - $cs_helper->PopulateStates($event, 'State', 'Country'); - - $object =& $event->getObject(); - - if( $object->isRequired('Country') && $cs_helper->CountryHasStates( $object->GetDBField('Country') ) ) $object->setRequired('State', true); - $object->setLogin(); - } - - /** - * Redirects user after succesfull registration to confirmation template (on Front only) - * - * @param kEvent $event - */ - function OnAfterItemCreate(&$event) - { - $is_subscriber = $this->Application->GetVar('IsSubscriber'); - if(!$is_subscriber) - { - $object =& $event->getObject(); - - $sql = 'UPDATE '.TABLE_PREFIX.'UserGroup - SET PrimaryGroup = 0 - WHERE PortalUserId = '.$object->GetDBField('PortalUserId'); - $this->Conn->Query($sql); - - $group_id = $this->Application->ConfigValue('User_NewGroup'); - - $sql = 'REPLACE INTO '.TABLE_PREFIX.'UserGroup(PortalUserId,GroupId,PrimaryGroup) VALUES (%s,%s,1)'; - $this->Conn->Query( sprintf($sql, $object->GetID(), $group_id) ); - } - } - - /** - * Login user if possible, if not then redirect to corresponding template - * - * @param kEvent $event - */ - function autoLoginUser(&$event) - { - $object =& $event->getObject(); - $this->Application->SetVar('u_id', $object->GetID() ); - - if($object->GetDBField('Status') == STATUS_ACTIVE) - { - $email_as_login = $this->Application->ConfigValue('Email_As_Login'); - list($login_field, $submit_field) = $email_as_login ? Array('Email', 'email') : Array('Login', 'login'); - - $this->Application->SetVar($submit_field, $object->GetDBField($login_field) ); - $this->Application->SetVar('password', $object->GetDBField('Password_plain') ); - - $event->CallSubEvent('OnLogin'); - } - } - - - /** - * When creating user & user with such email exists then force to use OnUpdate insted of ? - * - * @param kEvent $event - */ - function OnSubstituteSubscriber(&$event) - { - $ret = false; - $object =& $event->getObject( Array('skip_autoload' => true) ); - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if($items_info) - { - list($id, $field_values) = each($items_info); - $user_email = $field_values['Email']; - if($user_email) - { - // check if is subscriber - $verify_user =& $this->Application->recallObject('u.verify', null, Array('skup_autoload' => true) ); - $verify_user->Load($user_email, 'Email'); - if( $verify_user->isLoaded() && $verify_user->isSubscriberOnly() ) - { - $items_info = Array( $verify_user->GetDBField('PortalUserId') => $field_values ); - $this->Application->SetVar($event->getPrefixSpecial(true), $items_info); - $ret = true; - } - } - } - - if( isset($event->MasterEvent) ) - { - $event->MasterEvent->setEventParam('is_subscriber_only', $ret); - } - else - { - $event->setEventParam('is_subscriber_only', $ret); - } - } - - - /** - * Enter description here... - * - * @param kEvent $event - * @return bool - */ - function isSubscriberOnly(&$event) - { - $event->CallSubEvent('OnSubstituteSubscriber'); - $is_subscriber = false; - if( $event->getEventParam('is_subscriber_only') ) - { - $is_subscriber = true; - $object =& $event->getObject( Array('skip_autoload' => true) ); - $this->OnUpdate($event); - if($event->status == erSUCCESS) - { - $this->OnAfterItemCreate($event); - $object->SendEmailEvents(); - if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect) $this->autoLoginUser($event); - } - } - return $is_subscriber; - } - - /** - * Creates new user - * - * @param kEvent $event - */ - function OnCreate(&$event) - { - if( !$this->Application->IsAdmin() ) $this->setUserStatus($event); - - if( !$this->isSubscriberOnly($event) ) - { - $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); - $cs_helper->CheckStateField($event, 'State', 'Country'); - - parent::OnCreate($event); - - $object =& $event->getObject( Array('skip_autoload' => true) ); - - $this->Application->SetVar('u_id', $object->getID() ); - - $this->setNextTemplate($event); - - if( !$this->Application->IsAdmin() && ($event->status == erSUCCESS) && $event->redirect) - { - $object->SendEmailEvents(); - $this->autoLoginUser($event); - } - } - } - - /** - * Set's new user status based on config options - * - * @param kEvent $event - */ - function setUserStatus(&$event) - { - $object =& $event->getObject( Array('skip_autoload' => true) ); - - $new_users_allowed = $this->Application->ConfigValue('User_Allow_New'); - // 1 - Instant, 2 - Not Allowed, 3 - Pending - - switch ($new_users_allowed) - { - case 1: // Instant - $object->SetDBField('Status', 1); - $next_template = $this->Application->GetVar('registration_confirm_template'); - if($next_template) $event->redirect = $next_template; - break; - - case 3: // Pending - $next_template = $this->Application->GetVar('registration_confirm_pending_template'); - if($next_template) $event->redirect = $next_template; - $object->SetDBField('Status', 2); - break; - - case 2: // Not Allowed - $object->SetDBField('Status', 0); - break; - } - - /*if ($object->GetDBField('PaidMember') == 1) { - $this->Application->HandleEvent($add_to_cart, 'ord:OnAddToCart'); - $event->redirect = 'in-commerce/checkout/shop_cart'; - } */ - - } - - - - - /** - * Set's new unique resource id to user - * - * @param kEvent $event - */ - function OnBeforeItemCreate(&$event) - { - $email_as_login = $this->Application->ConfigValue('Email_As_Login'); - $object =& $event->getObject(); - if ($email_as_login) { - $object->Fields['Email']['error_msgs']['unique'] = $this->Application->Phrase('lu_user_and_email_already_exist'); - } - - } - - /** - * Set's new unique resource id to user - * - * @param kEvent $event - */ - function OnAfterItemValidate(&$event) - { - $object =& $event->getObject(); - $resource_id = $object->GetDBField('ResourceId'); - if (!$resource_id) - { - $object->SetDBField('ResourceId', $this->Application->NextResourceId() ); - } - } - - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnRecommend(&$event){ - - $friend_email = $this->Application->GetVar('friend_email'); - $friend_name = $this->Application->GetVar('friend_email'); - - if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $friend_email)) - { - - $send_params = array(); - $send_params['to_email']=$friend_email; - $send_params['to_name']=$friend_name; - - $user_id = $this->Application->GetVar('u_id'); - $email_event = &$this->Application->EmailEventUser('SITE.SUGGEST', $user_id, $send_params); - - if ($email_event->status == erSUCCESS){ - $event->redirect_params = array('opener' => 's', 'pass' => 'all'); - $event->redirect = $this->Application->GetVar('template_success'); - } - else { -// $event->redirect_params = array('opener' => 's', 'pass' => 'all'); -// $event->redirect = $this->Application->GetVar('template_fail'); - $object =& $this->Application->recallObject('u'); - $object->ErrorMsgs['send_error'] = $this->Application->Phrase('lu_email_send_error'); - $object->FieldErrors['Email']['pseudo'] = 'send_error'; - $event->status = erFAIL; - - } - } - else { - $object =& $this->Application->recallObject('u'); - $object->ErrorMsgs['invalid_email'] = $this->Application->Phrase('lu_InvalidEmail'); - $object->FieldErrors['Email']['pseudo'] = 'invalid_email'; - $event->status = erFAIL; - } - - - } - - /** - * Saves address changes and mades no redirect - * - * @param kEvent $event - */ - function OnUpdateAddress(&$event) - { - $object =& $event->getObject( Array('skip_autoload' => true) ); - - $items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) ); - if($items_info) - { - list($id,$field_values) = each($items_info); - if($id > 0) $object->Load($id); - $object->SetFieldsFromHash($field_values); - $object->setID($id); - $object->Validate(); - } - - $event->redirect = false; - } - - function OnSubscribeQuery(&$event){ - - $user_email = $this->Application->GetVar('subscriber_email'); - if ( preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email) ){ - - $object = &$this->Application->recallObject($this->Prefix.'.subscriber', null, Array('skip_autoload' => true)); - - $this->Application->StoreVar('SubscriberEmail', $user_email); - - if( $object->Load(array('Email'=>$user_email)) ){ - $group_info = $this->GetGroupInfo($object->GetID()); - if($group_info){ - $event->redirect = $this->Application->GetVar('unsubscribe_template'); - } - else { - $event->redirect = $this->Application->GetVar('subscribe_template'); - } - } - else { - $event->redirect = $this->Application->GetVar('subscribe_template'); - $this->Application->StoreVar('SubscriberEmail', $user_email); - } - - } - else { - - $object =& $this->Application->recallObject('u'); - $object->ErrorMsgs['invalid_email'] = $this->Application->Phrase('lu_InvalidEmail'); - $object->FieldErrors['SubscribeEmail']['pseudo'] = 'invalid_email'; - $event->status = erFAIL; - - } - - - //subscribe_query_ok_template - } - - function OnSubscribeUser(&$event){ - - $object = &$this->Application->recallObject($this->Prefix.'.subscriber', null, Array('skip_autoload' => true)); - - $user_email = $this->Application->RecallVar('SubscriberEmail'); - - if (preg_match("/^[_a-zA-Z0-9-\.]+@[a-zA-Z0-9-\.]+\.[a-z]{2,4}$/", $user_email)){ - - if($object->Load(array('Email'=>$user_email))){ - - $group_info = $this->GetGroupInfo($object->GetID()); - - if ($group_info){ - if ($event->getEventParam('no_unsubscribe')) return; - - if ($group_info['PrimaryGroup']){ - // delete user - $object->Delete(); - } - else { - $this->RemoveSubscriberGroup($object->GetID()); - } - - $event->redirect = $this->Application->GetVar('unsubscribe_ok_template'); - - } - else { - $this->AddSubscriberGroup($object->GetID(), 0); - $event->redirect = $this->Application->GetVar('subscribe_ok_template'); - } - - - } - else { - - $object->SetField('Email', $user_email); - $object->SetField('Login', $user_email); - $object->SetDBField('dob', 1); - $object->SetDBField('dob_date', 1); - $object->SetDBField('dob_time', 1); - $ip = getenv('HTTP_X_FORWARDED_FOR')?getenv('HTTP_X_FORWARDED_FOR'):getenv('REMOTE_ADDR'); - $object->SetDBField('ip', $ip); - - $this->Application->SetVar('IsSubscriber', 1); - - if ($object->Create()) { - - $this->AddSubscriberGroup($object->GetID(), 1); - $event->redirect = $this->Application->GetVar('subscribe_ok_template'); - } - - $this->Application->SetVar('IsSubscriber', 0); - } - } - else { - // error handling here - $event->redirect = $this->Application->GetVar('subscribe_fail_template'); - } - - - } - - function AddSubscriberGroup($user_id, $is_primary){ - - $group_id = $this->Application->ConfigValue('User_SubscriberGroup'); - $sql = 'INSERT INTO '.TABLE_PREFIX.'UserGroup(PortalUserId,GroupId,PrimaryGroup) VALUES (%s,%s,'.$is_primary.')'; - $this->Conn->Query( sprintf($sql, $user_id, $group_id) ); - $this->Application->EmailEventAdmin('USER.SUBSCRIBE', $user_id); - $this->Application->EmailEventUser('USER.SUBSCRIBE', $user_id); - - } - - function RemoveSubscriberGroup($user_id){ - - $group_id = $this->Application->ConfigValue('User_SubscriberGroup'); - $sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroup WHERE PortalUserId='.$user_id.' AND GroupId='.$this->Application->ConfigValue('User_SubscriberGroup'); - $this->Conn->Query($sql); - $this->Application->EmailEventAdmin('USER.UNSUBSCRIBE', $user_id); - $this->Application->EmailEventUser('USER.UNSUBSCRIBE', $user_id); - - } - - function GetGroupInfo($user_id){ - - $group_info = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'UserGroup - WHERE PortalUserId='.$user_id.' - AND GroupId='.$this->Application->ConfigValue('User_SubscriberGroup')); - return $group_info; - - } - - function OnForgotPassword(&$event){ - - $user_object = &$this->Application->recallObject('u.forgot', null, Array('skip_autoload' => true)); - $user_current_object = &$this->Application->recallObject('u'); - - $username = $this->Application->GetVar('username'); - $email = $this->Application->GetVar('email'); - $found = false; - $allow_reset = true; - - if( strlen($username) ) - { - if( $user_object->Load(array('Login'=>$username)) ) - $found = ($user_object->GetDBField("Login")==$username && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password")); - } - else if( strlen($email) ) - { - if( $user_object->Load(array('Email'=>$email)) ) - $found = ($user_object->GetDBField("Email")==$email && $user_object->GetDBField("Status")==1) && strlen($user_object->GetDBField("Password")); - } - - if( $user_object->isLoaded() ) - { - $PwResetConfirm = $user_object->GetDBField('PwResetConfirm'); - $PwRequestTime = $user_object->GetDBField('PwRequestTime'); - $PassResetTime = $user_object->GetDBField('PassResetTime'); - //$MinPwResetDelay = $user_object->GetDBField('MinPwResetDelay'); - $MinPwResetDelay = $this->Application->ConfigValue('Users_AllowReset'); - - $allow_reset = (strlen($PwResetConfirm) ? - adodb_mktime() > $PwRequestTime + $MinPwResetDelay : - adodb_mktime() > $PassResetTime + $MinPwResetDelay); - } - - if($found && $allow_reset) - { - $this->Application->StoreVar('tmp_user_id', $user_object->GetDBField("PortalUserId")); - $this->Application->StoreVar('tmp_email', $user_object->GetDBField("Email")); - $this->Application->EmailEventUser('INCOMMERCEUSER.PSWDC', $user_object->GetDBField("PortalUserId")); - - $event->redirect = $this->Application->GetVar('template_success'); - } - else - { - if(!strlen($username) && !strlen($email)) - { - $user_current_object->ErrorMsgs['forgotpw_nodata'] = $this->Application->Phrase('lu_ferror_forgotpw_nodata'); - $user_current_object->FieldErrors['Login']['pseudo'] = 'forgotpw_nodata'; - $user_current_object->FieldErrors['Email']['pseudo'] = 'forgotpw_nodata'; - } - else - { - if($allow_reset) - { - if( strlen($username) ){ - $user_current_object->ErrorMsgs['unknown_username'] = $this->Application->Phrase('lu_ferror_unknown_username'); - $user_current_object->FieldErrors['Login']['pseudo']='unknown_username'; - } - if( strlen($email) ){ - $user_current_object->ErrorMsgs['unknown_email'] = $this->Application->Phrase('lu_ferror_unknown_email'); - $user_current_object->FieldErrors['Email']['pseudo']='unknown_email'; - } - } - else - { - $user_current_object->ErrorMsgs['reset_denied'] = $this->Application->Phrase('lu_ferror_reset_denied'); - if( strlen($username) ){ - $user_current_object->FieldErrors['Login']['pseudo']='reset_denied'; - } - if( strlen($email) ){ - $user_current_object->FieldErrors['Email']['pseudo']='reset_denied'; - } - } - } - - if($user_current_object->FieldErrors){ - $event->redirect = false; - } - } - - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnResetPassword(&$event){ - - $user_object = &$this->Application->recallObject('u.forgot'); - - if($user_object->Load($this->Application->RecallVar('tmp_user_id'))){ - - $this->Application->EmailEventUser('INCOMMERCEUSER.PSWDC', $user_object->GetDBField("PortalUserId")); - $event->redirect = $this->Application->GetVar('template_success'); - - $mod_object =& $this->Application->recallObject('mod.'.'In-Commerce'); - $m_cat_id = $mod_object->GetDBField('RootCat'); - $event->SetRedirectParam('pass', 'm'); - //$event->SetRedirectParam('m_cat_id', $m_cat_id); - $this->Application->SetVar('m_cat_id', $m_cat_id); - - - } - - } - - function OnResetPasswordConfirmed(&$event){ - - $passed_key = $this->Application->GetVar('user_key'); - - $user_object = &$this->Application->recallObject('u.forgot'); - $user_current_object = &$this->Application->recallObject('u'); - - if (strlen(trim($passed_key)) == 0) { - $event->redirect_params = array('opener' => 's', 'pass' => 'all'); - $event->redirect = false; - - $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); - $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_is_not_valid'; - } - - - if($user_object->Load(array('PwResetConfirm'=>$passed_key))) - { - $exp_time = $user_object->GetDBField('PwRequestTime') + 3600; - $user_object->SetDBField("PwResetConfirm", ''); - $user_object->SetDBField("PwRequestTime", 0); - if ( $exp_time > adodb_mktime() ) - { - //$m_var_list_update['codevalidationresult'] = 'lu_resetpw_confirm_text'; - $newpw = makepassword4(); - - $this->Application->StoreVar('password', $newpw); - - $user_object->SetDBField("Password",$newpw); - $user_object->SetDBField("PassResetTime", adodb_mktime()); - $user_object->SetDBField("PwResetConfirm", ''); - $user_object->SetDBField("PwRequestTime", 0); - $user_object->Update(); - - $this->Application->SetVar('ForgottenPassword', $newpw); - - $email_event_user = &$this->Application->EmailEventUser('INCOMMERCEUSER.PSWD', $user_object->GetDBField('PortalUserId')); - $email_event_admin = &$this->Application->EmailEventAdmin('INCOMMERCEUSER.PSWD'); - - $this->Application->DeleteVar('ForgottenPassword'); - - if ($email_event_user->status == erSUCCESS){ - $event->redirect_params = array('opener' => 's', 'pass' => 'all'); - $event->redirect = $this->Application->GetVar('template_success'); - } - - $user_object->SetDBField("Password",md5($newpw)); - $user_object->Update(); - - } else { - $user_current_object->ErrorMsgs['code_expired'] = $this->Application->Phrase('lu_code_expired'); - $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_expired'; - $event->redirect = false; - - } - } else { - $user_current_object->ErrorMsgs['code_is_not_valid'] = $this->Application->Phrase('lu_code_is_not_valid'); - $user_current_object->FieldErrors['PwResetConfirm']['pseudo'] = 'code_is_not_valid'; - $event->redirect = false; - - } - } - - function OnUpdate(&$event) - { - $cs_helper =& $this->Application->recallObject('CountryStatesHelper'); - $cs_helper->CheckStateField($event, 'State', 'Country'); - - parent::OnUpdate($event); - - $this->setNextTemplate($event); - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function setNextTemplate(&$event) - { - if( !$this->Application->IsAdmin() ) - { - $event->redirect_params['opener'] = 's'; - $object =& $event->getObject(); - if($object->GetDBField('Status') == STATUS_ACTIVE) - { - $next_template = $this->Application->GetVar('next_template'); - if($next_template) $event->redirect = $next_template; - } - } - } - - - - /** - * Delete users from groups if their membership is expired - * - * @param kEvent $event - */ - function OnCheckExpiredMembership(&$event) - { - // send pre-expiration reminders: begin - $pre_expiration = adodb_mktime() + $this->Application->ConfigValue('User_MembershipExpirationReminder') * 3600 * 24; - $sql = 'SELECT PortalUserId, GroupId - FROM '.TABLE_PREFIX.'UserGroup - WHERE (MembershipExpires IS NOT NULL) AND (ExpirationReminderSent = 0) AND (MembershipExpires < '.$pre_expiration.')'; - - $skip_clause = $event->getEventParam('skip_clause'); - if ($skip_clause) { - $sql .= ' AND !('.implode(') AND !(', $skip_clause).')'; - } - - $records = $this->Conn->Query($sql); - if ($records) { - $conditions = Array(); - foreach ($records as $record) { - $email_event_user =& $this->Application->EmailEventUser('USER.MEMBERSHIP.EXPIRATION.NOTICE', $record['PortalUserId']); - $email_event_admin =& $this->Application->EmailEventAdmin('USER.MEMBERSHIP.EXPIRATION.NOTICE'); - $conditions[] = '(PortalUserId = '.$record['PortalUserId'].' AND GroupId = '.$record['GroupId'].')'; - } - $sql = 'UPDATE '.TABLE_PREFIX.'UserGroup - SET ExpirationReminderSent = 1 - WHERE '.implode(' OR ', $conditions); - $this->Conn->Query($sql); - } - // send pre-expiration reminders: end - - // remove users from groups with expired membership: begin - $sql = 'SELECT PortalUserId - FROM '.TABLE_PREFIX.'UserGroup - WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')'; - $user_ids = $this->Conn->GetCol($sql); - if ($user_ids) { - foreach ($user_ids as $id) { - $email_event_user =& $this->Application->EmailEventUser('USER.MEMBERSHIP.EXPIRED', $id); - $email_event_admin =& $this->Application->EmailEventAdmin('USER.MEMBERSHIP.EXPIRED'); - } - } - $sql = 'DELETE FROM '.TABLE_PREFIX.'UserGroup - WHERE (MembershipExpires IS NOT NULL) AND (MembershipExpires < '.adodb_mktime().')'; - $this->Conn->Query($sql); - // remove users from groups with expired membership: end - } - - /** - * Enter description here... - * - * @param kEvent $event - */ - function OnRefreshForm(&$event) - { - $event->redirect = false; - $item_info = $this->Application->GetVar($event->Prefix_Special); - list($id, $fields) = each($item_info); - - $object =& $event->getObject( Array('skip_autoload' => true) ); - $object->setID($id); - $object->IgnoreValidation = true; - $object->SetFieldsFromHash($fields); - } - - /** - * Sets persistant variable - * - * @param kEvent $event - */ - function OnSetPersistantVariable(&$event) - { - $object =& $event->getObject(); - - $field = $this->Application->GetVar('field'); - $value = $this->Application->GetVar('value'); - $object->setPersistantVar($field, $value); - - $force_tab = $this->Application->GetVar('SetTab'); - if ($force_tab) { - $this->Application->StoreVar('force_tab', $force_tab); - } - } - - /** - * Overwritten to return user from order by special .ord - * - * @param kEvent $event - */ - function getPassedId(&$event) - { - if ($event->Special == 'ord') { - $order =& $this->Application->recallObject('ord'); - return $order->GetDBField('PortalUserId'); - } - return parent::getPassedID($event); - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/users/users_item.php =================================================================== diff -u -N --- trunk/kernel/units/users/users_item.php (revision 6583) +++ trunk/kernel/units/users/users_item.php (revision 0) @@ -1,165 +0,0 @@ -GetID(); - if (!$id) return ; - $sql = 'SELECT VariableValue, VariableName - FROM '.TABLE_PREFIX.'PersistantSessionData - WHERE PortalUserId = '.$id; - $this->persistantVars = $this->Conn->GetCol($sql, 'VariableName'); - } - - function setPersistantVar($var_name, $var_value) - { - $this->persistantVars[$var_name] = $var_value; - - if ($this->GetID() > 0 || $this->GetID() == -1) { - $replace_hash = Array( 'PortalUserId' => $this->GetID(), - 'VariableName' => $var_name, - 'VariableValue' => $var_value - ); - $this->Conn->doInsert($replace_hash, TABLE_PREFIX.'PersistantSessionData', 'REPLACE'); - } - else { - $this->Application->StoreVar($var_name, $var_value); - } - } - - function getPersistantVar($var_name) - { - return getArrayValue($this->persistantVars, $var_name); - } - - function Load($id, $id_field_name = null) - { - $ret = parent::Load($id, $id_field_name); - if ($ret || $id == -1) { - $this->LoadPersistantVars($id); - } - return $ret; - } - - /** - * Returns IDs of groups to which user belongs and membership is not expired - * - * @return Array - * @access public - */ - function getMembershipGroups($force_reload = false) - { - $user_groups = $this->Application->RecallVar('UserGroups'); - if($user_groups === false || $force_reload) - { - $sql = 'SELECT GroupId FROM %s WHERE (PortalUserId = %s) AND ( (MembershipExpires IS NULL) OR ( MembershipExpires >= UNIX_TIMESTAMP() ) )'; - $sql = sprintf($sql, TABLE_PREFIX.'UserGroup', $this->GetID() ); - return $this->Conn->GetCol($sql); - } - else - { - return explode(',', $user_groups); - } - } - - /** - * Set's Login from Email if required by configuration settings - * - */ - function setLogin() - { - if( $this->Application->ConfigValue('Email_As_Login') ) - { - $this->SetDBField('Login', $this->GetDBField('Email') ); - } - } - - function SendEmailEvents() - { - switch( $this->GetDBField('Status') ) - { - case 1: - $this->Application->EmailEventAdmin('USER.ADD', $this->GetID() ); - $this->Application->EmailEventUser('USER.ADD', $this->GetID() ); - break; - - case 2: - $this->Application->EmailEventAdmin('USER.ADD.PENDING', $this->GetID() ); - $this->Application->EmailEventUser('USER.ADD.PENDING', $this->GetID() ); - break; - } - } - - function isSubscriberOnly() - { - $subscribers_group_id = $this->Application->ConfigValue('User_SubscriberGroup'); - $sql = 'SELECT PortalUserId - FROM '.TABLE_PREFIX.'UserGroup - WHERE GroupId = '.$subscribers_group_id.' AND - PortalUserId = '.$this->GetDBField('PortalUserId').' AND - PrimaryGroup = 1'; - return $this->Conn->GetOne($sql) == $this->GetDBField('PortalUserId'); - } - - function Create($force_id=false, $system_create=false) - { - $ret = parent::Create($force_id, $system_create); - if ($ret) { - // find out how to syncronize user only when it's copied to live table - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('createUser', $this->FieldValues); - } - return $ret; - } - - - function Update($id=null, $system_update=false) - { - $ret = parent::Update($id, $system_update); - if ($ret) { - // find out how to syncronize user only when it's copied to live table - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('updateUser', $this->FieldValues); - } - return $ret; - } - - /** - * Deletes the record from databse - * - * @access public - * @return bool - */ - function Delete($id = null) - { - $ret = parent::Delete($id); - if ($ret) { - $sync_manager =& $this->Application->recallObjectP('UsersSyncronizeManager', null, Array(), 'InPortalSyncronize'); - $sync_manager->performAction('deleteUser', $this->FieldValues); - } - - return $ret; - } - - function setName($full_name) - { - $full_name = explode(' ', $full_name); - - if (count($full_name) > 2) { - $last_name = array_pop($full_name); - $first_name = implode(' ', $full_name); - } - else { - $last_name = $full_name[1]; - $first_name = $full_name[0]; - } - - $this->SetDBField('FirstName', $first_name); - $this->SetDBField('LastName', $last_name); - } - - - } -?> \ No newline at end of file Index: trunk/kernel/units/users/users_syncronize.php =================================================================== diff -u -N --- trunk/kernel/units/users/users_syncronize.php (revision 4758) +++ trunk/kernel/units/users/users_syncronize.php (revision 0) @@ -1,167 +0,0 @@ -skipClass = $skip_class; - - $defs_file = SYNC_CLASS_PATH.'/sync_config.php'; - - if (file_exists($defs_file)) - { - include_once $defs_file; - foreach ($sync_classes as $class_info) { - $this->addSyncClass($class_info['class_name'], SYNC_CLASS_PATH.'/'.$class_info['class_file'], $class_info['sub_folder']); - } - } - } - - function addSyncClass($class_name, $class_file, $sub_folder) - { - $this->syncClasses[$class_name] = Array('file' => $class_file, 'sub_folder' => $sub_folder); - } - - /** - * Performs action specified for all syncronization classes. - * You can pass other arguments to function, they will be passed to action handler - * - * @param string $action - */ - function performAction($action) - { - $args = func_get_args(); - array_shift($args); - - foreach ($this->syncClasses as $class_name => $class_info) { - if ($class_name == $this->skipClass) continue; - $this->Application->registerClass($class_name, $class_info['file']); - $sync_object =& $this->Application->recallObjectP($class_name, null, Array(), $class_info['sub_folder'], $class_name); - call_user_func_array( Array(&$sync_object, $action), $args); - } - } - - /** - * Create new instance of object - * - * @return kBase - */ - function &makeClass($skip_class) - { - $sync_manager = new UsersSyncronizeManager($skip_class); - return $sync_manager; - } - } - - - /** - * Base class for 3rd party site user syncronizations - * - */ - class UsersSyncronize extends kBase { - - /** - * Sub folder to which syncronizable tool is installed - * - * @var string - */ - var $subFolder = ''; - - /** - * Connection to database - * - * @var kDBConnection - * @access public - */ - var $Conn; - - function UsersSyncronize($sub_folder) - { - parent::kBase(); - $this->subFolder = $sub_folder; - $this->Conn =& $this->Application->GetADODBConnection(); - } - - /** - * Used to login user with given username & password - * - * @param string $user - * @param string $password - * @return bool - */ - function LoginUser($user, $password) - { - return true; - } - - /** - * Used to logout currently logged in user (if any) - * - */ - function LogoutUser() - { - - } - - /** - * Creates user - * - * @param Array $user_data - * @return bool - */ - function createUser($user_data) - { - return true; - } - - /** - * Update user info with given $user_id - * - * @param Array $user_data - * @return bool - */ - function updateUser($user_data) - { - return true; - } - - /** - * Deletes user - * - * @param Array $user_data - * @return bool - */ - function deleteUser($user_data) - { - return true; - } - - /** - * Create new instance of object - * - * @return kBase - */ - function &makeClass($sub_folder, $class_name) - { - return new $class_name($sub_folder); - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/email_messages/email_messages_config.php =================================================================== diff -u -N --- trunk/kernel/units/email_messages/email_messages_config.php (revision 1566) +++ trunk/kernel/units/email_messages/email_messages_config.php (revision 0) @@ -1,49 +0,0 @@ - 'emailmessages', - 'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'EmailMessagesEventHandler','file'=>'email_messages_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'), - 'AutoLoad' => true, - - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - ), - - 'IDField' => 'EmailMessageId', - - 'TitleField' => 'Subject', - - 'TableName' => TABLE_PREFIX.'EmailMessage', - - 'ListSQLs' => Array( ''=>'SELECT * FROM %s'), - - 'ItemSQLs' => Array( ''=>'SELECT * FROM %s'), - - 'ForeignKey' => 'LanguageId', - 'ParentTableKey' => 'LanguageId', - 'ParentPrefix' => 'lang', - 'AutoDelete' => true, - 'AutoClone' => true, - - 'Fields' => Array( - 'EmailMessageId' => Array(), - 'Template' => Array('type' => 'string','default' => ''), - 'MessageType' => Array('type' => 'string', 'formatter'=>'kOptionsFormatter', 'options'=>Array('text'=>'la_Text','html'=>'la_Html'), 'not_null' => '1','default' => 'text'), - 'LanguageId' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'EventId' => Array('type' => 'int','not_null' => '1','default' => '0'), - ), - - 'VirtualFields' => Array( - 'Headers' => Array('type'=>'string'), - 'Subject' => Array('type'=>'string'), - 'Body' => Array('type'=>'string'), - ), - - ); - -?> \ No newline at end of file Index: trunk/kernel/units/email_messages/email_messages_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/email_messages/email_messages_event_handler.php (revision 6625) +++ trunk/kernel/units/email_messages/email_messages_event_handler.php (revision 0) @@ -1,137 +0,0 @@ -getEmailEventId(); - $object =& $event->getObject(); - - $parent_info = $object->getLinkedInfo(); - - $sql = 'SELECT '.$object->IDField.' FROM '.$object->TableName.' WHERE ('.$parent_info['ForeignKey'].' = '.$parent_info['ParentId'].') AND (EventId = '.$email_event_id.')'; - - $id = (int)$this->Conn->GetOne($sql); - if(!$id) - { - $object->SetDBField('EventId', $email_event_id); - $object->SetDBField('Headers', $this->Application->ConfigValue('Smtp_DefaultHeaders') ); - } - return $id; - } - - function getEmailEventId() - { - return parent::getPassedID( new kEvent('emailevents:OnDummy') ); - } - - /** - * If loading empty item, then set parent id - * - * @param kEvent $event - */ - function OnBeforeItemLoad(&$event) - { - if( !$event->getEventParam('id') ) - { - $this->OnNew($event); - $event->status = erFATAL; - } - } - - /** - * Parse message template (split into header, subject & body) - * - * @param kEvent $event - */ - function OnAfterItemLoad(&$event) - { - $object =& $event->getObject(); - - $lines = explode("\n", $object->GetDBField('Template') ); - - $headers = Array(); - - foreach($lines as $line) - { - if( strlen(trim($line)) == 0 || ($line == '.') ) break; - - $parts = explode(':', $line, 2); - if(strtolower($parts[0]) == 'subject') - { - $object->SetDBField('Subject', trim($parts[1]) ); - } - else - { - $headers[] = $line; - } - } - $object->SetDBField('Headers', implode("\n", $headers) ); - - $message_body = ''; - while( (list($line_id,$line) = each($lines)) ) - { - $message_body .= $line; - } - $object->SetDBField('Body', $message_body); - } - - /** - * Merge body+subject+headers into message template - * - * @param kEvent $event - */ - function OnBeforeItemUpdate(&$event) - { - $this->parseVirtualFields($event); - } - - /** - * Merge body+subject+headers into message template - * - * @param kEvent $event - */ - function OnBeforeItemCreate(&$event) - { - $this->parseVirtualFields($event); - } - - /** - * Merge body+subject+headers into message template - * - * @param kEvent $event - */ - function parseVirtualFields(&$event) - { - $object =& $event->getObject(); - if( $object->GetDBField('Headers') || $object->GetDBField('Subject') || $object->GetDBField('Body') ) - { - $ret = $object->GetDBField('Headers'); - if($ret) $ret .= "\n"; - - $ret = $this->removeTrailingCRLF($ret); - $ret .= 'Subject: '.$object->GetDBField('Subject')."\n\n"; - $ret .= $object->GetDBField('Body'); - $object->SetDBField('Template', $ret); - } - } - - /** - * Remove trailing CR/LF chars from string - * - * @param string $string - * @return string - */ - function removeTrailingCRLF($string) - { - return preg_replace('/(\n|\r)+/',"\\1",$string); - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/phrases/phrases_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/phrases/phrases_event_handler.php (revision 6625) +++ trunk/kernel/units/phrases/phrases_event_handler.php (revision 0) @@ -1,95 +0,0 @@ -Application->IsAdmin() && $this->Application->isDebugMode() && constOn('DBG_PHRASES')) { - if ($event->Name == 'OnNew' || $event->Name == 'OnCreate') { - return true; - } - } - - return parent::CheckPermission($event); - } - - /** - * Forces new label in case if issued from get link - * - * @param kEvent $event - */ - function OnNew(&$event) - { - parent::OnNew($event); - $label = $this->Application->GetVar('phrases_label'); - - $object =& $event->getObject( $label ? Array('live_table'=>true, 'skip_autoload' => true) : Array('skip_autoload' => true) ); - if ($label) { - $object->SetDBField('Phrase',$label); - $object->SetDBField('LanguageId', $this->Application->GetVar('m_lang') ); - $object->SetDBField('PhraseType',1); - - $primary_language = $this->Application->GetDefaultLanguageId(); - $live_table = $this->Application->getUnitOption($event->Prefix, 'TableName'); - $sql = 'SELECT Translation FROM %s WHERE Phrase = %s'; - $primary_value = $this->Conn->GetOne( sprintf($sql, $live_table, $this->Conn->qstr($label) ) ); - $object->SetDBField('PrimaryTranslation', $primary_value); - } - - $last_module = $this->Application->GetVar('last_module'); - if($last_module) $object->SetDBField('Module', $last_module); - - if($event->Special == 'export' || $event->Special == 'import') - { - $object->SetDBField('PhraseType', '|0|1|2|'); - $modules = $this->Conn->GetCol('SELECT Name FROM '.TABLE_PREFIX.'Modules'); - $object->SetDBField('Module', '|'.implode('|', $modules).'|' ); - } - } - - /** - * Forces create to use live table - * - * @param kEvent $event - */ - function OnBeforePhraseCreate(&$event) - { - $edit_direct = $this->Application->GetVar($event->Prefix.'_label'); - if ($edit_direct) { - $object =& $event->getObject( Array('skip_autoload' => true) ); - if ($this->Application->GetVar('m_lang') != $this->Application->GetVar('lang_id')) { - $object->SwitchToLive(); - } - } - } - - /** - * Save phrase change date & ip translation was made from - * - * @param kEvent $event - */ - function OnSetLastUpdated(&$event) - { - $object =& $event->getObject(); - $prev_translation = $this->Conn->GetOne('SELECT Translation FROM '.$object->TableName.' WHERE '.$object->IDField.' = '.(int)$object->GetId() ); - if( $prev_translation != $object->GetDBField('Translation') ) - { - $ip_address = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR'); - $object->SetDBField('LastChanged_date', adodb_mktime() ); - $object->SetDBField('LastChanged_time', adodb_mktime() ); - $object->SetDBField('LastChangeIP', $ip_address); - } - - $cookie_path = $this->Application->IsAdmin() ? BASE_PATH.'/admin' : BASE_PATH; - setcookie('last_module', $object->GetDBField('Module'), $cookie_path, '.'.SERVER_NAME); - } - } - - -?> \ No newline at end of file Index: trunk/kernel/units/phrases/phrases_config.php =================================================================== diff -u -N --- trunk/kernel/units/phrases/phrases_config.php (revision 6093) +++ trunk/kernel/units/phrases/phrases_config.php (revision 0) @@ -1,133 +0,0 @@ - 'phrases', - 'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'PhrasesEventHandler','file'=>'phrases_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'), - 'AutoLoad' => true, - - 'Hooks' => Array( - Array( - 'Mode' => hBEFORE, - 'Conditional' => false, - 'HookToPrefix' => 'phrases', - 'HookToSpecial' => '', - 'HookToEvent' => Array('OnCreate'), - 'DoPrefix' => 'phrases', - 'DoSpecial' => '', - 'DoEvent' => 'OnBeforePhraseCreate', - ), - - Array( - 'Mode' => hAFTER, - 'Conditional' => false, - 'HookToPrefix' => 'phrases', - 'HookToSpecial' => '', - 'HookToEvent' => Array('OnBeforeItemCreate','OnBeforeItemUpdate'), - 'DoPrefix' => 'phrases', - 'DoSpecial' => '', - 'DoEvent' => 'OnSetLastUpdated', - ), - ), - - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - 4 => 'label', - ), - 'IDField' => 'PhraseId', - - 'TitleField' => 'Phrase', - - 'TitlePresets' => Array( - 'default' => Array( 'new_status_labels' => Array('phrases'=>'!la_title_Adding_Phrase!'), - 'edit_status_labels' => Array('phrases'=>'!la_title_Editing_Phrase!'), - 'new_titlefield' => Array('phrases'=>'!la_title_New_Phrase!'), - ), - - 'phrase_edit' => Array('prefixes' => Array('phrases'), 'format' => '#phrases_status# - #phrases_titlefield#'), - - ), - - 'FilterMenu' => Array( - 'Groups' => Array( - Array('mode' => 'AND', 'filters' => Array('show_front','show_admin','show_both'), 'type' => WHERE_FILTER), - Array('mode' => 'AND', 'filters' => Array('translated', 'not_translated'), 'type' => WHERE_FILTER), - ), - 'Filters' => Array( - 'show_front' => Array('label' =>'la_PhraseType_Front', 'on_sql' => '', 'off_sql' => '%1$s.PhraseType != 0'), - 'show_admin' => Array('label' => 'la_PhraseType_Admin', 'on_sql' => '', 'off_sql' => '%1$s.PhraseType != 1'), - 'show_both' => Array('label' => 'la_PhraseType_Both', 'on_sql' => '', 'off_sql' => '%1$s.PhraseType != 2'), - 's1' => Array(), - 'translated' => Array('label' => 'la_PhraseTranslated', 'on_sql' => '', 'off_sql' => '%1$s.Translation = pri.Translation'), - 'not_translated' => Array('label' => 'la_PhraseNotTranslated', 'on_sql' => '', 'off_sql' => '%1$s.Translation != pri.Translation'), - ) - ), - - 'TableName' => TABLE_PREFIX.'Phrase', - - 'CalculatedFields' => Array( - '' => Array( - 'PrimaryTranslation' => 'pri.Translation', - ), - - ), - - 'ListSQLs' => Array( ''=>' SELECT %1$s.* %2$s - FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'Phrase pri ON (%1$s.Phrase = pri.Phrase) AND (pri.LanguageId = 1)'), - - 'ItemSQLs' => Array( ''=>' SELECT %1$s.* %2$s - FROM %1$s - LEFT JOIN '.TABLE_PREFIX.'Phrase pri ON (%1$s.Phrase = pri.Phrase) AND (pri.LanguageId = 1)',), - - 'ListSortings' => Array( - '' => Array( - 'Sorting' => Array('Phrase' => 'asc'), - ) - ), - - 'ForeignKey' => 'LanguageId', - 'ParentTableKey' => 'LanguageId', - 'ParentPrefix' => 'lang', - 'AutoDelete' => true, - 'AutoClone' => true, - - 'Fields' => Array( - 'Phrase' => Array('type' => 'string','required'=>1,'unique'=>Array('LanguageId'),'not_null' => '1','default' => ''), - 'Translation' => Array('type' => 'string','required'=>1,'not_null' => '1','default' => ''), - 'PhraseType' => Array('type' => 'int','required'=>1,'formatter'=>'kOptionsFormatter','options'=>Array(0=>'la_PhraseType_Front',1=>'la_PhraseType_Admin',2=>'la_PhraseType_Both'), 'use_phrases' => 1, 'not_null' => '1','default' => '0'), - 'PhraseId' => Array('type' => 'int','not_null' => '1','default' => ''), - 'LanguageId' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'LastChanged' => Array('type' => 'int', 'formatter'=>'kDateFormatter', 'not_null' => '1','default' => '0'), - 'LastChangeIP' => Array('type' => 'string','not_null' => '1','default' => ''), - 'Module' => Array('type' => 'string', 'formatter'=>'kOptionsFormatter', 'options'=>Array(''=>''), 'options_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'Modules WHERE Loaded = 1 ORDER BY LoadOrder', 'option_key_field'=>'Name', 'option_title_field'=>'Name', 'not_null' => '1','default' => 'In-Portal'), - ), - - 'VirtualFields' => Array( - 'PrimaryTranslation' => Array(), - 'LangFile' => Array(), - 'ImportOverwrite' => Array(), - 'DoNotEncode' => Array(), - ), - - 'Grids' => Array( - 'Default' => Array( - 'Icons' => Array('default'=>'icon16_language_var.gif'), - 'Fields' => Array( - 'Phrase' => Array( 'title'=>'la_col_Label', 'data_block' => 'grid_checkbox_td'), - 'Translation' => Array( 'title'=>'la_col_Translation' ), - 'PrimaryTranslation' => Array( 'title'=>'la_col_PrimaryValue' ), - 'PhraseType' => Array( 'title'=>'la_col_PhraseType' ), - 'LastChanged' => Array( 'title'=>'la_col_LastChanged' ), - 'Module' => Array( 'title'=>'la_col_Module' ), - ), - - ), - ), - ); - -?> \ No newline at end of file Index: trunk/kernel/units/languages/languages_config.php =================================================================== diff -u -N --- trunk/kernel/units/languages/languages_config.php (revision 6583) +++ trunk/kernel/units/languages/languages_config.php (revision 0) @@ -1,168 +0,0 @@ - 'lang', - 'ItemClass' => Array('class'=>'LanguagesItem','file'=>'languages_item.php','build_event'=>'OnItemBuild'), - 'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'), - 'EventHandlerClass' => Array('class'=>'LanguagesEventHandler','file'=>'languages_event_handler.php','build_event'=>'OnBuild'), - 'TagProcessorClass' => Array('class'=>'LanguagesTagProcessor','file'=>'languages_tag_processor.php','build_event'=>'OnBuild'), - 'RegisterClasses' => Array( - Array('pseudo'=>'LangXML','class'=>'LangXML_Parser','file'=>'import_xml.php'), - ), - - 'AutoLoad' => true, - 'Hooks' => Array( - Array( - 'Mode' => hAFTER, - 'Conditional' => false, - 'HookToPrefix' => 'lang', - 'HookToSpecial' => '', - 'HookToEvent' => Array('OnSave'), - 'DoPrefix' => '', - 'DoSpecial' => '', - 'DoEvent' => 'OnReflectMultiLingualFields', - ), - - Array( - 'Mode' => hAFTER, - 'Conditional' => false, - 'HookToPrefix' => 'lang', - 'HookToSpecial' => '', - 'HookToEvent' => Array('OnPreSave'), - 'DoPrefix' => '', - 'DoSpecial' => '', - 'DoEvent' => 'OnCopyLabels', - ), - - Array( - 'Mode' => hAFTER, - 'Conditional' => false, - 'HookToPrefix' => 'lang', - 'HookToSpecial' => '*', - 'HookToEvent' => Array('OnSave'), - 'DoPrefix' => '', - 'DoSpecial' => '', - 'DoEvent' => 'OnUpdatePrimary', - ), - ), - 'QueryString' => Array( - 1 => 'id', - 2 => 'page', - 3 => 'event', - 4 => 'mode', - ), - 'IDField' => 'LanguageId', - - 'StatusField' => Array('Enabled','PrimaryLang'), // field, that is affected by Approve/Decline events - - 'TitleField' => 'PackName', // field, used in bluebar when editing existing item - - 'TitlePresets' => Array( - 'default' => Array( 'new_status_labels' => Array('lang'=>'!la_title_Adding_Language!'), - 'edit_status_labels' => Array('lang'=>'!la_title_Editing_Language!'), - 'new_titlefield' => Array('lang'=>'!la_title_New_Language!'), - ), - - 'languages_list' => Array( 'prefixes' => Array('lang_List'), 'format' => "!la_title_Configuration! - !la_title_LanguagePacks! (#lang_recordcount#)"), - - 'languages_edit_general' => Array( 'prefixes' => Array('lang'), 'format' => "#lang_status# '#lang_titlefield#' - !la_title_General!"), - - 'phrases_list' => Array( 'prefixes' => Array('lang','phrases_List'), 'format' => "#lang_status# '#lang_titlefield#' - !la_title_Labels! (#phrases_recordcount#)"), - - 'import_language' => Array( 'prefixes' => Array('phrases.import'), 'format' => "!la_title_InstallLanguagePackStep1!"), - - 'import_language_step2' => Array( 'prefixes' => Array('phrases.import'), 'format' => "!la_title_InstallLanguagePackStep2!"), - - 'export_language' => Array( 'prefixes' => Array('phrases.export'), 'format' => "!la_title_ExportLanguagePackStep1!"), - - 'export_language_results' => Array( 'prefixes' => Array('phrases.export'), 'format' => "!la_title_ExportLanguagePackResults!"), - - 'events_list' => Array( 'prefixes' => Array('lang','emailevents_List'), 'format' => "#lang_status# '#lang_titlefield#' - !la_title_EmailEvents! (#emailevents_recordcount#)"), - - 'event_edit' => Array( 'prefixes' => Array('emailevents'), - 'edit_status_labels' => Array('emailevents' => '!la_title_Editing_EmailEvent!'), - 'format' => '#emailevents_status# - #emailevents_titlefield#'), - - 'email_messages_edit' => Array( 'prefixes' => Array('lang','emailmessages'), - 'new_titlefield' => Array('emailmessages' => '!la_NoSubject!'), - 'format' => "#lang_status# '#lang_titlefield#' - !la_title_EditingEmailEvent! '#emailmessages_titlefield#'"), - ), - - 'PermSection' => Array('main' => 'in-portal:configure_lang'), - - 'Sections' => Array( - 'in-portal:configure_lang' => Array( - 'parent' => 'in-portal:system', - 'icon' => 'conf_regional', - 'label' => 'la_tab_Regional', - 'url' => Array('t' => 'regional/languages_list', 'pass' => 'm'), - 'permissions' => Array('view', 'add', 'edit', 'delete', 'advanced:set_primary', 'advanced:import', 'advanced:export'), - 'priority' => 2, - 'type' => stTREE, - ), - - ), - - 'TableName' => TABLE_PREFIX.'Language', - 'SubItems' => Array('phrases','emailmessages'), - - 'FilterMenu' => Array( - 'Groups' => Array( - Array('mode' => 'AND', 'filters' => Array(0,1), 'type' => WHERE_FILTER), - ), - - 'Filters' => Array( - 0 => Array('label' =>'la_Enabled', 'on_sql' => '', 'off_sql' => '%1$s.Enabled != 1' ), - 1 => Array('label' => 'la_Disabled', 'on_sql' => '', 'off_sql' => '%1$s.Enabled != 0' ), - ) - ), - - 'AutoDelete' => true, - - 'AutoClone' => true, - - 'ListSQLs' => Array( ''=>'SELECT * FROM %s', - ), // key - special, value - list select sql - 'ItemSQLs' => Array( ''=>'SELECT * FROM %s', - ), - 'ListSortings' => Array( - '' => Array( - 'Sorting' => Array('PackName' => 'asc'), - ) - ), - 'Fields' => Array( - 'LanguageId' => Array(), - 'PackName' => Array('type' => 'string','not_null' => '1','default' => '','required'=>1), - 'LocalName' => Array('type' => 'string','not_null' => '1','default' => '','required'=>1), - 'Enabled' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array(0 => 'la_Disabled', 1 => 'la_Enabled'), 'use_phrases' => 1, 'not_null' => '1', 'default' => '0'), - 'PrimaryLang' => Array('type' => 'int','not_null' => '1','default' => '0'), - 'IconURL' => Array('type' => 'string','default' => ''), - 'DateFormat' => Array('type' => 'string','not_null' => '1','default' => '','required'=>1), - 'TimeFormat' => Array('type' => 'string','not_null' => '1','default' => '','required'=>1), - 'InputDateFormat' => Array('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array('m/d/Y' => 'm/d/Y'), 'not_null' => '1','default' => 'm/d/Y', 'required' => 1), - 'InputTimeFormat' => Array('type' => 'string', 'formatter' => 'kOptionsFormatter', 'options' => Array('g:i:s A' => 'g:i:s A'), 'not_null' => '1','default' => 'g:i:s A', 'required' => 1), - 'DecimalPoint' => Array('type' => 'string','not_null' => '1','default' => ''), - 'ThousandSep' => Array('type' => 'string','not_null' => '1','default' => ''), - 'Charset' => Array('type' => 'string','not_null' => '1','default' => '','required'=>1), - 'UnitSystem' => Array('type' => 'int','not_null' => '1','default' => '1','formatter' => 'kOptionsFormatter','options' => Array(1 => 'la_Metric', 2 => 'la_US_UK'),'use_phrases' => 1), - ), - - 'VirtualFields' => Array( - 'CopyLabels' => Array('type' => 'int', 'default' => 0), - 'CopyFromLanguage' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options_sql' => 'SELECT %s FROM '.TABLE_PREFIX.'Language ORDER BY PackName', 'option_title_field' => 'PackName', 'option_key_field' => 'LanguageId'), - ), - - 'Grids' => Array( - 'Default' => Array( - 'Icons' => Array('default'=>'icon16_custom.gif','0_0'=>'icon16_language_disabled.gif','1_0'=>'icon16_language.gif','0_1'=>'icon16_language_disabled.gif','1_1'=>'icon16_language_primary.gif'), - 'Fields' => Array( - 'PackName' => Array( 'title'=>'la_col_PackName', 'data_block' => 'grid_checkbox_td'), - 'LocalName' => Array( 'title'=>'la_col_LocalName' ), - 'Enabled' => Array( 'title'=>'la_col_Status' ), - ), - - ), - ), - ); - -?> \ No newline at end of file Index: trunk/kernel/units/languages/languages_tag_processor.php =================================================================== diff -u -N --- trunk/kernel/units/languages/languages_tag_processor.php (revision 3115) +++ trunk/kernel/units/languages/languages_tag_processor.php (revision 0) @@ -1,67 +0,0 @@ -Application->GetVar('phrases_label'); - - $top_prefix = $this->Application->GetTopmostPrefix($this->Prefix); - if( $this->Application->GetVar($top_prefix.'_mode') == 't' && !$edit_direct ) - { - $object =& $this->Application->recallObject($this->getPrefixSpecial(), $this->Prefix, $params); - return $object->GetDBField('Charset'); - } - $lang_current =& $this->Application->recallObject('lang.current'); - return $lang_current->GetDBField('Charset'); - } - - function ListLanguages($params) - { - $this->Special = 'enabled'; - return $this->PrintList2($params); - } - - function SelectedLanguage($params) - { - $object =& $this->Application->recallObject($this->getPrefixSpecial()); - return $object->GetDBField('LanguageId') == $this->Application->GetVar('m_lang'); - } - - /** - * Returns path where exported languages should be saved - * - * @param unknown_type $params - */ - function ExportPath($params) - { - $admin_folder = $this->Application->ConfigValue('AdminDirectory'); - if(!$admin_folder) $admin_folder = 'admin'; - $ret = FULL_PATH.'/'.$admin_folder.'/export/'; - - if( getArrayValue($params,'as_url') ) - { - $ret = str_replace( FULL_PATH.'/', $this->Application->BaseURL(), $ret); - } - return $ret; - } - -/* function Main_IsMetricUnits($params) - { - $object =& $this->Application->recallObject($this->Prefix.'.current'); - $measure_system = $object->GetDBField('UnitSystem'); - return $measure_system == 1 ? 1 : 0; - }*/ - - } - -?> \ No newline at end of file Index: trunk/kernel/units/languages/languages_item.php =================================================================== diff -u -N --- trunk/kernel/units/languages/languages_item.php (revision 6583) +++ trunk/kernel/units/languages/languages_item.php (revision 0) @@ -1,67 +0,0 @@ -IDField.') FROM '.$this->Application->GetLiveName($this->TableName); - return $this->Conn->GetOne($sql) + 1; - } - - function setPrimary($reset_primary = true) - { - if ($reset_primary) { - $sql = 'UPDATE '.$this->TableName.' - SET PrimaryLang = 0'; - $this->Conn->Query($sql); - } - - $sql = 'UPDATE '.$this->TableName.' - SET PrimaryLang = 1, Enabled = 1 - WHERE '.$this->IDField.' = '.$this->GetID(); - $this->Conn->Query($sql); - } - - /** - * Allows to format number according to regional settings - * - * @param float $number - * @param int $precision - * @return float - */ - function formatNumber($number, $precision = null) - { - if (is_null($precision)) { - $precision = preg_match('/[\.,]+/', $number) ? strlen(preg_replace('/^.*[\.,]+/', '', $number)) : 0; - } - return number_format($number, $precision, $this->GetDBField('DecimalPoint'), $this->GetDBField('ThousandSep')); - } - - function Load($id, $id_field_name=null) - { - $default = false; - if ($id == 'default') { - $id = 1; - $id_field_name = 'PrimaryLang'; - $default = true; - } - - $res = parent::Load($id, $id_field_name); - - if ($default) { - if (!$res) { - if ($this->Application->IsAdmin()) { - $res = parent::Load(1); - } - else { - $this->Application->ApplicationDie('No Primary Language Selected'); - } - } - $this->Application->SetVar('lang.current_id', $this->GetID() ); - $this->Application->SetVar('m_lang', $this->GetID() ); - } - return $res; - } - } - -?> \ No newline at end of file Index: trunk/kernel/units/languages/languages_event_handler.php =================================================================== diff -u -N --- trunk/kernel/units/languages/languages_event_handler.php (revision 6625) +++ trunk/kernel/units/languages/languages_event_handler.php (revision 0) @@ -1,438 +0,0 @@ - Array('self' => true), - 'OnSetPrimary' => Array('self' => 'advanced:set_primary|add|edit'), - 'OnImportLanguage' => Array('self' => 'advanced:import'), - 'OnImportProgress' => Array('self' => 'advanced:import'), - 'OnExportLanguage' => Array('self' => 'advanced:export'), - 'OnExportProgress' => Array('self' => 'advanced:export'), - - ); - $this->permMapping = array_merge($this->permMapping, $permissions); - } - - /** - * Updates table structure on new language adding/removing language - * - * @param kEvent $event - */ - function OnReflectMultiLingualFields($event) - { - $ml_helper =& $this->Application->recallObject('kMultiLanguageHelper'); - - $this->Application->UnitConfigReader->includeConfigFiles(MODULES_PATH); //make sure to re-read all configs - foreach ($this->Application->UnitConfigReader->configData as $prefix => $config_data) { - $ml_helper->createFields($prefix); - } - } - - /** - * Allows to set selected language as primary - * - * @param kEvent $event - */ - function OnSetPrimary(&$event) - { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { - return; - } - - $this->StoreSelectedIDs($event); - $ids = $this->getSelectedIDs($event); - if ($ids) { - $id = array_shift($ids); - $object =& $event->getObject( Array('skip_autoload' => true) ); - $object->Load($id); - $object->setPrimary(); - } - } - - /** - * [HOOK] Reset primary status of other languages if we are saving primary language - * - * @param kEvent $event - */ - function OnUpdatePrimary(&$event) - { - $object =& $event->getObject( Array('skip_autoload' => true) ); - $object->SwitchToLive(); - - // set primary for each languages, that have this checkbox checked - $ids = explode(',', $event->MasterEvent->getEventParam('ids')); - foreach ($ids as $id) { - $object->Load($id); - if ($object->GetDBField('PrimaryLang')) { - $object->setPrimary(); - } - - } - - // if no primary language left, then set primary last language (not to load again) from edited list - $sql = 'SELECT '.$object->IDField.' - FROM '.$object->TableName.' - WHERE PrimaryLang = 1'; - $primary_language = $this->Conn->GetOne($sql); - - if (!$primary_language) { - $object->setPrimary(false); - } - } - - - /** - * Occurse before updating item - * - * @param kEvent $event - * @access public - */ - function OnBeforeItemUpdate(&$event) - { - $object =& $event->getObject(); - $status_field = array_shift( $this->Application->getUnitOption($event->Prefix, 'StatusField') ); - - if ($object->GetDBField('PrimaryLang') == 1 && $object->GetDBField($status_field) == 0) { - $object->SetDBField($status_field, 1); - } - } - - /** - * Shows only enabled languages on front - * - * @param kEvent $event - */ - function SetCustomQuery(&$event) - { - if($event->Special == 'enabled') - { - $object =& $event->getObject(); - $object->addFilter('enabled_filter', '%1$s.Enabled = 1'); - } - } - - /** - * Copy labels from another language - * - * @param kEvent $event - */ - function OnCopyLabels(&$event) - { - $object =& $event->getObject(); - $from_lang_id = $object->GetDBField('CopyFromLanguage'); - - if( ($event->MasterEvent->status == erSUCCESS) && $object->GetDBField('CopyLabels') == 1 && ($from_lang_id > 0) ) - { - $lang_id = $object->GetID(); - - // 1. phrases import - $phrases_live = $this->Application->getUnitOption('phrases','TableName'); - $phrases_temp = $this->Application->GetTempName($phrases_live); - $sql = 'INSERT INTO '.$phrases_temp.' - SELECT Phrase, Translation, PhraseType, 0-PhraseId, '.$lang_id.', '.adodb_mktime().', "", Module - FROM '.$phrases_live.' - WHERE LanguageId='.$from_lang_id; - $this->Conn->Query($sql); - - // 2. events import - $em_table_live = $this->Application->getUnitOption('emailmessages','TableName'); - $em_table_temp = $this->Application->GetTempName($em_table_live); - - $sql = 'SELECT * FROM '.$em_table_live.' WHERE LanguageId = '.$from_lang_id; - $email_messages = $this->Conn->Query($sql); - if($email_messages) - { - $id = $this->Conn->GetOne('SELECT MIN(EmailMessageId) FROM '.$em_table_live); - if($id > 0) $id = 0; - $id--; - - $sqls = Array(); - foreach($email_messages as $email_message) - { - $sqls[] = $id.','.$this->Conn->qstr($email_message['Template']).','.$this->Conn->qstr($email_message['MessageType']).','.$lang_id.','.$email_message['EventId']; - $id--; - } - $sql = 'INSERT INTO '.$em_table_temp.'(EmailMessageId,Template,MessageType,LanguageId,EventId) VALUES ('.implode('),(',$sqls).')'; - $this->Conn->Query($sql); - } - - $object->SetDBField('CopyLabels', 0); - } - } - - /** - * Prepare temp tables for creating new item - * but does not create it. Actual create is - * done in OnPreSaveCreated - * - * @param kEvent $event - */ - function OnPreCreate(&$event) - { - parent::OnPreCreate($event); - - $object =& $event->getObject(); - $object->SetDBField('CopyLabels', 1); - - $live_table = $this->Application->GetLiveName($object->TableName); - $primary_lang_id = $this->Conn->GetOne('SELECT '.$object->IDField.' FROM '.$live_table.' WHERE PrimaryLang = 1'); - - $object->SetDBField('CopyFromLanguage', $primary_lang_id); - } - - - function OnChangeLanguage(&$event) - { - $this->Application->SetVar('m_lang', $this->Application->GetVar('language')); - - //$this->Application->LinkVar('language', 'm_lang'); - } - - /** - * Parse language XML file into temp tables and redirect to progress bar screen - * - * @param kEvent $event - */ - function OnImportLanguage(&$event) - { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { - return; - } - - $items_info = $this->Application->GetVar('phrases_import'); - if($items_info) - { - list($id,$field_values) = each($items_info); - $object =& $this->Application->recallObject('phrases.import', 'phrases', Array('skip_autoload' => true) ); - $object->SetFieldsFromHash($field_values); - - $filename = getArrayValue($field_values, 'LangFile', 'tmp_name'); - if( filesize($filename) ) - { - $modules = getArrayValue($field_values,'Module'); - $lang_xml =& $this->Application->recallObject('LangXML'); - $lang_xml->Parse($filename, $field_values['PhraseType'], $modules, $field_values['ImportOverwrite']); - - $event->redirect = true; - $event->SetRedirectParams( Array('lang_event' => 'OnImportProgress', 'pass' => 'all,lang', 'mode'=>$field_values['ImportOverwrite']) ); - } - else - { - $object =& $this->Application->recallObject('phrases.import'); - $object->SetError('LangFile', 'la_empty_file', 'la_EmptyFile'); - $event->redirect = false; - } - } - } - - /** - * Copies imported from xml file from temp table to live table - * - * @param kEvent $event - */ - function OnImportProgress(&$event) - { - define('IMPORT_BY', 300); // import this much records per step - $template_name = 'regional/languages_import_step2'; - - $import_mode = (int)$this->Application->GetVar('mode'); // 1 - overwrite existing phrases, 0 - don't overwrite existing phrases - $import_source = (int)$this->Application->GetVar('source'); - $import_steps = Array(0 => 'lang', 1 => 'phrases', 2 => 'emailmessages', 3 => 'finish'); - - $key_fields = Array(0 => 'PackName', 1 => 'Phrase', 2 => 'EventId'); // by what field should we search record match - - $import_titles = Array(0 => 'la_ImportingLanguages', 1 => 'la_ImportingPhrases', 2 => 'la_ImportingEmailEvents', 3 => 'la_Done'); - - // --- BEFORE --- - $import_prefix = $import_steps[$import_source]; - $import_start = (int)$this->Application->GetVar('start'); - $id_field = $this->Application->getUnitOption($import_prefix,'IDField'); - $dst_table = $this->Application->getUnitOption($import_prefix,'TableName'); - $src_table = $this->Application->GetTempName($dst_table); - - $import_total = $this->Application->GetVar('total'); - if(!$import_total) $import_total = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$src_table); - // --- AFTER --- - - if($import_start == $import_total) - { - $import_source++; - $import_prefix = $import_steps[$import_source]; - if($import_prefix == 'finish') - { - $event->SetRedirectParam('opener','u'); - return true; - } - - $import_start = 0; - $id_field = $this->Application->getUnitOption($import_prefix,'IDField'); - $dst_table = $this->Application->getUnitOption($import_prefix,'TableName'); - $src_table = $this->Application->GetTempName($dst_table); - $import_total = $this->Conn->GetOne('SELECT COUNT(*) FROM '.$src_table); - } - - if($import_total > 0) - { - $done_percent = ($import_start * 100) / $import_total; - } - else - { - $done_percent = 100; - } - - $block_params = Array( 'name' => $template_name, - 'title' => $import_titles[$import_source], - 'percent_done' => $done_percent, - 'percent_left' => 100 - $done_percent); - - $this->Application->InitParser(); - $this->Application->setUnitOption('phrases','AutoLoad',false); - echo $this->Application->ParseBlock($block_params); - - //break out of buffering - $buffer_content = Array(); - while (ob_get_level()) { - $buffer_content[] = ob_get_clean(); - } - $ret = implode('', array_reverse($buffer_content)); - echo $ret; - flush(); - - - $sql = 'SELECT * FROM %s LIMIT %s,%s'; - $rows = $this->Conn->Query( sprintf($sql,$src_table,$import_start,IMPORT_BY) ); - - $values_sql = ''; - - // if found and mode = 1 (overwrite) - $search_sql = 'SELECT '.$id_field.' FROM '.$dst_table.' WHERE '.$key_fields[$import_source].' = %s AND LanguageId = %s'; - $update_sql = 'UPDATE '.$dst_table.' SET %s WHERE '.$id_field.' = %s'; - - foreach($rows as $row) - { - $tmp_sql = sprintf($search_sql, $this->Conn->qstr($row[ $key_fields[$import_source] ]), $row['LanguageId'] ); - $tmp_id = $this->Conn->GetOne($tmp_sql); - if($tmp_id > 0 && $import_mode == 1) - { - // update - $update_fields = ''; - foreach($row as $field_name => $field_value) - { - if($field_name == $id_field) continue; - $update_fields .= '`'.$field_name.'` = '.$this->Conn->qstr($field_value).','; - } - $update_fields = preg_replace('/(.*),$/', '\\1', $update_fields); - $this->Conn->Query( sprintf($update_sql, $update_fields, $tmp_id) ); - } - elseif(!$tmp_id) - { - $values_sql .= '('; - foreach($row as $field_value) - { - $values_sql .= $this->Conn->qstr($field_value).','; - } - $values_sql = preg_replace('/(.*),$/', '\\1', $values_sql).'),'; - } - } - - if($values_sql) - { - $fields_sql = ''; - $fields = array_keys( $this->Application->getUnitOption($import_prefix,'Fields') ); - foreach($fields as $field_name) - { - $fields_sql .= '`'.$field_name.'`,'; - } - $fields_sql = preg_replace('/(.*),$/', '\\1', $fields_sql); - - $values_sql = preg_replace('/(.*),$/', '\\1', $values_sql); - $sql = sprintf('INSERT INTO %s (%s) VALUES %s', $dst_table, $fields_sql, $values_sql); - $this->Conn->Query($sql); - } - $event->setRedirectParams( Array('lang_event' => 'OnImportProgress', 'pass' => 'all,lang', 'start' => $import_start += count($rows), 'total' => $import_total, 'source' => $import_source, 'mode' => $import_mode) ); - } - - /** - * Stores ids of selected languages and redirects to export language step 1 - * - * @param kEvent $event - */ - function OnExportLanguage(&$event) - { - if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) { - return; - } - - $this->Application->setUnitOption('phrases','AutoLoad',false); - - $this->StoreSelectedIDs($event); - $this->Application->StoreVar('export_language_ids', implode(',', $this->getSelectedIDs($event)) ); - - $event->setRedirectParams( Array('m_opener'=>'d','phrases.export_event'=>'OnNew','pass'=>'all,phrases.export') ); - $event->redirect = 'regional/languages_export'; - } - - /** - * Saves selected languages to xml file passed - * - * @param kEvent $event - */ - function OnExportProgress(&$event) - { - $items_info = $this->Application->GetVar('phrases_export'); - if($items_info) - { - list($id,$field_values) = each($items_info); - $object =& $this->Application->recallObject('phrases.export', 'phrases', Array('skip_autoload' => true) ); - $object->SetFieldsFromHash($field_values); - - $lang_ids = explode(',', $this->Application->RecallVar('export_language_ids') ); - - if( !getArrayValue($field_values,'LangFile') ) - { - $object->SetError('LangFile', 'required'); - $event->redirect = false; - return false; - } - if( !is_writable(EXPORT_PATH) ) - { - $object->SetError('LangFile', 'write_error', 'la_ExportFolderNotWritable'); - $event->redirect = false; - return false; - } - if( substr($field_values['LangFile'], -5) != '.lang' ) $field_values['LangFile'] .= '.lang'; - $filename = EXPORT_PATH.'/'.$field_values['LangFile']; - - $lang_xml =& $this->Application->recallObject('LangXML'); - if ($object->GetDBField('DoNotEncode')) { - $lang_xml->SetEncoding('plain'); - } - $lang_xml->Create($filename, $field_values['PhraseType'], $lang_ids, $field_values['Module']); - - } - - $event->redirect = 'regional/languages_export_step2'; - $event->SetRedirectParam('export_file', $field_values['LangFile']); - } - - /** - * Returns to previous template in opener stack - * - * @param kEvent $event - */ - function OnGoBack(&$event) - { - $event->redirect_params['opener'] = 'u'; - } - - } - -?> \ No newline at end of file Index: trunk/kernel/units/languages/import_xml.php =================================================================== diff -u -N --- trunk/kernel/units/languages/import_xml.php (revision 6583) +++ trunk/kernel/units/languages/import_xml.php (revision 0) @@ -1,414 +0,0 @@ -Conn =& $this->Application->GetADODBConnection(); - - $this->Application->SetVar('lang_mode', 't'); - - $this->tables['lang'] = $this->prepareTempTable('lang'); - $this->lang_object =& $this->Application->recallObject('lang.imp', null, Array('skip_autoload' => true)); - - $this->tables['phrases'] = $this->prepareTempTable('phrases'); - $this->tables['emailmessages'] = $this->prepareTempTable('emailmessages'); - - $sql = 'SELECT EventId, CONCAT(Event,"_",Type) AS EventMix FROM '.TABLE_PREFIX.'Events'; - $this->events_hash = $this->Conn->GetCol($sql, 'EventMix'); - - $this->ip_address = getenv('HTTP_X_FORWARDED_FOR') ? getenv('HTTP_X_FORWARDED_FOR') : getenv('REMOTE_ADDR'); - } - - function SetEncoding($enc) - { - $this->Encoding = $enc; - } - - function renameTable($table_prefix, $new_name) - { - $this->Conn->Query('ALTER TABLE '.$this->tables[$table_prefix].' RENAME '.$new_name); - $this->tables[$table_prefix] = $new_name; - } - - /** - * Create temp table for prefix, if table already exists, then delete it and create again - * - * @param string $prefix - */ - function prepareTempTable($prefix) - { - $idfield = $this->Application->getUnitOption($prefix, 'IDField'); - $table = $this->Application->getUnitOption($prefix,'TableName'); - $temp_table = $this->Application->GetTempName($table); - - $sql = 'DROP TABLE IF EXISTS %s'; - $this->Conn->Query( sprintf($sql, $temp_table) ); - - $sql = 'CREATE TABLE %s SELECT * FROM %s WHERE 0'; - $this->Conn->Query( sprintf($sql, $temp_table, $table) ); - - $sql = 'ALTER TABLE %1$s CHANGE %2$s %2$s INT(11) NOT NULL'; - $this->Conn->Query( sprintf($sql, $temp_table, $idfield) ); - - return $temp_table; - } - - function Parse($filename, $phrase_types, $module_ids, $import_mode = LANG_SKIP_EXISTING) - { - // define the XML parsing routines/functions to call based on the handler path - if( !file_exists($filename) || !$phrase_types /*|| !$module_ids*/ ) return false; - - $phrase_types = explode('|', substr($phrase_types, 1, -1) ); -// $module_ids = explode('|', substr($module_ids, 1, -1) ); - - $this->phrase_types_allowed = array_flip($phrase_types); - $this->import_mode = $import_mode; - - //if (in_array('In-Portal',) - - $xml_parser = xml_parser_create(); - xml_set_element_handler( $xml_parser, Array(&$this, 'startElement'), Array(&$this, 'endElement') ); - xml_set_character_data_handler( $xml_parser, Array(&$this, 'characterData') ); - - $fdata = file_get_contents($filename); - - $ret = xml_parse($xml_parser, $fdata); - xml_parser_free($xml_parser); // clean up the parser object - - $this->Application->SetVar('lang_mode', ''); - return $ret; - } - - function startElement(&$parser, $element, $attributes) - { - array_push($this->path, $element); - $path = implode(' ',$this->path); - //check what path we are in - - $this->LastLine = xml_get_current_line_number($parser); - $this->SecondData = false; - - switch($path) - { - case 'LANGUAGES LANGUAGE': - $this->current_language = Array('PackName' => $attributes['PACKNAME'], 'LocalName' => $attributes['PACKNAME'], 'Encoding' => $attributes['ENCODING']); - - $sql = 'SELECT %s FROM %s WHERE PackName = %s'; - $sql = sprintf( $sql, - $this->lang_object->IDField, - $this->Application->GetLiveName($this->lang_object->TableName), - $this->Conn->qstr($this->current_language['PackName']) ); - $language_id = $this->Conn->GetOne($sql); - if($language_id) - { - $this->current_language['LanguageId'] = $language_id; - $this->lang_object->SwitchToLive(); - $this->lang_object->Load($language_id); - } - break; - - case 'LANGUAGES LANGUAGE PHRASES': - case 'LANGUAGES LANGUAGE EVENTS': - if( !getArrayValue($this->current_language,'Charset') ) $this->current_language['Charset'] = 'iso-8859-1'; - $this->lang_object->SetFieldsFromHash($this->current_language); - - if( !getArrayValue($this->current_language,'LanguageId') ) - { - if( $this->lang_object->Create() ) $this->current_language['LanguageId'] = $this->lang_object->GetID(); - } - elseif($this->import_mode == LANG_OVERWRITE_EXISTING) - { - $this->lang_object->TableName = $this->Application->getUnitOption($this->lang_object->Prefix, 'TableName'); - $this->lang_object->Update(); - } - break; - - case 'LANGUAGES LANGUAGE PHRASES PHRASE': - $phrase_module = getArrayValue($attributes,'MODULE'); - if(!$phrase_module) $phrase_module = 'In-Portal'; - - $this->current_phrase = Array( 'LanguageId' => $this->current_language['LanguageId'], - 'Phrase' => $attributes['LABEL'], - 'PhraseType' => $attributes['TYPE'], - 'Module' => $phrase_module, - 'LastChanged' => adodb_mktime(), - 'LastChangeIP' => $this->ip_address, - 'Translation' => ''); - break; - - case 'LANGUAGES LANGUAGE EVENTS EVENT': - $this->current_event = Array( 'LanguageId' => $this->current_language['LanguageId'], - 'EventId' => $this->events_hash[ $attributes['EVENT'].'_'.$attributes['TYPE'] ], - 'MessageType' => $attributes['MESSAGETYPE'], - 'Template' => ''); - break; - - - } - - // if($path == 'SHIPMENT PACKAGE') - } - - function characterData(&$parser, $line) - { - $line = trim($line); - if(!$line) return ; - - $path = join (' ',$this->path); - - $language_nodes = Array('DATEFORMAT','TIMEFORMAT','INPUTDATEFORMAT','INPUTTIMEFORMAT','DECIMAL','THOUSANDS','CHARSET','UNITSYSTEM'); - - - $node_field_map = Array('LANGUAGES LANGUAGE DATEFORMAT' => 'DateFormat', - 'LANGUAGES LANGUAGE TIMEFORMAT' => 'TimeFormat', - - 'LANGUAGES LANGUAGE INPUTDATEFORMAT'=> 'InputDateFormat', - 'LANGUAGES LANGUAGE INPUTTIMEFORMAT'=> 'InputTimeFormat', - - 'LANGUAGES LANGUAGE DECIMAL' => 'DecimalPoint', - 'LANGUAGES LANGUAGE THOUSANDS' => 'ThousandSep', - 'LANGUAGES LANGUAGE CHARSET' => 'Charset', - 'LANGUAGES LANGUAGE UNITSYSTEM' => 'UnitSystem'); - - if( in_array( end($this->path), $language_nodes) ) - { - $this->current_language[ $node_field_map[$path] ] = $line; - } - else - { - switch($path) - { - case 'LANGUAGES LANGUAGE PHRASES PHRASE': - if( isset($this->phrase_types_allowed[ $this->current_phrase['PhraseType'] ]) ) - { - $this->current_phrase['Translation'] .= $line; - } - break; - - case 'LANGUAGES LANGUAGE EVENTS EVENT': - $cur_line = xml_get_current_line_number($parser); - if ($cur_line != $this->LastLine) { - $this->current_event['Template'] .= str_repeat("\r\n", ($cur_line - $this->LastLine) ); - $this->LastLine = $cur_line; - } - $this->current_event['Template'] .= $line; - - $this->SecondData = true; - break; - } - } - } - - function endElement(&$parser, $element) - { - $path = implode(' ',$this->path); - - switch($path) - { - case 'LANGUAGES LANGUAGE PHRASES PHRASE': - if( isset($this->phrase_types_allowed[ $this->current_phrase['PhraseType'] ]) ) - { - if ($this->current_language['Encoding'] == 'plain') { - // nothing to decode! - } - else { - $this->current_phrase['Translation'] = base64_decode($this->current_phrase['Translation']); - } - $this->insertRecord($this->tables['phrases'], $this->current_phrase); - } - break; - - case 'LANGUAGES LANGUAGE EVENTS EVENT': - if ($this->current_language['Encoding'] == 'plain') { - $this->current_event['Template'] = rtrim($this->current_event['Template']); - // nothing to decode! - } - else { - $this->current_event['Template'] = base64_decode($this->current_event['Template']); - } - $this->insertRecord($this->tables['emailmessages'],$this->current_event); - break; - } - - array_pop($this->path); - } - - function insertRecord($table, $fields_hash) - { - $fields = ''; - $values = ''; - - foreach($fields_hash as $field_name => $field_value) - { - $fields .= '`'.$field_name.'`,'; - $values .= $this->Conn->qstr($field_value).','; - } - - $fields = preg_replace('/(.*),$/', '\\1', $fields); - $values = preg_replace('/(.*),$/', '\\1', $values); - - $sql = 'INSERT INTO `'.$table.'` ('.$fields.') VALUES ('.$values.')'; - $this->Conn->Query($sql); - -// return $this->Conn->getInsertID(); // no need because of temp table without auto_increment column at all - } - - /** - * Creates XML file with exported language data - * - * @param string $filename filename to export into - * @param Array $phrase_types phrases types to export from modules passed in $module_ids - * @param Array $language_ids IDs of languages to export - * @param Array $module_ids IDs of modules to export phrases from - */ - function Create($filename, $phrase_types, $language_ids, $module_ids) - { - $fp = fopen($filename,'w'); - if(!$fp || !$phrase_types || !$module_ids || !$language_ids) return false; - - $phrase_types = explode('|', substr($phrase_types, 1, -1) ); - $module_ids = explode('|', substr($module_ids, 1, -1) ); - - $this->events_hash = array_flip($this->events_hash); - - $lang_table = $this->Application->getUnitOption('lang','TableName'); - $phrases_table = $this->Application->getUnitOption('phrases','TableName'); - $emailevents_table = $this->Application->getUnitOption('emailmessages','TableName'); - $mainevents_table = $this->Application->getUnitOption('emailevents','TableName'); - - $phrase_tpl = "\t\t\t".'%s'."\n"; - $event_tpl = "\t\t\t".'%s'."\n"; - $sql = 'SELECT * FROM %s WHERE LanguageId = %s'; - $ret = ''."\n"; - foreach($language_ids as $language_id) - { - // languages - $row = $this->Conn->GetRow( sprintf($sql, $lang_table, $language_id) ); - $ret .= "\t".''.$row['DateFormat'].''; - $ret .= ''.$row['TimeFormat'].''.$row['InputDateFormat'].''; - $ret .= ''.$row['InputTimeFormat'].''.$row['DecimalPoint'].''; - $ret .= ''.$row['ThousandSep'].''.$row['Charset'].''; - $ret .= ''.$row['UnitSystem'].''."\n"; - - // phrases - $phrases_sql = 'SELECT * FROM '.$phrases_table.' WHERE LanguageId = %s AND PhraseType IN (%s) AND Module IN (%s) ORDER BY Phrase'; - if( in_array('In-Portal',$module_ids) ) array_push($module_ids, ''); // for old language packs - $rows = $this->Conn->Query( sprintf($phrases_sql,$language_id, implode(',',$phrase_types), '\''.implode('\',\'',$module_ids).'\'' ) ); - if($rows) - { - $ret .= "\t\t".''."\n"; - foreach($rows as $row) - { - $data = $this->Encoding == 'base64' ? base64_encode($row['Translation']) : ''; - $ret .= sprintf($phrase_tpl, $row['Phrase'], $row['Module'], $row['PhraseType'], $data ); - } - $ret .= "\t\t".''."\n"; - } - - // email events - if( in_array('In-Portal',$module_ids) ) unset( $module_ids[array_search('',$module_ids)] ); // for old language packs - $module_sql = preg_replace('/(.*) OR $/', '\\1', preg_replace('/(.*),/U', 'INSTR(Module,\'\\1\') OR ', implode(',', $module_ids).',' ) ); - - $sql = 'SELECT EventId FROM '.$mainevents_table.' WHERE '.$module_sql; - $event_ids = $this->Conn->GetCol($sql); - - if($event_ids) - { - $ret .= "\t\t".''."\n"; - $event_sql = ' SELECT em.* - FROM '.$emailevents_table.' em - LEFT JOIN '.$mainevents_table.' e ON e.EventId = em.EventId - WHERE em.LanguageId = %s AND em.EventId IN (%s) - ORDER BY e.Event, e.Type'; - $rows = $this->Conn->Query( sprintf($event_sql,$language_id, $event_ids ? implode(',',$event_ids) : '' ) ); - foreach($rows as $row) - { - list($event_name, $event_type) = explode('_', $this->events_hash[ $row['EventId'] ] ); - $data = $this->Encoding == 'base64' ? base64_encode($row['Template']) : ''; - $ret .= sprintf($event_tpl, $row['MessageType'], $event_name, $event_type, $data ); - } - $ret .= "\t\t".''."\n"; - } - $ret .= "\t".''."\n"; - } - - $ret .= ''; - fwrite($fp, $ret); - fclose($fp); - return true; - } - } - -?> \ No newline at end of file