Page MenuHomeIn-Portal Phabricator

in-portal
No OneTemporary

File Metadata

Created
Wed, Jun 18, 11:56 PM

in-portal

Index: branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/changelog_4_1_0.txt
===================================================================
--- branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/changelog_4_1_0.txt (revision 8331)
+++ branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/changelog_4_1_0.txt (revision 8332)
@@ -1,249 +1,256 @@
File in-portal/admin/install.php changed
File in-portal/admin/email/do_send.php changed
File in-portal/admin/include/elements.php changed
File in-portal/admin/include/mainscript.php changed
File in-portal/admin/include/style.css changed
+File in-portal/admin/include/tabs.js changed
File in-portal/admin/install/db_reconfig.php changed
File in-portal/admin/install/dbinfo.php changed
File in-portal/admin/install/domain.php changed
File in-portal/admin/install/download_license.php changed
File in-portal/admin/install/fix_paths.php changed
File in-portal/admin/install/general_error.php changed
File in-portal/admin/install/get_license.php changed
File in-portal/admin/install/inportal_data.sql changed
+File in-portal/admin/install/inportal_remove.sql changed
File in-portal/admin/install/inportal_schema.sql changed
File in-portal/admin/install/install_finish.php changed
File in-portal/admin/install/install_lib.php changed
File in-portal/admin/install/lang_default.php changed
File in-portal/admin/install/lang_run.php changed
File in-portal/admin/install/lang_select.php changed
File in-portal/admin/install/login.php changed
File in-portal/admin/install/modselect.php changed
File in-portal/admin/install/postconfig.php changed
File in-portal/admin/install/reinstall.php changed
File in-portal/admin/install/restore_run.php changed
File in-portal/admin/install/restore_select.php changed
File in-portal/admin/install/rootpass.php changed
File in-portal/admin/install/sel_license.php changed
File in-portal/admin/install/settings.php changed
File in-portal/admin/install/theme_select.php changed
File in-portal/admin/install/upgrade.php changed
File in-portal/admin/install/warning.php changed
File in-portal/admin/install/langpacks/english.lang changed
File in-portal/admin/install/upgrades/changelog_4_0_1.txt changed
-File in-portal/admin/install/upgrades/changelog_4_1_0.txt is new; release_4_1_0 revision 1.1.2.4
+File in-portal/admin/install/upgrades/changelog_4_1_0.txt is new; release_4_1_0 revision 1.1.2.5
File in-portal/admin/install/upgrades/inportal_upgrade_v1.3.2.sql is removed; release_4_0_1 revision 1.2
File in-portal/admin/install/upgrades/inportal_upgrade_v4.1.0.php is new; release_4_1_0 revision 1.1.2.2
-File in-portal/admin/install/upgrades/inportal_upgrade_v4.1.0.sql is new; release_4_1_0 revision 1.1.2.3
+File in-portal/admin/install/upgrades/inportal_upgrade_v4.1.0.sql is new; release_4_1_0 revision 1.1.2.4
+File in-portal/admin/install/upgrades/readme_4_1_0.txt is new; release_4_1_0 revision 1.1.2.1
File in-portal/admin/tools/server_info.php changed
+File in-portal/admin/users/adduser.php changed
File in-portal/kernel/parser.php changed
+File in-portal/kernel/admin/include/toolbar/sendmail.php changed
File in-portal/kernel/admin_templates/catalog.tpl changed
File in-portal/kernel/admin_templates/catalog_tab.tpl changed
File in-portal/kernel/admin_templates/no_permission.tpl changed
File in-portal/kernel/admin_templates/categories/ci_blocks.tpl changed
File in-portal/kernel/admin_templates/categories/permissions_tab.tpl changed
File in-portal/kernel/admin_templates/config/config_general.tpl changed
File in-portal/kernel/admin_templates/config/config_search.tpl changed
File in-portal/kernel/admin_templates/groups/groups_edit_permissions.tpl changed
File in-portal/kernel/admin_templates/groups/permissions_selector.tpl changed
File in-portal/kernel/admin_templates/incs/config_blocks.tpl changed
File in-portal/kernel/admin_templates/incs/custom_blocks.tpl changed
File in-portal/kernel/admin_templates/incs/image_blocks.tpl changed
File in-portal/kernel/admin_templates/regional/languages_edit.tpl changed
File in-portal/kernel/admin_templates/regional/languages_export.tpl changed
File in-portal/kernel/admin_templates/regional/languages_export_step2.tpl changed
File in-portal/kernel/admin_templates/stylesheets/base_style_edit.tpl changed
File in-portal/kernel/admin_templates/stylesheets/block_style_edit.tpl changed
File in-portal/kernel/admin_templates/stylesheets/style_editor.tpl changed
File in-portal/kernel/admin_templates/visits/visits_list.tpl changed
File in-portal/kernel/include/category.php changed
File in-portal/kernel/include/config.php changed
+File in-portal/kernel/include/customfield.php changed
File in-portal/kernel/include/custommetadata.php changed
File in-portal/kernel/include/emailmessage.php changed
File in-portal/kernel/include/globals.php changed
File in-portal/kernel/include/item.php changed
File in-portal/kernel/include/itemdb.php changed
File in-portal/kernel/include/language.php changed
File in-portal/kernel/include/modules.php changed
File in-portal/kernel/include/parse.php changed
File in-portal/kernel/include/permissions.php changed
File in-portal/kernel/include/theme.php changed
File in-portal/kernel/include/usersession.php changed
File in-portal/kernel/include/adodb/adodb.inc.php changed
File in-portal/kernel/include/adodb/drivers/adodb-mysql.inc.php changed
File in-portal/kernel/units/config_search/config_search_config.php changed
File in-portal/kernel/units/images/images_config.php changed
File in-portal/kernel/units/modules/modules_config.php is removed; release_4_0_1 revision 1.7
File in-portal/kernel/units/modules/modules_event_handler.php is removed; release_4_0_1 revision 1.10
File in-portal/kernel/units/modules/modules_tag_processor.php is removed; release_4_0_1 revision 1.3
File in-portal/kernel/units/relationship/relationship_config.php changed
File in-portal/kernel/units/reviews/reviews_config.php changed
File in-portal/kernel/units/sections/sections_config.php changed
File in-portal/kernel/units/selectors/selectors_config.php changed
File in-portal/kernel/units/statistics/statistics_config.php changed
File in-portal/kernel/units/stylesheets/stylesheets_config.php changed
File in-portal/kernel/units/visits/visits_config.php changed
File kernel.X/core/install.php is new; release_4_1_0 revision 1.9.2.1
File kernel.X/core/admin_templates/head.tpl changed
File kernel.X/core/admin_templates/index.tpl changed
File kernel.X/core/admin_templates/login.tpl changed
File kernel.X/core/admin_templates/no_permission.tpl changed
File kernel.X/core/admin_templates/sections_list.tpl changed
File kernel.X/core/admin_templates/swfupload.swf is new; release_4_1_0 revision 1.1.2.1
File kernel.X/core/admin_templates/tree.tpl changed
File kernel.X/core/admin_templates/config/config_general.tpl changed
File kernel.X/core/admin_templates/config/config_search.tpl changed
File kernel.X/core/admin_templates/config/config_search_edit.tpl changed
File kernel.X/core/admin_templates/config/config_universal.tpl changed
File kernel.X/core/admin_templates/custom_fields/custom_fields_edit.tpl changed
File kernel.X/core/admin_templates/emails/send_complete.tpl is new; release_4_1_0 revision 1.1.2.2
File kernel.X/core/admin_templates/emails/send_queue.tpl is new; release_4_1_0 revision 1.1.2.1
File kernel.X/core/admin_templates/img/icons/icon24_conf_themes.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/icons/icon46_conf_themes.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/icons/icon46_list_conf_themes.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_new_theme.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_new_theme_f2.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_new_theme_f3.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_primary_theme.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_primary_theme_f2.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_primary_theme_f3.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_rescan_themes.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_rescan_themes_f2.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/img/toolbar/tool_rescan_themes_f3.gif is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/incs/blocks.tpl changed
File kernel.X/core/admin_templates/incs/config_blocks.tpl changed
File kernel.X/core/admin_templates/incs/form_blocks.tpl changed
File kernel.X/core/admin_templates/incs/grid_blocks.tpl changed
File kernel.X/core/admin_templates/incs/style.css changed
File kernel.X/core/admin_templates/js/ajax.js changed
File kernel.X/core/admin_templates/js/forms.js changed
File kernel.X/core/admin_templates/js/grid.js changed
File kernel.X/core/admin_templates/js/script.js changed
File kernel.X/core/admin_templates/js/swfobject.js is new; release_4_1_0 revision 1.1.2.1
File kernel.X/core/admin_templates/js/tree.js changed
File kernel.X/core/admin_templates/js/uploader.js is new; release_4_1_0 revision 1.2.2.4
File kernel.X/core/admin_templates/popups/translator.tpl changed
File kernel.X/core/admin_templates/regional/email_messages_edit.tpl changed
File kernel.X/core/admin_templates/regional/languages_edit.tpl changed
File kernel.X/core/admin_templates/regional/languages_export.tpl changed
File kernel.X/core/admin_templates/regional/languages_export_step2.tpl changed
File kernel.X/core/admin_templates/regional/languages_import.tpl changed
File kernel.X/core/admin_templates/regional/languages_import_step2.tpl changed
File kernel.X/core/admin_templates/regional/languages_list.tpl changed
File kernel.X/core/admin_templates/regional/phrases_edit.tpl changed
File kernel.X/core/admin_templates/skins/skin_edit.tpl is new; release_4_1_0 revision 1.1.2.2
File kernel.X/core/admin_templates/skins/skin_list.tpl is new; release_4_1_0 revision 1.1.2.1
File kernel.X/core/admin_templates/themes/themes_edit.tpl is new; release_4_1_0 revision 1.2
File kernel.X/core/admin_templates/themes/themes_edit_files.tpl is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/themes/themes_edit_tabs.tpl is new; release_4_1_0 revision 1.1
File kernel.X/core/admin_templates/themes/themes_list.tpl is new; release_4_1_0 revision 1.2
File kernel.X/core/admin_templates/tools/skins.tpl is new; release_4_1_0 revision 1.1.2.1
File kernel.X/core/admin_templates/tools/system_tools.tpl changed
File kernel.X/core/install/english.lang changed
File kernel.X/core/install/install_data.sql changed
File kernel.X/core/install/install_schema.sql changed
File kernel.X/core/install/upgrades.php changed
File kernel.X/core/install/upgrades.sql changed
File kernel.X/core/install/incs/install.tpl changed
File kernel.X/core/install/incs/style.css changed
File kernel.X/core/install/step_templates/check_paths.tpl changed
File kernel.X/core/install/step_templates/choose_modules.tpl changed
File kernel.X/core/install/step_templates/db_config.tpl changed
File kernel.X/core/install/step_templates/finish.tpl changed
File kernel.X/core/install/step_templates/install_setup.tpl changed
File kernel.X/core/install/step_templates/root_password.tpl changed
File kernel.X/core/install/step_templates/upgrade_modules.tpl changed
File kernel.X/core/units/admin/admin_config.php changed
File kernel.X/core/units/admin/admin_events_handler.php changed
File kernel.X/core/units/admin/admin_tag_processor.php changed
File kernel.X/core/units/categories/cache_updater.php changed
File kernel.X/core/units/categories/categories_config.php changed
File kernel.X/core/units/category_items/category_items_config.php changed
File kernel.X/core/units/configuration/configuration_config.php changed
File kernel.X/core/units/configuration/configuration_tag_processor.php changed
File kernel.X/core/units/custom_data/custom_data_config.php changed
File kernel.X/core/units/custom_data/custom_data_event_handler.php changed
File kernel.X/core/units/custom_fields/custom_fields_config.php changed
File kernel.X/core/units/custom_fields/custom_fields_event_handler.php changed
File kernel.X/core/units/custom_fields/custom_fields_tag_processor.php changed
File kernel.X/core/units/email_events/email_events_config.php changed
File kernel.X/core/units/email_events/email_events_event_handler.php changed
File kernel.X/core/units/email_messages/email_messages_config.php changed
File kernel.X/core/units/general/cat_event_handler.php changed
File kernel.X/core/units/general/custom_fields.php changed
File kernel.X/core/units/general/inp1_parser.php changed
+File kernel.X/core/units/general/main_event_handler.php changed
File kernel.X/core/units/general/xml_helper.php changed
File kernel.X/core/units/general/helpers/count_helper.php is new; release_4_1_0 revision 1.4
File kernel.X/core/units/general/helpers/curl_helper.php is new; release_4_1_0 revision 1.1
File kernel.X/core/units/general/helpers/helpers_config.php changed
File kernel.X/core/units/general/helpers/mod_rewrite_helper.php changed
File kernel.X/core/units/general/helpers/modules.php changed
File kernel.X/core/units/general/helpers/multilanguage.php changed
File kernel.X/core/units/general/helpers/search_helper.php changed
File kernel.X/core/units/general/helpers/themes_helper.php changed
File kernel.X/core/units/groups/groups_config.php changed
File kernel.X/core/units/languages/import_xml.php changed
File kernel.X/core/units/languages/languages_config.php changed
File kernel.X/core/units/languages/languages_event_handler.php changed
File kernel.X/core/units/modules/modules_config.php changed
File kernel.X/core/units/permissions/permissions_config.php changed
File kernel.X/core/units/phrases/phrases_config.php changed
File kernel.X/core/units/skins/skin_eh.php is new; release_4_1_0 revision 1.1.2.1
File kernel.X/core/units/skins/skins_config.php is new; release_4_1_0 revision 1.1.2.3
File kernel.X/core/units/theme_files/theme_files_config.php is new; release_4_1_0 revision 1.1
File kernel.X/core/units/themes/themes_config.php changed
File kernel.X/core/units/themes/themes_eh.php is new; release_4_1_0 revision 1.2
File kernel.X/core/units/user_groups/user_groups_config.php changed
File kernel.X/core/units/users/users_config.php changed
File kernel.X/core/units/users/users_event_handler.php changed
File kernel.X/core/units/users/users_tag_processor.php changed
File kernel4_dev/kernel4/application.php changed
File kernel4_dev/kernel4/constants.php changed
File kernel4_dev/kernel4/event_handler.php changed
File kernel4_dev/kernel4/event_manager.php changed
File kernel4_dev/kernel4/globals.php changed
File kernel4_dev/kernel4/kbase.php changed
File kernel4_dev/kernel4/startup.php changed
File kernel4_dev/kernel4/db/db_connection.php changed
File kernel4_dev/kernel4/db/db_event_handler.php changed
File kernel4_dev/kernel4/db/db_tag_processor.php changed
File kernel4_dev/kernel4/db/dbitem.php changed
File kernel4_dev/kernel4/db/dblist.php changed
File kernel4_dev/kernel4/languages/phrases_cache.php changed
File kernel4_dev/kernel4/processors/main_processor.php changed
File kernel4_dev/kernel4/processors/tag_processor.php changed
File kernel4_dev/kernel4/session/session.php changed
File kernel4_dev/kernel4/utility/debugger.php changed
File kernel4_dev/kernel4/utility/email_send.php changed
File kernel4_dev/kernel4/utility/event.php changed
File kernel4_dev/kernel4/utility/filters.php changed
File kernel4_dev/kernel4/utility/http_query.php changed
File kernel4_dev/kernel4/utility/temp_handler.php changed
File kernel4_dev/kernel4/utility/unit_config_reader.php changed
File kernel4_dev/kernel4/utility/formatters/date_formatter.php changed
File kernel4_dev/kernel4/utility/formatters/serialized_formatter.php changed
File kernel4_dev/kernel4/utility/formatters/unit_formatter.php changed
File kernel4_dev/kernel4/utility/formatters/upload_formatter.php changed
File kernel.X/system/.cvsignore is new; release_4_1_0 revision 1.3
File kernel.X/system/dummy is new; release_4_1_0 revision 1.1
File kernel.X/system/cache/.cvsignore is new; release_4_1_0 revision 1.3
File kernel.X/system/cache/dummy is new; release_4_1_0 revision 1.1
File kernel.X/system/tmp/.cvsignore is new; release_4_1_0 revision 1.2.2.1
File kernel.X/system/user_files/.cvsignore is new; release_4_1_0 revision 1.2.2.1
File kernel.X/system/user_files/just_logo.gif is new; release_4_1_0 revision 1.1.2.1
File kernel.X/system/user_files/icons/audio.gif is new; release_4_1_0 revision 1.2
File kernel.X/system/user_files/icons/doc.gif is new; release_4_1_0 revision 1.2
File kernel.X/system/user_files/icons/excel.gif is new; release_4_1_0 revision 1.2
File kernel.X/system/user_files/icons/image.gif is new; release_4_1_0 revision 1.2
File kernel.X/system/user_files/icons/pdf.gif is new; release_4_1_0 revision 1.2
File kernel.X/system/user_files/icons/ppt.gif is new; release_4_1_0 revision 1.2
File kernel.X/system/user_files/icons/video.gif is new; release_4_1_0 revision 1.2
File kernel.X/system/user_files/icons/xml.gif is new; release_4_1_0 revision 1.2
File cmseditor/editor/filemanager/browser/default/connectors/php/commands.php changed
Changes in phrases and events:
! <LANGUAGE PackName="English" Encoding="base64"><DATEFORMAT>m/d/Y</DATEFORMAT><TIMEFORMAT>g:i:s A</TIMEFORMAT><INPUTDATEFORMAT>m/d/Y</INPUTDATEFORMAT><INPUTTIMEFORMAT>g:i:s A</INPUTTIMEFORMAT><DECIMAL>.</DECIMAL><THOUSANDS>'</THOUSANDS><CHARSET>iso-8859-1</CHARSET><UNITSYSTEM>2</UNITSYSTEM>
! <LANGUAGE PackName="English" Encoding="base64"><DATEFORMAT>m/d/Y</DATEFORMAT><TIMEFORMAT>g:i:s A</TIMEFORMAT><INPUTDATEFORMAT>m/d/Y</INPUTDATEFORMAT><INPUTTIMEFORMAT>g:i:s A</INPUTTIMEFORMAT><DECIMAL>.</DECIMAL><THOUSANDS>,</THOUSANDS><CHARSET>iso-8859-1</CHARSET><UNITSYSTEM>2</UNITSYSTEM>
Property changes on: branches/unlabeled/unlabeled-1.1.2/admin/install/upgrades/changelog_4_1_0.txt
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.1.2.5
\ No newline at end of property
+1.1.2.6
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.61.2/kernel/include/category.php
===================================================================
--- branches/unlabeled/unlabeled-1.61.2/kernel/include/category.php (revision 8331)
+++ branches/unlabeled/unlabeled-1.61.2/kernel/include/category.php (revision 8332)
@@ -1,2571 +1,2580 @@
<?php
define('TYPE_CATEGORY', 0);
$DownloadId=0;
RegisterPrefix("clsCategory","cat","kernel/include/category.php");
class clsCategory extends clsItem
{
var $Permissions;
var $DescriptionField = '';
+ var $PrimaryDescriptionField = '';
+ var $DescriptionField = '';
function clsCategory($CategoryId=NULL)
{
global $objSession;
$this->clsItem(TRUE);
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$this->TitleField = $ml_formatter->LangFieldName('Name');
$this->DescriptionField = $ml_formatter->LangFieldName('Description');
+ $this->PrimaryTitleField = $ml_formatter->LangFieldName('Name', 1);
+ $this->PrimaryDescriptionField = $ml_formatter->LangFieldName('Description', 1);
+
$this->tablename = GetTablePrefix()."Category";
$this->type=1;
$this->BasePermission ="CATEGORY";
$this->id_field = "CategoryId";
$this->TagPrefix = "cat";
$this->Prefix = 'c';
$this->debuglevel=0;
/* keyword highlighting */
$this->OpenTagVar = "Category_Highlight_OpenTag";
$this->CloseTagVar = "Category_Highlight_CloseTag";
if($CategoryId!=NULL)
{
$this->LoadFromDatabase($CategoryId);
$this->Permissions = new clsPermList($CategoryId,$objSession->Get("GroupId"));
}
else
{
$this->Permissions = new clsPermList();
}
}
function StripDisallowed($string)
{
$not_allowed = Array( ' ', '\\', '/', ':', '*', '?', '"', '<', '>', '|', '`',
'~', '!', '@', '#', '$', '%', '^', '&', '(', ')', '~',
'+', '=', '-', '{', '}', ']', '[', "'", ';', '.', ',');
$string = str_replace($not_allowed, '_', $string);
$string = preg_replace('/(_+)/', '_', $string);
$string = $this->checkAutoFilename($string);
return $string;
}
function checkAutoFilename($filename)
{
global $m_var_list;
if(!$filename || $this->UniqueId() == 0 ) return $filename;
$db =& GetADODBConnection();
$sql = 'SELECT CategoryId FROM '.$this->tablename.' WHERE (Filename = '.$db->qstr($filename).') AND (ParentId = '.$m_var_list['cat'].')';
$found_category_ids = $db->GetCol($sql);
$has_page = preg_match('/(.*)_([\d]+)([a-z]*)$/', $filename, $rets);
$duplicates_found = (count($found_category_ids) > 1) || ($found_category_ids && $found_category_ids[0] != $this->UniqueId());
if ($duplicates_found || $has_page)
{
$append = $duplicates_found ? '_a' : '';
if($has_page)
{
$filename = $rets[1].'_'.$rets[2];
$append = $rets[3] ? $rets[3] : '_a';
}
$sql = 'SELECT CategoryId FROM '.$this->tablename.' WHERE (Filename = %s) AND (CategoryId != '.$this->UniqueId().') AND (ParentId = '.$m_var_list['cat'].')';
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;
}
function GenerateFilename()
{
if ( !$this->Get('AutomaticFilename') && $this->Get('Filename') )
{
$name = $this->Get('Filename');
}
else
{
$name = $this->Get($this->TitleField);
}
$name = $this->StripDisallowed($name);
if ( $name != $this->Get('Filename') ) $this->Set('Filename', $name);
}
function ClearCacheData()
{
/*$env = "':m".$this->Get("CategoryId")."%'";
DeleteTagCache("m_list_cats","",$env); */
DeleteTagCache("m_itemcount","Category%");
DeleteModuleTagCache('kernel');
}
function DetectChanges($name, $value)
{
global $objSession;
//print_pre($_POST);
if (!isset($this->Data[$name]) ) return false;
if ($this->Data[$name] != $value) {
//echo "$name Modified tt ".$this->Data[$name]." tt $value<br>";
if (!stristr($name, 'Modif') && !stristr($name, 'Created')) {
if ($objSession->GetVariable("HasChanges") != 1) {
$objSession->SetVariable("HasChanges", 2);
}
}
}
}
function Delete()
{
global $CatDeleteList;
if(!is_array($CatDeleteList))
$CatDeleteList = array();
if($this->UsingTempTable()==FALSE)
{
$this->Permissions->Delete_CatPerms($this->Get("CategoryId"));
// TODO: find way to delete specific category cache only
/*$sql = "DELETE FROM ".GetTablePrefix()."CountCache WHERE CategoryId=".$this->Get("CategoryId");
$this->adodbConnection->Execute($sql);*/
$CatDeleteList[] = $this->Get("CategoryId");
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.DELETE",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.DELETE");
parent::Delete();
$this->ClearCacheData();
}
else
{
parent::Delete();
}
}
function Update($UpdatedBy=NULL)
{
parent::Update($UpdatedBy);
$this->GenerateFilename();
parent::Update($UpdatedBy);
if ($this->tablename == GetTablePrefix().'Category') $this->ClearCacheData();
}
function Create()
{
if( (int)$this->Get('CreatedOn') == 0 ) $this->Set('CreatedOn', adodb_date('U') );
parent::Create();
$this->GenerateFilename();
parent::Update();
if ($this->tablename == GetTablePrefix().'Category') $this->ClearCacheData();
}
function SetParentId($value)
{
//Before we set a parent verify that propsed parent is not our child.
//Otherwise it will cause recursion.
$id = $this->Get("CategoryId");
$path = $this->Get("ParentPath");
$sql = sprintf("SELECT CategoryId From ".GetTablePrefix()."Category WHERE ParentPath LIKE '$path%' AND CategoryId = %d ORDER BY ParentPath",$value);
$rs = $this->adodbConnection->SelectLimit($sql,1,0);
if(!$rs->EOF)
{
return;
}
$this->Set("ParentId",$value);
}
function Approve()
{
global $objSession;
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.APPROVE",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.APPROVE");
$this->Set("Status", 1);
$this->Update();
}
function Deny()
{
global $objSession;
if($this->Get("CreatedById")>0)
$this->SendUserEventMail("CATEGORY.DENY",$this->Get("CreatedById"));
$this->SendAdminEventMail("CATEGORY.DENY");
$this->Set("Status", 0);
$this->Update();
}
function IsEditorsPick()
{
return $this->Is("EditorsPick");
}
function SetEditorsPick($value)
{
$this->Set("EditorsPick", $value);
}
function GetSubCats($limit=NULL, $target_template=NULL, $separator=NULL, $anchor=NULL, $ending=NULL, $class=NULL)
{
global $m_var_list, $m_var_list_update, $var_list, $var_list_update;
$sql = " SELECT CategoryId, ".$this->TitleField."
FROM ".GetTablePrefix()."Category
WHERE ParentId=".$this->Get("CategoryId")." AND Status=1
ORDER BY Priority";
if(isset($limit))
{
$rs = $this->adodbConnection->SelectLimit($sql, $limit, 0);
}
else
{
$rs = $this->adodbConnection->Execute($sql);
}
$count=1;
$class_name = is_null($class)? "catsub" : $class;
while($rs && !$rs->EOF)
{
$var_list_update["t"] = !is_null($target_template)? $target_template : $var_list["t"];
$m_var_list_update["cat"] = $rs->fields["CategoryId"];
$m_var_list_update["p"] = "1";
$cat_name = $rs->fields[$this->TitleField];
if (!is_null($anchor))
$ret .= "<a class=\"$class_name\" href=\"". HREF_Wrapper() . "\">$cat_name</a>";
else
$ret .= "<span=\"$class_name\">$cat_name</span>";
$rs->MoveNext();
if(!$rs->EOF)
{
$ret.= is_null($separator)? ", " : $separator;
}
}
if(strlen($ret))
$ret .= is_null($ending)? " ..." : $ending;
unset($var_list_update["t"], $m_var_list_update["cat"], $m_var_list_update["p"]);
return $ret;
}
function Validate()
{
global $objSession;
$dataValid = true;
if(!isset($this->m_Type))
{
$Errors->AddError("error.fieldIsRequired",'Type',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Name))
{
$Errors->AddError("error.fieldIsRequired",'Name',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Description))
{
$Errors->AddError("error.fieldIsRequired",'Description',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_Visible))
{
$Errors->AddError("error.fieldIsRequired",'Visible',"","","clsCategory","Validate");
$dataValid = false;
}
if(!isset($this->m_CreatedById))
{
$Errors->AddError("error.fieldIsRequired",'CreatedBy',"","","clsCategory","Validate");
$dataValid = false;
}
return $dataValid;
}
function UpdateCachedPath()
{
if( $this->UsingTempTable() == true) return ;
$Id = $this->Get('CategoryId');
$Id2 = $Id;
$path_parts = Array();
$nav_parts = Array();
$named_parts = Array();
$cateogry_template = '';
$item_template = '';
$ml_helper =& $this->Application->recallObject('kMultiLanguageHelper');
$language_count = $ml_helper->getLanguageCount();
$primary_lang_id = $this->Application->GetDefaultLanguageId();
do {
$rs = $this->adodbConnection->Execute('SELECT * FROM '.$this->tablename.' WHERE CategoryId = '.$Id2);
$path_parts[] = $Id2;
$named_parts[] = $rs->fields['Filename'];
$i = 1;
while ($i <= $language_count) {
$nav_parts[$i][] = $rs->fields['l'.$i.'_Name'] ? $rs->fields['l'.$i.'_Name'] : $rs->fields['l'.$primary_lang_id.'_Name'];
$i++;
}
if (!$cateogry_template && $rs->fields['CachedCategoryTemplate']) {
$cateogry_template = $rs->fields['CachedCategoryTemplate'];
}
$Id2 = ($rs && !$rs->EOF) ? $rs->fields['ParentId'] : '0';
} while ($Id2 != '0');
$parent_path = '|'.implode('|', array_reverse($path_parts) ).'|';
$named_path = implode('/', array_reverse($named_parts) );
$i = 1;
while ($i <= $language_count) {
$this->Set('l'.$i.'_CachedNavbar', implode('&|&', array_reverse($nav_parts[$i]) ));
$i++;
}
$this->Set('ParentPath', $parent_path);
$this->Set('NamedParentPath', $named_path);
$this->Set('CachedCategoryTemplate', $cateogry_template);
$this->Update();
}
function GetCachedNavBar()
{
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$navbar_field = $ml_formatter->LangFieldName('CachedNavbar');
$res = $this->Get($navbar_field);
if (!strlen($res)) {
$this->UpdateCachedPath();
- $res = $this->Get($navbar_field);
+ $res = $this->Get($navbar_field, $ml_formatter->LangFieldName('CachedNavbar',1));
}
return str_replace('&|&', ' > ', $res);
}
function Increment_Count()
{
$this->Increment("CachedDescendantCatsQty");
}
function Decrement_Count()
{
$this->Decrement("CachedDescendantCatsQty");
$this->Update();
}
function LoadFromDatabase($Id)
{
global $objSession, $Errors, $objConfig;
if($Id==0)
return FALSE;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE CategoryId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if(is_array($data))
{
$this->SetFromArray($data);
$this->Clean();
}
else
return false;
return true;
}
function SetNewItem()
{
global $objConfig;
$value = $this->Get("CreatedOn");
$cutoff = adodb_date("U") - ($objConfig->Get("Category_DaysNew") * 86400);
$this->IsNew = FALSE;
if($value>$cutoff)
$this->IsNew = TRUE;
return $this->IsNew;
}
function LoadFromResourceId($Id)
{
global $objSession, $Errors;
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResourceId");
return false;
}
$sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'",$Id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResourceId");
return false;
}
$data = $result->fields;
if(is_array($data))
$this->SetFromArray($data);
else
return false;
return true;
}
function GetParentField($fieldname,$skipvalue,$default)
{
/* this function moves up the category tree until a value for $field other than
$skipvalue is returned. if no matches are made, then $default is returned */
$path = $this->Get("ParentPath");
$path = substr($path,1,-1); //strip off the first & last tokens
$aPath = explode("|",$path);
$aPath = array_slice($aPath,0,-1);
$ParentPath = implode("|",$aPath);
$sql = "SELECT $fieldname FROM ".GetTablePrefix()."Category WHERE $fieldname != '$skipvalue' AND ParentPath LIKE '$ParentPath' ORDER BY ParentPath DESC";
$rs = $this->adodbConnection->execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields[$fieldname];
}
else
{
$ret = $default;
}
$update = "UPDATE ".$this->tablename." SET $fieldname='$ret' WHERE CategoryId=".$this->Get("CategoryId");
$this->adodbConnection->execute($update);
return $ret;
}
function GetCustomField($fieldName)
{
global $objSession, $Errors;
if(!isset($this->m_CategoryId))
{
$Errors->AddError("error.appError","Get field is required in order to set custom field values","","",get_class($this),"GetCustomField");
return false;
}
return GetCustomFieldValue($this->m_CategoryId,"category",$fieldName);
}
function SetCustomField($fieldName, $value)
{
global $objSession, $Errors;
if(!isset($this->m_CategoryId))
{
$Errors->AddError("error.appError","Set field is required in order to set custom field values","","",get_class($this),"SetCustomField");
return false;
}
return SetCustomFieldValue($this->m_CategoryId,"category",$fieldName,$value);
}
function LoadPermissions($first=1)
{
/* load all permissions for group on this category */
$this->Permissions->CatId=$this->Get("CategoryId");
if($this->Permissions->NumItems()==0)
{
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
if(is_array($cats))
{
$cats = array_reverse($cats);
$cats[] = 0;
foreach($cats as $catid)
{
$this->Permissions->LoadCategory($catid);
}
}
}
if($this->Permissions->NumItems()==0)
{
if($first==1)
{
$this->Permissions->GroupId=NULL;
$this->LoadPermissions(0);
}
}
}
function PermissionObject()
{
return $this->Permissions;
}
function PermissionItemObject($PermissionName)
{
$p = $this->Permissions->GetPermByName($PermissionName);
return $p;
}
function HasPermission($PermissionName,$GroupID)
{
global $objSession;
$perm = $this->PermissionValue($PermissionName,$GroupID);
// echo "Permission $PermissionName for $GroupID is $perm in ".$this->Get("CategoryId")."<br>\n";
if(!$perm)
{
$perm=$objSession->HasSystemPermission("ROOT");
}
return ($perm==1);
}
function PermissionValue($PermissionName,$GroupID)
{
//$this->LoadPermissions();
$ret=NULL;
//echo "Looping though ".count($this->Permissions)." permissions Looking for $PermissionName of $GroupID<br>\n";
if($this->Permissions->GroupId != $GroupID)
{
$this->Permissions->Clear();
$this->Permissions->GroupId = $GroupID;
}
$this->Permissions->CatId=$this->Get("CategoryId");
$ret = $this->Permissions->GetPermissionValue($PermissionName);
if($ret == NULL)
{
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
if(is_array($cats))
{
$cats = array_reverse($cats);
$cats[] = 0;
foreach($cats as $catid)
{
$this->Permissions->LoadCategory($catid);
$ret = $this->Permissions->GetPermissionValue($PermissionName);
if(is_numeric($ret))
break;
}
}
}
return $ret;
}
function SetPermission($PermName,$GroupID,$Value,$Type=0)
{
global $objSession, $objPermissions, $objGroups;
if($this->Permissions->GroupId != $GroupID)
{
$this->Permissions->Clear();
$this->Permissions->GroupId = $GroupID;
}
if($objSession->HasSystemPermission("GRANT"))
{
$current = $this->PermissionValue($PermName,$GroupID);
if($current == NULL)
{
$this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
}
else
{
$p = $this->Permissions->GetPermByName($PermName);
if($p->Inherited==FALSE)
{
$p->Set("PermissionValue",$Value);
$p->Update();
}
else
$this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
}
if($PermName == "CATEGORY.VIEW")
{
$Groups = $objGroups->GetAllGroupList();
$ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$Groups);
$this->SetViewPerms("CATEGORY.VIEW",$ViewList,$Groups);
$this->Update();
}
}
}
function SetViewPerms($PermName,$acl,$allgroups)
{
global $objPermCache;
if (!is_array($allgroups)) {
global $objGroups;
$allgroups = $objGroups->GetAllGroupList();
}
$aval = implode(",",$acl);
if (strlen($aval)==0) {
$aval = implode(",",$allgroups);
}
$PermId = $this->Permissions->GetPermId($PermName);
$pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
if (is_object($pc)) {
$pc->Set("ACL",$aval);
$pc->Update();
}
else {
$objPermCache->AddPermCache($this->Get("CategoryId"),$PermId,$aval);
}
//$this->Update();
}
function GetACL($PermName)
{
global $objPermCache;
$ret = "";
$PermId = $this->Permissions->GetPermId($PermName);
$pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
if(is_object($pc))
{
$ret = $this->Get("ACL");
}
return $ret;
}
function UpdateACL()
{
$q = 'INSERT INTO '.TABLE_PREFIX.'PermCache (CategoryId, PermId, ACL)
SELECT '.$this->UniqueId().', PermId, ACL
FROM '.TABLE_PREFIX.'PermCache
WHERE CategoryId = '.$this->Get('ParentId');
$this->Conn->Query($q);
}
function Cat_Link()
{
global $m_var_list_update;
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = HREF_Wrapper();
unset($m_var_list_update["cat"]);
return $ret;
}
function Parent_Link()
{
global $m_var_list_update;
$m_var_list_update["cat"] = $this->Get("ParentId");
$ret = HREF_Wrapper();
unset($m_var_list_update["cat"]);
return $ret;
}
function Admin_Parent_Link($page=NULL)
{
global $m_var_list_update;
if(!strlen($page))
$page = $_SERVER["PHP_SELF"];
$m_var_list_update["cat"] = $this->Get("ParentId");
$ret = $page."?env=".BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
}
function StatusIcon()
{
global $imagesURL;
$ret = $imagesURL."/itemicons/";
switch($this->Get("Status"))
{
case STATUS_DISABLED:
$ret .= "icon16_cat_disabled.gif";
break;
case STATUS_PENDING:
$ret .= "icon16_cat_pending.gif";
break;
case STATUS_ACTIVE:
$img = "icon16_cat.gif";
if($this->IsPopItem())
$img = "icon16_cat_pop.gif";
if($this->IsHotItem())
$img = "icon16_cat_hot.gif";
if($this->IsNewItem())
$img = "icon16_cat_new.gif";
if($this->Is("EditorsPick"))
$img = "icon16_car_pick.gif";
$ret .= $img;
break;
}
return $ret;
}
function SubCatCount()
{
$ret = $this->Get("CachedDescendantCatsQty");
$sql = "SELECT COUNT(*) as SubCount FROM ".$this->tablename." WHERE ParentPath LIKE '".$this->Get("ParentPath")."%' AND CategoryId !=".$this->Get("CategoryId");
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$val = $rs->fields["SubCount"];
if($val != $this->Get("CachedDescendantCatsQty"))
{
$this->Set("CachedDescendantCatsQty",$val);
$this->Update();
}
$ret = $this->Get("CachedDescendantCatsQty");
}
return $ret;
}
function GetSubCatIds()
{
$sql = "SELECT CategoryId FROM ".$this->tablename." WHERE ParentPath LIKE '".$this->Get("ParentPath")."%' AND CategoryId !=".$this->Get("CategoryId");
$rs = $this->adodbConnection->Execute($sql);
$ret = array();
while($rs && !$rs->EOF)
{
$ret[] = $rs->fields["CategoryId"];
$rs->MoveNext();
}
return $ret;
}
function GetParentIds()
{
$Parents = array();
$ParentPath = $this->Get("ParentPath");
if(strlen($ParentPath))
{
$ParentPath = substr($ParentPath,1,-1);
$Parents = explode("|",$ParentPath);
}
return $Parents;
}
function ItemCount($ItemType="")
{
global $objItemTypes,$objCatList,$objCountCache;
if(!is_numeric($ItemType))
{
$TypeId = $objItemTypes->GetItemTypeValue($ItemType);
}
else
$TypeId = (int)$ItemType;
//$path = $this->Get("ParentPath");
//$path = substr($path,1,-1);
//$path = str_replace("|",",",$path);
$path = implode(",",$this->GetSubCatIds());
if(strlen($path))
{
$path = $this->Get("CategoryId").",".$path;
}
else
$path = $this->Get("CategoryId");
$res = TableCount(GetTablePrefix()."CategoryItems","CategoryId IN ($path)",FALSE);
return $res;
}
function GetNavbar()
{
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
- return str_replace('&|&', ' > ', $this->Get($ml_formatter->LangFieldName('CachedNavbar')));
+ return str_replace('&|&', ' > ', $this->Get($ml_formatter->LangFieldName('CachedNavbar'), $ml_formatter->LangFieldName('CachedNavbar', 1)));
}
function ParseObject($element)
{
global $objConfig, $objCatList, $rootURL, $var_list, $var_list_update, $m_var_list_update, $objItemTypes,$objCountCache, $objUsers;
$extra_attribs = ExtraAttributes($element->attributes);
//print_r($element);
if(strtolower($element->name)==$this->TagPrefix)
{
$field = strtolower( $element->GetAttributeByName('_field') );
switch($field)
{
case 'filename':
$ret = $this->Get('Filename');
break;
case 'm_language':
$ret = language( $element->GetAttributeByName('_Phrase') );
break;
case 'parentcategorylink':
$m_var_list_update['cat'] = $this->Get('ParentId');
$m_var_list_update['p'] = 1;
$ret = str_replace('advanced_view.php','browse.php',$_SERVER['PHP_SELF']).'?env='.BuildEnv();
unset($m_var_list_update['cat']);
unset($m_var_list_update['p']);
return $ret;
break;
case 'primarycategory':
$ret = $this->Get('CachedNavbar');
if($ret) // category not in root
{
$ret = explode('>',$ret);
array_pop($ret);
$ret = implode('>',$ret);
}
$ret = prompt_language($objConfig->Get("Root_Name")).($ret ? '>' : '').$ret;
break;
case "name":
case "Name":
/*
@field:cat.name
@description:Category name
*/
- $ret = $this->HighlightField($this->TitleField);
+ $ret = $this->HighlightText($this->Get($this->TitleField, $this->PrimaryTitleField));
break;
case "description":
/*
@field:cat.description
@description:Category Description
*/
- $ret = ($this->Get($this->DescriptionField));
+ $ret = ($this->Get($this->DescriptionField, $this->PrimaryDescriptionField));
$ret = $this->HighlightText($ret);
break;
case "cachednavbar":
/*
@field:cat.cachednavbar
@description: Category cached navbar
*/
$this->Set('CachedNavbar', $this->GetNavbar());
$ret = $this->HighlightField("CachedNavbar");
if(!strlen($ret))
{
$this->UpdateCachedPath();
$ret = $this->HighlightField("CachedNavbar");
}
break;
case "image":
/*
@field:cat.image
@description:Return an image associated with the category
@attrib:_default:bool:If true, will return the default image if the requested image does not exist
@attrib:_name::Return the image with this name
@attrib:_thumbnail:bool:If true, return the thumbnail version of the image
@attrib:_imagetag:bool:If true, returns a complete image tag. exta html attributes are passed to the image tag
*/
$default = $element->GetAttributeByName('_primary');
$name = $element->GetAttributeByName('_name');
if(strlen($name))
{
$img = $this->GetImageByName($name);
}
else
{
if($default)
$img = $this->GetDefaultImage();
}
if($img)
{
if( $element->GetAttributeByName('_thumbnail') )
{
$url = $img->parsetag("thumb_url");
}
else
$url = $img->parsetag("image_url");
}
else
{
$url = $element->GetAttributeByName('_defaulturl');
}
if( $element->GetAttributeByName('_imagetag') )
{
if(strlen($url))
{
$ret = "<IMG src=\"$url\" $extra_attribs >";
}
else
$ret = "";
}
else
$ret = $url;
break;
case "createdby":
/*
@field:cat.createdby
@description:parse a user field of the user that created the category
@attrib:_usertag::User field to return (defaults to login ID)
*/
$field = $element->GetAttributeByName('_usertag');
if(!strlen($field))
{
$field = "user_login";
}
$userId = $this->Get("CreatedById");
if (!empty($userId) && ($userId > 0))
{
$u =& $objUsers->GetItem($userId);
if (is_object($u))
{
$ret = $u->parsetag($field);
}
}
else
$ret = " ";
break;
case "custom":
/*
@field:cat.custom
@description:Returns a custom field
@attrib:_customfield::field name to return
@attrib:_default::default value
*/
$field = $element->GetAttributeByName('_customfield');
$default = $element->GetAttributeByName('_default');
$ret = $this->GetCustomFieldValue($field,$default);
break;
case "catsubcats":
/*
@field:cat.catsubcats
@description:Returns a list of subcats of current category
@attrib:_limit:int:Number of categories to return
@attrib:_separator::Separator between categories
@attrib:_anchor:bool:Make an anchor (only if template is not specified)
@attrib:_TargetTemplate:tpl:Target template
@attrib:_Ending::Add special text at the end of subcategory list
@attrib:_Class::Specify stly sheet class for anchors (if used) or "span" object
*/
$limit = ((int)$element->attributes["_limit"]>0)? $element->attributes["_limit"] : NULL;
$separator = $element->attributes["_separator"];
$anchor = (int)($element->attributes["_anchor"])? 1 : NULL;
$templ = $element->GetAttributeByName("_TargetTemplate");
$template = !empty($templ)? $templ : NULL;
$ending = strlen($element->attributes["_ending"])? $element->attributes["_ending"] : NULL;
$class = strlen($element->attributes["_class"])? $element->attributes["_class"] : NULL;
$ret = $this->GetSubCats($limit, $template, $separator, $anchor, $ending, $class);
break;
case "date":
/*
@field:cat.date
@description:Returns the date/time the category was created
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$d = $this->Get("CreatedOn");
if( $element->GetAttributeByName('_tz') )
{
$d = GetLocalTime($d,$objSession->Get("tz"));
}
$part = strtolower( $element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$d);
}
else
{
if(!is_numeric($d))
{
$ret = "";
}
else
$ret = LangDate($d);
}
break;
case "link":
/*
@field:cat.link
@description:Returns a URL setting the category to the current category
@attrib:_template:tpl:Template URL should point to
@attrib:_mod_template:tpl:Template INSIDE a module to which the category belongs URL should point to
*/
if ( strlen( $element->GetAttributeByName('_mod_template') ) ){
//will prefix the template with module template root path depending on category
$ids = $this->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)];
$module_templates = explode(',', $element->GetAttributeByName('_mod_template'));
$m_templates = Array();
foreach($module_templates as $module_t)
{
$module_t = explode(':', $module_t);
if( isset($module_t[1]) )
{
$m_templates[$module_t[0]] = $module_t[1];
}
else
{
$m_templates['default'] = $module_t[0];
}
}
$db =& GetADODBConnection();
$sql = 'SELECT Name FROM '.GetTablePrefix().'Modules WHERE RootCat = '.$ids[0];
$module = $db->GetOne($sql);
if( isset($m_templates[$module]) )
{
$target_template = $m_templates[$module];
}
else
{
$target_template = $m_templates['default'];
}
$t = $path . $target_template;
}
else
{
$t = $element->GetAttributeByName('_template');
}
$url_params = Array();
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
{
$var_list_update["t"] = $var_list["t"];
}
$m_var_list_update["cat"] = $this->Get("CategoryId");
if( $element->GetAttributeByName('reset') ) $url_params['reset'] = 1;
$ret = HREF_Wrapper('', $url_params);
unset($m_var_list_update["cat"], $var_list_update["t"]);
break;
case "adminlink":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$m_var_list_update["p"] = 1;
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
unset($m_var_list_update["p"]);
return $ret;
break;
case "customlink":
$t = $this->GetCustomFieldValue("indextemplate","");
if(strlen($t))
{
$var_list_update["t"] = $t;
}
else
{
$var_list_update["t"] = $var_list["t"];
}
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = HREF_Wrapper();
unset($m_var_list_update["cat"], $var_list_update["t"]);
break;
case "link_selector":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
$tmp = GetVar('Selector'); if($tmp) $ret .= '&Selector='.$tmp;
$tmp = GetVar('new'); if($tmp) $ret .= '&new='.$tmp;
$tmp = GetVar('destform'); if($tmp) $ret .= '&destform='.$tmp;
unset($m_var_list_update["cat"]);
return $ret;
break;
case "admin_icon":
if( $element->GetAttributeByName('fulltag') )
{
$ret = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
}
else
$ret = $this->StatusIcon();
break;
case "subcats":
/*
@field:cat.subcats
@description: Loads category's subcategories into a list and renders using the m_list_cats global tag
@attrib:_subcattemplate:tpl:Template used to render subcategory list elements
@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: _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
*/
$attr = array();
$attr["_catid"] = $this->Get("CategoryId");
$attr["_itemtemplate"] = $element->GetAttributeByName('_subcattemplate');
if( $element->GetAttributeByName('_notable') )
$attr["_notable"]=1;
$ret = m_list_cats($attr);
break;
case "subcatcount":
/*
@field:cat.subcatcount
@description:returns number of subcategories
*/
$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
$txt .="_CategoryCount=\"1\" _ItemType=\"1\" _GroupOnly=\"$GroupOnly\" />";
$tag = new clsHtmlTag($txt);
$ret = $tag->Execute();
break;
case "itemcount":
/*
@field:cat.itemcount
@description:returns the number of items in the category
@attrib:_itemtype::name of item type to count, or all items if not set
*/
$typestr = $element->GetAttributeByName('_itemtype');
if(strlen($typestr))
{
$type = $objItemTypes->GetTypeByName($typestr);
if(is_object($type))
{
$ForceUpdate = 1;
$TypeId = $type->Get("ItemType");
$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
$txt .=" _ListType=\"category\" _CountCurrent=\"1\" _ForceUpdate=\"$ForceUpdate\" _ItemType=\"$TypeId\" _GroupOnly=\"$GroupOnly\" />";
$tag = new clsHtmlTag($txt);
$ret = $tag->Execute();
//echo "Category parseobject: $ret<br>";
}
else
$ret = "";
}
else
{
$ret = (int)$objCountCache->GetCatListTotal($this->Get("CategoryId"));
}
break;
case "totalitems":
/*
@field:cat.totalitems
@description:returns the number of items in the category and all subcategories
*/
$ret = $this->ItemCount();
break;
case 'modified':
$ret = '';
$date = $this->Get('Modified');
if(!$date) $date = $this->Get('CreatedOn');
if( $element->GetAttributeByName('_tz') )
{
$date = GetLocalTime($date,$objSession->Get("tz"));
}
$part = strtolower($element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$date);
}
else
{
$ret = ($date <= 0) ? '' : LangDate($date);
}
break;
case "itemdate":
/*
@field:cat.itemdate
@description:Returns the date the cache count was last updated
@attrib:_itemtype:Item name to check
@attrib:_tz:bool:Convert the date to the user's local time
@attrib:_part::Returns part of the date. The following options are available: month,day,year,time_24hr,time_12hr
*/
$typestr = $element->GetAttributeByName('_itemtype');
$type = $objItemTypes->GetTypeByName($typestr);
if(is_object($type))
{
$TypeId = $type->Get("ItemType");
$cc = $objCountCache->GetCountObject(1,$TypeId,$this->get("CategoryId"),0);
if(is_object($cc))
{
$date = $cc->Get("LastUpdate");
}
else
$date = "";
//$date = $this->GetCacheCountDate($TypeId);
if( $element->GetAttributeByName('_tz') )
{
$date = GetLocalTime($date,$objSession->Get("tz"));
}
$part = strtolower($element->GetAttributeByName('_part') );
if(strlen($part))
{
$ret = ExtractDatePart($part,$date);
}
else
{
if($date<=0)
{
$ret = "";
}
else
$ret = LangDate($date);
}
}
else
$ret = "";
break;
case "new":
/*
@field:cat.new
@description:returns text if category's status is "new"
@attrib:_label:lang: Text to return if status is new
*/
if($this->IsNewItem())
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_new";
$ret = language($ret);
}
else
$ret = "";
break;
case "pick":
/*
@field:cat.pick
@description:returns text if article's status is "hot"
@attrib:_label:lang: Text to return if status is "hot"
*/
if($this->Get("EditorsPick")==1)
{
$ret = $element->GetAttributeByName('_label');
if(!strlen($ret))
$ret = "lu_pick";
$ret = language($ret);
}
else
$ret = "";
break;
case "parsetag":
/*
@field:cat.parsetag
@description:returns a tag output with this categoriy set as a current category
@attrib:_tag:: tag name
*/
$tag = new clsHtmlTag();
$tag->name = $element->GetAttributeByName('_tag');
$tag->attributes = $element->attributes;
$tag->attributes["_catid"] = $this->Get("CategoryId");
$ret = $tag->Execute();
break;
/*
@field:cat.relevance
@description:Displays the category relevance in search results
@attrib:_displaymode:: How the relevance should be displayed<br>
<UL>
<LI>"Numerical": Show the decimal value
<LI>"Bar": Show the HTML representing the relevance. Returns two HTML cells &lg;td&lt; with specified background colors
<LI>"Graphical":Show image representing the relevance
</UL>
@attrib:_onimage::Zero relevance image shown in graphical display mode. Also used as prefix to build other images (i.e. prefix+"_"+percentage+".file_extension"
@attrib:_OffBackGroundColor::Off background color of HTML cell in bar display mode
@attrib:_OnBackGroundColor::On background color of HTML cell in bar display mode
*/
}
if( !isset($ret) ) $ret = parent::ParseObject($element);
}
return $ret;
}
function parsetag($tag)
{
global $objConfig,$objUsers, $m_var_list, $m_var_list_update;
if(is_object($tag))
{
$tagname = $tag->name;
}
else
$tagname = $tag;
switch($tagname)
{
case "cat_id":
return $this->Get("CategoryId");
break;
case "cat_parent":
return $this->Get("ParentId");
break;
case "cat_fullpath":
return $this->GetNavbar();
break;
case "cat_name":
return $this->Get($this->TitleField);
break;
case "cat_desc":
return $this->Get($this->DescriptionField);
break;
case "cat_priority":
if($this->Get("Priority")!=0)
{
return (int)$this->Get("Priority");
}
else
return "";
break;
case "cat_pick":
if ($this->Get("EditorsPick"))
return "pick";
break;
case "cat_status":
return $this->Get("Status");
break;
case "cat_Pending":
return $this->Get($this->TitleField);
break;
case "cat_pop":
if($this->IsPopItem())
return "pop";
break;
case "cat_new":
if($this->IsNewItem())
return "new";
break;
case "cat_hot":
if($this->IsHotItem())
return "hot";
break;
case "cat_metakeywords":
return $this->Get("MetaKeywords");
break;
case "cat_metadesc":
return $this->Get("MetaDescription");
break;
case "cat_createdby":
return $objUsers->GetUserName($this->Get("CreatedById"));
break;
case "cat_resourceid":
return $this->Get("ResourceId");
break;
case "cat_sub_cats":
return $this->GetSubCats($objConfig->Get("SubCat_ListCount"));
break;
case "cat_link":
return $this->Cat_Link();
break;
case "subcat_count":
return $this->SubCatCount();
break;
case "cat_itemcount":
return (int)$this->GetTotalItemCount();
break;
case "cat_link_admin":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$m_var_list_update["p"] = 1;
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
unset($m_var_list_update["p"]);
return $ret;
break;
case "cat_admin_icon":
$ret = $this->StatusIcon();
return $ret;
break;
case "cat_link_selector":
$m_var_list_update["cat"] = $this->Get("CategoryId");
$ret = $_SERVER["PHP_SELF"]."?env=" . BuildEnv();
unset($m_var_list_update["cat"]);
return $ret;
break;
case "cat_link_edit":
$m_var_list_update["id"] = $this->Get("CategoryId");
$ret = "addcategory.php?env=" . BuildEnv();
unset($m_var_list_update["id"]);
return $ret;
break;
case "cat_date":
return LangDate($this->Get("CreatedOn"), 0, true);
break;
case "cat_num_cats":
return $this->Get("CachedDescendantCatsQty");
break;
case "cell_back":
if ($m_var_list_update["cat_cell"]=="#cccccc")
{
$m_var_list_update["cat_cell"]="#ffffff";
return "#ffffff";
}
else
{
$m_var_list_update["cat_cell"]="#cccccc";
return "#cccccc";
}
break;
default:
return "Undefined:$tagname";
}
}
/*function ParentNames()
{
global $objCatList;
if(strlen($this->Get("CachedNavbar"))==0)
{
$nav = "";
//echo "Rebuilding Navbar..<br>\n";
if(strlen($this->Get("ParentPath"))==0)
{
$this->UpdateCachedPath();
}
$cats = explode("|",substr($this->Get("ParentPath"),1,-1));
foreach($cats as $catid)
{
$cat =& $objCatList->GetCategory($catid);
if(is_object($cat))
{
if(strlen($cat->Get($this->TitleField)))
$names[] = $cat->Get($this->TitleField);
}
}
$nav = implode(">", $names);
$this->Set("CachedNavbar",$nav);
$this->Update();
}
$res = explode("&|&",$this->Get("CachedNavbar"));
return $res;
}*/
// not used anywhere
/* function UpdateCacheCounts()
{
global $objItemTypes;
$CatId = $this->Get("CategoryId");
if($CatId>0)
{
//echo "Updating count for ".$this->Get("CachedNavbar")."<br>\n";
UpdateCategoryCount(0,$CatId);
}
}*/
/**
* @return void
* @param int $date
* @desc Set Modified field for category & all it's parent categories
*/
function SetLastUpdate($date)
{
$parents = $this->Get('ParentPath');
if (!$parents) return false;
$parents = substr($parents, 1, strlen($parents) - 2 );
$parents = explode('|', $parents);
$db =&GetADODBConnection();
$sql = 'UPDATE '.$this->tablename.' SET Modified = '.$date.' WHERE CategoryId IN ('.implode(',', $parents).')';
$db->Execute($sql);
}
}
class clsCatList extends clsItemList //clsItemCollection
{
//var $Page; // no need because clsItemList class used instead of clsItemCollection
//var $PerPageVar;
var $TitleField = '';
var $DescriptionField = '';
+ var $PrimaryTitleField;
+ var $PrimaryDescriptionField;
function clsCatList()
{
global $m_var_list;
$this->clsItemCollection();
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$this->TitleField = $ml_formatter->LangFieldName('Name');
+ $this->PrimaryTitleField = $ml_formatter->LangFieldName('Name', 1);
$this->DescriptionField = $ml_formatter->LangFieldName('Description');
+ $this->PrimaryDescriptionField = $ml_formatter->LangFieldName('Description', 1);
$this->Prefix = 'c';
$this->classname="clsCategory";
$this->AdminSearchFields = array($this->TitleField, $this->DescriptionField);
$this->Page = (int)$m_var_list["p"];
$this->PerPageVar = "Perpage_Category";
$this->SourceTable = GetTablePrefix()."Category";
$this->BasePermission="CATEGORY";
$this->DefaultPerPage = 20;
}
function SaveNewPage()
{
global $m_var_list;
$m_var_list["p"] = $this->Page;
}
function GetCountSQL($PermName,$CatId=NULL, $GroupId=NULL, $AdditonalWhere="")
{
global $objSession, $objPermissions, $objCatList;
$ltable = $this->SourceTable;
$acl = $objSession->GetACLClause();
$cattable = GetTablePrefix()."CategoryItems";
$CategoryTable = GetTablePrefix()."Category";
$ptable = GetTablePrefix()."PermCache";
$VIEW = $objPermissions->GetPermId($PermName);
$sql = "SELECT count(*) as CacheVal FROM $ltable ";
$sql .="INNER JOIN $ptable ON ($ltable.CategoryId=$ptable.CategoryId) ";
$sql .="WHERE ($acl AND PermId=$VIEW AND $ltable.Status=1) ";
if(strlen($AdditonalWhere)>0)
{
$sql .= "AND (".$AdditonalWhere.")";
}
return $sql;
}
function CountCategories($attribs)
{
global $objSession;
$ParentWhere='';
$cat = getArrayValue($attribs,'_catid');
if(!is_numeric($cat))
{
$cat = $this->CurrentCategoryID();
}
if((int)$cat>0)
$c = $this->GetCategory($cat);
if( getArrayValue($attribs,'_subcats') && $cat>0)
{
$ParentWhere = "(ParentPath LIKE '".$c->Get("ParentPath")."%' AND ".$this->SourceTable.".CategoryId != $cat)";
}
if( getArrayValue($attribs,'_today') )
{
$today = adodb_mktime(0,0,0,adodb_date("m"),adodb_date("d"),adodb_date("Y"));
$TodayWhere = "(CreatedOn>=$today)";
}
else
{
$TodayWhere = '';
}
if( getArrayValue($attribs,'_grouponly') )
{
$GroupList = $objSession->Get("GroupList");
}
else
$GroupList = NULL;
$where = "";
if(strlen($ParentWhere))
{
$where = $ParentWhere;
}
if(strlen($TodayWhere))
{
if(strlen($where))
$where .=" AND ";
$where .= $TodayWhere;
}
$sql = $this->GetCountSQL("CATEGORY.VIEW",$cat,$GroupList,$where);
// echo "SQL: ".$sql."<BR>";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields["CacheVal"];
}
else
$ret = 0;
return $ret;
}
function CurrentCategoryID()
{
global $m_var_list;
return (int)$m_var_list["cat"];
}
function NumCategories()
{
return $this->NumItems();
}
function &CurrentCat()
{
//return $this->GetCategory($this->CurrentCategoryID());
return $this->GetItem($this->CurrentCategoryID());
}
function &GetCategory($CatID)
{
return $this->GetItem($CatID);
}
function GetByResource($ResId)
{
return $this->GetItemByField("ResourceId",$ResId);
}
function QueryOrderByClause($EditorsPick=FALSE,$Priority=FALSE,$UseTableName=FALSE)
{
global $objSession;
if($UseTableName)
{
$TableName = $this->SourceTable.".";
}
else
$TableName = "";
$Orders = array();
if($EditorsPick)
{
$Orders[] = $TableName."EditorsPick DESC";
}
if($Priority)
{
$Orders[] = $TableName."Priority DESC";
}
$FieldVar = "Category_Sortfield";
$OrderVar = "Category_Sortorder";
if(is_object($objSession))
{
if(strlen($objSession->GetPersistantVariable($FieldVar))>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
$FieldVar = "Category_Sortfield2";
$OrderVar = "Category_Sortorder2";
if(is_object($objSession))
{
if(strlen($objSession->GetPersistantVariable($FieldVar))>0)
{
$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ".
$objSession->GetPersistantVariable($OrderVar));
}
}
global $m_var_list;
foreach ($Orders as $key => $val) {
$Orders[$key] = preg_replace('/\.(Name|Description)/', '.l'.$m_var_list['lang'].'_$1', $Orders[$key]);
}
if(count($Orders)>0)
{
$OrderBy = "ORDER BY ".implode(", ",$Orders);
}
else
$OrderBy="";
return $OrderBy;
}
function LoadCategories($where="", $orderBy = "", $no_limit = true, $fix_method = 'set_first')
{
// load category list using $where clause
// apply ordering specified in $orderBy
// show all cats ($no_limit = true) or only from current page ($no_limit = false)
// in case if stored page is greather then page count issue page_fixing with
// method specified (see "FixInvalidPage" method for details)
$PerPage = $this->GetPerPage();
$this->QueryItemCount = TableCount($this->SourceTable,$where,0);
if($no_limit == false)
{
$this->FixInvalidPage($fix_method);
$Start = !empty($this->Page)? (($this->Page-1) * $PerPage) : 0;
$limit = "LIMIT ".$Start.",".$PerPage;
}
else
$limit = NULL;
return $this->Query_Category($where, $orderBy, $limit);
}
function Query_Category($whereClause="",$orderByClause="",$limit=NULL)
{
global $m_var_list, $objSession, $Errors, $objPermissions;
$GroupID = $objSession->Get("GroupID");
$resultset = array();
$table = $this->SourceTable;
$ptable = GetTablePrefix()."PermCache";
$CAT_VIEW = $objPermissions->GetPermId("CATEGORY.VIEW");
if(!$objSession->HasSystemPermission("ADMIN"))
{
$sql = "SELECT * FROM $table INNER JOIN $ptable ON ($ptable.CategoryId=$table.CategoryId)";
$acl_where = $objSession->GetACLClause();
if(strlen($whereClause))
{
$sql .= " WHERE ($acl_where) AND PermId=$CAT_VIEW AND ".$whereClause;
}
else
$sql .= " WHERE ($acl_where) AND PermId=$CAT_VIEW ";
}
else
{
$sql ="SELECT * FROM $table ".($whereClause ? "WHERE $whereClause" : '');
}
$sql .=" ".$orderByClause;
if(isset($limit) && strlen(trim($limit)))
$sql .= " ".$limit;
if($objSession->HasSystemPermission("DEBUG.LIST"))
echo $sql;
//echo "SQL: $sql<br>";
return $this->Query_item($sql);
}
function CountPending()
{
return TableCount($this->SourceTable,"Status=".STATUS_PENDING,0);
}
function GetPageLinkList($dest_template=NULL,$page="",$PagesToList=10,$HideEmpty=TRUE, $extra_attributes = '')
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
// if(!strlen($page)) $page = GetIndexURL(2);
$PerPage = $this->GetPerPage();
$NumPages = ceil( $this->GetNumPages($PerPage) );
if($NumPages == 1 && $HideEmpty) return '';
if(strlen($dest_template))
{
$var_list_update["t"] = $dest_template;
}
else
$var_list_update["t"] = $var_list["t"];
$o = "";
if($this->Page>$NumPages)
$this->Page=$NumPages;
$StartPage = (int)$this->Page - ($PagesToList/2);
if($StartPage<1)
$StartPage=1;
$EndPage = $StartPage+($PagesToList-1);
if($EndPage>$NumPages)
{
$EndPage = $NumPages;
$StartPage = $EndPage-($PagesToList-1);
if($StartPage<1)
$StartPage=1;
}
$o = "";
if($StartPage>1)
{
$m_var_list_update["p"] = $this->Page-$PagesToList;
$prev_url = HREF_Wrapper();
$o .= '<a href="'.$prev_url.'" '.$extra_attributes.'>&lt;&lt;</a>';
}
for($p=$StartPage;$p<=$EndPage;$p++)
{
if($p!=$this->Page)
{
$m_var_list_update["p"]=$p;
$href = HREF_Wrapper();
$o .= ' <a href="'.$href.'" '.$extra_attributes.'>'.$p.'</a> ';
}
else
{
$o .= "$p";
}
}
if($EndPage<$NumPages && $EndPage>0)
{
$m_var_list_update["p"]=$this->Page+$PagesToList;
$next_url = HREF_Wrapper();
$o .= '<a href="'.$next_url.'" '.$extra_attributes.'> &gt;&gt;</a>';
}
unset($m_var_list_update,$var_list_update["t"] );
return $o;
}
function GetAdminPageLinkList($url)
{
global $objConfig, $m_var_list_update, $var_list_update, $var_list;
$PerPage = $this->GetPerPage();
$NumPages = ceil($this->GetNumPages($PerPage));
$o = "";
if($this->Page>1)
{
$m_var_list_update["p"]=$this->Page-1;
$prev_url = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
$o .= "<A HREF=\"$prev_url\" class=\"NAV_URL\"><<</A>";
}
if($this->Page<$NumPages)
{
$m_var_list_update["p"]=$this->Page+1;
$next_url = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
}
for($p=1;$p<=$NumPages;$p++)
{
if($p != $this->Page)
{
$m_var_list_update["p"]=$p;
$href = $url."?env=".BuildEnv();
unset($m_var_list_update["p"]);
$o .= " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
}
else
$o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
}
if($this->Page < $NumPages)
$o .= "<A HREF=\"$next_url\" class=\"NAV_URL\">>></A>";
return $o;
}
function Search_Category($orderByClause)
{
global $objSession, $objConfig, $Errors;
$PerPage = $this->GetPerPage();
$Start = ($this->Page-1) * $PerPage;
$objResults = new clsSearchResults("Category","clsCategory");
$this->Clear();
$this->Categories = $objResults->LoadSearchResults($Start,$PerPage);
return $this->Categories;
}
function GetSubCats($ParentCat)
{
return $this->Query_Category("ParentId=".$ParentCat,"");
}
function AllSubCats($ParentCat)
{
$c =& $this->GetCategory($ParentCat);
$sql = "SELECT * FROM ".$this->SourceTable." WHERE ParentPath LIKE '".$c->Get("ParentPath")."%'";
$rs = $this->adodbConnection->Execute($sql);
$subcats = array();
while($rs && !$rs->EOF)
{
if($rs->fields["CategoryId"]!=$ParentCat)
{
$subcats[] = $rs->fields["CategoryId"];
}
$rs->MoveNext();
}
if($ParentCat>0)
{
if($c->Get("CachedDescendantCatsQty")!=count($subcats))
{
$c->Set("CachedDescendantCatsQty",count($subcats));
}
}
return $subcats;
}
function cat_navbar($admin=0, $cat, $target_template, $separator = " > ", $LinkLeaf = FALSE,
$root = 0,$RootTemplate="",$modcat=0, $ModTemplate="", $LinkRoot = FALSE)
{
// draw category navigation bar (at top)
global $Errors, $var_list_update, $var_list, $m_var_list_update, $m_var_list, $objConfig;
$url_params = Array('reset' => 1);
if( GetVar('Selector') ) $url_params['Selector'] = GetVar('Selector');
if( GetVar('new') ) $url_params['new'] = GetVar('new');
if( GetVar('destform') ) $url_params['destform'] = GetVar('destform');
if( GetVar('destfield') ) $url_params['destfield'] = GetVar('destfield');
$nav = "";
$m_var_list_update["p"]=1;
if(strlen($target_template)==0)
$target_template = $var_list["t"];
if($cat == 0)
{
$cat_name = language($objConfig->Get("Root_Name"));
if ($LinkRoot)
{
$var_list_update["t"] = strlen($RootTemplate)? $RootTemplate : $target_template;
$nav = "<a class=\"navbar\" href=\"" . HREF_Wrapper('', $url_params) . "\">$cat_name</a>"; }
else
$nav = "<span class=\"NAV_CURRENT_ITEM\">$cat_name</span>";
}
else
{
$nav = array();
$c =& $this->GetCategory($cat);
$nav_unparsed = $c->Get("ParentPath");
if(strlen($nav_unparsed)==0)
{
$c->UpdateCachedPath();
$nav_unparsed = $c->Get("ParentPath");
}
//echo " Before $nav_unparsed ";
if($root)
{
$r =& $this->GetCategory($root);
$rpath = $r->Get("ParentPath");
$nav_unparsed = substr($nav_unparsed,strlen($rpath),-1);
$cat_name = $r->Get($this->TitleField);
$m_var_list_update["cat"] = $root;
if($cat == $catid && !$LinkLeaf)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>"; //href=\"browse.php?env=". BuildEnv() ."\"
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".HREF_Wrapper('', $url_params)."\">".$cat_name."</a>";
}
else
{
if(strlen($RootTemplate))
{
$var_list_update["t"] = $RootTemplate;
}
else
{
$var_list_update["t"] = $target_template;
}
$nav[] = "<a class=\"navbar\" href=\"".HREF_Wrapper('', $url_params)."\">".$cat_name."</a>";
}
}
}
else
{
$nav_unparsed = substr($nav_unparsed,1,-1);
$cat_name = language($objConfig->Get("Root_Name"));
$m_var_list_update["cat"] = 0;
if($cat == 0)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>"; //href=\"browse.php?env=". BuildEnv() ."\"
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".HREF_Wrapper('', $url_params)."\">".$cat_name."</a>";
}
else
{
if(strlen($RootTemplate))
{
$var_list_update["t"] = $RootTemplate;
}
else
$var_list_update["t"] = $target_template;
$nav[] = "<a class=\"navbar\" href=\"".HREF_Wrapper('', $url_params)."\">".$cat_name."</a>";
}
}
}
//echo " After $nav_unparsed <br>\n";
if(strlen($target_template)==0)
$target_template = $var_list["t"];
$cats = explode("|", $nav_unparsed);
foreach($cats as $catid)
{
if($catid)
{
$c =& $this->GetCategory($catid);
if(is_object($c))
{
$cat_name = $c->Get($this->TitleField);
$m_var_list_update["cat"] = $catid;
if($catid==$modcat && strlen($ModTemplate)>0)
{
$t = $ModTemplate;
}
else
$t = $target_template;
if($cat == $catid && !$LinkLeaf)
{
$nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";
}
else
{
if ($admin == 1)
{
$nav[] = "<a class=\"control_link\" href=\"".HREF_Wrapper('', $url_params)."\">".$cat_name."</a>";
}
else
{
$var_list_update["t"] = $t;
$nav[] = "<a class=\"navbar\" href=\"".HREF_Wrapper('', $url_params)."\">".$cat_name."</a>";
unset($var_list_update["t"]);
}
}
unset($m_var_list_update["cat"]);
}
}
}
$nav = implode($separator, $nav);
}
return $nav;
}
function &Add_NEW($fields_hash, $from_import = false)
{
global $objSession;
$fields_hash['CreatedById'] = $objSession->Get('PortalUserId');
$d = new clsCategory(NULL);
$fields_hash['Filename'] = $d->StripDisallowed($fields_hash['Filename']);
$d->tablename = $this->SourceTable;
if ( $d->UsingTempTable() ) {
$d->Set('CategoryId', -1);
}
$d->idfield = 'CategoryId';
foreach ($fields_hash as $field_name => $field_value) {
$d->Set($field_name, $field_value);
}
-
+
$d->Create();
if (!$from_import) {
if ($d->Get('Status') == STATUS_ACTIVE) {
$d->SendUserEventMail("CATEGORY.ADD", $objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD");
}
else
{
$d->SendUserEventMail("CATEGORY.ADD.PENDING", $objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD.PENDING");
}
$d->UpdateCachedPath();
}
return $d;
}
function &Add( $ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New, $Pop,
$Priority, $MetaKeywords,$MetaDesc, $auto_filename = 1, $filename = '')
{
global $objSession;
$UserId = $objSession->Get('UserId');
$d = new clsCategory(NULL);
$filename = $d->StripDisallowed($filename);
$d->tablename = $this->SourceTable;
if( $d->UsingTempTable() ) $d->Set('CategoryId', -1);
$d->idfield = 'CategoryId';
$d->Set(Array( 'ParentId', $this->TitleField, $this->DescriptionField, 'CreatedOn', 'EditorsPick', 'Status', 'HotItem',
'NewItem','PopItem', 'Priority', 'MetaKeywords', 'MetaDescription', 'CreatedById',
'AutomaticFilename', 'Filename'),
Array( $ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New,
$Pop, $Priority, $MetaKeywords,$MetaDesc, $UserId, $auto_filename, $filename) );
$d->Create();
if($Status == 1)
{
$d->SendUserEventMail("CATEGORY.ADD",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD");
}
else
{
$d->SendUserEventMail("CATEGORY.ADD.PENDING",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.ADD.PENDING");
}
$d->UpdateCachedPath();
// RunUp($ParentId, 'Increment_Count');
return $d;
}
function &Edit_Category($category_id, $fields_hash)
{
$d =& $this->GetCategory($category_id);
$fields_hash['Filename'] = $d->StripDisallowed($fields_hash['Filename']);
foreach ($fields_hash as $field_name => $field_value) {
$d->Set($field_name, $field_value);
}
$d->Update();
$d->UpdateCachedPath();
return $d;
}
function Move_Category($Id, $ParentTo)
{
global $objCatList;
$d =& $this->GetCategory($Id);
$oldparent = $d->Get("ParentId");
$ChildList = $d->GetSubCatIds();
/*
echo "Target Parent Id: $ParentTo <br>\n";
echo "<PRE>";print_r($ChildList); echo "</PRE>";
echo "Old Parent: $oldparent <br>\n";
echo "ID: $Id <br>\n";
*/
/* sanity checks */
if(!in_array($ParentTo,$ChildList) && $oldparent != $ParentTo && $oldparent != $Id &&
$Id != $ParentTo)
{
$d->Set("ParentId", $ParentTo);
$d->Set('Filename', '');
$d->Update();
$d->UpdateCachedPath();
RunUp($oldparent, "Decrement_Count");
RunUp($ParentTo, "Increment_Count");
RunDown($ParentTo, "UpdateCachedPath");
return TRUE;
}
else
{
global $Errors;
$Errors->AddAdminUserError("la_error_move_subcategory");
return FALSE;
}
die();
}
function Copy_CategoryTree($Id, $ParentTo)
{
global $PastedCatIds;
$new = $this->Copy_Category($Id, $ParentTo);
if($new)
{
$PastedCatIds[$Id] = $new;
$sql = "SELECT CategoryId from ".GetTablePrefix()."Category where ParentId=$Id";
$result = $this->adodbConnection->Execute($sql);
if ($result && !$result->EOF)
{
while(!$result->EOF)
{
$this->Copy_CategoryTree($result->fields["CategoryId"], $new);
$result->MoveNext();
}
}
}
return $new;
}
function Copy_Category($Id, $ParentTo)
{
global $objGroups;
$src = $this->GetCategory($Id);
$Children = $src->GetSubCatIds();
if($Id==$ParentTo || in_array($ParentTo,$Children))
{
/* sanity error here */
global $Errors;
$Errors->AddAdminUserError("la_error_copy_subcategory");
return 0;
}
$dest = $src;
$dest->Set("ParentId", $ParentTo);
if ($src->get("ParentId") == $ParentTo)
{
$OldName = $src->Get($this->TitleField);
if(substr($OldName,0,5)=="Copy ")
{
$parts = explode(" ",$OldName,4);
if($parts[2]=="of" && is_numeric($parts[1]))
{
$Name = $parts[3];
}
else
if($parts[1]=="of")
{
$Name = $parts[2]." ".$parts[3];
}
else
$Name = $OldName;
}
else
$Name = $OldName;
//echo "New Name: $Name<br>";
$dest->Set($this->TitleField, $Name);
$Names = CategoryNameCount($ParentTo,$Name);
//echo "Names Count: ".count($Names)."<br>";
if(count($Names)>0)
{
$NameCount = count($Names);
$found = FALSE;
$NewName = "Copy of $Name";
if(!in_array($NewName,$Names))
{
//echo "Matched on $NewName in:<br>\n";
$found = TRUE;
}
else
{
for($x=2;$x<$NameCount+2;$x++)
{
$NewName = "Copy ".$x." of ".$Name;
if(!in_array($NewName,$Names))
{
$found = TRUE;
break;
}
}
}
if(!$found)
{
$NameCount++;
$NewName = "Copy $NameCount of $Name";
}
//echo "New Name: $NewName<br>";
$dest->Set($this->TitleField, $NewName);
}
}
$dest->UnsetIdField();
$dest->Set("CachedDescendantCatsQty",0);
$dest->Set("ResourceId",NULL);
$dest->Set('Filename', '');
$dest->Create();
$dest->UpdateCachedPath();
$p = new clsPermList();
$p->Copy_Permissions($src->Get("CategoryId"),$dest->Get("CategoryId"));
$glist = $objGroups->GetAllGroupList();
$view = $p->GetGroupPermList($dest, "CATEGORY.VIEW", $glist);
$dest->SetViewPerms("CATEGORY.VIEW",$view,$glist);
RunUp($ParentTo, "Increment_Count");
return $dest->Get("CategoryId");
}
function Delete_Category($Id, $check_perm = false)
{
global $objSession;
$d =& $this->GetCategory($Id);
if (is_object($d)) {
$perm_status = true;
if ($check_perm) {
if (defined('ADVANCED_VIEW') && ADVANCED_VIEW) {
// check by this cat parent category
$check_cat = $d->Get('ParentId');
}
else {
// check by current category
$check_cat = $this->CurrentCategoryID();
}
$perm_status = $objSession->HasCatPermission('CATEGORY.DELETE', $check_cat);
}
if (($d->Get("CategoryId") == $Id) && $perm_status) {
$d->SendUserEventMail("CATEGORY.DELETE",$objSession->Get("PortalUserId"));
$d->SendAdminEventMail("CATEGORY.DELETE");
$p =& $this->GetCategory($d->Get("ParentId"));
RunDown($d->Get("CategoryId"), "Delete");
RunUp($p->Get("CategoryId"), "Decrement_Count");
RunUp($d->Get("CategoryId"),"ClearCacheData");
}
}
}
function PasteFromClipboard($TargetCat)
{
global $objSession;
$clip = $objSession->GetVariable("ClipBoard");
if(strlen($clip))
{
$ClipBoard = ParseClipboard($clip);
$IsCopy = (substr($ClipBoard["command"],0,4)=="COPY") || ($ClipBoard["source"] == $TargetCat);
$item_ids = explode(",",$ClipBoard["ids"]);
for($i=0;$i<count($item_ids);$i++)
{
$ItemId = $item_ids[$i];
$item = $this->GetItem($item_ids[$i]);
if(!$IsCopy)
{
$this->Move_Category($ItemId, $TargetCat);
$clip = str_replace("CUT","COPY",$clip);
$objSession->SetVariable("ClipBoard",$clip);
}
else
{
$this->Copy_CategoryTree($ItemId,$TargetCat);
}
}
}
}
function NumChildren($ParentID)
{
$cat_filter = "m_cat_filter";
global $$cat_filter;
$filter = $$cat_filter;
$adodbConnection = &GetADODBConnection();
$sql = "SELECT COUNT(*) as children from ".$this->SourceTable." where ParentId=" . $ParentID . $filter;
$result = $adodbConnection->Execute($sql);
return $result->fields["children"];
}
function UpdateMissingCacheData()
{
$rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE ParentPath IS NULL or ParentPath=''");
while($rs && !$rs->EOF)
{
$c = new clsCategory(NULL);
$data = $rs->fields;
$c->SetFromArray($data);
$c->UpdateCachedPath();
$rs->MoveNext();
}
$ml_formatter =& $this->Application->recallObject('kMultiLanguage');
$navbar_field = $ml_formatter->LangFieldName('CachedNavbar');
$rs = $this->adodbConnection->Execute('SELECT * FROM '.$this->SourceTable.' WHERE '.$navbar_field.' IS NULL OR '.$navbar_field.' = ""');
while($rs && !$rs->EOF)
{
$c = new clsCategory(NULL);
$data = $rs->fields;
$c->SetFromArray($data);
$c->UpdateCachedPath();
$rs->MoveNext();
}
}
function CopyFromEditTable($idfield)
{
global $objGroups, $objSession, $objPermList;
$GLOBALS['_CopyFromEditTable']=1;
$objPermList = new clsPermList();
$edit_table = $objSession->GetEditTable($this->SourceTable);
$sql = "SELECT * FROM $edit_table";
$rs = $this->adodbConnection->Execute($sql);
$item_ids = Array();
while($rs && !$rs->EOF)
{
$data = $rs->fields;
$c = new $this->classname;
$c->SetFromArray($data);
$c->Dirty();
if($c->Get("CategoryId")>0)
{
$c->Update();
}
else
{
$c->UnsetIdField();
$c->Create();
$sql = "UPDATE ".GetTablePrefix()."Permissions SET CatId=".$c->Get("CategoryId")." WHERE CatId=-1";
$this->adodbConnection->Execute($sql);
}
$c->UpdateCachedPath();
$c->UpdateACL();
$c->SendUserEventMail("CATEGORY.MODIFY",$objSession->Get("PortalUserId"));
$c->SendAdminEventMail("CATEGORY.MODIFY");
$c->Related = new clsRelationshipList();
if(is_object($c->Related))
{
$r = $c->Related;
$r->CopyFromEditTable($c->Get("ResourceId"));
}
$item_ids[] = $c->UniqueId();
//RunDown($c->Get("CategoryId"),"UpdateCachedPath");
//RunDown($c->Get("CategoryId"),"UpdateACL");
unset($c);
unset($r);
$rs->MoveNext();
}
@$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");
unset($GLOBALS['_CopyFromEditTable']);
return $item_ids;
//$this->UpdateMissingCacheData();
}
function PurgeEditTable($idfield)
{
parent::PurgeEditTable($idfield);
$sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE CatId=-1";
$this->adodbConnection->Execute($sql);
}
function GetExclusiveType($CatId)
{
global $objItemTypes, $objConfig;
$itemtype = NULL;
$c =& $this->GetItem($CatId);
$path = $c->Get("ParentPath");
foreach($objItemTypes->Items as $Type)
{
$RootVar = $Type->Get("ItemName")."_Root";
$RootId = $objConfig->Get($RootVar);
if((int)$RootId)
{
$rcat = $this->GetItem($RootId);
$rpath = $rcat->Get("ParentPath");
$p = substr($path,0,strlen($rpath));
//echo $rpath." vs. .$p [$path]<br>\n";
if($rpath==$p)
{
$itemtype = $Type;
break;
}
}
}
return $itemtype;
}
}
function RunUp($Id, $function, $Param=NULL)
{
global $objCatList;
$d = $objCatList->GetCategory($Id);
$ParentId = $d->Get("ParentId");
if ($ParentId == 0)
{
if($Param == NULL)
{
$d->$function();
}
else
{
$d->$function($Param);
}
}
else
{
RunUp($ParentId, $function, $Param);
if($Param == NULL)
{
$d->$function();
}
else
{
$d->$function($Param);
}
}
}
function RunDown($Id, $function, $Param=NULL)
{
global $objCatList;
$adodbConnection = &GetADODBConnection();
$sql = "select CategoryId from ".GetTablePrefix()."Category where ParentId='$Id'";
$rs = $adodbConnection->Execute($sql);
while($rs && !$rs->EOF)
{
RunDown($rs->fields["CategoryId"], $function, $Param);
$rs->MoveNext();
}
$d = $objCatList->GetCategory($Id);
if($Param == NULL)
{
$d->$function();
}
else
$d->$function($Param);
}
?>
\ No newline at end of file
Property changes on: branches/unlabeled/unlabeled-1.61.2/kernel/include/category.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.61
\ No newline at end of property
+1.61.2.1
\ No newline at end of property
Index: branches/unlabeled/unlabeled-1.37.2/kernel/include/itemdb.php
===================================================================
--- branches/unlabeled/unlabeled-1.37.2/kernel/include/itemdb.php (revision 8331)
+++ branches/unlabeled/unlabeled-1.37.2/kernel/include/itemdb.php (revision 8332)
@@ -1,697 +1,701 @@
<?php
define('FT_OPTION', 1); // option formatter
-class clsItemDB
-{
+class clsItemDB
+{
var $Formatters = Array(); // by Alex
var $m_dirtyFieldsMap = array();
var $Data = array();
var $adodbConnection;
var $tablename;
var $BasePermission;
var $id_field;
var $NoResourceId;
var $debuglevel;
-
+
var $Prefix = '';
var $Special = '';
-
+
var $SelectSQL = 'SELECT * FROM %s WHERE %s';
-
+
/**
* Application object
*
* @var kApplication
*/
var $Application = null;
-
+
/**
* Connection to database
*
* @var kDBConnection
*/
var $Conn = null;
-
+
function clsItemDB()
{
if (class_exists('kApplication')) {
// just in case when aplication is not found
- $this->Application =& kApplication::Instance();
+ $this->Application =& kApplication::Instance();
$this->Conn =& $this->Application->GetADODBConnection();
}
-
+
$this->adodbConnection = &GetADODBConnection();
$this->tablename="";
$this->NoResourceId=0;
$this->debuglevel=0;
}
-
+
// ============================================================================================
function GetFormatter($field)
{
return $this->HasFormatter($field) ? $this->Formatters[$field] : false;
}
-
+
function isLiveTable()
{
global $objSession;
return !preg_match('/'.GetTablePrefix().'ses_'.$objSession->GetSessionKey().'_edit_(.*)/', $this->tablename);
}
function SetFormatter($field, $type, $params)
{
// by Alex
// all params after 2nd are formmater type specific
$this->Formatters[$field]['type'] = $type;
switch($type)
{
case FT_OPTION:
$this->Formatters[$field]['options'] = $params;
- break;
+ break;
}
}
- /*
+ /*
function FormatFields()
{
// format item in list data before printing
-
+
foreach($this->Formatters as $field => $formatter)
$this->Data[$field] = $this->FormatField($field);
}
*/
function FormatField($field)
{
// formats single field if it has formatter
if( $this->HasFormatter($field) )
{
$fmt = $this->Formatters[$field];
switch($fmt['type'])
{
case FT_OPTION:
return $fmt['options'][ $this->Data[$field] ];
- break;
+ break;
}
}
else
return $this->Get($field);
}
-
+
function HasFormatter($field)
{
// checks if formatter is set for field
return isset($this->Formatters[$field]) ? 1 : 0;
}
// ============================================================================================
-
+
function UnsetIdField()
{
$f = $this->IdField();
unset($this->Data[$f]);
unset($this->m_dirtyFieldsMap[$f]);
}
function UnsetField($field)
{
unset($this->Data[$field]);
unset($this->m_dirtyFieldsMap[$field]);
}
function IdField()
{
if(!strlen($this->id_field))
- {
+ {
return $this->tablename."Id";
}
else
return $this->id_field;
}
function UniqueId()
{
return $this->Get($this->IdField());
}
function SetUniqueId($value)
{
- $var = $this->IdField();
-
+ $var = $this->IdField();
+
if( $this->UsingTempTable() ) $value = $this->UniqueId();
-
+
$this->Set($var, $value);
}
function SetModified($UserId=NULL,$modificationDate=null)
{
global $objSession;
-
+
$keys = array_keys($this->Data);
if(in_array("Modified",$keys))
{
$this->Set("Modified", isset($modificationDate) ? $modificationDate : adodb_date("U") );
}
if(in_array("ModifiedById",$keys))
{
if(!$UserId)
$UserId = $objSession->Get("PortalUserId");
$this->Set("ModifiedById",$UserId);
}
}
function PrintVars()
{
echo '<pre>'.print_r($this->Data, true).'</pre>';
}
-
+
// =================================================================
function GetFormatted($name)
- {
+ {
// get formatted field value
return $this->FormatField($name);
}
- function Get($name)
- {
+ function Get($name, $ifempty=null)
+ {
// get un-formatted field value
//if( !isset($this->Data[$name]) ) print_pre( debug_backtrace() );
- return $this->HasField($name) ? $this->Data[$name] : '';
+ $ret = $this->HasField($name) ? $this->Data[$name] : '';
+ if (isset($ifempty) && $ret == '') {
+ $ret = $this->Data[$ifempty];
+ }
+ return $ret;
}
// =================================================================
function HasField($name)
{
// checks if field exists in item
- return isset($this->Data[$name]) ? 1 : 0;
+ return isset($this->Data[$name]) ? 1 : 0;
}
-
+
/**
* Set's value(-s) of field(-s) specified.
* Modifies HasChanges flag automatically.
*
* @param string/array $name
* @param string/array $value
* @access public
*/
function Set($name, $value)
{
//echo "Setting Field <b>$name</b>: = [$value]<br>";
if( is_array($name) )
{
for ($i=0; $i < sizeof($name); $i++)
{
$this->_Set($name[$i],$value[$i]);
}
}
else
{
$this->_Set($name,$value);
}
}
-
-
+
+
/**
* Set's value(-s) of field(-s) specified.
* Modifies HasChanges flag automatically.
*
* @param string $name
* @param string $value
* @access private
*/
function _Set($name,$value)
{
$var = 'm_'.$name;
if( !$this->HasField($name) || $this->Data[$name] != $value )
{
if( !(isset($_GET['new']) && $_GET['new']) ) {
$this->DetectChanges($name, $value);
}
$this->Data[$name] = $value;
$this->m_dirtyFieldsMap[$name] = $value;
}
}
function Dirty($list=NULL)
{
if($list==NULL)
{
foreach($this->Data as $field => $value)
{
$this->m_dirtyFieldsMap[$field] = $value;
}
}
else
- {
- foreach($list as $field)
- {
+ {
+ foreach($list as $field)
+ {
$this->m_dirtyFieldsMap[$field] = $this->Data[$field];
}
}
}
function Clean($list=NULL)
{
if($list == NULL)
{
unset($this->m_dirtyFieldsMap);
$this->m_dirtyFieldsMap=array();
}
else
- {
- foreach($list as $value)
- {
+ {
+ foreach($list as $value)
+ {
$varname = "m_" . $value;
unset($this->m_dirtyFieldsMap[$value]);
}
}
}
function SetDebugLevel($value)
{
$this->debuglevel = $value;
}
function SetFromArray($data, $dirty = false)
- {
+ {
if(is_array($data))
- {
+ {
$this->Data = $data;
if($dirty) $this->m_dirtyFieldsMap = $data;
}
}
function GetData()
{
return $this->Data;
}
function SetData($data, $dirty = false)
{
$this->SetFromArray($data, $dirty);
}
function Delete()
- {
+ {
global $Errors;
if($this->Get($this->IdField())==0)
{
$Errors->AddError("error.AppError",NULL,'Internal error: Delete requires set id',"",get_class($this),"Delete");
return false;
}
$sql = sprintf('DELETE FROM %s WHERE %s = %s', $this->tablename, $this->IdField(),
$this->UniqueId());
if($this->debuglevel>0)
echo $sql."<br>";
if ($this->adodbConnection->Execute($sql) === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Delete");
return false;
}
return true;
}
function Update($UpdatedBy=NULL,$modificationDate = null)
{
global $Errors, $objSession;
if( !$this->raiseEvent('OnBeforeItemUpdate') ) return false;
-
+
if( count($this->m_dirtyFieldsMap) == 0 ) return true;
$this->SetModified($UpdatedBy, $modificationDate);
$sql = 'UPDATE '.$this->tablename .' SET ';
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if(!is_numeric($key) && $key != $this->IdField() && $key!='ResourceId')
{
if( is_null($value) )
{
- $value = 'NULL';
+ $value = 'NULL';
}
else
{
- $value = $this->adodbConnection->qstr( isset($GLOBALS['_CopyFromEditTable']) ? $value : stripslashes($value) );
+ $value = $this->adodbConnection->qstr( isset($GLOBALS['_CopyFromEditTable']) ? $value : stripslashes($value) );
}
$sql .= '`'.$key.'` = '.$value.', ';
}
}
$sql = preg_replace('/(.*), $/','\\1',$sql);
-
+
$sql .= ' WHERE '.$this->IdField().' = '.$this->adodbConnection->qstr( $this->UniqueId() );
if( $this->debuglevel > 0 ) echo $sql.'<br>';
if( $this->adodbConnection->Execute($sql) === false )
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Update");
return false;
}
if( $objSession->GetVariable('HasChanges') == 2 ) $objSession->SetVariable('HasChanges', 1);
-
+
$this->raiseEvent('OnAfterItemUpdate');
-
+
return true;
}
-
+
function ReplaceID($new_id)
{
- // replace item's id, because Update method
+ // replace item's id, because Update method
// is too dummy to do this autommatically
// USED in temporary table editing stuff
$db =& $this->adodbConnection;
- $sql = "UPDATE %1\$s SET `%2\$s` = %3\$s WHERE `%2\$s` = %4\$s";
+ $sql = "UPDATE %1\$s SET `%2\$s` = %3\$s WHERE `%2\$s` = %4\$s";
$sql = sprintf($sql, $this->tablename, $this->IdField(), $new_id, (int)$this->UniqueId() );
if($this->debuglevel > 0) echo $sql.'<br>';
$db->Execute($sql);
}
-
+
function CreateSQL()
{
global $Errors;
-
+
$sql = "INSERT INTO ".$this->tablename." (";
$first = 1;
foreach ($this->Data as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s",$sql,$key);
$first = 0;
}
else
{
$sql = sprintf("%s, %s",$sql,$key);
}
}
$sql = sprintf('%s ) VALUES (',$sql);
$first = 1;
foreach ($this->Data as $key => $value)
{
if( is_array($value) )
{
global $debugger;
$debugger->dumpVars($value);
$debugger->appendTrace();
trigger_error('Value of array type not allowed in method <b>CreateSQL</b> of <b>clsItemDB</b> class', E_USER_ERROR);
}
if($first)
{
if(isset($GLOBALS['_CopyFromEditTable']))
$sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr(($value)));
else
$sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr(stripslashes($value)));
$first = 0;
}
else
{
if(isset($GLOBALS['_CopyFromEditTable']))
$sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr(($value)));
else
$sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr(stripslashes($value)));
}
}
$sql = sprintf('%s)',$sql);
-
+
return $sql;
}
-
+
/**
* Set's HasChanges flag based on new field
* with $name with value $value.
*
* @param string $name
* @param string $value
* @access private
*/
function DetectChanges($name, $value)
- {
+ {
global $objSession;
if( !is_object($objSession) ) return false;
-
+
//echo "<b>class: ".get_class($this)."</b><br>";
if (!isset($this->Data[$name]) ) return false;
-
- if ( getArrayValue($this->Data, $name) != $value && $value != '') {
+
+ if ( getArrayValue($this->Data, $name) != $value && $value != '') {
//echo "$name Modified tt ".$this->Data[$name]." tt $value<br>";
if ($objSession->GetVariable("HasChanges") != 1) {
- $objSession->SetVariable("HasChanges", 2);
+ $objSession->SetVariable("HasChanges", 2);
}
}
}
-
+
function Create()
{
global $Errors, $objSession;
-
+
if( !$this->raiseEvent('OnBeforeItemCreate') ) return false;
-
+
if($this->debuglevel) echo "Creating Item: ".get_class($this)."<br>";
if($this->NoResourceId!=1 && (int)$this->Get("ResourceId")==0)
{
$this->Set("ResourceId", GetNextResourceId());
}
$sql = $this->CreateSql();
if($this->debuglevel>0)
echo $sql."<br>\n";
if ($this->adodbConnection->Execute($sql) === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Create");
return false;
}
$this->SetUniqueId($this->adodbConnection->Insert_ID());
if ($objSession->GetVariable("HasChanges") == 2) {
$objSession->SetVariable("HasChanges", 1);
}
/*if ($this->adodbConnection->Affected_Rows() > 0) {
$objSession->SetVariable("HasChanges", 1);
} */
$this->raiseEvent('OnAfterItemCreate');
-
+
return true;
}
function Increment($field, $calculate_hot = false)
- {
+ {
global $Errors;
-
+
if ($calculate_hot) {
$sql = "SELECT $field FROM ".$this->tablename." WHERE ".$this->IdField()." = ".$this->UniqueId();
$rs = $this->adodbConnection->Execute($sql);
-
+
$sql = "SELECT MAX($field) AS max_value FROM ".$this->tablename." WHERE ROUND($field) = ".round($rs->fields[$field]);
$rs = $this->adodbConnection->Execute($sql);
//echo "MAX VALUE: ".$rs->fields['max_value']."<br>";
//echo "MAX SQL: $sql<br>";
$new_val = $rs->fields['max_value'] + 1;
-
+
$sql = "SELECT count($field) AS count FROM ".$this->tablename." WHERE $field = $new_val";
- $rsc = $this->adodbConnection->Execute($sql);
-
+ $rsc = $this->adodbConnection->Execute($sql);
+
while ($rsc->fields['count'] != 0) {
$sql = "SELECT count($field) AS count FROM ".$this->tablename." WHERE $field = $new_val";
- $rsc = $this->adodbConnection->Execute($sql);
+ $rsc = $this->adodbConnection->Execute($sql);
//echo "New Value:$new_val<br>";
if ($rsc->fields['count'] > 0) {
$new_val = $new_val + 0.000001;
}
}
-
+
$sql = "Update ".$this->tablename." set $field=$new_val where ".$this->IdField()."=" . $this->UniqueId();
}
else {
$sql = "Update ".$this->tablename." set $field=$field+1 where ".$this->IdField()."=" . $this->UniqueId();
}
if($this->debuglevel>0)
echo $sql."<br>";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Increment");
return false;
}
-
+
if ($calculate_hot) {
$this->Set($field,$new_val);
}
else {
$this->Set($field, $this->Get($field) + 1);
}
}
function Decrement($field)
- {
+ {
global $Errors;
$sql = "Update ".$this->tablename." set $field=$field-1 where ".$this->IdField()."=" .(int)$this->UniqueId();
if($this->debuglevel>0)
echo $sql;
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Decrement");
return false;
}
$this->Set($field,$this->Get($field)-1);
}
-
+
function GetFieldList($UseLoadedData=FALSE)
{
if(count($this->Data) && $UseLoadedData==TRUE)
{
$res = array_keys($this->Data);
}
else
{
$res = $this->adodbConnection->MetaColumnNames($this->tablename);
}
return $res;
}
-
+
function UsingTempTable()
{
global $objSession;
-
+
$temp = $objSession->GetEditTable($this->tablename);
$p = GetTablePrefix()."ses";
$t = substr($temp,0,strlen($p));
- $ThisTable = substr($this->tablename,0,strlen($p));
+ $ThisTable = substr($this->tablename,0,strlen($p));
if($t==$ThisTable)
{
return TRUE;
}
else
return FALSE;
}
-
+
function LoadFromDatabase($Id, $IdField = null) // custom IdField by Alex
{
global $objSession,$Errors;
-
+
if(!isset($Id))
{
$Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
-
+
// --------- multiple ids allowed: begin -----------------
$id_field = isset($IdField) ? $IdField : $this->IdField();
if( !is_array($id_field) ) $id_field = Array($id_field);
if( !is_array($Id) ) $Id = Array($Id);
-
+
$i = 0; $id_count = count($id_field);
$conditions = Array();
while($i < $id_count)
{
$conditions[] = "(`".$id_field[$i]."` = '".$Id[$i]."')";
$i++;
}
$sql = sprintf($this->SelectSQL, $this->tablename, implode(' AND ', $conditions) );
// --------- multiple ids allowed: end --------------------
- if($this->debuglevel) echo "Load SQL: $sql<br>";
+ if($this->debuglevel) echo "Load SQL: $sql<br>";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if($this->debuglevel) print_pre($data);
if(is_array($data))
$this->SetFromArray($data);
$this->Clean();
return TRUE;
}
-
+
function FieldExists($field)
{
$res = array_key_exists($field,$this->Data);
- return $res;
+ return $res;
}
-
+
function ValueExists($Field,$Value)
{
$sql = "SELECT $Field FROM ".$this->tablename." WHERE $Field='$Value'";
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
return TRUE;
}
else
return FALSE;
}
function FieldMax($Field)
{
$sql = "SELECT Max($Field) as m FROM ".$this->tablename;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields["m"];
}
else
$ret = 0;
}
-
+
function FieldMin($Field)
{
$sql = "SELECT Min($Field) as m FROM ".$this->tablename;
$rs = $this->adodbConnection->Execute($sql);
if($rs && !$rs->EOF)
{
$ret = $rs->fields["m"];
}
else
$ret = 0;
}
-
+
function TableExists($table = null)
{
static $tables_found = Array ();
-
+
if($table == null) $table = $this->tablename;
-
+
if (!isset($tables_found[$table])) {
- // checks if table specified in item exists in db
+ // checks if table specified in item exists in db
$db =& GetADODBConnection();
$sql = "SHOW TABLES LIKE '%s'";
-
+
$rs = $db->Execute( sprintf($sql, $table) );
if ($rs->RecordCount() == 1) {
// table exists in normal case
$tables_found[$table] = 1;
}
else {
// check if table exists in lowercase
$rs = $db->Execute( sprintf($sql, strtolower($table) ) );
$tables_found[$table] = $rs->RecordCount() == 1 ? 1 : 0;
}
}
-
+
return $tables_found[$table];
}
-
+
function raiseEvent($name, $id = null)
{
return true;
-
+
/*if (!getArrayValue($GLOBALS, '_CopyFromEditTable')) {
return true;
}
-
+
if( !isset($id) ) $id = $this->GetID();
$event = new kEvent( Array('name'=>$name,'prefix'=>$this->Prefix,'special'=>$this->Special) );
$event->setEventParam('id', $id);
$this->Application->HandleEvent($event);
return $event->status == erSUCCESS ? true : false;*/
}
-
+
}
?>
Property changes on: branches/unlabeled/unlabeled-1.37.2/kernel/include/itemdb.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.37.2.1
\ No newline at end of property
+1.37.2.2
\ No newline at end of property
Index: tags/release_1_1_8/kernel/include/usersession.php
===================================================================
--- tags/release_1_1_8/kernel/include/usersession.php (revision 8331)
+++ tags/release_1_1_8/kernel/include/usersession.php (revision 8332)
@@ -1,1258 +1,1260 @@
<?php
class clsUserSession
{
//Common DB operation class variables
var $m_dirtyFieldsMap = array();
//Identity
var $m_SessionKey;
var $m_CurrentTempKey;
var $m_PrevTempKey;
//Required attributes
var $m_LastAccessed;
var $m_PortalUserId;
var $m_Language;
var $m_Theme;
var $m_GroupId;
var $adodbConnection;
var $m_Errors;
var $m_GroupList;
var $PermCache;
var $SysPermCache;
var $PermCacheGroups;
var $CurrentUser;
var $UseTempKeys;
var $AdminSearchFields;
function clsUserSession($id=NULL, $TempKeys=FALSE)
{
global $objConfig, $objLanguages, $objThemes, $m_var_list, $FrontEnd;
$this->m_Errors = new clsErrorManager();
$this->adodbConnection = &GetADODBConnection();
$this->PermCache = array();
$this->PermCacheGroups = '';
$this->UseTempKeys = $TempKeys;
$this->AdminSearchFields = array("UserName", "GroupName", "us.IpAddress");
if( GetVar('help_usage') == 'install' ) return;
if(!$this->UseTempKeys || strlen($id)==0)
{
//echo "with cookies";
if( !isset($_SERVER['HTTP_REFERER']) ) $_SERVER['HTTP_REFERER'] = '';
if(!isset($_GET['destform'])) $_GET['destform'] = null;
if(!isset($_GET['continue_sess'])) $_GET['continue_sess'] = null;
// strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path")) || defined(IS_PO...)
// && ( (defined('IS_POPUP') && IS_POPUP) || $_GET['destform'] == 'popup' || $_GET['continue_sess'] == 1)
if( strlen($id) )
{
$this->Set("SessionKey",$id);
return $this->LoadFromDatabase($id);
}
else
{
$this->Set("PortalUserId", 0);
$this->Set("Language", $objLanguages->GetPrimary());
$ThemeId = $m_var_list["theme"];
$this->SetThemeName($ThemeId);
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->Set("GroupList",0);
$this->Set("SessionKey","");
if ($FrontEnd) {
$this->Set("GroupList",$objConfig->Get("User_GuestGroup").','.$objConfig->Get('User_LoggedInGroup') );
}
}
}
else
{
//echo "without cookies";
return $this->LoadFromTempKey($id);
}
}
function AdminSearchWhereClause($SearchList)
{
$sql = "";
if( !is_array($SearchList) ) $SearchList = explode(",",$SearchList);
// remove empty elements
$SearchListTmp=Array();
for($f = 0; $f < count($SearchList); $f++)
if($SearchList[$f])
$SearchListTmp[]=$SearchList[$f];
$SearchList=$SearchListTmp;
if( !count($SearchList) || !count($this->AdminSearchFields) ) return '';
for($f = 0; $f < count($SearchList); $f++)
{
$value = $SearchList[$f];
if( strlen($value) )
{
$inner_sql = "";
for($i = 0; $i < count($this->AdminSearchFields); $i++)
{
$field = $this->AdminSearchFields[$i];
if( strlen( trim($value) ) )
{
if( strlen($inner_sql) ) $inner_sql .= " OR ";
//if (!stristr($value, "Guest")) {
$inner_sql .= $field." LIKE '%".$value."%'";
//}
//else {
// $inner_sql .= $field." IS NULL";
//}
}
}
if( strlen($inner_sql) )
{
$sql .= '('.$inner_sql.') ';
if($f < count($SearchList) - 1) $sql .= " AND ";
}
}
}
return $sql;
}
function CopyToNewSession()
{
$OldKey = $this->GetSessionKey();
$this->GetNewSession();
if($OldKey != $this->GetSessionKey())
{
$this->Set("PortalUserId",$this->Get("PortalUserId"));
$this->Set("GroupId",$this->Get("GroupId"));
$this->Set("GroupList",$this->Get("GroupList"));
$this->Set("Language",$this->Get("Language"));
$this->Set("tz",$this->Get("tz"));
$this->Set("LastAccessed",adodb_date("U"));
$this->Update();
}
}
function Get($name)
{
$var = "m_" . $name;
return isset($this->$var) ? $this->$var : '';
}
function Set($name, $value)
{
if (is_array($name))
{
for ($i=0; $i<sizeof($name); $i++)
{ $var = "m_" . $name[$i];
$this->$var = $value[$i];
$this->m_dirtyFieldsMap[$name[$i]] = $value[$i];
}
}
else
{
$var = "m_" . $name;
$this->$var = $value;
$this->m_dirtyFieldsMap[$name] = $value;
//echo "Set: $var = $value <br>\n";
}
}
function Validate()
{
$dataValid = true;
if(!isset($this->m_LastAccessed))
{
$this->m_Errors->AddError("error.fieldIsRequired",'LastAccessed',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_PortalUserId))
{
$this->m_Errors->AddError("error.fieldIsRequired",'PortalUserId',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_Language))
{
$this->m_Errors->AddError("error.fieldIsRequired",'Language',"","",get_class($this),"Validate");
$dataValid = false;
}
if(!isset($this->m_Theme))
{
$this->m_Errors->AddError("error.fieldIsRequired",'Theme',"","",get_class($this),"Validate");
$dataValid = false;
}
return $dataValid;
}
function Delete()
{
if(!isset($this->m_SessionKey))
{
$this->m_Errors->AddError("error.AppError",NULL,'Internal error: Delete requires set id',"",get_class($this),"Delete");
return false;
}
//Delete associated adata first
$sql = sprintf("DELETE FROM ".GetTablePrefix()."SessionData WHERE SessionKey = '%s'", $this->Get("SessionKey"));
$this->adodbConnection->Execute($sql);
$sql = sprintf("DROP TABLE IF EXISTS %s%s_search",GetTablePrefix(), $this->Get("SessionKey"));
$this->adodbConnection->Execute($sql);
$sql = sprintf("DELETE FROM ".GetTablePrefix()."UserSession WHERE SessionKey = '%s'", $this->Get("SessionKey"));
$this->adodbConnection->Execute($sql);
if ($this->adodbConnection->Execute($sql) === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Delete");
return false;
}
$this->Set("SessionKey","");
$this->Set("SessionDataLoaded",false);
return true;
}
function Update()
{
global $objConfig;
//$this->Set("LastAccessed",adodb_date("U"));
$this->Set("IpAddress",$_SERVER["REMOTE_ADDR"]);
if(!isset($this->m_SessionKey))
{
$this->m_Errors->AddError("error.AppError",NULL,'Internal error: Update requires set id',"",get_class($this),"Update");
return false;
}
if(!is_numeric($this->Get("PortalUserId")))
{
$this->Set("PortalUserId",0);
}
if(!strlen($this->Get("GroupList")))
{
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
}
if(count($this->m_dirtyFieldsMap) == 0)
return true;
$sql = "UPDATE ".GetTablePrefix()."UserSession SET ";
$first = 1;
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s=%s",$sql,$key,$this->adodbConnection->qstr($value));
$first = 0;
}
else
{
$sql = sprintf("%s, %s=%s",$sql,$key,$this->adodbConnection->qstr($value));
}
}
$sql = sprintf("%s WHERE SessionKey = '%s'",$sql, $this->Get("SessionKey"));
//echo $sql;
if ($this->adodbConnection->Execute($sql) === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Update");
return false;
}
return true;
}
function Create()
{
global $objConfig;
$this->Set("LastAccessed", adodb_mktime());
if(!is_numeric($this->Get("PortalUserId")))
{
$this->Set("PortalUserId",0);
}
if(!strlen($this->Get("GroupList")))
{
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
}
$sql = "INSERT INTO ".GetTablePrefix()."UserSession (";
$first = 1;
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s",$sql,$key);
$first = 0;
}
else
{
$sql = sprintf("%s, %s",$sql,$key);
}
}
$sql = sprintf('%s ) VALUES (',$sql);
$first = 1;
foreach ($this->m_dirtyFieldsMap as $key => $value)
{
if($first)
{
$sql = sprintf("%s %s",$sql,$this->adodbConnection->qstr($value));
$first = 0;
}
else
{
$sql = sprintf("%s, %s",$sql,$this->adodbConnection->qstr($value));
}
}
$sql = sprintf('%s)',$sql);
//echo $sql."<br>\n";
if ($this->adodbConnection->Execute($sql) === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Create");
return false;
}
return true;
}
function LoadFromTempKey($id=NULL)
{
global $objLanguages, $objConfig,$m_var_list;
$referer = $_SERVER["HTTP_REFERER"];
//echo "Referer: $referer <br>\n";
if(strlen($referer) && strpos($referer,"env="))
{
$keystart = strpos($referer,"env=")+4;
$referer = substr($referer,$keystart);
$keyend = strpos($referer,"-");
$LastKey = substr($referer,0,$keyend);
if(strlen($LastKey))
{
$sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE (CurrentTempKey = '$id' OR PrevTempKey='$id' OR CurrentTempKey='$LastKey' OR PrevTempKey='$LastKey') ";
}
else
$sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE CurrentTempKey = '$id' AND PrevTempKey IS NULL";
}
else
$sql = "SELECT * FROM ".GetTablePrefix()."UserSession WHERE CurrentTempKey = '$id' AND PrevTempKey IS NULL";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if (is_array($data))
{
foreach($data as $field => $value)
{
$mname = "m_" . $field;
$this->$mname = $data[$field];
}
if($this->Get("CurrentTempKey")) {
$this->Set("PrevTempKey",$this->Get("CurrentTempKey"));
$this->UseTempKeys=TRUE;
}
if (!$this->Get("CurrentTempKey") || !strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'].$objConfig->Get("Site_Path"))) {
//$this->Set("PrevTempKey",$this->Get("CurrentTempKey"));
//$this->Set("CurrentTempKey",$this->GetUniqueKey());
$this->UseTempKeys=FALSE;
$this->Set("PortalUserId", 0);
$this->Set("Language", $objLanguages->GetPrimary());
$ThemeId = $m_var_list["theme"];
$this->SetThemeName($ThemeId);
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->Set("GroupList",0);
$this->Set("SessionKey","");
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
}
//$this->UseTempKeys=TRUE;
$this->Update();
return true;
}
else
{
$this->Set("PortalUserId", 0);
$this->Set("Language", $objLanguages->GetPrimary());
$ThemeId = $m_var_list["theme"];
$this->SetThemeName($ThemeId);
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->Set("GroupList",0);
$this->Set("SessionKey","");
$this->Set("GroupList",$objConfig->Get("User_GuestGroup"));
$this->Set("CurrentTempKey",$this->GetUniqueKey());
return false;
}
}
function LoadFromDatabase($id)
{
if(!isset($id))
{
$this->m_Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
return false;
}
$sql = sprintf("SELECT * FROM ".GetTablePrefix()."UserSession WHERE SessionKey = '%s'",$id);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
return false;
}
$data = $result->fields;
if (is_array($data))
{
foreach($data as $field => $value)
{
$mname = "m_" . $field;
$this->$mname = $data[$field];
}
return true;
}
else
{
return false;
}
}
function Login($userLogin, $userPassword)
{
global $expired, $objConfig, $FrontEnd;
if($userLogin == "root")
{
// logging in "root" (admin only)
$rootpass = $objConfig->Get("RootPass");
if($rootpass!=$userPassword)
{
return false;
}
else
{
if(!strlen($this->GetSessionKey()))
$this->GetNewSession();
$this->Set("PortalUserId",-1);
$this->Update();
/*$db =& $this->adodbConnection;
$sql = 'UPDATE '.GetTablePrefix().'Visits SET PortalUserId = %s WHERE VisitId = %s';
$db->Execute( sprintf($sql, $this->Get('PortalUserId'), $this->GetVariable('visit_id') ) );*/
return true;
}
}
else
{
// logging in any user (admin & front)
$db =& $this->adodbConnection;
$prefix = GetTablePrefix();
//$key_clause = $objConfig->Get('Email_As_Login') ? 'pu.Email = %1$s' : 'pu.Login = %1$s';
$key_clause = 'pu.Email = %1$s OR pu.Login = %1$s';
$sql = 'SELECT *, MD5(pu.Password) AS md5pw
FROM '.$prefix.'PortalUser pu
LEFT JOIN '.$prefix.'UserGroup ug USING (PortalUserId)
LEFT JOIN '.$prefix.'PortalGroup pg ON ug.GroupId = pg.GroupId
WHERE ('.$key_clause.') AND (pu.Status = 1) AND (pu.Password = %2$s OR MD5(pu.Password) = %2$s OR pu.Password = MD5(%2$s) ) AND
( (ug.MembershipExpires IS NULL) OR ( ug.MembershipExpires >= UNIX_TIMESTAMP() ) )
ORDER BY ug.PrimaryGroup DESC, pg.Personal DESC';
$result = $db->Execute( sprintf($sql, $db->qstr($userLogin), $db->qstr($userPassword) ) );
if($result === false)
{
$this->m_Errors->AddError('error.DatabaseError',NULL,$this->adodbConnection->ErrorMsg(),'',get_class($this),'Login');
return false;
}
if($result->EOF) return -1; // no any user with username & pass specified
}
if( !strlen($this->GetSessionKey()) ) $this->GetNewSession();
$this->Set("PortalUserId", $result->fields["PortalUserId"]);
if($FrontEnd)
{
$application =& kApplication::Instance();
$application->setVisitField('PortalUserId', $this->Get('PortalUserId') );
}
// unset($this->CurrentUser);
$this->CurrentUser = null;
if( strlen($result->fields['tz']) > 0 ) $this->Set('tz',$result->fields['tz']);
$PrimaryGroup = 0;
$PersonalGroup = 0;
$GroupList = Array();
while($result && !$result->EOF)
{
$skipadd=0;
$g = $result->fields["GroupId"];
if($result->fields["PrimaryGroup"]==1)
{
$PrimaryGroup = $g;
$skipadd=1;
}
if($result->fields["Personal"]==1)
{
$PersonalGroup=$g;
$skipadd=0;
}
if(!$skipadd)
$GroupList[] = $g;
$result->MoveNext();
}
if($PrimaryGroup) array_unshift($GroupList, $PrimaryGroup);
if ($FrontEnd) array_push($GroupList, $objConfig->Get('User_LoggedInGroup') );
$extra_groups = implode(',', $GroupList);
$this->SetVariable('UserGroups', $extra_groups);
$this->Set('GroupId', $PersonalGroup ? $PersonalGroup : $PrimaryGroup);
$this->Set('GroupList', $extra_groups);
$this->SetVariable('UserGroups', $this->Get('GroupList') );
if( class_exists('kApplication') )
{
$app = kApplication::Instance();
$kSession = $app->recallObject('Session');
$kSession->SetField('GroupList', $extra_groups);
$app->StoreVar('UserGroups', $this->Get('GroupList') );
$app->setVisitField('PortalUserId', $this->Get('PortalUserId') );
}
$this->Set('LastAccessed', adodb_date('U') );
$this_login = $this->GetPersistantVariable("ThisLogin");
$this->SetPersistantVariable("LastLogin", $this_login);
$this->SetPersistantVariable("ThisLogin", adodb_mktime());
$this->ResetSysPermCache();
$this->PermCache = array();
$this->Update();
if($userLogin != 'root' && $FrontEnd)
{
if( ! $this->HasSystemPermission('LOGIN') )
{
$this->Logout();
return -2; // no perm login
}
}
return true; // login ok
}
function Logout()
{
global $objConfig, $FrontEnd;
$this->Set("PortalUserId", 0); // not logged-in
$this->Set('LastAccessed',0); // session become expired
$this->Set("GroupId", $objConfig->Get("User_GuestGroup"));
#$this->SetPersistantVariable("LastLogin", adodb_mktime());
$group_list = $FrontEnd ? $objConfig->Get('User_GuestGroup').','.$objConfig->Get('User_LoggedInGroup') : '';
$this->Set("GroupList", $group_list);
$this->SetVariable('UserGroups', $group_list );
if( class_exists('kApplication') )
{
$app = kApplication::Instance();
$kSession = $app->recallObject('Session');
$kSession->SetField('GroupList', $group_list);
$app->StoreVar('UserGroups', $group_list );
}
$this->Set("IpAddress",$_SERVER['REMOTE_ADDR']);
$this->DeleteSessionData($this->GetSessionKey());
$this->Update();
//$this->Delete();
$this->ResetSysPermCache();
$this->PermCache = array();
if($FrontEnd && class_exists('kApplication') )
{
$app =& kApplication::Instance();
$app->Redirect();
}
}
function SetVariable($variableName, $variableValue)
{
global $objConfig, $FrontEnd;
$objConfig->Set($variableName,$variableValue,2);
$variableValue = addslashes($variableValue);
//if(!(int)$FrontEnd==1)
//{
$db =& $this->adodbConnection;
$sessionkey = $this->GetSessionKey();
$sql = 'REPLACE INTO '.GetTablePrefix().'SessionData (SessionKey,VariableName,VariableValue) VALUES (%s,%s,%s)';
$db->Execute( sprintf($sql, $db->qstr($sessionkey), $db->qstr($variableName), $db->qstr($variableValue) ) );
if( class_exists('kApplication') )
{
// echo 'var stored ['.$variableName.'] = ['.$variableValue.']<br>';
$application =& kApplication::Instance();
$application->StoreVar($variableName, $variableValue);
}
// echo "<BR>UPDATE: $sql<BR>";
//}
}
function SetPersistantVariable($variableName, $variableValue)
{
global $objConfig, $objUsers;
$userid = (int)$this->Get("PortalUserId");
if($userid > 0)
{
if(!is_object($this->CurrentUser))
{
$this->CurrentUser = $objUsers->GetItem($userid);
}
if(!$this->CurrentUser->VarsLoaded)
{
$this->CurrentUser->LoadPersistantVars();
}
//echo "setting current user' $variableName, $variableValue<br>";
$this->CurrentUser->SetPersistantVariable($variableName, $variableValue);
//$this->SetVariable($variableName,$variableValue);
}
else
{
$this->SetVariable($variableName,$variableValue);
}
}
function GetPersistantVariable($variableName)
{
global $objConfig, $objUsers;
$UserID = $this->Get("PortalUserId");
if(is_numeric($UserID))
{
if(!is_object($this->CurrentUser))
{
$this->CurrentUser = $objUsers->GetItem($UserID);
}
if(!$this->CurrentUser->VarsLoaded)
{
$this->CurrentUser->LoadPersistantVars();
}
$val = $this->CurrentUser->GetPersistantVariable($variableName);
//echo "Persistant Val for $variableName: $val<br>";
}
if(!strlen($val))
$val = $objConfig->Get($variableName);
return $val;
}
function GetVariable($variableName)
{
global $objConfig;
return $objConfig->Get($variableName);
}
function LoadSessionData()
{
global $objConfig, $objUsers;
if(is_numeric($this->Get("PortalUserId")))
{
$sql = "SELECT VariableName, VariableValue FROM ".GetTablePrefix()."SessionData where SessionKey='" . $this->Get("SessionKey") . "'";
//echo $sql."<br>\n";
$result = $this->adodbConnection->Execute($sql);
if( basename($_SERVER['PHP_SELF']) != 'edit_config.php' )
{
while ($result && !$result->EOF)
{
$data = $result->fields;
//echo "<PRE>"; print_r($data); echo "</PRE>";
$objConfig->Set($data["VariableName"],$data["VariableValue"],FALSE);
$result->MoveNext();
}
}
if(!is_object($this->CurrentUser))
{
$this->CurrentUser = $objUsers->GetItem($this->Get("PortalUserId"));
}
if(!$this->CurrentUser->VarsLoaded)
{
$this->CurrentUser->LoadPersistantVars();
}
}
if((int)$this->GetPersistantVariable("Language"))
$this->Set("Language",$objConfig->Get("Language"));
$this->DeleteExpiredSessions();
return true;
}
function DeleteSessionData($key)
{
$sql = "DELETE FROM ".GetTablePrefix()."SessionData WHERE SessionKey='$key'";
$this->adodbConnection->Execute($sql);
}
function SaveSessionData()
{
global $objConfig;
//echo "Saving Session Data..<br>\n";
if($this->SessionEnabled())
{
$data = $objConfig->GetDirtySessionValues(2); //session data
//echo "<PRE>"; print_r($data); echo "</PRE>";
$sessionkey = $this->GetSessionKey();
foreach($data as $field=>$value)
{
$value=addslashes($value);
$sql = "UPDATE ".GetTablePrefix()."SessionData SET VariableValue='$value' WHERE VariableName='$field' AND SessionKey='$sessionkey'";
$this->adodbConnection->Execute($sql);
//echo $sql."<br>\n";
if($this->adodbConnection->Affected_Rows()==0)
{
$sql = "INSERT INTO ".GetTablePrefix()."SessionData (VariableName,VariableValue,SessionKey) VALUES ('$field','$value','$sessionkey')";
$this->adodbConnection->Execute($sql);
}
// echo $sql."<br>\n";
}
}
}
function DeleteEditTables()
{
$tables = $this->adodbConnection->MetaTables();
$mask = '/'.GetTablePrefix().'ses_(.*)_edit_(.*)/';
$sql='SELECT COUNT(*) FROM '.GetTablePrefix().'UserSession WHERE SessionKey = \'%s\'';
foreach($tables as $table)
{
if( preg_match($mask,$table,$rets) )
{
$sid=$rets[1];
$is_alive = $this->adodbConnection->GetOne( sprintf($sql,$sid) );
if(!$is_alive) @$this->adodbConnection->Execute('DROP TABLE IF EXISTS '.$table);
}
}
}
function DeleteExpiredSessions()
{
global $objConfig;
$cutoff = adodb_mktime()-$objConfig->Get("SessionTimeout");
$thiskey = $this->GetSessionKey();
$sql = "SELECT SessionKey from ".GetTablePrefix()."UserSession WHERE LastAccessed<$cutoff AND SessionKey != '$thiskey'";
$result = $this->adodbConnection->Execute($sql);
$keys = array();
while ($result && !$result->EOF)
{
$keys[] = "SessionKey='" . $result->fields["SessionKey"] . "'";
$result->MoveNext();
}
if(count($keys)>0)
{
$keywhere = implode(" OR ", $keys);
$sql = "DELETE FROM ".GetTablePrefix()."SessionData WHERE $keywhere";
//echo $sql;
$this->adodbConnection->Execute($sql);
$this->adodbConnection->Execute("DELETE FROM ".GetTablePrefix()."UserSession WHERE LastAccessed<$cutoff");
$this->DeleteEditTables();
}
}
function SetSysPermCache()
{
unset($this->SysPermCache);
$GroupList = $this->Get('GroupList');
if ($GroupList && $GroupList != '0') {
$this->SysPermCache = Array();
$sql = 'SELECT *
FROM '.GetTablePrefix().'Permissions
WHERE Type = 1 AND GroupId IN ('.$GroupList.')'; // AND PermissionValue = 1';
$rs = $this->adodbConnection->Execute($sql);
$PermList = Array();
while (!$rs->EOF) {
$this->SysPermCache[ $rs->fields['Permission'] ] = $rs->fields['PermissionValue'];
$PermList[] = $rs->fields['Permission'];
$rs->MoveNext();
}
if ($PermList) {
$this->SetVariable('SysPerm', implode(',', $PermList));
}
}
}
/**
* Fills system permission cache in session (memory only, not db)
*
*/
function GetSysPermCache()
{
$perms = trim($this->GetVariable('SysPerm'));
if (!$perms) {
$this->SetSysPermCache();
}
else {
$p = explode(',', $perms);
$this->SysPermCache = Array();
for($i = 0; $i < count($p); $i++)
{
$n = $p[$i];
$this->SysPermCache[$n] = 1;
}
}
}
/**
* Allows to detect if system permissions are loaded
*
* @return bool
*/
function SysPermCacheLoaded()
{
return isset($this->SysPermCache);
}
/**
* Resets system permission cache
*
*/
function ResetSysPermCache()
{
$this->SetVariable('SysPerm', '');
unset($this->SysPermCache);
}
function HasSystemPermission($PermissionName)
{
global $objGroups;
// "root" is always allowed to login to admin
if ($this->Get('PortalUserId') == -1 && ($PermissionName == 'ADMIN' || $PermissionName == 'LOGIN') ) {
return true;
}
// cut last comma (just in case in-portal made a mistake before)
$GroupList = $this->Get('GroupList');
if (substr($GroupList, -1) == ',') {
$GroupList = substr($GroupList, 0, -1);
$this->Set('GroupList', $GroupList);
}
// if loaded permissions are from other group list, then current (e.g. user is become logged-in during script run)
if ($this->Get('GroupList') != $this->PermCacheGroups) {
$this->ResetSysPermCache();
}
// load system permission cache if not already loaded
if (!$this->SysPermCacheLoaded()) {
$this->GetSysPermCache();
$this->PermCacheGroups = $this->Get('GroupList');
}
//echo "SysPerm $PermissionName: [". $this->SysPermCache[$PermissionName]."]<br>\n";
return isset($this->SysPermCache[$PermissionName]) ? $this->SysPermCache[$PermissionName] == 1 : false;
}
function HasCatPermission($PermissionName,$CatId=NULL)
{
global $objCatList, $objUsers;
$PermSet =FALSE;
$Value = 0;
if($this->Get("PortalUserId")==-1)
return TRUE;
if(!strlen($PermissionName))
return FALSE;
$GroupList = $this->Get("GroupList");
if(substr($GroupList,-1)==",")
{
$GroupList = substr($GroupList,0,-1);
$this->Set("GroupList",$GroupList);
}
if(!strlen($this->Get("SessionKey")))
$this->Set("GroupId",0);
if(strlen(trim($GroupList)))
{
if(strlen($this->Get("GroupId")))
{
$GroupList = $this->Get("GroupId").",".$GroupList;
}
}
else
{
$GroupList = $this->Get("GroupId");
}
if($CatId == NULL)
{
$CatId = $objCatList->CurrentCategoryID();
}
$Cat = &$objCatList->GetCategory($CatId);
$Value="";
for($p=0;$p<count($this->PermCache);$p++)
{
$pItem = $this->PermCache[$p];
if($pItem["perm"]==$PermissionName && $pItem["cat"]==$CatId)
{
$Value=$pItem["value"];
break;
}
}
if(is_object($Cat) && !is_numeric($Value))
{
$Value = 0;
$CatList = $Cat->Get("ParentPath");
$CatList = substr($CatList,1,-1);
$CatList = str_replace("|",",",$CatList);
if(strlen($CatList))
{
$CatList ="0,".$CatList;
}
else
$CatList = "0";
$sql = "SELECT * FROM ".GetTablePrefix()."Permissions WHERE Permission LIKE '$PermissionName' AND CatId IN ($CatList) AND GroupId IN ($GroupList)";
// echo $sql."<br>\n";
$rs = $this->adodbConnection->Execute($sql);
$PermValue = array();
while($rs && !$rs->EOF)
{
$index = $rs->fields["CatId"];
if(!is_numeric($PermValue[$index]))
$PermValue[$index] = $rs->fields["PermissionValue"];
$rs->MoveNext();
}
$cats = array_reverse(explode(",",$CatList));
for($c=0;$c<count($cats);$c++)
{
$index = $cats[$c];
if( isset($PermValue[$index]) && is_numeric($PermValue[$index]) )
{
$Value = $PermValue[$index];
break;
}
}
$perm = array();
$perm["perm"] = $PermissionName;
$perm["cat"] = $CatId;
$perm["value"] = $Value;
array_push($this->PermCache, $perm);
}
//echo $GroupList." Has Permission $PermissionName = $Value<br>\n";
return $Value;
}
function HasCatPermInList($PermList,$CatId=NULL, $System=FALSE)
{
$value = 0;
if(strlen($PermList))
{
$plist = explode(",",$PermList);
$value=0;
for($p=0;$p<count($plist);$p++)
{
if($this->HasCatPermission($plist[$p]))
{
$value = 1;
break;
}
else
{
if($System)
{
if($this->HasSystemPermission($plist[$p]))
{
$value = 1;
break;
}
}
}
}
}
return $value;
}
function GetACLClause()
{
$GroupList = $this->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];
- if(strlen($g)>0)
- $acl_where[] = "(FIND_IN_SET($g,acl) OR ((NOT FIND_IN_SET($g,dacl)) AND acl='')) ";
+ if(strlen($g)>0) {
+// $acl_where[] = "(FIND_IN_SET($g,acl) OR ((NOT FIND_IN_SET($g,dacl)) AND acl='')) ";
+ $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))";
return $acl_where;
}
function GetEditTable($base_table)
{
$prefix = GetTablePrefix();
if(strlen($prefix))
{
if(substr($base_table,0,strlen($prefix))!=$prefix)
$base_table = $prefix.$base_table;
}
$table = $prefix."ses_".$this->GetSessionKey()."_edit_".$base_table;
//echo "Table: $table <br>\n";
return $table;
}
function GetSessionTable($base_table,$name)
{
$prefix = GetTablePrefix();
if(strlen($prefix))
{
if(substr($base_table,0,strlen($prefix))!=$prefix)
$base_table = $prefix.$base_table;
}
$table = $prefix."ses_".$this->GetSessionKey()."_".$name.$base_table;
//echo "Table: $table <br>\n";
return $table;
}
function GetSearchTable($base_table="")
{
$prefix = GetTablePrefix();
if(strlen($base_table))
{
if(strlen($prefix))
{
if(substr($base_table,0,strlen($prefix))!=$prefix)
$base_table = $prefix.$base_table;
}
$table = $prefix."ses_".$this->GetSessionKey()."_search_".$base_table;
}
else
$table = $this->GetSessionTable('Search',''); //$prefix."ses_".$this->GetSessionKey()."_search";
return $table;
}
function GetTotalSessions()
{
# $time = adodb_mktime() - 900;
$sql = "SELECT count(*) as SesCount FROM ".GetTablePrefix()."UserSession";
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"GetTotalSessions");
return false;
}
return $result->fields["SesCount"];
}
function Query_UserSession($whereClause,$orderByClause)
{
$resultSet = array();
$sql = "SELECT ".GetTablePrefix()."* FROM ".GetTablePrefix()."UserSession ";
if(isset($whereClause))
$sql = sprintf('%s WHERE %s',$sql,$whereClause);
if(isset($orderByClause))
$sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
$result = $this->adodbConnection->Execute($sql);
if ($result === false)
{
$this->m_Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_UserSession");
return false;
}
while (!$result->EOF)
{
$item = new clsUserSession(NULL);
$item->Set("SessionKey",$result->fields["SessionKey"]);
$item->Set("LastAccessed", $result->fields["LastAccessed"]);
$item->Set("PortalUserId", $result->fields["PortalUserId"]);
$item->Set("Language", $result->fields["Language"]);
$item->Set("Theme" , $result->fields["Theme"]);
array_push($resultSet,$item);
$result->MoveNext();
}
return $resultSet;
}
function GetUniqueKey()
{
while(true)
{
/* create the new session key here */
mt_srand(100000000*(double)microtime());
$sessionId=strtoupper(sprintf("AD%xFD",mt_rand(100000000,999999999))); //9 digit hex session id
$query = "select SessionKey from ".GetTablePrefix()."UserSession ";
$query .= "where SessionKey='$sessionId' OR CurrentTempKey='$sessionId' OR PrevTempKey='$sessionId'";
$rs = $this->adodbConnection->Execute($query);
if($rs->EOF)
break;
if($i>100)
{
return "";
}
$i++;
}
//echo "Getting Unique Key: $sessionId<br>";
return $sessionId;
}
function GetNewSession()
{
global $sessionId, $objConfig, $objLanguages, $m_var_list, $FrontEnd;
$i=0;
if($this->Get("PortalUserId")>0 || $objConfig->Get("GuestSessions")==1)
{
//echo "Creating Session<br>\n";
$sessionId = $this->GetUniqueKey();
$this->Set("SessionKey", $sessionId);
$this->Set("CurrentTempKey",$sessionId);
if($m_var_list["lang"])
{
$this->Set("Language",$m_var_list["lang"]);
}
else
$this->Set("Language", $objLanguages->GetPrimary());
$this->SetThemeName();
//$this->Set("Theme", $objConfig->Get("Default_Theme"));
$this->UpdateAccessTime();
$this->Set("IpAddress", $_SERVER['REMOTE_ADDR'] );
$this->Create();
if($FrontEnd)
{
$application =& kApplication::Instance();
$application->HandleEvent( new kEvent('visits:OnRegisterVisit') );
}
}
else
$this->Set("SessionKey","");
}
function SessionEnabled()
{
$res = FALSE;
$key = $this->GetSessionKey();
if(strlen($key)>0)
$res = TRUE;
return $res;
}
function GetSessionKey()
{
return $this->Get("SessionKey");
}
function SetThemeName($id=0)
{
global $objThemes;
if($id==0)
$id = $objThemes->GetPrimaryTheme();
$Theme = $objThemes->GetItem($id);
$name = $Theme->Get("Name");
$this->Set("Theme",$name);
//$this->Update();
}
function ValidSession($SessionKey=NULL)
{
global $objConfig;
$a = $this->Get("LastAccessed");
$cutoff = adodb_mktime()-$objConfig->Get("SessionTimeout");
//echo $a." ".$cutoff."<br>";
//$ip = ($_SERVER['REMOTE_ADDR'] == $this->Get("IpAddress"));
//echo $this->Get("IpAddress");
//$ip = TRUE;
if ($a < $cutoff) {
//$this->UpdateAccessTime();
}
return ($a >= $cutoff);
}
function UpdateAccessTime()
{
$this->Set("LastAccessed", adodb_mktime() );
}
function InSpamControl($ResourceId,$DataType=NULL)
{
static $ClearStat;
if(!$ClearStat)
$this->PurgeSpamControl();
$ClearStat=1;
if(strlen($DataType))
$DataType="'".$DataType."'";
$sql = "SELECT count(*) as SpamCount FROM ".GetTablePrefix()."SpamControl WHERE ItemResourceId=$ResourceId AND DataType=$DataType";
if($this->Get("PortalUserId")==0)
{
$sql .= " AND PortalUserId=0 AND IPaddress='".$_SERVER["REMOTE_ADDR"]."'";
}
else
{
$sql .= " AND PortalUserId=".$this->Get("PortalUserId");
}
$rs = $this->adodbConnection->Execute($sql);
$value = (int)$rs->fields["SpamCount"];
if($value>0)
{
return TRUE;
}
else
return FALSE;
}
function AddToSpamControl($ResourceId,$secstoexpire,$DataType=NULL)
{
$expire = adodb_date("U") + $secstoexpire;
if(strlen($DataType))
$DataType = "'".$DataType."'";
$sql = "INSERT INTO ".GetTablePrefix()."SpamControl (ItemResourceId,IPaddress,Expire,PortalUserId,DataType) VALUES (";
$sql .= $ResourceId.",'".$_SERVER["REMOTE_ADDR"]."',$expire,".$this->Get("PortalUserId").",$DataType)";
//echo $sql;
$this->adodbConnection->Execute($sql);
}
function PurgeSpamControl()
{
$sql = "DELETE FROM ".GetTablePrefix()."SpamControl WHERE Expire<".adodb_date("U");
$this->adodbConnection->Execute($sql);
}
}/* clsUserSession */
?>
Property changes on: tags/release_1_1_8/kernel/include/usersession.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.48.4.2
\ No newline at end of property
+1.48.4.3
\ No newline at end of property

Event Timeline