Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Sat, Feb 1, 11:08 AM

in-portal

This file is larger than 256 KB, so syntax highlighting was skipped.
Index: branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.1.0.sql
===================================================================
--- branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.1.0.sql (revision 8241)
+++ branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.1.0.sql (revision 8242)
@@ -1,39 +1,39 @@
ALTER TABLE EmailMessage ADD ReplacementTags TEXT AFTER Template;
ALTER TABLE Phrase CHANGE Translation Translation TEXT NOT NULL, CHANGE Module Module VARCHAR(30) NOT NULL DEFAULT 'In-Portal';
ALTER TABLE Category CHANGE Description Description TEXT, CHANGE l1_Description l1_Description TEXT, CHANGE l2_Description l2_Description TEXT, CHANGE l3_Description l3_Description TEXT, CHANGE l4_Description l4_Description TEXT, CHANGE l5_Description l5_Description TEXT, CHANGE CachedNavbar CachedNavbar text, CHANGE l1_CachedNavbar l1_CachedNavbar text, CHANGE l2_CachedNavbar l2_CachedNavbar text, CHANGE l3_CachedNavbar l3_CachedNavbar text, CHANGE l4_CachedNavbar l4_CachedNavbar text, CHANGE l5_CachedNavbar l5_CachedNavbar text, CHANGE ParentPath ParentPath TEXT NULL DEFAULT NULL, CHANGE NamedParentPath NamedParentPath TEXT NULL DEFAULT NULL;
ALTER TABLE ConfigurationAdmin CHANGE ValueList ValueList TEXT;
ALTER TABLE EmailQueue CHANGE `Subject` `Subject` TEXT, CHANGE toaddr toaddr TEXT, CHANGE fromaddr fromaddr TEXT;
ALTER TABLE Category DROP Pop;
-ALTER TABLE PortalUser CHANGE CreatedOn CreatedOn INT NOT NULL DEFAULT '0', CHANGE dob dob INT(11) NULL DEFAULT NULL, CHANGE PassResetTime PassResetTime INT(11) UNSIGNED NULL DEFAULT NULL, CHANGE PwRequestTime PwRequestTime INT(11) UNSIGNED NULL DEFAULT NULL, CHANGE `Password` `Password` VARCHAR(255) NULL DEFAULT 'd41d8cd98f00b204e9800998ecf8427e';
+ALTER TABLE PortalUser CHANGE CreatedOn CreatedOn INT DEFAULT NULL, CHANGE dob dob INT(11) NULL DEFAULT NULL, CHANGE PassResetTime PassResetTime INT(11) UNSIGNED NULL DEFAULT NULL, CHANGE PwRequestTime PwRequestTime INT(11) UNSIGNED NULL DEFAULT NULL, CHANGE `Password` `Password` VARCHAR(255) NULL DEFAULT 'd41d8cd98f00b204e9800998ecf8427e';
ALTER TABLE Modules CHANGE BuildDate BuildDate INT UNSIGNED NULL DEFAULT NULL, CHANGE Version Version VARCHAR(10) NOT NULL DEFAULT '0.0.0', CHANGE `Var` `Var` VARCHAR(100) NOT NULL DEFAULT '';
ALTER TABLE Language CHANGE Enabled Enabled INT(11) NOT NULL DEFAULT '1', CHANGE InputDateFormat InputDateFormat VARCHAR(50) NOT NULL DEFAULT 'm/d/Y', CHANGE InputTimeFormat InputTimeFormat VARCHAR(50) NOT NULL DEFAULT 'g:i:s A', CHANGE DecimalPoint DecimalPoint VARCHAR(10) NOT NULL DEFAULT '', CHANGE ThousandSep ThousandSep VARCHAR(10) NOT NULL DEFAULT '';
ALTER TABLE Events CHANGE FromUserId FromUserId INT(11) NOT NULL DEFAULT '-1';
ALTER TABLE StdDestinations CHANGE DestAbbr2 DestAbbr2 CHAR(2) NULL DEFAULT NULL;
ALTER TABLE PermCache DROP DACL;
ALTER TABLE Images CHANGE LocalThumb LocalThumb TINYINT(4) NOT NULL DEFAULT '1', CHANGE SameImages SameImages TINYINT(4) NOT NULL DEFAULT '1', CHANGE AltName AltName VARCHAR(255) NOT NULL DEFAULT '';
ALTER TABLE SearchConfig CHANGE SimpleSearch SimpleSearch TINYINT(4) NOT NULL DEFAULT '1', CHANGE AdvancedSearch AdvancedSearch TINYINT(4) NOT NULL DEFAULT '1', CHANGE ModuleName ModuleName VARCHAR(20) NOT NULL DEFAULT 'In-Portal';
ALTER TABLE ItemReview CHANGE CreatedById CreatedById INT(11) NOT NULL DEFAULT '-1', CHANGE Status Status TINYINT(4) NOT NULL DEFAULT '2', CHANGE CreatedOn CreatedOn INT UNSIGNED NULL DEFAULT NULL;
ALTER TABLE Visits CHANGE PortalUserId PortalUserId INT(11) NOT NULL DEFAULT '-2';
ALTER TABLE ItemRating CHANGE CreatedOn CreatedOn INT UNSIGNED NULL DEFAULT NULL;
ALTER TABLE PortalGroup CHANGE CreatedOn CreatedOn INT UNSIGNED NULL DEFAULT NULL;
ALTER TABLE SpamControl CHANGE Expire Expire INT UNSIGNED NULL DEFAULT NULL;
ALTER TABLE SuggestMail CHANGE sent sent INT UNSIGNED NULL DEFAULT NULL;
ALTER TABLE SysCache CHANGE Expire Expire INT UNSIGNED NULL DEFAULT NULL;
ALTER TABLE UserSession CHANGE SessionKey SessionKey INT UNSIGNED NULL DEFAULT NULL, CHANGE CurrentTempKey CurrentTempKey INT UNSIGNED NULL DEFAULT NULL, CHANGE PrevTempKey PrevTempKey INT UNSIGNED NULL DEFAULT NULL, CHANGE LastAccessed LastAccessed INT UNSIGNED NOT NULL DEFAULT '0', CHANGE PortalUserId PortalUserId INT(11) NOT NULL DEFAULT '-2', CHANGE Language Language INT(11) NOT NULL DEFAULT '1', CHANGE Theme Theme INT(11) NOT NULL DEFAULT '1';
UPDATE Phrase SET Translation = REPLACE(Translation, CHAR(146), "'");
CREATE TABLE Counters (CounterId int(10) unsigned NOT NULL auto_increment,Name varchar(100) NOT NULL default '',CountQuery text,CountValue text,LastCounted int(10) unsigned default NULL,LifeTime int(10) unsigned NOT NULL default '3600',IsClone tinyint(3) unsigned NOT NULL default '0',TablesAffected text,PRIMARY KEY (CounterId),UNIQUE KEY Name (Name));
UPDATE Modules SET Version = '4.1.0' WHERE Name = 'In-Portal';
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/inportal_upgrade_v4.1.0.sql
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.1
\ No newline at end of property
+1.1.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.1.2/core/units/skins/skins_config.php
===================================================================
--- branches/unlabeled/unlabeled-1.1.2/core/units/skins/skins_config.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.1.2/core/units/skins/skins_config.php (revision 8242)
@@ -1,164 +1,166 @@
<?php
$config = Array(
'Prefix' => 'skin',
'ItemClass' => Array('class'=>'kDBItem','file'=>'','build_event'=>'OnItemBuild'),
'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'),
'EventHandlerClass' => Array('class'=>'SkinEventHandler','file'=>'skin_eh.php','build_event'=>'OnBuild'),
'TagProcessorClass' => Array('class'=>'kDBTagProcessor','file'=>'','build_event'=>'OnBuild'),
'AutoLoad' => true,
'Hooks' => Array(
Array(
'Mode' => hAFTER,
'Conditional' => false,
'HookToPrefix' => 'skin',
'HookToSpecial' => '',
'HookToEvent' => Array('OnSave'),
'DoPrefix' => '',
'DoSpecial' => '',
'DoEvent' => 'OnCompileStylesheet',
),
),
'QueryString' => Array(
1 => 'id',
2 => 'Page',
3 => 'event',
4 => 'mode',
),
'IDField' => 'SkinId',
- 'StatusField' => Array('Status', 'IsPrimary'),
+ 'StatusField' => Array('IsPrimary'),
'TableName' => TABLE_PREFIX.'Skins',
/*
'ForeignKey' => 'ParentId', // field title in TableName, linking record to a parent
'ParentTableKey' => 'ParentId', // id (or other key) field title in parent's table
'ParentPrefix' => 'parent',
'AutoDelete' => true, // delete these items when parent is being deleted
'AutoClone' => true, // clone these items when parent is being cloned
*/
'TitlePresets' => Array(
'default' => Array(
'new_status_labels' => Array('skin'=>'!la_title_AddingSkin!'),
'edit_status_labels' => Array('skin'=>'!la_title_EditingSkin!'),
'new_titlefield' => Array('skin'=>''),
),
'skin_list'=>Array(
'prefixes' => Array('skin_List'),
'format' => '!la_title_Skins! (#skin_recordcount#)',
),
'skin_edit'=>Array(
'prefixes' => Array('skin'),
'format' => '#skin_status# #skin_titlefield#',
),
),
'PermSection' => Array('main' => 'in-portal:skins'),
// don't forget to add corresponding permissions to install script
// INSERT INTO Permissions VALUES (0, 'custom:custom.view', 11, 1, 1, 0);
// INSERT INTO Permissions VALUES (0, 'in-portal:skins.view', 11, 1, 1, 0), (0, 'in-portal:skins.add', 11, 1, 1, 0), (0, 'in-portal:skins.edit', 11, 1, 1, 0), (0, 'in-portal:skins.delete', 11, 1, 1, 0);
'Sections' => Array(
'in-portal:skins' => Array(
'parent' => 'in-portal:tools',
'icon' => 'conf_general',
'label' => 'la_tab_Skins',
'url' => Array('t' => 'skins/skin_list', 'pass' => 'm'),
'permissions' => Array('view'),
'priority' => 11,
'show_mode' => smSUPER_ADMIN,
'type' => stTREE,
),
),
'TitleField' => 'Name', // field, used in bluebar when editing existing item
// Use %1$s for local table name with prefix, %2$s for calculated fields
'ListSQLs' => Array( // key - special, value - list select sql
'' => 'SELECT %1$s.* %2$s
FROM %1$s',
),
'ItemSQLs' => Array(
'' => 'SELECT %1$s.* %2$s
FROM %1$s',
),
'ListSortings' => Array(
'' => Array(
// 'ForcedSorting' => Array('Priority' => 'desc'),
'Sorting' => Array('Name' => 'asc'),
)
),
'Fields' => Array (
- 'SkinId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
- 'Name' => Array ('type' => 'string', 'max_len' => 255, 'default' => NULL),
- 'CSS' => Array ('type' => 'string', 'default' => NULL),
- 'Logo' => Array(
- 'type'=>'string', 'formatter'=>'kUploadFormatter',
- 'max_size'=>MAX_UPLOAD_SIZE, // in Bytes !
- 'file_types'=>'*.jpg;*.gif;*.png', 'files_description'=>'!la_ImageFiles!',
+ 'SkinId' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
+ 'Name' => Array ('type' => 'string', 'max_len' => 255, 'default' => NULL),
+ 'CSS' => Array ('type' => 'string', 'default' => NULL),
+ 'Logo' => Array(
+ 'type'=>'string', 'formatter'=>'kUploadFormatter',
+ 'max_size'=>MAX_UPLOAD_SIZE, // in Bytes !
+ 'file_types'=>'*.jpg;*.gif;*.png', 'files_description'=>'!la_ImageFiles!',
'upload_dir'=>'/system/user_files/', // relative to project's home
'as_image'=>true, 'thumb_width'=>100, 'thumb_height'=>100,
'multiple'=>false, // false or max number of files - will be stored as serialized array of paths
'direct_links'=>false, // use direct file urls or send files through wrapper (requires mod_mime_magic)
- ),
- 'Options' => Array(
- 'type' => 'string', 'default' => NULL,
- 'formatter' => 'kSerializedFormatter',
- 'default'=>serialize(
- array(
- 'HeadBgColor' => array('Description'=>'Head frame background color', 'Value'=>'#1961B8'),
- 'HeadColor' => array('Description'=>'Head frame text color', 'Value'=>'#000000'),
- 'SectionBgColor' => array('Description'=>'Section bar background color', 'Value'=>'#2D79D6'),
- 'SectionColor' => array('Description'=>'Section bar text color', 'Value'=>'#000000'),
- )
- ),
- ),
- 'IsPrimary' => Array(
- 'type' => 'int', 'formatter' => 'kOptionsFormatter',
- 'options' => Array(1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1,
- 'not_null' => 1, 'default' => 0
- ),
+ 'default' => null,
+ ),
+ 'Options' => Array(
+ 'type' => 'string', 'default' => NULL,
+ 'formatter' => 'kSerializedFormatter',
+ 'default'=>serialize(
+ array(
+ 'HeadBgColor' => array('Description'=>'Head frame background color', 'Value'=>'#1961B8'),
+ 'HeadColor' => array('Description'=>'Head frame text color', 'Value'=>'#000000'),
+ 'SectionBgColor' => array('Description'=>'Section bar background color', 'Value'=>'#2D79D6'),
+ 'SectionColor' => array('Description'=>'Section bar text color', 'Value'=>'#000000'),
+ )
+ ),
+ ),
+ 'LastCompiled' => Array ('type' => 'int', 'not_null' => 1, 'default' => 0),
+ 'IsPrimary' => Array(
+ 'type' => 'int', 'formatter' => 'kOptionsFormatter',
+ 'options' => Array(1 => 'la_Yes', 0 => 'la_No'), 'use_phrases' => 1,
+ 'not_null' => 1, 'default' => 0
+ ),
),
'Grids' => Array(
'Default' => Array(
'Icons' => Array('default'=>'icon16_test.gif'),
'Fields' => Array(
'SkinId' => Array( 'title'=>'la_col_Id', 'data_block' => 'grid_checkbox_td', 'width'=>50, 'filter_block' => 'grid_range_filter' ),
- 'Name' => Array( 'title'=>'la_col_SkinName', 'width'=>200),
+ 'Name' => Array( 'title'=>'la_col_SkinName', 'width'=>200, 'filter_block' => 'grid_like_filter'),
'IsPrimary' => Array( 'title'=>'la_col_IsPrimary', 'width'=>150, 'filter_block' => 'grid_options_filter'),
),
),
),
/*'ConfigMapping' => Array(
'PerPage' => 'Comm_Perpage_Tests',
'ShortListPerPage' => 'Comm_Perpage_Tests_Short',
),*/
);
/*
Don't forget to:
- Add table create statement to install_schema.sql
CREATE TABLE Tests (
`TestId` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`Title` VARCHAR( 255 ) NOT NULL ,
`Description` TEXT NULL ,
`Email` VARCHAR( 255 ) NOT NULL ,
`Type` TINYINT NOT NULL ,
`Phone` VARCHAR( 50 ) NOT NULL ,
`Qty` DOUBLE NOT NULL ,
`Status` TINYINT NOT NULL ,
`CreatedOn` INT NOT NULL ,
`Good` TINYINT NOT NULL
)
- Add permissions for admin gorup to install script (see 'Sections' key above)
*/
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.1.2/core/units/skins/skins_config.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.2
\ No newline at end of property
+1.1.2.3
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.13.2/core/units/general/helpers/multilanguage.php
===================================================================
--- branches/unlabeled/unlabeled-1.13.2/core/units/general/helpers/multilanguage.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.13.2/core/units/general/helpers/multilanguage.php (revision 8242)
@@ -1,249 +1,251 @@
<?php
/**
* Performs action on multilingual fields
*
*/
class kMultiLanguageHelper extends kHelper {
var $languageCount = 0;
/**
* Structure of table, that is currently processed
*
* @var Array
*/
var $curStructure = Array();
/**
* Field, to get structure information from
*
* @var string
*/
var $curSourceField = false;
/**
* Indexes used in table of 32
*
* @var int
*/
var $curIndexCount = 0;
/**
* Fields from config, that are currently used
*
* @var Array
*/
var $curFields = Array();
function kMultiLanguageHelper()
{
parent::kHelper();
$this->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)
{
// if ($refresh || !getArrayValue($structure_status, $prefix.'.'.$table_name)) {
$this->curStructure = $this->Conn->Query('DESCRIBE '.$table_name, 'Field');
$this->curIndexCount = count($this->Conn->Query('SHOW INDEXES FROM '.$table_name));
// }
}
/**
* 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') );
+ if ($refresh && preg_match('/(.*)-cdata$/', $prefix, $regs)) {
+ // call main item config to clone cdata table
+ $this->Application->UnitConfigReader->loadConfig($regs[1]);
+ $this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
}
$table_name = $this->Application->getUnitOption($prefix, 'TableName');
$this->curFields = $this->Application->getUnitOption($prefix, 'Fields');
if (!($table_name && $this->curFields) || ($table_name && !$this->Conn->TableFound($table_name))) {
// 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;
if (strtoupper($field_mask['type']) == 'TEXT') {
// text fields in mysql doesn't have default value
$field_mask = $field_mask['name'].' '.$field_mask['type'].' '.$field_mask['null'];
}
else {
$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 = ' ';
$ml_field = preg_replace('/l(.*)_(.*?) (.*)/', '\\2', $field_mask);
$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);
$index_type = isset($this->curFields[$ml_field]['index_type']) ? $this->curFields[$prev_field]['index_type'] : 'string';
$ret .= $index_type == 'string' ? 'ADD INDEX (`'.$field_name.'` (5) ), ' : 'ADD INDEX (`'.$field_name.'`), ';
$this->curIndexCount++;
}
$start_index++;
}
return preg_replace('/, $/',';',$ret);
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.13.2/core/units/general/helpers/multilanguage.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.13.2.1
\ No newline at end of property
+1.13.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.38.2/core/units/users/users_config.php
===================================================================
--- branches/unlabeled/unlabeled-1.38.2/core/units/users/users_config.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.38.2/core/units/users/users_config.php (revision 8242)
@@ -1,211 +1,222 @@
<?php
$config = Array(
'Prefix' => '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',
- ),
+ 'ConfigPriority' => 0,
+ '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',
+ ),
+
+ Array (
+ 'Mode' => hBEFORE,
+ 'Conditional' => false,
+ 'HookToPrefix' => '',
+ 'HookToSpecial' => '*',
+ 'HookToEvent' => Array('OnAfterConfigRead'),
+ 'DoPrefix' => 'cdata',
+ 'DoSpecial' => '*',
+ 'DoEvent' => 'OnDefineCustomFields',
+ ),
+ ),
'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'=>''),
),
'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_custom' => Array('prefixes' => Array('u'), 'format' => "#u_status# '#u_titlefield#' - !la_title_Custom!"),
'users_select' => Array('prefixes' => Array('u_List'), 'format' => "!la_title_Users! (#u_recordcount#) - !la_title_SelectUser!"),
'user_groups_list' => Array('prefixes' => Array('u', 'u-ug_List'), 'format' => "#u_status# '#u_titlefield#' - !la_title_Groups! (#u-ug_recordcount#)"),
'tree_users' => Array('format' => '!la_section_overview!'),
),
'PermSection' => Array('main' => 'in-portal:user_list', 'email' => 'in-portal:user_email', 'custom' => 'in-portal:user_custom'),
'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('type' => 'int', 'not_null' => 1, 'default' => 0),
'Login' => Array('type' => 'string', 'unique'=>Array('Login'), 'default' => null,'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' => null),
'LastName' => Array('type' => 'string','default' => null),
'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}$/', 'sample_value' => 'email@domain.com', '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#'),
'Phone' => Array('type' => 'string','default' => null),
'Fax' => Array('type' => 'string', 'not_null' => 1, 'default' => ''),
'Street' => Array('type' => 'string', 'default' => null),
'Street2' => Array('type' => 'string', 'not_null' => '1', 'default' => ''),
'City' => Array('type' => 'string','default' => null),
'State' => Array('type' => 'string', 'formatter'=>'kOptionsFormatter',
'options' => Array(),
'option_key_field'=>'DestAbbr','option_title_field'=>'Translation',
'not_null' => '1','default' => ''),
'Zip' => Array('type' => 'string','default' => null),
'Country' => Array('type' => 'string', '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', 'default' => null, 'required'=>1),
'tz' => Array('type' => 'int','default' => 0),
'ip' => Array('type' => 'string','default' => null),
'IsBanned' => Array('type' => 'int','not_null' => 1, 'default' => 0),
'PassResetTime' => Array('type' => 'int','default' => null),
'PwResetConfirm' => Array('type' => 'string','default' => null),
'PwRequestTime' => Array('type' => 'int','default' => null),
'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' => 1800),
),
'VirtualFields' => Array(
'ValidateLogin' => Array('type'=>'string','default'=>''),
'SubscribeEmail' => Array('type'=>'string','default'=>''),
'PrimaryGroup' => Array('type' => 'string', 'default' => ''),
'Captcha' => Array('type' => 'string', 'default' => ''),
'RootPassword' => Array('type' => 'string', 'formatter' => 'kPasswordFormatter', 'encryption_method' => 'md5', 'verify_field' => 'VerifyRootPassword', 'skip_empty' => 1, 'default' => md5('') ),
),
'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
Property changes on: branches/unlabeled/unlabeled-1.38.2/core/units/users/users_config.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.38.2.1
\ No newline at end of property
+1.38.2.2
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.76.2/core/kernel/utility/unit_config_reader.php
===================================================================
--- branches/unlabeled/unlabeled-1.76.2/core/kernel/utility/unit_config_reader.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.76.2/core/kernel/utility/unit_config_reader.php (revision 8242)
@@ -1,753 +1,798 @@
<?php
class kUnitConfigReader extends kBase {
/**
* Configs readed
*
* @var Array
* @access private
*/
var $configData=Array();
var $configFiles=Array();
var $CacheExpired = false;
var $prefixFiles = array();
var $ProcessAllConfigs = false;
var $FinalStage = false;
var $StoreCache = false;
var $AfterConfigProcessed = array();
/**
* Scan kernel and user classes
* for available configs
*
* @access protected
*/
function Init($prefix,$special)
{
parent::Init($prefix,$special);
}
function CacheParsedData()
{
$event_manager =& $this->Application->recallObject('EventManager');
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
$config_vars = Array(
'SessionTimeout',
'SessionCookieName',
'SessionReferrerCheck',
'CookieSessions',
'UseCronForRegularEvent',
'User_GuestGroup',
'User_LoggedInGroup',
'SessionTimeout',
'UseModRewrite',
'UseOutputCompression',
'OutputCompressionLevel',
);
foreach ($config_vars as $var) {
$this->Application->ConfigValue($var);
}
$cache = Array(
'Factory.Files' => $this->Application->Factory->Files,
'Factory.realClasses' => $this->Application->Factory->realClasses,
'Factory.Dependencies' => $this->Application->Factory->Dependencies,
'ConfigReader.prefixFiles' => $this->prefixFiles,
'EventManager.buildEvents' => $event_manager->buildEvents,
'EventManager.beforeRegularEvents' => $event_manager->beforeRegularEvents,
'EventManager.afterRegularEvents' => $event_manager->afterRegularEvents,
'EventManager.beforeHooks' => $event_manager->beforeHooks,
'EventManager.afterHooks' => $event_manager->afterHooks,
'TagsAggregator.data' => $aggregator->_Array,
// the following caches should be reset based on admin interaction (adjusting config, enabling modules etc)
'Application.Caches.ConfigVariables' => $this->Application->Caches['ConfigVariables'],
'Application.ConfigCacheIds' => $this->Application->ConfigCacheIds,
'Application.ConfigHash' => $this->Application->ConfigHash,
'Application.ReplacementTemplates' => $this->Application->ReplacementTemplates,
'Application.ModuleInfo' => $this->Application->ModuleInfo,
);
$conn =& $this->Application->GetADODBConnection();
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("configs_parsed", '.$conn->qstr(serialize($cache)).', '.adodb_mktime().')');
$conn->Query('REPLACE '.TABLE_PREFIX.'Cache (VarName, Data, Cached) VALUES ("config_files", '.$conn->qstr(serialize($this->configFiles)).', '.adodb_mktime().')');
unset($this->configFiles);
}
function RestoreParsedData()
{
$conn =& $this->Application->GetADODBConnection();
$data = $conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "configs_parsed"');
if ($data && $data['Cached'] > 0 ) {
$cache = unserialize($data['Data']);
$this->Application->Factory->Files = $cache['Factory.Files'];
$this->Application->Factory->realClasses = $cache['Factory.realClasses'];
$this->Application->Factory->Dependencies = $cache['Factory.Dependencies'];
$this->prefixFiles = $cache['ConfigReader.prefixFiles'];
$event_manager =& $this->Application->recallObject('EventManager');
$event_manager->buildEvents = $cache['EventManager.buildEvents'];
$event_manager->beforeRegularEvents = $cache['EventManager.beforeRegularEvents'];
$event_manager->afterRegularEvents = $cache['EventManager.afterRegularEvents'];
$event_manager->beforeHooks = $cache['EventManager.beforeHooks'];
$event_manager->afterHooks = $cache['EventManager.afterHooks'];
$aggregator =& $this->Application->recallObject('TagsAggregator', 'kArray');
$aggregator->_Array = $cache['TagsAggregator.data'];
$this->Application->ConfigHash = $cache['Application.ConfigHash'];
$this->Application->Caches['ConfigVariables'] = $cache['Application.ConfigCacheIds'];
$this->Application->ConfigCacheIds = $cache['Application.ConfigCacheIds'];
$this->Application->ReplacementTemplates = $cache['Application.ReplacementTemplates'];
$this->Application->ModuleInfo = $cache['Application.ModuleInfo'];
return true;
}
else return false;
}
function ResetParsedData($include_sections = false)
{
$conn =& $this->Application->GetADODBConnection();
$conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "configs_parsed"');
if ($include_sections) {
$conn->Query('DELETE FROM '.TABLE_PREFIX.'Cache WHERE VarName = "sections_parsed"');
}
}
function scanModules($folderPath, $cache = true)
{
if (defined('IS_INSTALL') && IS_INSTALL && !defined('FORCE_CONFIG_CACHE')) {
// disable config caching during installation
$cache = false;
}
if ($cache) {
$restored = $this->RestoreParsedData();
if ($restored) return;
}
$this->ProcessAllConfigs = true;
$this->includeConfigFiles($folderPath, $cache);
$this->ParseConfigs();
// tell AfterConfigRead to store cache if neede
// can't store it here beacuse AfterConfigRead needs ability to change config data
$this->StoreCache = $cache;
}
function findConfigFiles($folderPath)
{
// if FULL_PATH = "/" ensure, that all "/" in $folderPath are not deleted
$reg_exp = '/^'.preg_quote(FULL_PATH, '/').'/';
$folderPath = preg_replace($reg_exp, '', $folderPath, 1); // this make sense, since $folderPath may NOT contain FULL_PATH
$fh = opendir(FULL_PATH.$folderPath);
while (($sub_folder = readdir($fh))) {
$full_path = FULL_PATH.$folderPath.'/'.$sub_folder;
if ($this->isDir($full_path)) {
//the following is to exclude OLD, not removed files when upgrading to 'core'
if (preg_match('/^\/kernel\/kernel4\//', $folderPath) || ($folderPath == '/kernel/units' && file_exists(FULL_PATH.$this->getConfigName('/core/units/'.$sub_folder)))) {
continue;
}
if (file_exists(FULL_PATH.$this->getConfigName($folderPath.'/'.$sub_folder))) {
$this->configFiles[] = $this->getConfigName($folderPath.'/'.$sub_folder);
}
$this->findConfigFiles($full_path);
// if (filemtime($full_path) > $cached) { }
}
}
}
function includeConfigFiles($folderPath, $cache = true)
{
$this->Application->refreshModuleInfo();
$conn =& $this->Application->GetADODBConnection();
$data = $conn->GetRow('SELECT Data, Cached FROM '.TABLE_PREFIX.'Cache WHERE VarName = "config_files"');
if ($cache && $data) {
$this->configFiles = unserialize($data['Data']);
shuffle($this->configFiles);
$files_cached = $data['Cached'];
}
else {
$this->findConfigFiles($folderPath); // search from base directory
}
foreach ($this->configFiles as $filename)
{
$prefix = $this->PreloadConfigFile($filename);
if (!$prefix) {
trigger_error('Prefix not defined in config file '.$filename, E_USER_ERROR);
}
}
}
/**
* Process all read config files - called ONLY when there is no cache!
*
*/
function ParseConfigs()
{
+ // 1. process normal configs and their dependencies
$prioritized_configs = array();
foreach ($this->configData as $prefix => $config) {
if (isset($config['ConfigPriority'])) {
$prioritized_configs[$prefix] = $config['ConfigPriority'];
continue;
}
$this->parseConfig($prefix);
}
foreach ($this->configData as $prefix => $config) {
$this->ProcessDependencies($prefix);
$this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = $this->postProcessConfig($prefix, 'Clones', 'prefix');
}
+ // 2. process prioritized configs and their dependencies
asort($prioritized_configs);
foreach ($prioritized_configs as $prefix => $priority) {
$this->parseConfig($prefix);
}
+
+ foreach ($prioritized_configs as $prefix => $priority) {
+ $this->ProcessDependencies($prefix);
+ }
}
function AfterConfigRead()
{
// if (!$this->ProcessAllConfigs) return ;
$this->FinalStage = true;
foreach ($this->configData as $prefix => $config) {
if (in_array($prefix, $this->AfterConfigProcessed)) continue;
$this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
$this->AfterConfigProcessed[] = $prefix;
}
- if ($this->StoreCache) $this->CacheParsedData();
+
+ if ($this->StoreCache) {
+ $this->processDynamicClones();
+ $this->CacheParsedData();
+ }
}
/**
+ * Re-reads all configs
+ *
+ */
+ function ReReadConfigs()
+ {
+ $this->includeConfigFiles(MODULES_PATH);
+ $this->ParseConfigs();
+ $this->AfterConfigRead();
+ $this->processDynamicClones();
+ }
+
+ /**
+ * Process clones, that were defined via OnAfterConfigRead event
+ *
+ */
+ function processDynamicClones()
+ {
+ $new_clones = Array();
+ foreach ($this->configData as $prefix => $config) {
+ $clones = $this->postProcessConfig($prefix, 'Clones', 'prefix');
+ if ($clones) {
+ $new_clones = array_merge($new_clones, $clones);
+ }
+ }
+
+ // call OnAfterConfigRead for cloned configs
+ $new_clones = array_unique($new_clones);
+ foreach ($new_clones as $prefix) {
+ if (in_array($prefix, $this->AfterConfigProcessed)) continue;
+ $this->Application->HandleEvent( new kEvent($prefix.':OnAfterConfigRead') );
+ $this->AfterConfigProcessed[] = $prefix;
+ }
+ }
+
+ /**
* Register nessasary classes
* This method should only process the data which is cached!
*
* @param string $prefix
* @access private
*/
function parseConfig($prefix)
{
$config =& $this->configData[$prefix];
$event_manager =& $this->Application->recallObject('EventManager');
$register_classes = getArrayValue($config,'RegisterClasses');
if (!$register_classes) $register_classes = Array();
$class_params=Array('ItemClass','ListClass','EventHandlerClass','TagProcessorClass');
foreach($class_params as $param_name)
{
if ( !(isset($config[$param_name]) ) ) continue;
$config[$param_name]['pseudo'] = $this->getPrefixByParamName($param_name,$prefix);
$register_classes[] = $config[$param_name];
}
foreach($register_classes as $class_info)
{
$require_classes = getArrayValue($class_info, 'require_classes');
if ($require_classes) {
if (!is_array($require_classes)) {
$require_classes = array($require_classes);
}
if (!isset($config['_Dependencies'][$class_info['class']])) {
$config['_Dependencies'][$class_info['class']] = array();
}
$config['_Dependencies'][$class_info['class']] = array_merge($config['_Dependencies'][$class_info['class']], $require_classes);
}
$this->Application->registerClass(
$class_info['class'],
$config['BasePath'].'/'.$class_info['file'],
$class_info['pseudo']/*,
getArrayValue($class_info, 'require_classes')*/
);
if (getArrayValue($class_info, 'build_event')) {
$event_manager->registerBuildEvent($class_info['pseudo'],$class_info['build_event']);
}
}
$regular_events = getArrayValue($config, 'RegularEvents');
if($regular_events)
{
foreach($regular_events as $short_name => $regular_event_info)
{
$event_manager->registerRegularEvent( $short_name, $config['Prefix'].':'.$regular_event_info['EventName'], $regular_event_info['RunInterval'], $regular_event_info['Type'] );
}
}
$hooks = getArrayValue($config, 'Hooks');
if (is_array($hooks) && count($hooks) > 0) {
foreach ($hooks as $hook) {
if (isset($config['ParentPrefix']) && $hook['HookToPrefix'] == $config['ParentPrefix']) {
trigger_error('Depricated Hook Usage [prefix: <b>'.$config['Prefix'].'</b>; do_prefix: <b>'.$hook['DoPrefix'].'</b>] use <b>#PARENT#</b> as <b>HookToPrefix</b> value, where HookToPrefix is same as ParentPrefix', E_USER_NOTICE);
}
if ($hook['HookToPrefix'] == '') {
$hook['HookToPrefix'] = $config['Prefix']; // new: set hooktoprefix to current prefix if not set
}
if (isset($config['ParentPrefix'])) {
// new: allow to set hook to parent prefix what ever it is
if ($hook['HookToPrefix'] == '#PARENT#') {
$hook['HookToPrefix'] = $config['ParentPrefix'];
}
if ($hook['DoPrefix'] == '#PARENT#') {
$hook['DoPrefix'] = $config['ParentPrefix'];
}
}
elseif ($hook['HookToPrefix'] == '#PARENT#' || $hook['DoPrefix'] == '#PARENT#') {
continue; // we need parent prefix but it's not set !
}
$do_prefix = $hook['DoPrefix'] == '' ? $config['Prefix'] : $hook['DoPrefix'];
if ( !is_array($hook['HookToEvent']) ) {
$hook_events = Array( $hook['HookToEvent'] );
}
else {
$hook_events = $hook['HookToEvent'];
}
foreach ($hook_events as $hook_event) {
$this->Application->registerHook($hook['HookToPrefix'], $hook['HookToSpecial'], $hook_event, $hook['Mode'], $do_prefix, $hook['DoSpecial'], $hook['DoEvent'], $hook['Conditional']);
}
}
}
if ( is_array(getArrayValue($config, 'AggregateTags')) ) {
foreach ($config['AggregateTags'] as $aggregate_tag) {
if (isset($config['ParentPrefix'])) {
if ($aggregate_tag['AggregateTo'] == $config['ParentPrefix']) {
trigger_error('Depricated Aggregate Tag Usage [prefix: <b>'.$config['Prefix'].'</b>; AggregateTo: <b>'.$aggregate_tag['AggregateTo'].'</b>] use <b>#PARENT#</b> as <b>AggregateTo</b> value, where AggregateTo is same as ParentPrefix', E_USER_NOTICE);
}
if ($aggregate_tag['AggregateTo'] == '#PARENT#') {
$aggregate_tag['AggregateTo'] = $config['ParentPrefix'];
}
}
$aggregate_tag['LocalPrefix'] = $config['Prefix'];
$this->Application->registerAggregateTag($aggregate_tag);
}
}
if (isset($config['ReplacementTemplates']) && $config['ReplacementTemplates']) {
// replacement templates defined in this config
$this->Application->ReplacementTemplates = array_merge_recursive2($this->Application->ReplacementTemplates, $config['ReplacementTemplates']);
}
if ( $this->Application->isDebugMode(false) && constOn('DBG_VALIDATE_CONFIGS') && isset($config['TableName']) ) {
$this->ValidateConfig($prefix);
}
}
function ValidateConfig($prefix)
{
global $debugger;
$config =& $this->configData[$prefix];
$tablename = $config['TableName'];
$float_types = Array ('float', 'double', 'numeric');
$conn =& $this->Application->GetADODBConnection();
$table_found = $conn->Query('SHOW TABLES LIKE "'.$tablename.'"');
if (!$table_found) {
// config present, but table missing, strange
$debugger->appendHTML("<b class='debug_error'>Config Warning: </b>Table <strong>$tablename</strong> missing, but prefix <b>".$config['Prefix']."</b> requires it!");
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
return ;
}
$res = $conn->Query('DESCRIBE '.$tablename);
$config_link = $debugger->getFileLink(FULL_PATH.$this->prefixFiles[$config['Prefix']], 1, $config['Prefix']);
$error_messages = Array (
'field_not_found' => 'Field <strong>%s</strong> exists in the database, but <strong>is not defined</strong> in config',
'default_missing' => 'Default value for field <strong>%s</strong> not set in config',
'not_null_error1' => 'Field <strong>%s</strong> is NOT NULL in the database, but is not configured as not_null or required',
'not_null_error2' => 'Field <strong>%s</strong> is described as NOT NULL in config, but <strong>does not have DEFAULT value</strong>',
'not_null_error3' => 'Field <strong>%s</strong> is described as <strong>NOT NULL in config</strong>, but is <strong>NULL in db</strong>',
'invalid_default' => '<strong>Default value</strong> for field %s<strong>%s</strong> not sync. to db (in config = %s, in db = %s)',
'type_missing' => '<strong>Type definition</strong> for field <strong>%s</strong> missing in config',
);
$config_errors = Array ();
$tablename = preg_replace('/^'.preg_quote(TABLE_PREFIX, '/').'(.*)/', '\\1', $tablename); // remove table prefix
foreach ($res as $field) {
$f_name = $field['Field'];
if (getArrayValue($config, 'Fields')) {
if (preg_match('/l[\d]+_[\w]/', $f_name)) {
// skip multilingual fields
continue;
}
if (!array_key_exists ($f_name, $config['Fields'])) {
$config_errors[] = sprintf($error_messages['field_not_found'], $f_name);
}
else {
if (is_numeric($field['Default'])) {
$field['Default'] = preg_match('/[\.,]/', $field['Default']) ? (float)$field['Default'] : (int)$field['Default'];
}
$options = $config['Fields'][$f_name];
$default_missing = false;
if (!array_key_exists('default', $options)) {
$config_errors[] = sprintf($error_messages['default_missing'], $f_name);
$default_missing = true;
}
if ($field['Null'] != 'YES') {
// field is NOT NULL in database (MySQL5 for null returns "NO", but MySQL4 returns "")
if ( $f_name != $config['IDField'] && !isset($options['not_null']) && !isset($options['required']) ) {
$config_errors[] = sprintf($error_messages['not_null_error1'], $f_name);
}
if (isset($options['not_null']) && $options['not_null'] && !isset($options['default']) ) {
$config_errors[] = sprintf($error_messages['not_null_error2'], $f_name);
}
}
else {
if (isset($options['not_null']) && $options['not_null']) {
$config_errors[] = sprintf($error_messages['not_null_error3'], $f_name);
}
}
if (!array_key_exists('type', $options)) {
$config_errors[] = sprintf($error_messages['type_missing'], $f_name);
}
if (!$default_missing) {
if ($f_name == $config['IDField'] && $options['type'] != 'string' && $options['default'] !== 0) {
$config_errors[] = sprintf($error_messages['invalid_default'], '<span class="debug_error">IDField</span> ', $f_name, $this->varDump($options['default']), $this->varDump($field['Default']));
}
else if ($options['default'] != '#NOW#' && $field['Default'] !== $options['default'] && !in_array($options['type'], $float_types)) {
$config_errors[] = sprintf($error_messages['invalid_default'], '', $f_name, $this->varDump($options['default']), $this->varDump($field['Default']));
}
}
}
}
}
if ($config_errors) {
$error_prefix = '<strong class="debug_error">Config Error'.(count($config_errors) > 1 ? 's' : '').': </strong> for prefix <strong>'.$config_link.'</strong> ('.$tablename.') in unit config:<br />';
$config_errors = $error_prefix.'&nbsp;&nbsp;&nbsp;'.implode('<br />&nbsp;&nbsp;&nbsp;', $config_errors);
$debugger->appendHTML($config_errors);
safeDefine('DBG_RAISE_ON_WARNINGS', 1);
}
}
function varDump($value)
{
return '<strong>'.var_export($value, true).'</strong> of '.gettype($value);
}
function ProcessDependencies($prefix)
{
$config =& $this->configData[$prefix];
$deps = getArrayValue($config, '_Dependencies');
if (!$deps) return ;
foreach ($deps as $real_class => $requires) {
foreach ($requires as $class) {
$this->Application->registerDependency($real_class, $class);
}
}
unset($config['_Dependencies']);
}
function postProcessConfig($prefix, $config_key, $dst_prefix_var)
{
$main_config =& $this->configData[$prefix];
- $sub_configs = getArrayValue($main_config, $config_key);
+ $sub_configs = isset($main_config[$config_key]) && $main_config[$config_key] ? $main_config[$config_key] : false; // getArrayValue($main_config, $config_key);
if (!$sub_configs) {
return array();
}
unset($main_config[$config_key]);
$processed = array();
foreach ($sub_configs as $sub_prefix => $sub_config) {
if ($config_key == 'AggregateConfigs' && !isset($this->configData[$sub_prefix])) {
$this->loadConfig($sub_prefix);
}
$sub_config['Prefix'] = $sub_prefix;
$this->configData[$sub_prefix] = array_merge_recursive2($this->configData[$$dst_prefix_var], $sub_config);
// when merging empty array to non-empty results non-empty array, but empty is required
foreach ($sub_config as $sub_key => $sub_value) {
if (!$sub_value) {
unset($this->configData[$sub_prefix][$sub_key]);
}
}
if ($config_key == 'Clones') {
$this->prefixFiles[$sub_prefix] = $this->prefixFiles[$prefix];
}
$this->postProcessConfig($sub_prefix, $config_key, $dst_prefix_var);
if ($config_key == 'AggregateConfigs') {
$processed = array_merge($this->postProcessConfig($sub_prefix, 'Clones', 'prefix'), $processed);
}
elseif ($this->ProcessAllConfigs) {
$this->parseConfig($sub_prefix);
}
array_push($processed, $sub_prefix);
}
if (!$prefix) {
// configs, that used only for cloning & not used ifself
unset($this->configData[$prefix]);
}
return array_unique($processed);
}
function PreloadConfigFile($filename)
{
$config_found = file_exists(FULL_PATH.$filename) && $this->configAllowed($filename);
if( defined('DEBUG_MODE') && DEBUG_MODE && constOn('DBG_PROFILE_INCLUDES') )
{
if ( in_array($filename, get_required_files()) ) return;
global $debugger;
if($config_found) {
$file = FULL_PATH.$filename;
$debugger->ProfileStart('inc_'.crc32($file), $file);
include_once($file);
$debugger->ProfileFinish('inc_'.crc32($file));
$debugger->profilerAddTotal('includes', 'inc_'.crc32($file));
}
}
else
{
if ($config_found) include_once(FULL_PATH.$filename);
}
if ($config_found) {
if (isset($config) && $config) {
// config file is included for 1st time -> save it's content for future processing
$prefix = isset($config['Prefix']) ? $config['Prefix'] : '';
preg_match('/\/(.*)\//U', $filename, $rets);
$config['ModuleFolder'] = $rets[1];
$config['BasePath'] = dirname(FULL_PATH.$filename);
if (isset($config['AdminTemplatePath'])) {
// append template base folder for admin templates path of this prefix
$module_templates = $rets[1] == 'core' ? 'in-portal/' : $rets[1].'/';
$config['AdminTemplatePath'] = $module_templates.$config['AdminTemplatePath'];
}
$this->configData[$prefix] = $config;
$this->prefixFiles[$prefix] = $filename;
return $prefix;
}
elseif ($prefix = array_search($filename, $this->prefixFiles)) {
// attempt is made to include config file twice or more, but include_once prevents that,
// but file exists on hdd, then it is already saved to all required arrays, just return it's prefix
return $prefix;
}
}
return 'dummy';
}
function loadConfig($prefix)
{
if (!isset($this->prefixFiles[$prefix])) {
if ($this->Application->isDebugMode()) $this->Application->Debugger->appendTrace();
trigger_error('Configuration file for prefix <b>'.$prefix.'</b> is unknown', E_USER_ERROR);
return ;
}
$file = $this->prefixFiles[$prefix];
$prefix = $this->PreloadConfigFile($file);
$clones = $this->postProcessConfig($prefix, 'AggregateConfigs', 'sub_prefix');
$clones = array_merge($this->postProcessConfig($prefix, 'Clones', 'prefix'), $clones);
if ($this->FinalStage) {
array_unshift($clones, $prefix);
$clones = array_unique($clones);
foreach ($clones as $a_prefix) {
$this->Application->HandleEvent( new kEvent($a_prefix.':OnAfterConfigRead') );
}
}
}
/**
* Reads unit (specified by $prefix)
* option specified by $option
*
* @param string $prefix
* @param string $name
* @param mixed $default
* @return string
* @access public
*/
function getUnitOption($prefix, $name, $default = false)
{
if (preg_match('/(.*)\.(.*)/', $prefix, $rets)) {
if (!isset($this->configData[$rets[1]])) {
$this->loadConfig($rets[1]);
}
$ret = isset($this->configData[$rets[1]][$name][$rets[2]]) ? $this->configData[$rets[1]][$name][$rets[2]] : false;
// $ret = getArrayValue($this->configData, $rets[1], $name, $rets[2]);
}
else {
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
$ret = isset($this->configData[$prefix][$name]) ? $this->configData[$prefix][$name] : false;
// $ret = getArrayValue($this->configData, $prefix, $name);
}
return $ret === false ? $default : $ret;
}
/**
* Read all unit with $prefix options
*
* @param string $prefix
* @return Array
* @access public
*/
function getUnitOptions($prefix)
{
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
return $this->configData[$prefix];
}
/**
* Set's new unit option value
*
* @param string $prefix
* @param string $name
* @param string $value
* @access public
*/
function setUnitOption($prefix, $name, $value)
{
if (preg_match('/(.*)\.(.*)/', $prefix, $rets)) {
if (!isset($this->configData[$rets[1]])) {
$this->loadConfig($rets[1]);
}
$this->configData[$rets[1]][$name][$rets[2]] = $value;
}
else {
if (!isset($this->configData[$prefix])) {
$this->loadConfig($prefix);
}
$this->configData[$prefix][$name] = $value;
}
}
function getPrefixByParamName($paramName,$prefix)
{
$pseudo_class_map=Array(
'ItemClass'=>'%s',
'ListClass'=>'%s_List',
'EventHandlerClass'=>'%s_EventHandler',
'TagProcessorClass'=>'%s_TagProcessor'
);
return sprintf($pseudo_class_map[$paramName],$prefix);
}
/**
* Get's config file name based
* on folder name supplied
*
* @param string $folderPath
* @return string
* @access private
*/
function getConfigName($folderPath)
{
return $folderPath.'/'.basename($folderPath).'_config.php';
}
/**
* is_dir ajustment to work with
* directory listings too
*
* @param string $folderPath
* @return bool
* @access private
*/
function isDir($folderPath)
{
$base_name = basename($folderPath);
$ret = !( $base_name == '.' || $base_name == '..' );
return $ret && is_dir($folderPath);
}
/**
* Checks if config file is allowed for includion (if module of config is installed)
*
* @param string $config_path relative path from in-portal directory
*/
function configAllowed($config_path)
{
if (defined('IS_INSTALL') && IS_INSTALL) {
// at installation start no modules in db and kernel configs could not be read
return true;
}
if (preg_match('#/plugins/|/core#', $config_path)) {
return true;
}
$module_found = false;
if (!$this->Application->ModuleInfo) return false;
foreach($this->Application->ModuleInfo as $module_name => $module_info)
{
$module_path = '/'.$module_info['Path'];
if (preg_match('/^'.preg_quote($module_path, '/').'/', $config_path)) {
// if (substr($config_path, 0, strlen($module_path)) == $module_path) {
// config file path starts with module folder path
$module_found = true;
break;
}
}
return $module_found;
}
/**
* Returns true if config exists and is allowed for reading
*
* @param string $prefix
* @return bool
*/
function prefixRegistred($prefix)
{
return isset($this->prefixFiles[$prefix]) ? true : false;
}
function iterateConfigs($callback_function, $params)
{
$this->includeConfigFiles(MODULES_PATH); //make sure to re-read all configs
$this->AfterConfigRead();
foreach ($this->configData as $prefix => $config_data) {
$callback_function[0]->$callback_function[1]($prefix, $config_data, $params);
}
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.76.2/core/kernel/utility/unit_config_reader.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.76.2.2
\ No newline at end of property
+1.76.2.3
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.60.2/core/units/categories/categories_config.php
===================================================================
--- branches/unlabeled/unlabeled-1.60.2/core/units/categories/categories_config.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.60.2/core/units/categories/categories_config.php (revision 8242)
@@ -1,277 +1,291 @@
<?php
$config = Array(
'Prefix' => 'c',
'ItemClass' => Array('class'=>'CategoriesItem','file'=>'categories_item.php','build_event'=>'OnItemBuild'),
'ListClass' => Array('class'=>'kDBList','file'=>'','build_event'=>'OnListBuild'),
'EventHandlerClass' => Array('class'=>'CategoriesEventHandler','file'=>'categories_event_handler.php','build_event'=>'OnBuild'),
'TagProcessorClass' => Array('class'=>'CategoriesTagProcessor','file'=>'categories_tag_processor.php','build_event'=>'OnBuild'),
'RegisterClasses' => Array(
Array('pseudo' => 'kPermCacheUpdater','class' => 'kPermCacheUpdater', 'file' => 'cache_updater.php','build_event'=>''),
),
+ 'ConfigPriority' => 0,
+ 'Hooks' => Array (
+ Array (
+ 'Mode' => hBEFORE,
+ 'Conditional' => false,
+ 'HookToPrefix' => '',
+ 'HookToSpecial' => '*',
+ 'HookToEvent' => Array('OnAfterConfigRead'),
+ 'DoPrefix' => 'cdata',
+ 'DoSpecial' => '*',
+ 'DoEvent' => 'OnDefineCustomFields',
+ ),
+ ),
+
'AutoLoad' => true,
'CatalogItem' => true,
'AdminTemplatePath' => 'categories',
'AdminTemplatePrefix' => 'categories_',
'QueryString' => Array(
1 => 'id',
2 => 'page',
3 => 'event',
4 => 'mode',
),
'AggregateTags' => Array(
Array(
'AggregateTo' => 'm',
'AggregatedTagName' => 'CategoryLink',
'LocalTagName' => 'CategoryLink',
),
),
'IDField' => 'CategoryId',
'StatusField' => Array('Status'),
'TitleField' => 'Name', // field, used in bluebar when editing existing item
'TitlePhrase' => 'la_Text_Category',
'ItemType' => 1, // used for custom fields only
'StatisticsInfo' => Array(
'pending' => Array(
'icon' => 'icon16_cat_pending.gif',
'label' => 'la_tab_Categories',
'js_url' => '#url#',
'url' => Array('t' => 'in-portal/advanced_view', 'SetTab' => 'c', 'pass' => 'm,c.showall', 'c.showall_event' => 'OnSetFilterPattern', 'c.showall_filters' => 'show_active=0,show_pending=1,show_disabled=0,show_new=1,show_pick=1'),
'status' => STATUS_PENDING,
),
),
'TableName' => TABLE_PREFIX.'Category',
'ViewMenuPhrase' => 'la_text_Categories',
'TitlePresets' => Array(
'default' => Array( 'new_status_labels' => Array('c' => '!la_title_Adding_Category!'),
'edit_status_labels' => Array('c' => '!la_title_Editing_Category!'),
'new_titlefield' => Array('c' => ''),
),
'category_list' => Array('prefixes' => Array('c_List'), 'format' => "!la_title_Categories! (#c_recordcount#)"),
'catalog' => Array('prefixes' => Array('c_List'), 'format' => "!la_title_Categories! (<span id='c_item_count'>#c_recordcount#</span>)"),
'advanced_view' => Array('prefixes' => Array('c_List'), 'format' => "!la_title_AdvancedView!"),
'categories_edit' => Array('prefixes' => Array('c'), 'format' => "#c_status# '#c_titlefield#' - !la_title_General!"),
'categories_properties' => Array('prefixes' => Array('c'), 'format' => "#c_status# '#c_titlefield#' - !la_title_Properties!"),
'categories_relations' => Array('prefixes' => Array('c'), 'format' => "#c_status# '#c_titlefield#' - !la_title_Relations!"),
'categories_images' => Array('prefixes' => Array('c'), 'format' => "#c_status# '#c_titlefield#' - !la_title_Images!"),
'categories_permissions'=> Array('prefixes' => Array('c', 'g_List'), 'format' => "#c_status# '#c_titlefield#' - !la_title_Permissions!"),
'categories_custom' => Array('prefixes' => Array('c'), 'format' => "#c_status# '#c_titlefield#' - !la_title_Custom!"),
'categories_update' => Array('prefixes' => Array(), 'format' => "!la_title_UpdatingCategories!"),
'images_edit' => Array( 'prefixes' => Array('c', 'c-img'),
'new_status_labels' => Array('c-img'=>'!la_title_Adding_Image!'),
'edit_status_labels' => Array('c-img'=>'!la_title_Editing_Image!'),
'new_titlefield' => Array('c-img'=>''),
'format' => "#c_status# '#c_titlefield#' - #c-img_status# '#c-img_titlefield#'",
),
'relations_edit' => Array( 'prefixes' => Array('c', 'c-rel'),
'new_status_labels' => Array('c-rel'=>"!la_title_Adding_Relationship! '!la_title_New_Relationship!'"),
'edit_status_labels' => Array('c-rel'=>'!la_title_Editing_Relationship!'),
'format' => "#c_status# '#c_titlefield#' - #c-rel_status#",
),
'tree_site' => Array('format' => '!la_selecting_categories!'),
),
'PermItemPrefix' => 'CATEGORY',
'PermSection' => Array('main' => 'CATEGORY:in-portal:categories', /*'search' => 'in-portal:configuration_search',*/ 'email' => 'in-portal:configuration_email', 'custom' => 'in-portal:configuration_custom'),
/* 'Sections' => Array(
// "Structure & Data" section
'in-portal:site' => Array(
'parent' => 'in-portal:root',
'icon' => 'struct',
'label' => 'la_tab_Site_Structure',
'url' => Array('t' => 'sections_list', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array('view'),
'priority' => 1,
'type' => stTREE,
),
'in-portal:browse' => Array(
'parent' => 'in-portal:site',
'icon' => 'catalog',
'label' => 'la_tab_Browse',
'url' => Array('t' => 'in-portal/catalog', 'pass' => 'm'),
'late_load' => Array('t' => 'in-portal/xml/tree_categories', 'pass' => 'm', 'm_cat_id' => 0),
'onclick' => 'checkCatalog(0)',
'permissions' => Array('view'),
'priority' => 0.1,
'type' => stTREE,
),
'in-portal:advanced_view' => Array(
'parent' => 'in-portal:site',
'icon' => 'advanced_view',
'label' => 'la_tab_AdvancedView',
'url' => Array('t' => 'in-portal/advanced_view', 'pass' => 'm'),
'permissions' => Array('view'),
'priority' => 0.2,
'type' => stTREE,
),
'in-portal:reviews' => Array(
'parent' => 'in-portal:site',
'icon' => 'reviews',
'label' => 'la_tab_Reviews',
'url' => Array('index_file' => 'reviews.php', 'pass' => 'm'),
'permissions' => Array('view'),
'priority' => 3,
'type' => stTREE,
),
'in-portal:configure_categories' => Array(
'parent' => 'in-portal:site',
'icon' => 'cat_settings',
'label' => 'la_tab_Settings',
'url' => Array('t' => 'config/config_universal', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array('view', 'edit'),
'priority' => 4,
'type' => stTREE,
),
'in-portal:configuration_search' => Array(
'parent' => 'in-portal:site',
'icon' => 'settings_search',
'label' => 'la_tab_ConfigSearch',
'url' => Array('t' => 'in-portal/config/config_search', 'module_key' => 'category', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array('view', 'edit'),
'priority' => 5,
'type' => stTREE,
),
'in-portal:configuration_email' => Array(
'parent' => 'in-portal:site',
'icon' => 'settings_email',
'label' => 'la_tab_ConfigE-mail',
'url' => Array('t' => 'in-portal/config/config_email', 'module' => 'In-Portal:Category', 'pass_section' => true, 'pass' => 'm'),
'permissions' => Array('view', 'edit'),
'priority' => 6,
'type' => stTREE,
),
'in-portal:configuration_custom' => Array(
'parent' => 'in-portal:site',
'icon' => 'settings_custom',
'label' => 'la_tab_ConfigCustom',
'url' => Array('t' => 'in-portal/custom_fields/custom_fields_list', 'cf_type' => 1, 'pass_section' => true, 'pass' => 'm,cf'),
'permissions' => Array('view', 'add', 'edit', 'delete'),
'priority' => 7,
'type' => stTREE,
),
),*/
'FilterMenu' => Array(
'Groups' => Array(
Array('mode' => 'AND', 'filters' => Array('show_active','show_pending','show_disabled'), 'type' => WHERE_FILTER),
Array('mode' => 'AND', 'filters' => Array('show_new'), 'type' => HAVING_FILTER),
Array('mode' => 'AND', 'filters' => Array('show_pick'), 'type' => WHERE_FILTER),
),
'Filters' => Array(
'show_active' => Array('label' =>'la_Active', 'on_sql' => '', 'off_sql' => 'Status != 1' ),
'show_pending' => Array('label' => 'la_Pending', 'on_sql' => '', 'off_sql' => 'Status != 2' ),
'show_disabled' => Array('label' => 'la_Disabled', 'on_sql' => '', 'off_sql' => 'Status != 0' ),
's1' => Array(),
'show_new' => Array('label' => 'la_Text_New', 'on_sql' => '', 'off_sql' => '`IsNew` != 1' ),
'show_pick' => Array('label' => 'la_prompt_EditorsPick', 'on_sql' => '', 'off_sql' => '`EditorsPick` != 1' ),
)
),
'ListSQLs' => Array( ''=> ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'PermCache ON '.TABLE_PREFIX.'PermCache.CategoryId = %1$s.CategoryId
LEFT JOIN '.TABLE_PREFIX.'%3$sCategoryCustomData cust ON %1$s.ResourceId = cust.ResourceId'),
'ItemSQLs' => Array( ''=> ' SELECT %1$s.* %2$s
FROM %1$s
LEFT JOIN '.TABLE_PREFIX.'PermCache ON '.TABLE_PREFIX.'PermCache.CategoryId = %1$s.CategoryId
LEFT JOIN '.TABLE_PREFIX.'%3$sCategoryCustomData cust ON %1$s.ResourceId = cust.ResourceId'),
'SubItems' => Array('c-rel', 'c-img', 'c-cdata', 'c-perm'),
'ListSortings' => Array(
'' => Array(
'ForcedSorting' => Array("CurrentSort" => 'asc', 'Priority' => 'desc', 'Name' => 'asc'),
'Sorting' => Array('Name' => 'asc'),
)
),
'CalculatedFields' => Array(
'' => Array(
'CurrentSort' => "REPLACE(ParentPath, CONCAT('|', ".'%1$s'.".CategoryId, '|'), '')",
)
),
'Fields' => Array
(
'CategoryId' => Array('type' => 'int','not_null' => 1,'default' => 0),
'Type' => Array('type' => 'int','not_null' => 1,'default' => 0),
'ParentId' => Array('type' => 'int','not_null' => 1,'default' => 0),
'Name' => Array('type' => 'string', 'formatter' => 'kMultiLanguage', 'not_null' => 1, 'required' => 1, 'default' => ''),
'Filename' => Array('type' => 'string', 'not_null' => 1, 'default' => ''),
'AutomaticFilename' => Array('type' => 'int', 'not_null' => 1, 'default' => 1),
'Description' => Array('type' => 'string', 'formatter' => 'kMultiLanguage', 'required' => 1, 'default' => null),
'CreatedOn' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'default'=>'#NOW#', 'required' => 1, 'not_null' => 1),
'EditorsPick' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'Status' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (1 => 'la_Active', 2 => 'la_Pending', 0 => 'la_Disabled' ), 'use_phrases' => 1, 'not_null' => 1,'default' => 2),
'Priority' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
'MetaKeywords' => Array('type' => 'string', 'default' => null),
'CachedDescendantCatsQty' => Array('type' => 'int', 'default' => 0),
'CachedNavbar' => Array('type' => 'string', 'formatter' => 'kMultiLanguage', 'default' => null),
'CreatedById' => Array('type' => 'int', 'formatter' => 'kLEFTFormatter', 'options' => Array(-1 => 'root', -2 => 'Guest'),'left_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'PortalUser WHERE `%s` = \'%s\'', 'left_key_field' => 'PortalUserId', 'left_title_field' => 'Login', 'not_null' => 1,'default' => 0),
'ResourceId' => Array('type' => 'int', 'default' => null),
'ParentPath' => Array('type' => 'string', 'default' => null),
'NamedParentPath' => Array('type' => 'string', 'default' => null),
'MetaDescription' => Array('type' => 'string', 'default' => null),
'HotItem' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (2 => 'la_Auto', 1 => 'la_Always', 0 => 'la_Never'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 2),
'NewItem' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (2 => 'la_Auto', 1 => 'la_Always', 0 => 'la_Never'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 2),
'PopItem' => Array('type' => 'int', 'formatter' => 'kOptionsFormatter', 'options' => Array (2 => 'la_Auto', 1 => 'la_Always', 0 => 'la_Never'), 'use_phrases' => 1, 'not_null' => 1, 'default' => 2),
'Modified' => Array('type' => 'int', 'formatter' => 'kDateFormatter', 'not_null' => 1,'default' => '#NOW#'),
'ModifiedById' => Array('type' => 'int', 'formatter' => 'kLEFTFormatter', 'options' => Array(-1 => 'root', -2 => 'Guest'),'left_sql'=>'SELECT %s FROM '.TABLE_PREFIX.'PortalUser WHERE `%s` = \'%s\'', 'left_key_field' => 'PortalUserId', 'left_title_field' => 'Login', 'not_null' => 1,'default' => 0),
'CategoryTemplate' => Array('type' => 'string', 'not_null' => 1, 'default' => ''),
'CachedCategoryTemplate' => Array('type' => 'string', 'not_null' => 1, 'default' => ''),
),
'VirtualFields' => Array(
'CurrentSort' => Array('type' => 'string', 'default' => ''),
'IsNew' => Array('type' => 'int', 'default' => 0),
),
'Grids' => Array(
'Default' => Array(
'Icons' => Array('default'=>'icon16_cat.gif'),
'Fields' => Array(
'Name' => Array('title' => 'la_col_Name', 'data_block' => 'category_td'),
'Description' => Array('title' => 'la_col_Description'),
'CreatedOn_formatted' => Array('title' => 'la_col_CreatedOn', 'sort_field' => 'CreatedOn'),
),
),
),
'ConfigMapping' => Array(
'PerPage' => 'Perpage_Category',
'DefaultSorting1Field' => 'Category_Sortfield',
'DefaultSorting2Field' => 'Category_Sortfield2',
'DefaultSorting1Dir' => 'Category_Sortorder',
'DefaultSorting2Dir' => 'Category_Sortorder2',
),
);
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.60.2/core/units/categories/categories_config.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.60
\ No newline at end of property
+1.60.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.85.2/core/kernel/db/db_event_handler.php
===================================================================
--- branches/unlabeled/unlabeled-1.85.2/core/kernel/db/db_event_handler.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.85.2/core/kernel/db/db_event_handler.php (revision 8242)
@@ -1,2156 +1,2069 @@
<?php
define('EH_CUSTOM_PROCESSING_BEFORE',1);
define('EH_CUSTOM_PROCESSING_AFTER',2);
/**
* Note:
* 1. When adressing variables from submit containing
* Prefix_Special as part of their name use
* $event->getPrefixSpecial(true) instead of
* $event->Prefix_Special as usual. This is due PHP
* is converting "." symbols in variable names during
* submit info "_". $event->getPrefixSpecial optional
* 1st parameter returns correct corrent Prefix_Special
* for variables beeing submitted such way (e.g. variable
* name that will be converted by PHP: "users.read_only_id"
* will be submitted as "users_read_only_id".
*
* 2. When using $this->Application-LinkVar on variables submitted
* from form which contain $Prefix_Special then note 1st item. Example:
* LinkVar($event->getPrefixSpecial(true).'_varname',$event->Prefix_Special.'_varname')
*
*/
/**
* EventHandler that is used to process
* any database related events
*
*/
class kDBEventHandler extends kEventHandler {
/**
* Description
*
* @var kDBConnection
* @access public
*/
var $Conn;
/**
* Adds ability to address db connection
*
* @return kDBEventHandler
* @access public
*/
function kDBEventHandler()
{
parent::kBase();
$this->Conn =& $this->Application->GetADODBConnection();
}
/**
* Checks permissions of user
*
* @param kEvent $event
*/
function CheckPermission(&$event)
{
if (!$this->Application->IsAdmin()) {
$allow_events = Array('OnSearch', 'OnSearchReset', 'OnNew');
if (in_array($event->Name, $allow_events)) {
// allow search on front
return true;
}
}
$section = $event->getSection();
if (!preg_match('/^CATEGORY:(.*)/', $section)) {
// only if not category item events
if ((substr($event->Name, 0, 9) == 'OnPreSave') || ($event->Name == 'OnSave')) {
if ($this->isNewItemCreate($event)) {
return $this->Application->CheckPermission($section.'.add', 1);
}
else {
return $this->Application->CheckPermission($section.'.add', 1) || $this->Application->CheckPermission($section.'.edit', 1);
}
}
}
if ($event->Name == 'OnPreCreate') {
// save category_id before item create (for item category selector not to destroy permission checking category)
$this->Application->LinkVar('m_cat_id');
}
return parent::CheckPermission($event);
}
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnLoad' => Array('self' => 'view', 'subitem' => 'view'),
'OnNew' => Array('self' => 'add', 'subitem' => 'add|edit'),
'OnCreate' => Array('self' => 'add', 'subitem' => 'add|edit'),
'OnUpdate' => Array('self' => 'edit', 'subitem' => 'add|edit'),
'OnSetPrimary' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnDelete' => Array('self' => 'delete', 'subitem' => 'add|edit'),
'OnMassDelete' => Array('self' => 'delete', 'subitem' => 'add|edit'),
'OnMassClone' => Array('self' => 'add', 'subitem' => 'add|edit'),
'OnCut' => array('self'=>'edit', 'subitem' => 'edit'),
'OnCopy' => array('self'=>'edit', 'subitem' => 'edit'),
'OnPaste' => array('self'=>'edit', 'subitem' => 'edit'),
'OnSelectItems' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnProcessSelected' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnSelectUser' => Array('self' => 'add|edit', 'subitem' => 'add|edit'),
'OnMassApprove' => Array('self' => 'advanced:approve|edit', 'subitem' => 'advanced:approve|add|edit'),
'OnMassDecline' => Array('self' => 'advanced:decline|edit', 'subitem' => 'advanced:decline|add|edit'),
'OnMassMoveUp' => Array('self' => 'advanced:move_up|edit', 'subitem' => 'advanced:move_up|add|edit'),
'OnMassMoveDown' => Array('self' => 'advanced:move_down|edit', 'subitem' => 'advanced:move_down|add|edit'),
'OnPreCreate' => Array('self' => 'add|add.pending', 'subitem' => 'edit|edit.pending'),
'OnEdit' => Array('self' => 'edit|edit.pending', 'subitem' => 'edit|edit.pending'),
'OnExport' => Array('self' => 'view|advanced:export'),
'OnExportBegin' => Array('self' => 'view|advanced:export'),
'OnExportProgress' => Array('self' => 'view|advanced:export'),
// theese event do not harm, but just in case check them too :)
'OnCancelEdit' => Array('self' => true, 'subitem' => true),
'OnCancel' => Array('self' => true, 'subitem' => true),
'OnReset' => Array('self' => true, 'subitem' => true),
'OnSetSorting' => Array('self' => true, 'subitem' => true),
'OnSetSortingDirect' => Array('self' => true, 'subitem' => true),
'OnSetFilter' => Array('self' => true, 'subitem' => true),
'OnApplyFilters' => Array('self' => true, 'subitem' => true),
'OnRemoveFilters' => Array('self' => true, 'subitem' => true),
'OnSetFilterPattern' => Array('self' => true, 'subitem' => true),
'OnSetPerPage' => Array('self' => true, 'subitem' => true),
'OnSearch' => Array('self' => true, 'subitem' => true),
'OnSearchReset' => Array('self' => true, 'subitem' => true),
'OnGoBack' => Array('self' => true, 'subitem' => true),
// it checks permission itself since flash uploader does not send cookies
'OnUploadFile' => Array('self'=>true, 'subitem'=>true),
'OnViewFile' => Array('self'=>true, 'subitem'=>true),
);
$this->permMapping = array_merge($this->permMapping, $permissions);
}
function mapEvents()
{
$events_map = Array(
'OnRemoveFilters' => 'FilterAction',
'OnApplyFilters' => 'FilterAction',
'OnMassApprove'=>'iterateItems',
'OnMassDecline'=>'iterateItems',
'OnMassMoveUp'=>'iterateItems',
'OnMassMoveDown'=>'iterateItems',
);
$this->eventMethods = array_merge($this->eventMethods, $events_map);
}
/**
* Returns ID of current item to be edited
* by checking ID passed in get/post as prefix_id
* or by looking at first from selected ids, stored.
* Returned id is also stored in Session in case
* it was explicitly passed as get/post
*
* @param kEvent $event
* @return int
*/
function getPassedID(&$event)
{
if ($event->getEventParam('raise_warnings') === false) {
$event->setEventParam('raise_warnings', 1);
}
// 1. get id from post (used in admin)
$ret = $this->Application->GetVar($event->getPrefixSpecial(true).'_id');
if($ret) return $ret;
// 2. get id from env (used in front)
$ret = $this->Application->GetVar($event->getPrefixSpecial().'_id');
if($ret) return $ret;
// recall selected ids array and use the first one
$ids = $this->Application->GetVar($event->getPrefixSpecial().'_selected_ids');
if ($ids != '') {
$ids=explode(',',$ids);
if($ids) $ret=array_shift($ids);
}
else { // if selected ids are not yet stored
$this->StoreSelectedIDs($event);
return $this->Application->GetVar($event->getPrefixSpecial(true).'_id'); // StoreSelectedIDs sets this variable
}
return $ret;
}
/**
* Prepares and stores selected_ids string
* in Session and Application Variables
* by getting all checked ids from grid plus
* id passed in get/post as prefix_id
*
* @param kEvent $event
* @param Array $ids
*
* @return Array ids stored
*/
function StoreSelectedIDs(&$event, $ids = null)
{
$wid = $this->Application->GetTopmostWid($event->Prefix);
$session_name = rtrim($event->getPrefixSpecial().'_selected_ids_'.$wid, '_');
if (isset($ids)) {
// save ids directly if they given
$this->Application->StoreVar($session_name, implode(',', $ids));
return $ids;
}
$ret = Array();
// May be we don't need this part: ?
$passed = $this->Application->GetVar($event->getPrefixSpecial(true).'_id');
if($passed !== false && $passed != '')
{
array_push($ret, $passed);
}
$ids = Array();
// get selected ids from post & save them to session
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
$id_field = $this->Application->getUnitOption($event->Prefix,'IDField');
foreach($items_info as $id => $field_values)
{
if( getArrayValue($field_values,$id_field) ) array_push($ids,$id);
}
//$ids=array_keys($items_info);
}
$ret = array_unique(array_merge($ret, $ids));
$this->Application->SetVar($event->getPrefixSpecial().'_selected_ids', implode(',',$ret));
$this->Application->LinkVar($event->getPrefixSpecial().'_selected_ids', $session_name);
// This is critical - otherwise getPassedID will return last ID stored in session! (not exactly true)
// this smells... needs to be refactored
$first_id = getArrayValue($ret,0);
if (($first_id === false) && ($event->getEventParam('raise_warnings') == 1)) {
if ($this->Application->isDebugMode()) {
$this->Application->Debugger->appendTrace();
}
trigger_error('Requested ID for prefix <b>'.$event->getPrefixSpecial().'</b> <span class="debug_error">not passed</span>',E_USER_NOTICE);
}
$this->Application->SetVar($event->getPrefixSpecial(true).'_id', $first_id);
return $ret;
}
/**
* Returns stored selected ids as an array
*
* @param kEvent $event
* @param bool $from_session return ids from session (written, when editing was started)
* @return array
*/
function getSelectedIDs(&$event, $from_session = false)
{
if ($from_session) {
$wid = $this->Application->GetTopmostWid($event->Prefix);
$var_name = rtrim($event->getPrefixSpecial().'_selected_ids_'.$wid, '_');
$ret = $this->Application->RecallVar($var_name);
}
else {
$ret = $this->Application->GetVar($event->getPrefixSpecial().'_selected_ids');
}
return explode(',', $ret);
}
/**
* Returs associative array of submitted fields for current item
* Could be used while creating/editing single item -
* meaning on any edit form, except grid edit
*
* @param kEvent $event
*/
function getSubmittedFields(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$field_values = $items_info ? array_shift($items_info) : Array();
return $field_values;
}
/**
* Removes any information about current/selected ids
* from Application variables and Session
*
* @param kEvent $event
*/
function clearSelectedIDs(&$event)
{
$prefix_special = $event->getPrefixSpecial();
$ids = implode(',', $this->getSelectedIDs($event, true));
$event->setEventParam('ids', $ids);
$wid = $this->Application->GetTopmostWid($event->Prefix);
$session_name = rtrim($prefix_special.'_selected_ids_'.$wid, '_');
$this->Application->RemoveVar($session_name);
$this->Application->SetVar($prefix_special.'_selected_ids', '');
$this->Application->SetVar($prefix_special.'_id', ''); // $event->getPrefixSpecial(true).'_id' too may be
}
/*function SetSaveEvent(&$event)
{
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnUpdate');
$this->Application->LinkVar($event->Prefix_Special.'_SaveEvent');
}*/
/**
* Common builder part for Item & List
*
* @param kDBBase $object
* @param kEvent $event
* @access private
*/
function dbBuild(&$object, &$event)
{
$object->Configure( $event->getEventParam('populate_ml_fields') );
$this->PrepareObject($object, $event);
// force live table if specified or is original item
$live_table = $event->getEventParam('live_table') || $event->Special == 'original';
if( $this->UseTempTables($event) && !$live_table )
{
$object->SwitchToTemp();
}
// This strange constuction creates hidden field for storing event name in form submit
// It pass SaveEvent to next screen, otherwise after unsuccsefull create it will try to update rather than create
$current_event = $this->Application->GetVar($event->Prefix_Special.'_event');
// $this->Application->setEvent($event->Prefix_Special, $current_event);
$this->Application->setEvent($event->Prefix_Special, '');
$save_event = $this->UseTempTables($event) && $this->Application->GetTopmostPrefix($event->Prefix) == $event->Prefix ? 'OnSave' : 'OnUpdate';
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent',$save_event);
}
/**
* Builds item (loads if needed)
*
* @param kEvent $event
* @access protected
*/
function OnItemBuild(&$event)
{
$object =& $event->getObject();
$this->dbBuild($object,$event);
$sql = $this->ItemPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
// 2. loads if allowed
$auto_load = $this->Application->getUnitOption($event->Prefix,'AutoLoad');
$skip_autload = $event->getEventParam('skip_autoload');
if($auto_load && !$skip_autload) $this->LoadItem($event);
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->Prefix_Special.'_GoTab', '');
$actions->Set($event->Prefix_Special.'_GoId', '');
}
/**
* Build subtables array from configs
*
* @param kEvent $event
*/
function OnTempHandlerBuild(&$event)
{
$object =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
/* @var $object kTempTablesHandler */
$object->BuildTables( $event->Prefix, $this->getSelectedIDs($event) );
}
/**
* Enter description here...
*
* @param kEvent $event
* @return unknown
*/
function UseTempTables(&$event)
{
$object = &$event->getObject();
$top_prefix = $this->Application->GetTopmostPrefix($event->Prefix);
$var_names = Array (
$top_prefix,
rtrim($top_prefix.'_'.$event->Special, '_'),
rtrim($top_prefix.'.'.$event->Special, '.'),
);
$var_names = array_unique($var_names);
$temp_mode = false;
foreach ($var_names as $var_name) {
$value = $this->Application->GetVar($var_name.'_mode');
if (substr($value, 0, 1) == 't') {
$temp_mode = true;
break;
}
}
return $temp_mode;
}
/**
* Returns table prefix from event (temp or live)
*
* @param kEvent $event
* @return string
* @todo Needed? Should be refactored (by Alex)
*/
function TablePrefix(&$event)
{
return $this->UseTempTables($event) ? $this->Application->GetTempTablePrefix('prefix:'.$event->Prefix).TABLE_PREFIX : TABLE_PREFIX;
}
/**
* Load item if id is available
*
* @param kEvent $event
*/
function LoadItem(&$event)
{
$object =& $event->getObject();
$id = $this->getPassedID($event);
if ($object->Load($id) )
{
$actions =& $this->Application->recallObject('kActions');
$actions->Set($event->Prefix_Special.'_id', $object->GetID() );
$use_pending_editing = $this->Application->getUnitOption($event->Prefix, 'UsePendingEditing');
if ($use_pending_editing && $event->Special != 'original') {
$this->Application->SetVar($event->Prefix.'.original_id', $object->GetDBField('OrgId'));
}
}
else
{
$object->setID($id);
}
}
/**
* Builds list
*
* @param kEvent $event
* @access protected
*/
function OnListBuild(&$event)
{
$object =& $event->getObject();
/* @var $object kDBList */
$this->dbBuild($object,$event);
$sql = $this->ListPrepareQuery($event);
$sql = $this->Application->ReplaceLanguageTags($sql);
$object->setSelectSQL($sql);
$object->Counted = false; // when requery="1" should re-count records too!
$object->linkToParent( $this->getMainSpecial($event) );
$this->AddFilters($event);
$this->SetCustomQuery($event); // new!, use this for dynamic queries based on specials for ex.
$this->SetPagination($event);
$this->SetSorting($event);
// $object->CalculateTotals(); // Now called in getTotals to avoid extra query
$actions =& $this->Application->recallObject('kActions');
$actions->Set('remove_specials['.$event->Prefix_Special.']', '0');
$actions->Set($event->Prefix_Special.'_GoTab', '');
}
/**
* Get's special of main item for linking with subitem
*
* @param kEvent $event
* @return string
*/
function getMainSpecial(&$event)
{
$special = $event->getEventParam('main_special');
if($special === false || $special == '$main_special')
{
$special = $event->Special;
}
return $special;
}
/**
* Apply any custom changes to list's sql query
*
* @param kEvent $event
* @access protected
* @see OnListBuild
*/
function SetCustomQuery(&$event)
{
}
/**
* Set's new perpage for grid
*
* @param kEvent $event
*/
function OnSetPerPage(&$event)
{
$per_page = $this->Application->GetVar($event->getPrefixSpecial(true).'_PerPage');
$this->Application->StoreVar($event->getPrefixSpecial().'_PerPage', $per_page);
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$this->Application->StorePersistentVar($event->getPrefixSpecial().'_PerPage.'.$view_name, $per_page);
}
/**
* 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) {
$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;
}
}
/*$per_page = $event->getEventParam('per_page');
if ($per_page == 'list_next') {
$cur_page = $page;
$cur_per_page = $per_page;
$object->SetPerPage(1);
$object =& $this->Application->recallObject($event->Prefix);
$cur_item_index = $object->CurrentIndex;
$page = ($cur_page-1) * $cur_per_page + $cur_item_index + 1;
$object->SetPerPage(1);
}*/
$object->SetPage($page);
}
/**
* Returns current per-page setting for list
*
* @param kEvent $event
* @return int
*/
function getPerPage(&$event)
{
// 1. per-page is passed as tag parameter to PrintList, InitList, etc.
$per_page = $event->getEventParam('per_page');
/*if ($per_page == 'list_next') {
$per_page = '';
}*/
// 2. per-page variable name is store into config variable
$config_mapping = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
if ($config_mapping) {
switch ( $per_page ){
case 'short_list' :
$per_page = $this->Application->ConfigValue($config_mapping['ShortListPerPage']);
break;
case 'default' :
$per_page = $this->Application->ConfigValue($config_mapping['PerPage']);
break;
}
}
if (!$per_page) {
// per-page is stored to persistent session
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$per_page = $this->Application->RecallPersistentVar($event->getPrefixSpecial().'_PerPage.'.$view_name);
if (!$per_page) {
// per-page is stored to current session
$per_page = $this->Application->RecallVar($event->getPrefixSpecial().'_PerPage');
}
if (!$per_page) {
if ($config_mapping) {
if (!isset($config_mapping['PerPage'])) {
trigger_error('Incorrect mapping of <span class="debug_error">PerPage</span> key in config for prefix <b>'.$event->Prefix.'</b>', E_USER_WARNING);
}
$per_page = $this->Application->ConfigValue($config_mapping['PerPage']);
}
if (!$per_page) {
// none of checked above per-page locations are useful, then try default value
$per_page = 10;
}
}
}
return $per_page;
}
/**
* Set's correct sorting for list
* based on data provided with event
*
* @param kEvent $event
* @access private
* @see OnListBuild
*/
function SetSorting(&$event)
{
$event->setPseudoClass('_List');
$object =& $event->getObject();
$cur_sort1 = $this->Application->RecallVar($event->Prefix_Special.'_Sort1');
$cur_sort1_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort1_Dir');
$cur_sort2 = $this->Application->RecallVar($event->Prefix_Special.'_Sort2');
$cur_sort2_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort2_Dir');
$sorting_configs = $this->Application->getUnitOption($event->Prefix, 'ConfigMapping');
$list_sortings = $this->Application->getUnitOption($event->Prefix, 'ListSortings');
$sorting_prefix = getArrayValue($list_sortings, $event->Special) ? $event->Special : '';
$tag_sort_by = $event->getEventParam('sort_by');
if ($tag_sort_by) {
if ($tag_sort_by == 'random') {
$by = 'RAND()';
$dir = '';
}
else {
list($by, $dir) = explode(',', $tag_sort_by);
}
$object->AddOrderField($by, $dir);
}
if ($sorting_configs && isset ($sorting_configs['DefaultSorting1Field'])){
$list_sortings[$sorting_prefix]['Sorting'] = Array(
$this->Application->ConfigValue($sorting_configs['DefaultSorting1Field']) => $this->Application->ConfigValue($sorting_configs['DefaultSorting1Dir']),
$this->Application->ConfigValue($sorting_configs['DefaultSorting2Field']) => $this->Application->ConfigValue($sorting_configs['DefaultSorting2Dir']),
);
}
// Use default if not specified
if ( !$cur_sort1 || !$cur_sort1_dir)
{
if ( $sorting = getArrayValue($list_sortings, $sorting_prefix, 'Sorting') ) {
reset($sorting);
$cur_sort1 = key($sorting);
$cur_sort1_dir = current($sorting);
if (next($sorting)) {
$cur_sort2 = key($sorting);
$cur_sort2_dir = current($sorting);
}
}
}
if ( $forced_sorting = getArrayValue($list_sortings, $sorting_prefix, 'ForcedSorting') ) {
foreach ($forced_sorting as $field => $dir) {
$object->AddOrderField($field, $dir);
}
}
if($cur_sort1 != '' && $cur_sort1_dir != '')
{
$object->AddOrderField($cur_sort1, $cur_sort1_dir);
}
if($cur_sort2 != '' && $cur_sort2_dir != '')
{
$object->AddOrderField($cur_sort2, $cur_sort2_dir);
}
}
/**
* Add filters found in session
*
* @param kEvent $event
*/
function AddFilters(&$event)
{
$object =& $event->getObject();
$edit_mark = rtrim($this->Application->GetSID().'_'.$this->Application->GetTopmostWid($event->Prefix), '_');
// add search filter
$filter_data = $this->Application->RecallVar($event->getPrefixSpecial().'_search_filter');
if ($filter_data) {
$filter_data = unserialize($filter_data);
foreach ($filter_data as $filter_field => $filter_params) {
$filter_type = ($filter_params['type'] == 'having') ? HAVING_FILTER : WHERE_FILTER;
$filter_value = str_replace(EDIT_MARK, $edit_mark, $filter_params['value']);
$object->addFilter($filter_field, $filter_value, $filter_type, FLT_SEARCH);
}
}
// add custom filter
$view_name = $this->Application->RecallVar($event->getPrefixSpecial().'_current_view');
$custom_filters = $this->Application->RecallPersistentVar($event->getPrefixSpecial().'_custom_filter.'.$view_name);
if ($custom_filters) {
$grid_name = $event->getEventParam('grid');
$custom_filters = unserialize($custom_filters);
if (isset($custom_filters[$grid_name])) {
foreach ($custom_filters[$grid_name] as $field_name => $field_options) {
list ($filter_type, $field_options) = each($field_options);
if (isset($field_options['value']) && $field_options['value']) {
$filter_type = ($field_options['sql_filter_type'] == 'having') ? HAVING_FILTER : WHERE_FILTER;
$filter_value = str_replace(EDIT_MARK, $edit_mark, $field_options['value']);
$object->addFilter($field_name, $filter_value, $filter_type, FLT_CUSTOM);
}
}
}
}
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
if($view_filter)
{
$view_filter = unserialize($view_filter);
$temp_filter =& $this->Application->makeClass('kMultipleFilter');
$filter_menu = $this->Application->getUnitOption($event->Prefix,'FilterMenu');
$group_key = 0; $group_count = count($filter_menu['Groups']);
while($group_key < $group_count)
{
$group_info = $filter_menu['Groups'][$group_key];
$temp_filter->setType( constant('FLT_TYPE_'.$group_info['mode']) );
$temp_filter->clearFilters();
foreach ($group_info['filters'] as $flt_id)
{
$sql_key = getArrayValue($view_filter,$flt_id) ? 'on_sql' : 'off_sql';
if ($filter_menu['Filters'][$flt_id][$sql_key] != '')
{
$temp_filter->addFilter('view_filter_'.$flt_id, $filter_menu['Filters'][$flt_id][$sql_key]);
}
}
$object->addFilter('view_group_'.$group_key, $temp_filter, $group_info['type'] , FLT_VIEW);
$group_key++;
}
}
}
/**
* Set's new sorting for list
*
* @param kEvent $event
* @access protected
*/
function OnSetSorting(&$event)
{
$cur_sort1 = $this->Application->RecallVar($event->Prefix_Special.'_Sort1');
$cur_sort1_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort1_Dir');
$use_double_sorting = $this->Application->ConfigValue('UseDoubleSorting') !== false ? $this->Application->ConfigValue('UseDoubleSorting') : true;
if ($use_double_sorting) {
$cur_sort2 = $this->Application->RecallVar($event->Prefix_Special.'_Sort2');
$cur_sort2_dir = $this->Application->RecallVar($event->Prefix_Special.'_Sort2_Dir');
}
$passed_sort1 = $this->Application->GetVar($event->getPrefixSpecial(true).'_Sort1');
if ($cur_sort1 == $passed_sort1) {
$cur_sort1_dir = $cur_sort1_dir == 'asc' ? 'desc' : 'asc';
}
else {
if ($use_double_sorting) {
$cur_sort2 = $cur_sort1;
$cur_sort2_dir = $cur_sort1_dir;
}
$cur_sort1 = $passed_sort1;
$cur_sort1_dir = 'asc';
}
$this->Application->StoreVar($event->Prefix_Special.'_Sort1', $cur_sort1);
$this->Application->StoreVar($event->Prefix_Special.'_Sort1_Dir', $cur_sort1_dir);
if ($use_double_sorting) {
$this->Application->StoreVar($event->Prefix_Special.'_Sort2', $cur_sort2);
$this->Application->StoreVar($event->Prefix_Special.'_Sort2_Dir', $cur_sort2_dir);
}
}
/**
* Set sorting directly to session
*
* @param kEvent $event
*/
function OnSetSortingDirect(&$event)
{
$combined = $this->Application->GetVar($event->getPrefixSpecial(true).'_CombinedSorting');
if ($combined) {
list($field,$dir) = explode('|',$combined);
$this->Application->StoreVar($event->Prefix_Special.'_Sort1', $field);
$this->Application->StoreVar($event->Prefix_Special.'_Sort1_Dir', $dir);
return;
}
$field_pos = $this->Application->GetVar($event->getPrefixSpecial(true).'_SortPos');
$this->Application->LinkVar( $event->getPrefixSpecial(true).'_Sort'.$field_pos, $event->Prefix_Special.'_Sort'.$field_pos);
$this->Application->LinkVar( $event->getPrefixSpecial(true).'_Sort'.$field_pos.'_Dir', $event->Prefix_Special.'_Sort'.$field_pos.'_Dir');
}
/**
* Reset grid sorting to default (from config)
*
* @param kEvent $event
*/
function OnResetSorting(&$event)
{
$this->Application->RemoveVar($event->Prefix_Special.'_Sort1');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort1_Dir');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort2');
$this->Application->RemoveVar($event->Prefix_Special.'_Sort2_Dir');
}
/**
* Creates needed sql query to load item,
* if no query is defined in config for
* special requested, then use default
* query
*
* @param kEvent $event
* @access protected
*/
function ItemPrepareQuery(&$event)
{
$sqls = $this->Application->getUnitOption($event->Prefix,'ItemSQLs');
return isset($sqls[$event->Special]) ? $sqls[$event->Special] : $sqls[''];
}
/**
* Creates needed sql query to load list,
* if no query is defined in config for
* special requested, then use default
* query
*
* @param kEvent $event
* @access protected
*/
function ListPrepareQuery(&$event)
{
$sqls = $this->Application->getUnitOption($event->Prefix,'ListSQLs');
return isset( $sqls[$event->Special] ) ? $sqls[$event->Special] : $sqls[''];
}
/**
* Apply custom processing to item
*
* @param kEvent $event
*/
function customProcessing(&$event, $type)
{
}
/* Edit Events mostly used in Admin */
/**
* Creates new kDBItem
*
* @param kEvent $event
* @access protected
*/
function OnCreate(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
/* @var $object kDBItem */
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info) {
list($id,$field_values) = each($items_info);
$object->SetFieldsFromHash($field_values);
}
$this->customProcessing($event,'before');
//look at kDBItem' Create for ForceCreateId description, it's rarely used and is NOT set by default
if( $object->Create($event->getEventParam('ForceCreateId')) )
{
if( $object->IsTempTable() ) $object->setTempID();
$this->customProcessing($event,'after');
$event->status=erSUCCESS;
$event->redirect_params = Array('opener'=>'u');
}
else
{
$event->status = erFAIL;
$event->redirect = false;
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnCreate');
$object->setID($id);
}
}
/**
* Updates kDBItem
*
* @param kEvent $event
* @access protected
*/
function OnUpdate(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
foreach($items_info as $id => $field_values)
{
$object->Load($id);
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Update($id) )
{
$this->customProcessing($event, 'after');
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
break;
}
}
}
$event->redirect_params = Array('opener'=>'u');
}
/**
* Delete's kDBItem object
*
* @param kEvent $event
* @access protected
*/
function OnDelete(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->ID = $this->getPassedID($event);
if( $object->Delete() )
{
$event->status = erSUCCESS;
}
else
{
$event->status = erFAIL;
$event->redirect = false;
}
}
/**
* Prepares new kDBItem object
*
* @param kEvent $event
* @access protected
*/
function OnNew(&$event)
{
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->setID(0);
$this->Application->SetVar($event->Prefix_Special.'_SaveEvent','OnCreate');
$table_info = $object->getLinkedInfo();
$object->SetDBField($table_info['ForeignKey'], $table_info['ParentId']);
$event->redirect = false;
}
/**
* Cancel's kDBItem Editing/Creation
*
* @param kEvent $event
* @access protected
*/
function OnCancel(&$event)
{
$object =& $event->getObject(Array('skip_autoload' => true));
$items_info = $this->Application->GetVar($event->getPrefixSpecial(true));
if ($items_info) {
$delete_ids = Array();
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
foreach ($items_info as $id => $field_values) {
$object->Load($id);
// record created for using with selector (e.g. Reviews->Select User), and not validated => Delete it
if ($object->isLoaded() && !$object->Validate() && ($id <= 0) ) {
$delete_ids[] = $id;
}
}
if ($delete_ids) {
$temp->DeleteItems($event->Prefix, $event->Special, $delete_ids);
}
}
$event->redirect_params = Array('opener'=>'u');
}
/**
* Deletes all selected items.
* Automatically recurse into sub-items using temp handler, and deletes sub-items
* by calling its Delete method if sub-item has AutoDelete set to true in its config file
*
* @param kEvent $event
*/
function OnMassDelete(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$event->status=erSUCCESS;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$ids = $this->StoreSelectedIDs($event);
$event->setEventParam('ids', $ids);
$this->customProcessing($event, 'before');
$ids = $event->getEventParam('ids');
if($ids)
{
$temp->DeleteItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
/**
* Sets window id (of first opened edit window) to temp mark in uls
*
* @param kEvent $event
*/
function setTempWindowID(&$event)
{
$mode = $this->Application->GetVar($event->Prefix.'_mode');
if ($mode == 't') {
$wid = $this->Application->GetVar('m_wid');
$this->Application->SetVar($event->Prefix.'_mode', 't'.$wid);
}
}
/**
* Prepare temp tables and populate it
* with items selected in the grid
*
* @param kEvent $event
*/
function OnEdit(&$event)
{
$this->setTempWindowID($event);
$this->StoreSelectedIDs($event);
$var_name = $event->getPrefixSpecial().'_file_pending_actions'.$this->Application->GetVar('m_wid');
$this->Application->RemoveVar($var_name);
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
/* @var $temp kTempTablesHandler */
$temp->PrepareEdit();
$event->redirect=false;
}
/**
* Saves content of temp table into live and
* redirects to event' default redirect (normally grid template)
*
* @param kEvent $event
*/
function OnSave(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
$skip_master = false;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
if (!$this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
$live_ids = $temp->SaveEdit($event->getEventParam('master_ids') ? $event->getEventParam('master_ids') : Array());
// Deleteing files scheduled for delete
$var_name = $event->getPrefixSpecial().'_file_pending_actions'.$this->Application->GetVar('m_wid');
$schedule = $this->Application->RecallVar($var_name);
$schedule = $schedule ? unserialize($schedule) : array();
foreach ($schedule as $data) {
if ($data['action'] == 'delete') {
unlink($data['file']);
}
}
if ($live_ids) {
// ensure, that newly created item ids are avalable as if they were selected from grid
// NOTE: only works if main item has subitems !!!
$this->StoreSelectedIDs($event, $live_ids);
}
}
$this->clearSelectedIDs($event);
$event->redirect_params = Array('opener' => 'u');
$this->Application->RemoveVar($event->getPrefixSpecial().'_modified');
// all temp tables are deleted here => all after hooks should think, that it's live mode now
$this->Application->SetVar($event->Prefix.'_mode', '');
}
}
/**
* Cancels edit
* Removes all temp tables and clears selected ids
*
* @param kEvent $event
*/
function OnCancelEdit(&$event)
{
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$temp->CancelEdit();
$this->clearSelectedIDs($event);
$event->redirect_params = Array('opener'=>'u');
$this->Application->RemoveVar($event->getPrefixSpecial().'_modified');
}
/**
* Allows to determine if we are creating new item or editing already created item
*
* @param kEvent $event
* @return bool
*/
function isNewItemCreate(&$event)
{
$event->setEventParam('raise_warnings', 0);
$object =& $event->getObject();
return !$object->IsLoaded();
// $item_id = $this->getPassedID($event);
// return ($item_id == '') ? true : false;
}
/**
* Saves edited item into temp table
* If there is no id, new item is created in temp table
*
* @param kEvent $event
*/
function OnPreSave(&$event)
{
//$event->redirect = false;
// if there is no id - it means we need to create an item
if (is_object($event->MasterEvent)) {
$event->MasterEvent->setEventParam('IsNew',false);
}
if ($this->isNewItemCreate($event)) {
$event->CallSubEvent('OnPreSaveCreated');
if (is_object($event->MasterEvent)) {
$event->MasterEvent->setEventParam('IsNew',true);
}
return;
}
$object =& $event->getObject( Array('skip_autoload' => true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if ($items_info) {
foreach ($items_info as $id => $field_values) {
$object->SetDefaultValues();
$object->Load($id);
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Update($id) )
{
$this->customProcessing($event, 'after');
$event->status=erSUCCESS;
}
else {
$event->status = erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
* Saves edited item in temp table and loads
* item with passed id in current template
* Used in Prev/Next buttons
*
* @param kEvent $event
*/
function OnPreSaveAndGo(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status==erSUCCESS) {
$event->redirect_params[$event->getPrefixSpecial(true).'_id'] = $this->Application->GetVar($event->Prefix_Special.'_GoId');
}
}
/**
* Saves edited item in temp table and goes
* to passed tabs, by redirecting to it with OnPreSave event
*
* @param kEvent $event
*/
function OnPreSaveAndGoToTab(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status==erSUCCESS) {
$event->redirect=$this->Application->GetVar($event->getPrefixSpecial(true).'_GoTab');
}
}
/**
* Saves editable list and goes to passed tab,
* by redirecting to it with empty event
*
* @param kEvent $event
*/
function OnUpdateAndGoToTab(&$event)
{
$event->setPseudoClass('_List');
$event->CallSubEvent('OnUpdate');
if ($event->status==erSUCCESS) {
$event->redirect=$this->Application->GetVar($event->getPrefixSpecial(true).'_GoTab');
}
}
/**
* Prepare temp tables for creating new item
* but does not create it. Actual create is
* done in OnPreSaveCreated
*
* @param kEvent $event
*/
function OnPreCreate(&$event)
{
$this->setTempWindowID($event);
$this->clearSelectedIDs($event);
$object =& $event->getObject( Array('skip_autoload' => true) );
$temp =& $this->Application->recallObject($event->Prefix.'_TempHandler', 'kTempTablesHandler');
$temp->PrepareEdit();
$object->setID(0);
$this->Application->SetVar($event->getPrefixSpecial().'_id',0);
$this->Application->SetVar($event->getPrefixSpecial().'_PreCreate', 1);
$event->redirect=false;
}
/**
* Creates a new item in temp table and
* stores item id in App vars and Session on succsess
*
* @param kEvent $event
*/
function OnPreSaveCreated(&$event)
{
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info) $field_values = array_shift($items_info);
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->SetFieldsFromHash($field_values);
$this->customProcessing($event, 'before');
if( $object->Create() )
{
$this->customProcessing($event, 'after');
$event->redirect_params[$event->getPrefixSpecial(true).'_id'] = $object->GetId();
$event->status=erSUCCESS;
}
else
{
$event->status=erFAIL;
$event->redirect=false;
$object->setID(0);
}
}
function OnReset(&$event)
{
//do nothing - should reset :)
if ($this->isNewItemCreate($event)) {
// just reset id to 0 in case it was create
$object =& $event->getObject( Array('skip_autoload' => true) );
$object->setID(0);
$this->Application->SetVar($event->getPrefixSpecial().'_id',0);
}
}
/**
* Apply same processing to each item beeing selected in grid
*
* @param kEvent $event
* @access private
*/
function iterateItems(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$object =& $event->getObject( Array('skip_autoload' => true) );
$ids = $this->StoreSelectedIDs($event);
if ($ids) {
$status_field = array_shift( $this->Application->getUnitOption($event->Prefix,'StatusField') );
foreach ($ids as $id) {
$object->Load($id);
switch ($event->Name) {
case 'OnMassApprove':
$object->SetDBField($status_field, 1);
break;
case 'OnMassDecline':
$object->SetDBField($status_field, 0);
break;
case 'OnMassMoveUp':
$object->SetDBField('Priority', $object->GetDBField('Priority') + 1);
break;
case 'OnMassMoveDown':
$object->SetDBField('Priority', $object->GetDBField('Priority') - 1);
break;
}
if ($object->Update()) {
$event->status = erSUCCESS;
}
else {
$event->status = erFAIL;
$event->redirect = false;
break;
}
}
}
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnMassClone(&$event)
{
if ($this->Application->CheckPermission('SYSTEM_ACCESS.READONLY', 1)) {
return;
}
$event->status = erSUCCESS;
$temp =& $this->Application->recallObject($event->getPrefixSpecial().'_TempHandler', 'kTempTablesHandler');
$ids = $this->StoreSelectedIDs($event);
if ($ids) {
$temp->CloneItems($event->Prefix, $event->Special, $ids);
}
$this->clearSelectedIDs($event);
}
function check_array($records, $field, $value)
{
foreach ($records as $record) {
if ($record[$field] == $value) {
return true;
}
}
return false;
}
function OnPreSavePopup(&$event)
{
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
$this->finalizePopup($event);
}
/* End of Edit events */
// III. Events that allow to put some code before and after Update,Load,Create and Delete methods of item
/**
* Occurse before loading item, 'id' parameter
* allows to get id of item beeing loaded
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemLoad(&$event)
{
}
/**
* Occurse after loading item, 'id' parameter
* allows to get id of item that was loaded
*
* @param kEvent $event
* @access public
*/
function OnAfterItemLoad(&$event)
{
}
/**
* Occurse before creating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemCreate(&$event)
{
}
/**
* Occurse after creating item
*
* @param kEvent $event
* @access public
*/
function OnAfterItemCreate(&$event)
{
}
/**
* Occurse before updating item
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemUpdate(&$event)
{
}
/**
* Occurse after updating item
*
* @param kEvent $event
* @access public
*/
function OnAfterItemUpdate(&$event)
{
}
/**
* Occurse before deleting item, id of item beeing
* deleted is stored as 'id' event param
*
* @param kEvent $event
* @access public
*/
function OnBeforeItemDelete(&$event)
{
}
/**
* Occurse after deleting item, id of deleted item
* is stored as 'id' param of event
*
* @param kEvent $event
* @access public
*/
function OnAfterItemDelete(&$event)
{
}
/**
* Occurs after successful item validation
*
* @param kEvent $event
*/
function OnAfterItemValidate(&$event)
{
}
/**
* Occures after an item has been copied to temp
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterCopyToTemp(&$event)
{
}
/**
* Occures before an item is deleted from live table when copying from temp
* (temp handler deleted all items from live and then copy over all items from temp)
* Id of item being deleted is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnBeforeDeleteFromLive(&$event)
{
}
/**
* Occures before an item is copied to live table (after all foreign keys have been updated)
* Id of item being copied is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnBeforeCopyToLive(&$event)
{
}
/**
* !!! NOT FULLY IMPLEMENTED - SEE TEMP HANDLER COMMENTS (search by event name)!!!
* Occures after an item has been copied to live table
* Id of copied item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterCopyToLive(&$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)
{
}
/**
* Occures after an item has been cloned
* Id of newly created item is passed as event' 'id' param
*
* @param kEvent $event
*/
function OnAfterClone(&$event)
{
}
/**
* Ensures that popup will be closed automatically
* and parent window will be refreshed with template
* passed
*
* @param kEvent $event
* @access public
*/
function finalizePopup(&$event)
{
$event->SetRedirectParam('opener', 'u');
/*return ;
// 2. substitute opener
$opener_stack = $this->Application->RecallVar('opener_stack');
$opener_stack = $opener_stack ? unserialize($opener_stack) : Array();
//array_pop($opener_stack);
$t = $this->Application->RecallVar('return_template');
$this->Application->RemoveVar('return_template');
// restore original "m" prefix all params, that have values before opening selector
$return_m = $this->Application->RecallVar('return_m');
$this->Application->RemoveVar('return_m');
$this->Application->HttpQuery->parseEnvPart($return_m);
$pass_events = $event->getEventParam('pass_events');
$redirect_params = array_merge_recursive2($event->redirect_params, Array('m_opener' => 'u', '__URLENCODE__' => 1));
$new_level = 'index.php|'.ltrim($this->Application->BuildEnv($t, $redirect_params, 'all', $pass_events), ENV_VAR_NAME.'=');
array_push($opener_stack, $new_level);
$this->Application->StoreVar('opener_stack', serialize($opener_stack));*/
}
/**
* Create search filters based on search query
*
* @param kEvent $event
* @access protected
*/
function OnSearch(&$event)
{
$event->setPseudoClass('_List');
$search_helper =& $this->Application->recallObject('SearchHelper');
$search_helper->performSearch($event);
}
/**
* Clear search keywords
*
* @param kEvent $event
* @access protected
*/
function OnSearchReset(&$event)
{
$search_helper =& $this->Application->recallObject('SearchHelper');
$search_helper->resetSearch($event);
}
/**
* Set's new filter value (filter_id meaning from config)
*
* @param kEvent $event
*/
function OnSetFilter(&$event)
{
$filter_id = $this->Application->GetVar('filter_id');
$filter_value = $this->Application->GetVar('filter_value');
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
$view_filter = $view_filter ? unserialize($view_filter) : Array();
$view_filter[$filter_id] = $filter_value;
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
}
function OnSetFilterPattern(&$event)
{
$filters = $this->Application->GetVar($event->getPrefixSpecial(true).'_filters');
if (!$filters) return ;
$view_filter = $this->Application->RecallVar($event->getPrefixSpecial().'_view_filter');
$view_filter = $view_filter ? unserialize($view_filter) : Array();
$filters = explode(',', $filters);
foreach ($filters as $a_filter) {
list($id, $value) = explode('=', $a_filter);
$view_filter[$id] = $value;
}
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
$event->redirect = false;
}
/**
* Add/Remove all filters applied to list from "View" menu
*
* @param kEvent $event
*/
function FilterAction(&$event)
{
$view_filter = Array();
$filter_menu = $this->Application->getUnitOption($event->Prefix,'FilterMenu');
switch ($event->Name)
{
case 'OnRemoveFilters':
$filter_value = 1;
break;
case 'OnApplyFilters':
$filter_value = 0;
break;
}
foreach($filter_menu['Filters'] as $filter_key => $filter_params)
{
if(!$filter_params) continue;
$view_filter[$filter_key] = $filter_value;
}
$this->Application->StoreVar( $event->getPrefixSpecial().'_view_filter', serialize($view_filter) );
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnPreSaveAndOpenTranslator(&$event)
{
$this->Application->SetVar('allow_translation', true);
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
$resource_id = $this->Application->GetVar('translator_resource_id');
if ($resource_id) {
$t_prefixes = explode(',', $this->Application->GetVar('translator_prefixes'));
$cdata =& $this->Application->recallObject($t_prefixes[1], null, Array('skip_autoload' => true));
$cdata->Load($resource_id, 'ResourceId');
if (!$cdata->isLoaded()) {
$cdata->SetDBField('ResourceId', $resource_id);
$cdata->Create();
}
$this->Application->SetVar($cdata->getPrefixSpecial().'_id', $cdata->GetID());
}
$event->redirect = $this->Application->GetVar('translator_t');
$event->redirect_params = Array('pass'=>'all,trans,'.$this->Application->GetVar('translator_prefixes'),
$event->getPrefixSpecial(true).'_id' => $object->GetID(),
'trans_event' => 'OnLoad',
'trans_prefix' => $this->Application->GetVar('translator_prefixes'),
'trans_field' => $this->Application->GetVar('translator_field'),
'trans_multi_line' => $this->Application->GetVar('translator_multi_line'),
);
// 1. SAVE LAST TEMPLATE TO SESSION (really needed here, because of tweaky redirect)
$last_template = $this->Application->RecallVar('last_template');
preg_match('/index4\.php\|'.$this->Application->GetSID().'-(.*):/U', $last_template, $rets);
$this->Application->StoreVar('return_template', $this->Application->GetVar('t'));
}
}
function RemoveRequiredFields(&$object)
{
// making all field non-required to achieve successful presave
foreach($object->Fields as $field => $options)
{
if(isset($options['required']))
{
unset($object->Fields[$field]['required']);
}
}
}
/**
- * Dynamically fills customdata config
- *
- * @param kEvent $event
- */
- function OnCreateCustomFields(&$event)
- {
- if (defined('IS_INSTALL') && IS_INSTALL && !$this->Application->TableFound('CustomField')) {
- return false;
- }
- $main_prefix = $this->Application->getUnitOption($event->Prefix, 'ParentPrefix');
- if (!$main_prefix) return false;
- $item_type = $this->Application->getUnitOption($main_prefix, 'ItemType');
- if (!$item_type) {
- // no main config of such type
- return false;
- }
-
- // 1. get custom field information
- $sql = 'SELECT *
- FROM '.TABLE_PREFIX.'CustomField
- WHERE Type = '.$item_type.'
- ORDER BY CustomFieldId';
- $custom_fields = $this->Conn->Query($sql, 'CustomFieldId');
- if (!$custom_fields) {
- // config doesn't have custom fields
- return false;
- }
-
- // 2. create fields (for customdata item)
- $fields = $this->Application->getUnitOption($event->Prefix, 'Fields', Array());
- $field_options = Array('type' => 'string', 'formatter' => 'kMultiLanguage', 'db_type' => 'text', 'default' => '');
- foreach ($custom_fields as $custom_id => $custom_params) {
- if (isset($fields['cust_'.$custom_id])) continue;
- $fields['cust_'.$custom_id] = $field_options;
- }
- $this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
-
- // 3. create virtual & calculated fields (for main item)
- $calculated_fields = Array();
- $virtual_fields = $this->Application->getUnitOption($main_prefix, 'VirtualFields', Array());
-
- $cf_helper =& $this->Application->recallObject('InpCustomFieldsHelper');
- $field_options = Array('type' => 'string', 'not_null' => 1, 'default' => '');
- $ml_formatter =& $this->Application->recallObject('kMultiLanguage');
-
- foreach ($custom_fields as $custom_id => $custom_params) {
- switch ($custom_params['ElementType']) {
- case 'date':
- case 'datetime':
- unset($field_options['options']);
- $field_options['formatter'] = 'kDateFormatter';
- break;
-
- case 'select':
- case 'multiselect':
- case 'radio':
- if ($custom_params['ValueList']) {
- $field_options['options'] = $cf_helper->GetValuesHash($custom_params['ValueList']);
- $field_options['formatter'] = 'kOptionsFormatter';
- }
- break;
-
- default:
- unset($field_options['options'], $field_options['formatter']);
- break;
- }
-
- $custom_name = $custom_params['FieldName'];
- $calculated_fields['cust_'.$custom_name] = 'cust.'.$ml_formatter->LangFieldName('cust_'.$custom_id);
- if (!isset($virtual_fields['cust_'.$custom_name])) {
- $virtual_fields['cust_'.$custom_name] = Array();
- }
- $virtual_fields['cust_'.$custom_name] = array_merge_recursive2($field_options, $virtual_fields['cust_'.$custom_name]);
- $custom_fields[$custom_id] = $custom_name;
- }
-
- $config_calculated_fields = $this->Application->getUnitOption($main_prefix, 'CalculatedFields', Array());
- foreach ($config_calculated_fields as $special => $special_fields) {
- $config_calculated_fields[$special] = array_merge_recursive2($config_calculated_fields[$special], $calculated_fields);
- }
- $this->Application->setUnitOption($main_prefix, 'CalculatedFields', $config_calculated_fields);
-
- $this->Application->setUnitOption($main_prefix, 'CustomFields', $custom_fields);
- $this->Application->setUnitOption($main_prefix, 'VirtualFields', $virtual_fields);
- }
-
- /**
* Saves selected user in needed field
*
* @param kEvent $event
*/
function OnSelectUser(&$event)
{
$items_info = $this->Application->GetVar('u');
if ($items_info) {
$user_id = array_shift( array_keys($items_info) );
$object =& $event->getObject();
$this->RemoveRequiredFields($object);
$is_new = !$object->isLoaded();
$is_main = substr($this->Application->GetVar($event->Prefix.'_mode'), 0, 1) == 't';
if ($is_new) {
$new_event = $is_main ? 'OnPreCreate' : 'OnNew';
$event->CallSubEvent($new_event);
}
$object->SetDBField($this->Application->RecallVar('dst_field'), $user_id);
if ($is_new) {
$object->Create();
if (!$is_main && $object->IsTempTable()) {
$object->setTempID();
}
}
else {
$object->Update();
}
}
$event->SetRedirectParam($event->getPrefixSpecial().'_id', $object->GetID());
$this->finalizePopup($event);
}
/** EXPORT RELATED **/
/**
* Shows export dialog
*
* @param kEvent $event
*/
function OnExport(&$event)
{
$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;
}
$this->Application->StoreVar($event->Prefix.'_export_ids', $selected_ids ? implode(',', $selected_ids) : '' );
$export_t = $this->Application->GetVar('export_template');
$this->Application->LinkVar('export_finish_t');
$this->Application->LinkVar('export_progress_t');
$this->Application->StoreVar('export_oroginal_special', $event->Special);
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
$event->redirect = $export_t ? $export_t : $export_helper->getModuleFolder($event).'/export';
list($index_file, $env) = explode('|', $this->Application->RecallVar('last_template'));
$finish_url = $this->Application->BaseURL('/admin').$index_file.'?'.ENV_VAR_NAME.'='.$env;
$this->Application->StoreVar('export_finish_url', $finish_url);
$redirect_params = Array(
$this->Prefix.'.export_event' => 'OnNew',
'pass' => 'all,'.$this->Prefix.'.export');
$event->setRedirectParams($redirect_params);
}
/**
* Apply some special processing to
* object beeing recalled before using
* it in other events that call prepareObject
*
* @param Object $object
* @param kEvent $event
* @access protected
*/
function prepareObject(&$object, &$event)
{
if ($event->Special == 'export' || $event->Special == 'import')
{
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
$export_helper->prepareExportColumns($event);
}
}
/**
* Returns specific to each item type columns only
*
* @param kEvent $event
* @return Array
*/
function getCustomExportColumns(&$event)
{
return Array();
}
/**
* Export form validation & processing
*
* @param kEvent $event
*/
function OnExportBegin(&$event)
{
$export_helper =& $this->Application->recallObject('CatItemExportHelper');
/* @var $export_helper kCatDBItemExportHelper */
$export_helper->OnExportBegin($event);
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnExportCancel(&$event)
{
$this->OnGoBack($event);
}
/**
* Allows configuring export options
*
* @param kEvent $event
*/
function OnBeforeExportBegin(&$event)
{
}
function OnDeleteExportPreset(&$event)
{
$object =& $event->GetObject();
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
if($items_info)
{
list($id,$field_values) = each($items_info);
$preset_key = $field_values['ExportPresets'];
$user =& $this->Application->recallObject('u.current');
$export_settings = $user->getPersistantVar('export_settings');
if (!$export_settings) return ;
$export_settings = unserialize($export_settings);
if (!isset($export_settings[$event->Prefix])) return ;
$to_delete = '';
$export_presets = array(''=>'');
foreach ($export_settings[$event->Prefix] as $key => $val) {
if (implode('|', $val['ExportColumns']) == $preset_key) {
$to_delete = $key;
break;
}
}
if ($to_delete) {
unset($export_settings[$event->Prefix][$to_delete]);
$user->setPersistantVar('export_settings', serialize($export_settings));
}
}
}
/**
* Saves changes & changes language
*
* @param kEvent $event
*/
function OnPreSaveAndChangeLanguage(&$event)
{
$event->CallSubEvent('OnPreSave');
if ($event->status == erSUCCESS) {
$this->Application->SetVar('m_lang', $this->Application->GetVar('language'));
}
}
function OnUploadFile(&$event)
{
// Flash uploader does NOT send correct cookies, so we need to make our own check
$cookie_name = 'adm_'.$this->Application->ConfigValue('SessionCookieName');
$this->Application->HttpQuery->Cookie['cookies_on'] = 1;
$this->Application->HttpQuery->Cookie[$cookie_name] = $this->Application->GetVar('flashsid');
$admin_ses =& $this->Application->recallObject('Session.admin');
/* @var $admin_ses Session */
$user = $admin_ses->RecallVar('user_id');
$perm_helper =& $this->Application->recallObject('PermissionsHelper');
/* @var $perm_helper kPermissionsHelper */
$section = $event->getSection();
if (!$perm_helper->CheckUserPermission($user, $section.'.add') && !$perm_helper->CheckUserPermission($user, $section.'.edit')) {
$event->status = erPERM_FAIL;
header('HTTP/1.0 403 You don\'t have permissions to upload');
exit;
return;
}
if (!$cookie_name) $cookie_name = 'sid';
$value = $this->Application->GetVar('Filedata');
if (!$value) return ;
$tmp_path = WRITEABLE.'/tmp/';
$fname = $value['name'];
$id = $this->Application->GetVar('id');
if ($id) $fname = $id.'_'.$fname;
if (!is_writable($tmp_path)) {
header('HTTP/1.0 500 Write permissions not set on the server');
exit;
}
move_uploaded_file($value['tmp_name'], $tmp_path.$fname);
exit;
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnDeleteFile(&$event)
{
if (strpos($this->Application->GetVar('file'), '../') !== false) return ;
$object =& $event->getObject(array('skip_autoload'=>true));
$options = $object->GetFieldOptions($this->Application->GetVar('field'));
$var_name = $event->getPrefixSpecial().'_file_pending_actions'.$this->Application->GetVar('m_wid');
$schedule = $this->Application->RecallVar($var_name);
$schedule = $schedule ? unserialize($schedule) : array();
$schedule[] = array('action'=>'delete', 'file'=>$path = FULL_PATH.$options['upload_dir'].$this->Application->GetVar('file'));
$this->Application->StoreVar($var_name, serialize($schedule));
$this->Application->Session->SaveData();
}
/**
* Enter description here...
*
* @param kEvent $event
*/
function OnViewFile(&$event)
{
if (strpos($this->Application->GetVar('file'), '../') !== false) return ;
if ($this->Application->GetVar('tmp')) {
$path = WRITEABLE.'/tmp/'.$this->Application->GetVar('id').'_'.$this->Application->GetVar('file');
}
else {
$object =& $event->getObject(array('skip_autoload'=>true));
$options = $object->GetFieldOptions($this->Application->GetVar('field'));
$path = FULL_PATH.$options['upload_dir'].$this->Application->GetVar('file');
}
$type = mime_content_type($path);
header('Content-Length: '.filesize($path));
header('Content-Type: '.$type);
safeDefine('DBG_SKIP_REPORTING',1);
readfile($path);
exit();
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.85.2/core/kernel/db/db_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.85.2.4
\ No newline at end of property
+1.85.2.5
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.2.2/core/units/custom_data/custom_data_event_handler.php
===================================================================
--- branches/unlabeled/unlabeled-1.2.2/core/units/custom_data/custom_data_event_handler.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.2.2/core/units/custom_data/custom_data_event_handler.php (revision 8242)
@@ -1,7 +1,140 @@
<?php
class CustomDataEventHandler extends kDBEventHandler {
+ /**
+ * [HOOK] Allows to apply custom fields functionality to specific config
+ * When main item is created, then cdata config is cloned
+ *
+ * @param kEvent $event
+ */
+ function OnDefineCustomFields(&$event)
+ {
+ // 1. clone customdata table
+ $clones = $this->Application->getUnitOption('cdata', 'Clones');
+ $clones[$event->MasterEvent->Prefix.'-cdata'] = Array (
+ 'ParentPrefix' => $event->MasterEvent->Prefix,
+ 'TableName' => $this->Application->getUnitOption($event->MasterEvent->Prefix, 'TableName').'CustomData',
+ );
+ $this->Application->setUnitOption('cdata', 'Clones', $clones);
+
+ // 2. add custom field information to main item
+ $this->createCustomFields($event->MasterEvent->Prefix);
+ }
+
+ function scanCustomFields($prefix)
+ {
+ if (defined('IS_INSTALL') && IS_INSTALL && !$this->Application->TableFound('CustomField')) {
+ return false;
+ }
+
+ if (!$prefix) {
+ // prefix not specified
+ return false;
+ }
+
+ $item_type = $this->Application->getUnitOption($prefix, 'ItemType');
+ if (!$item_type) {
+ // no main config of such type
+ return false;
+ }
+ // get custom field information
+ $sql = 'SELECT *
+ FROM '.TABLE_PREFIX.'CustomField
+ WHERE Type = '.$item_type.'
+ ORDER BY CustomFieldId';
+ $custom_fields = $this->Conn->Query($sql, 'CustomFieldId');
+ if (!$custom_fields) {
+ // config doesn't have custom fields
+ return false;
+ }
+
+ return $custom_fields;
+ }
+
+ /**
+ * Fills cloned cdata config with data from it's parent
+ *
+ * @param kEvent $event
+ */
+ function OnAfterConfigRead(&$event)
+ {
+ $main_prefix = $this->Application->getUnitOption($event->Prefix, 'ParentPrefix');
+
+ $custom_fields = $this->scanCustomFields($main_prefix);
+ if (!$custom_fields) {
+ return false;
+ }
+
+ // 2. create fields (for customdata item)
+ $fields = $this->Application->getUnitOption($event->Prefix, 'Fields', Array());
+ $field_options = Array('type' => 'string', 'formatter' => 'kMultiLanguage', 'db_type' => 'text', 'default' => '');
+ foreach ($custom_fields as $custom_id => $custom_params) {
+ if (isset($fields['cust_'.$custom_id])) continue;
+ $fields['cust_'.$custom_id] = $field_options;
+ }
+ $this->Application->setUnitOption($event->Prefix, 'Fields', $fields);
+ }
+
+ /**
+ * Creates "cust_<custom_name>" virtual fields for main item
+ *
+ * @param string $prefix
+ */
+ function createCustomFields($prefix)
+ {
+ $custom_fields = $this->scanCustomFields($prefix);
+ if (!$custom_fields) {
+ return false;
+ }
+
+ $calculated_fields = Array();
+ $virtual_fields = $this->Application->getUnitOption($prefix, 'VirtualFields', Array());
+
+ $cf_helper =& $this->Application->recallObject('InpCustomFieldsHelper');
+ $field_options = Array('type' => 'string', 'not_null' => 1, 'default' => '');
+ $ml_formatter =& $this->Application->recallObject('kMultiLanguage');
+
+ foreach ($custom_fields as $custom_id => $custom_params) {
+ switch ($custom_params['ElementType']) {
+ case 'date':
+ case 'datetime':
+ unset($field_options['options']);
+ $field_options['formatter'] = 'kDateFormatter';
+ break;
+
+ case 'select':
+ case 'multiselect':
+ case 'radio':
+ if ($custom_params['ValueList']) {
+ $field_options['options'] = $cf_helper->GetValuesHash($custom_params['ValueList']);
+ $field_options['formatter'] = 'kOptionsFormatter';
+ }
+ break;
+
+ default:
+ unset($field_options['options'], $field_options['formatter']);
+ break;
+ }
+
+ $custom_name = $custom_params['FieldName'];
+ $calculated_fields['cust_'.$custom_name] = 'cust.'.$ml_formatter->LangFieldName('cust_'.$custom_id);
+ if (!isset($virtual_fields['cust_'.$custom_name])) {
+ $virtual_fields['cust_'.$custom_name] = Array();
+ }
+ $virtual_fields['cust_'.$custom_name] = array_merge_recursive2($field_options, $virtual_fields['cust_'.$custom_name]);
+ $custom_fields[$custom_id] = $custom_name;
+ }
+
+ $config_calculated_fields = $this->Application->getUnitOption($prefix, 'CalculatedFields', Array());
+ foreach ($config_calculated_fields as $special => $special_fields) {
+ $config_calculated_fields[$special] = array_merge_recursive2($config_calculated_fields[$special], $calculated_fields);
+ }
+ $this->Application->setUnitOption($prefix, 'CalculatedFields', $config_calculated_fields);
+
+ $this->Application->setUnitOption($prefix, 'CustomFields', $custom_fields);
+ $this->Application->setUnitOption($prefix, 'VirtualFields', $virtual_fields);
+ }
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.2.2/core/units/custom_data/custom_data_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.2
\ No newline at end of property
+1.2.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.6.2/core/admin_templates/tools/system_tools.tpl
===================================================================
--- branches/unlabeled/unlabeled-1.6.2/core/admin_templates/tools/system_tools.tpl (revision 8241)
+++ branches/unlabeled/unlabeled-1.6.2/core/admin_templates/tools/system_tools.tpl (revision 8242)
@@ -1,51 +1,52 @@
<inp2:m_RequireLogin permissions="in-portal:service.view" system="1"/>
<inp2:m_include t="incs/header"/>
<inp2:m_ParseBlock name="section_header" icon="icon46_modules" title="!la_title_SystemTools!"/>
<inp2:m_ParseBlock name="blue_bar" prefix="adm" title_preset="system_tools" module="in-portal" icon="icon46_modules"/>
<script type="text/javascript">
function show_structure($prefix, $event) {
var $form = document.getElementById($form_name);
openwin('about:blank', 'table_structure', 800, 575);
$form.target = 'table_structure';
submit_event($prefix, $event);
set_hidden_field('events[adm]', '');
}
</script>
-<inp2:m_DefineElement name="service_elem">
+<inp2:m_DefineElement name="service_elem" event_prefix="adm">
<tr class="<inp2:m_odd_even odd="table-color1" even="table-color2"/>">
<inp2:m_inc param="tab_index" by="1"/>
<td class="text" style="width: 300px;">
<inp2:m_phrase label="$title"/>:
</td>
<td valign="top" colspan="2">
- <input class="button" type="button" onclick="submit_event('adm', '<inp2:m_param name="event_name"/>');" value="Go">
+ <input class="button" type="button" onclick="submit_event('<inp2:m_param name="event_prefix"/>', '<inp2:m_param name="event_name"/>');" value="Go">
</td>
<td class="error">&nbsp;</td>
</tr>
</inp2:m_DefineElement>
<table width="100%" border="0" cellspacing="0" cellpadding="4" class="bordered" id="config_table">
<inp2:m_RenderElement name="subsection" title="la_section_General"/>
<inp2:m_RenderElement name="service_elem" title="la_Service_ResetModRwCache" event_name="OnResetModRwCache"/>
<inp2:m_RenderElement name="service_elem" title="la_Service_ResetCMSMenuCache" event_name="OnResetCMSMenuCache"/>
<inp2:m_RenderElement name="service_elem" title="la_Service_ResetSections" event_name="OnResetSections"/>
<inp2:m_RenderElement name="service_elem" title="la_Service_ConfigCache" event_name="OnResetConfigsCache"/>
<inp2:m_RenderElement name="service_elem" title="la_Service_RebuildThemes" event_name="OnRebuildThemes"/>
+ <inp2:m_RenderElement name="service_elem" title="la_Service_RebuildMultilanguageFields" event_prefix="lang" event_name="OnReflectMultiLingualFields"/>
<inp2:m_RenderElement name="subsection" title="la_section_Configs"/>
<tr class="<inp2:m_odd_even odd="table-color1" even="table-color2"/>">
<inp2:m_inc param="tab_index" by="1"/>
<td class="text" style="width: 300px;">
Table Structure:
</td>
<td valign="top" colspan="3">
<input type="text" name="table_name" value="" size="30"/>
<input class="button" type="button" onclick="show_structure('adm', 'OnGenerateTableStructure');" value="Go">
<span class="small">table name (prefix optional) OR unit config prefix</span>
</td>
</tr>
</table>
<inp2:m_include t="incs/footer"/>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.6.2/core/admin_templates/tools/system_tools.tpl
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6.2.2
\ No newline at end of property
+1.6.2.3
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.10.2/core/units/custom_data/custom_data_config.php
===================================================================
--- branches/unlabeled/unlabeled-1.10.2/core/units/custom_data/custom_data_config.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.10.2/core/units/custom_data/custom_data_config.php (revision 8242)
@@ -1,83 +1,37 @@
<?php
- $config = Array(
- 'Prefix' => 'cdata',
-
- 'Clones' => Array(
- 'u-cdata' => Array(
- 'TableName' => TABLE_PREFIX.'PortalUserCustomData',
- 'ParentPrefix' => 'u',
- ),
-
- 'c-cdata' => Array(
- 'TableName' => TABLE_PREFIX.'CategoryCustomData',
- 'ParentPrefix' => 'c',
- ),
-
- 'l-cdata' => Array(
- 'TableName' => TABLE_PREFIX.'LinkCustomData',
- 'ParentPrefix' => 'l',
- ),
-
- 'n-cdata' => Array(
- 'TableName' => TABLE_PREFIX.'NewsCustomData',
- 'ParentPrefix' => 'n',
- ),
-
- 'bb-cdata' => Array(
- 'TableName' => TABLE_PREFIX.'TopicCustomData',
- 'ParentPrefix' => 'bb',
- ),
-
- 'p-cdata' => Array(
- 'TableName' => TABLE_PREFIX.'ProductsCustomData',
- 'ParentPrefix' => 'p',
- ),
- ),
-
- 'QueryString' => Array(
- 1 => 'id',
- 2 => 'event',
- ),
-
- '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,
-
- 'Hooks' => Array(
- Array(
- 'Mode' => hAFTER,
- 'Conditional' => false,
- 'HookToPrefix' => '#PARENT#', //self
- 'HookToSpecial' => '*',
- 'HookToEvent' => Array('OnAfterConfigRead'),
- 'DoPrefix' => '',
- 'DoSpecial' => '',
- 'DoEvent' => 'OnCreateCustomFields',
- ),
- ),
-
- 'IDField' => 'CustomDataId',
-
- 'ParentTableKey' => 'ResourceId',
- 'ForeignKey' => 'ResourceId',
- 'AutoDelete' => true,
- 'AutoClone' => false,
-
- 'CalculatedFields' => Array(
- '' => Array(),
- ),
-
- 'ListSQLs' => Array('' => 'SELECT %1$s.* %2$s FROM %1$s'),
- 'ItemSQLs' => Array('' => 'SELECT %1$s.* %2$s FROM %1$s'),
-
- 'Fields' => Array(
- 'CustomDataId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
- 'ResourceId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
- ),
- );
+ $config = Array (
+ 'Prefix' => 'cdata',
+ 'QueryString' => Array (
+ 1 => 'id',
+ 2 => 'event',
+ ),
+
+ 'ItemClass' => Array ('class' => 'kDBItem', 'file' => '', 'build_event' => 'OnItemBuild'),
+ 'ListClass' => Array('class' => 'kDBList', 'file' => '', 'build_event' => 'OnListBuild'),
+ 'EventHandlerClass' => Array('class' => 'CustomDataEventHandler', 'file' => 'custom_data_event_handler.php', 'build_event' => 'OnBuild'),
+ 'TagProcessorClass' => Array('class' => 'kDBTagProcessor', 'file' => '', 'build_event' => 'OnBuild'),
+ 'AutoLoad' => true,
+
+ 'IDField' => 'CustomDataId',
+
+ 'ParentTableKey' => 'ResourceId',
+ 'ForeignKey' => 'ResourceId',
+ 'AutoDelete' => true,
+ 'AutoClone' => false,
+
+ 'CalculatedFields' => Array (
+ '' => Array(),
+ ),
+
+ 'ListSQLs' => Array('' => 'SELECT %1$s.* %2$s FROM %1$s'),
+ 'ItemSQLs' => Array('' => 'SELECT %1$s.* %2$s FROM %1$s'),
+
+ 'Fields' => Array (
+ 'CustomDataId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
+ 'ResourceId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
+ ),
+ );
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.10.2/core/units/custom_data/custom_data_config.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.10.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.31.2/core/units/languages/languages_event_handler.php
===================================================================
--- branches/unlabeled/unlabeled-1.31.2/core/units/languages/languages_event_handler.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.31.2/core/units/languages/languages_event_handler.php (revision 8242)
@@ -1,461 +1,461 @@
<?php
class LanguagesEventHandler extends kDBEventHandler
{
/**
* Allows to override standart permission mapping
*
*/
function mapPermissions()
{
parent::mapPermissions();
$permissions = Array(
'OnChangeLanguage' => 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
+ * [HOOK] Updates table structure on new language adding/removing language
*
* @param kEvent $event
*/
- function OnReflectMultiLingualFields($event)
+ function OnReflectMultiLingualFields(&$event)
{
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
-
- $this->Application->UnitConfigReader->includeConfigFiles(MODULES_PATH); //make sure to re-read all configs
- $this->Application->UnitConfigReader->AfterConfigRead();
+ /* @var $ml_helper kMultiLanguageHelper */
+
+ $this->Application->UnitConfigReader->ReReadConfigs();
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, 'prefix:phrases');
$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, 'prefix:emailmessages');
$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->getUnitOption($event->Prefix, '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');
/* @var $lang_xml LangXML_Parser */
$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';
}
function OnScheduleTopFrameReload(&$event)
{
$this->Application->StoreVar('RefreshTopFrame',1);
}
/**
* Do now allow deleting current language
*
* @param kEvent $event
*/
function OnBeforeItemDelete(&$event)
{
$del_id = $event->getEventParam('id');
$object =& $event->getObject(array('skip_autload' => true));
$object->Load($del_id);
if ($object->GetDBField('PrimaryLang') || $del_id == $this->Application->GetVar('m_lang')) {
$event->status = erFAIL;
}
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.31.2/core/units/languages/languages_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.31
\ No newline at end of property
+1.31.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.48.2/admin/install/install_lib.php
===================================================================
--- branches/unlabeled/unlabeled-1.48.2/admin/install/install_lib.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.48.2/admin/install/install_lib.php (revision 8242)
@@ -1,1166 +1,1166 @@
<?php
function minimum_php_version( $vercheck )
{
$minver = explode(".", $vercheck);
$curver = explode(".", phpversion());
if (($curver[0] < $minver[0])
|| (($curver[0] == $minver[0])
&& ($curver[1] < $minver[1]))
|| (($curver[0] == $minver[0]) && ($curver[1] == $minver[1])
&& ($curver[2][0] < $minver[2][0])))
return false;
else
return true;
}
function VersionSort($a, $b)
{
if( preg_match('/inportal_upgrade_v(.*).(php|sql)$/', $a, $rets) )
{
$a_version = $rets[1];
$a_extension = $rets[2];
}
if( preg_match('/inportal_upgrade_v(.*).(php|sql)$/', $b, $rets) )
{
$b_version = $rets[1];
$b_extension = $rets[2];
}
if( !isset($a_version) || !isset($b_version) ) return 0; // not php or sql file
if($a_version == $b_version) // got PHP and SQL file for one version
{
if($a_extension == $b_extension)
{
return 0;
}
else
{
return ($a_extension == 'php') ? 1 : -1; // this makes .php extension go AFTER .sql in the sorting
}
}
else
{
return (ConvertVersion($a_version) < ConvertVersion($b_version)) ? -1 : 1;
}
}
function GetMaxPortalVersion($admindirname)
{
$dir = @dir($admindirname.'/install/upgrades');
if (!$dir) return '';
$upgrades_arr = Array();
$version = '';
while($file = $dir->read())
{
if ($file != "." && $file != ".." && !is_dir($admindirname.$file))
{
if (strstr($file, 'inportal_upgrade_v')) $upgrades_arr[] = $file;
}
}
usort($upgrades_arr, "VersionSort");
foreach($upgrades_arr as $file)
{
if( preg_match('/inportal_upgrade_v(.*).(php|sql)$/', $file, $rets) )
{
$a_version = $rets[1];
if (ConvertVersion($a_version) > ConvertVersion($version)) {
$version = $a_version;
}
}
}
return $version;
}
function ConvertVersion($version)
{
$parts = explode('.', $version);
$bin = '';
foreach ($parts as $part) {
$bin .= str_pad(decbin($part), 8, '0', STR_PAD_LEFT);
}
$dec = bindec($bin);
return $dec;
}
function TableExists(&$ado, $tables)
{
global $g_TablePrefix;
$t = explode(",",$tables);
$i = $ado->MetaTables();
for($x=0;$x<count($i);$x++)
$i[$x] = strtolower($i[$x]);
$AllFound = TRUE;
for($tIndex=0;$tIndex<count($t);$tIndex++)
{
$table = $g_TablePrefix.$t[$tIndex];
$table = strtolower($table);
if(!in_array($table,$i))
{
$AllFound = FALSE;
}
}
return $AllFound;
}
function set_ini_value($section, $key, $newvalue)
{
global $ini_vars;
$ini_vars[$section][$key] = $newvalue;
}
function save_values()
{
// Should write something to somwere, but it doesn't :(
global $ini_file,$ini_vars;
//if( file_exists($ini_file) )
//{
$fp = fopen($ini_file, "w");
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($ini_vars as $secname => $section)
{
fwrite($fp,"[".$secname."]\n");
foreach($section as $key => $value) fwrite($fp,"$key = \"$value\"\n");
fwrite($fp,"\n");
}
fclose($fp);
//}
}
function getConnectionInterface($action, $dbo_type='adodb')
{
if($dbo_type == 'adodb')
{
switch($action)
{
case 'query': return 'Execute'; break;
case 'errorno': return 'ErrorNo'; break;
case 'errormsg': return 'ErrorMsg'; break;
}
}
if($dbo_type == 'dbconnection')
{
switch($action)
{
case 'query': return 'Query'; break;
case 'errorno': return 'getErrorCode'; break;
case 'errormsg': return 'getErrorMsg'; break;
}
}
}
function RunSchemaFile(&$ado, $filename, $dbo_type='adodb')
{
if( file_exists($filename) )
{
$sql = file_get_contents($filename);
if($sql) RunSchemaText($ado,$sql,$dbo_type);
}
}
function RunSchemaText(&$ado, $sql, $dbo_type='adodb')
{
global $g_TablePrefix;
if(strlen($g_TablePrefix))
{
$what = "CREATE TABLE ";
$replace = "CREATE TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "DROP TABLE ";
$replace = "DROP TABLE IF EXISTS ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "INSERT INTO ";
$replace = "INSERT INTO ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "UPDATE ";
$replace = "UPDATE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "ALTER TABLE ";
$replace = "ALTER TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
}
$commands = explode("# --------------------------------------------------------",$sql);
if(count($commands)>0)
{
$query_func = getConnectionInterface('query',$dbo_type);
$errorno_func = getConnectionInterface('errorno',$dbo_type);
$errormsg_func = getConnectionInterface('errormsg',$dbo_type);
for($i = 0; $i < count($commands); $i++)
{
$cmd = $commands[$i];
$cmd = trim($cmd);
if(strlen($cmd)>0)
{
$ado->$query_func($cmd);
if($ado->$errorno_func() != 0)
{
$db_error = $ado->$errormsg_func()." COMMAND:<PRE>$cmd</PRE>";
}
}
}
}
}
function RunSQLText(&$ado, $allsql, $dbo_type='adodb')
{
global $g_TablePrefix;
$line = 0;
$query_func = getConnectionInterface('query',$dbo_type);
$errorno_func = getConnectionInterface('errorno',$dbo_type);
$errormsg_func = getConnectionInterface('errormsg',$dbo_type);
while($line<count($allsql))
{
$sql = $allsql[$line];
if(strlen(trim($sql))>0 && substr($sql,0,1)!="#")
{
if(strlen($g_TablePrefix))
{
$what = "CREATE TABLE ";
$replace = "CREATE TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "DELETE FROM ";
$replace = "DELETE FROM ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "DROP TABLE ";
$replace = "DROP TABLE IF EXISTS ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "DROP TABLE IF EXISTS ";
$replace = "DROP TABLE IF EXISTS ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "INSERT INTO ";
$replace = "INSERT INTO ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "UPDATE ";
$replace = "UPDATE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
$what = "ALTER TABLE ";
$replace = "ALTER TABLE ".$g_TablePrefix;
$sql = ereg_replace($what, $replace, $sql);
}
$sql = trim($sql);
if(strlen($sql)>0)
{
$ado->$query_func($sql);
if($ado->$errorno_func()!=0)
{
$db_error = $ado->$errormsg_func()." COMMAND:<PRE>$sql</PRE>";
$error = TRUE;
}
}
}
$line++;
}
}
function RunSQLFile(&$ado, $filename, $dbo_type='adodb')
{
if(file_exists($filename))
{
$allsql = file($filename);
RunSQLText($ado,$allsql,$dbo_type);
}
}
/**
* Executes all sqls in selected file (in K4 style)
*
* @param string $filename
* @param kDBConnection $db
* @param mixed $replace_from
* @param mixed $replace_to
*/
function K4_RunSQL($filename, $replace_from = null, $replace_to = null)
{
if (!file_exists(FULL_PATH.$filename)) {
return ;
}
$db =& inst_GetADODBConnection(true);
$sqls = file_get_contents(FULL_PATH.$filename);
// add prefix to all tables
if (strlen(TABLE_PREFIX) > 0) {
$replacements = Array ('CREATE TABLE ', 'INSERT INTO ', 'UPDATE ', 'ALTER TABLE ');
foreach ($replacements as $replacement) {
$sqls = str_replace($replacement, $replacement.TABLE_PREFIX, $sqls);
}
$sqls = str_replace('DROP TABLE ', 'DROP TABLE IF EXISTS '.TABLE_PREFIX, $sqls);
}
if (isset($replace_from) && isset($replace_to)) {
// replace something additionally, e.g. module root category
$sqls = str_replace($replace_from, $replace_to, $sqls);
}
$sqls = str_replace("\r\n", "\n", $sqls); // convert to linux line endings
- $sqls = preg_replace("/#(.*?)\n/", '', $sqls); // remove all comments
+ $sqls = preg_replace("/#([^;]*?)\n/", '', $sqls); // remove all comments
$sqls = explode(";\n", $sqls);
foreach ($sqls as $sql) {
$sql = trim($sql);
if (!$sql) {
continue; // usually last line
}
$db->Query($sql);
if ($db->getErrorCode() != 0) {
$db_error = $db->getErrorMsg()." COMMAND:<PRE>$sql</PRE>";
$error = true;
// break;
}
}
}
/**
* Sets module version to passed
*
* @param string $module_name
* @param string $version
*/
function K4_SetModuleVersion($module_name, $version = false)
{
if ($version === false) {
$version = K4_GetMaxModuleVersion($module_name);
}
$sql = 'UPDATE '.TABLE_PREFIX.'Modules
SET Version = "'.$version.'"
WHERE Name = "'.$module_name.'"';
$db =& inst_GetADODBConnection(true);
$db->Query($sql);
}
function K4_GetMaxModuleVersion($module_name)
{
define('UPGRADES_FILE', FULL_PATH.'/%sinstall/upgrades.sql');
define('VERSION_MARK', '# ===== v ([\d]+\.[\d]+\.[\d]+) =====');
$upgrades_file = sprintf(UPGRADES_FILE, strtolower($module_name).'/');
if (!file_exists($upgrades_file)) {
// no upgrade file
return '4.0.1';
}
$sqls = file_get_contents($upgrades_file);
$versions_found = preg_match_all('/'.VERSION_MARK.'/s', $sqls, $regs);
if (!$versions_found) {
// upgrades file doesn't contain version definitions
return '4.0.1';
}
return end($regs[1]);
}
function RunRestoreFile($ado,$filename,$FileOffset,$MaxLines)
{
$size = filesize($filename);
if($FileOffset > $size)
return -2;
$fp = fopen($filename,"r");
if(!$fp)
return -1;
if($FileOffset>0)
{
fseek($fp,$FileOffset);
}
else
{
$EndOfSQL = FALSE;
$sql = "";
while(!feof($fp) && !$EndOfSQL)
{
$l = fgets($fp,16384);
if(substr($l,0,11)=="INSERT INTO")
{
$EndOfSQL = TRUE;
}
else
{
$sql .= $l;
$FileOffset = ftell($fp) - strlen($l);
}
}
if(strlen($sql))
{
RunSchemaText($ado,$sql);
}
fseek($fp,$FileOffset);
}
$LinesRead = 0;
$sql = "";
$AllSql = array();
while($LinesRead < $MaxLines && !feof($fp))
{
$sql = fgets($fp, 16384);
if(strlen($sql))
{
$AllSql[] = $sql;
$LinesRead++;
}
}
if(!feof($fp))
{
$FileOffset = ftell($fp);
}
else
{
$FileOffset = $TotalSize;
}
fclose($fp);
if(count($AllSql)>0)
RunSQLText($ado,$AllSql);
return (int)$FileOffset;
}
function _inst_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 _inst_decrypt($txt,$key)
{
$txt = _inst_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 inst_LoadFromRemote()
{
return "";
}
function mod_DLid()
{
global $DownloadId;
echo $DownloadId."\n";
die();
}
function ae666b1b8279502f4c4b570f133d513e($LoadRemote=FALSE,$file="")
{
return _inst_LoadLicense($LoadRemote,$file);
}
function _inst_LoadLicense($LoadRemote=FALSE,$file="")
{
global $path,$admin;
$data = Array();
if(!strlen($file))
{
$f = $path.$admin."/include/inportal.dat";
}
else
$f = $file;
if(file_exists($f))
{
$contents = file($f);
$data[0] = base64_decode($contents[1]);
$data[1] = $contents[2];
}
else
if($LoadRemote)
return $LoadFromRemote;
return $data;
}
function inst_SaveLicense($data)
{
}
function _inst_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 a83570933e44bc66b31dd7127cf3f23a($txt)
{
return _inst_ParseLicense($txt);
}
function _inst_ParseLicense($txt)
{
global $i_User, $i_Pswd, $i_Keys;
$data = _inst_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(_inst_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 de3ec1b7a142cccd0d51f03d24280744($domain)
{
_inst_falseIsLocalSite($domain);
return _inst_IsLocalSite($domain);
}
function _inst_GetObscureValue($i)
{
$z = null;
if ($i == 'x') return 0254;
if ($i == 'z') return 0x7F.'.';
if ($i >= 5 && $i < 7) return _inst_GetObscureValue($z)*_inst_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 '.'.(_inst_GetObscureValue(6.5)+1);
if ($i == 'a') return 0xa;
}
function _inst_Chr($val)
{
$x = _inst_GetObscureValue(25);
$f = chr($x).chr($x+5).chr($x+15);
return $f($val);
}
function _inst_IsLocalSite($domain)
{
$yy = '';
$ee = _inst_GetObscureValue(35);
foreach ($ee as $e) {
$yy .= _inst_Chr($e);
}
$localb = FALSE;
if(substr($domain,0,3)==_inst_GetObscureValue('x'))
{
$b = substr($domain,0,6);
$p = explode(".",$domain);
$subnet = $p[1];
if($p[1]>15 && $p[1]<32)
$localb=TRUE;
}
$zz = _inst_GetObscureValue('z')._inst_GetObscureValue(5).'.'.(int)_inst_GetObscureValue(7)._inst_GetObscureValue(12);
$ff = _inst_GetObscureValue('z')+65;
$hh = $ff-0x18;
if($domain==$yy || $domain==$zz || substr($domain,0,7)==$ff._inst_Chr(46).$hh ||
substr($domain,0,3)==_inst_GetObscureValue('a')._inst_Chr(46) || $localb || strpos($domain,".")==0)
{
return TRUE;
}
return FALSE;
}
function _inst_falseIsLocalSite($domain)
{
$localb = FALSE;
if(substr($domain,0,3)=="172" || $domain == '##code##')
{
$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;
}
function ed592fe427e1ce60e32ffcb0c82d8557($name)
{
return _inst_ModuleLicensed($name);
}
function _inst_ModuleLicensed($name)
{
global $i_Keys, $objConfig, $g_License, $g_Domain;
$lic = base64_decode($g_License);
_inst_ParseLicense($lic);
$modules = array();
if(!_inst_IsLocalSite($g_Domain))
{
for($x=0;$x<count($i_Keys);$x++)
{
$key = $i_Keys[$x];
if (strlen(stristr($g_Domain,$key["domain"])))
{
$modules = explode(",",strtolower($key["mod"]));
}
}
if(in_array(strtolower($name),$modules))
{
return TRUE;
}
else
{
return FALSE;
}
}
else
return TRUE;
return FALSE;
}
function inst_parse_portal_ini($file, $parse_section = false) {
if(!file_exists($file) && !is_readable($file))
die("Could Not Open Ini File $file");
$contents = file($file);
$retval = array();
$section = '';
$ln = 1;
$resave = false;
foreach($contents as $line) {
if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
$resave = true;
}
$ln++;
$line = trim($line);
$line = eregi_replace(';[.]*','',$line);
if(strlen($line) > 0) {
if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
$section = substr($line,1,(strlen($line)-2));
if ($parse_section) {
$retval[$section] = array();
}
continue;
} elseif(eregi('=',$line)) {
list($key,$val) = explode(' = ',$line);
if (!$parse_section) {
$retval[trim($key)] = str_replace('"', '', $val);
}
else {
$retval[$section][trim($key)] = str_replace('"', '', $val);
}
} //end if
} //end if
} //end foreach
if ($resave) {
$fp = fopen($file, "w");
reset($contents);
fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
foreach($contents as $line) fwrite($fp,"$line");
fclose($fp);
}
return $retval;
}
function a48d819089308a9aeb447e7248b2587f()
{
return _inst_GetModuleList();
}
function _inst_GetModuleList()
{
global $rootpath,$pathchar,$admin, $pathtoroot;
$path = $pathtoroot;
$new = array();
if ($dir = @opendir($path))
{
while (($file = readdir($dir)) !== false)
{
if($file !="." && $file !=".." && substr($file,0,1)!="_")
{
if(is_dir($path."/".$file))
{
$ModuleAdminDir = $path.$file.'/admin/';
$inst_file = $ModuleAdminDir.'install.php';
if( file_exists($inst_file) && file_exists($ModuleAdminDir.'install/inportal_schema.sql') )
{
if(_inst_ModuleLicensed($file)) {
$new[$file] = $inst_file;
}
}
}
}
}
closedir($dir);
}
return array_keys($new);
}
function GetDirList ($dirName)
{
$filedates = array();
$d = dir($dirName);
while($entry = $d->read())
{
if ($entry != "." && $entry != "..")
{
if (!is_dir($dirName."/".$entry))
{
$filedate[]=$entry;
}
}
}
$d->close();
return $filedate;
}
function GetLanguageList()
{
global $pathtoroot, $admin;
$packs = array();
$dir = $pathtoroot.$admin."/install/langpacks";
$files = GetDirList($dir);
if(is_array($files))
{
foreach($files as $f)
{
$p = pathinfo($f);
if($p["extension"]=="lang")
{
$packs[] = $f;
}
}
}
return $packs;
}
function section_header($title, $return_result = false)
{
$ret = '<table border="0" cellpadding="2" cellspacing="0" class="tableborder_full" width="100%" height="30">'.
'<tr><td class="tablenav" width="580" nowrap background="images/tabnav_left.jpg"><span class="tablenav_link">&nbsp;'.$title.'</span>'.
'</td><td align="right" class="tablenav" background="images/tabnav_back.jpg" width="100%">'.
"<a class=\"link\" onclick=\"ShowHelp('in-portal:install');\"><img src=\"images/blue_bar_help.gif\" border=\"0\"></A>".
'</td></tr></table>';
if( $return_result )
return $ret;
else
echo $ret;
}
function &VerifyDB($error_state, $next_state, $success_func = null, $db_must_exist = false)
{
// perform various check type to database specified
// 1. user is allowed to connect to database
// 2. user has all types of permissions in database
global $state, $db_error;
// enshure we use data from post & not from config
$GLOBALS['g_DBType'] = $_POST["ServerType"];
$GLOBALS['g_DBHost'] = $_POST["ServerHost"];
$GLOBALS['g_DBName'] = $_POST["ServerDB"];
$GLOBALS['g_DBUser'] = $_POST["ServerUser"];
$GLOBALS['g_DBUserPassword'] = $_POST["ServerPass"];
if (strlen($_POST['TablePrefix']) > 7) {
$db_error = 'Table prefix should not be longer than 7 characters';
$state = $error_state;
return false;
}
// connect to database
$ado =& inst_GetADODBConnection();
if($ado->ErrorNo() != 0)
{
// was error while connecting
$db_error = "Connection Error: (".$ado->ErrorNo().") ".$ado->ErrorMsg();
$state = $error_state;
}
elseif( $ado->ErrorNo() == 0 )
{
// if connected, then check if all sql statements work
$test_result = 1;
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
$sql_tests[] = 'CREATE TABLE test_table(test_col mediumint(6))';
$sql_tests[] = 'LOCK TABLES test_table WRITE';
$sql_tests[] = 'INSERT INTO test_table(test_col) VALUES (5)';
$sql_tests[] = 'UPDATE test_table SET test_col = 12';
$sql_tests[] = 'UNLOCK TABLES';
$sql_tests[] = 'ALTER TABLE test_table ADD COLUMN new_col varchar(10)';
$sql_tests[] = 'SELECT * FROM test_table';
$sql_tests[] = 'DELETE FROM test_table';
$sql_tests[] = 'DROP TABLE IF EXISTS test_table';
foreach($sql_tests as $sql_test)
{
$ado->Execute($sql_test);
if( $ado->ErrorNo()!=0 )
{
$test_result = 0;
break;
}
}
if($test_result == 1)
{
// if statements work & connection made, then check table existance
$db_exists = TableExists($ado,"ConfigurationAdmin,Category,Permissions");
if($db_exists != $db_must_exist)
{
$state = $error_state;
$db_error = $db_must_exist ? 'An In-Portal Database already exists at this location' : 'An In-Portal Database was not found at this location';
}
else
{
$state = $next_state;
if( isset($success_func) ) $success_func();
}
}
else
{
// user has insufficient permissions in database specified
$db_error = "Permission Error: (".$ado->ErrorNo().") ".$ado->ErrorMsg();
$state = $error_state;
}
}
return $ado;
}
function SaveDBConfig()
{
// save new database configuration
set_ini_value("Database", "DBType",$_POST["ServerType"]);
set_ini_value("Database", "DBHost",$_POST["ServerHost"]);
set_ini_value("Database", "DBName",$_POST["ServerDB"]);
set_ini_value("Database", "DBUser",$_POST["ServerUser"]);
set_ini_value("Database", "DBUserPassword",$_POST["ServerPass"]);
set_ini_value("Database","TablePrefix",$_POST["TablePrefix"]);
save_values();
$GLOBALS['include_file'] = 'install/install_finish.php';
}
function ReSetVar($var)
{
// define varible if not defined before
if( !isset($GLOBALS[$var]) ) $GLOBALS[$var] = '';
}
// if globals.php not yet included (1st steps of install),
// then define GetVar function
if( !function_exists('GetVar') )
{
function GetVar($name, $post_priority = false)
{
if(!$post_priority) // follow gpc_order in php.ini
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
else // get variable from post 1stly if not found then from get
return isset($_POST[$name]) && $_POST[$name] ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );
}
}
function RadioChecked($name, $value)
{
// return " checked" word in case if radio is checked
$submit_value = GetVar($name);
return $submit_value == $value ? ' checked' : '';
}
function StripDisallowed($string, $item_info)
{
$not_allowed = Array( ' ', '\\', '/', ':', '*', '?', '"', '<', '>', '|',
'~', '!', '@', '#', '$', '%', '^', '&', '(', ')',
'+', '=', '-', '{', '}', ']', '[', "'", ';', '.', ',');
$string = str_replace($not_allowed, '_', $string);
$string = preg_replace('/(_+)/', '_', $string);
$string = checkAutoFilename($string, $item_info);
return $string;
}
function checkAutoFilename($filename, $item_info)
{
// 'table' => 'Category', 'id_field' => 'CategoryId', 'title_field' => 'Name'
$item_id = $item_info['item_id'];
$prefix = GetTablePrefix();
$db =& inst_GetADODBConnection();
$sql = 'SELECT '.$item_info['id_field'].' FROM '.$prefix.$item_info['table'].' WHERE Filename = '.$db->qstr($filename);
$found_item_id = $db->GetOne($sql);
$has_page = preg_match('/(.*)_([\d]+)([a-z]*)$/', $filename, $rets);
if( ($found_item_id != $item_id) || $has_page ) // other category has same filename as ours OR we have filename, that ends with _number
{
$append = $found_item_id ? 'a' : '';
if($has_page)
{
$filename = $rets[1].'_'.$rets[2];
$append = $rets[3] ? $rets[3] : 'a';
}
$sql = 'SELECT '.$item_info['id_field'].' FROM '.$prefix.$item_info['table'].' WHERE (Filename = %s) AND ('.$item_info['id_field'].' != '.$item_id.')';
while ( $db->GetOne( sprintf($sql, $db->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;
}
/**
* [INSTALL] Perform operations required for each module separate install (from admin)
*
* @param string $module_name
* @param bool $has_theme
* @return bool
*/
function finalizeModuleInstall($module_name, $has_theme = true)
{
global $objThemes;
$app =& kApplication::Instance();
if (!$app->GetVar('redirect')) return false;
if ($has_theme)
{
$objThemes->CreateMissingThemes(true);
}
// 2. import languagepack in case of separate install
$lang_xml =& $app->recallObject('LangXML');
$lang_xml->tables['phrases'] = TABLE_PREFIX.'Phrase';
$lang_xml->tables['emailmessages'] = TABLE_PREFIX.'EmailMessage';
$lang_path = FULL_PATH.'/'.$module_name.'/admin/install/langpacks';
$lang_xml->Parse($lang_path.'/english.lang', '|0|1|2|', '');
$app->Redirect('in-portal/modules/modules_list', Array('pass' => 'all', 'admin' => 1, 'RefreshTree' => 1), '', 'index.php');
}
/**
* [UPGRADE] Initializes [cached] category/item templates with default values for each module
*
* @param string $module
* @param string $category_template
* @param string $item_template
*/
function updateItemCategoryTemplate($module, $category_template, $item_template)
{
$table_prefix = GetTablePrefix();
$inst_ado =& inst_GetADODBConnection();
// get module root category by module name
$sql = 'SELECT RootCat
FROM '.$table_prefix.'Modules
WHERE Name = '.$inst_ado->qstr($module);
$module_root = $inst_ado->GetOne($sql);
// set category & item template to module root category
$sql = 'UPDATE '.$table_prefix.'Category
SET CategoryTemplate = '.$inst_ado->qstr($category_template).'
WHERE CategoryId = '.$module_root;
$inst_ado->Execute($sql);
// set cached category & item templates to all sub-categories of module root category
$sql = 'UPDATE '.$table_prefix.'Category
SET CachedCategoryTemplate = '.$inst_ado->qstr($category_template).'
WHERE ParentPath LIKE "|'.$module_root.'|%';
$inst_ado->Execute($sql);
}
/**
* [UPGRADE] Moves custom field values for prefix specified from CustomMetaData table to prefix dependant separate table
*
* @param string $prefix
*/
function convertCustomFields($prefix)
{
$application =& kApplication::Instance();
$ml_helper =& $application->recallObject('kMultiLanguageHelper');
$ml_helper->createFields($prefix.'-cdata', true);
$db =& $application->GetADODBConnection();
$custom_fields = $application->getUnitOption($prefix, 'CustomFields');
if (!$custom_fields) {
return true;
}
$custom_table = $application->getUnitOption($prefix.'-cdata', 'TableName');
// copy value from Value field to l<lang_id>_Value field, where destination field is empty
$m_lang = $application->GetVar('m_lang');
$sql = 'UPDATE '.TABLE_PREFIX.'CustomMetaData
SET l'.$m_lang.'_Value = Value
WHERE LENGTH(l'.$m_lang.'_Value) = 0';
$db->Query($sql);
$i = 1;
$field_mask = '';
$language_count = $ml_helper->getLanguageCount();
while ($i <= $language_count) {
$field_mask .= 'cdata%1$s.l'.$i.'_Value AS l'.$i.'_cust_%1$s, ';
$i++;
}
$field_mask = preg_replace('/(.*), $/', '\\1', $field_mask);
$join_mask = 'LEFT JOIN '.TABLE_PREFIX.'CustomMetaData cdata%1$s ON main_table.ResourceId = cdata%1$s.ResourceId AND cdata%1$s.CustomFieldId = %1$s';
$fields_sql = Array();
$joins_sql = Array();
foreach ($custom_fields as $custom_id => $custom_name) {
array_push($fields_sql, sprintf($field_mask, $custom_id) );
array_push($joins_sql, sprintf($join_mask, $custom_id));
}
$sql = 'INSERT INTO '.$custom_table.'
SELECT 0 AS CustomDataId, main_table.ResourceId, '.implode(', ', $fields_sql).'
FROM '.$application->getUnitOption($prefix, 'TableName').' main_table '.implode(' ', $joins_sql);
$db->Query($sql);
}
/**
* [INSTALL] Link custom field records with search config records + create custom field columns
*
* @param string $module_name
* @param int $item_type
*/
function linkCustomFields($module_name, $prefix, $item_type)
{
$application =& kApplication::Instance();
$db =& $application->GetADODBConnection();
$sql = 'SELECT FieldName, CustomFieldId
FROM '.TABLE_PREFIX.'CustomField
WHERE Type = '.$item_type.' AND IsSystem = 0'; // config is not read here yet :( $application->getUnitOption('p', 'ItemType');
$custom_fields = $db->GetCol($sql, 'CustomFieldId');
foreach ($custom_fields as $cf_id => $cf_name) {
$sql = 'UPDATE '.TABLE_PREFIX.'SearchConfig
SET CustomFieldId = '.$cf_id.'
WHERE (TableName = "CustomField") AND (LOWER(ModuleName) = "'.strtolower($module_name).'") AND (FieldName = '.$db->qstr($cf_name).')';
$db->Query($sql);
}
$application->refreshModuleInfo(); // this module configs are now processed
// because of configs was read only from installed before modules (in-portal), then reread configs
$unit_config_reader =& $application->recallObject('kUnitConfigReader');
$unit_config_reader->scanModules(MODULES_PATH.'/'.strtolower($module_name));
// create correct columns in ProductsCustomData table
$ml_helper =& $application->recallObject('kMultiLanguageHelper');
$ml_helper->createFields($prefix.'-cdata', true);
}
function moveItemTemplatesToCustom($module_name, $prefix)
{
$application =& kApplication::Instance();
$root_parent_path = $application->Conn->GetOne(
'SELECT ParentPath FROM '.TABLE_PREFIX.'Category
WHERE CategoryId = '.$application->ModuleInfo[$module_name]['RootCat']);
$item_t_customfield = $application->Conn->GetOne('SELECT CustomFieldId FROM '.TABLE_PREFIX.'CustomField WHERE FieldName = \''.$prefix.'_ItemTemplate\'');
$item_t_customfield = 'l1_cust_'.$item_t_customfield;
$current_item_tpls = $application->Conn->Query(
'SELECT ResourceId, ItemTemplate FROM '.TABLE_PREFIX.'Category
WHERE ParentPath LIKE "'.$root_parent_path.'%" AND ItemTemplate != "" AND ItemTemplate IS NOT NULL');
foreach ($current_item_tpls as $a_cat) {
$has_cdata = $application->Conn->GetOne(
'SELECT CustomDataId FROM '.TABLE_PREFIX.'CategoryCustomData
WHERE ResourceId = '.$a_cat['ResourceId']);
if (!$has_cdata) {
$query = 'INSERT INTO '.TABLE_PREFIX.'CategoryCustomData (ResourceId) VALUES ('.$a_cat['ResourceId'].')';
$application->Conn->Query($query);
}
$query = 'UPDATE '.TABLE_PREFIX.'CategoryCustomData
SET '.$item_t_customfield.' = '.$application->Conn->qstr($a_cat['ItemTemplate']).'
WHERE ResourceId = '.$a_cat['ResourceId'];
$application->Conn->Query($query);
}
}
?>
Property changes on: branches/unlabeled/unlabeled-1.48.2/admin/install/install_lib.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.48
\ No newline at end of property
+1.48.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.16.2/core/units/custom_fields/custom_fields_event_handler.php
===================================================================
--- branches/unlabeled/unlabeled-1.16.2/core/units/custom_fields/custom_fields_event_handler.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.16.2/core/units/custom_fields/custom_fields_event_handler.php (revision 8242)
@@ -1,143 +1,149 @@
<?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();
$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) {
$object->addFilter('itemtype_filter', '%1$s.Type = '.$item_type);
}
if (!($this->Application->isDebugMode() && $this->Application->IsAdmin())) {
$object->addFilter('user_filter', '%1$s.IsSystem = 0');
}
}
/**
* 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'));
- $this->Application->HandleEvent( new kEvent($main_prefix.'-cdata:OnCreateCustomFields') );
-
$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'));
}
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.16.2/core/units/custom_fields/custom_fields_event_handler.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.16
\ No newline at end of property
+1.16.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.105.2/kernel/parser.php
===================================================================
--- branches/unlabeled/unlabeled-1.105.2/kernel/parser.php (revision 8241)
+++ branches/unlabeled/unlabeled-1.105.2/kernel/parser.php (revision 8242)
@@ -1,3844 +1,3843 @@
<?php
$ItemTypes["category"]=1;
$ItemTables[1] = "Category";
$ParserFiles[] = "kernel/parser.php";
function m_ParseEnv($str = NULL)
{
global $m_var_list, $objConfig, $objCatList, $objLanguages, $objThemes;
if ($str != NULL)
{
$str = substr($str,1);
$pieces = explode("-", $str);
//echo "<PRE>";print_r($pieces);echo "</PRE>";
$m_var_list["cat"] = $pieces[0];
$m_var_list["p"] = $pieces[1];
$objCatList->Page = $m_var_list["p"];
$m_var_list["lang"] = $pieces[2];
$m_var_list["theme"] = $pieces[3];
$m_var_list['opener']=$pieces[4];
$m_var_list['wid']=$pieces[5];
}
else
{
$m_var_list["cat"]=0;
$m_var_list["p"] = 1;
$m_var_list["lang"] = $objLanguages->GetPrimary();
$m_var_list["theme"]= $objThemes->GetPrimaryTheme();
$m_var_list['opener']='s';
$m_var_list['wid']='';
}
}
function m_BuildEnv()
{
global $m_var_list, $m_var_list_update;
$module_vars = Array('cat','p','lang','theme','opener','wid');
$ret = GenerateModuleEnv('m', $module_vars);
if( isset($GLOBALS['m_var_list_update']['cat']) ) unset($GLOBALS['m_var_list_update']['cat']);
return $ret;
}
function m_BuildEnv_NEW()
{
global $m_var_list, $m_var_list_update;
$module_vars = Array( 'cat' => 'm_cat_id', 'p' => 'm_cat_page', 'lang' => 'm_lang',
'theme' => 'm_theme', 'opener' => 'm_opener','wid' => 'm_wid');
$pass_cat = 0;
if (isset($m_var_list_update['cat'])) {
$pass_cat = 1;
}
$ret = GenerateModuleEnv_NEW('m', $module_vars);
if ($pass_cat) {
$ret['pass_category'] = 1;
}
if( isset($GLOBALS['m_var_list_update']['cat']) ) unset($GLOBALS['m_var_list_update']['cat']);
return $ret;
}
function m_GetVar($name)
{
// get variable from template variable's list
global $m_var_list, $m_var_list_update;
return isset($m_var_list_update[$name]) ? $m_var_list_update[$name] : $m_var_list[$name];
}
function LoadRelatedItems(&$Relations,&$RelatedItems,$ResourceId)
{
global $objItemTypes;
if(!is_object($Relations))
{
$Relations = new clsRelationshipList();
}
//$Relations->debuglevel = 2;
if ($ResourceId != '') {
$sql = sprintf("SELECT RelationshipId, Type, Enabled, Priority,
IF(TargetId = %1\$s, TargetId, SourceId) AS SourceId,
IF(TargetId = %1\$s, SourceId, TargetId) AS TargetId,
IF(TargetId = %1\$s, TargetType, SourceType) AS SourceType,
IF(TargetId = %1\$s, SourceType, TargetType) AS TargetType
FROM %%s", $ResourceId);
$where = "((SourceId=$ResourceId) OR (TargetId=$ResourceId AND Type=1)) AND Enabled=1";
$Relations->LoadRelated($where,"",$sql);
$ids = array();
if($Relations->NumItems()>0)
{
foreach($Relations->Items as $r)
{
if($r->Get("SourceId")==$ResourceId)
{
$ids[$r->Get("TargetType")][] = $r->Get("TargetId");
}
if($r->Get("TargetId")==$ResourceId && $r->Get("Type")==1)
{
$ids[$r->Get("SourceType")][] = $ResourceId;
}
}
foreach($ids as $ItemType=>$idlist)
{
$Item =& $objItemTypes->GetItem($ItemType);
if( !is_object($Item) )
{
if( isDebugMode() ) echo 'Item with RID [<b>'.$ResourceId.'</b>] has <b>invalid relation</b> to items with RIDS: <b>'.print_r($idlist, true).'</b><br>';
continue;
}
$table = GetTablePrefix().$Item->Get("SourceTable");
if($ItemType!=1)
{
$cattable = GetTablePrefix()."CategoryItems";
$sql = "SELECT *,CategoryId FROM $table INNER JOIN $cattable ON ";
$sql .=" ($table.ResourceId=$cattable.ItemResourceId) WHERE $table.Status=1 AND PrimaryCat=1 ";
$sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
}
else
{
$sql = "SELECT *,CategoryId FROM $table ";
$sql .="WHERE $table.Status=1 ";
$sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")";
}
// echo $sql."<br>\n";
$RelatedItems->Query_Item($sql,-1,-1,$ItemType);
}
}
}
}
/*
@description: Inserts the html from a remote source
@attrib: _url:: Remote URL to include
@attrib: _StartPos:: Numeric start point of text to include, or string match
@attrib: _EndPos:: Numeric end point of text to include, or string match
@example: <inp:m_insert_url _Url="http://www.google.com" _StartPos="\<center\>" _EndPos="\</center\>" />
*/
function m_insert_url($attribs=array())
{
global $pathtoroot;
$url = $attribs["_url"];
$StartPos = $attribs["_startpos"];
$EndPos = $attribs["_endpos"];
$socket = new Socket($url,0,NULL);
$txt = $socket->socket_read_all();
$lines = explode("\n",$txt);
$txt = substr($txt,strpos($txt,"<"));
$tmp = strtolower($txt);
$bodypos = strpos($tmp,"<body");
if(strlen($bodypos)>0)
{
$head = substr($txt,0,$bodypos-1);
$body = substr($txt,$bodypos);
if(substr($tmp,-7)=="</html>")
$body = substr($body,0,-7);
}
else
$body = $txt;
if(strlen($body))
{
if(strlen($StartPos))
{
if(!is_numeric($StartPos))
{
$start = strpos($body,$StartPos);
}
else
$start = (int)$StartPos;
}
else
$start = 0;
if(strlen($EndPos))
{
if(!is_numeric($EndPos))
{
$end = strpos($body,$EndPos,$start) + strlen($EndPos);
}
else
$end = (int)$EndPos;
}
else
$end = NULL;
$o = substr($body,$start,$end-$start);
}
return $o;
}
/*
@description: Displays a template depending on the login status of the user
@attrib: _logintemplate:tpl: template to display when the user is NOT logged in
@attrib: _LoggedinTemplate:tpl: template to display when the user is logged in
@example: <inp:m_loginbox _LoginTemplate="right_login" _LoggedInTemplate="right_loggedin" />
*/
function m_loginbox($attribs = array())
{
global $var_list, $objSession, $objUsers, $objTemplate;
$userid = $objSession->Get('PortalUserId');
if ($userid <= 0) {
if ( getArrayValue($attribs, '_logintemplate')) {
$t = $objTemplate->ParseTemplate($attribs['_logintemplate']);
}
return $t;
}
else {
$user =& $objUsers->GetItem($userid);
if (getArrayValue($attribs, '_loggedintemplate')) {
$t = $user->ParseTemplate($attribs['_loggedintemplate']);
}
return $t;
}
}
/*
@description: result of suggest site action
*/
function m_suggest_result()
{
global $objSession;
$ret = $objSession->GetVariable('suggest_result');
$objSession->SetVariable('suggest_result', '');
return $ret;
}
/*
@description: result of subscribe to mailing list action
*/
function m_subscribe_result()
{
global $SubscribeResult;
if(strlen($SubscribeResult))
return language($SubscribeResult);
return "";
}
/*
@description: email address of user subscribing to mailing list
*/
function m_subscribe_address()
{
global $objSession;
return $objSession->GetVariable('SubscribeAddress');
}
/*
@description: Error message of subscribe to mailing list action
*/
function m_subscribe_error()
{
global $objSession;
$error_phrase = $objSession->GetVariable('SubscribeError');
return $error_phrase ? language($error_phrase) : '';
}
/*
@description: Displays a prompt for a form field
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _LangText:lang: Language var to use for field label
@attrib: _plaintext:: Plain text to use for field label (langtext is used by default if both are set)
@attrib: _Template:tpl: template used to display the field label (if not set "<inp:form_prompt />" is used
@attrib: _ErrorTemplate:tpl: If the field is in an error state (ie missing input) this template is used. Will default to the normal template if not set
*/
function m_form_prompt($attribs = array())
{
global $FormError, $objTemplate, $objConfig;
$form = strtolower($attribs["_form"]);
$field = strtolower($attribs["_field"]);
if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
{
$o = "";
}
else
{
$t = $attribs["_template"];
if(!strlen($t))
{
$templateText = "<inp:form_prompt />";
}
$e = $attribs["_errortemplate"];
if(!strlen($e))
$e = $t;
- if(strlen($attribs["_langtext"]))
- {
+ if(isset($attribs['_langtext']) && strlen($attribs['_langtext'])) {
$txt = language($attribs["_langtext"]);
}
else
$txt = $attribs["_plaintext"];
if (strtolower($field) == "dob")
{
if (isset($FormError[strtolower($form)][strtolower($field."_day")]) || isset($FormError[strtolower($form)][strtolower($field."_month")]) || isset($FormError[strtolower($form)][strtolower($field."_year")]))
$rawtext = $objTemplate->GetTemplate($e, true);
}
if(isset($FormError[strtolower($form)][strtolower($field)]))
{
$rawtext = $objTemplate->GetTemplate($e);
}
elseif (strlen($t))
$rawtext = $objTemplate->GetTemplate($t);
if(is_object($rawtext))
{
$src = $rawtext->source;
$o = str_replace("<inp:form_prompt />",$txt, $src);
}
else
$o = str_replace("<inp:form_prompt />", $txt, $templateText);
}
return $o;
}
/*
@description: Returns text if system is configured to use auto-generated passwords
@attrib:_LangText:lang:Language tag to return
@attrib:_PlainText::Plain text to return (_LangText takes precedece)
@attrib:_Value:bool:Auto Password setting value to match
*/
function m_autopassword($attribs = array())
{
global $objConfig;
if($attribs["_value"]=="true" || $attribs["_value"]==1)
{
$IsAuto = $objConfig->Get("User_Password_Auto");
}
else
{
$IsAuto = !$objConfig->Get("User_Password_Auto");
}
if($IsAuto)
{
if(strlen($attribs["_langtext"]))
{
$ret = language($attribs["_langtext"]);
}
else
$ret = $attribs["_plaintext"];
if(!$ret)
return "true";
}
return $ret;
}
/*
@description: checks if field specified is equals to value specified
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:: Field value to compare to
@example: <inp:m_field_equals _field="topic_subject" _Form="edit_topic" _Value="test" />true</inp:m_field_equals>
*/
function m_field_equals($attribs = array())
{
global $FormValues;
//print_pre($attribs);
$form = $attribs["_form"];
$field = $attribs["_field"];
if(isset($_POST[$field]))
{
$value = $_POST[$field];
}
else
{
$value = $FormValues[$form][$field];
if (is_array($value))
{
$value = is_null($value['lang_value'])? $value['value'] : $value['lang_value'];
}
}
//echo "POST_VALUE: [$value] vs USER_VALUE: [".$attribs['_value']."]<br>";
return $value == $attribs['_value'] ? 1 : '';
}
/*
@description: creates an INPUT tag for a form field. All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _ForgetValue:bool: if true, forget value
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@example: <inp:m_form_input type="text" class="input" style="width:600px;" _field="topic_subject" _Form="edit_topic" _Required="1" />
*/
function m_form_input($attribs = array())
{
global $FormValues, $objConfig;
$html_attribs = ExtraAttributes($attribs);
$form = $attribs["_form"];
$field = strtolower($attribs["_field"]);
// $field = $attribs["_field"];
$value='';
if(isset($_POST[$field]) && getArrayValue($attribs,'_forgetvalue') != 1)
{
$value = inp_htmlize($_POST[$field],1);
}
else {
if (getArrayValue($attribs,'_forgetvalue') != 1 && getArrayValue($FormValues[$form],$field) ) {
$value = $FormValues[$form][$field];
if (is_array($value))
{
$value = is_null($value['lang_value'])? $value['value'] : $value['lang_value'];
}
$value = inp_htmlize($value);
}
}
if($form=='new_pm' && $field=='pm_subject' && !get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// print_pre($FormValues);
// echo $form.".".$field."=".$value." = ".$attribs['_forgetvalue']."<br>\n";
if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
{
$ret = "";
}
else
{
$ret = "<INPUT ".$html_attribs." name=\"$field\" VALUE=\"$value\" />";
if(getArrayValue($attribs,'_required'))
$ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
if(getArrayValue($attribs,'_custom'))
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
}
return $ret;
}
/*
@description: creates an INPUT tag (type checkbox) for a form field. All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:bool: If true, the radio button is CHECKED
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _Custom:bool: If set, handled as a custom field
@example: <inp:m_form_checkbox _field="owner_notify" _Form="edit_topic" />
*/
function m_form_checkbox($attribs = array())
{
global $FormValues, $objConfig;
$html_attribs = ExtraAttributes($attribs);
$form = $attribs['_form'];
$field = strtolower($attribs['_field']);
if(isset($_POST[$field]))
{
$value = (int)$_POST[$field];
if($value==1) $checked = ' CHECKED';
}
else
{
$value = $FormValues[$form][$field];
if (is_array($value)) {
$value = $value['value'];
}
if ((int)$value==1) {
$checked = ' CHECKED';
}
}
//echo $form.".".$field."=".$value."<br>\n";
$ret = "<INPUT TYPE=\"checkbox\" $html_attribs name=\"$field\" VALUE=\"1\" $checked />";
if($attribs["_required"])
$ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
if($attribs["_custom"])
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
$ret .= '<input type="hidden" name="form_fields[]" VALUE="'.$field.'" />';
return $ret;
}
/*
@description: creates an INPUT tag (type radio) for a form field. All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:: Value assigned to radio button. If the form field value matches this attribute, the radio button is CHECKED
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _Default:string: Default value for radiobutton if not checked
@attrib: _Custom:bool: If set, handled as a custom field
@example: <inp:m_form_radio _field="owner_notify" _Form="edit_topic" />
*/
function m_form_radio($attribs = array())
{
global $FormValues, $objConfig;
$html_attribs = ExtraAttributes($attribs);
$form = $attribs['_form'];
$field = strtolower($attribs['_field']);
$val = $attribs['_value'];
if( GetVar($field) !== false )
{
$value = GetVar($field);
if($value == $val) $checked = ' CHECKED';
}
else
{
$value = $FormValues[$form][$field];
if (is_array($value))
{
$value = $value['value'];
}
if( !isset($value) && getArrayValue($attribs,'_default') ) $value = $val;
if($value==$val) $checked=' CHECKED';
}
//echo $form.".".$field."=".$value."<br>\n";
$ret = "<INPUT TYPE=\"radio\" $html_attribs name=\"$field\" VALUE=\"$val\" $checked />";
if($attribs["_required"])
$ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
if($attribs["_custom"])
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
return $ret;
}
/*
@description: returns the value for a form field. This may be defaulted by the system or set by a previus submit (as in an error condition)
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@example: <inp:m_form_value _field="owner_notify" _Form="edit_topic" />
*/
function m_form_value($attribs = array())
{
global $FormValues;
$form = $attribs["_form"];
$field = strtolower($attribs["_field"]);
if(isset($_POST[$field]))
{
$value = inp_htmlize($_POST[$field],1);
}
elseif(getArrayValue($_GET, 'search_type') == 'advanced')
{
$value = '';
}
else
{
$value = $FormValues[$form][$field];
if (is_array($value)) {
$value = is_null($value['lang_value'])? $value['value'] : $value['lang_value'];
}
$value = inp_htmlize($value, 1);
}
//echo "<pre>"; print_r($FormValues); echo "</pre>";
return $value;
}
/*
@description: creates an form OPTION tag for a form SELECT tag.
All extra attributes are passed to the OPTION tag.
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Value:: Value to use for this option (ie the value attribute) If the current value of the select
field is the same as this attribute, then this option will be set SELECTED.
@attrib: _langtext:lang: language tag to display for this option in the SELECT dropdown
@attrib: _plaintext:: plain text to display for this option in the SELECT dropdown (if _langtext is set, it is used instead of _plaintext)
@example: <inp:m_form_option _value="3321" _field="formfield" _form="formname" _langtext="lu..."
*/
function m_form_option($attribs = array())
{
global $FormValues, $objSession;
$html_attribs = ExtraAttributes($attribs);
$field = getArrayValue($attribs, "_field");
$form = getArrayValue($attribs, "_form");
$val = getArrayValue($attribs, "_value");
if(isset($_POST[$field]))
{
$value = $_POST[$field];
}
else
{
$value = isset($FormValues[$form][$field]) ? $FormValues[$form][$field] : $objSession->GetPersistantVariable($field);
// No need to read lan_value since it's options/drop-down field
if (is_array($value))
$value = $value['value'];
}
$selected = (strtolower($val) == strtolower($value))? "SELECTED" : "";
//echo "Sel $field = $value: $selected<br>";
if( getArrayValue($attribs,'_langtext') )
{
$txt = language($attribs["_langtext"]);
}
else
$txt = $attribs["_plaintext"];
$o = "<OPTION $html_attribs VALUE=\"$val\" $selected>$txt</OPTION>";
return $o;
}
function m_form_custom_options($attribs = array())
{
global $FormValues, $objSession;
$html_attribs = ExtraAttributes($attribs);
$form = $attribs['_form'];
$field = $attribs['_field'];
$application =& kApplication::Instance();
$item_type = $application->getUnitOption($attribs['_prefix'], 'ItemType');
$sql = 'SELECT ValueList FROM '.GetTablePrefix().'CustomField WHERE FieldName = %s AND Type = %s';
$values = $application->Conn->GetOne( sprintf($sql, $application->DB->qstr($field), $item_type ) );
// 2. replace any sqls found there
$objConfigDummy = new clsConfigAdminItem();
$values = $objConfigDummy->GetValues($values);
if(!$values) return '';
if (GetVar($field)) {
$value = GetVar($field);
}
else {
$value = $FormValues[$form][$field];
if( is_array($value) ) $value = $value['value'];
}
$ret = '';
$option_tpl = '<option value="%s"%s>%s</option>';
foreach ($values as $option_id => $option_title) {
$selected = $option_id == $value ? ' selected' : '';
$ret .= sprintf($option_tpl, $option_id, $selected, $option_title);
}
return $ret;
}
/*
@description: creates an form TEXTAREA field. All extra attributes are passed to the TEXTAREA tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _Custom:bool: If set, handled as a custom field
@example: <inp:m_form_textarea class="textarea" _field="bb_signature" _Form="bb_profile" ID="textbody" style="width:300px;" ROWS=10 COLS=65 WRAP="VIRTUAL" />
*/
function m_form_textarea($attribs = array())
{
global $FormValues;
$html_attribs = ExtraAttributes($attribs);
$field = $attribs["_field"];
$form = $attribs["_form"];
if(isset($_POST[$field]))
{
$value = inp_htmlize($_POST[$field],1);
}
else
{
$value = $FormValues[$form][$field];
if (is_array($value)) $value = $value['value'];
$value = inp_htmlize($value);
}
$ret = "<TEXTAREA NAME=\"$field\" $html_attribs>$value</TEXTAREA>";
if( getArrayValue($attribs,'_required') )
{
$ret .= "<input type=hidden name=required[] VALUE=\"$field\" />";
}
if( getArrayValue($attribs,'_custom') )
{
$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
}
return $ret;
}
/*
@description: creates an form field to upload images. (INPUT type=file) All extra attributes are passed to the INPUT tag
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
@attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
@attrib: _ImageTypes:: Comma-separated list of file extensions allowed
@attrib: _Thumbnail:bool: If true, image is treated as a thumbnail
@attrib: _ImageName:: System name of image being uploaded
@attrib: _MaxSize:int: Maximum size of image to upload, or 0 to allow all
*/
function m_form_imageupload($attribs = array())
{
$html_attribs = ExtraAttributes($attribs);
$field = $attribs["_field"];
$form = $attribs["_form"];
$TypesAllowed = getArrayValue($attribs,'_imagetypes');
$isthumb = (int)getArrayValue($attribs,'_thumbnail');
$imgname = getArrayValue($attribs,'_imagename');
$maxsize = getArrayValue($attribs,'_maxsize');
$is_default = getArrayValue($attribs, '_default');
$ret = "<INPUT $html_attribs TYPE=file NAME=\"$field\" >";
$ret .= "<INPUT TYPE=HIDDEN name=\"isthumb[$field]\" VALUE=\"$isthumb\">";
$ret .= "<INPUT TYPE=HIDDEN name=\"imagetypes[$field]\" VALUE=\"$TypesAllowed\">";
$ret .= "<INPUT TYPE=HIDDEN name=\"imagename[$field]\" VALUE=\"$imgname\">";
$ret .= "<INPUT TYPE=HIDDEN name=\"maxsize[$field]\" VALUE=\"$maxsize\">";
if($is_default) $ret .= '<input type="hidden" name="imgdefault['.$field.']" value="1">';
if( getArrayValue($attribs,'_required') )
{
$ret .= "<input type=hidden name=required[] VALUE=\"$field\" />";
}
return $ret;
}
/*
@description: Returns the error text for a form field, or nothing if no error exists for the field
@attrib: _Form:: Form name for the field
@attrib: _Field:: Field Name
*/
function m_form_error($attribs = array())
{
global $FormError;
$form = $attribs["_form"];
$field = $attribs["_field"];
return $FormError[$form][$field];
}
/**
@description: Provides a simple solution for displaying a language flag when a form has an error. Generic and limited to 1 language vairable.
@attrib: _Form:: Form name for the field
*/
function m_form_has_errors($attribs = array())
{
// shows specified template once if form has error(-s)
global $FormError;
$f = $attribs["_form"];
$ret = is_array($FormError[$f]);
if(!$ret) return '';
return isset($attribs["_asif"]) ? true : language('lu_errors_on_form');
}
/**
@description: Lists form errors for all fields in a form
@attrib: _Form:: Form name for the field
@attrib: _ItemTemplate:tpl: Template used to display each form error (if not set, "<inp:form_error />" is used)
*/
function m_list_form_errors($attribs = array())
{
global $FormError, $content_set, $objTemplate;
$t = $attribs["_itemtemplate"];
if(!strlen($t))
$templateText = "<inp:form_error />";
$f = $attribs["_form"];
$o = "";
if (strlen($t))
{
$rawtext = $objTemplate->GetTemplate($t, true);
$src = $rawtext->source;
}
else
$src = $templateText;
//echo $f."<br>";
//echo $t."<br>";
// echo "<PRE>"; print_r($FormError); echo "</pre>";
if( getArrayValue($FormError,$f) && is_array($FormError[$f]))
{
foreach($FormError[$f] as $e)
{
$o .= str_replace("<inp:form_error />",$e, $src);
}
}
if(!strlen($o))
$content_set = 0;
return $o;
}
function m_form_load_values($FormName,$IdValue)
{
global $FormValues, $objUsers, $objSession, $objConfig;
switch($FormName)
{
case "m_acctinfo":
$u =& $objUsers->GetItem($IdValue);
$FormValues[$FormName]["username"] = $u->Get("Login");
//$FormValues[$FormName]["password"] = $u->Get("Password");
//$FormValues[$FormName]["passwordverify"] = $u->Get("Password");
$FormValues[$FormName]["password"] = "";
$FormValues[$FormName]["passwordverify"] = "";
$FormValues[$FormName]["firstname"] = $u->Get("FirstName");
$FormValues[$FormName]["lastname"] = $u->Get("LastName");
$FormValues[$FormName]["company"] = $u->Get("Company");
$FormValues[$FormName]["email"] = $u->Get("Email");
$FormValues[$FormName]["phone"] = $u->Get("Phone");
$FormValues[$FormName]["fax"] = $u->Get("Fax");
$FormValues[$FormName]["street"] = $u->Get("Street");
$FormValues[$FormName]["street2"] = $u->Get("Street2");
$FormValues[$FormName]["city"] = $u->Get("City");
$FormValues[$FormName]["state"] = $u->Get("State");
$FormValues[$FormName]["zip"] = $u->Get("Zip");
$FormValues[$FormName]["country"] = $u->Get("Country");
$FormValues[$FormName]["minpwresetdelay"] = $u->Get("MinPwResetDelay");
// $FormValues[$FormName]["dob"] = LangDate($u->Get("dob"), 0, true);
$FormValues[$FormName]["dob_day"] = adodb_date("d", $u->Get("dob"));
$FormValues[$FormName]["dob_year"] = adodb_date("Y", $u->Get("dob"));
$FormValues[$FormName]["dob_month"] = adodb_date("m", $u->Get("dob"));
$u->LoadCustomFields();
if(is_array($u->CustomFields))
{
foreach($u->CustomFields as $f=>$v)
{
$FormValues[$FormName][$f] = $v;
}
}
break;
case "m_profile":
$u =& $objUsers->GetItem($IdValue);
if(is_object($u))
{
$FormValues[$FormName]["pp_firstname"] = $objSession->GetPersistantVariable("pp_firstname");
$FormValues[$FormName]["pp_lastname"] = $objSession->GetPersistantVariable("pp_lastname");
$FormValues[$FormName]["pp_dob"] = $objSession->GetPersistantVariable("pp_dob");
$FormValues[$FormName]["pp_email"] = $objSession->GetPersistantVariable("pp_email");
$FormValues[$FormName]["pp_phone"] = $objSession->GetPersistantVariable("pp_phone");
$FormValues[$FormName]["pp_street"] = $objSession->GetPersistantVariable("pp_street");
$FormValues[$FormName]["pp_city"] = $objSession->GetPersistantVariable("pp_city");
$FormValues[$FormName]["pp_state"] = $objSession->GetPersistantVariable("pp_state");
$FormValues[$FormName]["pp_zip"] = $objSession->GetPersistantVariable("pp_zip");
$FormValues[$FormName]["pp_country"] = $objSession->GetPersistantVariable("pp_country");
}
break;
case "m_simplesearch":
$FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
break;
case "m_simple_subsearch":
$FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords");
break;
}
}
/*
@description: Generates the ACTTION property for a FORM tag used by In-Portal
@attrib: _Template:tpl: If set, this is the template the form submits to (default is the current template)
@attrib: _Form:: The form name<br>Possible Values:
<UL>
<LI>login: user login
<LI>logout: user logout
<LI>forgotpw: Form to prompt the user for forgotten password information
<LI>forgotpw_confirm: confirmation form for forgotpw
<LI>suggest: form to suggest the site to a friend
<LI>suggest_confirm: form to confirm suggestion of the site to a friend
<LI>m_subscribe: form to subscribe to the mailing list
<LI>subscribe_confirm: form to confirm subscription to the mailing list
<LI>m_unsubscribe: form to unsubscribe from the mailing list
<LI>unsubscribe_confirm: form to confirm un-subscription from the mailing list
<LI>m_acctinfo: user account information
<LI>m_profile: system-level profile information
<LI>m_register: New User registration form
<LI>m_addcat: Suggest Category form
<LI>m_addcat_confirm: Confirmation for add category
<LI>m_simplesearch: Perform a simple search
<LI>m_simple_subsearch: Search within results
<LI>m_adv_searchtype: Form to select type of advanced search
<LI>m_adv_subsearch: Advanced Search
<LI>m_sort_cats: Sort categories
<LI>error_access: form displayed on the access denied template
<LI>error_template: Form displayed on the template error page
<LI>m_set_theme: Form displayed for theme selection
</UL>
@attrib: _SubscribeTemplate:tpl: The destination template with "m_subscribe", "subscribe_confirm", "unsubscribe_confirm" _Form actions. Can be reused in other scenarios as programmed.
@attrib: _UnSubscribeTemplate:tpl: The destination template for "m_subscribe" _Form action. Can be reused in other scenarios as programmed.
@attrib: _ConfirmTemplate:tpl: The destination template for "m_unsubscribe", "suggest" _Form actions. Can be reused in other scenarios as programmed.
@attrib: _DestTemplate:tpl: The destination template for "suggest_confirm", "suggest" _Form actions. Can be reused in other scenarios as programmed.
@attrib: _ErrorTemplate:tpl: The destination template extensively used in most of _Form actions in case of error.
@attrib: _Referer:bool: The destination template will be taken from referer page we can from.
@example: <FORM enctype="multipart/form-data" method="POST" NAME="article_review" ACTION="<inp:m_form_action _Form="register" _confirm="join_confirm" />">
*/
function m_form_action($attribs = array())
{
global $var_list, $var_list_update, $m_var_list_update, $objSession, $objConfig, $objCatList;
$var_list_update['t'] = getArrayValue($attribs, '_template') ? $attribs['_template'] : $var_list['t'];
$ret = '';
$form = strtolower( $attribs['_form'] );
$url_params = Array();
switch($form)
{
case 'login':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_login');
if( getArrayValue($attribs, '_successtemplate') )
{
$url_params['dest'] = $attribs['_successtemplate'];
}
else
{
if( getArrayValue($var_list, 'dest') )
{
$var_list_update['t'] = $var_list['dest'];
// $url_params['dest'] = $var_list['dest'];
}
}
$url_params['pass'] = 'all';
}
break;
case 'logout':
$url_params = Array('Action' => 'm_logout');
break;
case 'forgotpw':
if(!$objSession->SessionEnabled())
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_forgotpw');
$url_params['error'] = getArrayValue($attribs, '_errortemplate') ? $attribs['_errortemplate'] : $var_list['t'];
if( getArrayValue($attribs, '_confirm') ) $url_params['Confirm'] = $attribs['_confirm'];
}
break;
/*case 'forgotpw_confirm':
break;*/
case 'm_sort_cats':
$url_params = Array('Action' => 'm_sort_cats');
break;
case 'suggest':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_suggest_email');
if( getArrayValue($attribs, '_confirmtemplate') )
{
$url_params['Confirm'] = $attribs['_confirmtemplate'];
$url_params['DestTemplate'] = $_REQUEST['DestTemplate'] ? $_REQUEST['DestTemplate'] : $var_list['t'];
}
if( getArrayValue($attribs, '_errortemplate') ) $url_params['Error'] = $attribs['_errortemplate'];
if( getArrayValue($attribs, '_captchatemplate') ) $url_params['Captcha'] = $attribs['_captchatemplate'];
}
break;
case 'suggest_confirm':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$var_list_update['t'] = getArrayValue($_GET, 'DestTemplate') ? $_GET['DestTemplate'] : 'index';
}
break;
case 'm_subscribe':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_subscribe_confirm');
$params_map = Array('_subscribetemplate' => 'Subscribe', '_unsubscribetemplate' => 'Unsubscribe', '_errortemplate' => 'Error');
MapTagParams($url_params, $attribs, $params_map);
}
break;
case 'subscribe_confirm':
$url_params = Array('Action' => 'm_subscribe');
$params_map = Array('_subscribetemplate' => 'Subscribe');
MapTagParams($url_params, $attribs, $params_map);
break;
case 'unsubscribe_confirm':
$url_params = Array('Action' => 'm_unsubscribe');
$params_map = Array('_subscribetemplate' => 'Subscribe');
MapTagParams($url_params, $attribs, $params_map);
break;
case 'm_unsubscribe':
$params_map = Array('_confirmtemplate' => 'ErrorTemplate');
MapTagParams($url_params, $attribs, $params_map);
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params['Action'] = 'm_unsubscribe';
if( getArrayValue($attribs, '_confirmtemplate') )
{
$url_params['Confirm'] = $attribs['_confirmtemplate'];
$url_params['DestTemplate'] = $var_list['t'];
}
}
break;
/*case 'm_unsubscribe_confirm':
break;*/
case 'm_acctinfo':
$url_params = Array('Action' => 'm_acctinfo', 'UserId' => $objSession->Get('PortalUserId') );
m_form_load_values( $form, $objSession->Get('PortalUserId') );
break;
case 'm_profile':
$url_params = Array('Action' => 'm_profile', 'UserId' => $objSession->Get('PortalUserId') );
m_form_load_values( $form, $objSession->Get('PortalUserId') );
break;
case 'm_set_theme':
$url_params = Array('Action' => 'm_set_theme');
break;
case 'm_register':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_register');
switch ( $objConfig->Get('User_Allow_New') )
{
case 1:
if( getArrayValue($attribs, '_confirmtemplate') && $objConfig->Get('User_Password_Auto') )
{
$url_params['dest'] = $attribs['_confirmtemplate'];
}
else
{
$url_params['dest'] = $attribs['_logintemplate'];
}
break;
case 2:
if( getArrayValue($attribs, '_notallowedtemplate') ) $url_params['dest'] = $attribs['_notallowedtemplate'];
break;
case 3:
if( getArrayValue($attribs, '_pendingtemplate') ) $url_params['dest'] = $attribs['_pendingtemplate'];
break;
}
}
break;
case 'register_confirm':
if( !$objSession->SessionEnabled() ) $var_list_update['t'] = 'error_session';
break;
case 'm_addcat':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_add_cat');
if ( $objSession->HasCatPermission('CATEGORY.ADD.PENDING') )
{
$url_params['Confirm'] = $attribs[ getArrayValue($attribs, '_confirmpending') ? '_confirmpending' : '_confirm' ];
$url_params['Action'] = 'm_add_cat_confirm';
}
if ( $objSession->HasCatPermission('CATEGORY.ADD') )
{
$url_params['Confirm'] = $attribs['_confirm'];
$url_params['Action'] = 'm_add_cat_confirm';
}
if( !$url_params['Confirm'] ) unset($url_params['Confirm']);
if ( getArrayValue($attribs, '_mod_finishtemplate') )
{
$CurrentCat = (int)$objCatList->CurrentCategoryID();
if($CurrentCat > 0)
{
$c = $objCatList->GetCategory($CurrentCat);
//will prefix the template with module template root path depending on category
$ids = $c->GetParentIds();
$tpath = GetModuleArray('template');
$roots = GetModuleArray('rootcat');
// get template path of module, by searching for moudle name
// in this categories first parent category
// and then using found moudle name as a key for module template paths array
$path = $tpath[ array_search($ids[0], $roots) ];
$url_params['DestTemplate'] = $path . $attribs['_mod_finishtemplate'];
}
else
{
$url_params['DestTemplate'] = $attribs['_mod_finishtemplate']; //Just in case
}
}
else
{
$url_params['DestTemplate'] = $attribs['_finishtemplate'];
}
}
break;
case 'm_addcat_confirm':
$var_list_update['t'] = getArrayValue($_GET, 'DestTemplate') ? $_GET['DestTemplate'] : $var_list['t'];
break;
case 'm_simplesearch':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_simple_search');
if( getArrayValue($attribs, '_errortemplate') ) $url_params['Error'] = $attribs['_errortemplate'];
m_form_load_values($form, 0);
}
break;
case 'm_simple_subsearch':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_simple_subsearch');
m_form_load_values($form,0);
}
break;
case 'm_adv_search_type':
if( !$objSession->SessionEnabled() )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_advsearch_type');
m_form_load_values($form,0);
}
break;
case 'm_adv_search':
$SearchType = getArrayValue($_GET, 'type') ? $_GET['type'] : $_POST['itemtype'];
if( !$objSession->SessionEnabled() && !$SearchType )
{
$var_list_update['t'] = 'error_session';
}
else
{
$url_params = Array('Action' => 'm_adv_search', 'type' => $SearchType);
m_form_load_values($form,0);
}
break;
case 'error_access':
$var_list_update['t'] = getArrayValue($_GET, 'DestTemplate') ? $_GET['DestTemplate'] : 'login';
break;
case 'error_template':
$target_template = getArrayValue($_GET, 'DestTemplate');
if($attribs['_referer'] == 1)
{
$target_template = '_referer_';
}
elseif (!$target_template)
{
$target_template = 'index';
}
$var_list_update['t'] = $target_template;
break;
}
return HREF_Wrapper('', $url_params);
}
/*
@description: creates a URL to allow the user to log out. Accepts the same attributes as m_template_link
*/
function m_logout_link($attribs)
{
$query = getArrayValue($attribs, '_query');
$attribs['_query'] = $query.'&Action=m_logout';
$ret = m_template_link($attribs);
return $ret;
}
/*
@description: returns a URL to the current theme
@attrib: _page:: Additional address to be added to the end of the theme URL
*/
function m_theme_url($attribs=array())
{
global $objConfig,$objSession, $objThemes, $CurrentTheme;
if(!is_object($CurrentTheme))
$CurrentTheme = $objThemes->GetItem($m_var_list["theme"]);
$theme_url = PROTOCOL.SERVER_NAME.rtrim(BASE_PATH, '/').'/themes/'.$CurrentTheme->Get('Name').'/';
if(getArrayValue($attribs,'_page'))
{
if ($attribs["_page"] != 'current')
{
$theme_url .= $attribs["_page"];
}
else
{
$theme_url = PROTOCOL.SERVER_NAME.rtrim(BASE_PATH, '/').'/index.php?env='.BuildEnv();
}
}
return $theme_url;
}
/*
@description: returns a URL to the current theme
*/
function m_current_page_url($attribs=array())
{
global $objConfig,$objSession;
$theme_url = "http://".$objConfig->Get("Site_Path")."index.php?env=".BuildEnv();
return $theme_url;
}
/*
@description: returns a URL to the current theme
@attrib: _fullpath:bool: Append the title with the full path of the current category
@attrib: _currentcategory:bool: Append the title with the current category
@attrib: _catfield:: If _currentcategory is used, this attribute determines which category field to use (Name, Description, etc) Defaults to Name
*/
function m_page_title($attribs = array())
{
global $objConfig, $objCatList;
$application =& kApplication::Instance();
if ($application->isModuleEnabled('In-Edit')) {
$title = $application->ProcessTag('cms:PageInfo type="htmlhead_title"');
if ($title && !preg_match('/^_Auto.*/', $title)) {
return $title;
}
}
$ret = strip_tags( $objConfig->Get('Site_Name') );
if(getArrayValue($attribs,'_fullpath') || getArrayValue($attribs,'_currentcategory'))
{
$CurrentCat = $objCatList->CurrentCategoryID();
if((int)$CurrentCat>0)
{
$c = $objCatList->GetCategory($CurrentCat);
if($attribs["_fullpath"])
{
$application =& kApplication::Instance();
$ml_formatter =& $application->recallObject('kMultiLanguage');
$path = $c->Get($ml_formatter->LangFieldName('CachedNavbar'));
if (strlen($path)) {
$ret .= " - ".str_replace('&|&', ' > ', $path);
}
}
else
{
if($attribs["_currentcategory"])
{
$f = $attribs["_catfield"];
if (!strlen($f)) {
$f = "Name";
}
if ($f == 'Name') $f = $objCatList->TitleField;
$ret .= " - ".$c->Get($f);
}
}
}
}
$ret = stripslashes($ret);
return $ret;
}
/*
@description: list all active themes
@attrib: _ItemTemplate:tpl: Template to display each theme in the list
*/
function m_list_themes($attribs=array())
{
global $objThemes;
$t = $attribs["_itemtemplate"];
if(strlen($t))
{
$objThemes->Clear();
$objThemes->LoadThemes("Enabled=1","PrimaryTheme DESC");
foreach($objThemes->Items as $theme)
{
$o .= $theme->ParseTemplate($t);
}
}
return $o;
}
/*
@description: display text based on the user's language
@attrib: _Phrase:lang: label to replace with language-specific text
@example: <inp:m_language _Phrase="lu_hello_world" />
*/
function m_language($attribs)
{
global $objSession, $objLanguages, $ForceLanguage;
$phrase = $attribs["_phrase"];
$LangId = (int)$ForceLanguage;
if(strlen($phrase))
{
$lang = getArrayValue($attribs,'_language');
if(strlen($lang))
{
$l = $objLanguages->GetItemByField("PackName",$lang);
if(is_object($l))
{
$LangId = $l->Get("LanguageId");
}
}
return language($phrase,$LangId);
}
else
return "";
}
/*
@description: Creates a URL used to set the current language for a user
@attrib: _language:: Language to set (this value should be the language Pack Name)
*/
function m_setlang_link($attribs)
{
global $m_var_list_update, $objSession,$objLanguages;
$lang = getArrayValue($attribs, '_language');
if($lang)
{
$l = $objLanguages->GetItemByField('PackName', $lang);
if( is_object($l) ) $LangId = $l->Get('LanguageId');
}
else
{
$LangId = $objSession->Get('Language');
}
if($LangId)
{
$m_var_list_update['lang'] = $LangId;
$ret = HREF_Wrapper();
unset($m_var_list_update['lang']);
}
else
{
$ret = '';
}
return $ret;
}
/*
@description: list all active languages
@attrib: _ItemTemplate:tpl: Template to display each language in the list
*/
function m_list_languages($attribs)
{
global $objLanguages, $content_set;
$sql = "SELECT * FROM ".GetTablePrefix()."Language WHERE Enabled=1";
$objLanguages->Clear();
$objLanguages->Query_Item($sql);
$o='';
if($objLanguages->NumItems()>0)
{
foreach($objLanguages->Items as $l)
$o .= $l->ParseTemplate($attribs["_itemtemplate"]);
}
else
$content_set=0;
return $o;
}
/*
@description: returns the date format for a language
@attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
*/
function m_lang_dateformat($attribs=array())
{
global $objLanguages, $objSession;
$lang = $attribs["_lang"];
if(!strlen($lang))
{
$LangId = $objSession->Get("Language");
$l = $objLanguages->GetItem($LangId);
}
else
{
$l = $objLanguages->GetItemByField("PackName",$lang);
}
$fmt = GetDateFormat($LangId, true);
$fmt = GetStdFormat($fmt);
return $fmt;
}
/*
@description: returns a language field value
@attrib: _Field:: Language field to return
@attrib: _lang:: Pack Name of language to use. The current language is used if this is not set
*/
function m_lang_field($attribs = array())
{
global $objLanguages, $objSession;
if(!strlen($attribs["_field"]))
return "";
$lang = getArrayValue($attribs,'_lang');
if(!strlen($lang))
{
$LangId = $objSession->Get("Language");
$l = $objLanguages->GetItem($LangId);
}
else
{
$l = $objLanguages->GetItemByField("PackName",$lang);
}
if(is_object($l))
{
//$ret = $l->Get($attribs["_field"]);
$e = new clsHtmlTag();
$e->name=$l->TagPrefix;
$e->attributes=$attribs;
$ret = $l->ParseObject($e);
}
return $ret;
}
/*
@description: Creates a URL used to set the current theme for a user
@attrib: _theme:: Name of Theme to set. The template selected in the new them is always "index"
*/
function m_settheme_link($attribs)
{
global $m_var_list_update, $objSession, $objThemes, $CurrentTheme;
$ThemeName = getArrayValue($attribs, '_theme');
if($ThemeName)
{
$t = $objThemes->GetItemByField('Name',$ThemeName);
$Id = is_object($t) ? $t->Get('ThemeId') : 0;
}
else
{
$t = $CurrentTheme;
$Id = 0;
}
$m_var_list_update['theme'] = $Id;
$ret = HREF_Wrapper();
unset($m_var_list_update['theme']);
return $ret;
}
/*
@description: Initializes categories
*/
function m_init_cats($attribs = array())
{
// save current & previous category (used in pagination)
global $objSession, $objCatList;
global $var_list;
$objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') );
$objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() );
//$last_cat = $objSession->GetVariable('last_category');
//$prev_cat = $objSession->GetVariable('prev_category');
//echo "Last CAT: [$last_cat]<br>";
//echo "Prev CAT: [$prev_cat]<br>";
}
/*
@description: List all subcategories a user is allowed to view
@attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
@attrib: _maxlistcount:int: Maximum number of categories to list
@attrib: _FirstItemTemplate:tpl: Template used for the first category listed
@attrib: _LastItemTemplate:tpl: Template used for the last category listed
@attrib: _EdItemTemplate:tpl: Editors Pick template used for category list items
@attrib: _ItemTemplate:tpl: default template used for category list items
@attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
@example: <inp:m_list_cats _NoTable="0" _columns="2" _ItemTemplate="catlist_element" border="0" cellspacing="0" cellpadding="0" width="98%" />
*/
function m_list_cats($attribs = array())
{
global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, $objSystemCache;
$CachedList = GetTagCache("kernel","m_list_cats",$attribs,m_BuildEnv());
if(strlen($CachedList))
{
return $CachedList;
}
$cols = $attribs["_columns"];
if($cols<1)
$cols =1;
$CategoryId = getArrayValue($attribs,'_catid');
if(!is_numeric($CategoryId))
$CategoryId = $objCatList->CurrentCategoryID();
$cat_count = (int)getArrayValue($attribs,'_maxlistcount');
/* validation */
if(strlen($attribs["_itemtemplate"])==0)
{
if($attribs["dataexists"])
$content_set = 0;
return "";
}
$GroupList = $objSession->Get("GroupList");
if(strlen($GroupList))
{
$Groups = explode(",",$GroupList);
}
$acl_where = "";
if(@count($Groups)>0 && is_array($Groups))
{
$acl_where = array();
for($i=0;$i<count($Groups);$i++)
{
$g = $Groups[$i];
$acl_where[] = "FIND_IN_SET($g,acl) ";
}
if(count($acl_where))
{
$acl_where = "(".implode(" OR ",$acl_where).")";
}
else {
$acl_where = "FIND_IN_SET(0,acl)";
}
}
else {
$acl_where = "FIND_IN_SET(0,acl)";
}
$objCatList->Clear();
$OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE);
$objCatList->LoadCategories("ParentId=$CategoryId AND Status=1",$OrderBy, false);
if ($objCatList->NumItems() == 0)
{
if($attribs["_dataexists"])
$content_set = 0;
return "";
}
$html_attr = ExtraAttributes($attribs);
$o="";
$notable = $attribs["_notable"];
$count=0;
$row=0;
$var_list_update["t"] = $var_list["t"];
if(!$notable)
{
$per_row = ceil($objCatList->NumItems()/$cols);
$o = '<table '.$html_attr.'><tr class="m_list_cats">';
$o .= '<td valign="top">';
$CatCount = $objCatList->NumItems();
foreach($objCatList->Items as $cat)
{
$parsed=0;
if($count==$per_row)
{
$o .= '</td><td valign="top">';
$count=0;
}
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
{
if (getArrayValue($attribs, '_editemtemplate') && (int)$cat->Get('EditorsPick'))
{
$o .= $cat->ParseTemplate($attribs["_editemtemplate"]);
}
else
{
$o .= $cat->ParseTemplate($attribs['_itemtemplate']);
}
}
$count++;
$row++;
}
if($count != $per_row)
$o .= '</td>';
$o .= "\n</tr></table>\n";
}
else
{
$CatCount = $objCatList->NumItems();
foreach($objCatList->Items as $cat)
{
if($cat->Get("ParentId")==$CategoryId)
{
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
//echo 'Saving <b>ID</b> in <b>m_sub_cats</b>[ first ] '.$cat->UniqueId().'<br>';
//$GLOBALS['cat_ID'] = $cat->UniqueId();
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
//echo 'Saving <b>ID</b> in <b>m_sub_cats</b>[ last ] '.$cat->UniqueId().'<br>';
//$GLOBALS['cat_ID'] = $cat->UniqueId();
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
{
//echo 'Saving <b>ID</b> in <b>m_sub_cats</b>[ each ] '.$cat->UniqueId().'<br>';
//$GLOBALS['cat_ID'] = $cat->UniqueId();
$o .= $cat->ParseTemplate($attribs["_itemtemplate"]);
}
$row++;
$i++;
$count++;
if($count>=$cat_count && $cat_count>0)
break;
}
}
}
unset($var_list_update["t"]);
SaveTagCache("kernel","m_list_cats",$attribs,m_BuildEnv(),$o);
return $o;
}
function LoadCatSearchResults($attribs)
{
global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal, $m_var_list;
$GroupList = $objSession->Get("GroupList");
if(strlen($GroupList))
$Groups = explode(",",$GroupList);
$acl_where = "";
if(@count($Groups)>0 && is_array($Groups))
{
$acl_where = array();
for($i=0;$i<count($Groups);$i++)
{
$g = $Groups[$i];
$acl_where[] = "FIND_IN_SET($g,acl) ";
}
if(count($acl_where))
{
$acl_where = "(".implode(" OR ",$acl_where).")";
}
else {
$acl_where = "FIND_IN_SET(0,acl)";
}
}
else {
$acl_where = "FIND_IN_SET(0,acl)";
}
$order_by = "EdPick DESC,Relevance DESC";
if ($objSession->GetVariable("Category_Sortfield") != "") {
$order_by = $objSession->GetVariable("Category_Sortfield")." ".$objSession->GetVariable("Category_Sortorder");
}
$CAT_VIEW = $objPermissions->GetPermId("CATEGORY.VIEW");
$ctable = $objCatList->SourceTable;
$stable = $objSession->GetSearchTable(); // $objSearchCats->SourceTable;
$ptable = GetTablePrefix()."PermCache";
$sql = "SELECT * FROM $stable INNER JOIN $ctable ON ($stable.ItemId=$ctable.CategoryId) ";
$sql .= "INNER JOIN $ptable ON ($ctable.CategoryId=$ptable.CategoryId) ";
$sql .="WHERE ItemType=1 AND Status=1 AND $acl_where AND PermId=$CAT_VIEW ORDER BY $order_by ";
$objSearchCats->Page = $m_var_list["p"];
if($objSearchCats->Page<1)
$objSearchCats->Page=1;
if(is_numeric($objConfig->Get($objSearchCats->PerPageVar)))
{
$Start = ($objSearchCats->Page-1)*$objConfig->Get($objSearchCats->PerPageVar);
$limit = "LIMIT ".$Start.",".$objConfig->Get($objSearchCats->PerPageVar);
}
else
$limit = NULL;
if(strlen($limit))
$sql .= $limit;
// echo "TEST:<BR>$sql<br>\n";
$objSearchCats->Query_Item($sql);
$where = "ItemType=1";
$Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
//echo "SQL Loaded ItemCount (<b>".get_class($this).'</b>): '.$this->NumItems().'<br>';
for($i = 0; $i < $objSearchCats->NumItems(); $i++)
{
$objSearchCats->Items[$i]->Keywords = $Keywords;
}
if(is_numeric($CountVal[1]))
{
$objSearchCats->QueryItemCount = $CountVal[1];
}
else
{
$objSearchCats->QueryItemCount = QueryCount($sql);
$CountVal[1]= $objSearchCats->QueryItemCount;
}
}
/*
@description: Used in conjuction with m_search_list_cats. This function generates a navigation link which is
used to switch from a short list to a longer list. The page number is not changed.
If this tag is called before the list tag, this function will load the category list.
Generally, it is good practice to duplicate all attributes set for m_search_list_cats.
Any extra HTML attributes are passed to the anchor tag
@attrib: _Template:tpl: Template to link to
@attrib: _text:lang: language tag to include as text for the anchor tag
@attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
if both are included.
@attrib: _image:: URL to an image to include inside the anchor tag.
*/
function m_search_cat_more($attribs = array())
{
global $objSearchCats, $objConfig, $m_var_list_update;
$html_attribs = ExtraAttributes($attribs);
$DestTemplate = $attribs["_template"];
if($attribs["_shortlist"])
$objSearchList->PerPageVar = "Perpage_Category_Short";
if($objSearchCats->NumItems()==0)
{
LoadCatSearchResults($attribs);
}
$max = $objConfig->Get($objSearchList->PerPageVar);
$val = $objSearchCats->QueryItemCount;
if($val > $max)
{
if($attribs["_root"])
$attribs["_category"]=0;
$m_var_list_update["p"]=1;
$url = m_template_link($attribs);
unset($m_var_list_update["p"]);
$o = "<A $html_attribs HREF=\"$url\">";
$text = $attribs["_text"];
if(!strlen($text))
{
$text = $attribs["_plaintext"];
if(!strlen($text))
{
}
$o .= $text."</A>";
}
else
$o .= language($text);
if(strlen($attribs["_image"]))
{
$o .= "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\" alt=\"\"/>";
}
$o .= "</A>";
}
return $o;
}
/*
@description: Used in conjuction with l_list_cats. This function generates the page navigation
for the list. If this tag is called before the list tag, this function will load
the links. For that reason, the _ListType attribute is required if the pagnav
tag preceeds the l_list_links tag in the template. Generally, it is good practice to
duplicate all attributes set for l_list_links.
@attrib: _PagesToList:int: Number of pages to list (default is 10)
@attrib: _ShortList:bool: If set, uses the shortlist configuration value for links
@attrib: _label:lang: language tag to include in the output if there are pages to list. If there are no pages listed, this text will not be included (resulting in an empty output)
@attrib: _ListType::Determines the type of list to generate<br>
Possible values:<UL>
<LI>Category: List links from the current category (default)
</UL>
*/
function l_cat_pagenav($attribs = array())
{
global $objCatList, $objSession;
$DestTemplate = getArrayValue($attribs,'_template');
$PagesToList = getArrayValue($attribs,'_pagestolist');
$image = getArrayValue($attribs,'_PageIcon');
if(!is_numeric($PagesToList))
$PagesToList = 10;
$CatId = getArrayValue($attribs,'_catid');
if(!is_numeric($CatId))
$CatId = $objCatList->CurrentCategoryID();
if($attribs["_shortlist"] == 1)
$objCatList->PerPageVar = "Perpage_Category_Short";
$ListType = getArrayValue($attribs,'_listtype');
if(!strlen($ListType))
$ListType="category";
/*
if($objLinkList->ListType != $ListType) {
LoadLinkList($attribs);
}
*/
$o = $objCatList->GetPageLinkList($DestTemplate, '', 10, true, ExtraAttributes($attribs) );
if (strlen($image)) {
$o_i = '<img src="'.$image.'" width="9" height="12" alt="">&nbsp;';
}
if(strlen($o) && strlen($attribs["_label"]))
$o = $o_i.language($attribs["_label"]).' '.$o;
return $o;
}
/*
@description: Used in conjuction with m_search_list_cats. This function generates the page navigation
for the list. If this tag is called before the list tag, this function will load
the category list. Generally, it is good practice to duplicate all attributes set for
m_search_list_cats.
@attrib: _PagesToList:int: Number of pages to list (default is 10)
@attrib: _label:lang: language tag to include in the output if there are pages to list. If there are no pages
listed, this text will not be included (resulting in an empty output)
*/
function m_search_cat_pagenav($attribs = array())
{
global $objSearchCats, $objConfig, $objCatList, $objSession;
$DestTemplate = $attribs["_template"];
$PagesToList = $attribs["_pagestolist"];
if(!is_numeric($PagesToList))
$PagesToList = 10;
$CatId = $attribs["_catid"];
if(!is_numeric($CatId))
$CatId = $objCatList->CurrentCategoryID();
$objSearchCats->PerPageVar = "Perpage_Category";
if($attribs["_shortlist"])
$objSearchCats->PerPageVar = "Perpage_Category_Short";
if($objSearchCats->NumItems()==0)
{
LoadCatSearchResults($attribs);
}
$o = $objSearchCats->GetPageLinkList($DestTemplate, '', 10, true, ExtraAttributes($attribs));
if(strlen($o) && strlen($attribs["_label"]))
$o = language($attribs["_label"]).' '.$o;
return $o;
}
/*
@description: List all categories matched in a search
@attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
@attrib: _maxlistcount:int: Maximum number of categories to list
@attrib: _ShortList:bool: If set, the Perpage_Category_Short setting is used instead of Perpage_Category
@attrib: _FirstItemTemplate:tpl: Template used for the first category listed
@attrib: _LastItemTemplate:tpl: Template used for the last category listed
@attrib: _ItemTemplate:tpl: default template used for category list items
@attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
@example: <inp:m_search_list_cats _NoTable="1" _ItemTemplate="category_search_results_element" />
*/
function m_search_list_cats($attribs = array())
{
global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set,
$objSearchCats, $objPermissions, $m_var_list;
if(!is_object($objSearchCats))
{
$objSearchCats = new clsCatList();
$objSearchCats->SourceTable = $objSession->GetSessionTable('Search'); //"ses_".$objSession->GetSessionKey()."_Search"
$objSearchCats->Clear();
}
$objSearchCats->PerPageVar = "Perpage_Category";
if($attribs["_shortlist"])
{
$objSearchCats->Page=1;
$m_var_list["p"] = 1;
$objSearchCats->PerPageVar = "Perpage_Category_Short";
}
$keywords = $objSession->GetVariable("Search_Keywords"); // for using in all this func branches
if($objSearchCats->NumItems()==0)
{
LoadCatSearchResults($attribs);
//echo "Cat count: ". $objSearchCats->QueryItemCount;
$ret = 0;
if ($keywords) {
foreach ($objSearchCats->Items as $cat) {
if (strstr(strip_tags(strtolower($cat->Data[$cat->TitleField])), strtolower($_POST['keywords'])) || strstr(strip_tags(strtolower($cat->Data[$cat->DescriptionField])), strtolower($_POST['keywords']))) {
$ret++;
}
}
}
else {
$ret = $objSearchCats->QueryItemCount;
}
if ($ret == 0) //if ($objSearchCats->NumItems() == 0)
{
$content_set = 0;
return language("lu_no_categories");
}
}
$html_attr = ExtraAttributes($attribs);
$cols = $attribs["_columns"];
if($cols<1)
$cols =1;
$cat_count = (int)$attribs["_maxlistcount"];
/* validation */
if(strlen($attribs["_itemtemplate"])==0)
{
$content_set = 0;
return "ERROR -1";
}
$o="";
$notable = $attribs["_notable"];
$max_categories = $objConfig->Get($objSearchCats->PerPageVar);
$count=0;
$row=0;
$var_list_update["t"] = $var_list["t"];
if(!$notable)
{
$per_row = ceil($objCatList->NumItems()/$cols);
$o = "<TABLE $html_attr><TR CLASS=\"m_list_cats\">";
$o .= "<TD valign=\"top\">";
foreach($objSearchCats->Items as $cat)
{
$parsed=0;
if($count==$per_row)
{
$o .= "</TD><TD valign=\"top\">";
$count=0;
}
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
$o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
$count++;
}
if($count != $per_row)
$o .= "</TD>";
$o .= "\n</tr></table>\n";
}
else
{
//echo "<pre>"; print_r($objSearchCats->Items); echo "</pre>";
foreach($objSearchCats->Items as $cat)
{
//$cat->Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
/* $keywords_found = strstr( strip_tags(strtolower($cat->Data[$objCatList->TitleField])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data[$cat->DescriptionField])), strtolower($keywords));
if(!$keywords) $keywords_found = true;
if ($keywords_found) {*/
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
$o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
$row++;
$i++;
$count++;
if($count == $max_categories) break;
// }
}
}
unset($var_list_update["t"]);
return $o;
}
/*
@description: Parse a template based on the current advanced search type
@attrib:_TypeSelect:tpl:Template to parse if no item type has been selected
@attrib:_ItemSelect:tpl:Template to parse if an item type has been selected to search
*/
function m_advsearch_include($attribs)
{
global $objTemplate;
$TypeSelectTemplate = $attribs["_typeselect"];
$ItemTemplate = $attribs["_itemselect"];
if((strlen($_GET["type"])>0 || $_POST["itemtype"]>0) && ($_GET["Action"]=="m_advsearch_type" || $_GET["Action"]=="m_adv_search"))
{
$o = $objTemplate->ParseTemplate($ItemTemplate);
}
else
$o = $objTemplate->ParseTemplate($TypeSelectTemplate);
return $o;
}
/*
@description: Returns the name of the item type currently being advanced searched
@attrib::_plaintext:bool:If set, simply returns the name of the item if not, builds a language tag (lu_searchtitle_[name])
*/
function m_advsearch_type($attribs)
{
global $objItemTypes;
if($_GET["Action"]=="m_advsearch_type")
{
$ItemType = $_POST["itemtype"];
}
elseif($_GET["Action"]=="m_adv_search")
$ItemType = $_GET["type"];
$o = "";
if((int)$ItemType>0)
{
$Item = $objItemTypes->GetItem($ItemType);
if(is_object($Item))
{
$name = strtolower($Item->Get("ItemName"));
if($attribs["_plaintext"])
{
$o .= $name;
}
else
$o = language("lu_searchtitle_".strtolower($name));
}
}
return $o;
}
/*
@description: Lists advanced search fields for the selected item type
@attrib: _FirstItemTemplate:tpl: Template used for the first field listed
@attrib: _LastItemTemplate:tpl: Template used for the last field listed
@attrib: _AltLastItemTemplate:tpl: Altername Template used for the last field listed
@attrib: _ItemTemplate:tpl: default template used for field list items
@attrib: _AltTemplate:tpl: Alternate template used for field list items
*/
function m_advsearch_fields($attribs)
{
global $objItemTypes, $objTemplate, $objSearchConfig;
if(!is_object($objSearchConfig))
$objSearchConfig = new clsSearchConfigList();
if($_GET["Action"]=="m_advsearch_type")
{
$ItemType = $_POST["itemtype"];
}
elseif($_GET["Action"]=="m_adv_search")
$ItemType = $_GET["type"];
$o = "";
if((int)$ItemType>0)
{
$Item = $objItemTypes->GetItem($ItemType);
if(is_object($Item))
{
$name = strtolower($Item->Get("ItemName"));
$table = $Item->Get("SourceTable");
//$sql = "SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$table' AND AdvancedSearch=1 ORDER BY DisplayOrder";
$sql = "SELECT sc.* FROM ".$objSearchConfig->SourceTable." AS sc LEFT JOIN ".GetTablePrefix()."CustomField AS cf ON sc.CustomFieldId = cf.CustomFieldId WHERE (TableName='$table' OR ((TableName='".GetTablePrefix()."CustomField' OR TableName='CustomField') AND cf.Type = $ItemType)) AND AdvancedSearch=1 ORDER BY sc.DisplayOrder";
$objSearchConfig->Query_Item($sql);
$row=0;
if(is_array($objSearchConfig->Items))
{
$ItemCount = count($objSearchConfig->Items);
foreach($objSearchConfig->Items as $s)
{
$even = (($row+1) % 2 == 0);
$parsed=0;
if($row==0 && strlen($attribs["_firstitemtemplate"]))
{
$o .= $s->ParseTemplate($attribs["_firstitemtemplate"]);
$parsed=1;
}
if($row==$ItemCount-1 && $even && !$parsed && strlen($attribs["_altlastitemtemplate"])>0)
{
$o .= $s->ParseTemplate($attribs["_altlastitemtemplate"]);
$parsed=1;
}
if($row==$ItemCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
{
$o .= $s->ParseTemplate($attribs["_lastitemtemplate"]);
$parsed=1;
}
if(!$parsed)
{
if($even && strlen($attribs["_altitemtemplate"])>0)
{
$o .= $s->ParseTemplate($attribs["_altitemtemplate"]);
}
else
$o .= $s->ParseTemplate($attribs["_itemtemplate"]);
}
$row++;
}
}
}
}
return $o;
}
/*
@description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
are passed to the anchor tag created.
@attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
@attrib: _Module:: Module being linked to (ie In-Bulletin or In-News or In-Link)
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
and the link is created.)
@attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
attribute. If this attirbute is not included and the user does not have access,
nothing is returned. (The link is not created.)
@attrib: _Root:bool: If set, the current category is set to the module's root category
@attrib: _text:lang: language tag to include as text for the anchor tag
@attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
if both are included.
@attrib: _image:: URL to an image to include inside the anchor tag.
@attrib: _image_actions:: Image events.
*/
function m_module_link($attribs = array())
{
global $objCatList, $objSession;
$permission = getArrayValue($attribs,'_perm');
$o = "";
$tpath = GetModuleArray("template");
if(strlen($permission))
{
$perms = explode(",",$permission);
$hasperm = FALSE;
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasCatPermission($perms[$x]))
{
$hasperm = TRUE;
break;
}
}
}
else
$hasperm = TRUE;
if(!$hasperm && getArrayValue($attribs,'_deniedtemplate') )
{
$hasperm = TRUE;
$attribs["_template"]=$attribs["_deniedtemplate"];
}
if($hasperm)
{
$module = $attribs["_module"];
if(ModuleEnabled($module))
{
$t = $tpath[$attribs["_module"]];
$t .= $attribs["_template"];
$attribs["_template"] = $t;
$html_attr = ExtraAttributes($attribs);
if($attribs["_root"])
{
$func = ModuleTagPrefix($module)."_root_link";
if(function_exists($func))
{
$url = $func($attribs);
}
else
$url = m_template_link($attribs);
}
else
$url = m_template_link($attribs);
$o = "<A $html_attr HREF=\"";
$o .= $url;
$o .= "\"> ";
$text = getArrayValue($attribs,'_text');
if(!strlen($text))
{
$text = getArrayValue($attribs,'_plaintext');
if(!strlen($text))
{
if(strlen($attribs["_image"]))
{
$text = "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\" alt=\"\">";
}
}
$o .= $text."</A>";
}
else
$o .= language($text)."</A>";
}
else
{
$o = "";
}
}
return $o;
}
/*
@description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
are passed to the anchor tag created.
@attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index")
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
and the link is created.)
@attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
attribute. If this attirbute is not included and the user does not have access,
nothing is returned. (The link is not created.)
@attrib: _text:lang: language tag to include as text for the anchor tag
@attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence
if both are included.
@attrib: _image:: URL to an image to include inside the anchor tag.
*/
function m_permission_link($attribs = array())
{
global $objCatList, $objSession;
$permission = $attribs["_perm"];
$o = "";
if(strlen($permission))
{
$perms = explode(",",$permission);
$hasperm = FALSE;
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasCatPermission($perms[$x]))
{
$hasperm = TRUE;
break;
}
}
}
else
$hasperm = TRUE;
if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
{
$hasperm = TRUE;
$attribs["_template"]=$attribs["_deniedtemplate"];
}
if($hasperm)
{
$url = m_template_link($attribs);
$o = "<A $html_attr HREF=\"";
$o .= $url;
$o .= "\"> ";
$text = $attribs["_text"];
if(!strlen($text))
{
$text = $attribs["_plaintext"];
if(!strlen($text))
{
if(strlen($attribs["_image"]))
{
$text = "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\" alt=\"\">";
}
}
$o .= $text."</A>";
}
else
$o .= language($text)."</A>";
}
else
{
$o = "";
}
return $o;
}
function m_confirm_password_link($attribs = array())
{
global $m_var_list_update, $var_list_update, $objSession, $objConfig;
$template = "forgotpw_reset_result";
// $user = $objSession->Get("tmp_user_id").";".$objSession->Get("tmp_email");
$tmp_user_id = $objSession->Get("tmp_user_id");
$conn = &GetADODBConnection();
$code = md5(GenerateCode());
$sql = 'UPDATE '.GetTablePrefix().'PortalUser SET PwResetConfirm="'.$code.'", PwRequestTime='.adodb_mktime().' WHERE PortalUserId='.$tmp_user_id;
$query = "&user_key=".$code."&Action=m_resetpw";
$conn->Execute($sql);
$var_list_update["t"] = $template;
$ret = ($attribs["_secure"]?"https://":"http://").ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv().$query;
return $ret;
}
/**
* Returns result of password reset confirmation
* code validation as appropriate phrase
*
* @return string
* @example <inp:m_codevalidationresult />
*/
function m_codevalidationresult($attribs=Array())
{
global $objSession;
$result_phrase = $objSession->GetVariable('codevalidationresult');
return $result_phrase ? language($result_phrase) : '';
}
/*
@description: Create a link to a template.
@attrib: _Template:tpl: Template to link to (ex: "inbulletin/post_list")
@attrib: _Query:str: Extra query sring to be added to link URL (ex: "&test=test")
@attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
@attrib: _anchor:: If included, a local anchor (#) is added. (ex: _anchor="top" results in <A HREF="..#top">)
@attrib: _Root:bool:If set, gets module root category id
@attrib: _Module:str:Module Name
@attrib: _Relative:bool: Is set, creates an relative url url (../..address)
@example: <a href="<inp:m_template_link _Template="index" _Category=0 />"><inp:m_language _Phrase="lu_home" /></a>
*/
function m_template_link($attribs = array())
{
global $var_list, $var_list_update, $m_var_list_update, $objCatList;
$var_list_update['t'] = getArrayValue($attribs,'_template') ? $attribs['_template'] : $var_list['t'];
$query_string = trim( getArrayValue($attribs,'_query') );
$url_params = $query_string ? ExtractParams($query_string) : Array();
$cat = getArrayValue($attribs, '_category');
if($cat !== false) $m_var_list_update['cat'] = ($cat == 'NULL') ? 0 : $cat;
if( getArrayValue($attribs,'_anchor') ) $url_params['anchor'] = $attribs['_anchor'];
$ret = HREF_Wrapper('', $url_params);
unset( $var_list_update['t'] );
if($cat) unset( $m_var_list_update['cat'] );
return $ret;
}
/*
@description: create a link to a template based on user permissions. All extra HTML attributes are passed to the anchor tag created.
@attrib: _Template:tpl: Template to link to if the user has access
@attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm
attribute. If this attirbute is not included and the user does not have access,
the "login" template is used.
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list,
the link will be generated. (If the _DeniedTemplate attribute is set, this template is used
and the link is created.)
@attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
@attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
@example: <a href="<inp:m_access_template_link _Template="my_account" _DeniedTemplate="login" _Perm="login" />"><inp:m_language _Phrase="lu_myaccount" /></A>
*/
function m_access_template_link($attribs = array(), $Permission="")
{
global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
$cat = getArrayValue($attribs,'_category');
if(strlen($cat))
{
if($cat=="NULL")
$cat = 0;
}
else
$cat = $objCatList->CurrentCategoryID();
if(!strlen($Permission))
{
$Permission = strtoupper($attribs["_perm"]);
}
$o = "";
$hasperm = FALSE;
if(strlen($Permission))
{
$perms = explode(",",$Permission);
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasCatPermission(trim($perms[$x]),$cat))
{
$hasperm = TRUE;
break;
}
}
if(!$hasperm && $attribs["_system"])
{
for($x=0;$x<count($perms);$x++)
{
if($objSession->HasSystemPermission(trim($perms[$x])))
{
$hasperm = TRUE;
break;
}
}
}
}
$url_params = Array('dest' => '');
$access = $attribs["_template"];
$denied = $attribs["_deniedtemplate"];
if(!strlen($denied))
$denied = "login";
$m_var_list_update["cat"] = $cat;
if($hasperm)
{
$template = $access;
if(!strlen($template))
$template = $var_list["t"];
$var_list_update["t"] = $template;
}
else
{
$template = $denied;
if(!strlen($template))
$template = $var_list["t"];
if($template == "login")
{
$url_params['dest'] = $access;
}
$var_list_update["t"] = $template;
}
if( !$url_params['dest'] ) unset($url_params['dest']);
$ret = HREF_Wrapper('', $url_params);
unset($var_list_update["t"]);
return $ret;
}
/*
@description: returns a text based on user permissions. Text from inside of the tag will be returned if text attributes are not specified and user has permissions to category, or if _NoPerm attribute set to 1 and user doesn't have permissions. Otherwise entire section will be excluded.
@attrib: _Text:lang: Template to link to if the user has access
@attrib: _PlainText:: This template is used if the user does not have a permission listed in the _perm attribute. If this attirbute is not included and the user does not have access, the "login" template is used.
@attrib: _DenyText:lang: Template to link to if the user has access
@attrib: _PlainDenyText:: This exact text is used if the user does not have a permission listed in the _perm attribute and _DenyText attribute is not set.
@attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, the link will be generated.
@attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN)
@attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged
@attrib: _MatchAllPerms:int: Checks for all listed Permissions to be TRUE. Note: this attribute is rarely used.
@attrib: _NoPerm:int: The whole tag will return inner text if user has no permissions and attribute set to 1. Default value is 0.
@example: <inp:m_perm_text _Text="!lu_allow_language_tag!" _PlainText="Just a text" _DenyText="!lu_deny_language_tag!" _PlainDenyText="Just a plain text" _Perm="login" _MatchAllPerms="1" _NoPerm="0">Some HTML here!</inp>
*/
function m_perm_text($attribs = array())
{
global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
$cat = getArrayValue($attribs,'_category');
if(strlen($cat))
{
if($cat=="NULL")
$cat = 0;
}
else
$cat = $objCatList->CurrentCategoryID();
//if(!strlen($Permission))
$Permission = strtoupper($attribs["_perm"]);
$o = "";
$hasperm = FALSE;
$count = 0;
if(strlen($Permission))
{
$perms = explode(",",$Permission);
for($x=0;$x<count($perms);$x++)
{
$_AllPermsCount[$count] = 0;
if($objSession->HasCatPermission($perms[$x],$cat))
{
$hasperm = TRUE;
$_AllPermsCount[$count] = 1;
// break;
}
$count++;
}
if( !$hasperm && getArrayValue($attribs,'_system') )
{
for($x=0; $x<count($perms); $x++)
{
$_AllPermsCount[$count] = 0;
if($objSession->HasSystemPermission($perms[$x]))
{
$hasperm = TRUE;
$_AllPermsCount[$count] = 1;
// break;
}
$count++;
}
}
}
if ((int)getArrayValue($attribs,'_matchallperms'))
{
if (count($_AllPermsCount) != array_sum($_AllPermsCount))
$hasperm = FALSE;
}
$text = getArrayValue($attribs,'_text');
$plaintext = getArrayValue($attribs,'_plaintext');
$denytext = getArrayValue($attribs,'_denytext');
$plaindenytext = getArrayValue($attribs,'_plaindenytext');
$nopermissions_status = (int)getArrayValue($attribs,'_noperm')? 1 : 0;
//if(!strlen($denied)) $denied = "login";
if (!$nopermissions_status)
{
if ($hasperm)
{
if (strlen($text) || strlen($plaintext))
{
$ret = strlen($text)? language($text) : $plaintext;
}
else
{
$ret = "1";
}
}
else
{
$ret = strlen($denytext)? language($denytext) : $plaindenytext;
}
}
elseif (!$hasperm)
{
$ret = "1";
}
return $ret;
}
/*
@description: Returns the error string associated with a permission
*/
function m_permission_error($attribs = array())
{
global $objPermissions;
$ret = "";
$perm = strtoupper($_GET["error"]);
if(strlen($perm))
{
$ado = &GetADODBConnection();
$sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName ='$perm'";
$rs = $ado->Execute($sql);
if($rs && !$rs->EOF)
{
$data = $rs->fields;
$error_tag = $data["ErrorMessage"];
}
else
$error_tag = "lu_unknown_error";
$ret = language($error_tag);
}
return $ret;
}
/*
@description: Returns the error text encountered when parsing templates
*/
function m_template_error($attribs = array())
{
global $objTemplate;
$ret = "";
if($objTemplate->ErrorNo<0)
{
$ret = $objTemplate->ErrorStr;
}
return $ret;
}
/*
@description: Creates a category navigation bar
@attrib: _Template:tpl: template to use for navigation links
@attrib: _RootTemplate:bool: If set, this template is linked to for the root category
@attrib: _LinkCurrent:bool: If set, the last (current) category is linked. Otherwise the current category is simply displayed
@attrib: _Separator:: text to display between levels of the navigation bar
@attrib: _Root:: Root category configuration variable to use. (ex: Link for In-Link's root category) If not set, the system root is used
@example: <inp:m_navbar _RootTemplate="index" _Template="inbulletin/index" _LinkCurrent="1" _separator=" &gt; " />
*/
function m_navbar($attribs = array())
{
global $m_var_list_update, $var_list, $objCatList, $objConfig, $objModules;
$separator = getArrayValue($attribs, '_separator');
if(!$separator) $separator = "<span class=\"NAV_ARROW\"> > </span>";
$admin = (int)getArrayValue($attribs, 'admin');
$t = getArrayValue($attribs, '_template');
$LinkLeafNode = getArrayValue($attribs, '_linkcurrent');
$catid = (int)getArrayValue($attribs, '_catid');
if( getArrayValue($attribs, '_root') )
{
$var = getArrayValue($attribs, '_root')."_Root";
$Root = (int)$objConfig->Get($var);
}
else
$Root = 0;
$RootTemplate = getArrayValue($attribs, '_roottemplate');
if($RootTemplate === false) $RootTemplate = '';
$Module = getArrayValue($attribs, '_module');
$ModuleRootTemplate = '';
if($Module)
{
$ModuleRootCat = $objModules->GetModuleRoot($Module);
if($ModuleRootCat>0)
{
$modkey = "_moduleroottemplate";
$ModuleRootTemplate = getArrayValue($attribs, $modkey);
}
else
$ModuleRootTemplate="";
}
else
$ModuleRootCat = 0;
if(!$catid)
$catid = $objCatList->CurrentCategoryID();
$ret = $objCatList->cat_navbar($admin, $catid, $t, $separator,$LinkLeafNode,$Root,$RootTemplate,$ModuleRootCat,$ModuleRootTemplate);
return $ret;
}
/*
@description: Parse a category field and return the value
@attrib: _Field:: Category field to parse
@attrib: _CatId:int: Category ID to parse (uses current category if not set)
@attrib: _StripHTML:bool: if set, all HTML is removed from the output
*/
function m_category_field($attribs)
{
global $objCatList;
$ret = "";
$catid = (int)getArrayValue($attribs,'_catid');
$field = $attribs["_field"];
if(!$catid)
$catid = $objCatList->CurrentCategoryID();
if(strlen($field))
{
$cat =& $objCatList->GetCategory($catid);
if(is_object($cat))
{
$element = new clsHtmlTag();
$element->name=$cat->TagPrefix;
$element->attributes = $attribs;
$ret = $cat->ParseObject($element);
}
}
if(getArrayValue($attribs,'_striphtml'))
$ret = strip_tags($ret);
return $ret;
}
/*
@description: returns the date of the last modification to a category
@attrib: _Part:: part of the date to display
@attrib: _Local:bool: If set, only subcategories of the current category is checked
@example: <inp:m_category_modified />
*/
function m_category_modified($attribs)
{
global $objConfig, $objCatList;
$ado = &GetADODBConnection();
$ret='';
if(getArrayValue($attribs,'_local') && $objCatList->CurrentCategoryID() != 0)
{
$c =& $objCatList->GetItem($objCatList->CurrentCategoryID());
$catlist = $c->GetSubCatIds();
$catwhere = "CategoryId IN (".explode(",",$catlist).")";
$sql = "SELECT MAX(Modified) as ModDate,MAX(CreatedOn) as NewDate FROM ".GetTablePrefix()."Category ";
$sql .= "INNER JOIN ".GetTablePrefix()."CategoryItems ON (".GetTablePrefix()."Category.ResourceId=".GetTablePrefix()."CategoryItems.ItemResourceId) ";
$sql .= "WHERE $catwhere LIMIT 1";
}
else
{
$sql = "SELECT MAX(Modified) as ModDate FROM ".GetTablePrefix()."Category LIMIT 1";
}
$rs = $ado->Execute($sql);
if($rs && ! $rs->EOF)
{
$mod = $rs->fields["ModDate"];
if($mod)
{
$part = strtolower(getArrayValue($attribs,'_part'));
$ret = $part?ExtractDatePart($part,$mod):LangDate($mod);
}
}
return $ret;
}
/*
@description: creates LINK tags to include all module style sheets
@attrib: _Modules:: Accepts a comma-separated list of modules to include (ie: "In-Link, In-News, In-Bulletin")
@attrib: _*css:none: Each module may set a custom-named stylesheet. For example, for In-Link the attribute would be _In-Linkcss="..".
If a module does not have a *css attribute, the default (style.css) is assumed.
@example: <inp:m_module_stylesheets _Modules="In-Portal,In-News,In-Bulletin,In-Link" _In-PortalCss="incs/inportal_main.css" />
*/
function m_module_stylesheets($attribs)
{
global $TemplateRoot;
$require_css = explode(',', trim($attribs['_modules']) );
$tpath = GetModuleArray('template');
$ret = '';
foreach($require_css as $module_name)
{
$css_attr = '_'.strtolower($module_name).'css';
$mod_css = getArrayValue($attribs,$css_attr) ? $attribs[$css_attr] : 'style.css';
$file = $TemplateRoot.getArrayValue($tpath,$module_name).$mod_css;
if( file_exists($file) )
{
$ret .= '<link rel="stylesheet" href="'.$tpath[$module_name].$mod_css.'" type="text/css" />'."\n";
}
}
return $ret;
}
/*
@description: lists items related to a category
@attrib:CatId:int: Category ID of category, or current category if not set
@attrib:_ListItem:string: Comma-separated list of item types (ie: Link, Topic, Category, News) The items are listed in the order this list provides, then by priority.
Each item should have its own template passed in as an attribute (_{ItemType}Template)
*/
function m_related_items($attribs)
{
global $objItemTypes, $objCatList, $content_set, $CatRelations;
static $Related;
$cat = getArrayValue($attribs,'_catid');
if(!is_numeric($cat))
{
$cat = $objCatList->CurrentCategoryID();
}
$c =& $objCatList->GetCategory($cat);
$data_sent=0;
if(is_object($c))
{
$ResourceId = $c->Get("ResourceId");
$IncludeList = explode(",",trim(strtolower($attribs["_listitems"])));
$o = "";
if(!is_object($CatRelations))
{
$CatRelations = new clsMultiTypeList();
LoadRelatedItems($Related, $CatRelations,$c->Get("ResourceId"));
}
if($CatRelations->NumItems()>0)
{
for($inc=0;$inc<count($IncludeList);$inc++)
{
$t_attr = "_".$IncludeList[$inc]."template";
$t = $attribs[$t_attr];
$item_type = $IncludeList[$inc];
if(strlen($item_type))
{
$objType = $objItemTypes->GetTypeByName($item_type);
if(is_object($objType))
{
foreach($CatRelations->Items as $item)
{
if(is_object($item))
{
if(strtolower($objType->Get("ItemName")) == strtolower($item_type) && $item->type==$objType->Get("ItemType"))
{
if(strlen($item->BasePermissionName))
{
$perm = $item->BasePermissionName.".VIEW";
$haspem = $objSession->HasCatPermission($perm,$item->Get("CategoryId"));
}
else
$hasperm = 1;
if($hasperm)
{
$data_sent =1;
$classname = $objType->Get("ClassName");
if(strlen($classname))
{
$l = new $classname;
$l->Data = $item->Data;
$o .= $l->ParseTemplate($t);
}
}
}
}
$item = NULL;
}
}
else
echo $item_type." not found <br>\n";
}
}
if($data_sent)
{
return $o;
}
else
{
$content_set=0;
return "";
}
}
else
{
$content_set = 0;
return "";
}
}
else
{
$content_set = 0;
return "";
}
}
/*
@description: Returns the number of items related to the current category
@attrib:_CatId:int: If set, this is the category ID to use, otherwise the current category is used
@attrib:_ItemType::Name of item to count. If not set, all related items are counted
*/
function m_related_count($attribs)
{
global $objItemTypes, $objCatList, $content_set, $CatRelations;
$cat = getArrayValue($attribs,'_catid');
if(!is_numeric($cat))
{
$cat = $objCatList->CurrentCategoryID();
}
$c =& $objCatList->GetCategory($cat);
$data_sent=0;
//echo "Category: $cat<pre>"; print_r($c); echo " </pre>";
if(is_object($c))
{
$ResourceId = $c->Get("ResourceId");
if(!is_object($CatRelations))
{
$CatRelations = new clsMultiTypeList();
LoadRelatedItems($Related, $CatRelations, $c->Get("ResourceId"));
}
$item_type = getArrayValue($attribs,'_itemtype');
if(strlen($item_type))
{
$objType = $objItemTypes->GetTypeByName($item_type);
if(is_object($objType))
{
$TargetType = $objType->Get("ItemType");
}
else
$TargetType="";
}
$count=0;
if($CatRelations->NumItems()>0)
{
for($x=0;$x<$CatRelations->NumItems();$x++)
{
$a = $CatRelations->GetItemByIndex($x);
if($a->type == $TargetType || !strlen($TargetType))
{
$count++;
}
}
}
}
return $count;
}
/*
@description: Returns the MetaKeywords field for a category, or the system MetaKeywords value if the category doesn't have a value for MetaKeywords
@attrib: _CatId:int: Category to use (The current category is used by default)
*/
function m_meta_keywords($attribs = array())
{
global $objCatList, $objConfig;
$application =& kApplication::Instance();
if ($application->isModuleEnabled('In-Edit')) {
$keywords = $application->ProcessTag('cms:PageInfo type="meta_keywords"');
if ($keywords) {
return $keywords;
}
}
$keywords = '';
$catid = (int)getArrayValue($attribs, '_catid');
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
if ($catid)
{
$c = $objCatList->GetItem($catid);
$keywords = $c->Get('MetaKeywords');
}
if (!$keywords)
{
$keywords = $objConfig->Get('Category_MetaKey');
}
return $keywords;
}
/*
@description: Returns the MetaDescription field for a category, or the system MetaDescription value if the category doesn't have a value for MetaDescription
@attrib: _CatId:int: Category to use (The current category is used by default)
*/
function m_meta_description($attribs = array())
{
global $objCatList, $objConfig;
$application =& kApplication::Instance();
if ($application->isModuleEnabled('In-Edit')) {
$description = $application->ProcessTag('cms:PageInfo type="meta_description"');
if ($description) {
return $description;
}
}
$description = '';
$catid = (int)getArrayValue($attribs, '_catid');
if (!$catid)
{
$catid = $objCatList->CurrentCategoryID();
}
if ($catid)
{
$c = $objCatList->GetItem($catid);
$description = $c->Get('MetaDescription');
}
if (!$description)
{
$description = $objConfig->Get('Category_MetaDesc');
}
return $description;
}
/*
@description: return the number of items in the database
@attrib: _ItemType:: Name of item to count
@attrib: _ListType:: Type of item to count (ie: favorites, editor's pick, etc)
@attrib: _CategoryCount:int: Limit scope to the current category
@attrib: _SubCats:bool: Count items in all subcategories (_CategoryCount must be set)
@attrib: _Today:bool: Count items added today
@attrib: _GroupOnly:bool: Only count items the current user can view
@attrib: _NoCache:bool: Count without using cache
*/
function m_itemcount($attribs = array())
{
global $objItemTypes, $objCatList, $objSession, $objCountCache;
$Bit_None = 0;
$Bit_Today = 1;
$Bit_Owner = 2;
$Bit_Global = 4;
$Bit_SubCats=8;
if(getArrayValue($attribs,'_categorycount'))
{
$evar = m_BuildEnv();
}
else
$evar = "";
$cat = getArrayValue($attribs,'_catid');
if(!is_numeric($cat))
{
$cat = $objCatList->CurrentCategoryID();
}
if((int)$cat>0)
$c = $objCatList->GetCategory($cat);
if(is_numeric($attribs["_itemtype"]))
{
$item = $objItemTypes->GetItem($attribs["_itemtype"]);
}
else
$item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
$DoUpdate=0;
//echo "<pre>"; print_r($item); echo "</pre>";
$ExtraId="";
if(is_object($item))
{
if($item->Get("ItemType")==1) /* counting categories */
{
$ret = $objCatList->CountCategories($attribs);
}
else
{
$ListVar =& GetItemCollection($attribs["_itemtype"]);
if(is_object($ListVar))
{
//echo get_class($ListVar)."<br>";
//print_pre($attribs);
$ret = $ListVar->PerformItemCount($attribs);
//echo "m_itemcount: $ret<br>";
}
}
}
else
$ret = 0;
return !$ret ? 0 : $ret;
}
/*
@description: Parse a User field and return the value
@attrib: _Field:: User field to parse
@attrib: _UserId:int: Category ID to parse (uses current user if not set)
*/
function m_user_field($attribs)
{
global $objUsers, $objSession;
$o = "";
$userid = getArrayValue($attribs,'_userid');
if(!is_numeric($userid) || $userid=="0")
$userid = $objSession->Get("PortalUserId");
if($userid)
{
$u =& $objUsers->GetItem($userid);
if(is_object($u))
{
$element = new clsHtmlTag();
$element->name = $u->TagPrefix;
$element->attributes = $attribs;
$o = $u->ParseObject($element);
}
}
return $o;
}
/*
@description: Parses a user template
@attrib:_Template:tpl: Template to parse
@attrib:_UserId:int: User ID to parse. If not set, the current user is used
*/
function m_user_detail($attribs = array())
{
global $objTemplate, $objUsers, $objSession;
$tname = $attribs["_template"];
$UserId = (int)$attribs["_userid"];
if(!$UserId)
{
$UserId=$objSession->Get("PortalUserId");
}
if($UserId>0)
{
$u = $objUsers->GetUser($UserId);
$o = $u->ParseTemplate($tname);
}
else
{
$u = new clsPortalUser(NULL);
$o = $u->ParseTemplate($tname);
}
return $o;
}
/*
@description: returns a user field from the current profile being viewed
@example:<inp:m_user_profile_field _Field="login" />
*/
function m_user_profile_field($attribs = array())
{
if((int)$_GET["UserId"])
{
$attribs["_userid"] = $_GET["UserId"];
}
$ret = m_user_field($attribs);
/* if ($ret == '') {
$ret = admin_language("lu_Guest");
}*/
return $ret;
}
/*
@description: Parses a user profile template
@attrib:_Template:tpl: Template to parse
@attrib:_UserId:int: User ID to parse. If not set, the current user is used
*/
function m_user_profile_detail($attribs)
{
if((int)$_GET["UserId"])
{
$attribs["_userid"] = $_GET["UserId"];
}
$ret = m_user_detail($attribs);
return $ret;
}
/*
@description: Lists all user profile fields the user has indicated to be public
@attrib: _ItemTemplate:tpl: Template used to list each field
@example:<inp:m_user_profile _ItemTemplate="view_profile_field" />
*/
function m_user_profile($attribs = array())
{
global $objTemplate, $objUsers;
$tname = $attribs["_itemtemplate"];
$t = $objTemplate->GetTemplate($tname);
if(is_object($t))
{
$html = $t->source;
}
$userid = $_GET["UserId"];
$o = "";
if((int)$userid>0)
{
$u = $objUsers->GetItem($userid);
$vars = $u->GetAllPersistantVars();
foreach($vars as $field=>$value)
{
if(substr($field,0,3)=="pp_")
{
if($value==1)
{
$src = $html;
$src = str_replace("<inp:user_profile_field />","<inp:user _field=\"".substr($field,3)."\" />",$src);
$src = str_replace("lu_profile_field","lu_".$field,$src);
$o .= $u->ParseTemplateText($src);
}
}
}
}
return $o;
}
/*
@description: List users the current user has marked as 'friend'
@attrib: _Status:: Determines which online status to list, either "online" or "offline".
@attrib: _ItemTemplate:tpl: Template used to parse list items
*/
function m_list_friends($attribs = array())
{
global $objUsers, $objSession;
global $online_friends;
$ado = &GetADODBConnection();
$status = strtolower($attribs["_status"]);
$logedin_user = $objSession->Get("PortalUserId");
$u =& $objUsers->GetUser($logedin_user);
//echo "<pre>"; print_r($u); echo "</pre>";
if(!isset($online_friends) || $status=="online")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
if(isset($online_friends))
{
foreach($online_friends as $id=>$name)
{
$u =& $objUsers->GetUser($id);
$o .= $u->ParseTemplate($attribs["_itemtemplate"]);
}
}
else
{
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
$sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
//echo $sql;
$rs = $ado->Execute($sql);
while($rs && ! $rs->EOF)
{
$u =& $objUsers->GetItem($rs->fields["PortalUserId"]);
if($status=="online")
{
$o .= $u->ParseTemplate($attribs["_itemtemplate"]);
}
$online_friends[]=$rs->fields["PortalUserId"];
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
}
}
if($status=="offline")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
$sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
if(count($online_friends)>0)
{
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
$sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
else
{
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
//echo $sql;
$rs = $ado->Execute($sql);
while($rs && ! $rs->EOF)
{
$u = $objUsers->GetItem($rs->fields["PortalUserId"]);
$o .= $u->ParseTemplate($attribs["_itemtemplate"]);
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
}
$t = $attribs["_itemtemplate"];
return $o;
}
/*
@description: Returns the number of users the current user has marked as 'friend'
@attrib: _Status:: Determines which online status to count, either "online" or "offline".
*/
function m_friend_count($attribs=array())
{
global $objUsers, $objSession;
global $online_friends;
$ado = &GetADODBConnection();
$logedin_user = $objSession->Get("PortalUserId");
$u =& $objUsers->GetUser($logedin_user);
$status = strtolower($attribs["_status"]);
if(!isset($online_friends) || $status=="online")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
if(isset($online_friends) && $status="online")
{
return count($online_friends);
}
else
{
$online_friends = array();
$sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
$sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
//echo $sql."<br>\n";
$rs = $ado->Execute($sql);
while($rs && ! $rs->EOF)
{
$online_friends[$rs->fields["PortalUserId"]]=$rs->fields["PortalUserId"];
if(ADODB_EXTENSION>0)
{
adodb_movenext($rs);
}
else
$rs->MoveNext();
}
if($status=="online")
return count($online_friends);
}
}
if($status=="offline")
{
$ftable = GetTablePrefix()."Favorites";
$stable = GetTablePrefix()."UserSession";
$ptable = GetTablePrefix()."PortalUser";
$sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
if(count($online_friends)>0)
{
$sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
$sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
else
{
$sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
$sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];
}
$rs = $ado->Execute($sql);
return $rs->fields["ItemCount"];
}
}
/*
@description: Returns the number of users the current user has marked as 'friend' today
*/
function m_friend_count_today($attribs)
{
global $objSession;
$logedin_user = $objSession->Get("PortalUserId");
$ret =0;
$ado = &GetADODBConnection();
$today = adodb_mktime(0, 0, 0, adodb_date("m"), adodb_date("d"), adodb_date("Y"));
$sql = "SELECT count(*) as c FROM ".GetTablePrefix()."Favorites WHERE ItemTypeId=6 and PortalUserId=".$objSession->Get("PortalUserId")." AND Modified>$today";
$rs = $ado->Execute($sql);
if($rs && !$rs->EOF)
$ret = $rs->fields["c"];
return $ret;
}
/*
@description: Returns the number of items in a search result
@Example: <span>(<inp:m_search_item_count _ItemType="Topic" />)</span>
*/
function m_search_item_count($attribs)
{
global $objItemTypes, $objCatList, $objSession, $CountVal;
if(!is_array($CountVal))
$CountVal=array();
$item = $objItemTypes->GetTypeByName($attribs["_itemtype"]);
if(is_object($item))
{
$val = $CountVal[$item->Get("ItemType")];
if(is_numeric($val))
return $val;
$where = "ItemType=".$item->Get("ItemType");
$table = $objSession->GetSearchTable();
$ret = TableCount($table,$where,0);
$CountVal[$item->Get("ItemType")]=(int)$ret;
}
return $ret;
}
/*
@description: Returns the number of categories in a search result
@Example: <span>(<inp:m_search_cat_count />)</span>
*/
function m_search_cat_count($attribs = array())
{
global $objItemTypes, $objCatList, $objSession, $CountVal, $objSearchCats;
if(!is_object($objSearchCats))
{
$objSearchCats = new clsCatList();
$objSearchCats->SourceTable = $objSession->GetSearchTable();
$objSearchCats->Clear();
}
if( !clsParsedItem::TableExists( $objSearchCats->SourceTable ) )
{
return 0;
}
LoadCatSearchResults($attribs);
//echo "<pre>"; print_r($objSearchCats->Items); echo "</pre>";
$ret = 0;
$keywords = $objSession->GetVariable("Search_Keywords");
/*if ($keywords) {
foreach ($objSearchCats->Items as $cat) {
if (strstr(strip_tags(strtolower($cat->Data[$objCatList->TitleField])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data[$cat->DescriptionField])), strtolower($keywords))) {
$ret++;
}
}
}*/
//else {
$ret = $objSearchCats->QueryItemCount;
//}
if ($ret == '') {
$ret = 0;
}
//echo $ret;
//$objSearchCats->QueryItemCount = $ret;
return $ret;
}
/*
@description: Returns super global variable by type and name
@attrib: _Name:: Name of variable
@attrib: _Type:: Type super global variable <br>Possible Values:
<UL>
<LI>get: $_GET super variable
<LI>post: $_POST super variable
<LI>cookie: $_COOKIE super variable
<LI>env: $_ENV super variable
<LI>server: $_SERVER super variable
<LI>session: $_SESSION super variable
</UL>
@Example: <inp:m_get_var _name="url" _type="get" />
*/
function m_get_var($attribs = array())
{
$type = strtoupper( $attribs['_type'] );
$name = $attribs['_name'];
$array_name = '_'.$type;
$vars = $GLOBALS[ isset( $GLOBALS[$array_name] ) ? $array_name : '_POST' ];
return $vars[$name];
}
/*
@description: Returns number of users currently on-line
@attrib: _LastActive:: Last user/session activity in seconds
@attrib: _OwnCount:bool: Count user's own session
*/
function m_users_online($attribs = array())
{
global $objSession;
$LastActive = (int)($attribs['_lastactive']);
$OwnCount = (int)($attribs['_owncount']);
if ($LastActive && !is_null($LastActive))
$sql_add = " AND LastAccessed>".(adodb_mktime()-$LastActive);
if (!$OwnCount || is_null($OwnCount))
$sql_add.= " AND SessionKey!='".$objSession->GetSessionKey()."'";
$ado = &GetADODBConnection();
$sql = "SELECT COUNT(*) AS Counter FROM ".GetTablePrefix()."UserSession WHERE Status=1".$sql_add;
$rs = $ado->Execute($sql);
$ret = ($rs && !$rs->EOF)? $rs->fields["Counter"] : 0;
return $ret;
}
function m_debug_mode($attribs = array())
{
$const_name = $attribs['_debugconst'];
return defined($const_name) && (constant($const_name) == 1) ? 'yes' : '';
}
function m_info($attribs = array())
{
switch ($attribs['_infotype'])
{
case 'site':
global $objConfig;
$ret = ThisDomain().$objConfig->Get('Site_Path');
break;
default:
$ret = '';
break;
}
return $ret;
}
function m_module_enabled($attribs = array())
{
global $objModules;
$module = $attribs['_module'];
// check if module is installed
$ModuleItem = $objModules->GetItemByField('Name', $module);
if( !is_object($ModuleItem) ) return '';
// module is enabled
$ret = $ModuleItem->Get('Loaded') == 1;
// check if installed module is licensed
return $ret ? 'yes' : '';
}
function m_recall($attribs = array())
{
global $objSession;
return $objSession->GetVariable($attribs['_name']);
}
function m_regional_option($attribs = array())
{
return GetRegionalOption($attribs['_name']);
}
/*
@description: Returns a sitemap
@attrib: _CatId:int: Top Level Catagory ID to start sitemap with.
@attrib: _ModuleName:: Module name (optional, default none)
@attrib: _MainItemTemplate:tpl: Item template for Top level category
@attrib: _SubCatItemTemplate:tpl: Item template for Sub categories
@attrib: _MaxDepth:: Max Depth, default all, minimum 2
@attrib: _MaxCats:: Maximum number of Categories for each Module, default 300
*/
function m_sitemap($attribs = array())
{
global $objModules, $objConfig, $objCatList, $m_var_list;
$backup_m_var_list = $m_var_list;
$html_attribs = ExtraAttributes($attribs);
$mod_name = getArrayValue($attribs, "_modulename");
$StartCatId = getArrayValue($attribs, "_catid");
$MaxDepth = (int)getArrayValue($attribs, "_maxdepth");
$MaxCats = getArrayValue($attribs, "_maxcats");
$MaxCats = !empty($MaxCats) ? (int)$MaxCats : 300;
if ($MaxDepth == 0)
unset($MaxDepth);
elseif ($MaxDepth < 2)
$MaxDepth = 2;
$MainItemTemplate = getArrayValue($attribs, "_mainitemtemplate");
$SubCatItemTemplate = getArrayValue($attribs, "_subcatitemtemplate");
if (!strlen($SubCatItemTemplate))
$SubCatItemTemplate = "sitemap_subcat_element";
if (!strlen($MainItemTemplate))
$MainItemTemplate = "sitemap_cat_element";
$cols = getArrayValue($attribs, "_columns");
$cols = ($cols<1)? 2 : $cols;
if (!isset($StartCatId))
{
if (!strlen($mod_name))
{
$_RootCat = 0;
}
else
{
$_RootCat = $objModules->GetModuleRoot($mod_name);
}
}
else
{
$_RootCat = (int)$StartCatId? (int)$StartCatId : 0;
}
// Get Root Categories of all installed Modules
if (is_array($objModules->Items))
{
foreach ($objModules->Items as $curr_mod)
{
if( !$curr_mod->Get('Loaded') || ($curr_mod->Get('Name') == 'In-Portal') ) continue;
$mod_name = (int)$curr_mod->Get('RootCat');
if( !empty($mod_name) )
{
$modules[$mod_name] = !isset($modules[$mod_name]) ? $curr_mod->Get('TemplatePath') : '';
}
else
{
$modules[$mod_name] = '';
}
}
}
$_C_objCat = new clsCatList();
$_Where = GetTablePrefix()."Category.ParentId = $_RootCat AND Status = 1";
$_OrderBy = " ORDER BY ".GetTablePrefix()."Category.Priority DESC ";
$_C_catList = $_C_objCat->LoadCategories($_Where, $_OrderBy, false);
## getting TOP level categories
if( is_array($_C_catList) && count($_C_catList) )
{
$ret = "<TABLE $html_attribs><TR CLASS=\"m_list_cats\">";
$ret.= "<TD valign=\"top\">";
$CatCount = $_C_objCat->NumCategories();
$per_row = ceil($CatCount / $cols);
foreach ($_C_catList as $cat)
{
$text = $cat->Get($objCatList->TitleField);
$val = $cat->Get("CategoryId");
$sub_path = $cat->Get("ParentPath");
$add_path = "";
if( is_array($modules) )
{
foreach($modules as $curr => $v)
{
if (strpos($sub_path, "|$curr|") !== false)
{
$add_path = $v;
break;
}
}
}
if(!$add_path) continue;
$main_templ = $add_path.$MainItemTemplate;
$ret.= $cat->ParseTemplate($main_templ);
$count++;
$row++;
$_C_objCatSubs = new clsCatList();
$ParentPath = empty($_RootCat) ? '|'.$val.'|%' : '|'.$_RootCat.'|'.$val.'|%';
$_Where = GetTablePrefix()."Category.ParentPath LIKE '$ParentPath' AND ".GetTablePrefix()."Category.CategoryId!=$val AND Status=1";
$_OrderBy = " ORDER BY ".GetTablePrefix()."Category.ParentPath ASC, ".GetTablePrefix()."Category.".$objCatList->TitleField." ASC";
$old_value = $objConfig->Get($_C_objCatSubs->PerPageVar);
$objConfig->Set($_C_objCatSubs->PerPageVar, (int)$MaxCats);
$SubCats = $_C_objCatSubs->LoadCategories($_Where, $_OrderBy, false);
$objConfig->Set($_C_objCatSubs->PerPageVar, $old_value);
if (is_array($SubCats) && count($SubCats))
{
foreach ($SubCats as $subcat)
{
$SubCatName = $subcat->Get($objCatList->TitleField);
$SubCatId = $subcat->Get("CategoryId");
$SubPath = $subcat->Get("ParentPath");
$add_path = "";
if (is_array($modules))
{
foreach ($modules as $curr => $v)
{
if (strpos($SubPath, "|$curr|") !== false)
{
$add_path = $v;
break;
}
}
}
$CatIds = $subcat->GetParentIds();
$nbs = "";
// echo 'MD: <b>'.$MaxDepth.'</b>, CATS: <b>'.count($CatIds).'</b><br />';
if (!isset($MaxDepth) || (isset($MaxDepth) && ($MaxDepth >= count($CatIds))))
{
for ($i = (count($CatIds)-2); $i>0; $i--)
$nbs.= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
$sub_templ = $add_path.$SubCatItemTemplate;
$ret.= $nbs.$subcat->ParseTemplate($sub_templ);
}
}
}
unset($_C_objCatSubs);
if($count==$per_row)
{
$ret.= "</TD><TD valign=\"top\">";
$count=0;
}
else
$ret.= "<BR />";
}
if($count != $per_row)
$ret .= "</TD>";
$ret.= "\n</tr></table>\n";
}
$m_var_list = $backup_m_var_list;
return $ret;
}
function m_IsDebugMode($params)
{
// echo 'kool';
return IsDebugMode() ? true : '';
}
function m_param($params)
{
$parser_params = GetVar('parser_params');
$param_name = strtolower($params['_name']);
$value = getArrayValue($parser_params, $param_name);
if ($value) {
if (getArrayValue($params, '_asphrase')) {
$value = language($value);
}
}
return $value;
}
function m_set_category($params)
{
global $m_var_list;
if (getArrayValue($params, '_onlyonce') && $m_var_list['cat']) return ;
$db =& GetADODBConnection();
$category_id = getArrayValue($params, '_catid');
if (!$category_id) {
$module = getArrayValue($params, '_module');
if ($module) {
$sql = 'SELECT RootCat FROM '.GetTablePrefix().'Modules WHERE LOWER(Name) = '.$db->qstr( strtolower($module) );
$category_id = $db->GetOne($sql);
}
}
if ($category_id) {
$m_var_list['cat'] = $category_id;
}
}
function m_template_equals($params)
{
$t = preg_replace('/(.*)\.tpl/', '\\1', $params['_template']);
return $GLOBALS['var_list']['t'] == $t ? true : '';
}
function m_ShowSearchError($params)
{
global $objSession, $objTemplate;
$error_phrase = $objSession->GetVariable('search_error');
if (!$error_phrase) {
return '';
}
$template = getArrayValue($params, '_itemtemplate');
if (!$template) {
$ret = '<inp:form_error />';
}
$ret = $objTemplate->GetTemplate($template, true);
$ret = $ret->source;
return str_replace('<inp:form_error />', language($error_phrase), $ret);
}
/*function m_object($attribs=Array())
{
$element = new clsHtmlTag();
$element->name=$attribs['_prefix'];
$element->attributes = $attribs;
$ret = $cat->ParseObject($element);
}*/
?>
Property changes on: branches/unlabeled/unlabeled-1.105.2/kernel/parser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.105
\ No newline at end of property
+1.105.2.1
\ No newline at end of property

Event Timeline