Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Wed, Feb 12, 10:09 AM

in-portal

Index: branches/RC/core/units/custom_fields/custom_fields_event_handler.php
===================================================================
--- branches/RC/core/units/custom_fields/custom_fields_event_handler.php (revision 11853)
+++ branches/RC/core/units/custom_fields/custom_fields_event_handler.php (revision 11854)
@@ -1,290 +1,295 @@
<?php
class CustomFieldsEventHandler extends kDBEventHandler {
/**
* Changes permission section to one from REQUEST, not from config
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
$sql = 'SELECT Prefix
FROM '.TABLE_PREFIX.'ItemTypes
WHERE ItemType = '.$this->Conn->qstr( $this->Application->GetVar('cf_type') );
$main_prefix = $this->Conn->GetOne($sql);
$section = $this->Application->getUnitOption($main_prefix.'.custom', '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)
{
$object =& $event->getObject();
/* @var $object kDBList */
$item_type = $this->Application->GetVar('cf_type');
if (!$item_type) {
$prefix = $event->getEventParam('SourcePrefix');
$item_type = $this->Application->getUnitOption($prefix, 'ItemType');
}
if ($event->Special == 'general') {
$object->addFilter('generaltab_filter', '%1$s.OnGeneralTab = 1');
}
if ($item_type) {
$hidden_fields = array_map(Array(&$this->Conn, 'qstr'), $this->_getHiddenFiels($event));
if ($hidden_fields) {
$object->addFilter('hidden_filter', '%1$s.FieldName NOT IN (' . implode(',', $hidden_fields) . ')');
}
$object->addFilter('itemtype_filter', '%1$s.Type = '.$item_type);
}
if (!($this->Application->isDebugMode() && $this->Application->IsAdmin())) {
$object->addFilter('user_filter', '%1$s.IsSystem = 0');
}
}
/**
* Returns prefix, that custom fields are printed for
*
* @param kEvent $event
* @return string
*/
function _getSourcePrefix(&$event)
{
$prefix = $event->getEventParam('SourcePrefix');
if (!$prefix) {
$sql = 'SELECT Prefix
FROM ' . TABLE_PREFIX . 'ItemTypes
WHERE ItemType = ' . $this->Application->GetVar('cf_type');
$prefix = $this->Conn->GetOne($sql);
}
return $prefix;
}
/**
* Get custom fields, that should no be shown anywhere
*
* @param kEvent $event
* @return Array
*/
function _getHiddenFiels(&$event)
{
$prefix = $this->_getSourcePrefix($event);
$virtual_fields = $this->Application->getUnitOption($prefix, 'VirtualFields', Array ());
$custom_fields = $this->Application->getUnitOption($prefix, 'CustomFields', Array ());
$hidden_fields = Array ();
foreach ($custom_fields as $custom_field) {
$check_field = 'cust_' . $custom_field;
$show_mode = array_key_exists('show_mode', $virtual_fields[$check_field]) ? $virtual_fields[$check_field]['show_mode'] : true;
if (($show_mode === false) || (($show_mode === smDEBUG) && !(defined('DEBUG_MODE') && DEBUG_MODE))) {
$hidden_fields[] = $custom_field;
}
}
return $hidden_fields;
}
/**
* Prevents from duplicate item creation
*
* @param kEvent $event
*/
function OnBeforeItemCreate(&$event)
{
$object =& $event->getObject();
$live_table = $this->Application->getUnitOption($event->Prefix, 'TableName');
$sql = 'SELECT COUNT(*)
FROM '.$live_table.'
WHERE FieldName = '.$this->Conn->qstr($object->GetDBField('FieldName')).' AND Type = '.$object->GetDBField('Type');
$found = $this->Conn->GetOne($sql);
if ($found) {
$event->status = erFAIL;
$object->SetError('FieldName', 'duplicate', 'la_error_CustomExists');
}
}
/**
* Occurse after deleting item, id of deleted item
* is stored as 'id' param of event
*
* @param kEvent $event
* @access public
*/
function OnAfterItemDelete(&$event)
{
$object =& $event->getObject();
$main_prefix = $this->getPrefixByItemType($object->GetDBField('Type'));
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
// call main item config to clone cdata table
$this->Application->getUnitOption($main_prefix, 'TableName');
$ml_helper->deleteField($main_prefix.'-cdata', $event->getEventParam('id'));
}
/**
* Get config prefix based on item type
*
* @param unknown_type $item_type
* @return unknown
*/
function getPrefixByItemType($item_type)
{
$sql = 'SELECT Prefix
FROM '.TABLE_PREFIX.'ItemTypes
WHERE ItemType = '.$item_type;
return $this->Conn->GetOne($sql);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnSaveCustomField(&$event)
{
if ($event->MasterEvent->status != erSUCCESS) {
return false;
}
$object =& $event->getObject();
$main_prefix = $this->getPrefixByItemType($object->GetDBField('Type'));
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
/* @var $ml_helper kMultiLanguageHelper */
// call main item config to clone cdata table
$this->Application->getUnitOption($main_prefix, 'TableName');
$ml_helper->createFields($main_prefix.'-cdata');
}
function OnMassDelete(&$event)
{
parent::OnMassDelete($event);
$event->redirect_params = Array('opener' => 's');
}
/**
* 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('Type', $this->Application->GetVar('cf_type'));
}
/**
* Prepares ValueList field's value as xml for editing
*
* @param kEvent $event
*/
function OnAfterItemLoad(&$event)
{
parent::OnAfterItemLoad($event);
$object =& $event->getObject();
/* @var $object kDBItem */
if (!in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes())) {
return ;
}
$custom_field_helper =& $this->Application->recallObject('InpCustomFieldsHelper');
/* @var $custom_field_helper InpCustomFieldsHelper */
$options = $custom_field_helper->GetValuesHash( $object->GetDBField('ValueList'), VALUE_LIST_SEPARATOR, false );
$records = Array ();
$option_key = key($options);
if ($option_key === '' || $option_key == 0) {
// remove 1st empty option, and add it later, when options will be saved, but allow string option keys
unset($options[$option_key]); // keep index, don't use array_unshift!
}
foreach ($options as $option_key => $option_title) {
$records[] = Array ('OptionKey' => $option_key, 'OptionTitle' => $option_title);
}
$minput_helper =& $this->Application->recallObject('MInputHelper');
/* @var $minput_helper MInputHelper */
$xml = $minput_helper->prepareMInputXML($records, Array ('OptionKey', 'OptionTitle'));
$object->SetDBField('Options', $xml);
}
/**
* Returns custom field element types, that will use minput control
*
* @return unknown
*/
function _getMultiElementTypes()
{
return Array ('select', 'multiselect', 'radio');
}
/**
* Saves minput content to ValueList field
*
* @param kEvent $event
*/
function OnBeforeItemUpdate(&$event)
{
parent::OnBeforeItemUpdate($event);
$object =& $event->getObject();
/* @var $object kDBItem */
if (!in_array($object->GetDBField('ElementType'), $this->_getMultiElementTypes())) {
return ;
}
$minput_helper =& $this->Application->recallObject('MInputHelper');
/* @var $minput_helper MInputHelper */
$ret = $object->GetDBField('ElementType') == 'multiselect' ? Array () : Array ('' => '=+');
$records = $minput_helper->parseMInputXML($object->GetDBField('Options'));
if ($object->GetDBField('SortValues')) {
usort($records, Array (&$this, '_sortValues'));
ksort($records);
}
foreach ($records as $record) {
- $ret[] = $record['OptionKey'] . '=+' . $record['OptionTitle'];
+ if (substr($record['OptionKey'], 0, 3) == 'SQL') {
+ $ret[] = $record['OptionTitle'];
+ }
+ else {
+ $ret[] = $record['OptionKey'] . '=' . $record['OptionTitle'];
+ }
}
$object->SetDBField('ValueList', implode(VALUE_LIST_SEPARATOR, $ret));
}
function _sortValues($record_a, $record_b)
{
return strcasecmp($record_a['OptionTitle'], $record_b['OptionTitle']);
}
}
?>
\ No newline at end of file
Index: branches/RC/core/units/general/helpers/mod_rewrite_helper.php
===================================================================
--- branches/RC/core/units/general/helpers/mod_rewrite_helper.php (revision 11853)
+++ branches/RC/core/units/general/helpers/mod_rewrite_helper.php (revision 11854)
@@ -1,625 +1,575 @@
<?php
class kModRewriteHelper extends kHelper {
/**
* Holds a refererence to httpquery
*
* @var kHttpQuery
*/
var $HTTPQuery = null;
function kModRewriteHelper()
{
parent::kHelper();
$this->HTTPQuery =& $this->Application->recallObject('HTTPQuery');
}
function SetDefaultValues(&$vars)
{
$defaults = Array ('m_cat_id' => 0, 'm_cat_page' => 1, 'm_opener' => 's', 't' => 'index');
foreach ($defaults as $default_key => $default_value) {
// bug: null is never returned
if ($this->HTTPQuery->Get($default_key) == null) {
$vars[$default_key] = $default_value;
}
}
}
/**
* Gets language part from url
*
* @param Array $url_parts
* @param Array $vars
* @return bool
*/
function ProcessLanguage(&$url_parts, &$vars)
{
if (!$url_parts) {
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;
}
/**
* Gets theme part from url
*
* @param Array $url_parts
* @param Array $vars
* @return bool
*/
function ProcessTheme(&$url_parts, &$vars)
{
if (!$url_parts) {
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;
}
/**
* Extracts category part from url
*
* @param Array $url_parts
* @param Array $vars
* @return bool
*/
function ProcessCategory($url_parts, &$vars)
{
if (!$url_parts) {
return false;
}
$res = false;
$url_part = array_shift($url_parts);
$category_id = 0;
$last_category_info = false;
$category_path = $url_part == 'content' ? '' : 'content';
do {
$category_path = trim($category_path . '/' . $url_part, '/');
// bb_<topic_id> -> forums/bb_2
if ( !preg_match('/^bb_[\d]+$/', $url_part) && preg_match('/(.*)_([\d]+)$/', $category_path, $rets) ) {
$category_path = $rets[1];
$vars['m_cat_page'] = $rets[2];
}
$sql = 'SELECT CategoryId, IsIndex, NamedParentPath
FROM ' . TABLE_PREFIX . 'Category
WHERE Status IN (1,4) AND (LOWER(NamedParentPath) = ' . $this->Conn->qstr($category_path) . ')';
$category_info = $this->Conn->GetRow($sql);
if ($category_info !== false) {
$last_category_info = $category_info;
$url_part = array_shift($url_parts);
$res = true;
}
} while ($category_info !== false && $url_part);
if ($last_category_info) {
// IsIndex = 2 is a Container-only page, meaning it should go to index-page child
if ($last_category_info['IsIndex'] == 2) {
$sql = 'SELECT CategoryId, NamedParentPath
FROM ' . TABLE_PREFIX . 'Category
WHERE ParentId = ' . $last_category_info['CategoryId'] . ' AND IsIndex = 1';
$category_info = $this->Conn->GetRow($sql);
if ($category_info) {
// when index sub-page is found use it, otherwise use container page
$last_category_info = $category_info;
}
}
// 1. Set virtual page as template, this will be replaced to physical template later in kApplication::Run.
// 2. Don't set CachedTemplate field as template here, because we will loose original page associated with it's cms blocks!
$vars['t'] = strtolower( preg_replace('/^Content\//i', '', $last_category_info['NamedParentPath']) );
$vars['m_cat_id'] = $last_category_info['CategoryId'];
$vars['is_virtual'] = true; // for template from POST, strange code there!
}
else {
$vars['m_cat_id'] = 0;
}
/*if ($url_part) {
array_unshift($url_parts, $url_part);
}*/
return $res;
}
/**
* Set's 1st page for all modules (will be used when not passed in url)
*
* @param Array $vars
* @todo this is temporary fix, until mod-rewrite helper will become category-independend
*/
function SetDefaultPages(&$vars)
{
// 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'] . '_Page'] = 1;
}
}
function _processTopic($url_parts, &$vars, $set_template = true)
{
$sql = 'SELECT c.ParentPath, c.CategoryId
FROM ' . TABLE_PREFIX . 'Category AS c
WHERE c.CategoryId = ' . $vars['m_cat_id'];
$cat_item = $this->Conn->GetRow($sql);
if ($set_template) {
$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';
}
function ProcessModuleItem(&$url_parts, &$vars, $set_template = true)
{
if (!$url_parts) {
return false;
}
$item_filename = end($url_parts);
if (is_numeric($item_filename)) {
// this page, don't process here
return false;
}
if (preg_match('/^bb_[\d]+/', $item_filename)) {
// process topics separatly, because they don't use item filenames
return $this->_processTopic($url_parts, $vars, $set_template);
}
// locating the item in CategoryItems by filename to detect its ItemPrefix and its category ParentPath
$sql = '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($item_filename) . ')';
$cat_item = $this->Conn->GetRow($sql);
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);
$sql = 'SELECT ' . $module_config['IDField'] . '
FROM ' . $module_config['TableName'] . '
WHERE ResourceId = ' . $cat_item['ItemResourceId'];
$item_id = $this->Conn->GetOne($sql);
array_pop($url_parts);
if ((!$set_template || $item_template) && $item_id) {
if ($set_template) {
$vars['t'] = $item_template;
}
$vars[$module_prefix . '_id'] = $item_id;
return $module_prefix;
}
}
return false;
}
/**
* Returns module item details template specified in given category custom field for given module prefix
*
* @param mixed $category
* @param string $module_prefix
* @return string
*/
function GetItemTemplate($category, $module_prefix)
{
$cache_key = serialize($category) . '_' . $module_prefix;
$cached_value = $this->Application->getCache(__CLASS__ . __FUNCTION__, $cache_key);
if ($cached_value !== false) {
return $cached_value;
}
if (!is_array($category)) {
if ($category == 0) {
$category = $this->Application->findModule('Var', $module_prefix, 'RootCat');
}
$sql = 'SELECT c.ParentPath, c.CategoryId
FROM ' . TABLE_PREFIX . 'Category AS c
WHERE c.CategoryId = ' . $category;
$category = $this->Conn->GetRow($sql);
}
$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->_getItemTemplateCustomField($module_prefix);
// 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);
$this->Application->setCache(__CLASS__ . __FUNCTION__, $cache_key, $item_template);
return $item_template;
}
/**
* Returns category custom field id, where given module prefix item template name is stored
*
* @param string $module_prefix
* @return int
*/
function _getItemTemplateCustomField($module_prefix)
{
$cached_value = $this->Application->getCache(__CLASS__ . __FUNCTION__, $module_prefix);
if ($cached_value !== false) {
return $cached_value;
}
$sql = 'SELECT CustomFieldId
FROM ' . TABLE_PREFIX . 'CustomField
WHERE FieldName = ' . $this->Conn->qstr($module_prefix . '_ItemTemplate');
$item_template_field_id = $this->Conn->GetOne($sql);
$this->Application->setCache(__CLASS__ . __FUNCTION__, $module_prefix, $item_template_field_id);
return $item_template_field_id;
}
function ProcessPhisycalTemplate($url_parts, &$vars)
{
if (!$url_parts) {
return false;
}
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') . ')';
$template_found = $this->Conn->GetOne($sql);
if (!$template_found) {
array_shift($url_parts);
}
} while (!$template_found && $url_parts);
if ($template_found) {
$vars['t'] = $template_path;
return true;
}
return false;
}
/**
* Set's page (when found) to all modules
*
* @param Array $url_parts
* @param Array $vars
* @return string
*/
function ProcessPage(&$url_parts, &$vars)
{
if (!$url_parts) {
return false;
}
$page_number = end($url_parts);
if (!is_numeric($page_number)) {
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'] = $page_number;
}
array_pop($url_parts);
return true;
}
/**
* Checks if whole url_parts matches a whole In-CMS page
*
* @param array $url_parts
* @return boolean
*/
function ProcessFriendlyUrl($url_parts, &$vars)
{
if (!$url_parts) {
return false;
}
$sql = 'SELECT CategoryId, NamedParentPath
FROM ' . TABLE_PREFIX . 'Category
WHERE FriendlyURL = ' . $this->Conn->qstr(implode('/', $url_parts));
$friendly = $this->Conn->GetRow($sql);
if ($friendly) {
$vars['m_cat_id'] = $friendly['CategoryId'];
$vars['t'] = preg_replace('/^Content\//i', '', $friendly['NamedParentPath']);
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;
$sql = 'SELECT Data, Cached
FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = "mod_rw_' . md5($url) . '"';
$cache = $this->Conn->GetRow($sql);
if (false && $cache && $cache['Cached'] > 0) {
// not used for now
$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);
$fields_hash = Array (
'VarName' => 'mod_rw_' . md5($url),
'Data' => serialize($cache),
'Cached' => adodb_mktime(),
);
$this->Conn->doInsert($fields_hash, TABLE_PREFIX . 'Cache', 'REPLACE');
if (array_key_exists('t', $this->HTTPQuery->Post) && $this->HTTPQuery->Post['t']) {
// template from POST overrides template from URL.
$vars['t'] = $this->HTTPQuery->Post['t'];
if (isset($vars['is_virtual']) && $vars['is_virtual']) {
$vars['m_cat_id'] = 0; // this is virtual template category (for Proj-CMS)
}
}
unset($vars['is_virtual']);
}
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)
{
$sql = 'SELECT Data, Cached
FROM ' . TABLE_PREFIX . 'Cache
WHERE VarName = "mod_rw_' . md5($url) . '"';
$vars = $this->Conn->GetRow($sql);
if (false && $vars && $vars['Cached'] > 0) {
// not used for now
$vars = unserialize($menu['Data']);
return $vars;
}
$vars = Array ();
$url_parts = $url ? explode('/', trim($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->ProcessFriendlyUrl($url_parts, $vars) ) {
// friendly urls work like exact match only!
return $vars;
}
// http://site-url/<language>/<theme>/<category>[_<category_page>]/<template>/<module_page>
// http://site-url/<language>/<theme>/<category>[_<category_page>]/<module_page> (category-based section template)
// http://site-url/<language>/<theme>/<category>[_<category_page>]/<template>/<module_item>
// http://site-url/<language>/<theme>/<category>[_<category_page>]/<module_item> (category-based detail template)
$found = Array ();
$category_found = $this->ProcessCategory($url_parts, $vars);
if ($category_found) {
$found[] = 'ProcessCategory';
}
$this->SetDefaultPages($vars);
$page_found = $this->ProcessPage($url_parts, $vars);
if ($page_found) {
$found[] = 'ProcessPage';
}
$module_prefix = $this->ProcessModuleItem($url_parts, $vars);
if ($module_prefix !== false) {
$passed[] = $module_prefix;
$found[] = 'ProcessModuleItem';
}
$template_found = $this->ProcessPhisycalTemplate($url_parts, $vars);
if ($template_found) {
$found[] = 'ProcessPhisycalTemplate';
}
if (($module_prefix === false) && in_array('ProcessCategory', $found)) {
// no item found, but category found -> module index page
/*if (!$vars['t']) {
// no template found before -> assume it's index
$vars['t'] = 'index';
}*/
foreach ($this->Application->ModuleInfo as $module_name => $info) {
// no idea what module we are talking about, so pass info form all modules
$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->ProcessPage($url_parts, $vars) ) {
- if (count($passed) == 1) {// passed contains only 1 value which is 'm'
- // this may be search results page, so we need to find out the module, especially for old in-portal
- foreach ($this->Application->ModuleInfo as $module_name => $module_data) {
- if (!$module_data['TemplatePath']) continue;
- if ( preg_match('/^' . preg_quote($module_data['TemplatePath'], '/') . '/i', $vars['t']) )
- {
- $module_prefix = $module_data['Var'];
- break;
- }
- }
- $passed[] = $module_prefix;
- }
- return $vars;
- }
-
- if ( $module_prefix = $this->ProcessModuleItem($url_parts, $vars, false) ) {
- $passed[] = $module_prefix;
- return $vars;
- }*/
-
if (!$found) {
$not_found = $this->Application->ConfigValue('ErrorTemplate');
$vars['t'] = $not_found ? $not_found : 'error_notfound';
$themes_helper =& $this->Application->recallObject('ThemesHelper');
/* @var $themes_helper kThemesHelper */
$vars['m_cat_id'] = $themes_helper->getPageByTemplate($vars['t']);
header('HTTP/1.0 404 Not Found');
}
return $vars;
// $this->HTTPQuery->finalizeParsing($passed, $module_params);
}
}
?>
\ No newline at end of file
Index: branches/RC/core/units/general/custom_fields.php
===================================================================
--- branches/RC/core/units/general/custom_fields.php (revision 11853)
+++ branches/RC/core/units/general/custom_fields.php (revision 11854)
@@ -1,131 +1,145 @@
<?php
/**
* Enter description here...
*
* @todo rewrite
*/
class InpCustomFieldsHelper extends kHelper {
/**
* Parses given option string and returns associative array
*
* @param string $values_list
* @param string $separator
- * @param bool $parse_sqls
+ * @param bool $parse
* @return Array
*/
- function GetValuesHash($values_list, $separator = VALUE_LIST_SEPARATOR, $parse_sqls = true)
+ function GetValuesHash($values_list, $separator = VALUE_LIST_SEPARATOR, $parse = true)
{
- $values_list = trim($this->ParseConfigSQL($values_list, $separator, $parse_sqls), $separator);
+ $values_list = trim($this->ParseConfigSQL($values_list, $separator, $parse), $separator);
if (!$values_list) {
// no options, then return empty array
return Array();
}
$optionValuesTmp = explode($separator, $values_list);
$optionValues = Array();
if (substr_count($values_list, '=') != count($optionValuesTmp)) {
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
trigger_error('Invalid symbol in ValueList field [' . substr($values_list, 0, 100) . ' ...]' , E_USER_NOTICE);
return Array ();
}
- foreach ($optionValuesTmp as $optionValue) {
- list ($key, $val) = explode('=', $optionValue);
- $val = (substr($val,0,1) == '+') ? substr($val, 1) : $this->Application->Phrase($val);
+ if ($parse) {
+ // normal way
+ foreach ($optionValuesTmp as $optionValue) {
+ list ($key, $val) = explode('=', $optionValue);
- if (substr($key, 0, 3) == 'SQL') {
- $val = base64_decode( str_replace('_', '=', $val) );
+ $val = substr($val, 0, 1) == '+' ? substr($val, 1) : $this->Application->Phrase($val);
+
+ $optionValues[$key] = $val;
}
- $optionValues[$key] = $val;
}
+ else {
+ // during custom field editing
+ foreach ($optionValuesTmp as $optionValue) {
+ list ($key, $val) = explode('=', $optionValue);
+
+ if (substr($key, 0, 3) == 'SQL') {
+ $val = base64_decode( str_replace('_', '=', substr($val, 1)) );
+ }
+
+ $optionValues[$key] = $val;
+ }
+ }
+
return $optionValues;
}
/**
* Replace SQL's in valueList with appropriate queried values
*
* @param string $valueString
* @param string $separator
* @return string
* @todo Apply refactoring to embedded vars stuff
*/
function ParseConfigSQL($valueString, $separator = VALUE_LIST_SEPARATOR, $parse_sqls = true)
{
$string = trim( str_replace(Array('<PREFIX>', '%3$s'), Array (TABLE_PREFIX, $this->Application->GetVar('m_lang')), $valueString) );
preg_match_all("|\{(.*)\}|U", $string, $embedded_vars, PREG_SET_ORDER);
/*
<SQL> 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([+]{0,1})>(.*?)<\/SQL>/', $string, $regs)) {
$i = 0;
$sql_count = count($regs[0]);
while ($i < $sql_count) {
if ($parse_sqls) {
$replacement = $this->_queryConfigSQL($regs[2][$i], $regs[1][$i], $separator);
}
else {
$sql = base64_encode('<SQL'.$regs[1][$i].'>'.$regs[2][$i].'</SQL>');
$replacement = 'SQL' . $i . '=+' . str_replace('=', '_', $sql);
}
$string = str_replace('<SQL'.$regs[1][$i].'>'.$regs[2][$i].'</SQL>', $replacement, $string);
$i++;
}
$string = preg_replace('/[' . preg_quote($separator, '/') . ']+/', $separator, $string); // trim trailing separators inside string
}
return $string;
}
/**
* Transforms given sql into value list string
*
* @param string $sql
* @param string $plus
* @param string $separator
* @return string
*/
function _queryConfigSQL($sql, $plus = '', $separator = VALUE_LIST_SEPARATOR)
{
$values = $this->Conn->Query($sql);
foreach ($values as $index => $value) {
$values[$index] = $value['OptionValue'] . '=' . $plus . $value['OptionName'];
}
return implode($separator, $values);
}
}
?>
\ No newline at end of file
Index: branches/RC/core/admin_templates/custom_fields/custom_fields_edit.tpl
===================================================================
--- branches/RC/core/admin_templates/custom_fields/custom_fields_edit.tpl (revision 11853)
+++ branches/RC/core/admin_templates/custom_fields/custom_fields_edit.tpl (revision 11854)
@@ -1,156 +1,158 @@
<inp2:adm_SetPopupSize width="750" height="620"/>
<inp2:m_include t="incs/header"/>
<inp2:m_Get name="section" result_to_var="section"/>
<inp2:m_RenderElement name="combined_header" prefix="cf" section="$section" perm_event="cf:OnLoad" title_preset="custom_fields_edit"/>
<!-- ToolBar -->
<table class="toolbar" height="30" cellspacing="0" cellpadding="0" width="100%" border="0">
<tbody>
<tr>
<td>
<script type="text/javascript">
a_toolbar = new ToolBar();
a_toolbar.AddButton( new ToolBarButton('select', '<inp2:m_phrase label="la_ToolTip_Save" escape="1"/>', function() {
submit_event('cf','<inp2:cf_SaveEvent/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('cancel', '<inp2:m_phrase label="la_ToolTip_Cancel" escape="1"/>', function() {
submit_event('cf','OnCancelEdit');
}
) );
a_toolbar.AddButton( new ToolBarSeparator('sep1') );
a_toolbar.AddButton( new ToolBarButton('prev', '<inp2:m_phrase label="la_ToolTip_Prev" escape="1"/>', function() {
go_to_id('cf', '<inp2:cf_PrevId/>');
}
) );
a_toolbar.AddButton( new ToolBarButton('next', '<inp2:m_phrase label="la_ToolTip_Next" escape="1"/>', function() {
go_to_id('cf', '<inp2:cf_NextId/>');
}
) );
a_toolbar.Render();
<inp2:m_if check="cf_IsSingle" >
a_toolbar.HideButton('prev');
a_toolbar.HideButton('next');
a_toolbar.HideButton('sep1');
<inp2:m_else/>
<inp2:m_if check="cf_IsLast" >
a_toolbar.DisableButton('next');
</inp2:m_if>
<inp2:m_if check="cf_IsFirst" >
a_toolbar.DisableButton('prev');
</inp2:m_if>
</inp2:m_if>
</script>
</td>
</tr>
</tbody>
</table>
<inp2:m_RenderElement name="inp_edit_hidden" prefix="cf" field="Type" db="db"/>
<inp2:cf_SaveWarning name="grid_save_warning"/>
<inp2:cf_ErrorWarning name="form_error_warning"/>
<div id="scroll_container">
<table class="edit-form">
<inp2:m_RenderElement name="subsection" title="!la_section_General!"/>
<inp2:m_RenderElement name="inp_id_label" prefix="cf" field="CustomFieldId" title="!la_prompt_FieldId!"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="FieldName" title="!la_prompt_FieldName!" size="40"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="FieldLabel" title="!la_prompt_FieldLabel!" size="40"/>
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="cf" field="MultiLingual" title="!la_fld_MultiLingual!"/>
<inp2:m_RenderElement name="subsection" title="!la_tab_AdminUI!"/>
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="cf" field="OnGeneralTab" title="!la_prompt_showgeneraltab!"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="Heading" title="!la_prompt_heading!" size="40"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="Prompt" title="!la_prompt_FieldPrompt!" size="40"/>
<inp2:m_RenderElement name="inp_edit_options" prefix="cf" field="ElementType" title="!la_prompt_InputType!" size="20" onchange="update_layout();"/>
<inp2:m_if check="cf_Field" name="ElementType" equals_to="select|multiselect|radio" db="db" inverse="inverse">
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="ValueList" title="!la_prompt_valuelist!" size="40"/>
</inp2:m_if>
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="cf" field="IsRequired" title="la_fld_IsRequired"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="DefaultValue" title="la_prompt_Default"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="DisplayOrder" title="!la_field_displayorder!" size="10"/>
<inp2:m_if check="m_IsDebugMode">
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="cf" field="IsSystem" title="!la_fld_IsSystem!"/>
</inp2:m_if>
<inp2:m_if check="cf_Field" name="ElementType" equals_to="select|multiselect|radio" db="db">
<inp2:m_RenderElement name="subsection" title="la_section_Values"/>
<inp2:m_RenderElement name="inp_edit_checkbox" prefix="cf" field="SortValues" title="la_fld_SortValues"/>
<inp2:m_RenderElement name="inp_edit_hidden" prefix="cf" field="OptionKey"/>
<inp2:m_RenderElement name="inp_edit_box" prefix="cf" field="OptionTitle" title="la_fld_OptionTitle" size="60"/>
<inp2:m_RenderElement name="inp_edit_minput" prefix="cf" field="Options" title="la_fld_Options" format="#OptionTitle# (#OptionKey#)" style="width: 400px; height: 200px;"/>
</inp2:m_if>
+
+ <inp2:m_RenderElement name="inp_edit_filler"/>
</table>
</div>
<inp2:m_if check="cf_Field" name="ElementType" equals_to="select|multiselect|radio" db="db">
<script type="text/javascript">
Options.registerControl('OptionKey', 'text', false);
Options.registerControl('OptionTitle', 'text', true);
Options.LoadValues();
Options.getControlValue = function ($field) {
var $value = this.getControl($field).value;
if ($field == 'OptionKey' && !$value) {
$options = this.getControl(this.FieldName, 'minput').options;
if ($options.length) {
var $i = 0;
var $max_option_key = 0;
while ($i < $options.length) {
if (parseInt(this.Records[ $options[$i].value ]['OptionKey']) > $max_option_key) {
$max_option_key = parseInt(this.Records[ $options[$i].value ]['OptionKey']);
}
$i++;
}
return $max_option_key + 1;
}
// when no this will be 1st record in list use 1
return 1;
}
return $value;
}
Options.compareRecords = function($record_a, $record_b) {
// compare by option title only, it's id doesn't matter
return $record_a['OptionTitle'].toLowerCase() == $record_b['OptionTitle'].toLowerCase();
}
</script>
</inp2:m_if>
<script type="text/javascript">
function update_layout() {
var $last_element_type = '<inp2:cf_Field name="ElementType" db="db" js_escape="1"/>';
var $element_type = document.getElementById('<inp2:cf_InputName name="ElementType" js_escape="1"/>').value;
// value is changed from ml supported to normal or otherwise
if (canHaveMultipleValues($last_element_type) != canHaveMultipleValues($element_type)) {
submit_event('cf', 'OnPreSave');
}
}
function canHaveMultipleValues($element_type) {
var $element_types = ['select', 'multiselect', 'radio'];
return $element_types.indexOf($element_type) != -1;
}
</script>
<inp2:m_include t="incs/footer"/>
Index: branches/RC/core/admin_templates/js/form_controls.js
===================================================================
--- branches/RC/core/admin_templates/js/form_controls.js (revision 11853)
+++ branches/RC/core/admin_templates/js/form_controls.js (revision 11854)
@@ -1,540 +1,540 @@
function MultiInputControl($field_name, $field_mask, $field_labels, $result_mask) {
this.FieldName = $field_name;
this.ValidateURL = '';
this.FieldMask = $field_mask;
this.FieldLabels = $field_labels;
this.ResultMask = $result_mask; // format of record in list
this.Permissions = new Array (); // action groups allowed
this.Messages = new Array (); // various phrase (errors, confirmations, button titles)
this.Controls = new Array (); // controls used for editing list content
this.Records = new Array (); // data to be submitted (needs to be parsed using formatters)
this.Errors = new Array (); // error messages in fields
this.InEditing = false;
}
MultiInputControl.prototype.registerControl = function($field_name, $type, $required, $options) {
this.Controls[$field_name] = {'type' : $type, 'required' : $required, 'options' : $options};
}
MultiInputControl.prototype.getControl = function ($field, $appendix, $prepend) {
$appendix = isset($appendix) ? '_' + $appendix : '';
$prepend = isset($prepend) ? $prepend + '_' : '';
return document.getElementById( $prepend + this.FieldMask.replace('#FIELD_NAME#', $field) + $appendix );
}
MultiInputControl.prototype.getControlValue = function ($field) {
var $value = '';
switch (this.Controls[$field]['type']) {
case 'select':
var $control = this.getControl($field);
$value = $control.options[$control.selectedIndex].value;
break;
/*case 'datetime':
$value = this.getControl($field + '_date').value + ' ' + this.getControl($field + '_time').value;
break;*/
default:
$value = this.getControl($field).value;
break;
}
return $value;
}
MultiInputControl.prototype.setControlValue = function ($field, $value) {
switch (this.Controls[$field]['type']) {
case 'select':
var $i = 0;
var $control = this.getControl($field);
if ($value === null) {
$control.selectedIndex = 0;
}
while ($i < $control.options.length) {
if ($control.options[$i].value == $value) {
$control.selectedIndex = $i;
break;
}
$i++;
}
break;
case 'checkbox':
this.getControl($field).value = ($value === null) ? 0 : $value;
this.getControl($field, null, '_cb').checked = parseInt($value) == 1;
break;
/*case 'datetime':
$value = $value.split(' ');
this.getControl($field + '_date').value = $value[0];
this.getControl($field + '_time').value = $value[1];
break;*/
default:
this.getControl($field).value = ($value === null) ? '' : $value;
break;
}
}
MultiInputControl.prototype.formatValue = function ($field, $value) {
if (this.Controls[$field]['type'] == 'select') {
var $i = 0;
var $control = this.getControl($field);
while ($i < $control.options.length) {
if ($control.options[$i].value == $value) {
$value = $control.options[$i].innerHTML;
break;
}
$i++;
}
}
if (this.Controls[$field]['type'] == 'textbox') {
var $field_options = this.Controls[$field]['options'];
if ($field_options && parseInt($field_options.first_chars) > 0) {
$value = $value.substring(0, parseInt($field_options.first_chars));
}
}
if (this.Controls[$field]['type'] == 'checkbox') {
$value = this.Controls[$field]['options'][ parseInt($value) ];
}
return $value;
}
MultiInputControl.prototype.formatLine = function($record_index) {
var $ret = this.ResultMask;
for (var $field_name in this.Controls) {
var $value = this.Records[$record_index][$field_name];
$ret = $ret.replace('#' + $field_name + '#', this.formatValue($field_name, $value));
}
- return $ret;
+ return this.htmlspecialchars($ret);
}
MultiInputControl.prototype._getRecordIndex = function ($selected_index) {
var $object = this.getControl(this.FieldName, 'minput');
if (!isset($selected_index)) {
$selected_index = $object.selectedIndex;
}
return $selected_index == -1 ? -1 : $object.options[$selected_index].value;
}
MultiInputControl.prototype.makeRequest = function($request_type, $record, $skip_index) {
var $url = this.ValidateURL;
for (var $field_name in $record) {
$url += '&' + this.FieldMask.replace('#FIELD_NAME#', $field_name) + '=' + escape($record[$field_name]);
}
Request.makeRequest($url, this.BusyRequest, '', this.successCallback, this.errorCallback, [$request_type, $record, $skip_index], this);
}
MultiInputControl.prototype.AddRecord = function() {
var $record = this.prepareRecord();
if (this.InEditing) {
// already in editing
var $record_index = this.getControl(this.FieldName, 'minput').selectedIndex;
this.makeRequest('SaveRecord', $record, $record_index);
return ;
}
if (this.hasPermission('add')) {
this.makeRequest('AddRecord', $record, false);
}
}
MultiInputControl.prototype.EditRecord = function() {
var $record_index = this._getRecordIndex(); // this.getControl(this.FieldName, 'minput').selectedIndex;
if ($record_index == -1 || this.InEditing) {
// no record selected
return ;
}
this.InEditing = true;
var $edit_record = this.Records[$record_index];
for (var $field_name in $edit_record) {
this.setControlValue($field_name, $edit_record[$field_name]);
}
this.getControl(this.FieldName, 'add_button').value = this.Messages['save_button'];
this.getControl(this.FieldName, 'minput').disabled = true;
this.SetButtonState('edit', false);
this.SetButtonState('delete', false);
}
MultiInputControl.prototype.ResetControls = function() {
for (var $field_name in this.Controls) {
this.setControlValue($field_name, null);
}
this.Errors = new Array ();
}
MultiInputControl.prototype.CancelEditing = function() {
this.ResetControls();
this.getControl(this.FieldName, 'add_button').value = this.Messages['add_button'];
this.getControl(this.FieldName, 'minput').disabled = false;
this.SetButtonState('edit', true);
this.SetButtonState('delete', true);
this.InEditing = false;
}
MultiInputControl.prototype.ShowRecord = function($option_index) {
var $options = this.getControl(this.FieldName, 'minput').options;
if ($option_index < $options.length) {
// update existing record
$options[$option_index].innerHTML = this.formatLine( this._getRecordIndex($option_index) );
}
else {
// create new record
var $new_option = document.createElement('OPTION');
$options.add($new_option, $options.length);
$new_option.value = $option_index; // will be used in move up/down & sorting (if any)
$new_option.innerHTML = this.formatLine(this.Records.length - 1);
}
}
MultiInputControl.prototype.DeleteRecords = function() {
if (!confirm(this.Messages['delete_confirm'])) {
return ;
}
var $control = this.getControl(this.FieldName, 'minput');
var $i = $control.length - 1;
while ($i >= 0) {
if ($control.options[$i].selected == true) {
this.Records[$control.options[$i].value] = null; // preserves index, when removing element from middle of array. this.Records.splice($control.options[$i].value, 1);
$control.remove($i);
}
$i--;
}
this.SaveValues();
}
MultiInputControl.prototype.MoveRecordsUp = function() {
move_options_up(this.getControl(this.FieldName, 'minput'), 1);
this.SaveValues();
}
MultiInputControl.prototype.MoveRecordsDown = function() {
move_options_down(this.getControl(this.FieldName, 'minput'), 1);
this.SaveValues();
}
MultiInputControl.prototype.AddFromXML = function($xml) {
var $document = getDocumentFromXML($xml);
this.ProcessXMLNode($document);
}
MultiInputControl.prototype.ProcessXMLNode = function($node, $root_name) {
for (var $i = 0; $i < $node.childNodes.length; $i++) {
var $child = $node.childNodes.item($i);
if ($child.tagName == 'record') {
this.Records[this.Records.length] = new Array ();
this.ProcessXMLNode($child, $root_name);
this.ShowRecord(this.Records.length - 1);
}
else if ($child.tagName == 'field') {
if ($root_name == 'records') {
// no firstChild, when node value is empty!
this.Records[this.Records.length - 1][$child.getAttribute('name')] = $child.firstChild ? $child.firstChild.nodeValue : '';
}
else if ($root_name == 'errors') {
this.Errors[$child.getAttribute('name')] = $child.firstChild.nodeValue;
}
}
else if ($child.tagName == 'records') {
this.ProcessXMLNode($child, $child.tagName);
}
else if ($child.tagName == 'errors') {
this.Errors = new Array ();
this.ProcessXMLNode($child, $child.tagName);
}
}
}
MultiInputControl.prototype.LoadValues = function() {
var $current_value = this.getControl(this.FieldName).value;
if ($current_value) {
this.AddFromXML($current_value);
}
}
MultiInputControl.prototype.SaveValues = function() {
var $object = this.getControl(this.FieldName, 'minput');
var $record_index = 0;
var $xml = '';
var $i = 0;
while ($i < $object.options.length) {
$record_index = $object.options[$i].value;
$xml += '<record>';
for (var $field_name in this.Controls) {
$xml += '<field name="' + $field_name + '">' + this.htmlspecialchars(this.Records[$record_index][$field_name]) + '</field>';
}
$xml += '</record>';
$i++;
}
this.getControl(this.FieldName).value = $xml ? '<records>' + $xml + '</records>' : '';
}
MultiInputControl.prototype.htmlspecialchars = function (string) {
string = string.toString();
string = string.replace(/&/g, '&amp;');
string = string.replace(/</g, '&lt;');
string = string.replace(/>/g, '&gt;');
string = string.replace(/\"/g, '&quot;');
return string;
}
MultiInputControl.prototype.prepareRecord = function() {
var $record = new Array ();
for (var $field_name in this.Controls) {
$record[$field_name] = this.getControlValue($field_name);
}
return $record;
}
MultiInputControl.prototype.ValidateRecord = function($record, $skip_index) {
var $valid = true;
$valid = $valid && this.ValidateRequired($record);
$valid = $valid && this.ValidateUnique($record, $skip_index);
return $valid;
}
MultiInputControl.prototype.ValidateRequired = function($record) {
for (var $field_name in $record) {
if (this.Controls[$field_name]['required'] && !$record[$field_name]) {
alert(this.Messages['required_error']);
return false;
}
}
return true;
}
MultiInputControl.prototype.compareRecords = function($record_a, $record_b) {
var $equals = true;
for (var $field_name in $record_a) {
if ($record_a[$field_name] !== $record_b[$field_name]) {
return false;
}
}
return $equals;
}
MultiInputControl.prototype.ValidateUnique = function($record, $skip_index) {
var $i = 0;
if (!isset($skip_index)) {
$skip_index = -1;
}
while ($i < this.Records.length) {
if (this.Records[$i] == null) {
// skip deleted records
$i++;
continue;
}
if ($i != $skip_index && this.compareRecords($record, this.Records[$i])) {
alert(this.Messages['unique_error']);
return false;
}
$i++;
}
return true;
}
MultiInputControl.prototype.displayErrors = function() {
var $has_errors = false;
var $field_label = '';
for (var $field_name in this.Errors) {
$has_errors = true;
alert(this.FieldLabels[$field_name] + ': ' + this.Errors[$field_name]);
}
return $has_errors;
}
MultiInputControl.prototype.successCallback = function($request, $params, $object) {
if (Request.processRedirect($request) === true) {
return ;
}
var $document = getDocumentFromXML($request.responseText);
$object.ProcessXMLNode($document);
if ($object.displayErrors()) {
return ;
}
// params: 0 - action type, 1 - record data, 2 - option index
switch ($params[0]) {
case 'AddRecord':
if (!$object.ValidateRecord($params[1])) {
return ;
}
$object.Records.push($params[1]);
$object.ShowRecord($object.Records.length - 1);
$object.ResetControls();
break;
case 'SaveRecord':
$record_index = $object._getRecordIndex($params[2]);
if (!$object.ValidateRecord($params[1], $record_index)) {
return ;
}
$object.Records[$record_index] = $params[1];
$object.ShowRecord($params[2]);
$object.CancelEditing();
break;
}
$object.SaveValues();
}
MultiInputControl.prototype.errorCallback = function($request, $params, $object) {
alert('AJAX Error; class: MultiInputControl; ' + Request.getErrorHtml($request));
}
MultiInputControl.prototype.SetMessage = function($pseudo, $message) {
this.Messages[$pseudo] = $message;
}
MultiInputControl.prototype.InitEvents = function() {
var $button = null;
var $var_name = this.FieldName;
$button = this.getControl(this.FieldName, 'add_button');
$button.onclick = function() { eval($var_name).AddRecord() };
if (this.hasPermission('add') || this.hasPermission('edit')) {
$button = this.getControl(this.FieldName, 'cancel_button');
$button.onclick = function() { eval($var_name).CancelEditing() };
}
if (this.hasPermission('edit')) {
$button = this.getControl(this.FieldName, 'edit_button');
$button.onclick = function() { eval($var_name).EditRecord() };
$button = this.getControl(this.FieldName, 'minput');
$button.ondblclick = function() { eval($var_name).EditRecord() };
}
if (this.hasPermission('delete')) {
$button = this.getControl(this.FieldName, 'delete_button');
$button.onclick = function() { eval($var_name).DeleteRecords() };
}
if (this.hasPermission('move')) {
$button = this.getControl(this.FieldName, 'moveup_button');
$button.onclick = function() { eval($var_name).MoveRecordsUp() };
$button = this.getControl(this.FieldName, 'movedown_button');
$button.onclick = function() { eval($var_name).MoveRecordsDown() };
}
}
MultiInputControl.prototype.hasPermission = function ($perm_name) {
return in_array($perm_name, this.Permissions);
}
MultiInputControl.prototype.SetPermission = function ($perm_name, $perm_value) {
var $perm_index = array_search($perm_name, this.Permissions);
if ($perm_index != -1) {
// permission found
if (!$perm_value) {
this.Permissions = this.Permissions.splice($perm_index, 1);
}
}
else if ($perm_value) {
// permission not found
this.Permissions.push($perm_name);
}
}
MultiInputControl.prototype.SetButtonState = function ($button, $mode) {
if (!this.hasPermission($button)) {
return ;
}
var $button = this.getControl(this.FieldName, $button + '_button');
$button.disabled = !$mode;
$button.className = $mode ? 'button' : 'button-disabled';
}
// =======================================================================================
function EditPickerControl($field_name, $field_mask) {
this.FieldName = $field_name;
this.FieldMask = $field_mask;
this.Messages = new Array ();
this.InitEvents();
select_sort( this.getControl('available') );
}
EditPickerControl.prototype.getControl = function ($type) {
var $control_id = this.FieldMask + (isset($type) ? '_' + $type : '');
return document.getElementById($control_id);
}
EditPickerControl.prototype.SetMessage = function ($pseudo, $message) {
this.Messages[$pseudo] = $message;
}
EditPickerControl.prototype.SaveValues = function () {
this.getControl().value = select_to_string(this.getControl('selected'));
this.getControl('available_field').value = select_to_string(this.getControl('available'));
}
EditPickerControl.prototype.MoveLeft = function () {
move_selected(this.getControl('available'), this.getControl('selected'), this.Messages['nothing_selected']);
this.SaveValues();
}
EditPickerControl.prototype.MoveRight = function () {
move_selected(this.getControl('selected'), this.getControl('available'), this.Messages['nothing_selected']);
select_sort( this.getControl('available') );
this.SaveValues();
}
EditPickerControl.prototype.InitEvents = function() {
var $button = null;
var $var_name = this.FieldName;
$button = this.getControl('move_left_button');
$button.onclick = function() { eval($var_name).MoveLeft() };
$button = this.getControl('move_right_button');
$button.onclick = function() { eval($var_name).MoveRight() };
}
\ No newline at end of file

Event Timeline