Index: trunk/kernel/include/config.php =================================================================== diff -u -N -r636 -r642 --- trunk/kernel/include/config.php (.../config.php) (revision 636) +++ trunk/kernel/include/config.php (.../config.php) (revision 642) @@ -1,514 +1,515 @@ -m_IsDirty=false; - $this->adodbConnection = &GetADODBConnection(); - $this->config = array(); - $this->m_IsDefault = array(); - $this->VarType = array(); - } - - function SetDebugLevel($value) - { - } - - - function Load() - { - if(is_object($this->adodbConnection)) - { - LogEntry("Config Load Start\n"); - $sql = "select VariableName, VariableValue from ".GetTablePrefix()."ConfigurationValues"; - $rs = $this->adodbConnection->Execute($sql); - unset($this->config); - #this->config=array(); - $count=0; - while($rs && !$rs->EOF) - { - $this->config[$rs->fields["VariableName"]] = $rs->fields["VariableValue"]; - $this->m_VarType[$rs->fields["VariableName"]] = 0; - // $this->Set($rs->fields["VariableName"],$rs->fields["VariableValue"],0); - if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 ) - { - adodb_movenext($rs); - } - else - $rs->MoveNext(); - $count++; - } - LogEntry("Config Load End - $count Variables\n"); - } - unset($this->m_DirtyFields); - $this->m_IsDirty=false; - } - - function Get($property) - { - return isset($this->config[$property]) ? $this->config[$property] : ''; - } - - function Set($property, $value,$type=0,$force=FALSE) - { - if(is_array($this->config) && strlen($property)>0) - { - if(array_key_exists($property,$this->config)) - { - $current = $this->config[$property]; - $changed = ($current != $value); - } - else - $changed = true; - } - else - $changed = false; - $this->config[$property]=$value; - $this->m_IsDirty = ($this->m_IsDirty or $changed or $force); - if($changed || $force) - { - $this->m_DirtyFields[$property] = $value; - } - $this->m_VarType[$property] = $type; - } - - function Save() - { - if($this->m_IsDirty==TRUE) - { - foreach($this->m_DirtyFields as $field=>$value) - { - if($this->m_VarType[$field]==0) - { - $sql = sprintf("UPDATE ".GetTablePrefix()."ConfigurationValues SET VariableValue=%s WHERE VariableName=%s", $this->adodbConnection->qstr($value), $this->adodbConnection->qstr($field)); - // echo $sql."
\n"; - - $rs = $this->adodbConnection->execute($sql); - } - } - } - $this->m_IsDirty=FALSE; - unset($this->m_DirtyFields); - } - - function TimeFormat() - { - if($this->Get("ampm_time")=="1") - { - $format = "g:i:s A"; - } - else - $format = "H:i:s"; - return $format; - } - - /* vartype should be either 1 or 2, 1 = perstant data, 2 = session data */ - function GetDirtySessionValues($VarType) - { - $result = array(); - - if(is_array($this->m_DirtyFields)) - { - foreach($this->m_DirtyFields as $property=>$values) - { - if($this->m_VarType[$property]==$VarType) - $result[$property] = $values; - } - } - return $result; - } - - function GetConfigValues($postfix = '') - { - // return only varibles, that match specified criteria - if(!$postfix) return $this->config; - $result = Array(); - $postfix_len = $postfix ? strlen($postfix) : 0; - foreach($this->config as $config_var => $var_value) - { - if( substr($config_var, - $postfix_len) == $postfix ) - $result[$config_var] = $var_value; - } - return $result; - } -}/* clsConfig */ - -/* -To create the configuration forms in the admin section, populate the table ConfigurationAdmin and -ConfigurationValues. - - The tables are fairly straight-forward. The fields of concern in the ConfigurationValues table is -ModuleOwner and Section. ModuleOwner should either be the module name or In-Portal for kernel related stuff. -(Items which should appear under 'System Configuration'). - - The Section field determines the NavMenu section the value is associated with. For example, -in-portal:configure_general refers to items listed under System Configuration->General. - - In the ConfigurationAdmin table, ensure the VariableName field is the same as the one in ConfigurationValues -(this is the field that creates the natural join.) The prompt field is the text displayed to the left of the form element -in the table. This should contain LANGUAGE ELEMENT IDENTIFIERS that are plugged into the Language function. - - The element_type field describes the type of form element is associated with this item. Possible values are: - - text : textbox - - checkbox : a simple checkbox - - select : creates a dropdown box. In this case, the ValueList field should be populated with a comma-separated list - in name=value,name=value format (each element is translated to: - - - To add dynamic data to this list, enclose an SQL statement with tags for example: - SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE .CustomFieldType=3> - - note the specific field labels OptionName and OptionValue. They are required by the parser. - use the tag to insert the system's table prefix into the sql statement as appropriate - -*/ -class clsConfigAdminItem -{ - var $name; - var $heading; - var $prompt; - var $ElementType; - var $ValueList; /* comma-separated list in name=value pair format*/ - var $ValidationRules; - var $default_value; - var $adodbConnection; - var $NextItem=NULL; - var $Section; - - function clsConfigAdminItem($config_name=NULL) - { - $this->adodbConnection = &GetADODBConnection(); - if($config_name) - $this->LoadSetting($config_name); - } - - function LoadSetting($config_name) - { - $sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName) WHERE ".GetTablePrefix()."ConfigurationAdmin.VariableName='".$config_name."'"; - $rs = $this->adodbConnection->Execute($sql); - if($rs && !$rs->EOF) - { - $this->name = $rs->fields["VariableName"]; - $this->heading = $rs->fields["heading"]; - $this->prompt = $rs->fields["prompt"]; - $this->ElementType = $rs->fields["element_type"]; - $this->ValidationRules=$rs->fields["validation"]; - $this->default_value = $rs->fields["VariableValue"]; - $this->ValueList=$rs->fields["ValueList"]; - $this->Section = $rs->fields["Section"]; - } - } - - function explode_sql($sql) - { - $s = ""; - - $rs = $this->adodbConnection->Execute($sql); - - while ($rs && !$rs->EOF) - { - if(strlen(trim($rs->fields["OptionName"]))>0 && strlen(trim($rs->fields["OptionValue"]))>0) - { - if(strlen($s)) - $s .= ","; - $s .= $rs->fields["OptionName"]."="."+".$rs->fields["OptionValue"]; - } - $rs->MoveNext(); - } - return $s; - } - - function replace_sql($string) - { - $string = str_replace("",GetTablePrefix(),$string); - - $start = strpos($string,""); - - while($start) - { - $end = strpos($string,""); - if(!$end) - { - $end = strlen($string); - } - $len = $end - $start; - $sql = substr($string,$start+5,$len-5); - - $sql_val = $this->explode_sql($sql); - $s = substr($string,0,$start) . $sql_val . substr($string,$end+5); - - $string = $s; - $start = strpos($string,""); - } - return $string; - } - - function ItemFormElement($StartFrom=1) - { - global $objConfig; - static $TabIndex; - - if (empty($TabIndex)) - $TabIndex = $StartFrom; - - $o = ""; - if($objConfig->Get($this->name)!="") - $this->default_value = stripslashes($objConfig->Get($this->name)); - - switch($this->ElementType) - { - case "text": - $o .= "name."\" "; - $o .= "VALUE=\"".$this->default_value."\">"; - break; - case "checkbox": - $o .= "name."\" tabindex=\"".($TabIndex++)."\""; - if($this->default_value) - { - $o .= " CHECKED>"; - } - else - $o .= ">"; - - break; - case "password": - - /* To exclude config form from populating with Root (md5) password */ - if ($this->Section == "in-portal:configure_users") - $this->default_value = ""; - - $o .= "name."\" "; - $o .= "VALUE=\"".$this->default_value."\">"; - break; - case "textarea": - $o .= ""; - break; - case "label": - if($this->default_value) - { - $o .= $this->default_value; - } - break; - case "radio": - $radioname = $this->name; - - $ValList = $this->replace_sql($this->ValueList); - - $TabIndex++; - $localTabIndex = $TabIndex; - $TabIndex++; - - $val = explode(",",$ValList); - for($i=0;$i<=count($val);$i++) - { - if(strlen($val[$i])) - { - $parts = explode("=",$val[$i]); - $s = $parts[1]; - if(strlen($s)==0) - $s=""; - - $o .= "name."\" VALUE=\"".$parts[0]."\""; - if($this->default_value==$parts[0]) - { - $o .= " CHECKED>"; - } - else - $o .= ">"; - if(substr($s,0,1)=="+") - { - $o .= $s; - } - else - $o .= prompt_language($s); - } - } - - break; - case "select": - $o .= ""; - } - return $o; - } - - function GetPrompt() - { - $ret = prompt_language($this->prompt); - return $ret; - } -} - -class clsConfigAdmin -{ - var $module; - var $section; - var $Items; - - function clsConfigAdmin($module="",$section="",$Inst=FALSE) - { - $this->module = $module; - $this->section = $section; - $this->Items= array(); - if(strlen($module) && strlen($section)) - $this->LoadItems(TRUE,$Inst); - } - - function Clear() - { - unset($this->Items); - $this->Items = array(); - } - - function NumItems() - { - if(is_array($this->Items)) - { - return count($this->Items); - } - else - return 0; - } - - function LoadItems($CheckNextItems=TRUE, $inst=FALSE) - { - $this->Clear(); - if(!$inst) - { - $sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName) - WHERE ModuleOwner='".$this->module."' AND Section='".$this->section."' ORDER BY DisplayOrder ASC"; - } - else - { - - $sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName) - WHERE ModuleOwner='".$this->module."' AND Section='".$this->section."' AND Install=1 ORDER BY DisplayOrder ASC"; - } - if( $GLOBALS['debuglevel'] ) echo $sql."
\n"; - $adodbConnection = &GetADODBConnection(); - $rs = $adodbConnection->Execute($sql); - while($rs && !$rs->EOF) - { - $data = $rs->fields; - if(is_object($i) && $CheckNextItems) - { - $last = $i->prompt; - unset($i); - } - $i = new clsConfigAdminItem(NULL); - $i->name = $data["VariableName"]; - $i->default_value = $data["VariableValue"]; - $i->heading = $data["heading"]; - $i->prompt = $data["prompt"]; - $i->ElementType = $data["element_type"]; - $i->ValueList = $data["ValueList"]; - $i->ValidationRules = isset($data['validaton']) ? $data['validaton'] : ''; - $i->Section = $data["Section"]; - - if(strlen($last)>0) - { - if($i->prompt==$last) - { - $this->Items[count($this->Items)-1]->NextItem=$i; - } - else - { - $i->NextItem=NULL; - array_push($this->Items,$i); - } - } - else - { - $i->NextItem=NULL; - array_push($this->Items,$i); - } - //unset($i); - $rs->MoveNext(); - } - } - - function SaveItems($POSTVARS, $force=FALSE) - { - global $objConfig; - - foreach($this->Items as $i) - { - if($i->ElementType != "label") - { - if($i->ElementType != "checkbox") - { - $objConfig->Set($i->name,$POSTVARS[$i->name]); - } - else - { - if($POSTVARS[$i->name]=="on") - { - $value=1; - } - else - $value = (int)$POSTVARS[$i->name]; - $objConfig->Set($i->name,$value,0,$force); - } - } - } - $objConfig->Save(); - } - - function GetHeadingList() - { - $res = array(); - foreach($this->Items as $i) - { - $res[$i->heading]=1; - } - reset($res); - return array_keys($res); - } - - function GetHeadingItems($heading) - { - $res = array(); - foreach($this->Items as $i) - { - if($i->heading==$heading) - array_push($res,$i); - } - return $res; - } -} - - -?> +m_IsDirty=false; + $this->adodbConnection = &GetADODBConnection(); + $this->config = array(); + $this->m_IsDefault = array(); + $this->VarType = array(); + } + + function SetDebugLevel($value) + { + } + + + function Load() + { + if(is_object($this->adodbConnection)) + { + LogEntry("Config Load Start\n"); + $sql = "select VariableName, VariableValue from ".GetTablePrefix()."ConfigurationValues"; + $rs = $this->adodbConnection->Execute($sql); + unset($this->config); + #this->config=array(); + $count=0; + while($rs && !$rs->EOF) + { + $this->config[$rs->fields["VariableName"]] = $rs->fields["VariableValue"]; + $this->m_VarType[$rs->fields["VariableName"]] = 0; + // $this->Set($rs->fields["VariableName"],$rs->fields["VariableValue"],0); + if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 ) + { + adodb_movenext($rs); + } + else + $rs->MoveNext(); + $count++; + } + LogEntry("Config Load End - $count Variables\n"); + } + unset($this->m_DirtyFields); + $this->m_IsDirty=false; + } + + function Get($property) + { + return isset($this->config[$property]) ? $this->config[$property] : ''; + } + + function Set($property, $value,$type=0,$force=FALSE) + { + if(is_array($this->config) && strlen($property)>0) + { + if(array_key_exists($property,$this->config)) + { + $current = $this->config[$property]; + $changed = ($current != $value); + } + else + $changed = true; + } + else + $changed = false; + $this->config[$property]=$value; + $this->m_IsDirty = ($this->m_IsDirty or $changed or $force); + if($changed || $force) + { + $this->m_DirtyFields[$property] = $value; + } + $this->m_VarType[$property] = $type; + } + + function Save() + { + if($this->m_IsDirty==TRUE) + { + foreach($this->m_DirtyFields as $field=>$value) + { + if($this->m_VarType[$field]==0) + { +// $sql = sprintf("UPDATE ".GetTablePrefix()."ConfigurationValues SET VariableValue=%s WHERE VariableName=%s", $this->adodbConnection->qstr($value), $this->adodbConnection->qstr($field)); + $sql = 'UPDATE '.GetTablePrefix().'ConfigurationValues SET VariableValue="'.addslashes($value).'" WHERE VariableName="'.addslashes($field).'"'; + // echo $sql."
\n"; + + $rs = $this->adodbConnection->execute($sql); + } + } + } + $this->m_IsDirty=FALSE; + unset($this->m_DirtyFields); + } + + function TimeFormat() + { + if($this->Get("ampm_time")=="1") + { + $format = "g:i:s A"; + } + else + $format = "H:i:s"; + return $format; + } + + /* vartype should be either 1 or 2, 1 = perstant data, 2 = session data */ + function GetDirtySessionValues($VarType) + { + $result = array(); + + if(is_array($this->m_DirtyFields)) + { + foreach($this->m_DirtyFields as $property=>$values) + { + if($this->m_VarType[$property]==$VarType) + $result[$property] = $values; + } + } + return $result; + } + + function GetConfigValues($postfix = '') + { + // return only varibles, that match specified criteria + if(!$postfix) return $this->config; + $result = Array(); + $postfix_len = $postfix ? strlen($postfix) : 0; + foreach($this->config as $config_var => $var_value) + { + if( substr($config_var, - $postfix_len) == $postfix ) + $result[$config_var] = $var_value; + } + return $result; + } +}/* clsConfig */ + +/* +To create the configuration forms in the admin section, populate the table ConfigurationAdmin and +ConfigurationValues. + + The tables are fairly straight-forward. The fields of concern in the ConfigurationValues table is +ModuleOwner and Section. ModuleOwner should either be the module name or In-Portal for kernel related stuff. +(Items which should appear under 'System Configuration'). + + The Section field determines the NavMenu section the value is associated with. For example, +in-portal:configure_general refers to items listed under System Configuration->General. + + In the ConfigurationAdmin table, ensure the VariableName field is the same as the one in ConfigurationValues +(this is the field that creates the natural join.) The prompt field is the text displayed to the left of the form element +in the table. This should contain LANGUAGE ELEMENT IDENTIFIERS that are plugged into the Language function. + + The element_type field describes the type of form element is associated with this item. Possible values are: + - text : textbox + - checkbox : a simple checkbox + - select : creates a dropdown box. In this case, the ValueList field should be populated with a comma-separated list + in name=value,name=value format (each element is translated to: + + + To add dynamic data to this list, enclose an SQL statement with tags for example: + SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE .CustomFieldType=3> + + note the specific field labels OptionName and OptionValue. They are required by the parser. + use the tag to insert the system's table prefix into the sql statement as appropriate + +*/ +class clsConfigAdminItem +{ + var $name; + var $heading; + var $prompt; + var $ElementType; + var $ValueList; /* comma-separated list in name=value pair format*/ + var $ValidationRules; + var $default_value; + var $adodbConnection; + var $NextItem=NULL; + var $Section; + + function clsConfigAdminItem($config_name=NULL) + { + $this->adodbConnection = &GetADODBConnection(); + if($config_name) + $this->LoadSetting($config_name); + } + + function LoadSetting($config_name) + { + $sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName) WHERE ".GetTablePrefix()."ConfigurationAdmin.VariableName='".$config_name."'"; + $rs = $this->adodbConnection->Execute($sql); + if($rs && !$rs->EOF) + { + $this->name = $rs->fields["VariableName"]; + $this->heading = $rs->fields["heading"]; + $this->prompt = $rs->fields["prompt"]; + $this->ElementType = $rs->fields["element_type"]; + $this->ValidationRules=$rs->fields["validation"]; + $this->default_value = $rs->fields["VariableValue"]; + $this->ValueList=$rs->fields["ValueList"]; + $this->Section = $rs->fields["Section"]; + } + } + + function explode_sql($sql) + { + $s = ""; + + $rs = $this->adodbConnection->Execute($sql); + + while ($rs && !$rs->EOF) + { + if(strlen(trim($rs->fields["OptionName"]))>0 && strlen(trim($rs->fields["OptionValue"]))>0) + { + if(strlen($s)) + $s .= ","; + $s .= $rs->fields["OptionName"]."="."+".$rs->fields["OptionValue"]; + } + $rs->MoveNext(); + } + return $s; + } + + function replace_sql($string) + { + $string = str_replace("",GetTablePrefix(),$string); + + $start = strpos($string,""); + + while($start) + { + $end = strpos($string,""); + if(!$end) + { + $end = strlen($string); + } + $len = $end - $start; + $sql = substr($string,$start+5,$len-5); + + $sql_val = $this->explode_sql($sql); + $s = substr($string,0,$start) . $sql_val . substr($string,$end+5); + + $string = $s; + $start = strpos($string,""); + } + return $string; + } + + function ItemFormElement($StartFrom=1) + { + global $objConfig; + static $TabIndex; + + if (empty($TabIndex)) + $TabIndex = $StartFrom; + + $o = ""; + if($objConfig->Get($this->name)!="") + $this->default_value = $objConfig->Get($this->name); + $this->default_value=inp_htmlize($this->default_value); + switch($this->ElementType) + { + case "text": + $o .= "name."\" "; + $o .= "VALUE=\"".$this->default_value."\">"; + break; + case "checkbox": + $o .= "name."\" tabindex=\"".($TabIndex++)."\""; + if($this->default_value) + { + $o .= " CHECKED>"; + } + else + $o .= ">"; + + break; + case "password": + + /* To exclude config form from populating with Root (md5) password */ + if ($this->Section == "in-portal:configure_users") + $this->default_value = ""; + + $o .= "name."\" "; + $o .= "VALUE=\"".$this->default_value."\">"; + break; + case "textarea": + $o .= ""; + break; + case "label": + if($this->default_value) + { + $o .= $this->default_value; + } + break; + case "radio": + $radioname = $this->name; + + $ValList = $this->replace_sql($this->ValueList); + + $TabIndex++; + $localTabIndex = $TabIndex; + $TabIndex++; + + $val = explode(",",$ValList); + for($i=0;$i<=count($val);$i++) + { + if(strlen($val[$i])) + { + $parts = explode("=",$val[$i]); + $s = $parts[1]; + if(strlen($s)==0) + $s=""; + + $o .= "name."\" VALUE=\"".$parts[0]."\""; + if($this->default_value==$parts[0]) + { + $o .= " CHECKED>"; + } + else + $o .= ">"; + if(substr($s,0,1)=="+") + { + $o .= $s; + } + else + $o .= prompt_language($s); + } + } + + break; + case "select": + $o .= ""; + } + return $o; + } + + function GetPrompt() + { + $ret = prompt_language($this->prompt); + return $ret; + } +} + +class clsConfigAdmin +{ + var $module; + var $section; + var $Items; + + function clsConfigAdmin($module="",$section="",$Inst=FALSE) + { + $this->module = $module; + $this->section = $section; + $this->Items= array(); + if(strlen($module) && strlen($section)) + $this->LoadItems(TRUE,$Inst); + } + + function Clear() + { + unset($this->Items); + $this->Items = array(); + } + + function NumItems() + { + if(is_array($this->Items)) + { + return count($this->Items); + } + else + return 0; + } + + function LoadItems($CheckNextItems=TRUE, $inst=FALSE) + { + $this->Clear(); + if(!$inst) + { + $sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName) + WHERE ModuleOwner='".$this->module."' AND Section='".$this->section."' ORDER BY DisplayOrder ASC"; + } + else + { + + $sql = "SELECT * FROM ".GetTablePrefix()."ConfigurationAdmin INNER JOIN ".GetTablePrefix()."ConfigurationValues Using(VariableName) + WHERE ModuleOwner='".$this->module."' AND Section='".$this->section."' AND Install=1 ORDER BY DisplayOrder ASC"; + } + if( $GLOBALS['debuglevel'] ) echo $sql."
\n"; + $adodbConnection = &GetADODBConnection(); + $rs = $adodbConnection->Execute($sql); + while($rs && !$rs->EOF) + { + $data = $rs->fields; + if(is_object($i) && $CheckNextItems) + { + $last = $i->prompt; + unset($i); + } + $i = new clsConfigAdminItem(NULL); + $i->name = $data["VariableName"]; + $i->default_value = $data["VariableValue"]; + $i->heading = $data["heading"]; + $i->prompt = $data["prompt"]; + $i->ElementType = $data["element_type"]; + $i->ValueList = $data["ValueList"]; + $i->ValidationRules = isset($data['validaton']) ? $data['validaton'] : ''; + $i->Section = $data["Section"]; + + if(strlen($last)>0) + { + if($i->prompt==$last) + { + $this->Items[count($this->Items)-1]->NextItem=$i; + } + else + { + $i->NextItem=NULL; + array_push($this->Items,$i); + } + } + else + { + $i->NextItem=NULL; + array_push($this->Items,$i); + } + //unset($i); + $rs->MoveNext(); + } + } + + function SaveItems($POSTVARS, $force=FALSE) + { + global $objConfig; + + foreach($this->Items as $i) + { + if($i->ElementType != "label") + { + if($i->ElementType != "checkbox") + { + $objConfig->Set($i->name,stripslashes($POSTVARS[$i->name])); + } + else + { + if($POSTVARS[$i->name]=="on") + { + $value=1; + } + else + $value = (int)$POSTVARS[$i->name]; + $objConfig->Set($i->name,stripslashes($value),0,$force); + } + } + } + $objConfig->Save(); + } + + function GetHeadingList() + { + $res = array(); + foreach($this->Items as $i) + { + $res[$i->heading]=1; + } + reset($res); + return array_keys($res); + } + + function GetHeadingItems($heading) + { + $res = array(); + foreach($this->Items as $i) + { + if($i->heading==$heading) + array_push($res,$i); + } + return $res; + } +} + + +?> Index: trunk/kernel/include/parseditem.php =================================================================== diff -u -N -r640 -r642 --- trunk/kernel/include/parseditem.php (.../parseditem.php) (revision 640) +++ trunk/kernel/include/parseditem.php (.../parseditem.php) (revision 642) @@ -1,2953 +1,2959 @@ -clsItemDB(); - $this->Parser = new clsTemplateList($TemplateRoot); - $this->AdminParser = new clsAdminTemplateList(); - } - -/* function ParseObject($element) - { - $extra_attribs = ExtraAttributes($element->attributes); - if(strtolower($element->name)==$this->TagPrefix) - { - $field = strtolower($element->attributes["_field"]); - $tag = $this->TagPrefix."_".$field; - $ret = $this->parsetag($tag); - } - return $ret; - } -*/ - function ParseTimeStamp($d,$attribs=array()) - { - if( isset($attribs["_tz"]) ) - { - $d = GetLocalTime($d,$objSession->Get("tz")); - } - $part = isset($attribs["_part"]) ? strtolower($attribs["_part"]) : ''; - if(strlen($part)) - { - $ret = ExtractDatePart($part,$d); - } - else - { - if($d<=0) - { - $ret = ""; - } - else - $ret = LangDate($d); - } - return $ret; - } - - function ParseObject($element) - { - global $objConfig, $objCatList, $var_list_update, $var_list, $n_var_list_update, $m_var_list_update; - - $extra_attribs = ExtraAttributes($element->attributes); - $ret = ""; - - if ($this->TagPrefix == "email" && strtolower($element->name) == "touser") { - $this->TagPrefix = "touser"; - } - - if(strtolower($element->name)==$this->TagPrefix) - { - $field = strtolower($element->attributes["_field"]); - switch($field) - { - case "id": - $ret = $this->Get($this->id_field); - break; - case "resourceid": - if(!$this->NoResourceId) - $ret = $this->Get("ResourceId"); - break; - case "category": - $c = $objCatList->GetItem($this->Get("CategoryId")); - if(is_object($c)) - { - $ret = $c->parsetag($element->attributes["_cattag"]); - } - break; - case "priority": - if($this->Get("Priority")!=0) - { - $ret = (int)$this->Get("Priority"); - } - else - $ret = ""; - break; - case "link": - if(method_exists($this,"ItemURL")) - { - $ret = $this->ItemURL($element->attributes["_template"],FALSE,""); - } - break; - case "cat_link": - if(method_exists($this,"ItemURL")) - { - $ret = $this->ItemURL($element->attributes["_template"],TRUE,""); - } - break; - case "fullpath": - $ret = $this->Get("CachedNavbar"); - if(!strlen($ret)) - { - if(is_numeric($this->Get("CategoryId"))) - { - $c = $objCatList->GetItem($this->Get("CategoryId")); - if(is_object($c)) - $ret = $c->Get("CachedNavbar"); - } - else - { - if(method_exists($this,"GetPrimaryCategory")) - { - $cat = $this->GetPrimaryCategory(); - $c = $objCatList->GetItem($cat); - if(is_object($c)) - $ret = $c->Get("CachedNavbar"); - } - } - } - // $ret = $this->HighlightText($ret); - break; - - case "relevance": - $style = $element->attributes["_displaymode"]; - if(!strlen($style)) - $style = "numerical"; - switch ($style) - { - case "numerical": - $ret = (100 * LangNumber($this->Get("Relevance"),1))."%"; - break; - case "bar": - $OffColor = $element->attributes["_offbackgroundcolor"]; - $OnColor = $element->attributes["_onbackgroundcolor"]; - $percentsOff = (int)(100 - (100 * $this->Get("Relevance"))); if ($percentsOff) - { - $percentsOn = 100 - $percentsOff; - $ret = ""; - } - else - $ret = ""; - break; - case "graphical": - $OnImage = $element->attributes["_onimage"]; - if (!strlen($OnImage)) - break; - // Get image extension - $image_data = explode(".", $OnImage); - $image_ext = $image_data[count($image_data)-1]; - unset($image_data[count($image_data)-1]); - $rel = (10 * LangNumber($this->Get("Relevance"),1)); - $OnImage1 = join(".", $image_data); - - if ($rel) - $img_src = $OnImage1."_".$rel.".".$image_ext; - else - $img_src = $OnImage; - - $ret = "\"".(10*$rel)."\""; - break; - } - - break; - - case "rating": - $style = $element->GetAttributeByName("_displaymode"); - if(!strlen($style)) - $style = "numerical"; - switch($style) - { - case "numerical": - $ret = LangNumber($this->Get("CachedRating"),1); - break; - case "text": - $ret = RatingText($this->Get("CachedRating")); - break; - case "graphical": - $OnImage = $element->attributes["_onimage"]; - $OffImage = $element->attributes["_offimage"]; - $images = RatingTickImage($this->Get("CachedRating"),$OnImage,$OffImage); - - for($i=1;$i<=count($images);$i++) - { - $url = $images[$i]; - if(strlen($url)) - { - $ret .= ""; - $ret .= $element->attributes["_separator"]; - } - } - break; - } - break; - case "reviews": - $today = FALSE; - - if(method_exists($this,"ReviewCount")) - { - if($element->GetAttributeByName("_today")) - $today = TRUE; - $ret = $this->ReviewCount($today); - } - else - $ret = ""; - - break; - case "votes": - $ret = (int)$this->Get("CachedVotesQty"); - break; - - case "favorite": - if(method_exists($this,"IsFavorite")) - { - if($this->IsFavorite()) - { - $ret = $element->attributes["_label"]; - if(!strlen($ret)) - $ret = "lu_favorite"; - $ret = language($ret); - } - else - $ret = ""; - } - break; - case "new": - if(method_exists($this,"IsNewItem")) - { - if($this->IsNewItem()) - { - $ret = $element->GetAttributeByName('_label'); - if(!strlen($ret)) - $ret = "lu_new"; - $ret = language($ret); - } - else - $ret = ""; - } - break; - case "pop": - if(method_exists($this,"IsPopItem")) - { - if($this->IsPopItem()) - { - $ret = $element->attributes["_label"]; - if(!strlen($ret)) - $ret = "lu_pop"; - $ret = language($ret); - } - else - $ret = ""; - } - break; - case "hot": - if(method_exists($this,"IsHotItem")) - { - if($this->IsHotItem()) - { - $ret = $element->GetAttributeByName("_label"); - if(!strlen($ret)) - $ret = "lu_hot"; - $ret = language($ret); - } - else - $ret = ""; - } - break; - case "pick": - if($this->Get("EditorsPick")==1) - { - $ret = $element->GetAttributeByName('_label'); - if(!strlen($ret)) - $ret = "lu_pick"; - $ret = language($ret); - } - else - $ret = ""; - break; - case "admin_icon": - if(method_exists($this,"StatusIcon")) - { - if($element->GetAttributeByName("fulltag")) - { - $ret = "StatusIcon()."\">"; - } - else - $ret = $this->StatusIcon(); - } - break; - case "custom": - if(method_exists($this,"GetCustomFieldValue")) - { - $field = $element->attributes["_customfield"]; - $default = $element->attributes["_default"]; - if (strlen($field)) - $ret = $this->GetCustomFieldValue($field,$default); - } - break; - case "image": - $default = $element->attributes["_primary"]; - $name = $element->attributes["_name"]; - - if(strlen($name)) - { - $img = $this->GetImageByName($name); - } - else - { - if($default) - $img = $this->GetDefaultImage(); - } - - if(is_object($img)) - { - - if(strlen($element->attributes["_imagetemplate"])) - { - $ret = $img->ParseTemplate($element->attributes["_imagetemplate"]); - break; - } - else - { - if($element->attributes["_thumbnail"]) - { - $url = $img->parsetag("thumb_url"); - } - else - { - - if(!$element->attributes["_nothumbnail"]) - { - $url = $img->parsetag("image_url"); - } - else - { - $url = $img->FullURL(TRUE,""); - } - } - } - } - else - { - $url = $element->attributes["_defaulturl"]; - - } - - if($element->attributes["_imagetag"]) - { - if(strlen($url)) - { - $ret = ""; - } - else - $ret = ""; - } - else - $ret = $url; - break; - default: - $ret = "Undefined:".$element->name; - break; - } - - } - else if ($this->TagPrefix == 'email'){ - $ret = "Undefined:".$element->name; - } - return $ret; - } - - function ParseString($name) - { - $el = new clsHtmlTag(); - $el->Clear(); - $el->prefix = "inp"; - $el->name = $name; - - $numargs = func_num_args(); - $arg_list = func_get_args(); - for ($i = 1; $i < $numargs; $i++) - { - $attr = $arg_list[$i]; - $parts = explode("=",$attr,2); - $name = $parts[0]; - $val = $parts[1]; - $el->attributes[$name] = $val; - } - return $this->ParseObject($el); - } - - /* pass attributes as strings - ie: ParseStringEcho('tagname','_field="something" _data="somethingelse"'); - */ - function ParseStringEcho($name) - { - $el = new clsHtmlTag(); - $el->Clear(); - $el->prefix = "inp"; - $el->name = $name; - - $numargs = func_num_args(); - $arg_list = func_get_args(); - for ($i = 1; $i < $numargs; $i++) - { - $attr = $arg_list[$i]; - $parts = explode("=",$attr,2); - $name = $parts[0]; - $val = $parts[1]; - $el->attributes[$name] = $val; - } - echo $this->ParseObject($el); - } - - function ParseElement($raw, $inner_html ="") - { - $tag = new clsHtmlTag($raw); - $tag->inner_html = $inner_html; - - if($tag->parsed) - { - if($tag->name=="include" || $tag->name=="perm_include" || $tag->name=="lang_include") - { - $output = $this->Parser->IncludeTemplate($tag); - } - else - { - $output = $this->ParseObject($tag); - //echo $output."
"; - if(substr($output,0,9)=="Undefined") - { - $output = $tag->Execute(); - // if(substr($output,0,8)="{Unknown") - // $output = $raw; - } return $output; - } - } - else - return ""; - } - - function AdminParseTemplate($file) - { - $html = ""; - $t = $this->AdminParser->GetTemplate($file); - - if(is_object($t)) - { - array_push($this->AdminParser->stack,$file); - $html = $t->source; - $next_tag = strpos($html,"",$next_tag); - $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2); - $pre = substr($html,0,$next_tag); - $post = substr($html,$end_tag+2); - $inner = $this->ParseElement($tagtext); - $html = $pre.$inner.$post; - $next_tag = strpos($html,"AdminParser->stack); - } - return $html; - } - - function ParseTemplateText($text) - { - $html = $text; - $search = "TagPrefix; - //$next_tag = strpos($html,"",$next_tag); - $end_tag = strpos($html,"/>",$next_tag); - if($end_tag < $closer || $closer == 0) - { - $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2); - $pre = substr($html,0,$next_tag); - $post = substr($html,$end_tag+2); - $inner = $this->ParseElement($tagtext); - $html = $pre.$inner.$post; - } - else - { - - $OldTagStyle = ""; - - ## Try to find end of TagName - $TagNameEnd = strpos($html, " ", $next_tag); - - ## Support Old version -// $closer = strpos(strtolower($html),"",$next_tag); - if ($TagNameEnd) - { - $Tag = strtolower(substr($html, $next_tag, $TagNameEnd-$next_tag)); - $TagName = explode(":", $Tag); - if (strlen($TagName[1])) - $CloserTag = ""; - } - else - { - $CloserTag = $OldTagStyle; - } - - $closer = strpos(strtolower($html), $CloserTag, $next_tag); - - ## Try to find old tag closer - if (!$closer && ($CloserTag != $OldTagStyle)) - { - $CloserTag = $OldTagStyle; - $closer = strpos(strtolower($html), $CloserTag, $next_tag); - } - - $end_tag = strpos($html,">",$next_tag); - $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+1); - $pre = substr($html,0,$next_tag); - $inner = substr($html,$end_tag+1,$closer-($end_tag+1)); - $post = substr($html,$end_tag+1+strlen($inner) + strlen($CloserTag)); - //echo "PRE:". htmlentities($pre,ENT_NOQUOTES); - //echo "INNER:". htmlentities($inner,ENT_NOQUOTES); - //echo "POST:". htmlentities($post,ENT_NOQUOTES); - - $parsed = $this->ParseElement($tagtext); - if(strlen($parsed)) - { - $html = $pre.$this->ParseTemplateText($inner).$post; - } - else - $html = $pre.$post; - } - $next_tag = strpos($html,$search); - } - return $html; - } - - function ParseTemplate($tname) - { - global $objTemplate, $LogLevel,$ptime,$timestart; - - //echo 'Saving ID'.$this->UniqueId().' in Main parseTempalate
'; - //$GLOBALS[$this->TagPrefix.'_ID'] = $this->UniqueId(); - LogEntry("Parsing $tname\n"); - $LogLevel++; - $html = ""; - $t = $objTemplate->GetTemplate($tname); - //$t = $this->Parser->GetTemplate($tname); - if( is_array($this->Parser->stack) ) $this->Parser->stack = Array(); - if(is_object($t)) - { - array_push($this->Parser->stack,$tname); - $html = $t->source; - - $html = $this->ParseTemplateText($html); - array_pop($this->Parser->stack); - } - $LogLevel--; - LogEntry("Finished Parsing $tname\n"); - $ptime = round(getmicrotime() - $timestart,6); - $xf = 867530; //Download ID - if($xf != 0) - { - $x2 = substr($ptime,-6); - $ptime .= $xf ^ $x2; //(1/1000); - } - return $html; - } - - function SendUserEventMail($EventName,$ToUserId,$LangId=NULL,$RecptName=NULL) - { - global $objMessageList,$FrontEnd; - - $Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId); - - if(is_object($Event)) - { - if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd)) - { - $Event->Item = $this; - if(is_numeric($ToUserId)) - { - return $Event->SendToUser($ToUserId); - } - else - return $Event->SendToAddress($ToUserId,$RecptName); - } - } - } - - function SendAdminEventMail($EventName,$LangId=NULL) - { - global $objMessageList,$FrontEnd; - - //echo "Firing Admin Event $EventName
\n"; - $Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId); - if(is_object($Event)) - { - if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd)) - { - $Event->Item = $this; - //echo "Admin Event $EventName Enabled
\n"; - return $Event->SendAdmin($ToUserId); - } - } - } - - function parse_template($t) - { - } - -} - -class clsItemCollection -{ - var $Items; - var $CurrentItem; - var $adodbConnection; - var $classname; - var $SourceTable; - var $LiveTable; - var $QueryItemCount; - var $AdminSearchFields = array(); - var $SortField; - var $debuglevel; - var $id_field = null; // id field for list item - var $BasePermission; - var $Dummy = null; - - // enshure that same sql won't be queried twice - var $QueryDone = false; - var $LastQuerySQL = ''; - - function SetTable($action, $table_name = null) // new by Alex - { - // $action = {'live', 'restore','edit'} - switch($action) - { - case 'live': - $this->LiveTable = $table_name; - $this->SourceTable = $this->LiveTable; - break; - case 'restore': - $this->SourceTable = $this->LiveTable; - break; - case 'edit': - global $objSession; - $this->SourceTable = $objSession->GetEditTable($this->LiveTable); - break; - } - } - - function &GetDummy() // new by Alex - { - if( !isset($this->Dummy) ) - $this->Dummy =& new $this->classname(); - $this->Dummy->tablename = $this->SourceTable; - return $this->Dummy; - } - - function clsItemCollection() - { - - $this->adodbConnection = &GetADODBConnection(); - - $this->Clear(); - $this->BasePermission=""; - } - - function GetIDField() // new by Alex - { - // returns id field for list item - if( !isset($this->id_field) ) - { - $dummy =& $this->GetDummy(); - $this->id_field = $dummy->IdField(); - } - return $this->id_field; - } - - function &GetNewItemClass() - { - return new $this->classname(); - } - - function Clear() - { - unset($this->Items); - $this->Items = array(); - $this->CurrentItem=0; - } - - function &SetCurrentItem($id) - { - $this->CurrentItem=$id; - return $this->GetItem($id); - } - - function &GetCurrentItem() - { - if($this->CurrentItem>0) - { - return $this->GetItem($this->CurrentItem); - } - else - return FALSE; - } - - function NumItems() - { - if(is_array($this->Items)) - { -// echo "TEST COUNT: ".count($this->Items)."
"; - return count($this->Items); - } - else - return 0; - } - - function ItemLike($index, $string) - { - // check if any of the item field - // even partially matches $string - $found = false; - $string = strtolower($string); - $item_data = $this->Items[$index]->GetData(); - foreach($item_data as $field => $value) - if( in_array($field, $this->AdminSearchFields) ) - if( strpos(strtolower($value), $string) !== false) - { - $found = true; - break; - } - return $found; - } - - function DeleteItem($index) // by Alex - { - // deletes item with specific index from list - $i = $index; $item_count = $this->NumItems(); - while($i < $item_count - 1) - { - $this->Items[$i] = $this->Items[$i + 1]; - $i++; - } - unset($this->Items[$i]); - } - - function ShowItems() - { - $i = 0; $item_count = $this->NumItems(); - while($i < $item_count) - { - echo "Item No $i:
"; - $this->Items[$i]->PrintVars(); - $i++; - } - } - - function SwapItems($Index,$Index2) - { - $temp = $this->Items[$Index]->GetData(); - $this->Items[$Index]->SetData($this->Items[$Index2]->GetData()); - $this->Items[$Index2]->SetData($temp); - - } - - function CopyResource($OldId,$NewId) - { - $this->Clear(); - - $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$OldId"; - $this->Query_Item($sql); -// echo $sql."
\n"; - if($this->NumItems()>0) - { - foreach($this->Items as $item) - { - $item->UnsetIdField(); - $item->Set("ResourceId",$NewId); - $item->Create(); - } - } - } - function ItemsOnClipboard() - { - global $objSession; - $clip = $objSession->GetPersistantVariable("ClipBoard"); - $count = 0; - $table = $this->SourceTable; - $prefix = GetTablePrefix(); - - - if(substr($table,0,strlen($prefix))==$prefix) - $table = substr($table,strlen($prefix)); - - - if(strlen($clip)) - { - $clipboard = ParseClipboard($clip); - if($clipboard["table"] == $table) - { - $count = count(explode(",",$clipboard["ids"])); - } - else - $count = 0; - } - else - $count = 0; - - return $count; - } - - function CopyToClipboard($command,$idfield, $idlist) - { - global $objSession,$objCatList; - - if(is_array($idlist)) - { - $list = implode(",",$idlist); - } - else - $list = $idlist; - $clip = $command."-".$objCatList->CurrentCategoryID().".".$this->SourceTable.".$idfield=".$list; - - $objSession->SetVariable("ClipBoard",$clip); - } - - function SortItems($asc=TRUE) - { - $done = FALSE; - - $field = $this->SortField; - $ItemCount = $this->NumItems(); - while(!$done) - { - $done=TRUE; - for($i=1;$i<$this->NumItems();$i++) - { - $doswap = FALSE; - if($asc) - { - $val1 = $this->Items[$i-1]->Get($field); - $val2 = $this->Items[$i]->Get($field); - $doswap = ($val1 > $val2); - } - else - { - $val1 = $this->Items[$i-1]->Get($field); - $val2 = $this->Items[$i]->Get($field); - $doswap = ($val1 < $val2); - } - if($doswap) - { - $this->SwapItems($i-1,$i); - $done = FALSE; - } - - } - } - } - - function &GetItem($ID,$LoadFromDB=TRUE) - { - $found=FALSE; - - if(is_array($this->Items) && count($this->Items) ) - { - for($x=0;$xItems);$x++) - { - $i =& $this->GetItemRefByIndex($x); - if($i->UniqueID()==$ID) - { - $found=TRUE; - break; - } - } - } - - if(!$found) - { - if($LoadFromDB) - { - $n = NULL; - $n = new $this->classname(); - $n->tablename = $this->SourceTable; - $n->LoadFromDatabase($ID); - $index = array_push($this->Items, $n); - $i =& $this->Items[count($this->Items)-1]; - } - else - $i = FALSE; - } - return $i; - } - - function GetItemByIndex($index) - { - return $this->Items[$index]; - } - - function &GetItemRefByIndex($index) - { - return $this->Items[$index]; - } - - function &GetItemByField($Field,$Value,$LoadFromDB=TRUE) - { - $found=FALSE; - - if(is_array($this->Items)) - { - foreach($this->Items as $i) - { - if($i->Get($Field)==$Value) - { - $found = TRUE; - break; - } - } - } - if(!$found && $LoadFromDB==TRUE) - { - $sql = "SELECT * FROM ".$this->SourceTable." WHERE $Field = '$Value'"; - //echo $sql; - $res = $this->adodbConnection->Execute($sql); - - if($res && !$res->EOF) - { - $i = $this->AddItemFromArray($res->fields); - $i->tablename = $this->SourceTable; - $i->Clean(); - } - else - $i = FALSE; - } - - return $i; - } - - function GetPage($Page, $ItemsPerPage) - { - $result = array_slice($this->Items, ($Page * $ItemsPerPage) - $ItemsPerPage, $ItemsPerPage); - return $result; - } - - function GetNumPages($ItemsPerPage) - { - if( isset($_GET['reset']) && $_GET['reset'] == 1) $this->Page = 1; - return GetPageCount($ItemsPerPage,$this->QueryItemCount); - } - - function &AddItemFromArray($data, $clean=FALSE) - { - $class = new $this->classname; - $class->SetFromArray($data); - $class->tablename = $this->SourceTable; - if($clean==TRUE) - $class->Clean(); - //array_push($this->Items,$class); - $this->Items[] =& $class; - return $class; - } - - function Query_Item($sql, $offset=-1,$rows=-1) - { - global $Errors; - //echo "Method QItem [".get_class($this).'], sql: ['.$sql.']
'; - //if( get_class($this) == 'clsthemefilelist') trace(); - $dummy =& $this->GetDummy(); - if( !$dummy->TableExists() ) - { - if($this->debuglevel) echo "ERROR: table ".$dummy->tablename." missing.
"; - $this->Clear(); - return false; - } - - if($rows>-1 && $offset>-1) - { - //print_pre(debug_backtrace()); - //echo "Executing SelectLimit $sql Offset: $offset,$rows
\n"; - $result = $this->adodbConnection->SelectLimit($sql, $rows,$offset); - } - else { - $result = $this->adodbConnection->Execute($sql); - } - - if ($result === false) - { - $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_Item"); - if($this->debuglevel) { - echo '

'.$sql.'

'; - echo "Error: ".$this->adodbConnection->ErrorMsg()."
"; - } - $this->Clear(); - return false; - } - - $this->Clear(); - - if($this->debuglevel > 0) - { - echo "This SQL: $sql

"; - if( ($this->debuglevel > 1) && ($result->RecordCount() > 0) ) - { - echo '
'.print_r($result->GetRows(), true).'
'; - $result->MoveFirst(); - } - } - //echo "SQL: $sql

"; - LogEntry("SQL Loop Start\n"); - $count = 0; - - while ($result && !$result->EOF) - { - $count++; - $data = $result->fields; - $this->AddItemFromArray($data,TRUE); - if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 ) - adodb_movenext($result); - else - $result->MoveNext(); - } - - LogEntry("SQL Loop End ($count iterations)\n"); - $result->Free(); - return $this->Items; - } - - function GetOrderClause($FieldVar,$OrderVar,$DefaultField,$DefaultVar,$Priority=TRUE,$UseTableName=FALSE) - { - global $objConfig, $objSession; - - if($UseTableName) - { - $TableName = $this->SourceTable."."; - } - else - $TableName = ""; - - $PriorityClause = $TableName."EditorsPick DESC, ".$TableName."Priority DESC"; - - if(strlen(trim($FieldVar))>0) - { - if(is_object($objSession)) - { - if(strlen($objSession->GetPersistantVariable($FieldVar))>0) - { - $OrderBy = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". - $objSession->GetPersistantVariable($OrderVar)); - $FieldUsed = $objSession->GetPersistantVariable($FieldVar); - } - } - $OrderBy = trim($OrderBy); - if (strlen(trim($OrderBy))==0) - { - if(!$UseTableName) - { - $OrderBy = trim($DefaultField." ".$DefaultVar); - } - else - { - if(strlen(trim($DefaultField))>0) - { - $OrderBy = $this->SourceTable.".".$DefaultField.".".$DefaultVar; - } - $FieldUsed=$DefaultField; - } - } - } - if(($FieldUsed != "Priority" || strlen($OrderBy)==0) && $Priority==TRUE) - { - if(strlen($OrderBy)==0) - { - $OrderBy = $PriorityClause; - } - else - $OrderBy = $PriorityClause.", ".$OrderBy; - } - return $OrderBy; - } - - function GetResourceIDList() - { - $ret = array(); - foreach($this->Items as $i) - array_push($ret,$i->Get("ResourceId")); - return $ret; - } - - function GetFieldList($field) - { - $ret = array(); - foreach($this->Items as $i) - array_push($ret,$i->Get($field)); - return $ret; - } - - function SetCommonField($FieldName,$FieldValue) - { - for($i=0;$i<$this->NumItems();$i++) - { - $this->Items[$i]->Set($FieldName,$fieldValue); - $this->Items[$i]->Update(); - } - } - - function ClearCategoryItems($CatId,$CatTable = "CategoryItems") - { - $CatTable = AddTablePrefix($CatTable); - $sql = "SELECT * FROM ".$this->SourceTable." INNER JOIN $CatTable ". - " ON (".$this->SourceTable.".ResourceId=$CatTable.ItemResourceId) WHERE CategoryId=$CatId"; - $this->Clear(); - $this->Query_Item($sql); - if($this->NumItems()>0) - { - foreach($this->Items as $i) - { - $i->DeleteCategoryItems($CatId,$CatTable); - } - } - } - - function CopyToEditTable($idfield = null, $idlist = 0) - { - global $objSession; - - if($idfield == null) $idfield = $this->GetIDField(); - $edit_table = $objSession->GetEditTable($this->SourceTable); - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); - if(is_array($idlist)) - { - $list = implode(",",$idlist); - } - else - $list = $idlist; - $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)"; - $insert = "CREATE TABLE ".$edit_table." ".$query; - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($insert,ENT_NOQUOTES)."
\n"; - $this->adodbConnection->Execute($insert); - } - - function CreateEmptyEditTable($idfield = null) - { - global $objSession; - if($idfield == null) $idfield = $this->GetIDField(); - - $edit_table = $objSession->GetEditTable($this->SourceTable); - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); - $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield = -1"; - $insert = "CREATE TABLE ".$edit_table." ".$query; - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($insert,ENT_NOQUOTES)."
\n"; - $this->adodbConnection->Execute($insert); - //echo $insert."
"; - } - - function CopyFromEditTable($idfield = null) - { - global $objSession; - - $dropRelTableFlag = false; - if($idfield == null) $idfield = $this->GetIDField(); - $edit_table = $objSession->GetEditTable($this->SourceTable); - $sql = "SELECT * FROM $edit_table"; - $rs = $this->adodbConnection->Execute($sql); - - //echo "In Main CopyFromEditTable in class ".get_class($this).'
'; - //echo $sql."
"; - - while($rs && !$rs->EOF) - { - $data = $rs->fields; - $c = new $this->classname; - $c->SetFromArray($data); - $c->idfield = $idfield; - $c->Dirty(); - if($c->Get($idfield) < 1) - { - $old_id = $c->Get($idfield); - $c->UnsetIdField(); - if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0) - { - $c->Clean(array("OrgId")); - } - else - { - if($c->Get("Status") != -2) - { - $org = new $this->classname(); - $org->LoadFromDatabase($c->Get("OrgId")); - $org->DeleteCustomData(); - $org->Delete(TRUE); - $c->Set("OrgId",0); - } - } - $c->Create(); - } - if(is_numeric($c->Get("ResourceId"))) - { - if( isset($c->Related) && is_object($c->Related) ) - { - $r = $c->Related; - $r->CopyFromEditTable($c->Get("ResourceId")); - $dropRelTableFlag = true; - } - - unset($r); - - if( isset($c->Reviews) && is_object($c->Reviews) ) - { - $r = $c->Reviews; - $r->CopyFromEditTable($c->Get("ResourceId")); - } - } - if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0) - { - $c->Clean(array("OrgId")); - } - else - { - if($c->Get("Status") != -2) - { - $org = new $this->classname(); - $org->LoadFromDatabase($c->Get("OrgId")); - $org->DeleteCustomData(); - $org->Delete(TRUE); - $c->Set("OrgId",0); - } - } - - if(method_exists($c,"CategoryMemberList")) - { - $cats = $c->CategoryMemberList($objSession->GetEditTable("CategoryItems")); - $ci_table = $objSession->GetEditTable('CategoryItems'); - $primary_cat = $c->GetPrimaryCategory($ci_table); - $c->Update(); - UpdateCategoryItems($c,$cats,$primary_cat); - } - else - $c->Update(); - - unset($c); - unset($r); - - $rs->MoveNext(); - } - - if ($dropRelTableFlag) - { - $objRelGlobal = new clsRelationshipList(); - $objRelGlobal->PurgeEditTable(); - } - - if($edit_table) @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->GetEditTable("CategoryItems")); - } - - function GetNextTempID() - { - // get next temporary id (lower then zero) from temp table - $db =& $this->adodbConnection; - $sql = 'SELECT MIN(%s) AS MinValue FROM %s'; - return $db->GetOne( sprintf($sql, $this->GetIDField(), $this->SourceTable) ) - 1; - } - - function PurgeEditTable($idfield = null) - { - global $objSession; - - if($idfield == null) $idfield = $this->GetIDField(); - $edit_table = $objSession->GetEditTable($this->SourceTable); -/* $rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table"); - while($rs && !$rs->EOF) - { - $data = $rs->fields; - $c = new $this->classname; - $c->SetFromArray($data); - $c->id_field = $idfield; - $c->tablename = $edit_table; - $c->Delete(); - $rs->MoveNext(); - }*/ - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->Get("CategoryItems")); - } - - function CopyCatListToEditTable($idfield, $idlist) - { - global $objSession; - - $edit_table = $objSession->GetEditTable("CategoryItems"); - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); - if(is_array($idlist)) - { - $list = implode(",",$idlist); - } - else - $list = $idlist; - $query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield IN ($list)"; - - $insert = "CREATE TABLE ".$edit_table." ".$query; - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($insert,ENT_NOQUOTES)."
\n"; - $this->adodbConnection->Execute($insert); - } - - function CreateEmptyCatListTable($idfield) - { - global $objSession; - - $edit_table = $objSession->GetEditTable("CategoryItems"); - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); - $query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield = -1"; - $insert = "CREATE TABLE ".$edit_table." ".$query; - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($insert,ENT_NOQUOTES)."
\n"; - $this->adodbConnection->Execute($insert); - } - - - function PurgeCatListEditTable() - { - global $objSession; - - $edit_table = $objSession->GetEditTable("CategoryItems"); - $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); - } - - function AdminSearchWhereClause($SearchList) - { - $sql = ""; - if( !is_array($SearchList) ) $SearchList = explode(",",$SearchList); - 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 "; - $inner_sql .= $field." LIKE '%".$value."%'"; - } - } - if( strlen($inner_sql) ) - { - $sql .= '('.$inner_sql.') '; - if($f < count($SearchList) - 1) $sql .= " AND "; - } - } - } - return $sql; - } - - function BackupData($OutFileName,$Start,$Limit) - { - $fp=fopen($Outfile,"a"); - if($fp) - { - if($Start==1) - { - $sql = "DELETE FROM ".$this->SourceTable; - fputs($fp,$sql); - } - $this->Query_Item("SELECT * FROM ".$this->SourceTable." LIMIT $Start, $Limit"); - foreach($this->Items as $i) - { - $sql = $i->CreateSQL(); - fputs($fp,$sql); - } - fclose($fp); - $this->Clear(); - } - } - - function RestoreData($InFileName,$Start,$Limit) - { - $res = -1; - $fp=fopen($InFileName,"r"); - if($fp) - { - fseek($fp,$Start); - $Line = 0; - while($Line < $Limit) - { - $sql = fgets($fp,16384); - $this->adodbConnection->Execute($sql); - $Line++; - } - $res = ftell($fp); - fclose($fp); - } - return $res; - } - - function Delete_Item($Id) - { - global $objCatList; - - $l =& $this->GetItem($Id); - $l->BasePermission=$this->BasePermission; - $l->DeleteCategoryItems($objCatList->CurrentCategoryID()); - } - - function Move_Item($Id, $OldCat, $ParentTo) - { - global $objCatList; - - $l = $this->GetItem($Id); - $l->BasePermission=$this->BasePermission; - $l->AddtoCategory($ParentTo); - $l->RemoveFromCategory($OldCat); - } - - function Copy_Item($Id, $ParentTo) - { - $l = $this->GetItem($Id); - $l->BasePermission=$this->BasePermission; - $l->AddtoCategory($ParentTo); - } - -}/* clsItemCollection */ - -class clsItemList extends clsItemCollection -{ - var $Page; - var $PerPageVar; - var $DefaultPerPage; // use this perpage value in case if no found in config - var $EnablePaging; - var $MaxListCount = 0; - var $PageEnvar; - var $PageEnvarIndex; - var $ListType; - - var $LastLimitClause = ''; // used to store last limit cluse used in query - - function clsItemList() - { - $this->clsItemCollection(); - $this->EnablePaging = TRUE; - $this->PageEnvarIndex = "p"; - } - - function GetPageLimitSQL() - { - global $objConfig; - $limit = NULL; - if($this->EnablePaging) - { - if($this->Page<1) - $this->Page=1; - //echo "Limited to ".$objConfig->Get($this->PerPageVar)." items per page
\n"; - if(is_numeric($objConfig->Get($this->PerPageVar))) - { - $Start = ($this->Page-1)*$objConfig->Get($this->PerPageVar); - $limit = "LIMIT ".$Start.",".$objConfig->Get($this->PerPageVar); - } - else - $limit = NULL; - } - else - { - if($this->MaxListCount) - { - $limit = "LIMIT 0, $MaxListCount"; - } - } - return $limit; - } - - function GetPageOffset() - { - $Start = 0; - if($this->EnablePaging) - { - if($this->Page < 1) $this->Page = 1; - $PerPage = $this->GetPerPage(); - $Start = ($this->Page - 1) * $PerPage; - } - else - { - if((int)$this->MaxListCount == 0) $Start = -1; - } - return $Start; - } - - function GetPageRowCount() - { - if($this->EnablePaging) - { - if($this->Page < 1) $this->Page = 1; - return $this->GetPerPage(); - } - else - return (int)$this->MaxListCount; - } - - function Query_Item($sql,$limit = null, $fix_method = 'set_first') - { - // query itemlist (module items) using $sql specified - // apply direct limit clause ($limit) or calculate it if not specified - // fix invalid page in case if needed by method specified in $fix_method - if(strlen($limit)) - { - $sql .= " ".$limit; - return parent::Query_Item($sql); - } - else - { - //echo "page fix pre (class: ".get_class($this).")
"; - $this->QueryItemCount = QueryCount($sql); // must get total item count before fixing - $this->FixInvalidPage($fix_method); - - // specially made for cats delete - if ( GetVar('Action', true) != 'm_cat_delete') { - return parent::Query_Item($sql,$this->GetPageOffset(),$this->GetPageRowCount()); - } - else { - return parent::Query_Item($sql); - } - } - } - - function Query_List($whereClause,$orderByClause=NULL,$JoinCats=TRUE,$fix_method='set_first') - { - global $objSession, $Errors; - - if($JoinCats) - { - $cattable = GetTablePrefix()."CategoryItems"; - $t = $this->SourceTable; - $sql = "SELECT *,CategoryId FROM $t INNER JOIN $cattable ON $cattable.ItemResourceId=$t.ResourceId"; - } - else - $sql = "SELECT * FROM ". $this->SourceTable; - if(trim($whereClause)!="") - { - if(isset($whereClause)) - $sql = sprintf('%s WHERE %s',$sql,$whereClause); - } - if(strlen($orderByClause)>0) - { - if(substr($orderByClause,0,8)=="ORDER BY") - { - $sql .= " ".$orderByClause; - } - else - { - $sql .= " ORDER BY $orderByClause"; - } - } - - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo $sql."
\n"; - - return $this->Query_Item($sql, null, $fix_method); - } - - function GetPerPage() - { - // return category perpage - global $objConfig; - $PerPage = $objConfig->Get( $this->PerPageVar ); - if( !is_numeric($PerPage) ) $PerPage = $this->DefaultPerPage ? $this->DefaultPerPage : 10; - return $PerPage; - } - - function FixInvalidPage($fix_method = 'set_first') - { - // in case if current page > total page count, - // then set current page to last possible "set_last" - // or first possible "set_first" - $PerPage = $this->GetPerPage(); - $NumPages = ceil( $this->GetNumPages($PerPage) ); -/* - echo "=====
"; - echo "Class ".get_class($this).": Page ".$this->Page." of $NumPages
"; - echo "PerPage: $PerPage
"; - echo "Items Queries: ".$this->QueryItemCount."
"; - echo "=====
"; -*/ - if($this->Page > $NumPages) - { - switch($fix_method) - { - case 'set_first': - $this->Page = 1; - //echo "Move 2 First (class ".get_class($this).")
"; - break; - case 'set_last': - $this->Page = $NumPages; - //echo "Move 2 Last (class ".get_class($this).")
"; - break; - } - $this->SaveNewPage(); - } - } - - function SaveNewPage() - { - // redefine in each list, should save to env array new page value - - } - - function GetPageLinkList($dest_template=NULL,$page = "",$PagesToList=10, $HideEmpty=TRUE,$EnvSuffix = '') - { - global $objConfig, $var_list_update, $var_list; - - - $v= $this->PageEnvar; - - global ${$v}; - - if(!strlen($page)) - $page = GetIndexURL(); - - $PerPage = $objConfig->Get($this->PerPageVar); - if($PerPage<1) - $PerPage=20; - $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==0 || !is_numeric($this->Page)) - $this->Page=1; - 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) - { - ${$v}[$this->PageEnvarIndex] = $this->Page-$PagesToList; - - $prev_url = $page."?env=".BuildEnv().$EnvSuffix; - $o .= "<<"; - } - - for($p=$StartPage;$p<=$EndPage;$p++) - { - if($p!=$this->Page) - { - ${$v}[$this->PageEnvarIndex]=$p; - $href = $page."?env=".BuildEnv().$EnvSuffix; - $o .= " $p "; - } - else - { - $o .= " $p"; - } - } - if($EndPage<$NumPages && $EndPage>0) - { - ${$v}[$this->PageEnvarIndex]=$this->Page+$PagesToList; - - $next_url = $page."?env=".BuildEnv().$EnvSuffix; - $o .= " >>"; - } - unset(${$v}[$this->PageEnvarIndex],$var_list_update["t"] ); - return $o; - } - - function GetAdminPageLinkList($url) - { - global $objConfig; - - $update =& $GLOBALS[$this->PageEnvar]; // env_var_update - - // insteresting stuff :) - if(!$this->PerPageVar) $this->PerPageVar = "Perpage_Links"; - - $PerPage = $objConfig->Get($this->PerPageVar); - if($PerPage < 1) $PerPage = 20; - - $NumPages = ceil($this->GetNumPages($PerPage)); - - //echo $this->CurrentPage." of ".$NumPages." Pages"; - - if($this->Page > $NumPages) $this->Page = $NumPages; - - $StartPage = $this->Page - 5; - if($StartPage < 1) $StartPage = 1; - $EndPage = $StartPage + 9; - if($EndPage > $NumPages) - { - $EndPage = $NumPages; - $StartPage = $EndPage-9; - if($StartPage < 1) $StartPage = 1; - } - - $o = ''; - - if($StartPage > 1) - { - $update[$this->PageEnvarIndex]= $this->Page - 10; - $prev_url = $url.'?env='.BuildEnv(); - $o .= '<<'; - } - - - for($p = $StartPage; $p <= $EndPage; $p++) - { - if($p != $this->Page) - { - $update[$this->PageEnvarIndex] = $p; - $href = $url.'?env='.BuildEnv(); - $o .= ' '.$p.' '; - } - else - { - $o .= ''.$p.''; - } - } - if($EndPage < $NumPages) - { - $update[$this->PageEnvarIndex] = $this->Page + 10; - $next_url = $url.'?env='.BuildEnv(); - $o .= ' >>'; - } - unset( $update[$this->PageEnvarIndex] ); - return $o; - } -} - -function ParseClipboard($clip) -{ - $ret = array(); - - $parts = explode(".",$clip,3); - $command = $parts[0]; - $table = $parts[1]; - $prefix = GetTablePrefix(); - if(substr($table,0,strlen($prefix))==$prefix) - $table = substr($table,strlen($prefix)); - - $subparts = explode("=",$parts[2],2); - $idfield = $subparts[0]; - $idlist = $subparts[1]; - $cmd = explode("-",$command); - $ret["command"] = $cmd[0]; - $ret["source"] = $cmd[1]; - $ret["table"] = $table; - $ret["idfield"] = $idfield; - $ret["ids"] = $idlist; - //print_pre($ret); - return $ret; -} - -function UpdateCategoryItems($item,$NewCatList,$PrimaryCatId = false) -{ - global $objCatList; - - $CurrentList = explode(",",$item->CategoryMemberList()); - $del_list = array(); - $ins_list = array(); - - - if(!is_array($NewCatList)) - { - if(strlen(trim($NewCatList))==0) - $NewCatList = $objCatList->CurrentCategoryID(); - - $NewCatList = explode(",",$NewCatList); - } - //print_r($NewCatList); - - for($i=0;$iAddToCategory($cat); - } - for($i=0;$iRemoveFromCategory($cat); - } - if($PrimaryCatId !== false) $item->SetPrimaryCategory($PrimaryCatId); -} - -class clsCatItemList extends clsItemList -{ - var $PerPageVarLong; - var $PerPageShortVar; - var $Query_SortField; - var $Query_SortOrder; - var $ItemType; - - function clsCatItemList() - { - $this->ClsItemList(); - $this->Query_SortField = array(); - $this->Query_SortOrder = array(); - } - - 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"; - } - - if(count($this->Query_SortField)>0) - { - for($x=0; $xQuery_SortField); $x++) - { - $FieldVar = $this->Query_SortField[$x]; - $OrderVar = $this->Query_SortOrder[$x]; - - if(is_object($objSession)) - { - $FieldVarData = $objSession->GetPersistantVariable($FieldVar); - if(strlen($FieldVarData)>0) - { - $Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". - $objSession->GetPersistantVariable($OrderVar)); - } - } - } - } - - if(count($Orders)>0) - { - $OrderBy = "ORDER BY ".implode(", ",$Orders); - } - else - $OrderBy=""; - - return $OrderBy; - } - - function AddSortField($SortField, $SortOrder) - { - if(strlen($SortField)) - { - $this->Query_SortField[] = $SortField; - $this->Query_SortOrder[] = $SortOrder; - } - } - - function ClearSortFields() - { - $this->Query_SortField = array(); - $this->Query_SortOrder = array(); - } - - /* skeletons in this closet */ - - function GetNewValue($CatId=NULL) - { - return 0; - } - - function GetPopValue($CategoryId=NULL) - { - return 0; - } - - /* end of skeletons */ - - 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 $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) "; - $sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) "; - $sql .="INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) "; - $sql .="WHERE ($acl AND PermId=$VIEW AND $cattable.PrimaryCat=1 AND $CategoryTable.Status=1) "; - - if(strlen($AdditonalWhere)>0) - { - $sql .= "AND (".$AdditonalWhere.")"; - } - - return $sql; - } - - function SqlCategoryList($attribs = array()) - { - $CatTable = GetTablePrefix()."CategoryItems"; - $t = $this->SourceTable; - - $sql = "SELECT *,$CatTable.CategoryId FROM $t INNER JOIN $CatTable ON $CatTable.ItemResourceId=$t.ResourceId "; - $sql .="WHERE ($CatTable.CategoryId=".$catid." AND $t.Status=1)"; - - return $sql; - } - - - function CategoryCount($attribs=array()) - { - global $objCatList, $objCountCache; - - $cat = $attribs["_catid"]; - if(!is_numeric($cat)) - { - $cat = $objCatList->CurrentCategoryID(); - } - if((int)$cat>0) - $c = $objCatList->GetCategory($cat); - - $CatTable = GetTablePrefix()."CategoryItems"; - $t = $this->SourceTable; - - $sql = "SELECT count(*) as MyCount FROM $t INNER JOIN $CatTable ON ($CatTable.ItemResourceId=$t.ResourceId) "; - if($attribs["_subcats"]) - { - $ctable = $objCatList->SourceTable; - $sql .= "INNER JOIN $ctable ON ($CatTable.CategoryId=$ctable.CategoryId) "; - $sql .= "WHERE (ParentPath LIKE '".$c->Get("ParentPath")."%' "; - if(!$attribs["_countcurrent"]) - { - $sql .=" AND $ctable.CategoryId != $cat) "; - } - else - $sql .=") "; - } - else - $sql .="WHERE ($CatTable.CategoryId=".$cat." AND $t.Status=1) "; - - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $sql .= "AND ($t.CreatedOn>=$today) "; - } - //echo $sql."

\n"; - $rs = $this->adodbConnection->Execute($sql); - $ret = ""; - if($rs && !$rs->EOF) - $ret = (int)$rs->fields["MyCount"]; - return $ret; - } - - function SqlGlobalCount($attribs=array()) - { - global $objSession; - - $p = $this->BasePermission.".VIEW"; - $t = $this->SourceTable; - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $where = "($t.CreatedOn>=$today)"; - } - - if($attribs["_grouponly"]) - { - $GroupList = $objSession->Get("GroupList"); - } - else - $GroupList = NULL; - - $sql = $this->GetCountSQL($p,NULL,$GroupList,$where); - return $sql; - } - - function DoGlobalCount($attribs) - { - global $objCountCache; - - $cc = $objCountCache->GetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)$attribs["_today"], 3600); - if(!is_numeric($cc)) - { - $sql = $this->SqlGlobalCount($attribs); - $ret = QueryCount($sql); - $objCountCache->SetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)$attribs["_today"],$ret); - } - else - $ret = $cc; - return $ret; - } - - - function CacheListExtraId($ListType) - { - global $objSession; - - if(!strlen($ListType)) - $ListType="_"; - switch($ListType) - { - case "_": - $ExtraId = $objSession->Get("GroupList"); - break; - case "category": - $ExtraId = $objSession->Get("GroupList"); - break; - case "myitems": - $ExtraId = $objSession->Get("PortalUserId"); - break; - case "hot": - $ExtraId = $objSession->Get("GroupList"); - break; - case "pop": - $ExtraId = $objSession->Get("GroupList"); - break; - case "pick": - $ExtraId = $objSession->Get("GroupList"); - break; - case "favorites": - $ExtraId = $objSession->Get("PortalUserId"); - break; - case "new": - $ExtraId = $objSession->Get("GroupList"); - break; - } - return $ExtraId; - } - - function CacheListType($ListType) - { - if(!strlen($ListType)) - $ListType="_"; - switch($ListType) - { - case "_": - $ListTypeId = 0; - break; - case "category": - $ListTypeId = 1; - break; - case "myitems": - $ListTypeId = 2; - break; - case "hot": - $ListTypeId = 3; - break; - case "pop": - $ListTypeId = 4; - break; - case "pick": - $ListTypeId = 5; - break; - case "favorites": - $ListTypeId = 6; - break; - case "new": - $ListTypeId = 8; - break; - } - return $ListTypeId; - } - - function PerformItemCount($attribs=array()) - { - global $objCountCache, $objSession; - - $ret = ""; - $ListType = $attribs["_listtype"]; - if(!strlen($ListType)) - $ListType="_"; - - $ListTypeId = $this->CacheListType($ListType); - //echo "ListType: $ListType ($ListTypeId)
\n"; - $ExtraId = $this->CacheListExtraId($ListType); - switch($ListType) - { - case "_": - $ret = $this->DoGlobalCount($attribs); - break; - case "category": - $ret = $this->CategoryCount($attribs); - break; - case "myitems": - $sql = $this->SqlMyItems($attribs); - break; - case "hot": - $sql = $this->SqlHotItems($attribs); - break; - case "pop": - $sql = $this->SqlPopItems($attribs); - break; - case "pick": - $sql = $this->SqlPickItems($attribs); - break; - case "favorites": - $sql = $this->SqlFavorites($attribs); - break; - case "search": - $sql = $this->SqlSearchItems($attribs); - break; - case "new": - $sql = $this->SqlNewItems($attribs); - break; - } - //echo "SQL: $sql
"; - if(strlen($sql)) - { - if(is_numeric($ListTypeId)) - { - $cc = $objCountCache->GetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"], 3600); - - if(!is_numeric($cc) || $attribs['_nocache'] == 1) - { - $ret = QueryCount($sql); - $objCountCache->SetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"],$ret); - } - else - $ret = $cc; - } - else - $ret = QueryCount($sql); - } - - return $ret; - } - - function GetJoinedSQL($PermName, $CatId=NULL, $AdditionalWhere="") - { - global $objSession, $objPermissions; - - $ltable = $this->SourceTable; - $acl = $objSession->GetACLClause(); - $cattable = GetTablePrefix()."CategoryItems"; - $CategoryTable = GetTablePrefix()."Category"; - $ptable = GetTablePrefix()."PermCache"; - $VIEW = $objPermissions->GetPermId($PermName); - $sql ="INNER JOIN $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) "; - $sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) "; - $sql .= "INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) "; - $sql .="WHERE ($acl AND PermId=$VIEW AND PrimaryCat=1 AND $CategoryTable.Status=1) "; - - if(is_numeric($CatId)) - { - $sql .= " AND ($CategoryTable.CategoryId=$CatId) "; - } - if(strlen($AdditionalWhere)>0) - { - $sql .= "AND (".$AdditionalWhere.")"; - } - return $sql; - } - - function CountFavorites($attribs) - { - if($attribs["_today"]) - { - global $objSession, $objConfig, $objPermissions; - - $acl = $objSession->GetACLClause(); - $favtable = GetTablePrefix()."Favorites"; - $ltable = $this->SourceTable; - $cattable = GetTablePrefix()."CategoryItems"; - $CategoryTable = GetTablePrefix()."Category"; - $ptable = GetTablePrefix()."PermCache"; - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - - $where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1"; - $where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType; - $p = $this->BasePermission.".VIEW"; - - $sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) "; - $sql .= $this->GetJoinedSQL($p,NULL,$where); - $ret = QueryCount($sql); - } - else - { - if (!$this->ListType == "favorites") - { - $this->ListType = "favorites"; - $this->LoadFavorites($attribs); - $ret = $this->QueryItemCount; - } - else - $ret = $this->QueryItemCount; - } - return $ret; - } - - - - function CountPickItems($attribs) - { - if (!$this->ListType == "pick") - { - $this->ListType = "pick"; - $this->LoadPickItems($attribs); - $ret = $this->QueryItemCount; - } - else - $ret = $this->QueryItemCount; - - return $ret; - } - - function CountMyItems($attribs) - { - if (!$this->ListType == "myitems") - { - $this->ListType = "myitems"; - $this->LoadMyItems($attribs); - $ret = $this->QueryItemCount; - } - else - $ret = $this->QueryItemCount; - - return $ret; - } - - function CountHotItems($attribs) - { - if (!$this->ListType == "hotitems") - { - $this->ListType = "hotitems"; - $this->LoadHotItems($attribs); - $ret = $this->QueryItemCount; - } - else - $ret = $this->QueryItemCount; - - return $ret; - } - - function CountNewItems($attribs) - { - if (!$this->ListType == "newitems") - { - $this->ListType = "newitems"; - $this->LoadNewItems($attribs); - $ret = $this->QueryItemCount; - } - else - $ret = $this->QueryItemCount; - - return $ret; - } - - function CountPopItems($attribs) - { - if (!$this->ListType == "popitems") - { - $this->ListType = "popitems"; - $this->LoadPopItems($attribs); - $ret = $this->QueryItemCount; - } - else - $ret = $this->QueryItemCount; - - return $ret; - } - - - function CountSearchItems($attribs) - { - if (!$this->ListType == "search") - { - $this->ListType = "search"; - $this->LoadSearchItems($attribs); - $ret = $this->QueryItemCount; - } - else - $ret = $this->QueryItemCount; - - return $ret; - } - - function SqlFavorites($attribs) - { - global $objSession, $objConfig, $objPermissions; - - $acl = $objSession->GetACLClause(); - $favtable = GetTablePrefix()."Favorites"; - $ltable = $this->SourceTable; - $cattable = GetTablePrefix()."CategoryItems"; - $CategoryTable = GetTablePrefix()."Category"; - $ptable = GetTablePrefix()."PermCache"; - - $where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1"; - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType; - } - $p = $this->BasePermission.".VIEW"; - - $sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) "; - $sql .= $this->GetJoinedSQL($p,NULL,$where); - - - $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); - $sql .= " ".$OrderBy; - return $sql; - } - - function LoadFavorites($attribs) - { - global $objSession, $objCountCache; - - $sql = $this->SqlFavorites($attribs); - - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($sql,ENT_NOQUOTES)."
\n"; - if($attribs["_shortlist"]) - { - $this->PerPageVar = $this->PerPageShortVar; - } - else - $this->PerPageVar = $this->PerPageVarLong; - - $CachedCount = $objCountCache->GetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],3600); - if(!is_numeric($CachedCount)) - { - $this->QueryItemCount = QueryCount($sql); - $objCountCache->SetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],$this->QueryItemCount); - } - else - $this->QueryItemCount = (int)$CachedCount; - - return $this->Query_Item($sql); - } - - function SqlPickItems($attribs) - { - global $objSession, $objCatList; - - $catid = (int)$attribs["_catid"]; - $scope = (int)$attribs["_scope"]; - //$JoinCats = (int)$attribs["_catinfo"] || $scope; - - $TableName = $this->SourceTable; - if($scope) - { - if (!$catid) - { - $catid = $objCatList->CurrentCategoryID(); - } - $where = "CategoryId =".$catid." AND ".$TableName.".EditorsPick=1 AND ".$TableName.".Status=1"; - } - else - { - $where = $TableName.".EditorsPick=1 AND ".$TableName.".Status=1 "; - $catid=NULL; - } - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $where .= " AND ($TableName.CreatedOn>=$today)"; - } - $CategoryTable = GetTablePrefix()."Category"; - $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; - $p = $this->BasePermission.".VIEW"; - $sql .= $this->GetJoinedSQL($p,$CatUd,$where); - - $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); - $sql .= " ".$OrderBy; - return $sql; - } - - function LoadPickItems($attribs) - { - global $objSession, $objCountCache; - - $sql = $this->SqlPickItems($attribs); - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($sql,ENT_NOQUOTES)."
\n"; - - if($attribs["_shortlist"]) - { - $this->PerPageVar = $this->PerPageShortVar; - } - else - $this->PerPageVar = $this->PerPageVarLong; - - $CachedCount = $objCountCache->GetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$attribs["_today"],3600); - if(!is_numeric($CachedCount)) - { - $this->QueryItemCount= QueryCount($sql); - $objCountCache->SetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$attribs["_today"],$this->QueryItemCount); - } - else - $this->QueryItemCount=$CachedCount; - - return $this->Query_Item($sql); - } - - function SqlMyItems($attribs= array()) - { - global $objSession; - - $TableName = $this->SourceTable; - $where = " ".$TableName.".Status>-1 AND ".$TableName.".CreatedById=".$objSession->Get("PortalUserId"); - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $where .= " AND ($TableName.CreatedOn>=$today)"; - } - $CategoryTable = GetTablePrefix()."Category"; - $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; - $p = $this->BasePermission.".VIEW"; - $sql .= $this->GetJoinedSQL($p,$CatUd,$where); - - $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); - $sql .= " ".$OrderBy; - - return $sql; - } - - function LoadMyItems($attribs=array()) - { - global $objSession,$objCountCache; - $sql = $this->SqlMyItems($attribs); - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($sql,ENT_NOQUOTES)."
\n"; - if($attribs["_shortlist"]) - { - $this->PerPageVar = $this->PerPageShortVar; - } - else - $this->PerPageVar = $this->PerPageVarLong; - - $CachedCount = $objCountCache->GetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],3600); - if(!is_numeric($CachedCount)) - { - $this->QueryItemCount= QueryCount($sql); - $objCountCache->SetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],$this->QueryItemCount); - } - else - $this->QueryItemCount=$CachedCount; - - return $this->Query_Item($sql); - } - - function SqlNewItems($attribs = array()) - { - global $objSession, $objCatList; - - $catid = (int)$attribs["_catid"]; - $scope = (int)$attribs["_scope"]; - //$JoinCats = (int)$attribs["_catinfo"] || $scope; - - $TableName = $this->SourceTable; - if($attribs["_today"]) - { - $cutoff = mktime(0,0,0,date("m"),date("d"),date("Y")); - } - else - { - if($scope) - { - if (!$catid) - { - $catid = $objCatList->CurrentCategoryID(); - } - $cutoff = $this->GetNewValue($catid); - } - else - $cutoff = $this->GetNewValue(); - } - if($scope) - { - if (!$catid) - { - $catid = $objCatList->CurrentCategoryID(); - } - - $where = "CategoryId =".$catid." AND ((".$TableName.".CreatedOn >=".$cutoff." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 "; - } - else - { - $where = "((".$TableName.".CreatedOn >=".$this->GetNewValue()." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 "; - } - - $CategoryTable = GetTablePrefix()."Category"; - $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; - $p = $this->BasePermission.".VIEW"; - $sql .= $this->GetJoinedSQL($p,$CatUd,$where); - - $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); - $sql .= " ".$OrderBy; - return $sql; - } - - function LoadNewItems($attribs) - { - global $objSession,$objCountCache; - - $sql = $this->SqlNewItems($attribs); - - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($sql,ENT_NOQUOTES)."
\n"; - if($attribs["_shortlist"]) - { - $this->PerPageVar = $this->PerPageShortVar; - } - else - $this->PerPageVar = $this->PerPageVarLong; - - $CachedCount = $objCountCache->GetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],3600); - if(!is_numeric($CachedCount)) - { - $this->QueryItemCount= QueryCount($sql); - $objCountCache->SetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],$this->QueryItemCount); - } - else - $this->QueryItemCount=$CachedCount; - - - return $this->Query_Item($sql); - } - - function SqlPopItems($attribs) - { - global $objSession, $objCatList; - - $catid = (int)$attribs["_catid"]; - $scope = (int)$attribs["_scope"]; - //$JoinCats = (int)$attribs["_catinfo"] || $scope; - - $TableName = $this->SourceTable; - - if($scope) - { - if (!$catid) - { - $catid = $objCatList->CurrentCategoryID(); - } - $where = "CategoryId =".$catid." AND ((".$TableName.".Hits >=".$this->GetLinkPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1"; - } - else - { - $where = "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 "; - - $where = "((".$TableName.".Hits >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 "; - } - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $where .= " AND ($TableName.CreatedOn>=$today)"; - } - $CategoryTable = GetTablePrefix()."Category"; - $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; - $p = $this->BasePermission.".VIEW"; - $sql .= $this->GetJoinedSQL($p,$catid,$where); - - $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); - $sql .= " ".$OrderBy; - - return $sql; - } - - function LoadPopItems($attribs) - { - global $objSession,$objCountCache; - $sql = $this->SqlPopItems($attribs); - - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($sql,ENT_NOQUOTES)."
\n"; - if($attribs["_shortlist"]) - { - $this->PerPageVar = $this->PerPageShortVar; - } - else - $this->PerPageVar = $this->PerPageVarLong; - - $CachedCount = $objCountCache->GetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],3600); - if(!is_numeric($CachedCount)) - { - $this->QueryItemCount= QueryCount($sql); - $objCountCache->SetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],$this->QueryItemCount); - } - else - $this->QueryItemCount=$CachedCount; - - return $this->Query_Item($sql); - } - - function SqlHotItems($attribs) - { - global $objSession, $objCatList; - - $catid = (int)$attribs["_catid"]; - $scope = (int)$attribs["_scope"]; - -// $JoinCats = (int)$attribs["_catinfo"] || $scope; - - $TableName = $this->SourceTable; - - $OrderBy = $TableName.".CachedRating DESC"; - - if($scope) - { - if (!$catid) - { - $catid = $objCatList->CurrentCategoryID(); - } - $where = "CategoryId =".$catid." AND ((".$TableName.".CachedRating >=".$this->GetHotValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1"; - } - else - { - $where = "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 "; - } - - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $where .= " AND ($TableName.CreatedOn>=$today)"; - } - $CategoryTable = GetTablePrefix()."Category"; - $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; - $p = $this->BasePermission.".VIEW"; - $CatId = !$scope? NULL : $catid; - $sql .= $this->GetJoinedSQL($p,$CatId,$where); - - if(strlen($OrderBy)) - $sql .= " ORDER BY $OrderBy "; - - return $sql; - } - - function LoadHotItems($attribs) - { - global $objSession,$objCountCache; - - $sql = $this->SqlHotItems($attribs); - if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($sql,ENT_NOQUOTES)."
\n"; - - if($attribs["_shortlist"]) - { - $this->PerPageVar = $this->PerPageShortVar; - } - else - $this->PerPageVar = $this->PerPageVarLong; - - $CachedCount = $objCountCache->GetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"], 0); - if(!is_numeric($CachedCount)) - { - $this->QueryItemCount= QueryCount($sql); - $objCountCache->SetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"],$this->QueryItemCount); - } - else - $this->QueryItemCount=$CachedCount; - - return $this->Query_Item($sql); - } - - function SqlSearchItems($attribs = array()) - { - global $objConfig, $objItemTypes, $objSession, $objPermissions, $CountVal; - - $acl = $objSession->GetACLClause(); - $this->Clear(); - //$stable = "ses_".$objSession->GetSessionKey()."_Search"; - $stable = $objSession->GetSearchTable(); - $ltable = $this->SourceTable; - $catitems = GetTablePrefix()."CategoryItems"; - $cattable = GetTablePrefix()."Category"; - $ptable = GetTablePrefix()."PermCache"; - $p = $this->BasePermission.".VIEW"; - $i = new $this->classname(); - - $sql = "SELECT $cattable.CategoryId,$cattable.CachedNavbar,$ltable.*, Relevance FROM $stable "; - $sql .= "INNER JOIN $ltable ON ($stable.ItemId=$ltable.".$i->id_field.") "; - - $where = "ItemType=".$this->ItemType." AND $ltable.Status=1"; - - $sql .= $this->GetJoinedSQL($p,NULL,$where); - $sql .= " ORDER BY EdPick DESC,Relevance DESC "; - - $tmp = $this->QueryOrderByClause(FALSE,TRUE,TRUE); - $tmp = substr($tmp,9); - if(strlen($tmp)) - { - $sql .= ", ".$tmp." "; - } - return $sql; - } - - function LoadSearchItems($attribs = array()) - { - global $CountVal, $objSession; - //echo "Loading ".get_class($this)." Search Items
"; - $sql = $this->SqlSearchItems($attribs); - //echo "$sql
"; - $this->Query_Item($sql); - $Keywords = GetKeywords($objSession->GetVariable("Search_Keywords")); - //echo "SQL Loaded ItemCount (".get_class($this).'): '.$this->NumItems().'
'; - for($i = 0; $i < $this->NumItems(); $i++) - { - $this->Items[$i]->Keywords = $Keywords; - } - if(is_numeric($CountVal[$this->ItemType])) - { - $this->QueryItemCount = $CountVal[$this->ItemType]; - //echo "CACHE:
"; print_r($CountVal); echo "

"; - } - else - { - $this->QueryItemCount = QueryCount($sql); - //echo "SQL: ".$sql."

"; - $CountVal[$this->ItemType] = $this->QueryItemCount; - } - - } - - function PasteFromClipboard($TargetCat,$NameField="") - { - global $objSession,$objCatList; - - $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;$iGetItem($item_ids[$i]); - if(!$IsCopy) // paste to other category then current - { - $item->MoveToCategory($ClipBoard["source"],$TargetCat); - $clip = str_replace("CUT","COPY",$clip); - $objSession->SetVariable("ClipBoard",$clip); - } - else - { - $item->CopyToNewResource($TargetCat,$NameField); // create item copy, but with new ResourceId - $item->AddToCategory($TargetCat); - UpdateCategoryCount($item->type,$TargetCat); - - } - } - } - } - - function AdminPrintItems($template) - { - // prints item listing for admin (browse/advanced view) tabs - $o = ''; - - $i = 1; - - $topleft = 0; - $topright = 0; - $rightcount = 0; - $total_items = $this->NumItems(); - $topleft = ceil($total_items / 2); - $topright = $total_items - $topleft; - - for($x = 0; $x < $topleft; $x++) - { - //printingleft - $item = $this->Items[$x]; - if ($i > 2) - { - $o .= "\n"; - $i = 1; - } - $o .= $item->AdminParseTemplate($template); - $i++; - - //printingright - if ($rightcount < $topright && ( ($x + $topleft) < $total_items) ) - { - $item = $this->Items[ $x + $topleft ]; - if ($i > 2) - { - $o.="\n"; - $i = 1; - } - $o .= $item->AdminParseTemplate($template); - $i++; - $rightcount++; - } - } - $o .= "\n
\n"; - - return $o; - } - -} - -// -------------- NEW CLASSES ----------------------- - -class DBList { - - // table related attributes - var $db = null; - var $table_name = ''; - var $LiveTable = ''; - var $EditTable = ''; - - - // record related attributes - var $records = Array(); - var $record_count = 0; - var $cur_rec = -1; // "-1" means no records, or record index otherwise - - // query related attributes - var $SelectSQL = "SELECT * FROM %s"; - - function DBList() - { - // use $this->SetTable('live', 'table name'); - // in inherited constructors to set table for list - $this->db =&GetADODBConnection(); - } - - function SetTable($action, $table_name = null) - { - // $action = {'live', 'restore','edit'} - switch($action) - { - case 'live': - $this->LiveTable = $table_name; - $this->table_name = $this->LiveTable; - break; - case 'restore': - $this->table_name = $this->LiveTable; - break; - case 'edit': - global $objSession; - $this->table_name = $objSession->GetEditTable($this->LiveTable); - break; - } - } - - function Clear() - { - // no use of this method at a time :) - $this->records = Array(); - $this->record_count = 0; - $this->cur_rec = -1; - } - - function Query() - { - // query list - $sql = sprintf($this->SelectSQL, $this->table_name); - echo "SQL: $sql
"; - $rs =& $this->db->Execute($sql); - - if( $this->db->ErrorNo() == 0 ) - { - $this->records = $rs->GetRows(); - $this->record_count = count($this->records); - //$this->cur_rec = $this->record_count ? 0 : -1; - } - else - return false; - } - - function ProcessList($callback_method) - { - // process list using user-defined method called - // with one parameter - current record fields - // (associative array) - if($this->record_count > 0) - { - $this->cur_rec = 0; - while($this->cur_rec < $this->record_count) - { - if( method_exists($this, $callback_method) ) - $this->$callback_method( $this->GetCurrent() ); - $this->cur_rec++; - } - } - } - - function &GetCurrent() - { - // return currently processed record (with change ability) - return ($this->cur_rec != -1) ? $this->records[$this->cur_rec] : false; - } - - function GetDBField($field_name) - { - $rec =& $this->GetCurrent(); - return is_array($rec) && isset($rec[$field_name]) ? $rec[$field_name] : false; - } -} - - -?> +clsItemDB(); + $this->Parser = new clsTemplateList($TemplateRoot); + $this->AdminParser = new clsAdminTemplateList(); + } + +/* function ParseObject($element) + { + $extra_attribs = ExtraAttributes($element->attributes); + if(strtolower($element->name)==$this->TagPrefix) + { + $field = strtolower($element->attributes["_field"]); + $tag = $this->TagPrefix."_".$field; + $ret = $this->parsetag($tag); + } + return $ret; + } +*/ + function ParseTimeStamp($d,$attribs=array()) + { + if( isset($attribs["_tz"]) ) + { + $d = GetLocalTime($d,$objSession->Get("tz")); + } + $part = isset($attribs["_part"]) ? strtolower($attribs["_part"]) : ''; + if(strlen($part)) + { + $ret = ExtractDatePart($part,$d); + } + else + { + if($d<=0) + { + $ret = ""; + } + else + $ret = LangDate($d); + } + return $ret; + } + + function ParseObject($element) + { + global $objConfig, $objCatList, $var_list_update, $var_list, $n_var_list_update, $m_var_list_update; + + $extra_attribs = ExtraAttributes($element->attributes); + $ret = ""; + + if ($this->TagPrefix == "email" && strtolower($element->name) == "touser") { + $this->TagPrefix = "touser"; + } + + if(strtolower($element->name)==$this->TagPrefix) + { + $field = strtolower($element->attributes["_field"]); + switch($field) + { + case "id": + $ret = $this->Get($this->id_field); + break; + case "resourceid": + if(!$this->NoResourceId) + $ret = $this->Get("ResourceId"); + break; + case "category": + $c = $objCatList->GetItem($this->Get("CategoryId")); + if(is_object($c)) + { + $ret = $c->parsetag($element->attributes["_cattag"]); + } + break; + case "priority": + if($this->Get("Priority")!=0) + { + $ret = (int)$this->Get("Priority"); + } + else + $ret = ""; + break; + case "link": + if(method_exists($this,"ItemURL")) + { + $ret = $this->ItemURL($element->attributes["_template"],FALSE,""); + } + break; + case "cat_link": + if(method_exists($this,"ItemURL")) + { + $ret = $this->ItemURL($element->attributes["_template"],TRUE,""); + } + break; + case "fullpath": + $ret = $this->Get("CachedNavbar"); + if(!strlen($ret)) + { + if(is_numeric($this->Get("CategoryId"))) + { + $c = $objCatList->GetItem($this->Get("CategoryId")); + if(is_object($c)) + $ret = $c->Get("CachedNavbar"); + } + else + { + if(method_exists($this,"GetPrimaryCategory")) + { + $cat = $this->GetPrimaryCategory(); + $c = $objCatList->GetItem($cat); + if(is_object($c)) + $ret = $c->Get("CachedNavbar"); + } + } + } + // $ret = $this->HighlightText($ret); + break; + + case "relevance": + $style = $element->attributes["_displaymode"]; + if(!strlen($style)) + $style = "numerical"; + switch ($style) + { + case "numerical": + $ret = (100 * LangNumber($this->Get("Relevance"),1))."%"; + break; + case "bar": + $OffColor = $element->attributes["_offbackgroundcolor"]; + $OnColor = $element->attributes["_onbackgroundcolor"]; + $percentsOff = (int)(100 - (100 * $this->Get("Relevance"))); if ($percentsOff) + { + $percentsOn = 100 - $percentsOff; + $ret = ""; + } + else + $ret = ""; + break; + case "graphical": + $OnImage = $element->attributes["_onimage"]; + if (!strlen($OnImage)) + break; + // Get image extension + $image_data = explode(".", $OnImage); + $image_ext = $image_data[count($image_data)-1]; + unset($image_data[count($image_data)-1]); + $rel = (10 * LangNumber($this->Get("Relevance"),1)); + $OnImage1 = join(".", $image_data); + + if ($rel) + $img_src = $OnImage1."_".$rel.".".$image_ext; + else + $img_src = $OnImage; + + $ret = "\"".(10*$rel)."\""; + break; + } + + break; + + case "rating": + $style = $element->GetAttributeByName("_displaymode"); + if(!strlen($style)) + $style = "numerical"; + switch($style) + { + case "numerical": + $ret = LangNumber($this->Get("CachedRating"),1); + break; + case "text": + $ret = RatingText($this->Get("CachedRating")); + break; + case "graphical": + $OnImage = $element->attributes["_onimage"]; + $OffImage = $element->attributes["_offimage"]; + $images = RatingTickImage($this->Get("CachedRating"),$OnImage,$OffImage); + + for($i=1;$i<=count($images);$i++) + { + $url = $images[$i]; + if(strlen($url)) + { + $ret .= ""; + $ret .= $element->attributes["_separator"]; + } + } + break; + } + break; + case "reviews": + $today = FALSE; + + if(method_exists($this,"ReviewCount")) + { + if($element->GetAttributeByName("_today")) + $today = TRUE; + $ret = $this->ReviewCount($today); + } + else + $ret = ""; + + break; + case "votes": + $ret = (int)$this->Get("CachedVotesQty"); + break; + + case "favorite": + if(method_exists($this,"IsFavorite")) + { + if($this->IsFavorite()) + { + $ret = $element->attributes["_label"]; + if(!strlen($ret)) + $ret = "lu_favorite"; + $ret = language($ret); + } + else + $ret = ""; + } + break; + case "new": + if(method_exists($this,"IsNewItem")) + { + if($this->IsNewItem()) + { + $ret = $element->GetAttributeByName('_label'); + if(!strlen($ret)) + $ret = "lu_new"; + $ret = language($ret); + } + else + $ret = ""; + } + break; + case "pop": + if(method_exists($this,"IsPopItem")) + { + if($this->IsPopItem()) + { + $ret = $element->attributes["_label"]; + if(!strlen($ret)) + $ret = "lu_pop"; + $ret = language($ret); + } + else + $ret = ""; + } + break; + case "hot": + if(method_exists($this,"IsHotItem")) + { + if($this->IsHotItem()) + { + $ret = $element->GetAttributeByName("_label"); + if(!strlen($ret)) + $ret = "lu_hot"; + $ret = language($ret); + } + else + $ret = ""; + } + break; + case "pick": + if($this->Get("EditorsPick")==1) + { + $ret = $element->GetAttributeByName('_label'); + if(!strlen($ret)) + $ret = "lu_pick"; + $ret = language($ret); + } + else + $ret = ""; + break; + case "admin_icon": + if(method_exists($this,"StatusIcon")) + { + if($element->GetAttributeByName("fulltag")) + { + $ret = "StatusIcon()."\">"; + } + else + $ret = $this->StatusIcon(); + } + break; + case "custom": + if(method_exists($this,"GetCustomFieldValue")) + { + $field = $element->attributes["_customfield"]; + $default = $element->attributes["_default"]; + if (strlen($field)) + $ret = $this->GetCustomFieldValue($field,$default); + } + break; + case "image": + $default = $element->attributes["_primary"]; + $name = $element->attributes["_name"]; + + if(strlen($name)) + { + $img = $this->GetImageByName($name); + } + else + { + if($default) + $img = $this->GetDefaultImage(); + } + + if(is_object($img)) + { + + if(strlen($element->attributes["_imagetemplate"])) + { + $ret = $img->ParseTemplate($element->attributes["_imagetemplate"]); + break; + } + else + { + if($element->attributes["_thumbnail"]) + { + $url = $img->parsetag("thumb_url"); + } + else + { + + if(!$element->attributes["_nothumbnail"]) + { + $url = $img->parsetag("image_url"); + } + else + { + $url = $img->FullURL(TRUE,""); + } + } + } + } + else + { + $url = $element->attributes["_defaulturl"]; + + } + + if($element->attributes["_imagetag"]) + { + if(strlen($url)) + { + $ret = ""; + } + else + $ret = ""; + } + else + $ret = $url; + break; + default: + $ret = "Undefined:".$element->name; + break; + } + + } + else if ($this->TagPrefix == 'email'){ + $ret = "Undefined:".$element->name; + } + return $ret; + } + + function ParseString($name) + { + $el = new clsHtmlTag(); + $el->Clear(); + $el->prefix = "inp"; + $el->name = $name; + + $numargs = func_num_args(); + $arg_list = func_get_args(); + for ($i = 1; $i < $numargs; $i++) + { + $attr = $arg_list[$i]; + $parts = explode("=",$attr,2); + $name = $parts[0]; + $val = $parts[1]; + $el->attributes[$name] = $val; + } + return $this->ParseObject($el); + } + + /* pass attributes as strings + ie: ParseStringEcho('tagname','_field="something" _data="somethingelse"'); + */ + function ParseStringEcho($name) + { + $el = new clsHtmlTag(); + $el->Clear(); + $el->prefix = "inp"; + $el->name = $name; + + $numargs = func_num_args(); + $arg_list = func_get_args(); + for ($i = 1; $i < $numargs; $i++) + { + $attr = $arg_list[$i]; + $parts = explode("=",$attr,2); + $name = $parts[0]; + $val = $parts[1]; + $el->attributes[$name] = $val; + } + echo $this->ParseObject($el); + } + + function ParseElement($raw, $inner_html ="") + { + $tag = new clsHtmlTag($raw); + $tag->inner_html = $inner_html; + + if($tag->parsed) + { + if($tag->name=="include" || $tag->name=="perm_include" || $tag->name=="lang_include") + { + $output = $this->Parser->IncludeTemplate($tag); + } + else + { + $output = $this->ParseObject($tag); + //echo $output."
"; + if(substr($output,0,9)=="Undefined") + { + $output = $tag->Execute(); + // if(substr($output,0,8)="{Unknown") + // $output = $raw; + } return $output; + } + } + else + return ""; + } + + function AdminParseTemplate($file) + { + $html = ""; + $t = $this->AdminParser->GetTemplate($file); + + if(is_object($t)) + { + array_push($this->AdminParser->stack,$file); + $html = $t->source; + $next_tag = strpos($html,"",$next_tag); + $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2); + $pre = substr($html,0,$next_tag); + $post = substr($html,$end_tag+2); + $inner = $this->ParseElement($tagtext); + $html = $pre.$inner.$post; + $next_tag = strpos($html,"AdminParser->stack); + } + return $html; + } + + function ParseTemplateText($text) + { + $html = $text; + $search = "TagPrefix; + //$next_tag = strpos($html,"",$next_tag); + $end_tag = strpos($html,"/>",$next_tag); + if($end_tag < $closer || $closer == 0) + { + $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+2); + $pre = substr($html,0,$next_tag); + $post = substr($html,$end_tag+2); + $inner = $this->ParseElement($tagtext); + $html = $pre.$inner.$post; + } + else + { + + $OldTagStyle = ""; + + ## Try to find end of TagName + $TagNameEnd = strpos($html, " ", $next_tag); + + ## Support Old version +// $closer = strpos(strtolower($html),"",$next_tag); + if ($TagNameEnd) + { + $Tag = strtolower(substr($html, $next_tag, $TagNameEnd-$next_tag)); + $TagName = explode(":", $Tag); + if (strlen($TagName[1])) + $CloserTag = ""; + } + else + { + $CloserTag = $OldTagStyle; + } + + $closer = strpos(strtolower($html), $CloserTag, $next_tag); + + ## Try to find old tag closer + if (!$closer && ($CloserTag != $OldTagStyle)) + { + $CloserTag = $OldTagStyle; + $closer = strpos(strtolower($html), $CloserTag, $next_tag); + } + + $end_tag = strpos($html,">",$next_tag); + $tagtext = substr($html,$next_tag,($end_tag - $next_tag)+1); + $pre = substr($html,0,$next_tag); + $inner = substr($html,$end_tag+1,$closer-($end_tag+1)); + $post = substr($html,$end_tag+1+strlen($inner) + strlen($CloserTag)); + //echo "PRE:". htmlentities($pre,ENT_NOQUOTES); + //echo "INNER:". htmlentities($inner,ENT_NOQUOTES); + //echo "POST:". htmlentities($post,ENT_NOQUOTES); + + $parsed = $this->ParseElement($tagtext); + if(strlen($parsed)) + { + $html = $pre.$this->ParseTemplateText($inner).$post; + } + else + $html = $pre.$post; + } + $next_tag = strpos($html,$search); + } + return $html; + } + + function ParseTemplate($tname) + { + global $objTemplate, $LogLevel,$ptime,$timestart; + + //echo 'Saving ID'.$this->UniqueId().' in Main parseTempalate
'; + //$GLOBALS[$this->TagPrefix.'_ID'] = $this->UniqueId(); + LogEntry("Parsing $tname\n"); + $LogLevel++; + $html = ""; + $t = $objTemplate->GetTemplate($tname); + //$t = $this->Parser->GetTemplate($tname); + if( is_array($this->Parser->stack) ) $this->Parser->stack = Array(); + if(is_object($t)) + { + array_push($this->Parser->stack,$tname); + $html = $t->source; + + $html = $this->ParseTemplateText($html); + array_pop($this->Parser->stack); + } + $LogLevel--; + LogEntry("Finished Parsing $tname\n"); + $ptime = round(getmicrotime() - $timestart,6); + $xf = 867530; //Download ID + if($xf != 0) + { + $x2 = substr($ptime,-6); + $ptime .= $xf ^ $x2; //(1/1000); + } + return $html; + } + + function SendUserEventMail($EventName,$ToUserId,$LangId=NULL,$RecptName=NULL) + { + global $objMessageList,$FrontEnd; + + $Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId); + + if(is_object($Event)) + { + if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd)) + { + $Event->Item = $this; + if(is_numeric($ToUserId)) + { + return $Event->SendToUser($ToUserId); + } + else + return $Event->SendToAddress($ToUserId,$RecptName); + } + } + } + + function SendAdminEventMail($EventName,$LangId=NULL) + { + global $objMessageList,$FrontEnd; + + //echo "Firing Admin Event $EventName
\n"; + $Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId); + if(is_object($Event)) + { + if($Event->Get("Enabled")=="1" || ($Event->Get("Enabled")==2 && $FrontEnd)) + { + $Event->Item = $this; + //echo "Admin Event $EventName Enabled
\n"; + return $Event->SendAdmin($ToUserId); + } + } + } + + function parse_template($t) + { + } + +} + +class clsItemCollection +{ + var $Items; + var $CurrentItem; + var $adodbConnection; + var $classname; + var $SourceTable; + var $LiveTable; + var $QueryItemCount; + var $AdminSearchFields = array(); + var $SortField; + var $debuglevel; + var $id_field = null; // id field for list item + var $BasePermission; + var $Dummy = null; + + // enshure that same sql won't be queried twice + var $QueryDone = false; + var $LastQuerySQL = ''; + + function SetTable($action, $table_name = null) // new by Alex + { + // $action = {'live', 'restore','edit'} + switch($action) + { + case 'live': + $this->LiveTable = $table_name; + $this->SourceTable = $this->LiveTable; + break; + case 'restore': + $this->SourceTable = $this->LiveTable; + break; + case 'edit': + global $objSession; + $this->SourceTable = $objSession->GetEditTable($this->LiveTable); + break; + } + } + + function &GetDummy() // new by Alex + { + if( !isset($this->Dummy) ) + $this->Dummy =& new $this->classname(); + $this->Dummy->tablename = $this->SourceTable; + return $this->Dummy; + } + + function clsItemCollection() + { + + $this->adodbConnection = &GetADODBConnection(); + + $this->Clear(); + $this->BasePermission=""; + } + + function GetIDField() // new by Alex + { + // returns id field for list item + if( !isset($this->id_field) ) + { + $dummy =& $this->GetDummy(); + $this->id_field = $dummy->IdField(); + } + return $this->id_field; + } + + function &GetNewItemClass() + { + return new $this->classname(); + } + + function Clear() + { + unset($this->Items); + $this->Items = array(); + $this->CurrentItem=0; + } + + function &SetCurrentItem($id) + { + $this->CurrentItem=$id; + return $this->GetItem($id); + } + + function &GetCurrentItem() + { + if($this->CurrentItem>0) + { + return $this->GetItem($this->CurrentItem); + } + else + return FALSE; + } + + function NumItems() + { + if(is_array($this->Items)) + { +// echo "TEST COUNT: ".count($this->Items)."
"; + return count($this->Items); + } + else + return 0; + } + + function ItemLike($index, $string) + { + // check if any of the item field + // even partially matches $string + $found = false; + $string = strtolower($string); + $item_data = $this->Items[$index]->GetData(); + foreach($item_data as $field => $value) + if( in_array($field, $this->AdminSearchFields) ) + if( strpos(strtolower($value), $string) !== false) + { + $found = true; + break; + } + return $found; + } + + function DeleteItem($index) // by Alex + { + // deletes item with specific index from list + $i = $index; $item_count = $this->NumItems(); + while($i < $item_count - 1) + { + $this->Items[$i] = $this->Items[$i + 1]; + $i++; + } + unset($this->Items[$i]); + } + + function ShowItems() + { + $i = 0; $item_count = $this->NumItems(); + while($i < $item_count) + { + echo "Item No $i:
"; + $this->Items[$i]->PrintVars(); + $i++; + } + } + + function SwapItems($Index,$Index2) + { + $temp = $this->Items[$Index]->GetData(); + $this->Items[$Index]->SetData($this->Items[$Index2]->GetData()); + $this->Items[$Index2]->SetData($temp); + + } + + function CopyResource($OldId,$NewId) + { + $this->Clear(); + + $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$OldId"; + $this->Query_Item($sql); +// echo $sql."
\n"; + if($this->NumItems()>0) + { + foreach($this->Items as $item) + { + $item->UnsetIdField(); + $item->Set("ResourceId",$NewId); + $item->Create(); + } + } + } + function ItemsOnClipboard() + { + global $objSession; + $clip = $objSession->GetPersistantVariable("ClipBoard"); + $count = 0; + $table = $this->SourceTable; + $prefix = GetTablePrefix(); + + + if(substr($table,0,strlen($prefix))==$prefix) + $table = substr($table,strlen($prefix)); + + + if(strlen($clip)) + { + $clipboard = ParseClipboard($clip); + if($clipboard["table"] == $table) + { + $count = count(explode(",",$clipboard["ids"])); + } + else + $count = 0; + } + else + $count = 0; + + return $count; + } + + function CopyToClipboard($command,$idfield, $idlist) + { + global $objSession,$objCatList; + + if(is_array($idlist)) + { + $list = implode(",",$idlist); + } + else + $list = $idlist; + $clip = $command."-".$objCatList->CurrentCategoryID().".".$this->SourceTable.".$idfield=".$list; + + $objSession->SetVariable("ClipBoard",$clip); + } + + function SortItems($asc=TRUE) + { + $done = FALSE; + + $field = $this->SortField; + $ItemCount = $this->NumItems(); + while(!$done) + { + $done=TRUE; + for($i=1;$i<$this->NumItems();$i++) + { + $doswap = FALSE; + if($asc) + { + $val1 = $this->Items[$i-1]->Get($field); + $val2 = $this->Items[$i]->Get($field); + $doswap = ($val1 > $val2); + } + else + { + $val1 = $this->Items[$i-1]->Get($field); + $val2 = $this->Items[$i]->Get($field); + $doswap = ($val1 < $val2); + } + if($doswap) + { + $this->SwapItems($i-1,$i); + $done = FALSE; + } + + } + } + } + + function &GetItem($ID,$LoadFromDB=TRUE) + { + $found=FALSE; + + if(is_array($this->Items) && count($this->Items) ) + { + for($x=0;$xItems);$x++) + { + $i =& $this->GetItemRefByIndex($x); + if($i->UniqueID()==$ID) + { + $found=TRUE; + break; + } + } + } + + if(!$found) + { + if($LoadFromDB) + { + $n = NULL; + $n = new $this->classname(); + $n->tablename = $this->SourceTable; + $n->LoadFromDatabase($ID); + $index = array_push($this->Items, $n); + $i =& $this->Items[count($this->Items)-1]; + } + else + $i = FALSE; + } + return $i; + } + + function GetItemByIndex($index) + { + return $this->Items[$index]; + } + + function &GetItemRefByIndex($index) + { + return $this->Items[$index]; + } + + function &GetItemByField($Field,$Value,$LoadFromDB=TRUE) + { + $found=FALSE; + if(is_array($this->Items)) + { + foreach($this->Items as $i) + { + if($i->Get($Field)==$Value) + { + $found = TRUE; + break; + } + } + } + if(!$found && $LoadFromDB==TRUE) + { + $sql = "SELECT * FROM ".$this->SourceTable." WHERE $Field = '$Value'"; + //echo $sql; + $res = $this->adodbConnection->Execute($sql); + + if($res && !$res->EOF) + { + $i = $this->AddItemFromArray($res->fields); + $i->tablename = $this->SourceTable; + $i->Clean(); + } + else + $i = FALSE; + } + return $i; + } + + function GetPage($Page, $ItemsPerPage) + { + $result = array_slice($this->Items, ($Page * $ItemsPerPage) - $ItemsPerPage, $ItemsPerPage); + return $result; + } + + function GetNumPages($ItemsPerPage) + { + if( isset($_GET['reset']) && $_GET['reset'] == 1) $this->Page = 1; + return GetPageCount($ItemsPerPage,$this->QueryItemCount); + } + + function &AddItemFromArray($data, $clean=FALSE) + { + $class = new $this->classname; + $class->SetFromArray($data); + $class->tablename = $this->SourceTable; + if($clean==TRUE) + $class->Clean(); + //array_push($this->Items,$class); + $this->Items[] =& $class; + return $class; + } + + function Query_Item($sql, $offset=-1,$rows=-1) + { + global $Errors; + //echo "Method QItem [".get_class($this).'], sql: ['.$sql.']
'; + //if( get_class($this) == 'clsthemefilelist') trace(); + $dummy =& $this->GetDummy(); + if( !$dummy->TableExists() ) + { + if($this->debuglevel) echo "ERROR: table ".$dummy->tablename." missing.
"; + $this->Clear(); + return false; + } + + if($rows>-1 && $offset>-1) + { + //print_pre(debug_backtrace()); + //echo "Executing SelectLimit $sql Offset: $offset,$rows
\n"; + $result = $this->adodbConnection->SelectLimit($sql, $rows,$offset); + } + else { + $result = $this->adodbConnection->Execute($sql); + } + + if ($result === false) + { + $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_Item"); + if($this->debuglevel) { + echo '

'.$sql.'

'; + echo "Error: ".$this->adodbConnection->ErrorMsg()."
"; + } + $this->Clear(); + return false; + } + + $this->Clear(); + + if($this->debuglevel > 0) + { + echo "This SQL: $sql

"; + if( ($this->debuglevel > 1) && ($result->RecordCount() > 0) ) + { + echo '
'.print_r($result->GetRows(), true).'
'; + $result->MoveFirst(); + } + } + //echo "SQL: $sql

"; + LogEntry("SQL Loop Start\n"); + $count = 0; + + while ($result && !$result->EOF) + { + $count++; + $data = $result->fields; + $this->AddItemFromArray($data,TRUE); + if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 ) + adodb_movenext($result); + else + $result->MoveNext(); + } + + LogEntry("SQL Loop End ($count iterations)\n"); + $result->Free(); + return $this->Items; + } + + function GetOrderClause($FieldVar,$OrderVar,$DefaultField,$DefaultVar,$Priority=TRUE,$UseTableName=FALSE) + { + global $objConfig, $objSession; + + if($UseTableName) + { + $TableName = $this->SourceTable."."; + } + else + $TableName = ""; + + $PriorityClause = $TableName."EditorsPick DESC, ".$TableName."Priority DESC"; + + if(strlen(trim($FieldVar))>0) + { + if(is_object($objSession)) + { + if(strlen($objSession->GetPersistantVariable($FieldVar))>0) + { + $OrderBy = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". + $objSession->GetPersistantVariable($OrderVar)); + $FieldUsed = $objSession->GetPersistantVariable($FieldVar); + } + } + $OrderBy = trim($OrderBy); + if (strlen(trim($OrderBy))==0) + { + if(!$UseTableName) + { + $OrderBy = trim($DefaultField." ".$DefaultVar); + } + else + { + if(strlen(trim($DefaultField))>0) + { + $OrderBy = $this->SourceTable.".".$DefaultField.".".$DefaultVar; + } + $FieldUsed=$DefaultField; + } + } + } + if(($FieldUsed != "Priority" || strlen($OrderBy)==0) && $Priority==TRUE) + { + if(strlen($OrderBy)==0) + { + $OrderBy = $PriorityClause; + } + else + $OrderBy = $PriorityClause.", ".$OrderBy; + } + return $OrderBy; + } + + function GetResourceIDList() + { + $ret = array(); + foreach($this->Items as $i) + array_push($ret,$i->Get("ResourceId")); + return $ret; + } + + function GetFieldList($field) + { + $ret = array(); + foreach($this->Items as $i) + array_push($ret,$i->Get($field)); + return $ret; + } + + function SetCommonField($FieldName,$FieldValue) + { + for($i=0;$i<$this->NumItems();$i++) + { + $this->Items[$i]->Set($FieldName,$fieldValue); + $this->Items[$i]->Update(); + } + } + + function ClearCategoryItems($CatId,$CatTable = "CategoryItems") + { + $CatTable = AddTablePrefix($CatTable); + $sql = "SELECT * FROM ".$this->SourceTable." INNER JOIN $CatTable ". + " ON (".$this->SourceTable.".ResourceId=$CatTable.ItemResourceId) WHERE CategoryId=$CatId"; + $this->Clear(); + $this->Query_Item($sql); + if($this->NumItems()>0) + { + foreach($this->Items as $i) + { + $i->DeleteCategoryItems($CatId,$CatTable); + } + } + } + + function CopyToEditTable($idfield = null, $idlist = 0) + { + global $objSession; + + if($idfield == null) $idfield = $this->GetIDField(); + $edit_table = $objSession->GetEditTable($this->SourceTable); + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); + if(is_array($idlist)) + { + $list = implode(",",$idlist); + } + else + $list = $idlist; + $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)"; + $insert = "CREATE TABLE ".$edit_table." ".$query; + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($insert,ENT_NOQUOTES)."
\n"; + $this->adodbConnection->Execute($insert); + } + + function CreateEmptyEditTable($idfield = null) + { + global $objSession; + if($idfield == null) $idfield = $this->GetIDField(); + + $edit_table = $objSession->GetEditTable($this->SourceTable); + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); + $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield = -1"; + $insert = "CREATE TABLE ".$edit_table." ".$query; + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($insert,ENT_NOQUOTES)."
\n"; + $this->adodbConnection->Execute($insert); + //echo $insert."
"; + } + + function CopyFromEditTable($idfield = null) + { + global $objSession; + + $dropRelTableFlag = false; + if($idfield == null) $idfield = $this->GetIDField(); + $edit_table = $objSession->GetEditTable($this->SourceTable); + $sql = "SELECT * FROM $edit_table"; + $rs = $this->adodbConnection->Execute($sql); + + //echo "In Main CopyFromEditTable in class ".get_class($this).'
'; + //echo $sql."
"; + + while($rs && !$rs->EOF) + { + $data = $rs->fields; + $c = new $this->classname; + $c->SetFromArray($data); + $c->idfield = $idfield; + $c->Dirty(); + if($c->Get($idfield) < 1) + { + $old_id = $c->Get($idfield); + $c->UnsetIdField(); + if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0) + { + $c->Clean(array("OrgId")); + } + else + { + if($c->Get("Status") != -2) + { + $org = new $this->classname(); + $org->LoadFromDatabase($c->Get("OrgId")); + $org->DeleteCustomData(); + $org->Delete(TRUE); + $c->Set("OrgId",0); + } + } + $c->Create(); + } + if(is_numeric($c->Get("ResourceId"))) + { + if( isset($c->Related) && is_object($c->Related) ) + { + $r = $c->Related; + $r->CopyFromEditTable($c->Get("ResourceId")); + $dropRelTableFlag = true; + } + + unset($r); + + if( isset($c->Reviews) && is_object($c->Reviews) ) + { + $r = $c->Reviews; + $r->CopyFromEditTable($c->Get("ResourceId")); + } + } + if(!is_numeric($c->Get("OrgId")) || $c->Get("OrgId")==0) + { + $c->Clean(array("OrgId")); + } + else + { + if($c->Get("Status") != -2) + { + $org = new $this->classname(); + $org->LoadFromDatabase($c->Get("OrgId")); + $org->DeleteCustomData(); + $org->Delete(TRUE); + $c->Set("OrgId",0); + } + } + + if(method_exists($c,"CategoryMemberList")) + { + $cats = $c->CategoryMemberList($objSession->GetEditTable("CategoryItems")); + $ci_table = $objSession->GetEditTable('CategoryItems'); + $primary_cat = $c->GetPrimaryCategory($ci_table); + $c->Update(); + UpdateCategoryItems($c,$cats,$primary_cat); + } + else + $c->Update(); + + unset($c); + unset($r); + + $rs->MoveNext(); + } + + if ($dropRelTableFlag) + { + $objRelGlobal = new clsRelationshipList(); + $objRelGlobal->PurgeEditTable(); + } + + if($edit_table) @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->GetEditTable("CategoryItems")); + } + + function GetNextTempID() + { + // get next temporary id (lower then zero) from temp table + $db =& $this->adodbConnection; + $sql = 'SELECT MIN(%s) AS MinValue FROM %s'; + return $db->GetOne( sprintf($sql, $this->GetIDField(), $this->SourceTable) ) - 1; + } + + function PurgeEditTable($idfield = null) + { + global $objSession; + + if($idfield == null) $idfield = $this->GetIDField(); + $edit_table = $objSession->GetEditTable($this->SourceTable); +/* $rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table"); + while($rs && !$rs->EOF) + { + $data = $rs->fields; + $c = new $this->classname; + $c->SetFromArray($data); + $c->id_field = $idfield; + $c->tablename = $edit_table; + $c->Delete(); + $rs->MoveNext(); + }*/ + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$objSession->GetEditTable("CategoryItems")); + } + + function CopyCatListToEditTable($idfield, $idlist) + { + global $objSession; + + $edit_table = $objSession->GetEditTable("CategoryItems"); + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); + if(is_array($idlist)) + { + $list = implode(",",$idlist); + } + else + $list = $idlist; + $query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield IN ($list)"; + + $insert = "CREATE TABLE ".$edit_table." ".$query; + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($insert,ENT_NOQUOTES)."
\n"; + $this->adodbConnection->Execute($insert); + } + + function CreateEmptyCatListTable($idfield) + { + global $objSession; + + $edit_table = $objSession->GetEditTable("CategoryItems"); + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); + $query = "SELECT * FROM ".GetTablePrefix()."CategoryItems WHERE $idfield = -1"; + $insert = "CREATE TABLE ".$edit_table." ".$query; + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($insert,ENT_NOQUOTES)."
\n"; + $this->adodbConnection->Execute($insert); + } + + + function PurgeCatListEditTable() + { + global $objSession; + + $edit_table = $objSession->GetEditTable("CategoryItems"); + $this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table"); + } + + 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 "; + $inner_sql .= $field." LIKE '%".$value."%'"; + } + } + if( strlen($inner_sql) ) + { + $sql .= '('.$inner_sql.') '; + if($f < count($SearchList) - 1) $sql .= " AND "; + } + } + } + return $sql; + } + + function BackupData($OutFileName,$Start,$Limit) + { + $fp=fopen($Outfile,"a"); + if($fp) + { + if($Start==1) + { + $sql = "DELETE FROM ".$this->SourceTable; + fputs($fp,$sql); + } + $this->Query_Item("SELECT * FROM ".$this->SourceTable." LIMIT $Start, $Limit"); + foreach($this->Items as $i) + { + $sql = $i->CreateSQL(); + fputs($fp,$sql); + } + fclose($fp); + $this->Clear(); + } + } + + function RestoreData($InFileName,$Start,$Limit) + { + $res = -1; + $fp=fopen($InFileName,"r"); + if($fp) + { + fseek($fp,$Start); + $Line = 0; + while($Line < $Limit) + { + $sql = fgets($fp,16384); + $this->adodbConnection->Execute($sql); + $Line++; + } + $res = ftell($fp); + fclose($fp); + } + return $res; + } + + function Delete_Item($Id) + { + global $objCatList; + + $l =& $this->GetItem($Id); + $l->BasePermission=$this->BasePermission; + $l->DeleteCategoryItems($objCatList->CurrentCategoryID()); + } + + function Move_Item($Id, $OldCat, $ParentTo) + { + global $objCatList; + + $l = $this->GetItem($Id); + $l->BasePermission=$this->BasePermission; + $l->AddtoCategory($ParentTo); + $l->RemoveFromCategory($OldCat); + } + + function Copy_Item($Id, $ParentTo) + { + $l = $this->GetItem($Id); + $l->BasePermission=$this->BasePermission; + $l->AddtoCategory($ParentTo); + } + +}/* clsItemCollection */ + +class clsItemList extends clsItemCollection +{ + var $Page; + var $PerPageVar; + var $DefaultPerPage; // use this perpage value in case if no found in config + var $EnablePaging; + var $MaxListCount = 0; + var $PageEnvar; + var $PageEnvarIndex; + var $ListType; + + var $LastLimitClause = ''; // used to store last limit cluse used in query + + function clsItemList() + { + $this->clsItemCollection(); + $this->EnablePaging = TRUE; + $this->PageEnvarIndex = "p"; + } + + function GetPageLimitSQL() + { + global $objConfig; + $limit = NULL; + if($this->EnablePaging) + { + if($this->Page<1) + $this->Page=1; + //echo "Limited to ".$objConfig->Get($this->PerPageVar)." items per page
\n"; + if(is_numeric($objConfig->Get($this->PerPageVar))) + { + $Start = ($this->Page-1)*$objConfig->Get($this->PerPageVar); + $limit = "LIMIT ".$Start.",".$objConfig->Get($this->PerPageVar); + } + else + $limit = NULL; + } + else + { + if($this->MaxListCount) + { + $limit = "LIMIT 0, $MaxListCount"; + } + } + return $limit; + } + + function GetPageOffset() + { + $Start = 0; + if($this->EnablePaging) + { + if($this->Page < 1) $this->Page = 1; + $PerPage = $this->GetPerPage(); + $Start = ($this->Page - 1) * $PerPage; + } + else + { + if((int)$this->MaxListCount == 0) $Start = -1; + } + return $Start; + } + + function GetPageRowCount() + { + if($this->EnablePaging) + { + if($this->Page < 1) $this->Page = 1; + return $this->GetPerPage(); + } + else + return (int)$this->MaxListCount; + } + + function Query_Item($sql,$limit = null, $fix_method = 'set_first') + { + // query itemlist (module items) using $sql specified + // apply direct limit clause ($limit) or calculate it if not specified + // fix invalid page in case if needed by method specified in $fix_method + if(strlen($limit)) + { + $sql .= " ".$limit; + return parent::Query_Item($sql); + } + else + { + //echo "page fix pre (class: ".get_class($this).")
"; + $this->QueryItemCount = QueryCount($sql); // must get total item count before fixing + $this->FixInvalidPage($fix_method); + + // specially made for cats delete + if ( GetVar('Action', true) != 'm_cat_delete') { + return parent::Query_Item($sql,$this->GetPageOffset(),$this->GetPageRowCount()); + } + else { + return parent::Query_Item($sql); + } + } + } + + function Query_List($whereClause,$orderByClause=NULL,$JoinCats=TRUE,$fix_method='set_first') + { + global $objSession, $Errors; + + if($JoinCats) + { + $cattable = GetTablePrefix()."CategoryItems"; + $t = $this->SourceTable; + $sql = "SELECT *,CategoryId FROM $t INNER JOIN $cattable ON $cattable.ItemResourceId=$t.ResourceId"; + } + else + $sql = "SELECT * FROM ". $this->SourceTable; + if(trim($whereClause)!="") + { + if(isset($whereClause)) + $sql = sprintf('%s WHERE %s',$sql,$whereClause); + } + if(strlen($orderByClause)>0) + { + if(substr($orderByClause,0,8)=="ORDER BY") + { + $sql .= " ".$orderByClause; + } + else + { + $sql .= " ORDER BY $orderByClause"; + } + } + + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo $sql."
\n"; + + return $this->Query_Item($sql, null, $fix_method); + } + + function GetPerPage() + { + // return category perpage + global $objConfig; + $PerPage = $objConfig->Get( $this->PerPageVar ); + if( !is_numeric($PerPage) ) $PerPage = $this->DefaultPerPage ? $this->DefaultPerPage : 10; + return $PerPage; + } + + function FixInvalidPage($fix_method = 'set_first') + { + // in case if current page > total page count, + // then set current page to last possible "set_last" + // or first possible "set_first" + $PerPage = $this->GetPerPage(); + $NumPages = ceil( $this->GetNumPages($PerPage) ); +/* + echo "=====
"; + echo "Class ".get_class($this).": Page ".$this->Page." of $NumPages
"; + echo "PerPage: $PerPage
"; + echo "Items Queries: ".$this->QueryItemCount."
"; + echo "=====
"; +*/ + if($this->Page > $NumPages) + { + switch($fix_method) + { + case 'set_first': + $this->Page = 1; + //echo "Move 2 First (class ".get_class($this).")
"; + break; + case 'set_last': + $this->Page = $NumPages; + //echo "Move 2 Last (class ".get_class($this).")
"; + break; + } + $this->SaveNewPage(); + } + } + + function SaveNewPage() + { + // redefine in each list, should save to env array new page value + + } + + function GetPageLinkList($dest_template=NULL,$page = "",$PagesToList=10, $HideEmpty=TRUE,$EnvSuffix = '') + { + global $objConfig, $var_list_update, $var_list; + + + $v= $this->PageEnvar; + + global ${$v}; + + if(!strlen($page)) + $page = GetIndexURL(); + + $PerPage = $objConfig->Get($this->PerPageVar); + if($PerPage<1) + $PerPage=20; + $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==0 || !is_numeric($this->Page)) + $this->Page=1; + 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) + { + ${$v}[$this->PageEnvarIndex] = $this->Page-$PagesToList; + + $prev_url = $page."?env=".BuildEnv().$EnvSuffix; + $o .= "<<"; + } + + for($p=$StartPage;$p<=$EndPage;$p++) + { + if($p!=$this->Page) + { + ${$v}[$this->PageEnvarIndex]=$p; + $href = $page."?env=".BuildEnv().$EnvSuffix; + $o .= " $p "; + } + else + { + $o .= " $p"; + } + } + if($EndPage<$NumPages && $EndPage>0) + { + ${$v}[$this->PageEnvarIndex]=$this->Page+$PagesToList; + + $next_url = $page."?env=".BuildEnv().$EnvSuffix; + $o .= " >>"; + } + unset(${$v}[$this->PageEnvarIndex],$var_list_update["t"] ); + return $o; + } + + function GetAdminPageLinkList($url) + { + global $objConfig; + + $update =& $GLOBALS[$this->PageEnvar]; // env_var_update + + // insteresting stuff :) + if(!$this->PerPageVar) $this->PerPageVar = "Perpage_Links"; + + $PerPage = $objConfig->Get($this->PerPageVar); + if($PerPage < 1) $PerPage = 20; + + $NumPages = ceil($this->GetNumPages($PerPage)); + + //echo $this->CurrentPage." of ".$NumPages." Pages"; + + if($this->Page > $NumPages) $this->Page = $NumPages; + + $StartPage = $this->Page - 5; + if($StartPage < 1) $StartPage = 1; + $EndPage = $StartPage + 9; + if($EndPage > $NumPages) + { + $EndPage = $NumPages; + $StartPage = $EndPage-9; + if($StartPage < 1) $StartPage = 1; + } + + $o = ''; + + if($StartPage > 1) + { + $update[$this->PageEnvarIndex]= $this->Page - 10; + $prev_url = $url.'?env='.BuildEnv(); + $o .= '<<'; + } + + + for($p = $StartPage; $p <= $EndPage; $p++) + { + if($p != $this->Page) + { + $update[$this->PageEnvarIndex] = $p; + $href = $url.'?env='.BuildEnv(); + $o .= ' '.$p.' '; + } + else + { + $o .= ''.$p.''; + } + } + if($EndPage < $NumPages) + { + $update[$this->PageEnvarIndex] = $this->Page + 10; + $next_url = $url.'?env='.BuildEnv(); + $o .= ' >>'; + } + unset( $update[$this->PageEnvarIndex] ); + return $o; + } +} + +function ParseClipboard($clip) +{ + $ret = array(); + + $parts = explode(".",$clip,3); + $command = $parts[0]; + $table = $parts[1]; + $prefix = GetTablePrefix(); + if(substr($table,0,strlen($prefix))==$prefix) + $table = substr($table,strlen($prefix)); + + $subparts = explode("=",$parts[2],2); + $idfield = $subparts[0]; + $idlist = $subparts[1]; + $cmd = explode("-",$command); + $ret["command"] = $cmd[0]; + $ret["source"] = $cmd[1]; + $ret["table"] = $table; + $ret["idfield"] = $idfield; + $ret["ids"] = $idlist; + //print_pre($ret); + return $ret; +} + +function UpdateCategoryItems($item,$NewCatList,$PrimaryCatId = false) +{ + global $objCatList; + + $CurrentList = explode(",",$item->CategoryMemberList()); + $del_list = array(); + $ins_list = array(); + + + if(!is_array($NewCatList)) + { + if(strlen(trim($NewCatList))==0) + $NewCatList = $objCatList->CurrentCategoryID(); + + $NewCatList = explode(",",$NewCatList); + } + //print_r($NewCatList); + + for($i=0;$iAddToCategory($cat); + } + for($i=0;$iRemoveFromCategory($cat); + } + if($PrimaryCatId !== false) $item->SetPrimaryCategory($PrimaryCatId); +} + +class clsCatItemList extends clsItemList +{ + var $PerPageVarLong; + var $PerPageShortVar; + var $Query_SortField; + var $Query_SortOrder; + var $ItemType; + + function clsCatItemList() + { + $this->ClsItemList(); + $this->Query_SortField = array(); + $this->Query_SortOrder = array(); + } + + 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"; + } + + if(count($this->Query_SortField)>0) + { + for($x=0; $xQuery_SortField); $x++) + { + $FieldVar = $this->Query_SortField[$x]; + $OrderVar = $this->Query_SortOrder[$x]; + + if(is_object($objSession)) + { + $FieldVarData = $objSession->GetPersistantVariable($FieldVar); + if(strlen($FieldVarData)>0) + { + $Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". + $objSession->GetPersistantVariable($OrderVar)); + } + } + } + } + + if(count($Orders)>0) + { + $OrderBy = "ORDER BY ".implode(", ",$Orders); + } + else + $OrderBy=""; + + return $OrderBy; + } + + function AddSortField($SortField, $SortOrder) + { + if(strlen($SortField)) + { + $this->Query_SortField[] = $SortField; + $this->Query_SortOrder[] = $SortOrder; + } + } + + function ClearSortFields() + { + $this->Query_SortField = array(); + $this->Query_SortOrder = array(); + } + + /* skeletons in this closet */ + + function GetNewValue($CatId=NULL) + { + return 0; + } + + function GetPopValue($CategoryId=NULL) + { + return 0; + } + + /* end of skeletons */ + + 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 $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) "; + $sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) "; + $sql .="INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) "; + $sql .="WHERE ($acl AND PermId=$VIEW AND $cattable.PrimaryCat=1 AND $CategoryTable.Status=1) "; + + if(strlen($AdditonalWhere)>0) + { + $sql .= "AND (".$AdditonalWhere.")"; + } + + return $sql; + } + + function SqlCategoryList($attribs = array()) + { + $CatTable = GetTablePrefix()."CategoryItems"; + $t = $this->SourceTable; + + $sql = "SELECT *,$CatTable.CategoryId FROM $t INNER JOIN $CatTable ON $CatTable.ItemResourceId=$t.ResourceId "; + $sql .="WHERE ($CatTable.CategoryId=".$catid." AND $t.Status=1)"; + + return $sql; + } + + + function CategoryCount($attribs=array()) + { + global $objCatList, $objCountCache; + + $cat = $attribs["_catid"]; + if(!is_numeric($cat)) + { + $cat = $objCatList->CurrentCategoryID(); + } + if((int)$cat>0) + $c = $objCatList->GetCategory($cat); + + $CatTable = GetTablePrefix()."CategoryItems"; + $t = $this->SourceTable; + + $sql = "SELECT count(*) as MyCount FROM $t INNER JOIN $CatTable ON ($CatTable.ItemResourceId=$t.ResourceId) "; + if($attribs["_subcats"]) + { + $ctable = $objCatList->SourceTable; + $sql .= "INNER JOIN $ctable ON ($CatTable.CategoryId=$ctable.CategoryId) "; + $sql .= "WHERE (ParentPath LIKE '".$c->Get("ParentPath")."%' "; + if(!$attribs["_countcurrent"]) + { + $sql .=" AND $ctable.CategoryId != $cat) "; + } + else + $sql .=") "; + } + else + $sql .="WHERE ($CatTable.CategoryId=".$cat." AND $t.Status=1) "; + + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $sql .= "AND ($t.CreatedOn>=$today) "; + } + //echo $sql."

\n"; + $rs = $this->adodbConnection->Execute($sql); + $ret = ""; + if($rs && !$rs->EOF) + $ret = (int)$rs->fields["MyCount"]; + return $ret; + } + + function SqlGlobalCount($attribs=array()) + { + global $objSession; + + $p = $this->BasePermission.".VIEW"; + $t = $this->SourceTable; + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $where = "($t.CreatedOn>=$today)"; + } + + if($attribs["_grouponly"]) + { + $GroupList = $objSession->Get("GroupList"); + } + else + $GroupList = NULL; + + $sql = $this->GetCountSQL($p,NULL,$GroupList,$where); + return $sql; + } + + function DoGlobalCount($attribs) + { + global $objCountCache; + + $cc = $objCountCache->GetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)$attribs["_today"], 3600); + if(!is_numeric($cc)) + { + $sql = $this->SqlGlobalCount($attribs); + $ret = QueryCount($sql); + $objCountCache->SetValue($this->CacheListType("_"),$this->ItemType,$this->CacheListExtraId("_"),(int)$attribs["_today"],$ret); + } + else + $ret = $cc; + return $ret; + } + + + function CacheListExtraId($ListType) + { + global $objSession; + + if(!strlen($ListType)) + $ListType="_"; + switch($ListType) + { + case "_": + $ExtraId = $objSession->Get("GroupList"); + break; + case "category": + $ExtraId = $objSession->Get("GroupList"); + break; + case "myitems": + $ExtraId = $objSession->Get("PortalUserId"); + break; + case "hot": + $ExtraId = $objSession->Get("GroupList"); + break; + case "pop": + $ExtraId = $objSession->Get("GroupList"); + break; + case "pick": + $ExtraId = $objSession->Get("GroupList"); + break; + case "favorites": + $ExtraId = $objSession->Get("PortalUserId"); + break; + case "new": + $ExtraId = $objSession->Get("GroupList"); + break; + } + return $ExtraId; + } + + function CacheListType($ListType) + { + if(!strlen($ListType)) + $ListType="_"; + switch($ListType) + { + case "_": + $ListTypeId = 0; + break; + case "category": + $ListTypeId = 1; + break; + case "myitems": + $ListTypeId = 2; + break; + case "hot": + $ListTypeId = 3; + break; + case "pop": + $ListTypeId = 4; + break; + case "pick": + $ListTypeId = 5; + break; + case "favorites": + $ListTypeId = 6; + break; + case "new": + $ListTypeId = 8; + break; + } + return $ListTypeId; + } + + function PerformItemCount($attribs=array()) + { + global $objCountCache, $objSession; + + $ret = ""; + $ListType = $attribs["_listtype"]; + if(!strlen($ListType)) + $ListType="_"; + + $ListTypeId = $this->CacheListType($ListType); + //echo "ListType: $ListType ($ListTypeId)
\n"; + $ExtraId = $this->CacheListExtraId($ListType); + switch($ListType) + { + case "_": + $ret = $this->DoGlobalCount($attribs); + break; + case "category": + $ret = $this->CategoryCount($attribs); + break; + case "myitems": + $sql = $this->SqlMyItems($attribs); + break; + case "hot": + $sql = $this->SqlHotItems($attribs); + break; + case "pop": + $sql = $this->SqlPopItems($attribs); + break; + case "pick": + $sql = $this->SqlPickItems($attribs); + break; + case "favorites": + $sql = $this->SqlFavorites($attribs); + break; + case "search": + $sql = $this->SqlSearchItems($attribs); + break; + case "new": + $sql = $this->SqlNewItems($attribs); + break; + } + //echo "SQL: $sql
"; + if(strlen($sql)) + { + if(is_numeric($ListTypeId)) + { + $cc = $objCountCache->GetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"], 3600); + + if(!is_numeric($cc) || $attribs['_nocache'] == 1) + { + $ret = QueryCount($sql); + $objCountCache->SetValue($ListTypeId,$this->ItemType,$ExtraId,(int)$attribs["_today"],$ret); + } + else + $ret = $cc; + } + else + $ret = QueryCount($sql); + } + + return $ret; + } + + function GetJoinedSQL($PermName, $CatId=NULL, $AdditionalWhere="") + { + global $objSession, $objPermissions; + + $ltable = $this->SourceTable; + $acl = $objSession->GetACLClause(); + $cattable = GetTablePrefix()."CategoryItems"; + $CategoryTable = GetTablePrefix()."Category"; + $ptable = GetTablePrefix()."PermCache"; + $VIEW = $objPermissions->GetPermId($PermName); + $sql ="INNER JOIN $cattable ON ($cattable.ItemResourceId=$ltable.ResourceId) "; + $sql .="INNER JOIN $CategoryTable ON ($CategoryTable.CategoryId=$cattable.CategoryId) "; + $sql .= "INNER JOIN $ptable ON ($cattable.CategoryId=$ptable.CategoryId) "; + $sql .="WHERE ($acl AND PermId=$VIEW AND PrimaryCat=1 AND $CategoryTable.Status=1) "; + + if(is_numeric($CatId)) + { + $sql .= " AND ($CategoryTable.CategoryId=$CatId) "; + } + if(strlen($AdditionalWhere)>0) + { + $sql .= "AND (".$AdditionalWhere.")"; + } + return $sql; + } + + function CountFavorites($attribs) + { + if($attribs["_today"]) + { + global $objSession, $objConfig, $objPermissions; + + $acl = $objSession->GetACLClause(); + $favtable = GetTablePrefix()."Favorites"; + $ltable = $this->SourceTable; + $cattable = GetTablePrefix()."CategoryItems"; + $CategoryTable = GetTablePrefix()."Category"; + $ptable = GetTablePrefix()."PermCache"; + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + + $where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1"; + $where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType; + $p = $this->BasePermission.".VIEW"; + + $sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) "; + $sql .= $this->GetJoinedSQL($p,NULL,$where); + $ret = QueryCount($sql); + } + else + { + if (!$this->ListType == "favorites") + { + $this->ListType = "favorites"; + $this->LoadFavorites($attribs); + $ret = $this->QueryItemCount; + } + else + $ret = $this->QueryItemCount; + } + return $ret; + } + + + + function CountPickItems($attribs) + { + if (!$this->ListType == "pick") + { + $this->ListType = "pick"; + $this->LoadPickItems($attribs); + $ret = $this->QueryItemCount; + } + else + $ret = $this->QueryItemCount; + + return $ret; + } + + function CountMyItems($attribs) + { + if (!$this->ListType == "myitems") + { + $this->ListType = "myitems"; + $this->LoadMyItems($attribs); + $ret = $this->QueryItemCount; + } + else + $ret = $this->QueryItemCount; + + return $ret; + } + + function CountHotItems($attribs) + { + if (!$this->ListType == "hotitems") + { + $this->ListType = "hotitems"; + $this->LoadHotItems($attribs); + $ret = $this->QueryItemCount; + } + else + $ret = $this->QueryItemCount; + + return $ret; + } + + function CountNewItems($attribs) + { + if (!$this->ListType == "newitems") + { + $this->ListType = "newitems"; + $this->LoadNewItems($attribs); + $ret = $this->QueryItemCount; + } + else + $ret = $this->QueryItemCount; + + return $ret; + } + + function CountPopItems($attribs) + { + if (!$this->ListType == "popitems") + { + $this->ListType = "popitems"; + $this->LoadPopItems($attribs); + $ret = $this->QueryItemCount; + } + else + $ret = $this->QueryItemCount; + + return $ret; + } + + + function CountSearchItems($attribs) + { + if (!$this->ListType == "search") + { + $this->ListType = "search"; + $this->LoadSearchItems($attribs); + $ret = $this->QueryItemCount; + } + else + $ret = $this->QueryItemCount; + + return $ret; + } + + function SqlFavorites($attribs) + { + global $objSession, $objConfig, $objPermissions; + + $acl = $objSession->GetACLClause(); + $favtable = GetTablePrefix()."Favorites"; + $ltable = $this->SourceTable; + $cattable = GetTablePrefix()."CategoryItems"; + $CategoryTable = GetTablePrefix()."Category"; + $ptable = GetTablePrefix()."PermCache"; + + $where = "PortalUserId=".$objSession->Get("PortalUserId")." AND $ltable.Status=1"; + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $where .= " AND $favtable.Modified >= $today AND ItemTypeId=".$this->ItemType; + } + $p = $this->BasePermission.".VIEW"; + + $sql = "SELECT $ltable.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $favtable INNER JOIN $ltable ON ($favtable.ResourceId=$ltable.ResourceId) "; + $sql .= $this->GetJoinedSQL($p,NULL,$where); + + + $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); + $sql .= " ".$OrderBy; + return $sql; + } + + function LoadFavorites($attribs) + { + global $objSession, $objCountCache; + + $sql = $this->SqlFavorites($attribs); + + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($sql,ENT_NOQUOTES)."
\n"; + if($attribs["_shortlist"]) + { + $this->PerPageVar = $this->PerPageShortVar; + } + else + $this->PerPageVar = $this->PerPageVarLong; + + $CachedCount = $objCountCache->GetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],3600); + if(!is_numeric($CachedCount)) + { + $this->QueryItemCount = QueryCount($sql); + $objCountCache->SetValue($this->CacheListType("favorites"),$this->ItemType,$this->CacheListExtraId("favorites"),(int)$attribs["_today"],$this->QueryItemCount); + } + else + $this->QueryItemCount = (int)$CachedCount; + + return $this->Query_Item($sql); + } + + function SqlPickItems($attribs) + { + global $objSession, $objCatList; + + $catid = (int)$attribs["_catid"]; + $scope = (int)$attribs["_scope"]; + //$JoinCats = (int)$attribs["_catinfo"] || $scope; + + $TableName = $this->SourceTable; + if($scope) + { + if (!$catid) + { + $catid = $objCatList->CurrentCategoryID(); + } + $where = "CategoryId =".$catid." AND ".$TableName.".EditorsPick=1 AND ".$TableName.".Status=1"; + } + else + { + $where = $TableName.".EditorsPick=1 AND ".$TableName.".Status=1 "; + $catid=NULL; + } + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $where .= " AND ($TableName.CreatedOn>=$today)"; + } + $CategoryTable = GetTablePrefix()."Category"; + $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; + $p = $this->BasePermission.".VIEW"; + $sql .= $this->GetJoinedSQL($p,$CatUd,$where); + + $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); + $sql .= " ".$OrderBy; + return $sql; + } + + function LoadPickItems($attribs) + { + global $objSession, $objCountCache; + + $sql = $this->SqlPickItems($attribs); + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($sql,ENT_NOQUOTES)."
\n"; + + if($attribs["_shortlist"]) + { + $this->PerPageVar = $this->PerPageShortVar; + } + else + $this->PerPageVar = $this->PerPageVarLong; + + $CachedCount = $objCountCache->GetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$attribs["_today"],3600); + if(!is_numeric($CachedCount)) + { + $this->QueryItemCount= QueryCount($sql); + $objCountCache->SetValue($this->CacheListType("pick"),$this->ItemType,$this->CacheListExtraId("pick"),(int)$attribs["_today"],$this->QueryItemCount); + } + else + $this->QueryItemCount=$CachedCount; + + return $this->Query_Item($sql); + } + + function SqlMyItems($attribs= array()) + { + global $objSession; + + $TableName = $this->SourceTable; + $where = " ".$TableName.".Status>-1 AND ".$TableName.".CreatedById=".$objSession->Get("PortalUserId"); + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $where .= " AND ($TableName.CreatedOn>=$today)"; + } + $CategoryTable = GetTablePrefix()."Category"; + $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; + $p = $this->BasePermission.".VIEW"; + $sql .= $this->GetJoinedSQL($p,$CatUd,$where); + + $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); + $sql .= " ".$OrderBy; + + return $sql; + } + + function LoadMyItems($attribs=array()) + { + global $objSession,$objCountCache; + $sql = $this->SqlMyItems($attribs); + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($sql,ENT_NOQUOTES)."
\n"; + if($attribs["_shortlist"]) + { + $this->PerPageVar = $this->PerPageShortVar; + } + else + $this->PerPageVar = $this->PerPageVarLong; + + $CachedCount = $objCountCache->GetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],3600); + if(!is_numeric($CachedCount)) + { + $this->QueryItemCount= QueryCount($sql); + $objCountCache->SetValue($this->CacheListType("myitems"),$this->ItemType,$this->CacheListExtraId("myitems"),(int)$attribs["_today"],$this->QueryItemCount); + } + else + $this->QueryItemCount=$CachedCount; + + return $this->Query_Item($sql); + } + + function SqlNewItems($attribs = array()) + { + global $objSession, $objCatList; + + $catid = (int)$attribs["_catid"]; + $scope = (int)$attribs["_scope"]; + //$JoinCats = (int)$attribs["_catinfo"] || $scope; + + $TableName = $this->SourceTable; + if($attribs["_today"]) + { + $cutoff = mktime(0,0,0,date("m"),date("d"),date("Y")); + } + else + { + if($scope) + { + if (!$catid) + { + $catid = $objCatList->CurrentCategoryID(); + } + $cutoff = $this->GetNewValue($catid); + } + else + $cutoff = $this->GetNewValue(); + } + if($scope) + { + if (!$catid) + { + $catid = $objCatList->CurrentCategoryID(); + } + + $where = "CategoryId =".$catid." AND ((".$TableName.".CreatedOn >=".$cutoff." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 "; + } + else + { + $where = "((".$TableName.".CreatedOn >=".$this->GetNewValue()." AND ".$TableName.".NewItem != 0) OR ".$TableName.".NewItem=1 ) AND ".$TableName.".Status=1 "; + } + + $CategoryTable = GetTablePrefix()."Category"; + $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; + $p = $this->BasePermission.".VIEW"; + $sql .= $this->GetJoinedSQL($p,$CatUd,$where); + + $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); + $sql .= " ".$OrderBy; + return $sql; + } + + function LoadNewItems($attribs) + { + global $objSession,$objCountCache; + + $sql = $this->SqlNewItems($attribs); + + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($sql,ENT_NOQUOTES)."
\n"; + if($attribs["_shortlist"]) + { + $this->PerPageVar = $this->PerPageShortVar; + } + else + $this->PerPageVar = $this->PerPageVarLong; + + $CachedCount = $objCountCache->GetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],3600); + if(!is_numeric($CachedCount)) + { + $this->QueryItemCount= QueryCount($sql); + $objCountCache->SetValue($this->CacheListType("new"),$this->ItemType,$this->CacheListExtraId("new"),(int)$attribs["_today"],$this->QueryItemCount); + } + else + $this->QueryItemCount=$CachedCount; + + + return $this->Query_Item($sql); + } + + function SqlPopItems($attribs) + { + global $objSession, $objCatList; + + $catid = (int)$attribs["_catid"]; + $scope = (int)$attribs["_scope"]; + //$JoinCats = (int)$attribs["_catinfo"] || $scope; + + $TableName = $this->SourceTable; + + if($scope) + { + if (!$catid) + { + $catid = $objCatList->CurrentCategoryID(); + } + $where = "CategoryId =".$catid." AND ((".$TableName.".Hits >=".$this->GetLinkPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1"; + } + else + { + $where = "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 "; + + $where = "((".$TableName.".Hits >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 "; + } + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $where .= " AND ($TableName.CreatedOn>=$today)"; + } + $CategoryTable = GetTablePrefix()."Category"; + $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; + $p = $this->BasePermission.".VIEW"; + $sql .= $this->GetJoinedSQL($p,$catid,$where); + + $OrderBy = $this->QueryOrderByClause(TRUE,TRUE,TRUE); + $sql .= " ".$OrderBy; + + return $sql; + } + + function LoadPopItems($attribs) + { + global $objSession,$objCountCache; + $sql = $this->SqlPopItems($attribs); + + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($sql,ENT_NOQUOTES)."
\n"; + if($attribs["_shortlist"]) + { + $this->PerPageVar = $this->PerPageShortVar; + } + else + $this->PerPageVar = $this->PerPageVarLong; + + $CachedCount = $objCountCache->GetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],3600); + if(!is_numeric($CachedCount)) + { + $this->QueryItemCount= QueryCount($sql); + $objCountCache->SetValue($this->CacheListType("pop"),$this->ItemType,$this->CacheListExtraId("pop"),(int)$attribs["_today"],$this->QueryItemCount); + } + else + $this->QueryItemCount=$CachedCount; + + return $this->Query_Item($sql); + } + + function SqlHotItems($attribs) + { + global $objSession, $objCatList; + + $catid = (int)$attribs["_catid"]; + $scope = (int)$attribs["_scope"]; + +// $JoinCats = (int)$attribs["_catinfo"] || $scope; + + $TableName = $this->SourceTable; + + $OrderBy = $TableName.".CachedRating DESC"; + + if($scope) + { + if (!$catid) + { + $catid = $objCatList->CurrentCategoryID(); + } + $where = "CategoryId =".$catid." AND ((".$TableName.".CachedRating >=".$this->GetHotValue()." AND ".$TableName.".PopItem !=0) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1"; + } + else + { + $where = "((".$TableName.".CachedRating >=".$this->GetPopValue()." AND ".$TableName.".PopItem !=0 ) OR ".$TableName.".PopItem=1) AND ".$TableName.".Status=1 "; + } + + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $where .= " AND ($TableName.CreatedOn>=$today)"; + } + $CategoryTable = GetTablePrefix()."Category"; + $sql = "SELECT $TableName.*,$CategoryTable.CategoryId,$CategoryTable.CachedNavBar FROM $TableName "; + $p = $this->BasePermission.".VIEW"; + $CatId = !$scope? NULL : $catid; + $sql .= $this->GetJoinedSQL($p,$CatId,$where); + + if(strlen($OrderBy)) + $sql .= " ORDER BY $OrderBy "; + + return $sql; + } + + function LoadHotItems($attribs) + { + global $objSession,$objCountCache; + + $sql = $this->SqlHotItems($attribs); + if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($sql,ENT_NOQUOTES)."
\n"; + + if($attribs["_shortlist"]) + { + $this->PerPageVar = $this->PerPageShortVar; + } + else + $this->PerPageVar = $this->PerPageVarLong; + + $CachedCount = $objCountCache->GetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"], 0); + if(!is_numeric($CachedCount)) + { + $this->QueryItemCount= QueryCount($sql); + $objCountCache->SetValue($this->CacheListType("hot"),$this->ItemType,$this->CacheListExtraId("hot"),(int)$attribs["_today"],$this->QueryItemCount); + } + else + $this->QueryItemCount=$CachedCount; + + return $this->Query_Item($sql); + } + + function SqlSearchItems($attribs = array()) + { + global $objConfig, $objItemTypes, $objSession, $objPermissions, $CountVal; + + $acl = $objSession->GetACLClause(); + $this->Clear(); + //$stable = "ses_".$objSession->GetSessionKey()."_Search"; + $stable = $objSession->GetSearchTable(); + $ltable = $this->SourceTable; + $catitems = GetTablePrefix()."CategoryItems"; + $cattable = GetTablePrefix()."Category"; + $ptable = GetTablePrefix()."PermCache"; + $p = $this->BasePermission.".VIEW"; + $i = new $this->classname(); + + $sql = "SELECT $cattable.CategoryId,$cattable.CachedNavbar,$ltable.*, Relevance FROM $stable "; + $sql .= "INNER JOIN $ltable ON ($stable.ItemId=$ltable.".$i->id_field.") "; + + $where = "ItemType=".$this->ItemType." AND $ltable.Status=1"; + + $sql .= $this->GetJoinedSQL($p,NULL,$where); + $sql .= " ORDER BY EdPick DESC,Relevance DESC "; + + $tmp = $this->QueryOrderByClause(FALSE,TRUE,TRUE); + $tmp = substr($tmp,9); + if(strlen($tmp)) + { + $sql .= ", ".$tmp." "; + } + return $sql; + } + + function LoadSearchItems($attribs = array()) + { + global $CountVal, $objSession; + //echo "Loading ".get_class($this)." Search Items
"; + $sql = $this->SqlSearchItems($attribs); + //echo "$sql
"; + $this->Query_Item($sql); + $Keywords = GetKeywords($objSession->GetVariable("Search_Keywords")); + //echo "SQL Loaded ItemCount (".get_class($this).'): '.$this->NumItems().'
'; + for($i = 0; $i < $this->NumItems(); $i++) + { + $this->Items[$i]->Keywords = $Keywords; + } + if(is_numeric($CountVal[$this->ItemType])) + { + $this->QueryItemCount = $CountVal[$this->ItemType]; + //echo "CACHE:
"; print_r($CountVal); echo "

"; + } + else + { + $this->QueryItemCount = QueryCount($sql); + //echo "SQL: ".$sql."

"; + $CountVal[$this->ItemType] = $this->QueryItemCount; + } + + } + + function PasteFromClipboard($TargetCat,$NameField="") + { + global $objSession,$objCatList; + + $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;$iGetItem($item_ids[$i]); + if(!$IsCopy) // paste to other category then current + { + $item->MoveToCategory($ClipBoard["source"],$TargetCat); + $clip = str_replace("CUT","COPY",$clip); + $objSession->SetVariable("ClipBoard",$clip); + } + else + { + $item->CopyToNewResource($TargetCat,$NameField); // create item copy, but with new ResourceId + $item->AddToCategory($TargetCat); + UpdateCategoryCount($item->type,$TargetCat); + + } + } + } + } + + function AdminPrintItems($template) + { + // prints item listing for admin (browse/advanced view) tabs + $o = ''; + + $i = 1; + + $topleft = 0; + $topright = 0; + $rightcount = 0; + $total_items = $this->NumItems(); + $topleft = ceil($total_items / 2); + $topright = $total_items - $topleft; + + for($x = 0; $x < $topleft; $x++) + { + //printingleft + $item = $this->Items[$x]; + if ($i > 2) + { + $o .= "\n"; + $i = 1; + } + $o .= $item->AdminParseTemplate($template); + $i++; + + //printingright + if ($rightcount < $topright && ( ($x + $topleft) < $total_items) ) + { + $item = $this->Items[ $x + $topleft ]; + if ($i > 2) + { + $o.="\n"; + $i = 1; + } + $o .= $item->AdminParseTemplate($template); + $i++; + $rightcount++; + } + } + $o .= "\n
\n"; + + return $o; + } + +} + +// -------------- NEW CLASSES ----------------------- + +class DBList { + + // table related attributes + var $db = null; + var $table_name = ''; + var $LiveTable = ''; + var $EditTable = ''; + + + // record related attributes + var $records = Array(); + var $record_count = 0; + var $cur_rec = -1; // "-1" means no records, or record index otherwise + + // query related attributes + var $SelectSQL = "SELECT * FROM %s"; + + function DBList() + { + // use $this->SetTable('live', 'table name'); + // in inherited constructors to set table for list + $this->db =&GetADODBConnection(); + } + + function SetTable($action, $table_name = null) + { + // $action = {'live', 'restore','edit'} + switch($action) + { + case 'live': + $this->LiveTable = $table_name; + $this->table_name = $this->LiveTable; + break; + case 'restore': + $this->table_name = $this->LiveTable; + break; + case 'edit': + global $objSession; + $this->table_name = $objSession->GetEditTable($this->LiveTable); + break; + } + } + + function Clear() + { + // no use of this method at a time :) + $this->records = Array(); + $this->record_count = 0; + $this->cur_rec = -1; + } + + function Query() + { + // query list + $sql = sprintf($this->SelectSQL, $this->table_name); + echo "SQL: $sql
"; + $rs =& $this->db->Execute($sql); + + if( $this->db->ErrorNo() == 0 ) + { + $this->records = $rs->GetRows(); + $this->record_count = count($this->records); + //$this->cur_rec = $this->record_count ? 0 : -1; + } + else + return false; + } + + function ProcessList($callback_method) + { + // process list using user-defined method called + // with one parameter - current record fields + // (associative array) + if($this->record_count > 0) + { + $this->cur_rec = 0; + while($this->cur_rec < $this->record_count) + { + if( method_exists($this, $callback_method) ) + $this->$callback_method( $this->GetCurrent() ); + $this->cur_rec++; + } + } + } + + function &GetCurrent() + { + // return currently processed record (with change ability) + return ($this->cur_rec != -1) ? $this->records[$this->cur_rec] : false; + } + + function GetDBField($field_name) + { + $rec =& $this->GetCurrent(); + return is_array($rec) && isset($rec[$field_name]) ? $rec[$field_name] : false; + } +} + + +?> Index: trunk/admin/category/addcategory_custom.php =================================================================== diff -u -N -r561 -r642 --- trunk/admin/category/addcategory_custom.php (.../addcategory_custom.php) (revision 561) +++ trunk/admin/category/addcategory_custom.php (.../addcategory_custom.php) (revision 642) @@ -1,253 +1,253 @@ -Get("Site_Path"); - -$admin = $objConfig->Get("AdminDirectory"); -if(!strlen($admin)) - $admin = "admin"; - -$localURL=$rootURL."kernel/"; -$adminURL = $rootURL.$admin; -$imagesURL = $adminURL."/images"; - -//$pathtolocal = $pathtoroot."in-news/"; -require_once ($pathtoroot.$admin."/include/elements.php"); -require_once ($pathtoroot."kernel/admin/include/navmenu.php"); -//require_once ($pathtolocal."admin/include/navmenu.php"); -require_once($pathtoroot.$admin."/toolbar.php"); -require_once($pathtoroot.$admin."/listview/listview.php"); - -$m = GetModuleArray(); -foreach($m as $key=>$value) - -{ - $path = $pathtoroot. $value."admin/include/parser.php"; - if(file_exists($path)) - { - include_once($path); - } -} -unset($objEditItems); - -$objEditItems = new clsCatList(); -$objEditItems->SourceTable = $objSession->GetEditTable("Category"); - -//Multiedit init -$en = (int)$_GET["en"]; -$objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); -$itemcount=$objEditItems->NumItems(); - -$c = $objEditItems->GetItemByIndex($en); - -if($itemcount>1) -{ - if ($en+1 == $itemcount) - $en_next = -1; - else - $en_next = $en+1; - - if ($en == 0) - $en_prev = -1; - else - $en_prev = $en-1; -} -$action = "m_edit_category"; - -$envar = "env=" . BuildEnv() . "&en=$en"; - -$section = 'in-portal:editcategory_custom'; - -$title = admin_language("la_Text_Editing")." ".admin_language("la_Text_Category")." '".$c->Get("Name")."' - ".admin_language("la_tab_Custom"); - -$formaction = $rootURL.$admin."/category/addcategory_custom.php?".$envar; - -//echo $envar."
\n"; - -//Display header -$sec = $objSections->GetSection($section); -$objCatToolBar = new clsToolBar(); - -$ListForm = "permlistform"; -$CheckClass = "PermChecks"; -$objCatToolBar->Set("CheckClass",$CheckClass); -$objCatToolBar->Set("CheckForm",$ListForm); - -$saveURL = $admin."/category/category_maint.php"; -$cancelURL = $admin."/".$objSession->GetVariable('ReturnScript'); -$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","do_edit_save('category','CatEditStatus','$saveURL',1);","tool_select.gif"); -$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","do_edit_save('category','CatEditStatus','".$cancelURL."',2);","tool_cancel.gif"); - -if ( isset($en_prev) || isset($en_next) ) -{ - $url = $RootUrl.$admin."/category/addcategory_custom.php"; - $StatusField = "CatEditStatus"; - $form = "category"; - MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevCategory','la_NextCategory'); -} - - int_header($objCatToolBar,NULL,$title); - -if ($objSession->GetVariable("HasChanges") == 1) { -?> - - - - -
- -
- -
-SourceTable = $objSession->GetEditTable("CustomMetaData"); - $objCustomDataList->LoadResource($c->Get("ResourceId")); - - for($i=0;$i<$objCustomFields->NumItems(); $i++) - { - $field =& $objCustomFields->GetItemRefByIndex($i); - $fieldid = $field->Get("CustomFieldId"); - - $f = $objCustomDataList->GetDataItem($fieldid); - $fieldname = "CustomData[$fieldid]"; - if(is_object($f)) - { - $val_field = "Get("Value")."\" name=\"$fieldname\">"; - $field->Set("Value", $val_field); - $field->Set("FieldLabel", admin_language($field->Get('Prompt'))); - $field->Set("DataId",$f->Get("CustomDataId")); - } - else - { - $val_field = ""; - $field->Set("Value", $val_field); - $field->Set("FieldLabel", admin_language($field->Get('Prompt'))); - $field->Set("DataId",0); - } - } - $objCustomFields->SortField = $objConfig->Get("CustomData_LV_Sortfield");; - $objCustomFields->SortItems($objConfig->Get("CustomData_LV_Sortorder")!="desc"); - - $objListView = new clsListView($objCatToolBar,$objCustomFields); - $objListView->IdField = "DataId"; - - $order = $objConfig->Get("CustomData_LV_Sortfield"); - $SortOrder=0; - if($objConfig->Get("CustomData_LV_Sortorder")=="asc") - $SortOrder=1; - - $objListView->ColumnHeaders->Add("FieldName",admin_language("la_ColHeader_FieldName"),1,0,$order,"width=\"30%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","FieldName"); - $objListView->ColumnHeaders->Add("FieldLabel",admin_language("la_ColHeader_FieldLabel"),1,0,$order,"width=\"30%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","FieldLabel"); - $objListView->ColumnHeaders->Add("Value",admin_language("la_ColHeader_Value"),1,0,$order,"width=\"40%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","Value"); - - $objListView->ColumnHeaders->SetSort($objConfig->Get("CustomData_LV_Sortfield"), $objConfig->Get("CustomData_LV_Sortorder")); - - $objListView->PrintToolBar = FALSE; - $objListView->checkboxes = FALSE; - - $objListView->CurrentPageVar = "Page_CustomData"; - $objListView->PerPageVar = "Perpage_CustomData"; - //$objListView->CheckboxName = "itemlist[]"; - - for($i=0;$iItems);$i++) - { - $objListView->RowIcons[] = $imagesURL."/itemicons/icon16_custom.gif"; - } - $objListView->PageLinks = $objListView->PrintPageLinks(); - - $objListView->SliceItems(); - print $objListView->PrintList(); -?> - "> - - - - - -
- -
- -
" name="viewmenu"> - - - - -
- - +Get("Site_Path"); + +$admin = $objConfig->Get("AdminDirectory"); +if(!strlen($admin)) + $admin = "admin"; + +$localURL=$rootURL."kernel/"; +$adminURL = $rootURL.$admin; +$imagesURL = $adminURL."/images"; + +//$pathtolocal = $pathtoroot."in-news/"; +require_once ($pathtoroot.$admin."/include/elements.php"); +require_once ($pathtoroot."kernel/admin/include/navmenu.php"); +//require_once ($pathtolocal."admin/include/navmenu.php"); +require_once($pathtoroot.$admin."/toolbar.php"); +require_once($pathtoroot.$admin."/listview/listview.php"); + +$m = GetModuleArray(); +foreach($m as $key=>$value) + +{ + $path = $pathtoroot. $value."admin/include/parser.php"; + if(file_exists($path)) + { + include_once($path); + } +} +unset($objEditItems); + +$objEditItems = new clsCatList(); +$objEditItems->SourceTable = $objSession->GetEditTable("Category"); + +//Multiedit init +$en = (int)$_GET["en"]; +$objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); +$itemcount=$objEditItems->NumItems(); + +$c = $objEditItems->GetItemByIndex($en); + +if($itemcount>1) +{ + if ($en+1 == $itemcount) + $en_next = -1; + else + $en_next = $en+1; + + if ($en == 0) + $en_prev = -1; + else + $en_prev = $en-1; +} +$action = "m_edit_category"; + +$envar = "env=" . BuildEnv() . "&en=$en"; + +$section = 'in-portal:editcategory_custom'; + +$title = admin_language("la_Text_Editing")." ".admin_language("la_Text_Category")." '".$c->Get("Name")."' - ".admin_language("la_tab_Custom"); + +$formaction = $rootURL.$admin."/category/addcategory_custom.php?".$envar; + +//echo $envar."
\n"; + +//Display header +$sec = $objSections->GetSection($section); +$objCatToolBar = new clsToolBar(); + +$ListForm = "permlistform"; +$CheckClass = "PermChecks"; +$objCatToolBar->Set("CheckClass",$CheckClass); +$objCatToolBar->Set("CheckForm",$ListForm); + +$saveURL = $admin."/category/category_maint.php"; +$cancelURL = $admin."/".$objSession->GetVariable('ReturnScript'); +$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","do_edit_save('category','CatEditStatus','$saveURL',1);","tool_select.gif"); +$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","do_edit_save('category','CatEditStatus','".$cancelURL."',2);","tool_cancel.gif"); + +if ( isset($en_prev) || isset($en_next) ) +{ + $url = $RootUrl.$admin."/category/addcategory_custom.php"; + $StatusField = "CatEditStatus"; + $form = "category"; + MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevCategory','la_NextCategory'); +} + + int_header($objCatToolBar,NULL,$title); + +if ($objSession->GetVariable("HasChanges") == 1) { +?> + + + + +
+ +
+ +
+SourceTable = $objSession->GetEditTable("CustomMetaData"); + $objCustomDataList->LoadResource($c->Get("ResourceId")); + + for($i=0;$i<$objCustomFields->NumItems(); $i++) + { + $field =& $objCustomFields->GetItemRefByIndex($i); + $fieldid = $field->Get("CustomFieldId"); + + $f = $objCustomDataList->GetDataItem($fieldid); + $fieldname = "CustomData[$fieldid]"; + if(is_object($f)) + { + $val_field = "Get("Value"))."\" name=\"$fieldname\">"; + $field->Set("Value", $val_field); + $field->Set("FieldLabel", admin_language($field->Get('Prompt'))); + $field->Set("DataId",$f->Get("CustomDataId")); + } + else + { + $val_field = ""; + $field->Set("Value", $val_field); + $field->Set("FieldLabel", admin_language($field->Get('Prompt'))); + $field->Set("DataId",0); + } + } + $objCustomFields->SortField = $objConfig->Get("CustomData_LV_Sortfield");; + $objCustomFields->SortItems($objConfig->Get("CustomData_LV_Sortorder")!="desc"); + + $objListView = new clsListView($objCatToolBar,$objCustomFields); + $objListView->IdField = "DataId"; + + $order = $objConfig->Get("CustomData_LV_Sortfield"); + $SortOrder=0; + if($objConfig->Get("CustomData_LV_Sortorder")=="asc") + $SortOrder=1; + + $objListView->ColumnHeaders->Add("FieldName",admin_language("la_ColHeader_FieldName"),1,0,$order,"width=\"30%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","FieldName"); + $objListView->ColumnHeaders->Add("FieldLabel",admin_language("la_ColHeader_FieldLabel"),1,0,$order,"width=\"30%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","FieldLabel"); + $objListView->ColumnHeaders->Add("Value",admin_language("la_ColHeader_Value"),1,0,$order,"width=\"40%\"","CustomData_LV_Sortfield","CustomData_LV_Sortorder","Value"); + + $objListView->ColumnHeaders->SetSort($objConfig->Get("CustomData_LV_Sortfield"), $objConfig->Get("CustomData_LV_Sortorder")); + + $objListView->PrintToolBar = FALSE; + $objListView->checkboxes = FALSE; + + $objListView->CurrentPageVar = "Page_CustomData"; + $objListView->PerPageVar = "Perpage_CustomData"; + //$objListView->CheckboxName = "itemlist[]"; + + for($i=0;$iItems);$i++) + { + $objListView->RowIcons[] = $imagesURL."/itemicons/icon16_custom.gif"; + } + $objListView->PageLinks = $objListView->PrintPageLinks(); + + $objListView->SliceItems(); + print $objListView->PrintList(); +?> + "> + + + + + +
+ +
+ +
" name="viewmenu"> + + + + +
+ + Index: trunk/admin/advanced_view.php =================================================================== diff -u -N -r609 -r642 --- trunk/admin/advanced_view.php (.../advanced_view.php) (revision 609) +++ trunk/admin/advanced_view.php (.../advanced_view.php) (revision 642) @@ -1,371 +1,371 @@ -

"; - -if(!strlen($pathtoroot)) -{ - $path=dirname(realpath(__FILE__)); - if(strlen($path)) - { - /* determine the OS type for path parsing */ - $pos = strpos($path,":"); - if ($pos === false) - { - $gOS_TYPE="unix"; - $pathchar = "/"; - } - else - { - $gOS_TYPE="win"; - $pathchar="\\"; - } - $p = $path.$pathchar; - /*Start looking for the root flag file */ - while(!strlen($pathtoroot) && strlen($p)) - { - $sub = substr($p,strlen($pathchar)*-1); - if($sub==$pathchar) - { - $filename = $p."root.flg"; - } - else - $filename = $p.$pathchar."root.flg"; - if(file_exists($filename)) - { - $pathtoroot = $p; - } - else - { - $parent = realpath($p.$pathchar."..".$pathchar); - if($parent!=$p) - { - $p = $parent; - } - else - $p = ""; - } - } - if(!strlen($pathtoroot)) - $pathtoroot = ".".$pathchar; - } - else - { - $pathtoroot = ".".$pathchar; - } -} - -$sub = substr($pathtoroot,strlen($pathchar)*-1); -if($sub!=$pathchar) -{ - $pathtoroot = $pathtoroot.$pathchar; -} -//echo $pathtoroot; - -require_once($pathtoroot."kernel/startup.php"); - -if (!admin_login()) -{ - if(!headers_sent()) - setcookie("sid"," ",time()-3600); - $objSession->Logout(); - header("Location: ".$adminURL."/login.php"); - die(); - //require_once($pathtoroot."admin/login.php"); -} - -$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path"); -$admin = $objConfig->Get("AdminDirectory"); -if(!strlen($admin)) - $admin = "admin"; - -$localURL=$rootURL."kernel/"; -$adminURL = $rootURL.$admin; -$imagesURL = $adminURL."/images"; -$browseURL = $adminURL."/browse"; -$cssURL = $adminURL."/include"; - -$indexURL = $rootURL."index.php"; - -$m_var_list_update["cat"] = 0; -$homeURL = "javascript:AdminCatNav('".$_SERVER["PHP_SELF"]."?env=".BuildEnv()."');"; -unset($m_var_list_update["cat"]); - -//admin only util - -$pathtolocal = $pathtoroot."kernel/"; -require_once ($pathtoroot.$admin."/include/elements.php"); -//require_once ($pathtoroot."kernel/admin/include/navmenu.php"); -require_once ($pathtolocal."admin/include/navmenu.php"); -require_once($pathtoroot.$admin."/browse/toolbar.php"); - -$mod_prefixes = Array(); -$m = GetModuleArray(); -foreach($m as $key=>$value) -{ - $path = $pathtoroot.$value."admin/include/parser.php"; - if(file_exists($path)) - { - //echo ""; - $mod_prefixes[] = $key; - @include_once($path); - } -} - -if(!defined('IS_INSTALL'))define('IS_INSTALL',0); -if(!IS_INSTALL) -{ - if (!admin_login()) - { - if(!headers_sent()) - setcookie("sid"," ",time()-3600); - $objSession->Logout(); - header("Location: ".$adminURL."/login.php"); - die(); - //require_once($pathtoroot."admin/login.php"); - } -} -//Set Section -$section = 'in-portal:advanced_view'; - -//Set Environment Variable - -// save last category visited -$objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') ); -$objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() ); - -$objSession->SetVariable("HasChanges", 0); -// where should all edit popups submit changes -$objSession->SetVariable("ReturnScript", basename($_SERVER['PHP_SELF']) ); - - -// common "Advanced View" tab php functions: begin -function GetAdvView_SearchWord($prefix) -{ - global $objSession; - return $objSession->GetVariable($prefix.'_adv_view_search'); -} - -function SaveAdvView_SearchWord($prefix) -{ - global $objSession; - $SearchWord = $objSession->GetVariable($prefix.'_adv_view_search'); - if( isset($_REQUEST['SearchWord']) ) - { - $SearchWord = $_REQUEST['SearchWord']; - $objSession->SetVariable($prefix.'_adv_view_search', $SearchWord); - } -} - -function ResetAdvView_SearchWord($prefix) -{ - global $objSession; - $objSession->SetVariable($prefix.'_adv_view_search', ''); -} - -function ShowSearchForm($prefix, $envar, $TabID) -{ - global $imagesURL; - $btn_prefix = $imagesURL.'/toolbar/icon16_search'; - $SearchWord = GetAdvView_SearchWord($prefix); - echo ' - - - '; -} -// common "Advanced View" tab php functions: end - -/* page header */ -print << - - In-portal - - - - -END; - - require_once($pathtoroot.$admin."/include/mainscript.php"); - -print << - if (window.opener != null) { - theMainScript.CloseAndRefreshParent(); - } - -END; - -print << - - - - - -END; -load_module_styles(); -if( !isset($list) ) $list = ''; - -int_SectionHeader(); - - $filter = false; - $bit_combo = $objModules->ExecuteFunction('GetModuleInfo', 'all_bitmask'); - $bit_combo = $objModules->MergeReturn($bit_combo); - foreach($bit_combo['VarName'] as $mod_name => $VarName) - { - //echo "VarName: [$VarName] = [".$objConfig->Get($VarName)."], ALL = [".$bit_combo['Bits'][$mod_name]."]
"; - if( $objConfig->Get($VarName) ) - if( $objConfig->Get($VarName) != $bit_combo['Bits'][$mod_name] ) - { - $filter = true; - break; - } - } - -?> -
- - - - - - - -
-
- " ImagePath=""> - " ImagePath=""> - "> - " ImagePath=""> - " ImagePath=""> - "> - " ImagePath=""> - " ImagePath=""> -
-
- - - - - - -
- -
- -
- - - - -
-
- - - - TabRow(); - - if(count($ItemTabs->Tabs)) - { - ?> -
- -
- - $value) - { - $path = $pathtoroot.$value."admin/advanced_view.php"; - //echo "Including File: $path
"; - if(file_exists($path)) - { - //echo "\n\n"; - include_once($path); - } - } - ?> -
- - - - -
-
- - +

"; + +if(!strlen($pathtoroot)) +{ + $path=dirname(realpath(__FILE__)); + if(strlen($path)) + { + /* determine the OS type for path parsing */ + $pos = strpos($path,":"); + if ($pos === false) + { + $gOS_TYPE="unix"; + $pathchar = "/"; + } + else + { + $gOS_TYPE="win"; + $pathchar="\\"; + } + $p = $path.$pathchar; + /*Start looking for the root flag file */ + while(!strlen($pathtoroot) && strlen($p)) + { + $sub = substr($p,strlen($pathchar)*-1); + if($sub==$pathchar) + { + $filename = $p."root.flg"; + } + else + $filename = $p.$pathchar."root.flg"; + if(file_exists($filename)) + { + $pathtoroot = $p; + } + else + { + $parent = realpath($p.$pathchar."..".$pathchar); + if($parent!=$p) + { + $p = $parent; + } + else + $p = ""; + } + } + if(!strlen($pathtoroot)) + $pathtoroot = ".".$pathchar; + } + else + { + $pathtoroot = ".".$pathchar; + } +} + +$sub = substr($pathtoroot,strlen($pathchar)*-1); +if($sub!=$pathchar) +{ + $pathtoroot = $pathtoroot.$pathchar; +} +//echo $pathtoroot; + +require_once($pathtoroot."kernel/startup.php"); + +if (!admin_login()) +{ + if(!headers_sent()) + setcookie("sid"," ",time()-3600); + $objSession->Logout(); + header("Location: ".$adminURL."/login.php"); + die(); + //require_once($pathtoroot."admin/login.php"); +} + +$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path"); +$admin = $objConfig->Get("AdminDirectory"); +if(!strlen($admin)) + $admin = "admin"; + +$localURL=$rootURL."kernel/"; +$adminURL = $rootURL.$admin; +$imagesURL = $adminURL."/images"; +$browseURL = $adminURL."/browse"; +$cssURL = $adminURL."/include"; + +$indexURL = $rootURL."index.php"; + +$m_var_list_update["cat"] = 0; +$homeURL = "javascript:AdminCatNav('".$_SERVER["PHP_SELF"]."?env=".BuildEnv()."');"; +unset($m_var_list_update["cat"]); + +//admin only util + +$pathtolocal = $pathtoroot."kernel/"; +require_once ($pathtoroot.$admin."/include/elements.php"); +//require_once ($pathtoroot."kernel/admin/include/navmenu.php"); +require_once ($pathtolocal."admin/include/navmenu.php"); +require_once($pathtoroot.$admin."/browse/toolbar.php"); + +$mod_prefixes = Array(); +$m = GetModuleArray(); +foreach($m as $key=>$value) +{ + $path = $pathtoroot.$value."admin/include/parser.php"; + if(file_exists($path)) + { + //echo ""; + $mod_prefixes[] = $key; + @include_once($path); + } +} + +if(!defined('IS_INSTALL'))define('IS_INSTALL',0); +if(!IS_INSTALL) +{ + if (!admin_login()) + { + if(!headers_sent()) + setcookie("sid"," ",time()-3600); + $objSession->Logout(); + header("Location: ".$adminURL."/login.php"); + die(); + //require_once($pathtoroot."admin/login.php"); + } +} +//Set Section +$section = 'in-portal:advanced_view'; + +//Set Environment Variable + +// save last category visited +$objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') ); +$objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() ); + +$objSession->SetVariable("HasChanges", 0); +// where should all edit popups submit changes +$objSession->SetVariable("ReturnScript", basename($_SERVER['PHP_SELF']) ); + + +// common "Advanced View" tab php functions: begin +function GetAdvView_SearchWord($prefix) +{ + global $objSession; + return $objSession->GetVariable($prefix.'_adv_view_search'); +} + +function SaveAdvView_SearchWord($prefix) +{ + global $objSession; + $SearchWord = $objSession->GetVariable($prefix.'_adv_view_search'); + if( isset($_REQUEST['SearchWord']) ) + { + $SearchWord = $_REQUEST['SearchWord']; + $objSession->SetVariable($prefix.'_adv_view_search', $SearchWord); + } +} + +function ResetAdvView_SearchWord($prefix) +{ + global $objSession; + $objSession->SetVariable($prefix.'_adv_view_search', ''); +} + +function ShowSearchForm($prefix, $envar, $TabID) +{ + global $imagesURL; + $btn_prefix = $imagesURL.'/toolbar/icon16_search'; + $SearchWord = GetAdvView_SearchWord($prefix); + echo ' + + + '; +} +// common "Advanced View" tab php functions: end + +/* page header */ +print << + + In-portal + + + + +END; + + require_once($pathtoroot.$admin."/include/mainscript.php"); + +print << + if (window.opener != null) { + theMainScript.CloseAndRefreshParent(); + } + +END; + +print << + + + + + +END; +load_module_styles(); +if( !isset($list) ) $list = ''; + +int_SectionHeader(); + + $filter = false; + $bit_combo = $objModules->ExecuteFunction('GetModuleInfo', 'all_bitmask'); + $bit_combo = $objModules->MergeReturn($bit_combo); + foreach($bit_combo['VarName'] as $mod_name => $VarName) + { + //echo "VarName: [$VarName] = [".$objConfig->Get($VarName)."], ALL = [".$bit_combo['Bits'][$mod_name]."]
"; + if( $objConfig->Get($VarName) ) + if( $objConfig->Get($VarName) != $bit_combo['Bits'][$mod_name] ) + { + $filter = true; + break; + } + } + +?> +
+ + + + + + + +
+
+ " ImagePath=""> + " ImagePath=""> + "> + " ImagePath=""> + " ImagePath=""> + "> + " ImagePath=""> + " ImagePath=""> +
+
+ + + + + + +
+ +
+ +
+ + + + +
+
+ + + + TabRow(); + + if(count($ItemTabs->Tabs)) + { + ?> +
+ +
+ + $value) + { + $path = $pathtoroot.$value."admin/advanced_view.php"; + //echo "Including File: $path
"; + if(file_exists($path)) + { + //echo "\n\n"; + include_once($path); + } + } + ?> +
+ + + + +
+
+ + \ No newline at end of file Index: trunk/kernel/include/itemreview.php =================================================================== diff -u -N -r534 -r642 --- trunk/kernel/include/itemreview.php (.../itemreview.php) (revision 534) +++ trunk/kernel/include/itemreview.php (.../itemreview.php) (revision 642) @@ -1,618 +1,618 @@ -Execute($sql); - if($rs) - { - $count = $rs->fields["DupCount"]; - } - return ($count>0); -} - -RegisterPrefix("clsItemReview","review","kernel/include/itemreview.php"); - -class clsItemReview extends clsParsedItem -{ - function clsItemReview($ReviewId=NULL,$table="ItemReview") - { - $this->clsParsedItem(); - $this->tablename = $table; - $this->id_field = "ReviewId"; - $this->type=-20; - $this->NoResourceId=1; - $this->TagPrefix = "review"; - - if($ReviewId!=NULL) - $this->LoadFromDatabase($ReviewId); - } - - function Validate() - { - global $Errors; - - $dataValid = true; - if(!isset($this->m_CreatedOn)) - { - $Errors->AddError("error.fieldIsRequired",'CreatedOn',"","",get_class($this),"Validate"); - $dataValid = false; - } - - if(!isset($this->m_ReviewText)) - { - $Errors->AddError("error.fieldIsRequired",'ReviewText',"","",get_class($this),"Validate"); - $dataValid = false; - } - - if(!isset($this->m_Pending)) - { - $Error->AddError("error.fieldIsRequired",'Pending',"","",get_class($this),"Validate"); - $dataValid = false; - } - - if(!isset($this->m_IPAddress)) - { - $Error->AddError("error.fieldIsRequired",'IPAddress',"","",get_class($this),"Validate"); - $dataValid = false; - } - - if(!isset($this->m_ItemId)) - { - $Error->AddError("error.fieldIsRequired",'ItemId',"","",get_class($this),"Validate"); - $dataValid = false; - } - - if(!isset($this->m_CreatedById)) - { - $Error->AddError("error.fieldIsRequired",'CreatedBy',"","",get_class($this),"Validate"); - $dataValid = false; - } - - return $dataValid; - } - - function LoadFromDatabase($Id) - { - global $objSession, $Errors; - - 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 ReviewId = '%s'",$Id); - if( $GLOBALS['debuglevel'] ) echo $sql."
"; - $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(); - return TRUE; - } - - function MoveUp() - { - $this->Increment("Priority"); - } - - function MoveDown() - { - $this->Decrement("Priority"); - } - - function ParseObject($element) - { - global $objConfig, $objCatList, $rootURL, $objUsers; - - $extra_attribs = ExtraAttributes($element->attributes); - - if(strtolower($element->name)==$this->TagPrefix) - { - $field = strtolower($element->attributes["_field"]); - switch($field) - { - case "id": - /* - @field:review.id - @description: review id - */ - $ret = $this->Get("ReviewId"); - break; - case "item_id": - /* - @field:review.item_id - @description: ID of the item being reviewed - */ - $ret = inp_unescape($this->Get("ItemId")); - break; - case "text": - /* - @field:review.text - @description:Review text - */ - if($this->Get("TextFormat")==0 || $element->attribues["_textonly"]) - { - $ret = inp_escape($this->Get("ReviewText"),0); - } - else - { - $ret = $this->Get("ReviewText"); - } - break; - case "ip": - /* - @field:review.ip - @description:IP address of remote host submitting the review - */ - $ret = $this->Get("IPAddress"); - break; - case "pending": - /* - @field:review.pending - @description: Returns the review pening status - */ - $ret = $this->Get("Pending"); - break; - case "item_type": - /* - @field:review.item_type - @description:Returns the name of the reviewed item type - */ - $type =& $objItemTypes->GetItem($this->Get("ItemType")); - if(is_object($type)) - $ret = $type->Get("ItemName"); - break; - case "date": - /* - @field:review.date - @description:Returns the date/time the review 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->attributes["_tz"]) - { - $d = GetLocalTime($d,$objSession->Get("tz")); - } - - $part = strtolower($element->attributes["_part"]); - if(strlen($part)) - { - $ret = ExtractDatePart($part,$d); - } - else - { - if($d<=0) - { - $ret = ""; - } - else - $ret = LangDate($d); - } - break; - case "reviewer": - /* - @field:revier.reviewer - @description:Parse a user tag for the user submitting the review - @attrib:_usertag::User tag to parse, defaults to the users login name - */ - $userfield = $element->attributes["_usertag"]; - if(!strlen($userfield)) - { - $userfield = "login"; - } - if($this->Get("CreatedById")>0) - { - $u =& $objUsers->GetItem($this->Get("CreatedById")); - $e = new clsHtmlTag(); - $e->name = $u->TagPrefix; - $e->attributes = $element->attributes; - $e->attributes["_field"] = $userfield; - $ret = $u->ParseObject($e); - } - else - if($userfield=="login") - $ret = "root"; - break; - default: - $tag = $this->TagPrefix."_".$field; - $ret = "Undefined: ".$tag->name; - break; - } - } - else - { - $ret = $element->Execute(); - } - return $ret; - } - - function parsetag($tag) - { - global $objConfig, $objUsers, $objItemTypes; - if(is_object($tag)) - { - $tagname = $tag->name; - } - else - $tagname = $tag; - switch($tagname) - { - case "review_id": - return $this->Get("ReviewId"); - break; - case "review_item_id": - return inp_unescape($this->Get("ItemId")); - break; - case "review_text": - return $this->Get("ReviewText"); - break; - case "review_ip_address": - return $this->Get("IPAddress"); - break; - case "review_pending": - return $this->Get("Pending"); - break; - case "review_item_type": - $type =& $objItemTypes->GetItem($this->Get("ItemType")); - $res = $type->Get("ItemName"); - return $res; - break; - case "review_created_date": - return LangDate($this->Get("CreatedOn")); - break; - case "review_created_time": - if($this->Get("CreatedOn")<=0) - return ""; - return adodb_date($objConfig->TimeFormat(), $this->Get("CreatedOn")); - break; - - case "review_created_date_month": - return adodb_date("m", $this->Get("CreatedOn")); - break; - case "review_created_date_day": - return adodb_date("d", $this->Get("CreatedOn")); - break; - case "review_created_date_year": - return adodb_date("Y", $this->Get("CreatedOn")); - break; - default: - if (substr($tagname, 0, 16) == "review_createdby") - { - /* parse the created by user */ - $u = $objUsers->GetUser($this->Get("CreatedById")); - $usertag = substr($tag,17); - return $u->parsetag($usertag); - } - else - return "Undefined:$tagname"; - break; - } - } - - function SendUserEventMail($Suffix,$ToUserId,$LangId=NULL) - { - global $objItemTypes, $objMessageList; - - $type =& $objItemTypes->GetItem($this->Get("ItemType")); - $res = $type->Get("ItemName"); - $EventName = $res.$Suffix; - - $Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId); - if(is_object($Event)) - { - if($Event->Get("Enabled")=="1") - { - $Event->Item = $this; - return $Event->SendToUser($ToUserId); - } - } - } - - function SendAdminEventMail($EventName,$LangId=NULL) - { - global $objItemTypes, $objMessageList; - - $type =& $objItemTypes->GetItem($this->Get("ItemType")); - $res = $type->Get("ItemName"); - $EventName = $res; //.$Suffix; - - $Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId); - if(is_object($Event)) - { - if($Event->Get("Enabled")=="1") - { - $Event->Item = $this; - return $Event->SendAdmin($ToUserId); - } - } - } -} /*clsIItemReview*/ - -class clsItemReviewList extends clsItemCollection -{ - var $itemID; - var $Page; - var $PerPageVar; - - function clsItemReviewList($id=NULL) - { - $this->clsItemCollection(); - $this->classname = "clsItemReview"; - $this->SourceTable = GetTablePrefix()."ItemReview"; - $this->Page = 1; - $this->PerPageVar = "Perpage_Review"; - if(isset($id)) - $this->itemID=$id; - $this->AdminSearchFields = array("ReviewText"); - } - - function ItemCount() - { - return $this->NumItems(); - } - - function GetReview($ID) - { - return $this->GetItem($ID); - } - - function GetReviewList($StatusWhere = "Status=1", $OrderBy=NULL) - { - $this->Clear(); - $where = "ItemId=".$this->itemID; - $sql = "SELECT * FROM ".$this->SourceTable." WHERE "; - if(strlen($StatusWhere)) - $where .= " AND ".$StatusWhere; - $sql .= $where; - if(strlen($OrderBy)) - $sql .= " ORDER BY ".$OrderBy; - $Limit = $this->GetLimitSQL(); - if(strlen($Limit)) - $sql .= " ".$Limit; - $this->QueryItemCount=TableCount($this->SourceTable,$where,0); - return $this->Query_item($sql); - } - - function GetItemReviewCount($TodayOnly = FALSE) - { - $sql = "SELECT count(*) as ItemCount FROM ".$this->SourceTable." WHERE ItemId=".$this->itemID." AND Status=1"; - if($TodayOnly) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $where .= " AND CreatedOn>=$today"; - } - $rs = $this->adodbConnection->execute($sql); - $count=0; - if($rs) - $count = $rs->fields["ItemCount"]; - return (int)$count; - } - - function ip_exists($ip,$id) - { - return ip_exists($ip,id,$this->SourceTable); - } - - function GetLimitSQL() - { - global $objConfig; - if($this->Page<1) - $this->Page=1; - $PerPage = $objConfig->Get($this->PerPageVar); - if(is_numeric($PerPage)) - { - $Start = ($this->Page-1)*$PerPage; - $limit = "LIMIT ".$Start.",".$PerPage; - } - else - $limit = NULL; - return $limit; - } - - - function Query_Review($whereClause=NULL,$orderByClause=NULL) - { - global $Errors; - - $this->Clear(); - $sql = "SELECT * FROM ".$this->SourceTable." "; - - if(isset($whereClause) && strlen(trim($whereClause))>0) - $sql = sprintf("%s WHERE %s",$sql,$whereClause); - - if(isset($orderByClause) && strlen(trim($orderByClause))>0) - $sql = sprintf("%s ORDER BY %s",$sql,$orderByClause); - - return $this->Query_Item($sql); - } - - function &AddReview($CreatedOn,$ReviewText, $Status, $IPAddress, - $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat=0,$Module) - { - global $objSession; - - $r = new clsItemReview(NULL,$this->SourceTable); - - $ReviewText = str_replace("env=".$objSession->GetSessionKey(), "env=",$ReviewText); - //$r->debuglevel = 1; - - $r->Set(array("CreatedOn","ReviewText","Status", "IPAddress", - "Priority","ItemId","ItemType","CreatedById","TextFormat","Module"), - array($CreatedOn,$ReviewText,$Status, $IPAddress, - $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)); - $r->Create(); - array_push($this->Items,$r); - if($Status==1) - { - $r->SendUserEventMail("REVIEW.ADD",$CreatedById); - $r->SendAdminEventMail("REVIEW.ADD"); - } - else - { - $r->SendUserEventMail("REVIEW.ADD.PENDING",$CreatedById); - $r->SendAdminEventMail("REVIEW.ADD.PENDING"); - } - - return $r; - } - - function EditReview($ReviewId,$CreatedOn,$ReviewText, $Status, - $IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module) - { - global $objSession; - - $r = $this->GetItem($ReviewId); - if($CreatedById==0) - $CreatedById = $r->Get("CreatedById"); - $r->Set(array("ReviewId","CreatedOn","ReviewText","Status", - "IPAddress", "Priority", "ItemId","ItemType","CreatedById","TextFormat","Module"), - array($ReviewId,$CreatedOn,$ReviewText,$Status, - $IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)); - $r->Update(); - //$r->SendUserEventMail("REVIEW.MODIFY",$objSession->Get("PortalUserId")); - $r->SendAdminEventMail("REVIEW.MODIFY"); - return $r; - } - - function DeleteReview($ReviewId) - { - $r = $this->GetItem($ReviewId); - $r->Delete(); - } - - function CopyToItemId($OldId,$NewId) - { - $this->Clear(); - $this->Query_Review("ItemId=$OldId",""); - if($this->NumItems()>0) - { - foreach($this->Items as $i) - { - $i->Set("ItemId",$NewId); - $i->UnsetIdField(); - $i->Create(); - } - } - } - - function CopyFromEditTable($ResourceId) - { - global $objSession; - //echo "ToLive [Reviews]
"; - $edit_table = $objSession->GetEditTable($this->SourceTable); - $idlist = array(); - $sql = "SELECT * FROM $edit_table"; - $this->Clear(); - // get all items in edit-table - $rs = $this->adodbConnection->Execute($sql); - while($rs && !$rs->EOF) - { - $data =& $rs->fields; - - $c = $this->AddItemFromArray($data); - - $c->Dirty(); - if($data["ReviewId"]>0) - { - $c->Update(); - } - else - { - $c->UnsetIdField(); - $c->Create(); - } - $idlist[] = $c->Get("ReviewId"); - $rs->MoveNext(); - } - //print_pre($idlist); - $sql = "DELETE FROM ".$this->SourceTable." WHERE ItemId=$ResourceId ".(count($idlist) > 0 ? "AND ReviewId NOT IN (".implode(",",$idlist).")" : ""); - //echo "DEL REVIEW SQL: $sql
"; - $this->adodbConnection->Execute($sql); - @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$edit_table); - } - - - function GetPageLinkList(&$UpdateVar,$dest_template=NULL,$page = NULL,$PagesToList=10,$HideEmpty=TRUE) - { - global $objConfig, $var_list_update, $var_list; - - if(!strlen($page)) - $page = GetIndexURL(); - $PerPage = $objConfig->Get($this->PerPageVar); - if($PerPage<1) - $PerPage=20; - $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) - { - $UpdateVar["rp"] = $this->Page-$PagesToList; - $prev_url = $page."?env=".BuildEnv(); - $o .= "<<"; - } - - - for($p=$StartPage;$p<=$EndPage;$p++) - { - if($p!=$this->Page) - { - $UpdateVar["rp"]=$p; - $href = $page."?env=".BuildEnv(); - $o .= " $p "; - } - else - { - $o .= "$p"; - } - } - if($EndPage<$NumPages && $EndPage>0) - { - $UpdateVar["rp"]=$this->Page+$PagesToList; - $next_url = $page."?env=".BuildEnv(); - $o .= " >>"; - } - unset($UpdateVar,$var_list_update["t"] ); - return $o; - } - - -} /*clsItemReviewList*/ - -?> +Execute($sql); + if($rs) + { + $count = $rs->fields["DupCount"]; + } + return ($count>0); +} + +RegisterPrefix("clsItemReview","review","kernel/include/itemreview.php"); + +class clsItemReview extends clsParsedItem +{ + function clsItemReview($ReviewId=NULL,$table="ItemReview") + { + $this->clsParsedItem(); + $this->tablename = $table; + $this->id_field = "ReviewId"; + $this->type=-20; + $this->NoResourceId=1; + $this->TagPrefix = "review"; + + if($ReviewId!=NULL) + $this->LoadFromDatabase($ReviewId); + } + + function Validate() + { + global $Errors; + + $dataValid = true; + if(!isset($this->m_CreatedOn)) + { + $Errors->AddError("error.fieldIsRequired",'CreatedOn',"","",get_class($this),"Validate"); + $dataValid = false; + } + + if(!isset($this->m_ReviewText)) + { + $Errors->AddError("error.fieldIsRequired",'ReviewText',"","",get_class($this),"Validate"); + $dataValid = false; + } + + if(!isset($this->m_Pending)) + { + $Error->AddError("error.fieldIsRequired",'Pending',"","",get_class($this),"Validate"); + $dataValid = false; + } + + if(!isset($this->m_IPAddress)) + { + $Error->AddError("error.fieldIsRequired",'IPAddress',"","",get_class($this),"Validate"); + $dataValid = false; + } + + if(!isset($this->m_ItemId)) + { + $Error->AddError("error.fieldIsRequired",'ItemId',"","",get_class($this),"Validate"); + $dataValid = false; + } + + if(!isset($this->m_CreatedById)) + { + $Error->AddError("error.fieldIsRequired",'CreatedBy',"","",get_class($this),"Validate"); + $dataValid = false; + } + + return $dataValid; + } + + function LoadFromDatabase($Id) + { + global $objSession, $Errors; + + 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 ReviewId = '%s'",$Id); + if( $GLOBALS['debuglevel'] ) echo $sql."
"; + $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(); + return TRUE; + } + + function MoveUp() + { + $this->Increment("Priority"); + } + + function MoveDown() + { + $this->Decrement("Priority"); + } + + function ParseObject($element) + { + global $objConfig, $objCatList, $rootURL, $objUsers; + + $extra_attribs = ExtraAttributes($element->attributes); + + if(strtolower($element->name)==$this->TagPrefix) + { + $field = strtolower($element->attributes["_field"]); + switch($field) + { + case "id": + /* + @field:review.id + @description: review id + */ + $ret = $this->Get("ReviewId"); + break; + case "item_id": + /* + @field:review.item_id + @description: ID of the item being reviewed + */ + $ret = $this->Get("ItemId"); + break; + case "text": + /* + @field:review.text + @description:Review text + */ + if($this->Get("TextFormat")==0 || $element->attribues["_textonly"]) + { + $ret = inp_htmlize($this->Get("ReviewText")); + } + else + { + $ret = $this->Get("ReviewText"); + } + break; + case "ip": + /* + @field:review.ip + @description:IP address of remote host submitting the review + */ + $ret = $this->Get("IPAddress"); + break; + case "pending": + /* + @field:review.pending + @description: Returns the review pening status + */ + $ret = $this->Get("Pending"); + break; + case "item_type": + /* + @field:review.item_type + @description:Returns the name of the reviewed item type + */ + $type =& $objItemTypes->GetItem($this->Get("ItemType")); + if(is_object($type)) + $ret = $type->Get("ItemName"); + break; + case "date": + /* + @field:review.date + @description:Returns the date/time the review 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->attributes["_tz"]) + { + $d = GetLocalTime($d,$objSession->Get("tz")); + } + + $part = strtolower($element->attributes["_part"]); + if(strlen($part)) + { + $ret = ExtractDatePart($part,$d); + } + else + { + if($d<=0) + { + $ret = ""; + } + else + $ret = LangDate($d); + } + break; + case "reviewer": + /* + @field:revier.reviewer + @description:Parse a user tag for the user submitting the review + @attrib:_usertag::User tag to parse, defaults to the users login name + */ + $userfield = $element->attributes["_usertag"]; + if(!strlen($userfield)) + { + $userfield = "login"; + } + if($this->Get("CreatedById")>0) + { + $u =& $objUsers->GetItem($this->Get("CreatedById")); + $e = new clsHtmlTag(); + $e->name = $u->TagPrefix; + $e->attributes = $element->attributes; + $e->attributes["_field"] = $userfield; + $ret = $u->ParseObject($e); + } + else + if($userfield=="login") + $ret = "root"; + break; + default: + $tag = $this->TagPrefix."_".$field; + $ret = "Undefined: ".$tag->name; + break; + } + } + else + { + $ret = $element->Execute(); + } + return $ret; + } + + function parsetag($tag) + { + global $objConfig, $objUsers, $objItemTypes; + if(is_object($tag)) + { + $tagname = $tag->name; + } + else + $tagname = $tag; + switch($tagname) + { + case "review_id": + return $this->Get("ReviewId"); + break; + case "review_item_id": + return $this->Get("ItemId"); + break; + case "review_text": + return $this->Get("ReviewText"); + break; + case "review_ip_address": + return $this->Get("IPAddress"); + break; + case "review_pending": + return $this->Get("Pending"); + break; + case "review_item_type": + $type =& $objItemTypes->GetItem($this->Get("ItemType")); + $res = $type->Get("ItemName"); + return $res; + break; + case "review_created_date": + return LangDate($this->Get("CreatedOn")); + break; + case "review_created_time": + if($this->Get("CreatedOn")<=0) + return ""; + return adodb_date($objConfig->TimeFormat(), $this->Get("CreatedOn")); + break; + + case "review_created_date_month": + return adodb_date("m", $this->Get("CreatedOn")); + break; + case "review_created_date_day": + return adodb_date("d", $this->Get("CreatedOn")); + break; + case "review_created_date_year": + return adodb_date("Y", $this->Get("CreatedOn")); + break; + default: + if (substr($tagname, 0, 16) == "review_createdby") + { + /* parse the created by user */ + $u = $objUsers->GetUser($this->Get("CreatedById")); + $usertag = substr($tag,17); + return $u->parsetag($usertag); + } + else + return "Undefined:$tagname"; + break; + } + } + + function SendUserEventMail($Suffix,$ToUserId,$LangId=NULL) + { + global $objItemTypes, $objMessageList; + + $type =& $objItemTypes->GetItem($this->Get("ItemType")); + $res = $type->Get("ItemName"); + $EventName = $res.$Suffix; + + $Event =& $objMessageList->GetEmailEventObject($EventName,0,$LangId); + if(is_object($Event)) + { + if($Event->Get("Enabled")=="1") + { + $Event->Item = $this; + return $Event->SendToUser($ToUserId); + } + } + } + + function SendAdminEventMail($EventName,$LangId=NULL) + { + global $objItemTypes, $objMessageList; + + $type =& $objItemTypes->GetItem($this->Get("ItemType")); + $res = $type->Get("ItemName"); + $EventName = $res; //.$Suffix; + + $Event =& $objMessageList->GetEmailEventObject($EventName,1,$LangId); + if(is_object($Event)) + { + if($Event->Get("Enabled")=="1") + { + $Event->Item = $this; + return $Event->SendAdmin($ToUserId); + } + } + } +} /*clsIItemReview*/ + +class clsItemReviewList extends clsItemCollection +{ + var $itemID; + var $Page; + var $PerPageVar; + + function clsItemReviewList($id=NULL) + { + $this->clsItemCollection(); + $this->classname = "clsItemReview"; + $this->SourceTable = GetTablePrefix()."ItemReview"; + $this->Page = 1; + $this->PerPageVar = "Perpage_Review"; + if(isset($id)) + $this->itemID=$id; + $this->AdminSearchFields = array("ReviewText"); + } + + function ItemCount() + { + return $this->NumItems(); + } + + function GetReview($ID) + { + return $this->GetItem($ID); + } + + function GetReviewList($StatusWhere = "Status=1", $OrderBy=NULL) + { + $this->Clear(); + $where = "ItemId=".$this->itemID; + $sql = "SELECT * FROM ".$this->SourceTable." WHERE "; + if(strlen($StatusWhere)) + $where .= " AND ".$StatusWhere; + $sql .= $where; + if(strlen($OrderBy)) + $sql .= " ORDER BY ".$OrderBy; + $Limit = $this->GetLimitSQL(); + if(strlen($Limit)) + $sql .= " ".$Limit; + $this->QueryItemCount=TableCount($this->SourceTable,$where,0); + return $this->Query_item($sql); + } + + function GetItemReviewCount($TodayOnly = FALSE) + { + $sql = "SELECT count(*) as ItemCount FROM ".$this->SourceTable." WHERE ItemId=".$this->itemID." AND Status=1"; + if($TodayOnly) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $where .= " AND CreatedOn>=$today"; + } + $rs = $this->adodbConnection->execute($sql); + $count=0; + if($rs) + $count = $rs->fields["ItemCount"]; + return (int)$count; + } + + function ip_exists($ip,$id) + { + return ip_exists($ip,id,$this->SourceTable); + } + + function GetLimitSQL() + { + global $objConfig; + if($this->Page<1) + $this->Page=1; + $PerPage = $objConfig->Get($this->PerPageVar); + if(is_numeric($PerPage)) + { + $Start = ($this->Page-1)*$PerPage; + $limit = "LIMIT ".$Start.",".$PerPage; + } + else + $limit = NULL; + return $limit; + } + + + function Query_Review($whereClause=NULL,$orderByClause=NULL) + { + global $Errors; + + $this->Clear(); + $sql = "SELECT * FROM ".$this->SourceTable." "; + + if(isset($whereClause) && strlen(trim($whereClause))>0) + $sql = sprintf("%s WHERE %s",$sql,$whereClause); + + if(isset($orderByClause) && strlen(trim($orderByClause))>0) + $sql = sprintf("%s ORDER BY %s",$sql,$orderByClause); + + return $this->Query_Item($sql); + } + + function &AddReview($CreatedOn,$ReviewText, $Status, $IPAddress, + $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat=0,$Module) + { + global $objSession; + + $r = new clsItemReview(NULL,$this->SourceTable); + + $ReviewText = str_replace("env=".$objSession->GetSessionKey(), "env=",$ReviewText); + //$r->debuglevel = 1; + + $r->Set(array("CreatedOn","ReviewText","Status", "IPAddress", + "Priority","ItemId","ItemType","CreatedById","TextFormat","Module"), + array($CreatedOn,$ReviewText,$Status, $IPAddress, + $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)); + $r->Create(); + array_push($this->Items,$r); + if($Status==1) + { + $r->SendUserEventMail("REVIEW.ADD",$CreatedById); + $r->SendAdminEventMail("REVIEW.ADD"); + } + else + { + $r->SendUserEventMail("REVIEW.ADD.PENDING",$CreatedById); + $r->SendAdminEventMail("REVIEW.ADD.PENDING"); + } + + return $r; + } + + function EditReview($ReviewId,$CreatedOn,$ReviewText, $Status, + $IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module) + { + global $objSession; + + $r = $this->GetItem($ReviewId); + if($CreatedById==0) + $CreatedById = $r->Get("CreatedById"); + $r->Set(array("ReviewId","CreatedOn","ReviewText","Status", + "IPAddress", "Priority", "ItemId","ItemType","CreatedById","TextFormat","Module"), + array($ReviewId,$CreatedOn,$ReviewText,$Status, + $IPAddress, $Priority, $ItemId,$ItemType,$CreatedById,$TextFormat,$Module)); + $r->Update(); + //$r->SendUserEventMail("REVIEW.MODIFY",$objSession->Get("PortalUserId")); + $r->SendAdminEventMail("REVIEW.MODIFY"); + return $r; + } + + function DeleteReview($ReviewId) + { + $r = $this->GetItem($ReviewId); + $r->Delete(); + } + + function CopyToItemId($OldId,$NewId) + { + $this->Clear(); + $this->Query_Review("ItemId=$OldId",""); + if($this->NumItems()>0) + { + foreach($this->Items as $i) + { + $i->Set("ItemId",$NewId); + $i->UnsetIdField(); + $i->Create(); + } + } + } + + function CopyFromEditTable($ResourceId) + { + global $objSession; + //echo "ToLive [Reviews]
"; + $edit_table = $objSession->GetEditTable($this->SourceTable); + $idlist = array(); + $sql = "SELECT * FROM $edit_table"; + $this->Clear(); + // get all items in edit-table + $rs = $this->adodbConnection->Execute($sql); + while($rs && !$rs->EOF) + { + $data =& $rs->fields; + + $c = $this->AddItemFromArray($data); + + $c->Dirty(); + if($data["ReviewId"]>0) + { + $c->Update(); + } + else + { + $c->UnsetIdField(); + $c->Create(); + } + $idlist[] = $c->Get("ReviewId"); + $rs->MoveNext(); + } + //print_pre($idlist); + $sql = "DELETE FROM ".$this->SourceTable." WHERE ItemId=$ResourceId ".(count($idlist) > 0 ? "AND ReviewId NOT IN (".implode(",",$idlist).")" : ""); + //echo "DEL REVIEW SQL: $sql
"; + $this->adodbConnection->Execute($sql); + @$this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$edit_table); + } + + + function GetPageLinkList(&$UpdateVar,$dest_template=NULL,$page = NULL,$PagesToList=10,$HideEmpty=TRUE) + { + global $objConfig, $var_list_update, $var_list; + + if(!strlen($page)) + $page = GetIndexURL(); + $PerPage = $objConfig->Get($this->PerPageVar); + if($PerPage<1) + $PerPage=20; + $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) + { + $UpdateVar["rp"] = $this->Page-$PagesToList; + $prev_url = $page."?env=".BuildEnv(); + $o .= "<<"; + } + + + for($p=$StartPage;$p<=$EndPage;$p++) + { + if($p!=$this->Page) + { + $UpdateVar["rp"]=$p; + $href = $page."?env=".BuildEnv(); + $o .= " $p "; + } + else + { + $o .= "$p"; + } + } + if($EndPage<$NumPages && $EndPage>0) + { + $UpdateVar["rp"]=$this->Page+$PagesToList; + $next_url = $page."?env=".BuildEnv(); + $o .= " >>"; + } + unset($UpdateVar,$var_list_update["t"] ); + return $o; + } + + +} /*clsItemReviewList*/ + +?> Index: trunk/admin/users/adduser.php =================================================================== diff -u -N -r624 -r642 --- trunk/admin/users/adduser.php (.../adduser.php) (revision 624) +++ trunk/admin/users/adduser.php (.../adduser.php) (revision 642) @@ -1,385 +1,386 @@ -Get("Site_Path"); -$admin = $objConfig->Get("AdminDirectory"); -if(!strlen($admin)) - $admin = "admin"; -$localURL=$rootURL."kernel/"; -$adminURL = $rootURL.$admin; -$imagesURL = $adminURL."/images"; -//$pathtolocal = $pathtoroot."in-news/"; -require_once ($pathtoroot.$admin."/include/elements.php"); -require_once ($pathtoroot."kernel/admin/include/navmenu.php"); -//require_once ($pathtolocal."admin/include/navmenu.php"); -require_once($pathtoroot.$admin."/toolbar.php"); - -unset($objEditItems); -$objEditItems = new clsUserManager(); -$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser"); -$objEditItems->EnablePaging = FALSE; -$objCustomFields = new clsCustomFieldList(6); -$objRelList = new clsRelationshipList(); -$objImages = new clsImageList(); -//$objUserGroupsList = new clsUserGroupList(); - -//Multiedit init -if ( GetVar('new') == 1) -{ - $c = new clsPortalUser(NULL); - $c->Set("CreatedOn", time()); - $c->Set("Status", 2); - $en = 0; - $action = "m_add_user"; - $objUsers->CreateEmptyEditTable("PortalUserId"); - $objRelList->CreateEmptyEditTable("RelationshipId"); - $objCustomDataList->CreateEmptyEditTable("CustomDataId"); - $objImages->CreateEmptyEditTable("ResourceId"); - //$objUserGroupsList->CreateEmptyEditTable("PortalUserId"); -} -else -{ - $en = GetVar('en'); - if (isset($_POST["itemlist"])) - { - $objUsers->CopyToEditTable("ResourceId",$_POST["itemlist"]); - } - $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); - $first=1; - foreach($objEditItems->Items as $u) - { - $objItemTypes->BuildUserItemTable($u->Get("PortalUserId"),$first); - $first=0; - } - - if(isset($_POST["itemlist"])) - { - /* make a copy of the relationship records */ - $ids = $objEditItems->GetResourceIDList(); - $objRelList->CopyToEditTable("SourceId",$ids); - $objCustomDataList->CopyToEditTable("ResourceId",$ids); - $objImages->CopyToEditTable("ResourceId",$ids); - //$objUserGroupsList->CopyToEditTable("PortalUserId", $ids); - } - - $itemcount=$objEditItems->NumItems(); - $c = $objEditItems->GetItemByIndex($en); - - if($itemcount>1) - { - if ($en+1 == $itemcount) - $en_next = -1; - else - $en_next = $en+1; - - if ($en == 0) - $en_prev = -1; - else - $en_prev = $en-1; - } - $action = "m_edit_user"; -} - -$envar = "env=" . BuildEnv() . "&en=$en"; - -$section = 'in-portal:edituser_general'; - -if (strlen($c->Get("Login"))) - $editing_title = "'".$c->Get("Login")."' "; -else - $editing_title = ""; - - -//$title = prompt_language("la_Text_Editing")." ".prompt_language("la_Text_User")." $editing_title- ".prompt_language("la_tab_General"); -$title = GetTitle("la_Text_User", "la_Text_General", $c->Get('PortalUserId'), $c->Get('Login')); - -//Display header -$sec = $objSections->GetSection($section); -$objCatToolBar = new clsToolBar(); -$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('edituser','UserEditStatus','".$admin."/users/user_list.php',1);","tool_select.gif"); -$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('edituser','UserEditStatus','".$admin."/users/user_list.php',2);","tool_cancel.gif"); - -if ( isset($en_prev) || isset($en_next) ) -{ - $url = $RootUrl.$admin."/users/adduser.php"; - $StatusField = "UserEditStatus"; - $form = "edituser"; - MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevUser','la_NextUser'); -} - -int_header($objCatToolBar,NULL,$title); -?> - - - - - - - - > - - - - - > - - - - - > - - - - - - - - > - - - - - > - - - - - - > - - - - - > - - - - - - > - - - - - - > - - - - - > - - - - - > - - - - - > - - - - - > - - - - - - > - - - - - - > - - - - - > - - - - - - -GetFieldUIList(TRUE); // get custom fields to show on general tab -if($CustomFieldUI->NumItems()>0) -{ - $objCustomDataList->SetTable('edit'); - - if((int)$c->Get("ResourceId")>0) - $objCustomDataList->LoadResource($c->Get("ResourceId")); - - $headings = $CustomFieldUI->GetHeadingList(); - // draw headings - for($i = 0; $i < count($headings); $i++) - { - $h = $headings[$i]; - if(strlen($h)) - { - int_subsection_title(prompt_language($h)); - $Items = $CustomFieldUI->GetHeadingItems($h); - foreach($Items as $f) - { - $n = substr($f->name,1); // TabIndex - $cfield = $objCustomFields->GetItemByField('FieldName',$n,FALSE); - if(is_object($cfield)) - { - $cv = $objCustomDataList->GetDataItem($cfield->Get("CustomFieldId")); - if(is_object($cv)) - { - $f->default_value = $cv->Get("Value"); - } - } - print "\n"; - print " \n"; - - print " "; - if(is_object($f->NextItem)) - { - $n = $f->NextItem; - print " "; - } - else - print " \n"; - print "\n"; - } - } - } - $objCustomDataList->SetTable('live'); -} -?> - > - - - - -
- "> - -
- - -
- -
- "> -
- "> -
- "> -  
- "> -
- "> -  
- "> -  
- "> -  
- "> -  
- "> -  
- "> -  
- Get("Status") == 1) echo "checked"; ?>> - Get("Status") == 2) echo "checked"; ?>> - Get("Status") == 0) echo "checked"; ?>> -  
- "> -
- "> -
".$f->GetPrompt()."".$f->ItemFormElement(17)."".$n->ItemFormElement(17)." 
- - "> - -
- - - -Get("Site_Path"); +$admin = $objConfig->Get("AdminDirectory"); +if(!strlen($admin)) + $admin = "admin"; +$localURL=$rootURL."kernel/"; +$adminURL = $rootURL.$admin; +$imagesURL = $adminURL."/images"; +//$pathtolocal = $pathtoroot."in-news/"; +require_once ($pathtoroot.$admin."/include/elements.php"); +require_once ($pathtoroot."kernel/admin/include/navmenu.php"); +//require_once ($pathtolocal."admin/include/navmenu.php"); +require_once($pathtoroot.$admin."/toolbar.php"); + +unset($objEditItems); +$objEditItems = new clsUserManager(); +$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser"); +$objEditItems->EnablePaging = FALSE; +$objCustomFields = new clsCustomFieldList(6); +$objRelList = new clsRelationshipList(); +$objImages = new clsImageList(); +//$objUserGroupsList = new clsUserGroupList(); + +//Multiedit init +if ( GetVar('new') == 1) +{ + $c = new clsPortalUser(NULL); + $c->Set("CreatedOn", time()); + $c->Set("Status", 2); + $en = 0; + $action = "m_add_user"; + $objUsers->CreateEmptyEditTable("PortalUserId"); + $objRelList->CreateEmptyEditTable("RelationshipId"); + $objCustomDataList->CreateEmptyEditTable("CustomDataId"); + $objImages->CreateEmptyEditTable("ResourceId"); + //$objUserGroupsList->CreateEmptyEditTable("PortalUserId"); +} +else +{ + $en = GetVar('en'); + if (isset($_POST["itemlist"])) + { + $objUsers->CopyToEditTable("ResourceId",$_POST["itemlist"]); + } + $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); + $first=1; + foreach($objEditItems->Items as $u) + { + $objItemTypes->BuildUserItemTable($u->Get("PortalUserId"),$first); + $first=0; + } + + if(isset($_POST["itemlist"])) + { + /* make a copy of the relationship records */ + $ids = $objEditItems->GetResourceIDList(); + $objRelList->CopyToEditTable("SourceId",$ids); + $objCustomDataList->CopyToEditTable("ResourceId",$ids); + $objImages->CopyToEditTable("ResourceId",$ids); + //$objUserGroupsList->CopyToEditTable("PortalUserId", $ids); + } + + $itemcount=$objEditItems->NumItems(); + $c = $objEditItems->GetItemByIndex($en); + + if($itemcount>1) + { + if ($en+1 == $itemcount) + $en_next = -1; + else + $en_next = $en+1; + + if ($en == 0) + $en_prev = -1; + else + $en_prev = $en-1; + } + $action = "m_edit_user"; +} + +$envar = "env=" . BuildEnv() . "&en=$en"; + +$section = 'in-portal:edituser_general'; + +if (strlen($c->Get("Login"))) + $editing_title = "'".$c->Get("Login")."' "; +else + $editing_title = ""; + +$c->Data=inp_htmlize($c->Data); + +//$title = prompt_language("la_Text_Editing")." ".prompt_language("la_Text_User")." $editing_title- ".prompt_language("la_tab_General"); +$title = GetTitle("la_Text_User", "la_Text_General", $c->Get('PortalUserId'), $c->Get('Login')); + +//Display header +$sec = $objSections->GetSection($section); +$objCatToolBar = new clsToolBar(); +$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('edituser','UserEditStatus','".$admin."/users/user_list.php',1);","tool_select.gif"); +$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('edituser','UserEditStatus','".$admin."/users/user_list.php',2);","tool_cancel.gif"); + +if ( isset($en_prev) || isset($en_next) ) +{ + $url = $RootUrl.$admin."/users/adduser.php"; + $StatusField = "UserEditStatus"; + $form = "edituser"; + MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevUser','la_NextUser'); +} + +int_header($objCatToolBar,NULL,$title); +?> + + + + + + + + > + + + + + > + + + + + > + + + + + + + + > + + + + + > + + + + + + > + + + + + > + + + + + + > + + + + + + > + + + + + > + + + + + > + + + + + > + + + + + > + + + + + + > + + + + + + > + + + + + > + + + + + + +GetFieldUIList(TRUE); // get custom fields to show on general tab +if($CustomFieldUI->NumItems()>0) +{ + $objCustomDataList->SetTable('edit'); + + if((int)$c->Get("ResourceId")>0) + $objCustomDataList->LoadResource($c->Get("ResourceId")); + + $headings = $CustomFieldUI->GetHeadingList(); + // draw headings + for($i = 0; $i < count($headings); $i++) + { + $h = $headings[$i]; + if(strlen($h)) + { + int_subsection_title(prompt_language($h)); + $Items = $CustomFieldUI->GetHeadingItems($h); + foreach($Items as $f) + { + $n = substr($f->name,1); // TabIndex + $cfield = $objCustomFields->GetItemByField('FieldName',$n,FALSE); + if(is_object($cfield)) + { + $cv = $objCustomDataList->GetDataItem($cfield->Get("CustomFieldId")); + if(is_object($cv)) + { + $f->default_value = $cv->Get("Value"); + } + } + print "\n"; + print " \n"; + + print " "; + if(is_object($f->NextItem)) + { + $n = $f->NextItem; + print " "; + } + else + print " \n"; + print "\n"; + } + } + } + $objCustomDataList->SetTable('live'); +} +?> + > + + + + +
+ "> + +
+ + +
+ +
+ "> +
+ "> +
+ "> +  
+ "> +
+ "> +  
+ "> +  
+ "> +  
+ "> +  
+ "> +  
+ "> +  
+ Get("Status") == 1) echo "checked"; ?>> + Get("Status") == 2) echo "checked"; ?>> + Get("Status") == 0) echo "checked"; ?>> +  
+ "> +
+ "> +
".$f->GetPrompt()."".$f->ItemFormElement(17)."".$n->ItemFormElement(17)." 
+ + "> + +
+ + + + \ No newline at end of file Index: trunk/kernel/include/adodb/adodb.inc.php =================================================================== diff -u -N -r228 -r642 --- trunk/kernel/include/adodb/adodb.inc.php (.../adodb.inc.php) (revision 228) +++ trunk/kernel/include/adodb/adodb.inc.php (.../adodb.inc.php) (revision 642) @@ -1,3379 +1,3389 @@ - - Manual is at http://php.weblogs.com/adodb_manual - - */ - - if (!defined('_ADODB_LAYER')) { - define('_ADODB_LAYER',1); - - //============================================================================================== - // CONSTANT DEFINITIONS - //============================================================================================== - - define('ADODB_BAD_RS','

Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;

'); - - define('ADODB_FETCH_DEFAULT',0); - define('ADODB_FETCH_NUM',1); - define('ADODB_FETCH_ASSOC',2); - define('ADODB_FETCH_BOTH',3); - - /* - Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names. - This currently works only with mssql, odbc, oci8po and ibase derived drivers. - - 0 = assoc lowercase field names. $rs->fields['orderid'] - 1 = assoc uppercase field names. $rs->fields['ORDERID'] - 2 = use native-case field names. $rs->fields['OrderID'] - */ - if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); - - // allow [ ] @ ` and . in table names - define('ADODB_TABLE_REGEX','([]0-9a-z_\`\.\@\[-]*)'); - - - if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); - - /** - * Set ADODB_DIR to the directory where this file resides... - * This constant was formerly called $ADODB_RootPath - */ - if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__)); - - if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100); - - //============================================================================================== - // GLOBAL VARIABLES - //============================================================================================== - - GLOBAL - $ADODB_vers, // database version - $ADODB_Database, // last database driver used - $ADODB_COUNTRECS, // count number of records returned - slows down query - $ADODB_CACHE_DIR, // directory to cache recordsets - $ADODB_EXTENSION, // ADODB extension installed - $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF - $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... - - //============================================================================================== - // GLOBAL SETUP - //============================================================================================== - - if (strnatcmp(PHP_VERSION,'4.3.0')>=0) { - define('ADODB_PHPVER',0x4300); - } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) { - define('ADODB_PHPVER',0x4200); - } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) { - define('ADODB_PHPVER',0x4050); - } else { - define('ADODB_PHPVER',0x4000); - } - $ADODB_EXTENSION = defined('ADODB_EXTENSION'); - //if (extension_loaded('dbx')) define('ADODB_DBX',1); - - /** - Accepts $src and $dest arrays, replacing string $data - */ - function ADODB_str_replace($src, $dest, $data) - { - if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data); - - $s = reset($src); - $d = reset($dest); - while ($s !== false) { - $data = str_replace($s,$d,$data); - $s = next($src); - $d = next($dest); - } - return $data; - } - - function ADODB_Setup() - { - GLOBAL - $ADODB_vers, // database version - $ADODB_Database, // last database driver used - $ADODB_COUNTRECS, // count number of records returned - slows down query - $ADODB_CACHE_DIR, // directory to cache recordsets - $ADODB_FETCH_MODE; - - $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; - - if (!isset($ADODB_CACHE_DIR)) { - $ADODB_CACHE_DIR = '/tmp'; - } else { - // do not accept url based paths, eg. http:/ or ftp:/ - if (strpos($ADODB_CACHE_DIR,'://') !== false) - die("Illegal path http:// or ftp://"); - } - - - // Initialize random number generator for randomizing cache flushes - srand(((double)microtime())*1000000); - - /** - * Name of last database driver loaded into memory. Set by ADOLoadCode(). - */ - $ADODB_Database = ''; - - /** - * ADODB version as a string. - */ - $ADODB_vers = 'V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved. Released BSD & LGPL.'; - - /** - * Determines whether recordset->RecordCount() is used. - * Set to false for highest performance -- RecordCount() will always return -1 then - * for databases that provide "virtual" recordcounts... - */ - $ADODB_COUNTRECS = true; - } - - - //============================================================================================== - // CHANGE NOTHING BELOW UNLESS YOU ARE CODING - //============================================================================================== - - ADODB_Setup(); - - //============================================================================================== - // CLASS ADOFieldObject - //============================================================================================== - /** - * Helper class for FetchFields -- holds info on a column - */ - class ADOFieldObject { - var $name = ''; - var $max_length=0; - var $type=""; - - // additional fields by dannym... (danny_milo@yahoo.com) - var $not_null = false; - // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^ - // so we can as well make not_null standard (leaving it at "false" does not harm anyways) - - var $has_default = false; // this one I have done only in mysql and postgres for now ... - // others to come (dannym) - var $default_value; // default, if any, and supported. Check has_default first. - } - - - - function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) - { - //print "Errorno ($fn errno=$errno m=$errmsg) "; - - $thisConnection->_transOK = false; - if ($thisConnection->_oldRaiseFn) { - $fn = $thisConnection->_oldRaiseFn; - $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); - } - } - - //============================================================================================== - // CLASS ADOConnection - //============================================================================================== - - /** - * Connection object. For connecting to databases, and executing queries. - */ - class ADOConnection { - // - // PUBLIC VARS - // - var $dataProvider = 'native'; - var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql - var $database = ''; /// Name of database to be used. - var $host = ''; /// The hostname of the database server - var $user = ''; /// The username which is used to connect to the database server. - var $password = ''; /// Password for the username. For security, we no longer store it. - var $debug = false; /// if set to true will output sql statements - var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro - var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase - var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database - var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt. - var $true = '1'; /// string that represents TRUE for a database - var $false = '0'; /// string that represents FALSE for a database - var $replaceQuote = "\\'"; /// string to use to replace quotes - var $charSet=false; /// character set to use - only for interbase - var $metaDatabasesSQL = ''; - var $metaTablesSQL = ''; - var $uniqueOrderBy = false; /// All order by columns have to be unique - var $emptyDate = ' '; - //-- - var $hasInsertID = false; /// supports autoincrement ID? - var $hasAffectedRows = false; /// supports affected rows for update/delete? - var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE - var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10 - var $readOnly = false; /// this is a readonly database - used by phpLens - var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards - var $hasGenID = false; /// can generate sequences using GenID(); - var $hasTransactions = true; /// has transactions - //-- - var $genID = 0; /// sequence id used by GenID(); - var $raiseErrorFn = false; /// error function to call - var $upperCase = false; /// uppercase function to call for searching/where - var $isoDates = false; /// accepts dates in ISO format - var $cacheSecs = 3600; /// cache for 1 hour - var $sysDate = false; /// name of function that returns the current date - var $sysTimeStamp = false; /// name of function that returns the current timestamp - var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets - - var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' - var $numCacheHits = 0; - var $numCacheMisses = 0; - var $pageExecuteCountRows = true; - var $uniqueSort = false; /// indicates that all fields in order by must be unique - var $leftOuter = false; /// operator to use for left outer join in WHERE clause - var $rightOuter = false; /// operator to use for right outer join in WHERE clause - var $ansiOuter = false; /// whether ansi outer join syntax supported - var $autoRollback = false; // autoRollback on PConnect(). - var $poorAffectedRows = false; // affectedRows not working or unreliable - - var $fnExecute = false; - var $fnCacheExecute = false; - var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char - var $dbxDriver = false; - - // - // PRIVATE VARS - // - var $_oldRaiseFn = false; - var $_transOK = null; - var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. - var $_errorMsg = ''; /// A variable which was used to keep the returned last error message. The value will - /// then returned by the errorMsg() function - - var $_queryID = false; /// This variable keeps the last created result link identifier - - var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ - var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. - var $autoCommit = true; /// do not modify this yourself - actually private - var $transOff = 0; /// temporarily disable transactions - var $transCnt = 0; /// count of nested transactions - - var $fetchMode=false; - - /** - * Constructor - */ - function ADOConnection() - { - die('Virtual Class -- cannot instantiate'); - } - - /** - Get server version info... - - @returns An array with 2 elements: $arr['string'] is the description string, - and $arr[version] is the version (also a string). - */ - function ServerInfo() - { - return array('description' => '', 'version' => ''); - } - - function _findvers($str) - { - if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; - else return ''; - } - - /** - * All error messages go through this bottleneck function. - * You can define your own handler by defining the function name in ADODB_OUTP. - */ - function outp($msg,$newline=true) - { - global $HTTP_SERVER_VARS; - - if (defined('ADODB_OUTP')) { - $fn = ADODB_OUTP; - $fn($msg,$newline); - return; - } - - if ($newline) $msg .= "
\n"; - - if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg; - else echo strip_tags($msg); - flush(); - } - - /** - * Connect to database - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * @param [forceNew] force new connection - * - * @return true or false - */ - function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) - { - if ($argHostname != "") $this->host = $argHostname; - if ($argUsername != "") $this->user = $argUsername; - if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons - if ($argDatabaseName != "") $this->database = $argDatabaseName; - - $this->_isPersistentConnection = false; - if ($fn = $this->raiseErrorFn) { - if ($forceNew) { - if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; - } else { - if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; - } - $err = $this->ErrorMsg(); - if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; - $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); - } else { - if ($forceNew) { - if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; - } else { - if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; - } - } - if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg()); - return false; - } - - function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) - { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName); - } - - - /** - * Always force a new connection to database - currently only works with oracle - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * - * @return true or false - */ - function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") - { - return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true); - } - - /** - * Establish persistent connect to database - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * - * @return return true or false - */ - function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") - { - if (defined('ADODB_NEVER_PERSIST')) - return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName); - - if ($argHostname != "") $this->host = $argHostname; - if ($argUsername != "") $this->user = $argUsername; - if ($argPassword != "") $this->password = $argPassword; - if ($argDatabaseName != "") $this->database = $argDatabaseName; - - $this->_isPersistentConnection = true; - - if ($fn = $this->raiseErrorFn) { - if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; - $err = $this->ErrorMsg(); - if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; - $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); - } else - if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; - - if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg()); - return false; - } - - // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) - { - if (!$col) $col = $this->sysDate; - return $col; // child class implement - } - - /** - * Should prepare the sql statement and return the stmt resource. - * For databases that do not support this, we return the $sql. To ensure - * compatibility with databases that do not support prepare: - * - * $stmt = $db->Prepare("insert into table (id, name) values (?,?)"); - * $db->Execute($stmt,array(1,'Jill')) or die('insert failed'); - * $db->Execute($stmt,array(2,'Joe')) or die('insert failed'); - * - * @param sql SQL to send to database - * - * @return return FALSE, or the prepared statement, or the original sql if - * if the database does not support prepare. - * - */ - function Prepare($sql) - { - return $sql; - } - - /** - * Some databases, eg. mssql require a different function for preparing - * stored procedures. So we cannot use Prepare(). - * - * Should prepare the stored procedure and return the stmt resource. - * For databases that do not support this, we return the $sql. To ensure - * compatibility with databases that do not support prepare: - * - * @param sql SQL to send to database - * - * @return return FALSE, or the prepared statement, or the original sql if - * if the database does not support prepare. - * - */ - function PrepareSP($sql) - { - return $this->Prepare($sql); - } - - /** - * PEAR DB Compat - */ - function Quote($s) - { - return $this->qstr($s,false); - } - - function q(&$s) - { - $s = $this->qstr($s,false); - } - - /** - * PEAR DB Compat - do not use internally. - */ - function ErrorNative() - { - return $this->ErrorNo(); - } - - - /** - * PEAR DB Compat - do not use internally. - */ - function nextId($seq_name) - { - return $this->GenID($seq_name); - } - - /** - * Lock a row, will escalate and lock the table if row locking not supported - * will normally free the lock at the end of the transaction - * - * @param $table name of table to lock - * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock - */ - function RowLock($table,$where) - { - return false; - } - - function CommitLock($table) - { - return $this->CommitTrans(); - } - - function RollbackLock($table) - { - return $this->RollbackTrans(); - } - - /** - * PEAR DB Compat - do not use internally. - * - * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical - * for easy porting :-) - * - * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM - * @returns The previous fetch mode - */ - function SetFetchMode($mode) - { - $old = $this->fetchMode; - $this->fetchMode = $mode; - - if ($old === false) { - global $ADODB_FETCH_MODE; - return $ADODB_FETCH_MODE; - } - return $old; - } - - - /** - * PEAR DB Compat - do not use internally. - */ - function &Query($sql, $inputarr=false) - { - $rs = &$this->Execute($sql, $inputarr); - if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - return $rs; - } - - - /** - * PEAR DB Compat - do not use internally - */ - function &LimitQuery($sql, $offset, $count) - { - $rs = &$this->SelectLimit($sql, $count, $offset); // swap - if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - return $rs; - } - - - /** - * PEAR DB Compat - do not use internally - */ - function Disconnect() - { - return $this->Close(); - } - - /* - Usage in oracle - $stmt = $db->Prepare('select * from table where id =:myid and group=:group'); - $db->Parameter($stmt,$id,'myid'); - $db->Parameter($stmt,$group,'group',64); - $db->Execute(); - - @param $stmt Statement returned by Prepare() or PrepareSP(). - @param $var PHP variable to bind to - @param $name Name of stored procedure variable name to bind to. - @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8. - @param [$maxLen] Holds an maximum length of the variable. - @param [$type] The data type of $var. Legal values depend on driver. - - */ - function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) - { - return false; - } - - /** - Improved method of initiating a transaction. Used together with CompleteTrans(). - Advantages include: - - a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans. - Only the outermost block is treated as a transaction.
- b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
- c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block - are disabled, making it backward compatible. - */ - function StartTrans($errfn = 'ADODB_TransMonitor') - { - - if ($this->transOff > 0) { - $this->transOff += 1; - return; - } - - $this->_oldRaiseFn = $this->raiseErrorFn; - $this->raiseErrorFn = $errfn; - $this->_transOK = true; - - if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); - $this->BeginTrans(); - $this->transOff = 1; - } - - /** - Used together with StartTrans() to end a transaction. Monitors connection - for sql errors, and will commit or rollback as appropriate. - - @autoComplete if true, monitor sql errors and commit and rollback as appropriate, - and if set to false force rollback even if no SQL error detected. - @returns true on commit, false on rollback. - */ - function CompleteTrans($autoComplete = true) - { - if ($this->transOff > 1) { - $this->transOff -= 1; - return true; - } - $this->raiseErrorFn = $this->_oldRaiseFn; - - $this->transOff = 0; - if ($this->_transOK && $autoComplete) $this->CommitTrans(); - else $this->RollbackTrans(); - - return $this->_transOK; - } - - /* - At the end of a StartTrans/CompleteTrans block, perform a rollback. - */ - function FailTrans() - { - if ($this->debug && $this->transOff == 0) { - ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); - } - $this->_transOK = false; - } - - function getmicrotime() - { - list($usec, $sec) = explode(" ",microtime()); - return ((float)$usec + (float)$sec); - } - - /** - * Execute SQL - * - * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) - * @param [inputarr] holds the input data to bind to. Null elements will be set to null. - * @param [arg3] reserved for john lim for future use - * @return RecordSet or false - */ - function &Execute($sql,$inputarr=false,$arg3=false) - { - global $pathtoroot, $totalsql, $sqlcount; - - if ($this->fnExecute) { - $fn = $this->fnExecute; - $fn($this,$sql,$inputarr); - } - if (!$this->_bindInputArray && $inputarr) { - $sqlarr = explode('?',$sql); - $sql = ''; - $i = 0; - foreach($inputarr as $v) { - - $sql .= $sqlarr[$i]; - // from Ron Baldwin - // Only quote string types - if (gettype($v) == 'string') - $sql .= $this->qstr($v); - else if ($v === null) - $sql .= 'NULL'; - else - $sql .= $v; - $i += 1; - - } - $sql .= $sqlarr[$i]; - if ($i+1 != sizeof($sqlarr)) - ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql)); - $inputarr = false; - } - // debug version of query - if ($this->debug) { - global $HTTP_SERVER_VARS; - - $ss = ''; - if ($inputarr) { - foreach ($inputarr as $kk => $vv) { - if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...'; - $ss .= "($kk=>'$vv') "; - } - $ss = "[ $ss ]"; - } - $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql); - - // check if running from browser or command-line - $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); - - if ($inBrowser) - ADOConnection::outp( "
\n($this->databaseType): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); - else - ADOConnection::outp( "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false); - flush(); - - $this->_queryID = $this->_query($sql,$inputarr,$arg3); - - /* - Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql - because ErrorNo() calls Execute('SELECT @ERROR'), causing recure - */ - if ($this->databaseType == 'mssql') { - // ErrorNo is a slow function call in mssql, and not reliable - // in PHP 4.0.6 - if($emsg = $this->ErrorMsg()) { - $err = $this->ErrorNo(); - if ($err) { - ADOConnection::outp($err.': '.$emsg); - flush(); - } - } - } else - if (!$this->_queryID) { - $e = $this->ErrorNo(); - $m = $this->ErrorMsg(); - ADOConnection::outp($e .': '. $m ); - flush(); - } - } else { - // non-debug version of query - - - $sqlcount++; - $sql_start = $this->getmicrotime(); - $this->_queryID =@$this->_query($sql,$inputarr,$arg3); - $sql_end = $this->getmicrotime(); - $elapsed = $sql_end - $sql_start; - $totalsql += $elapsed; - //$fp = @fopen ($pathtoroot."log.sql", "aw"); - $starttime = 0; // by Alex (variable was not defined) - $d=time()-$starttime; - $t=date("Y-m-d\tH:i:s",$starttime); - $e = round($elapsed,5); - if(function_exists("LogEntry")) - @LogEntry("\t\t$sqlcount|$e:|$sql\n"); - - } - // error handling if query fails - if ($this->_queryID === false) { - $fn = $this->raiseErrorFn; - if ($fn) { - $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this); - } - return false; - } else if ($this->_queryID === true) { - // return simplified empty recordset for inserts/updates/deletes with lower overhead - $rs = new ADORecordSet_empty(); - return $rs; - } - - // return real recordset from select statement - $rsclass = "ADORecordSet_".$this->databaseType; - $rs = new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions - $rs->connection = &$this; // Pablo suggestion - $rs->Init(); - if (is_array($sql)) $rs->sql = $sql[0]; - else $rs->sql = $sql; - - if ($rs->_numOfRows <= 0) { - global $ADODB_COUNTRECS; - - if ($ADODB_COUNTRECS) { - if (!$rs->EOF){ - $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql)); - $rs->_queryID = $this->_queryID; - } else - $rs->_numOfRows = 0; - } - } - return $rs; - } - - function CreateSequence($seqname='adodbseq',$startID=1) - { - if (empty($this->_genSeqSQL)) return false; - return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); - } - - function DropSequence($seqname) - { - if (empty($this->_dropSeqSQL)) return false; - return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); - } - - /** - * Generates a sequence id and stores it in $this->genID; - * GenID is only available if $this->hasGenID = true; - * - * @param seqname name of sequence to use - * @param startID if sequence does not exist, start at this ID - * @return 0 if not supported, otherwise a sequence id - */ - - function GenID($seqname='adodbseq',$startID=1) - { - if (!$this->hasGenID) { - return 0; // formerly returns false pre 1.60 - } - - $getnext = sprintf($this->_genIDSQL,$seqname); - $rs = @$this->Execute($getnext); - if (!$rs) { - $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); - $rs = $this->Execute($getnext); - } - if ($rs && !$rs->EOF) $this->genID = reset($rs->fields); - else $this->genID = 0; // false - - if ($rs) $rs->Close(); - - return $this->genID; - } - - /** - * @return the last inserted ID. Not all databases support this. - */ - function Insert_ID() - { - if ($this->hasInsertID) return $this->_insertid(); - if ($this->debug) ADOConnection::outp( '

Insert_ID error

'); - return false; - } - - - /** - * Portable Insert ID. Pablo Roca - * - * @return the last inserted ID. All databases support this. But aware possible - * problems in multiuser environments. Heavy test this before deploying. - */ - function PO_Insert_ID($table="", $id="") - { - if ($this->hasInsertID){ - return $this->Insert_ID(); - } else { - return $this->GetOne("SELECT MAX($id) FROM $table"); - } - } - - - /** - * @return # rows affected by UPDATE/DELETE - */ - function Affected_Rows() - { - if ($this->hasAffectedRows) { - $val = $this->_affectedrows(); - return ($val < 0) ? false : $val; - } - - if ($this->debug) ADOConnection::outp( '

Affected_Rows error

',false); - return false; - } - - - /** - * @return the last error message - */ - function ErrorMsg() - { - return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; - } - - - /** - * @return the last error number. Normally 0 means no error. - */ - function ErrorNo() - { - return ($this->_errorMsg) ? -1 : 0; - } - - function MetaError($err=false) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - if ($err === false) $err = $this->ErrorNo(); - return adodb_error($this->dataProvider,$this->databaseType,$err); - } - - function MetaErrorMsg($errno) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - return adodb_errormsg($errno); - } - - /** - * @returns an array with the primary key columns in it. - */ - function MetaPrimaryKeys($table, $owner=false) - { - // owner not used in base class - see oci8 - $p = array(); - $objs =& $this->MetaColumns($table); - if ($objs) { - foreach($objs as $v) { - if (!empty($v->primary_key)) - $p[] = $v->name; - } - } - if (sizeof($p)) return $p; - return false; - } - - - /** - * Choose a database to connect to. Many databases do not support this. - * - * @param dbName is the name of the database to select - * @return true or false - */ - function SelectDB($dbName) - {return false;} - - - /** - * Will select, getting rows from $offset (1-based), for $nrows. - * This simulates the MySQL "select * from table limit $offset,$nrows" , and - * the PostgreSQL "select * from table limit $nrows offset $offset". Note that - * MySQL and PostgreSQL parameter ordering is the opposite of the other. - * eg. - * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) - * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) - * - * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) - * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set - * - * @param sql - * @param [offset] is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to get - * @param [inputarr] array of bind variables - * @param [arg3] is a private parameter only used by jlim - * @param [secs2cache] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - */ - function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0) - { - if ($this->hasTop && $nrows > 0) { - // suggested by Reinhard Balling. Access requires top after distinct - // Informix requires first before distinct - F Riosa - $ismssql = (strpos($this->databaseType,'mssql') !== false); - if ($ismssql) $isaccess = false; - else $isaccess = (strpos($this->databaseType,'access') !== false); - - if ($offset <= 0) { - - // access includes ties in result - if ($isaccess) { - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); - - if ($secs2cache>0) return $this->CacheExecute($secs2cache, $sql,$inputarr,$arg3); - else return $this->Execute($sql,$inputarr,$arg3); - } else if ($ismssql){ - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); - } else { - $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); - } - } else { - $nn = $nrows + $offset; - if ($isaccess || $ismssql) { - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); - } else { - $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); - } - } - } - - // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows - // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - if ($offset>0){ - if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3); - else $rs = &$this->Execute($sql,$inputarr,$arg3); - } else { - if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3); - else $rs = &$this->Execute($sql,$inputarr,$arg3); - } - $ADODB_COUNTRECS = $savec; - if ($rs && !$rs->EOF) { - return $this->_rs2rs($rs,$nrows,$offset); - } - //print_r($rs); - return $rs; - } - - - /** - * Convert database recordset to an array recordset - * input recordset's cursor should be at beginning, and - * old $rs will be closed. - * - * @param rs the recordset to copy - * @param [nrows] number of rows to retrieve (optional) - * @param [offset] offset by number of rows (optional) - * @return the new recordset - */ - function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) - { - if (! $rs) return false; - - $dbtype = $rs->databaseType; - if (!$dbtype) { - $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? - return $rs; - } - if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { - $rs->MoveFirst(); - $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? - return $rs; - } - $flds = array(); - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { - $flds[] = $rs->FetchField($i); - } - $arr =& $rs->GetArrayLimit($nrows,$offset); - //print_r($arr); - if ($close) $rs->Close(); - - $arrayClass = $this->arrayClass; - - $rs2 = new $arrayClass(); - $rs2->connection = &$this; - $rs2->sql = $rs->sql; - $rs2->dataProvider = $this->dataProvider; - $rs2->InitArrayFields($arr,$flds); - return $rs2; - } - - - function &GetArray($sql, $inputarr=false) - { - return $this->GetAll($sql,$inputarr); - } - - /** - * Return first element of first row of sql statement. Recordset is disposed - * for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function GetOne($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - $crecs = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - $ret = false; - $rs = &$this->Execute($sql,$inputarr); - if ($rs) { - if (!$rs->EOF) $ret = reset($rs->fields); - $rs->Close(); - } - $ADODB_COUNTRECS = $crecs; - return $ret; - } - - function CacheGetOne($secs2cache,$sql=false,$inputarr=false) - { - $ret = false; - $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); - if ($rs) { - if (!$rs->EOF) $ret = reset($rs->fields); - $rs->Close(); - } - - return $ret; - } - - function GetCol($sql, $inputarr = false, $trim = false) - { - $rv = false; - $rs = &$this->Execute($sql, $inputarr); - - if ($rs) { - if ($trim) { - while (!$rs->EOF) { - $rv[] = trim(reset($rs->fields)); - $rs->MoveNext(); - } - } else { - while (!$rs->EOF) { - $rv[] = reset($rs->fields); - $rs->MoveNext(); - } - } - $rs->Close(); - } - - return $rv; - } - - function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) - { - $rv = false; - $rs = &$this->CacheExecute($secs, $sql, $inputarr); - if ($rs) { - if ($trim) { - while (!$rs->EOF) { - $rv[] = trim(reset($rs->fields)); - $rs->MoveNext(); - } - } else { - while (!$rs->EOF) { - $rv[] = reset($rs->fields); - $rs->MoveNext(); - } - } - $rs->Close(); - } - return $rv; - } - - /* - Calculate the offset of a date for a particular database and generate - appropriate SQL. Useful for calculating future/past dates and storing - in a database. - - If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour. - */ - function OffsetDate($dayFraction,$date=false) - { - if (!$date) $date = $this->sysDate; - return '('.$date.'+'.$dayFraction.')'; - } - - - /** - * Return all rows. Compat with PEAR DB - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function &GetAll($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs = $this->Execute($sql,$inputarr); - $ADODB_COUNTRECS = $savec; - - if (!$rs) - if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; - $arr =& $rs->GetArray(); - $rs->Close(); - return $arr; - } - - function &CacheGetAll($secs2cache,$sql=false,$inputarr=false) - { - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); - $ADODB_COUNTRECS = $savec; - - if (!$rs) - if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - else return false; - - $arr =& $rs->GetArray(); - $rs->Close(); - return $arr; - } - - - - /** - * Return one row of sql statement. Recordset is disposed for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function &GetRow($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - $crecs = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - $rs = $this->Execute($sql,$inputarr); - - $ADODB_COUNTRECS = $crecs; - if ($rs) { - $arr = array(); - if (!$rs->EOF) $arr = $rs->fields; - $rs->Close(); - return $arr; - } - - return false; - } - - function &CacheGetRow($secs2cache,$sql=false,$inputarr=false) - { - $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); - if ($rs) { - $arr = false; - if (!$rs->EOF) $arr = $rs->fields; - $rs->Close(); - return $arr; - } - return false; - } - - /** - * Insert or replace a single record. Note: this is not the same as MySQL's replace. - * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. - * Also note that no table locking is done currently, so it is possible that the - * record be inserted twice by two programs... - * - * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); - * - * $table table name - * $fieldArray associative array of data (you must quote strings yourself). - * $keyCol the primary key field name or if compound key, array of field names - * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers - * but does not work with dates nor SQL functions. - * has_autoinc the primary key is an auto-inc field, so skip in insert. - * - * Currently blob replace not supported - * - * returns 0 = fail, 1 = update, 2 = insert - */ - - function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) - { - if (count($fieldArray) == 0) return 0; - $first = true; - $uSet = ''; - - if (!is_array($keyCol)) { - $keyCol = array($keyCol); - } - foreach($fieldArray as $k => $v) { - if ($autoQuote && !is_numeric($v) and substr($v,0,1) != "'" and strcasecmp($v,'null')!=0) { - $v = $this->qstr($v); - $fieldArray[$k] = $v; - } - if (in_array($k,$keyCol)) continue; // skip UPDATE if is key - - if ($first) { - $first = false; - $uSet = "$k=$v"; - } else - $uSet .= ",$k=$v"; - } - - $first = true; - foreach ($keyCol as $v) { - if ($first) { - $first = false; - $where = "$v=$fieldArray[$v]"; - } else { - $where .= " and $v=$fieldArray[$v]"; - } - } - - if ($uSet) { - $update = "UPDATE $table SET $uSet WHERE $where"; - - $rs = $this->Execute($update); - if ($rs) { - if ($this->poorAffectedRows) { - /* - The Select count(*) wipes out any errors that the update would have returned. - http://phplens.com/lens/lensforum/msgs.php?id=5696 - */ - if ($this->ErrorNo()<>0) return 0; - - # affected_rows == 0 if update field values identical to old values - # for mysql - which is silly. - - $cnt = $this->GetOne("select count(*) from $table where $where"); - if ($cnt > 0) return 1; // record already exists - } else - if (($this->Affected_Rows()>0)) return 1; - } - - } - // print "

Error=".$this->ErrorNo().'

'; - $first = true; - foreach($fieldArray as $k => $v) { - if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col - - if ($first) { - $first = false; - $iCols = "$k"; - $iVals = "$v"; - } else { - $iCols .= ",$k"; - $iVals .= ",$v"; - } - } - $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; - $rs = $this->Execute($insert); - return ($rs) ? 2 : 0; - } - - - /** - * Will select, getting rows from $offset (1-based), for $nrows. - * This simulates the MySQL "select * from table limit $offset,$nrows" , and - * the PostgreSQL "select * from table limit $nrows offset $offset". Note that - * MySQL and PostgreSQL parameter ordering is the opposite of the other. - * eg. - * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based) - * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based) - * - * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set - * - * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional - * @param sql - * @param [offset] is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to get - * @param [inputarr] array of bind variables - * @param [arg3] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - */ - function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false) - { - if (!is_numeric($secs2cache)) { - if ($sql === false) $sql = -1; - if ($offset == -1) $offset = false; - // sql, nrows, offset,inputarr,arg3 - return $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$inputarr,$this->cacheSecs); - } else { - if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()"); - return $this->SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache); - } - } - - /** - * Flush cached recordsets that match a particular $sql statement. - * If $sql == false, then we purge all files in the cache. - */ - function CacheFlush($sql=false,$inputarr=false) - { - global $ADODB_CACHE_DIR; - - if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { - if (strpos(strtoupper(PHP_OS),'WIN') !== false) { - $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache'; - } else { - $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache'; - // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; - } - if ($this->debug) { - ADOConnection::outp( "CacheFlush: $cmd

\n", system($cmd),"
"); - } else { - exec($cmd); - } - return; - } - $f = $this->_gencachename($sql.serialize($inputarr),false); - adodb_write_file($f,''); // is adodb_write_file needed? - @unlink($f); - } - - /** - * Private function to generate filename for caching. - * Filename is generated based on: - * - * - sql statement - * - database type (oci8, ibase, ifx, etc) - * - database name - * - userid - * - * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). - * Assuming that we can have 50,000 files per directory with good performance, - * then we can scale to 12.8 million unique cached recordsets. Wow! - */ - function _gencachename($sql,$createdir) - { - global $ADODB_CACHE_DIR; - - $m = md5($sql.$this->databaseType.$this->database.$this->user); - $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2); - if ($createdir && !file_exists($dir)) { - $oldu = umask(0); - if (!mkdir($dir,0771)) - if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql"); - umask($oldu); - } - return $dir.'/adodb_'.$m.'.cache'; - } - - - /** - * Execute SQL, caching recordsets. - * - * @param [secs2cache] seconds to cache data, set to 0 to force query. - * This is an optional parameter. - * @param sql SQL statement to execute - * @param [inputarr] holds the input data to bind to - * @param [arg3] reserved for john lim for future use - * @return RecordSet or false - */ - function &CacheExecute($secs2cache,$sql=false,$inputarr=false,$arg3=false) - { - if (!is_numeric($secs2cache)) { - $arg3 = $inputarr; - $inputarr = $sql; - $sql = $secs2cache; - $secs2cache = $this->cacheSecs; - } - include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); - - $md5file = $this->_gencachename($sql.serialize($inputarr),true); - $err = ''; - - if ($secs2cache > 0){ - $rs = &csv2rs($md5file,$err,$secs2cache); - $this->numCacheHits += 1; - } else { - $err='Timeout 1'; - $rs = false; - $this->numCacheMisses += 1; - } - if (!$rs) { - // no cached rs found - if ($this->debug) { - if (get_magic_quotes_runtime()) { - ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); - } - ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); - } - $rs = &$this->Execute($sql,$inputarr,$arg3); - if ($rs) { - $eof = $rs->EOF; - $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately - $txt = _rs2serialize($rs,false,$sql); // serialize - - if (!adodb_write_file($md5file,$txt,$this->debug)) { - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); - } - if ($this->debug) ADOConnection::outp( " Cache write error"); - } - if ($rs->EOF && !$eof) { - $rs->MoveFirst(); - //$rs = &csv2rs($md5file,$err); - $rs->connection = &$this; // Pablo suggestion - } - - } else - @unlink($md5file); - } else { - if ($this->fnCacheExecute) { - $fn = $this->fnCacheExecute; - $fn($this, $secs2cache, $sql, $inputarr); - } - // ok, set cached object found - $rs->connection = &$this; // Pablo suggestion - if ($this->debug){ - global $HTTP_SERVER_VARS; - - $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); - $ttl = $rs->timeCreated + $secs2cache - time(); - $s = is_array($sql) ? $sql[0] : $sql; - if ($inBrowser) $s = ''.htmlspecialchars($s).''; - - ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); - } - } - return $rs; - } - - - /** - * Generates an Update Query based on an existing recordset. - * $arrFields is an associative array of fields with the value - * that should be assigned. - * - * Note: This function should only be used on a recordset - * that is run against a single table and sql should only - * be a simple select stmt with no groupby/orderby/limit - * - * "Jonathan Younger" - */ - function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false) - { - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq); - } - - - /** - * Generates an Insert Query based on an existing recordset. - * $arrFields is an associative array of fields with the value - * that should be assigned. - * - * Note: This function should only be used on a recordset - * that is run against a single table. - */ - function GetInsertSQL(&$rs, $arrFields,$magicq=false) - { - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getinsertsql($this,$rs,$arrFields,$magicq); - } - - - /** - * Update a blob column, given a where clause. There are more sophisticated - * blob handling functions that we could have implemented, but all require - * a very complex API. Instead we have chosen something that is extremely - * simple to understand and use. - * - * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course. - * - * Usage to update a $blobvalue which has a primary key blob_id=1 into a - * field blobtable.blobcolumn: - * - * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1'); - * - * Insert example: - * - * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); - * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); - */ - - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') - { - return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false; - } - - /** - * Usage: - * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1'); - * - * $blobtype supports 'BLOB' and 'CLOB' - * - * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); - * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1'); - */ - function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') - { - $fd = fopen($path,'rb'); - if ($fd === false) return false; - $val = fread($fd,filesize($path)); - fclose($fd); - return $this->UpdateBlob($table,$column,$val,$where,$blobtype); - } - - function BlobDecode($blob) - { - return $blob; - } - - function BlobEncode($blob) - { - return $blob; - } - - /** - * Usage: - * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB'); - * - * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)'); - * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1'); - */ - function UpdateClob($table,$column,$val,$where) - { - return $this->UpdateBlob($table,$column,$val,$where,'CLOB'); - } - - - /** - * $meta contains the desired type, which could be... - * C for character. You will have to define the precision yourself. - * X for teXt. For unlimited character lengths. - * B for Binary - * F for floating point, with no need to define scale and precision - * N for decimal numbers, you will have to define the (scale, precision) yourself - * D for date - * T for timestamp - * L for logical/Boolean - * I for integer - * R for autoincrement counter/integer - * and if you want to use double-byte, add a 2 to the end, like C2 or X2. - * - * - * @return the actual type of the data or false if no such type available - */ - function ActualType($meta) - { - switch($meta) { - case 'C': - case 'X': - return 'VARCHAR'; - case 'B': - - case 'D': - case 'T': - case 'L': - - case 'R': - - case 'I': - case 'N': - return false; - } - } - - /* - * Maximum size of C field - */ - function CharMax() - { - return 255; // make it conservative if not defined - } - - - /* - * Maximum size of X field - */ - function TextMax() - { - return 4000; // make it conservative if not defined - } - - /** - * Close Connection - */ - function Close() - { - return $this->_close(); - - // "Simon Lee" reports that persistent connections need - // to be closed too! - //if ($this->_isPersistentConnection != true) return $this->_close(); - //else return true; - } - - /** - * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). - * - * @return true if succeeded or false if database does not support transactions - */ - function BeginTrans() {return false;} - - - /** - * If database does not support transactions, always return true as data always commited - * - * @param $ok set to false to rollback transaction, true to commit - * - * @return true/false. - */ - function CommitTrans($ok=true) - { return true;} - - - /** - * If database does not support transactions, rollbacks always fail, so return false - * - * @return true/false. - */ - function RollbackTrans() - { return false;} - - - /** - * return the databases that the driver can connect to. - * Some databases will return an empty array. - * - * @return an array of database names. - */ - function MetaDatabases() - { - global $ADODB_FETCH_MODE; - - if ($this->metaDatabasesSQL) { - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - - $arr = $this->GetCol($this->metaDatabasesSQL); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - return $arr; - } - - return false; - } - - /** - * @return array of tables for current database. - */ - function &MetaTables() - { - global $ADODB_FETCH_MODE; - - if ($this->metaTablesSQL) { - // complicated state saving by the need for backward compat - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - - $rs = $this->Execute($this->metaTablesSQL); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - if ($rs === false) return false; - $arr =& $rs->GetArray(); - $arr2 = array(); - for ($i=0; $i < sizeof($arr); $i++) { - $arr2[] = $arr[$i][0]; - } - $rs->Close(); - return $arr2; - } - return false; - } - - - /** - * List columns in a database as an array of ADOFieldObjects. - * See top of file for definition of object. - * - * @param table table name to query - * @param upper uppercase table name (required by some databases) - * - * @return array of ADOFieldObjects for current table. - */ - function &MetaColumns($table,$upper=true) - { - global $ADODB_FETCH_MODE; - - if (!empty($this->metaColumnsSQL)) { - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table)); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - if ($rs === false) return false; - - $retarr = array(); - while (!$rs->EOF) { //print_r($rs->fields); - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $fld->type = $rs->fields[1]; - if (isset($rs->fields[3]) && $rs->fields[3]) { - if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3]; - $fld->scale = $rs->fields[4]; - if ($fld->scale>0) $fld->max_length += 1; - } else - $fld->max_length = $rs->fields[2]; - - - $retarr[strtoupper($fld->name)] = $fld; - - $rs->MoveNext(); - } - $rs->Close(); - return $retarr; - } - return false; - } - - /** - * List columns names in a table as an array. - * @param table table name to query - * - * @return array of column names for current table. - */ - function &MetaColumnNames($table) - { - $objarr =& $this->MetaColumns($table); - if (!is_array($objarr)) return false; - - $arr = array(); - foreach($objarr as $v) { - $arr[] = $v->name; - } - return $arr; - } - - /** - * Different SQL databases used different methods to combine strings together. - * This function provides a wrapper. - * - * param s variable number of string parameters - * - * Usage: $db->Concat($str1,$str2); - * - * @return concatenated string - */ - function Concat() - { - $arr = func_get_args(); - return implode($this->concat_operator, $arr); - } - - - /** - * Converts a date "d" to a string that the database can understand. - * - * @param d a date in Unix date time format. - * - * @return date string in database date format - */ - function DBDate($d) - { - - if (empty($d) && $d !== 0) return 'null'; - - if (is_string($d) && !is_numeric($d)) { - if ($d === 'null') return $d; - if ($this->isoDates) return "'$d'"; - $d = ADOConnection::UnixDate($d); - } - - return adodb_date($this->fmtDate,$d); - } - - - /** - * Converts a timestamp "ts" to a string that the database can understand. - * - * @param ts a timestamp in Unix date time format. - * - * @return timestamp string in database timestamp format - */ - function DBTimeStamp($ts) - { - if (empty($ts) && $ts !== 0) return 'null'; - - if (is_string($ts) && !is_numeric($ts)) { - if ($ts === 'null') return $ts; - if ($this->isoDates) return "'$ts'"; - else $ts = ADOConnection::UnixTimeStamp($ts); - } - - return adodb_date($this->fmtTimeStamp,$ts); - } - - /** - * Also in ADORecordSet. - * @param $v is a date string in YYYY-MM-DD format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixDate($v) - { - if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", - ($v), $rr)) return false; - - if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; - // h-m-s-MM-DD-YY - return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - } - - - /** - * Also in ADORecordSet. - * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixTimeStamp($v) - { - if (!preg_match( - "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", - ($v), $rr)) return false; - if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; - - // h-m-s-MM-DD-YY - if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); - } - - /** - * Also in ADORecordSet. - * - * Format database date based on user defined format. - * - * @param v is the character date in YYYY-MM-DD format, returned by database - * @param fmt is the format to apply to it, using date() - * - * @return a date formated as user desires - */ - - function UserDate($v,$fmt='Y-m-d') - { - $tt = $this->UnixDate($v); - // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - else if ($tt == 0) return $this->emptyDate; - else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR - } - - return adodb_date($fmt,$tt); - - } - - - /** - * Correctly quotes a string so that all strings are escaped. We prefix and append - * to the string single-quotes. - * An example is $db->qstr("Don't bother",magic_quotes_runtime()); - * - * @param s the string to quote - * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). - * This undoes the stupidity of magic quotes for GPC. - * - * @return quoted string to be sent back to database - */ - function qstr($s,$magic_quotes=false) - { - if (!$magic_quotes) { - - if ($this->replaceQuote[0] == '\\'){ - // only since php 4.0.5 - $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); - //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); - } - return "'".str_replace("'",$this->replaceQuote,$s)."'"; - } - - // undo magic quotes for " - $s = str_replace('\\"','"',$s); - - if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything - return "'$s'"; - else {// change \' to '' for sybase/mssql - $s = str_replace('\\\\','\\',$s); - return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; - } - } - - - /** - * Will select the supplied $page number from a recordset, given that it is paginated in pages of - * $nrows rows per page. It also saves two boolean values saying if the given page is the first - * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination. - * - * See readme.htm#ex8 for an example of usage. - * - * @param sql - * @param nrows is the number of rows per page to get - * @param page is the page number to get (1-based) - * @param [inputarr] array of bind variables - * @param [arg3] is a private parameter only used by jlim - * @param [secs2cache] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - * - * NOTE: phpLens uses a different algorithm and does not use PageExecute(). - * - */ - function &PageExecute($sql, $nrows, $page, $inputarr=false, $arg3=false, $secs2cache=0) - { - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $arg3, $secs2cache); - return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $arg3, $secs2cache); - - } - - - /** - * Will select the supplied $page number from a recordset, given that it is paginated in pages of - * $nrows rows per page. It also saves two boolean values saying if the given page is the first - * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination. - * - * @param secs2cache seconds to cache data, set to 0 to force query - * @param sql - * @param nrows is the number of rows per page to get - * @param page is the page number to get (1-based) - * @param [inputarr] array of bind variables - * @param [arg3] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - */ - function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false, $arg3=false) - { - /*switch($this->dataProvider) { - case 'postgres': - case 'mysql': - break; - default: $secs2cache = 0; break; - }*/ - return $this->PageExecute($sql,$nrows,$page,$inputarr,$arg3,$secs2cache); - } - -} // end class ADOConnection - - - - //============================================================================================== - // CLASS ADOFetchObj - //============================================================================================== - - /** - * Internal placeholder for record objects. Used by ADORecordSet->FetchObj(). - */ - class ADOFetchObj { - }; - - //============================================================================================== - // CLASS ADORecordSet_empty - //============================================================================================== - - /** - * Lightweight recordset when there are no records to be returned - */ - class ADORecordSet_empty - { - var $dataProvider = 'empty'; - var $databaseType = false; - var $EOF = true; - var $_numOfRows = 0; - var $fields = false; - var $connection = false; - function RowCount() {return 0;} - function RecordCount() {return 0;} - function PO_RecordCount(){return 0;} - function Close(){return true;} - function FetchRow() {return false;} - function FieldCount(){ return 0;} - } - - //============================================================================================== - // DATE AND TIME FUNCTIONS - //============================================================================================== - include_once(ADODB_DIR.'/adodb-time.inc.php'); - - //============================================================================================== - // CLASS ADORecordSet - //============================================================================================== - - - /** - * RecordSet class that represents the dataset returned by the database. - * To keep memory overhead low, this class holds only the current row in memory. - * No prefetching of data is done, so the RecordCount() can return -1 ( which - * means recordcount not known). - */ - class ADORecordSet { - /* - * public variables - */ - var $dataProvider = "native"; - var $fields = false; /// holds the current row data - var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob - /// in other words, we use a text area for editting. - var $canSeek = false; /// indicates that seek is supported - var $sql; /// sql text - var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object. - - var $emptyTimeStamp = ' '; /// what to display when $time==0 - var $emptyDate = ' '; /// what to display when $time==0 - var $debug = false; - var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets - - var $bind = false; /// used by Fields() to hold array - should be private? - var $fetchMode; /// default fetch mode - var $connection = false; /// the parent connection - /* - * private variables - */ - var $_numOfRows = -1; /** number of rows, or -1 */ - var $_numOfFields = -1; /** number of fields in recordset */ - var $_queryID = -1; /** This variable keeps the result link identifier. */ - var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */ - var $_closed = false; /** has recordset been closed */ - var $_inited = false; /** Init() should only be called once */ - var $_obj; /** Used by FetchObj */ - var $_names; /** Used by FetchObj */ - - var $_currentPage = -1; /** Added by Iv�n Oliva to implement recordset pagination */ - var $_atFirstPage = false; /** Added by Iv�n Oliva to implement recordset pagination */ - var $_atLastPage = false; /** Added by Iv�n Oliva to implement recordset pagination */ - var $_lastPageNo = -1; - var $_maxRecordCount = 0; - var $dateHasTime = false; - - /** - * Constructor - * - * @param queryID this is the queryID returned by ADOConnection->_query() - * - */ - function ADORecordSet($queryID) - { - $this->_queryID = $queryID; - } - - - - function Init() - { - if ($this->_inited) return; - $this->_inited = true; - if ($this->_queryID) @$this->_initrs(); - else { - $this->_numOfRows = 0; - $this->_numOfFields = 0; - } - - if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) { - - $this->_currentRow = 0; - if ($this->EOF = ($this->_fetch() === false)) { - $this->_numOfRows = 0; // _numOfRows could be -1 - } - } else { - $this->EOF = true; - } - } - - - /** - * Generate a SELECT tag string from a recordset, and return the string. - * If the recordset has 2 cols, we treat the 1st col as the containing - * the text to display to the user, and 2nd col as the return value. Default - * strings are compared with the FIRST column. - * - * @param name name of SELECT tag - * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox. - * @param [blank1stItem] true to leave the 1st item in list empty - * @param [multiple] true for listbox, false for popup - * @param [size] #rows to show for listbox. not used by popup - * @param [selectAttr] additional attributes to defined for SELECT tag. - * useful for holding javascript onChange='...' handlers. - & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with - * column 0 (1st col) if this is true. This is not documented. - * - * @return HTML - * - * changes by glen.davies@cce.ac.nz to support multiple hilited items - */ - function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false, - $size=0, $selectAttr='',$compareFields0=true) - { - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple, - $size, $selectAttr,$compareFields0); - } - - /** - * Generate a SELECT tag string from a recordset, and return the string. - * If the recordset has 2 cols, we treat the 1st col as the containing - * the text to display to the user, and 2nd col as the return value. Default - * strings are compared with the SECOND column. - * - */ - function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') - { - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple, - $size, $selectAttr,false); - } - - - /** - * return recordset as a 2-dimensional array. - * - * @param [nRows] is the number of rows to return. -1 means every row. - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function &GetArray($nRows = -1) - { - global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows); - - $results = array(); - $cnt = 0; - while (!$this->EOF && $nRows != $cnt) { - $results[] = $this->fields; - $this->MoveNext(); - $cnt++; - } - return $results; - } - - /* - * Some databases allow multiple recordsets to be returned. This function - * will return true if there is a next recordset, or false if no more. - */ - function NextRecordSet() - { - return false; - } - - /** - * return recordset as a 2-dimensional array. - * Helper function for ADOConnection->SelectLimit() - * - * @param offset is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to return - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function &GetArrayLimit($nrows,$offset=-1) - { - if ($offset <= 0) { - return $this->GetArray($nrows); - } - - $this->Move($offset); - - $results = array(); - $cnt = 0; - while (!$this->EOF && $nrows != $cnt) { - $results[$cnt++] = $this->fields; - $this->MoveNext(); - } - - return $results; - } - - - /** - * Synonym for GetArray() for compatibility with ADO. - * - * @param [nRows] is the number of rows to return. -1 means every row. - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function &GetRows($nRows = -1) - { - return $this->GetArray($nRows); - } - - /** - * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. - * The first column is treated as the key and is not included in the array. - * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless - * $force_array == true. - * - * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional - * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, - * read the source. - * - * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and - * instead of returning array[col0] => array(remaining cols), return array[col0] => col1 - * - * @return an associative array indexed by the first column of the array, - * or false if the data has less than 2 cols. - */ - function &GetAssoc($force_array = false, $first2cols = false) { - $cols = $this->_numOfFields; - if ($cols < 2) { - return false; - } - $numIndex = isset($this->fields[0]); - $results = array(); - - if (!$first2cols && ($cols > 2 || $force_array)) { - if ($numIndex) { - while (!$this->EOF) { - $results[trim($this->fields[0])] = array_slice($this->fields, 1); - $this->MoveNext(); - } - } else { - while (!$this->EOF) { - $results[trim(reset($this->fields))] = array_slice($this->fields, 1); - $this->MoveNext(); - } - } - } else { - // return scalar values - if ($numIndex) { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $results[trim(($this->fields[0]))] = $this->fields[1]; - $this->MoveNext(); - } - } else { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $v1 = trim(reset($this->fields)); - $v2 = ''.next($this->fields); - $results[$v1] = $v2; - $this->MoveNext(); - } - } - } - return $results; - } - - - /** - * - * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format - * @param fmt is the format to apply to it, using date() - * - * @return a timestamp formated as user desires - */ - function UserTimeStamp($v,$fmt='Y-m-d H:i:s') - { - $tt = $this->UnixTimeStamp($v); - // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - if ($tt == 0) return $this->emptyTimeStamp; - return adodb_date($fmt,$tt); - } - - - /** - * @param v is the character date in YYYY-MM-DD format, returned by database - * @param fmt is the format to apply to it, using date() - * - * @return a date formated as user desires - */ - function UserDate($v,$fmt='Y-m-d') - { - $tt = $this->UnixDate($v); - // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - else if ($tt == 0) return $this->emptyDate; - else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR - } - return adodb_date($fmt,$tt); - - } - - - /** - * @param $v is a date string in YYYY-MM-DD format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixDate($v) - { - - if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", - ($v), $rr)) return false; - - if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; - // h-m-s-MM-DD-YY - return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - } - - - /** - * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - function UnixTimeStamp($v) - { - - if (!preg_match( - "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", - ($v), $rr)) return false; - if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; - - // h-m-s-MM-DD-YY - if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); - } - - - /** - * PEAR DB Compat - do not use internally - */ - function Free() - { - return $this->Close(); - } - - - /** - * PEAR DB compat, number of rows - */ - function NumRows() - { - return $this->_numOfRows; - } - - - /** - * PEAR DB compat, number of cols - */ - function NumCols() - { - return $this->_numOfFields; - } - - /** - * Fetch a row, returning false if no more rows. - * This is PEAR DB compat mode. - * - * @return false or array containing the current record - */ - function FetchRow() - { - if ($this->EOF) return false; - $arr = $this->fields; - $this->_currentRow++; - if (!$this->_fetch()) $this->EOF = true; - return $arr; - } - - - /** - * Fetch a row, returning PEAR_Error if no more rows. - * This is PEAR DB compat mode. - * - * @return DB_OK or error object - */ - function FetchInto(&$arr) - { - if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false; - $arr = $this->fields; - $this->MoveNext(); - return 1; // DB_OK - } - - - /** - * Move to the first row in the recordset. Many databases do NOT support this. - * - * @return true or false - */ - function MoveFirst() - { - if ($this->_currentRow == 0) return true; - return $this->Move(0); - } - - - /** - * Move to the last row in the recordset. - * - * @return true or false - */ - function MoveLast() - { - if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1); - if ($this->EOF) return false; - while (!$this->EOF) { - $f = $this->fields; - $this->MoveNext(); - } - $this->fields = $f; - $this->EOF = false; - return true; - } - - - /** - * Move to next record in the recordset. - * - * @return true if there still rows available, or false if there are no more rows (EOF). - */ - function MoveNext() - { - if (!$this->EOF) { - $this->_currentRow++; - if ($this->_fetch()) return true; - } - $this->EOF = true; - /* -- tested error handling when scrolling cursor -- seems useless. - $conn = $this->connection; - if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { - $fn = $conn->raiseErrorFn; - $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); - } - */ - return false; - } - - /** - * Random access to a specific row in the recordset. Some databases do not support - * access to previous rows in the databases (no scrolling backwards). - * - * @param rowNumber is the row to move to (0-based) - * - * @return true if there still rows available, or false if there are no more rows (EOF). - */ - function Move($rowNumber = 0) - { - $this->EOF = false; - if ($rowNumber == $this->_currentRow) return true; - if ($rowNumber >= $this->_numOfRows) - if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2; - - if ($this->canSeek) { - - if ($this->_seek($rowNumber)) { - $this->_currentRow = $rowNumber; - if ($this->_fetch()) { - return true; - } - } else { - $this->EOF = true; - return false; - } - } else { - if ($rowNumber < $this->_currentRow) return false; - global $ADODB_EXTENSION; - if ($ADODB_EXTENSION) { - while (!$this->EOF && $this->_currentRow < $rowNumber) { - adodb_movenext($this); - } - } else { - - while (! $this->EOF && $this->_currentRow < $rowNumber) { - $this->_currentRow++; - - if (!$this->_fetch()) $this->EOF = true; - } - } - return !($this->EOF); - } - - $this->fields = false; - $this->EOF = true; - return false; - } - - - /** - * Get the value of a field in the current row by column name. - * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. - * - * @param colname is the field to access - * - * @return the value of $colname column - */ - function Fields($colname) - { - return $this->fields[$colname]; - } - - function GetAssocKeys($upper=true) - { - $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { - $o = $this->FetchField($i); - if ($upper === 2) $this->bind[$o->name] = $i; - else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; - } - } - - /** - * Use associative array to get fields array for databases that do not support - * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it - * - * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC - * before you execute your SQL statement, and access $rs->fields['col'] directly. - * - * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField - */ - function GetRowAssoc($upper=1) - { - - if (!$this->bind) { - $this->GetAssocKeys($upper); - } - - $record = array(); - foreach($this->bind as $k => $v) { - $record[$k] = $this->fields[$v]; - } - - return $record; - } - - - /** - * Clean up recordset - * - * @return true or false - */ - function Close() - { - // free connection object - this seems to globally free the object - // and not merely the reference, so don't do this... - // $this->connection = false; - if (!$this->_closed) { - $this->_closed = true; - return $this->_close(); - } else - return true; - } - - /** - * synonyms RecordCount and RowCount - * - * @return the number of rows or -1 if this is not supported - */ - function RecordCount() {return $this->_numOfRows;} - - - /* - * If we are using PageExecute(), this will return the maximum possible rows - * that can be returned when paging a recordset. - */ - function MaxRecordCount() - { - return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); - } - - /** - * synonyms RecordCount and RowCount - * - * @return the number of rows or -1 if this is not supported - */ - function RowCount() {return $this->_numOfRows;} - - - /** - * Portable RecordCount. Pablo Roca - * - * @return the number of records from a previous SELECT. All databases support this. - * - * But aware possible problems in multiuser environments. For better speed the table - * must be indexed by the condition. Heavy test this before deploying. - */ - function PO_RecordCount($table="", $condition="") { - - $lnumrows = $this->_numOfRows; - // the database doesn't support native recordcount, so we do a workaround - if ($lnumrows == -1 && $this->connection) { - IF ($table) { - if ($condition) $condition = " WHERE " . $condition; - $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); - if ($resultrows) $lnumrows = reset($resultrows->fields); - } - } - return $lnumrows; - } - - /** - * @return the current row in the recordset. If at EOF, will return the last row. 0-based. - */ - function CurrentRow() {return $this->_currentRow;} - - /** - * synonym for CurrentRow -- for ADO compat - * - * @return the current row in the recordset. If at EOF, will return the last row. 0-based. - */ - function AbsolutePosition() {return $this->_currentRow;} - - /** - * @return the number of columns in the recordset. Some databases will set this to 0 - * if no records are returned, others will return the number of columns in the query. - */ - function FieldCount() {return $this->_numOfFields;} - - - /** - * Get the ADOFieldObject of a specific column. - * - * @param fieldoffset is the column position to access(0-based). - * - * @return the ADOFieldObject for that column, or false. - */ - function &FetchField($fieldoffset) - { - // must be defined by child class - } - - /** - * Get the ADOFieldObjects of all columns in an array. - * - */ - function FieldTypesArray() - { - $arr = array(); - for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) - $arr[] = $this->FetchField($i); - return $arr; - } - - /** - * Return the fields array of the current row as an object for convenience. - * The default case is lowercase field names. - * - * @return the object with the properties set to the fields of the current row - */ - function &FetchObj() - { - return FetchObject(false); - } - - /** - * Return the fields array of the current row as an object for convenience. - * The default case is uppercase. - * - * @param $isupper to set the object property names to uppercase - * - * @return the object with the properties set to the fields of the current row - */ - function &FetchObject($isupper=true) - { - if (empty($this->_obj)) { - $this->_obj = new ADOFetchObj(); - $this->_names = array(); - for ($i=0; $i <$this->_numOfFields; $i++) { - $f = $this->FetchField($i); - $this->_names[] = $f->name; - } - } - $i = 0; - $o = &$this->_obj; - for ($i=0; $i <$this->_numOfFields; $i++) { - $name = $this->_names[$i]; - if ($isupper) $n = strtoupper($name); - else $n = $name; - - $o->$n = $this->Fields($name); - } - return $o; - } - - /** - * Return the fields array of the current row as an object for convenience. - * The default is lower-case field names. - * - * @return the object with the properties set to the fields of the current row, - * or false if EOF - * - * Fixed bug reported by tim@orotech.net - */ - function &FetchNextObj() - { - return $this->FetchNextObject(false); - } - - - /** - * Return the fields array of the current row as an object for convenience. - * The default is upper case field names. - * - * @param $isupper to set the object property names to uppercase - * - * @return the object with the properties set to the fields of the current row, - * or false if EOF - * - * Fixed bug reported by tim@orotech.net - */ - function &FetchNextObject($isupper=true) - { - $o = false; - if ($this->_numOfRows != 0 && !$this->EOF) { - $o = $this->FetchObject($isupper); - $this->_currentRow++; - if ($this->_fetch()) return $o; - } - $this->EOF = true; - return $o; - } - - /** - * Get the metatype of the column. This is used for formatting. This is because - * many databases use different names for the same type, so we transform the original - * type to our standardised version which uses 1 character codes: - * - * @param t is the type passed in. Normally is ADOFieldObject->type. - * @param len is the maximum length of that field. This is because we treat character - * fields bigger than a certain size as a 'B' (blob). - * @param fieldobj is the field object returned by the database driver. Can hold - * additional info (eg. primary_key for mysql). - * - * @return the general type of the data: - * C for character < 200 chars - * X for teXt (>= 200 chars) - * B for Binary - * N for numeric floating point - * D for date - * T for timestamp - * L for logical/Boolean - * I for integer - * R for autoincrement counter/integer - * - * - */ - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } - // changed in 2.32 to hashing instead of switch stmt for speed... - static $typeMap = array( - 'VARCHAR' => 'C', - 'VARCHAR2' => 'C', - 'CHAR' => 'C', - 'C' => 'C', - 'STRING' => 'C', - 'NCHAR' => 'C', - 'NVARCHAR' => 'C', - 'VARYING' => 'C', - 'BPCHAR' => 'C', - 'CHARACTER' => 'C', - 'INTERVAL' => 'C', # Postgres - ## - 'LONGCHAR' => 'X', - 'TEXT' => 'X', - 'NTEXT' => 'X', - 'M' => 'X', - 'X' => 'X', - 'CLOB' => 'X', - 'NCLOB' => 'X', - 'LVARCHAR' => 'X', - ## - 'BLOB' => 'B', - 'IMAGE' => 'B', - 'BINARY' => 'B', - 'VARBINARY' => 'B', - 'LONGBINARY' => 'B', - 'B' => 'B', - ## - 'YEAR' => 'D', // mysql - 'DATE' => 'D', - 'D' => 'D', - ## - 'TIME' => 'T', - 'TIMESTAMP' => 'T', - 'DATETIME' => 'T', - 'TIMESTAMPTZ' => 'T', - 'T' => 'T', - ## - 'BOOLEAN' => 'L', - 'BIT' => 'L', - 'L' => 'L', - ## - 'COUNTER' => 'R', - 'R' => 'R', - 'SERIAL' => 'R', // ifx - 'INT IDENTITY' => 'R', - ## - 'INT' => 'I', - 'INTEGER' => 'I', - 'SHORT' => 'I', - 'TINYINT' => 'I', - 'SMALLINT' => 'I', - 'I' => 'I', - ## - 'LONG' => 'N', // interbase is numeric, oci8 is blob - 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers - 'DECIMAL' => 'N', - 'DEC' => 'N', - 'REAL' => 'N', - 'DOUBLE' => 'N', - 'DOUBLE PRECISION' => 'N', - 'SMALLFLOAT' => 'N', - 'FLOAT' => 'N', - 'NUMBER' => 'N', - 'NUM' => 'N', - 'NUMERIC' => 'N', - 'MONEY' => 'N', - - ## informix 9.2 - 'SQLINT' => 'I', - 'SQLSERIAL' => 'I', - 'SQLSMINT' => 'I', - 'SQLSMFLOAT' => 'N', - 'SQLFLOAT' => 'N', - 'SQLMONEY' => 'N', - 'SQLDECIMAL' => 'N', - 'SQLDATE' => 'D', - 'SQLVCHAR' => 'C', - 'SQLCHAR' => 'C', - 'SQLDTIME' => 'T', - 'SQLINTERVAL' => 'N', - 'SQLBYTES' => 'B', - 'SQLTEXT' => 'X' - ); - - $tmap = false; - $t = strtoupper($t); - $tmap = @$typeMap[$t]; - switch ($tmap) { - case 'C': - - // is the char field is too long, return as text field... - if (!empty($this->blobSize)) { - if ($len > $this->blobSize) return 'X'; - } else if ($len > 250) { - return 'X'; - } - return 'C'; - - case 'I': - if (!empty($fieldobj->primary_key)) return 'R'; - return 'I'; - - case false: - return 'N'; - - case 'B': - if (isset($fieldobj->binary)) - return ($fieldobj->binary) ? 'B' : 'X'; - return 'B'; - - case 'D': - if (!empty($this->dateHasTime)) return 'T'; - return 'D'; - - default: - if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; - return $tmap; - } - } - - function _close() {} - - /** - * set/returns the current recordset page when paginating - */ - function AbsolutePage($page=-1) - { - if ($page != -1) $this->_currentPage = $page; - return $this->_currentPage; - } - - /** - * set/returns the status of the atFirstPage flag when paginating - */ - function AtFirstPage($status=false) - { - if ($status != false) $this->_atFirstPage = $status; - return $this->_atFirstPage; - } - - function LastPageNo($page = false) - { - if ($page != false) $this->_lastPageNo = $page; - return $this->_lastPageNo; - } - - /** - * set/returns the status of the atLastPage flag when paginating - */ - function AtLastPage($status=false) - { - if ($status != false) $this->_atLastPage = $status; - return $this->_atLastPage; - } -} // end class ADORecordSet - - //============================================================================================== - // CLASS ADORecordSet_array - //============================================================================================== - - /** - * This class encapsulates the concept of a recordset created in memory - * as an array. This is useful for the creation of cached recordsets. - * - * Note that the constructor is different from the standard ADORecordSet - */ - - class ADORecordSet_array extends ADORecordSet - { - var $databaseType = 'array'; - - var $_array; // holds the 2-dimensional data array - var $_types; // the array of types of each column (C B I L M) - var $_colnames; // names of each column in array - var $_skiprow1; // skip 1st row because it holds column names - var $_fieldarr; // holds array of field objects - var $canSeek = true; - var $affectedrows = false; - var $insertid = false; - var $sql = ''; - var $compat = false; - /** - * Constructor - * - */ - function ADORecordSet_array($fakeid=1) - { - global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH; - - // fetch() on EOF does not delete $this->fields - $this->compat = !empty($ADODB_COMPAT_FETCH); - $this->ADORecordSet($fakeid); // fake queryID - $this->fetchMode = $ADODB_FETCH_MODE; - } - - - /** - * Setup the Array. Later we will have XML-Data and CSV handlers - * - * @param array is a 2-dimensional array holding the data. - * The first row should hold the column names - * unless paramter $colnames is used. - * @param typearr holds an array of types. These are the same types - * used in MetaTypes (C,B,L,I,N). - * @param [colnames] array of column names. If set, then the first row of - * $array should not hold the column names. - */ - function InitArray($array,$typearr,$colnames=false) - { - $this->_array = $array; - $this->_types = $typearr; - if ($colnames) { - $this->_skiprow1 = false; - $this->_colnames = $colnames; - } else $this->_colnames = $array[0]; - - $this->Init(); - } - /** - * Setup the Array and datatype file objects - * - * @param array is a 2-dimensional array holding the data. - * The first row should hold the column names - * unless paramter $colnames is used. - * @param fieldarr holds an array of ADOFieldObject's. - */ - function InitArrayFields($array,$fieldarr) - { - $this->_array = $array; - $this->_skiprow1= false; - if ($fieldarr) { - $this->_fieldobjects = $fieldarr; - } - $this->Init(); - } - - function &GetArray($nRows=-1) - { - if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) { - return $this->_array; - } else { - return ADORecordSet::GetArray($nRows); - } - } - - function _initrs() - { - $this->_numOfRows = sizeof($this->_array); - if ($this->_skiprow1) $this->_numOfRows -= 1; - - $this->_numOfFields =(isset($this->_fieldobjects)) ? - sizeof($this->_fieldobjects):sizeof($this->_types); - } - - /* Use associative array to get fields array */ - function Fields($colname) - { - if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname]; - - if (!$this->bind) { - $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { - $o = $this->FetchField($i); - $this->bind[strtoupper($o->name)] = $i; - } - } - return $this->fields[$this->bind[strtoupper($colname)]]; - } - - function &FetchField($fieldOffset = -1) - { - if (isset($this->_fieldobjects)) { - return $this->_fieldobjects[$fieldOffset]; - } - $o = new ADOFieldObject(); - $o->name = $this->_colnames[$fieldOffset]; - $o->type = $this->_types[$fieldOffset]; - $o->max_length = -1; // length not known - - return $o; - } - - function _seek($row) - { - if (sizeof($this->_array) && $row < $this->_numOfRows) { - $this->fields = $this->_array[$row]; - return true; - } - return false; - } - - function MoveNext() - { - if (!$this->EOF) { - $this->_currentRow++; - - $pos = $this->_currentRow; - if ($this->_skiprow1) $pos += 1; - - if ($this->_numOfRows <= $pos) { - if (!$this->compat) $this->fields = false; - } else { - $this->fields = $this->_array[$pos]; - return true; - } - $this->EOF = true; - } - - return false; - } - - function _fetch() - { - $pos = $this->_currentRow; - if ($this->_skiprow1) $pos += 1; - - if ($this->_numOfRows <= $pos) { - if (!$this->compat) $this->fields = false; - return false; - } - - $this->fields = $this->_array[$pos]; - return true; - } - - function _close() - { - return true; - } - - } // ADORecordSet_array - - //============================================================================================== - // HELPER FUNCTIONS - //============================================================================================== - - /** - * Synonym for ADOLoadCode. - * - * @deprecated - */ - function ADOLoadDB($dbType) - { - return ADOLoadCode($dbType); - } - - /** - * Load the code for a specific database driver - */ - function ADOLoadCode($dbType) - { - GLOBAL $ADODB_Database; - - if (!$dbType) return false; - $ADODB_Database = strtolower($dbType); - switch ($ADODB_Database) { - case 'maxsql': $ADODB_Database = 'mysqlt'; break; - case 'postgres': - case 'pgsql': $ADODB_Database = 'postgres7'; break; - } - // Karsten Kraus - return @include_once(ADODB_DIR."/drivers/adodb-".$ADODB_Database.".inc.php"); - } - - /** - * synonym for ADONewConnection for people like me who cannot remember the correct name - */ - function &NewADOConnection($db='') - { - return ADONewConnection($db); - } - - /** - * Instantiate a new Connection class for a specific database driver. - * - * @param [db] is the database Connection object to create. If undefined, - * use the last database driver that was loaded by ADOLoadCode(). - * - * @return the freshly created instance of the Connection class. - */ - function &ADONewConnection($db='') - { - global $ADODB_Database; - - $rez = true; - if ($db) { - if ($ADODB_Database != $db) ADOLoadCode($db); - } else { - if (!empty($ADODB_Database)) { - ADOLoadCode($ADODB_Database); - } else { - $rez = false; - } - } - - $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; - if (!$rez) { - if ($errorfn) { - // raise an error - $errorfn('ADONewConnection', 'ADONewConnection', -998, - "could not load the database driver for '$db", - $dbtype); - } else - ADOConnection::outp( "

ADONewConnection: Unable to load database driver '$db'

",false); - - return false; - } - - $cls = 'ADODB_'.$ADODB_Database; - $obj = new $cls(); - if ($errorfn) $obj->raiseErrorFn = $errorfn; - - return $obj; - } - - function &NewDataDictionary(&$conn) - { - $provider = $conn->dataProvider; - $drivername = $conn->databaseType; - if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') - $drivername = $conn->dataProvider; - else { - if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5); - else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4); - else - switch($drivername) { - case 'oracle': $drivername = 'oci8';break; - case 'sybase': $drivername = 'mssql';break; - case 'access': - case 'db2': - break; - default: - $drivername = 'generic'; - break; - } - } - include_once(ADODB_DIR.'/adodb-lib.inc.php'); - include_once(ADODB_DIR.'/adodb-datadict.inc.php'); - $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; - - if (!file_exists($path)) { - ADOConnection::outp("Database driver '$path' not available"); - return false; - } - include_once($path); - $class = "ADODB2_$drivername"; - $dict =& new $class(); - $dict->dataProvider = $conn->dataProvider; - $dict->connection = &$conn; - $dict->upperName = strtoupper($drivername); - if (is_resource($conn->_connectionID)) - $dict->serverInfo = $conn->ServerInfo(); - - return $dict; - } - - - /** - * Save a file $filename and its $contents (normally for caching) with file locking - */ - function adodb_write_file($filename, $contents,$debug=false) - { - # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows - # So to simulate locking, we assume that rename is an atomic operation. - # First we delete $filename, then we create a $tempfile write to it and - # rename to the desired $filename. If the rename works, then we successfully - # modified the file exclusively. - # What a stupid need - having to simulate locking. - # Risks: - # 1. $tempfile name is not unique -- very very low - # 2. unlink($filename) fails -- ok, rename will fail - # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs - # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated - if (strpos(strtoupper(PHP_OS),'WIN') !== false) { - // skip the decimal place - $mtime = substr(str_replace(' ','_',microtime()),2); - // unlink will let some latencies develop, so uniqid() is more random - @unlink($filename); - // getmypid() actually returns 0 on Win98 - never mind! - $tmpname = $filename.uniqid($mtime).getmypid(); - if (!($fd = fopen($tmpname,'a'))) return false; - $ok = ftruncate($fd,0); - if (!fwrite($fd,$contents)) $ok = false; - fclose($fd); - chmod($tmpname,0644); - if (!@rename($tmpname,$filename)) { - unlink($tmpname); - $ok = false; - } - if (!$ok) { - if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed')); - } - return $ok; - } - if (!($fd = fopen($filename, 'a'))) return false; - if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) { - $ok = fwrite( $fd, $contents ); - fclose($fd); - chmod($filename,0644); - }else { - fclose($fd); - if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename
\n"); - $ok = false; - } - - return $ok; - } - - - function adodb_backtrace($print=true) - { - $s = ''; - if (PHPVERSION() >= 4.3) { - - $MAXSTRLEN = 64; - - $s = '
';
-			$traceArr = debug_backtrace();
-			array_shift($traceArr);
-			$tabs = sizeof($traceArr)-1;
-			
-			foreach ($traceArr as $arr) {
-				$args = array();
-				for ($i=0; $i < $tabs; $i++) $s .= '   ';
-				$tabs -= 1;
-				$s .= '';
-				if (isset($arr['class'])) $s .= $arr['class'].'.';
-				if (isset($arr['args']))
-				 foreach($arr['args'] as $v) {
-					if (is_null($v)) $args[] = 'null';
-					else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
-					else if (is_object($v)) $args[] = 'Object:'.get_class($v);
-					else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
-					else { 
-						$v = (string) @$v;
-						$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
-						if (strlen($v) > $MAXSTRLEN) $str .= '...';
-						$args[] = $str;
-					}
-				}
-				$s .= $arr['function'].'('.implode(', ',$args).')';
-				$s .= @sprintf(" # line %4d, file: %s",
-					$arr['line'],$arr['file'],$arr['file']);
-				$s .= "\n";
-			}	
-			$s .= '
'; - if ($print) print $s; - } - return $s; - } - -} // defined + + Manual is at http://php.weblogs.com/adodb_manual + + */ + + if (!defined('_ADODB_LAYER')) { + define('_ADODB_LAYER',1); + + //============================================================================================== + // CONSTANT DEFINITIONS + //============================================================================================== + + define('ADODB_BAD_RS','

Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;

'); + + define('ADODB_FETCH_DEFAULT',0); + define('ADODB_FETCH_NUM',1); + define('ADODB_FETCH_ASSOC',2); + define('ADODB_FETCH_BOTH',3); + + /* + Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names. + This currently works only with mssql, odbc, oci8po and ibase derived drivers. + + 0 = assoc lowercase field names. $rs->fields['orderid'] + 1 = assoc uppercase field names. $rs->fields['ORDERID'] + 2 = use native-case field names. $rs->fields['OrderID'] + */ + if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + + // allow [ ] @ ` and . in table names + define('ADODB_TABLE_REGEX','([]0-9a-z_\`\.\@\[-]*)'); + + + if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); + + /** + * Set ADODB_DIR to the directory where this file resides... + * This constant was formerly called $ADODB_RootPath + */ + if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__)); + + if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100); + + //============================================================================================== + // GLOBAL VARIABLES + //============================================================================================== + + GLOBAL + $ADODB_vers, // database version + $ADODB_Database, // last database driver used + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_EXTENSION, // ADODB extension installed + $ADODB_COMPAT_PATCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF + $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... + + //============================================================================================== + // GLOBAL SETUP + //============================================================================================== + + if (strnatcmp(PHP_VERSION,'4.3.0')>=0) { + define('ADODB_PHPVER',0x4300); + } else if (strnatcmp(PHP_VERSION,'4.2.0')>=0) { + define('ADODB_PHPVER',0x4200); + } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) { + define('ADODB_PHPVER',0x4050); + } else { + define('ADODB_PHPVER',0x4000); + } + $ADODB_EXTENSION = defined('ADODB_EXTENSION'); + //if (extension_loaded('dbx')) define('ADODB_DBX',1); + + /** + Accepts $src and $dest arrays, replacing string $data + */ + function ADODB_str_replace($src, $dest, $data) + { + if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data); + + $s = reset($src); + $d = reset($dest); + while ($s !== false) { + $data = str_replace($s,$d,$data); + $s = next($src); + $d = next($dest); + } + return $data; + } + + function ADODB_Setup() + { + GLOBAL + $ADODB_vers, // database version + $ADODB_Database, // last database driver used + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_FETCH_MODE; + + $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; + + if (!isset($ADODB_CACHE_DIR)) { + $ADODB_CACHE_DIR = '/tmp'; + } else { + // do not accept url based paths, eg. http:/ or ftp:/ + if (strpos($ADODB_CACHE_DIR,'://') !== false) + die("Illegal path http:// or ftp://"); + } + + + // Initialize random number generator for randomizing cache flushes + srand(((double)microtime())*1000000); + + /** + * Name of last database driver loaded into memory. Set by ADOLoadCode(). + */ + $ADODB_Database = ''; + + /** + * ADODB version as a string. + */ + $ADODB_vers = 'V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved. Released BSD & LGPL.'; + + /** + * Determines whether recordset->RecordCount() is used. + * Set to false for highest performance -- RecordCount() will always return -1 then + * for databases that provide "virtual" recordcounts... + */ + $ADODB_COUNTRECS = true; + } + + + //============================================================================================== + // CHANGE NOTHING BELOW UNLESS YOU ARE CODING + //============================================================================================== + + ADODB_Setup(); + + //============================================================================================== + // CLASS ADOFieldObject + //============================================================================================== + /** + * Helper class for FetchFields -- holds info on a column + */ + class ADOFieldObject { + var $name = ''; + var $max_length=0; + var $type=""; + + // additional fields by dannym... (danny_milo@yahoo.com) + var $not_null = false; + // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^ + // so we can as well make not_null standard (leaving it at "false" does not harm anyways) + + var $has_default = false; // this one I have done only in mysql and postgres for now ... + // others to come (dannym) + var $default_value; // default, if any, and supported. Check has_default first. + } + + + + function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) + { + //print "Errorno ($fn errno=$errno m=$errmsg) "; + + $thisConnection->_transOK = false; + if ($thisConnection->_oldRaiseFn) { + $fn = $thisConnection->_oldRaiseFn; + $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); + } + } + + //============================================================================================== + // CLASS ADOConnection + //============================================================================================== + + /** + * Connection object. For connecting to databases, and executing queries. + */ + class ADOConnection { + // + // PUBLIC VARS + // + var $dataProvider = 'native'; + var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql + var $database = ''; /// Name of database to be used. + var $host = ''; /// The hostname of the database server + var $user = ''; /// The username which is used to connect to the database server. + var $password = ''; /// Password for the username. For security, we no longer store it. + var $debug = false; /// if set to true will output sql statements + var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro + var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase + var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database + var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt. + var $true = '1'; /// string that represents TRUE for a database + var $false = '0'; /// string that represents FALSE for a database + var $replaceQuote = "\\'"; /// string to use to replace quotes + var $charSet=false; /// character set to use - only for interbase + var $metaDatabasesSQL = ''; + var $metaTablesSQL = ''; + var $uniqueOrderBy = false; /// All order by columns have to be unique + var $emptyDate = ' '; + //-- + var $hasInsertID = false; /// supports autoincrement ID? + var $hasAffectedRows = false; /// supports affected rows for update/delete? + var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE + var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10 + var $readOnly = false; /// this is a readonly database - used by phpLens + var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards + var $hasGenID = false; /// can generate sequences using GenID(); + var $hasTransactions = true; /// has transactions + //-- + var $genID = 0; /// sequence id used by GenID(); + var $raiseErrorFn = false; /// error function to call + var $upperCase = false; /// uppercase function to call for searching/where + var $isoDates = false; /// accepts dates in ISO format + var $cacheSecs = 3600; /// cache for 1 hour + var $sysDate = false; /// name of function that returns the current date + var $sysTimeStamp = false; /// name of function that returns the current timestamp + var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets + + var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' + var $numCacheHits = 0; + var $numCacheMisses = 0; + var $pageExecuteCountRows = true; + var $uniqueSort = false; /// indicates that all fields in order by must be unique + var $leftOuter = false; /// operator to use for left outer join in WHERE clause + var $rightOuter = false; /// operator to use for right outer join in WHERE clause + var $ansiOuter = false; /// whether ansi outer join syntax supported + var $autoRollback = false; // autoRollback on PConnect(). + var $poorAffectedRows = false; // affectedRows not working or unreliable + + var $fnExecute = false; + var $fnCacheExecute = false; + var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char + var $dbxDriver = false; + + // + // PRIVATE VARS + // + var $_oldRaiseFn = false; + var $_transOK = null; + var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. + var $_errorMsg = ''; /// A variable which was used to keep the returned last error message. The value will + /// then returned by the errorMsg() function + + var $_queryID = false; /// This variable keeps the last created result link identifier + + var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ + var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. + var $autoCommit = true; /// do not modify this yourself - actually private + var $transOff = 0; /// temporarily disable transactions + var $transCnt = 0; /// count of nested transactions + + var $fetchMode=false; + + /** + * Constructor + */ + function ADOConnection() + { + die('Virtual Class -- cannot instantiate'); + } + + /** + Get server version info... + + @returns An array with 2 elements: $arr['string'] is the description string, + and $arr[version] is the version (also a string). + */ + function ServerInfo() + { + return array('description' => '', 'version' => ''); + } + + function _findvers($str) + { + if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; + else return ''; + } + + /** + * All error messages go through this bottleneck function. + * You can define your own handler by defining the function name in ADODB_OUTP. + */ + function outp($msg,$newline=true) + { + global $HTTP_SERVER_VARS; + + if (defined('ADODB_OUTP')) { + $fn = ADODB_OUTP; + $fn($msg,$newline); + return; + } + + if ($newline) $msg .= "
\n"; + + if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT'])) echo $msg; + else echo strip_tags($msg); + flush(); + } + + /** + * Connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * @param [forceNew] force new connection + * + * @return true or false + */ + function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) + { + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons + if ($argDatabaseName != "") $this->database = $argDatabaseName; + + $this->_isPersistentConnection = false; + if ($fn = $this->raiseErrorFn) { + if ($forceNew) { + if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + } else { + if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + } + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); + } else { + if ($forceNew) { + if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + } else { + if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + } + } + if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg()); + return false; + } + + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) + { + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName); + } + + + /** + * Always force a new connection to database - currently only works with oracle + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return true or false + */ + function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true); + } + + /** + * Establish persistent connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return return true or false + */ + function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + if (defined('ADODB_NEVER_PERSIST')) + return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName); + + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; + if ($argDatabaseName != "") $this->database = $argDatabaseName; + + $this->_isPersistentConnection = true; + + if ($fn = $this->raiseErrorFn) { + if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); + } else + if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; + + if ($this->debug) ADOConnection::outp( $this->host.': '.$this->ErrorMsg()); + return false; + } + + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col=false) + { + if (!$col) $col = $this->sysDate; + return $col; // child class implement + } + + /** + * Should prepare the sql statement and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * $stmt = $db->Prepare("insert into table (id, name) values (?,?)"); + * $db->Execute($stmt,array(1,'Jill')) or die('insert failed'); + * $db->Execute($stmt,array(2,'Joe')) or die('insert failed'); + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function Prepare($sql) + { + return $sql; + } + + /** + * Some databases, eg. mssql require a different function for preparing + * stored procedures. So we cannot use Prepare(). + * + * Should prepare the stored procedure and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function PrepareSP($sql) + { + return $this->Prepare($sql); + } + + /** + * PEAR DB Compat + */ + function Quote($s) + { + return $this->qstr($s,false); + } + + function q(&$s) + { + $s = $this->qstr($s,false); + } + + /** + * PEAR DB Compat - do not use internally. + */ + function ErrorNative() + { + return $this->ErrorNo(); + } + + + /** + * PEAR DB Compat - do not use internally. + */ + function nextId($seq_name) + { + return $this->GenID($seq_name); + } + + /** + * Lock a row, will escalate and lock the table if row locking not supported + * will normally free the lock at the end of the transaction + * + * @param $table name of table to lock + * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock + */ + function RowLock($table,$where) + { + return false; + } + + function CommitLock($table) + { + return $this->CommitTrans(); + } + + function RollbackLock($table) + { + return $this->RollbackTrans(); + } + + /** + * PEAR DB Compat - do not use internally. + * + * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical + * for easy porting :-) + * + * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM + * @returns The previous fetch mode + */ + function SetFetchMode($mode) + { + $old = $this->fetchMode; + $this->fetchMode = $mode; + + if ($old === false) { + global $ADODB_FETCH_MODE; + return $ADODB_FETCH_MODE; + } + return $old; + } + + + /** + * PEAR DB Compat - do not use internally. + */ + function &Query($sql, $inputarr=false) + { + $rs = &$this->Execute($sql, $inputarr); + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } + + + /** + * PEAR DB Compat - do not use internally + */ + function &LimitQuery($sql, $offset, $count) + { + $rs = &$this->SelectLimit($sql, $count, $offset); // swap + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } + + + /** + * PEAR DB Compat - do not use internally + */ + function Disconnect() + { + return $this->Close(); + } + + /* + Usage in oracle + $stmt = $db->Prepare('select * from table where id =:myid and group=:group'); + $db->Parameter($stmt,$id,'myid'); + $db->Parameter($stmt,$group,'group',64); + $db->Execute(); + + @param $stmt Statement returned by Prepare() or PrepareSP(). + @param $var PHP variable to bind to + @param $name Name of stored procedure variable name to bind to. + @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8. + @param [$maxLen] Holds an maximum length of the variable. + @param [$type] The data type of $var. Legal values depend on driver. + + */ + function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) + { + return false; + } + + /** + Improved method of initiating a transaction. Used together with CompleteTrans(). + Advantages include: + + a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans. + Only the outermost block is treated as a transaction.
+ b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
+ c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block + are disabled, making it backward compatible. + */ + function StartTrans($errfn = 'ADODB_TransMonitor') + { + + if ($this->transOff > 0) { + $this->transOff += 1; + return; + } + + $this->_oldRaiseFn = $this->raiseErrorFn; + $this->raiseErrorFn = $errfn; + $this->_transOK = true; + + if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); + $this->BeginTrans(); + $this->transOff = 1; + } + + /** + Used together with StartTrans() to end a transaction. Monitors connection + for sql errors, and will commit or rollback as appropriate. + + @autoComplete if true, monitor sql errors and commit and rollback as appropriate, + and if set to false force rollback even if no SQL error detected. + @returns true on commit, false on rollback. + */ + function CompleteTrans($autoComplete = true) + { + if ($this->transOff > 1) { + $this->transOff -= 1; + return true; + } + $this->raiseErrorFn = $this->_oldRaiseFn; + + $this->transOff = 0; + if ($this->_transOK && $autoComplete) $this->CommitTrans(); + else $this->RollbackTrans(); + + return $this->_transOK; + } + + /* + At the end of a StartTrans/CompleteTrans block, perform a rollback. + */ + function FailTrans() + { + if ($this->debug && $this->transOff == 0) { + ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); + } + $this->_transOK = false; + } + + function getmicrotime() + { + list($usec, $sec) = explode(" ",microtime()); + return ((float)$usec + (float)$sec); + } + + /** + * Execute SQL + * + * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) + * @param [inputarr] holds the input data to bind to. Null elements will be set to null. + * @param [arg3] reserved for john lim for future use + * @return RecordSet or false + */ + function &Execute($sql,$inputarr=false,$arg3=false) + { + global $pathtoroot, $totalsql, $sqlcount; + if ($this->fnExecute) { + $fn = $this->fnExecute; + $fn($this,$sql,$inputarr); + } + if (!$this->_bindInputArray && $inputarr) { + $sqlarr = explode('?',$sql); + $sql = ''; + $i = 0; + foreach($inputarr as $v) { + + $sql .= $sqlarr[$i]; + // from Ron Baldwin + // Only quote string types + if (gettype($v) == 'string') + $sql .= $this->qstr($v); + else if ($v === null) + $sql .= 'NULL'; + else + $sql .= $v; + $i += 1; + + } + $sql .= $sqlarr[$i]; + if ($i+1 != sizeof($sqlarr)) + ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql)); + $inputarr = false; + } + // debug version of query + if ($this->debug) { + global $HTTP_SERVER_VARS; + + $ss = ''; + if ($inputarr) { + foreach ($inputarr as $kk => $vv) { + if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...'; + $ss .= "($kk=>'$vv') "; + } + $ss = "[ $ss ]"; + } + $sqlTxt = str_replace(',',', ',is_array($sql) ?$sql[0] : $sql); + + // check if running from browser or command-line + $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); + + if ($inBrowser) + ADOConnection::outp( "
\n($this->databaseType): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); + else + ADOConnection::outp( "=----\n($this->databaseType): ".($sqlTxt)." \n-----\n",false); + flush(); + + $this->_queryID = $this->_query($sql,$inputarr,$arg3); + + /* + Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql + because ErrorNo() calls Execute('SELECT @ERROR'), causing recure + */ + if ($this->databaseType == 'mssql') { + // ErrorNo is a slow function call in mssql, and not reliable + // in PHP 4.0.6 + if($emsg = $this->ErrorMsg()) { + $err = $this->ErrorNo(); + if ($err) { + ADOConnection::outp($err.': '.$emsg); + flush(); + } + } + } else + if (!$this->_queryID) { + $e = $this->ErrorNo(); + $m = $this->ErrorMsg(); + +if(defined('SQL_ERROR_DIE')&&SQL_ERROR_DIE) +{ + echo '
'.$sql.'
Error #'.$e.': '.$m.'

'; + echo 'Request
'; + print_r($_REQUEST); + echo 'Back Trace
'; + print_r(debug_backtrace()); + echo '
'; + exit; +} + ADOConnection::outp($e .': '. $m ); + flush(); + } + } else { + // non-debug version of query + + + $sqlcount++; + $sql_start = $this->getmicrotime(); + $this->_queryID =@$this->_query($sql,$inputarr,$arg3); + $sql_end = $this->getmicrotime(); + $elapsed = $sql_end - $sql_start; + $totalsql += $elapsed; + //$fp = @fopen ($pathtoroot."log.sql", "aw"); + $starttime = 0; // by Alex (variable was not defined) + $d=time()-$starttime; + $t=date("Y-m-d\tH:i:s",$starttime); + $e = round($elapsed,5); + if(function_exists("LogEntry")) + @LogEntry("\t\t$sqlcount|$e:|$sql\n"); + + } + // error handling if query fails + if ($this->_queryID === false) { + $fn = $this->raiseErrorFn; + if ($fn) { + $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this); + } + return false; + } else if ($this->_queryID === true) { + // return simplified empty recordset for inserts/updates/deletes with lower overhead + $rs = new ADORecordSet_empty(); + return $rs; + } + + // return real recordset from select statement + $rsclass = "ADORecordSet_".$this->databaseType; + $rs = new $rsclass($this->_queryID,$this->fetchMode); // &new not supported by older PHP versions + $rs->connection = &$this; // Pablo suggestion + $rs->Init(); + if (is_array($sql)) $rs->sql = $sql[0]; + else $rs->sql = $sql; + + if ($rs->_numOfRows <= 0) { + global $ADODB_COUNTRECS; + + if ($ADODB_COUNTRECS) { + if (!$rs->EOF){ + $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql)); + $rs->_queryID = $this->_queryID; + } else + $rs->_numOfRows = 0; + } + } + return $rs; + } + + function CreateSequence($seqname='adodbseq',$startID=1) + { + if (empty($this->_genSeqSQL)) return false; + return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); + } + + function DropSequence($seqname) + { + if (empty($this->_dropSeqSQL)) return false; + return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); + } + + /** + * Generates a sequence id and stores it in $this->genID; + * GenID is only available if $this->hasGenID = true; + * + * @param seqname name of sequence to use + * @param startID if sequence does not exist, start at this ID + * @return 0 if not supported, otherwise a sequence id + */ + + function GenID($seqname='adodbseq',$startID=1) + { + if (!$this->hasGenID) { + return 0; // formerly returns false pre 1.60 + } + + $getnext = sprintf($this->_genIDSQL,$seqname); + $rs = @$this->Execute($getnext); + if (!$rs) { + $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); + $rs = $this->Execute($getnext); + } + if ($rs && !$rs->EOF) $this->genID = reset($rs->fields); + else $this->genID = 0; // false + + if ($rs) $rs->Close(); + + return $this->genID; + } + + /** + * @return the last inserted ID. Not all databases support this. + */ + function Insert_ID() + { + if ($this->hasInsertID) return $this->_insertid(); + if ($this->debug) ADOConnection::outp( '

Insert_ID error

'); + return false; + } + + + /** + * Portable Insert ID. Pablo Roca + * + * @return the last inserted ID. All databases support this. But aware possible + * problems in multiuser environments. Heavy test this before deploying. + */ + function PO_Insert_ID($table="", $id="") + { + if ($this->hasInsertID){ + return $this->Insert_ID(); + } else { + return $this->GetOne("SELECT MAX($id) FROM $table"); + } + } + + + /** + * @return # rows affected by UPDATE/DELETE + */ + function Affected_Rows() + { + if ($this->hasAffectedRows) { + $val = $this->_affectedrows(); + return ($val < 0) ? false : $val; + } + + if ($this->debug) ADOConnection::outp( '

Affected_Rows error

',false); + return false; + } + + + /** + * @return the last error message + */ + function ErrorMsg() + { + return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; + } + + + /** + * @return the last error number. Normally 0 means no error. + */ + function ErrorNo() + { + return ($this->_errorMsg) ? -1 : 0; + } + + function MetaError($err=false) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + if ($err === false) $err = $this->ErrorNo(); + return adodb_error($this->dataProvider,$this->databaseType,$err); + } + + function MetaErrorMsg($errno) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + return adodb_errormsg($errno); + } + + /** + * @returns an array with the primary key columns in it. + */ + function MetaPrimaryKeys($table, $owner=false) + { + // owner not used in base class - see oci8 + $p = array(); + $objs =& $this->MetaColumns($table); + if ($objs) { + foreach($objs as $v) { + if (!empty($v->primary_key)) + $p[] = $v->name; + } + } + if (sizeof($p)) return $p; + return false; + } + + + /** + * Choose a database to connect to. Many databases do not support this. + * + * @param dbName is the name of the database to select + * @return true or false + */ + function SelectDB($dbName) + {return false;} + + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) + * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) + * + * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) + * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @param [arg3] is a private parameter only used by jlim + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + */ + function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0) + { + if ($this->hasTop && $nrows > 0) { + // suggested by Reinhard Balling. Access requires top after distinct + // Informix requires first before distinct - F Riosa + $ismssql = (strpos($this->databaseType,'mssql') !== false); + if ($ismssql) $isaccess = false; + else $isaccess = (strpos($this->databaseType,'access') !== false); + + if ($offset <= 0) { + + // access includes ties in result + if ($isaccess) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + + if ($secs2cache>0) return $this->CacheExecute($secs2cache, $sql,$inputarr,$arg3); + else return $this->Execute($sql,$inputarr,$arg3); + } else if ($ismssql){ + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql); + } + } else { + $nn = $nrows + $offset; + if ($isaccess || $ismssql) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } + } + } + + // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows + // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + if ($offset>0){ + if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3); + else $rs = &$this->Execute($sql,$inputarr,$arg3); + } else { + if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3); + else $rs = &$this->Execute($sql,$inputarr,$arg3); + } + $ADODB_COUNTRECS = $savec; + if ($rs && !$rs->EOF) { + return $this->_rs2rs($rs,$nrows,$offset); + } + //print_r($rs); + return $rs; + } + + + /** + * Convert database recordset to an array recordset + * input recordset's cursor should be at beginning, and + * old $rs will be closed. + * + * @param rs the recordset to copy + * @param [nrows] number of rows to retrieve (optional) + * @param [offset] offset by number of rows (optional) + * @return the new recordset + */ + function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) + { + if (! $rs) return false; + + $dbtype = $rs->databaseType; + if (!$dbtype) { + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? + return $rs; + } + if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { + $rs->MoveFirst(); + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? + return $rs; + } + $flds = array(); + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { + $flds[] = $rs->FetchField($i); + } + $arr =& $rs->GetArrayLimit($nrows,$offset); + //print_r($arr); + if ($close) $rs->Close(); + + $arrayClass = $this->arrayClass; + + $rs2 = new $arrayClass(); + $rs2->connection = &$this; + $rs2->sql = $rs->sql; + $rs2->dataProvider = $this->dataProvider; + $rs2->InitArrayFields($arr,$flds); + return $rs2; + } + + + function &GetArray($sql, $inputarr=false) + { + return $this->GetAll($sql,$inputarr); + } + + /** + * Return first element of first row of sql statement. Recordset is disposed + * for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function GetOne($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $ret = false; + $rs = &$this->Execute($sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + $ADODB_COUNTRECS = $crecs; + return $ret; + } + + function CacheGetOne($secs2cache,$sql=false,$inputarr=false) + { + $ret = false; + $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + + return $ret; + } + + function GetCol($sql, $inputarr = false, $trim = false) + { + $rv = false; + $rs = &$this->Execute($sql, $inputarr); + + if ($rs) { + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + + return $rv; + } + + function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) + { + $rv = false; + $rs = &$this->CacheExecute($secs, $sql, $inputarr); + if ($rs) { + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + return $rv; + } + + /* + Calculate the offset of a date for a particular database and generate + appropriate SQL. Useful for calculating future/past dates and storing + in a database. + + If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour. + */ + function OffsetDate($dayFraction,$date=false) + { + if (!$date) $date = $this->sysDate; + return '('.$date.'+'.$dayFraction.')'; + } + + + /** + * Return all rows. Compat with PEAR DB + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetAll($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs = $this->Execute($sql,$inputarr); + $ADODB_COUNTRECS = $savec; + + if (!$rs) + if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + else return false; + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + function &CacheGetAll($secs2cache,$sql=false,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); + $ADODB_COUNTRECS = $savec; + + if (!$rs) + if (defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + else return false; + + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + + + /** + * Return one row of sql statement. Recordset is disposed for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function &GetRow($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $rs = $this->Execute($sql,$inputarr); + + $ADODB_COUNTRECS = $crecs; + if ($rs) { + $arr = array(); + if (!$rs->EOF) $arr = $rs->fields; + $rs->Close(); + return $arr; + } + + return false; + } + + function &CacheGetRow($secs2cache,$sql=false,$inputarr=false) + { + $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + $arr = false; + if (!$rs->EOF) $arr = $rs->fields; + $rs->Close(); + return $arr; + } + return false; + } + + /** + * Insert or replace a single record. Note: this is not the same as MySQL's replace. + * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. + * Also note that no table locking is done currently, so it is possible that the + * record be inserted twice by two programs... + * + * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); + * + * $table table name + * $fieldArray associative array of data (you must quote strings yourself). + * $keyCol the primary key field name or if compound key, array of field names + * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers + * but does not work with dates nor SQL functions. + * has_autoinc the primary key is an auto-inc field, so skip in insert. + * + * Currently blob replace not supported + * + * returns 0 = fail, 1 = update, 2 = insert + */ + + function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) + { + if (count($fieldArray) == 0) return 0; + $first = true; + $uSet = ''; + + if (!is_array($keyCol)) { + $keyCol = array($keyCol); + } + foreach($fieldArray as $k => $v) { + if ($autoQuote && !is_numeric($v) and substr($v,0,1) != "'" and strcasecmp($v,'null')!=0) { + $v = $this->qstr($v); + $fieldArray[$k] = $v; + } + if (in_array($k,$keyCol)) continue; // skip UPDATE if is key + + if ($first) { + $first = false; + $uSet = "$k=$v"; + } else + $uSet .= ",$k=$v"; + } + + $first = true; + foreach ($keyCol as $v) { + if ($first) { + $first = false; + $where = "$v=$fieldArray[$v]"; + } else { + $where .= " and $v=$fieldArray[$v]"; + } + } + + if ($uSet) { + $update = "UPDATE $table SET $uSet WHERE $where"; + + $rs = $this->Execute($update); + if ($rs) { + if ($this->poorAffectedRows) { + /* + The Select count(*) wipes out any errors that the update would have returned. + http://phplens.com/lens/lensforum/msgs.php?id=5696 + */ + if ($this->ErrorNo()<>0) return 0; + + # affected_rows == 0 if update field values identical to old values + # for mysql - which is silly. + + $cnt = $this->GetOne("select count(*) from $table where $where"); + if ($cnt > 0) return 1; // record already exists + } else + if (($this->Affected_Rows()>0)) return 1; + } + + } + // print "

Error=".$this->ErrorNo().'

'; + $first = true; + foreach($fieldArray as $k => $v) { + if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col + + if ($first) { + $first = false; + $iCols = "$k"; + $iVals = "$v"; + } else { + $iCols .= ",$k"; + $iVals .= ",$v"; + } + } + $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; + $rs = $this->Execute($insert); + return ($rs) ? 2 : 0; + } + + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based) + * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based) + * + * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @param [arg3] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + */ + function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false) + { + if (!is_numeric($secs2cache)) { + if ($sql === false) $sql = -1; + if ($offset == -1) $offset = false; + // sql, nrows, offset,inputarr,arg3 + return $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$inputarr,$this->cacheSecs); + } else { + if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()"); + return $this->SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache); + } + } + + /** + * Flush cached recordsets that match a particular $sql statement. + * If $sql == false, then we purge all files in the cache. + */ + function CacheFlush($sql=false,$inputarr=false) + { + global $ADODB_CACHE_DIR; + + if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { + if (strpos(strtoupper(PHP_OS),'WIN') !== false) { + $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache'; + } else { + $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache'; + // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; + } + if ($this->debug) { + ADOConnection::outp( "CacheFlush: $cmd

\n", system($cmd),"
"); + } else { + exec($cmd); + } + return; + } + $f = $this->_gencachename($sql.serialize($inputarr),false); + adodb_write_file($f,''); // is adodb_write_file needed? + @unlink($f); + } + + /** + * Private function to generate filename for caching. + * Filename is generated based on: + * + * - sql statement + * - database type (oci8, ibase, ifx, etc) + * - database name + * - userid + * + * We create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). + * Assuming that we can have 50,000 files per directory with good performance, + * then we can scale to 12.8 million unique cached recordsets. Wow! + */ + function _gencachename($sql,$createdir) + { + global $ADODB_CACHE_DIR; + + $m = md5($sql.$this->databaseType.$this->database.$this->user); + $dir = $ADODB_CACHE_DIR.'/'.substr($m,0,2); + if ($createdir && !file_exists($dir)) { + $oldu = umask(0); + if (!mkdir($dir,0771)) + if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql"); + umask($oldu); + } + return $dir.'/adodb_'.$m.'.cache'; + } + + + /** + * Execute SQL, caching recordsets. + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. + * This is an optional parameter. + * @param sql SQL statement to execute + * @param [inputarr] holds the input data to bind to + * @param [arg3] reserved for john lim for future use + * @return RecordSet or false + */ + function &CacheExecute($secs2cache,$sql=false,$inputarr=false,$arg3=false) + { + if (!is_numeric($secs2cache)) { + $arg3 = $inputarr; + $inputarr = $sql; + $sql = $secs2cache; + $secs2cache = $this->cacheSecs; + } + include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); + + $md5file = $this->_gencachename($sql.serialize($inputarr),true); + $err = ''; + + if ($secs2cache > 0){ + $rs = &csv2rs($md5file,$err,$secs2cache); + $this->numCacheHits += 1; + } else { + $err='Timeout 1'; + $rs = false; + $this->numCacheMisses += 1; + } + if (!$rs) { + // no cached rs found + if ($this->debug) { + if (get_magic_quotes_runtime()) { + ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); + } + ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); + } + $rs = &$this->Execute($sql,$inputarr,$arg3); + if ($rs) { + $eof = $rs->EOF; + $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately + $txt = _rs2serialize($rs,false,$sql); // serialize + + if (!adodb_write_file($md5file,$txt,$this->debug)) { + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); + } + if ($this->debug) ADOConnection::outp( " Cache write error"); + } + if ($rs->EOF && !$eof) { + $rs->MoveFirst(); + //$rs = &csv2rs($md5file,$err); + $rs->connection = &$this; // Pablo suggestion + } + + } else + @unlink($md5file); + } else { + if ($this->fnCacheExecute) { + $fn = $this->fnCacheExecute; + $fn($this, $secs2cache, $sql, $inputarr); + } + // ok, set cached object found + $rs->connection = &$this; // Pablo suggestion + if ($this->debug){ + global $HTTP_SERVER_VARS; + + $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']); + $ttl = $rs->timeCreated + $secs2cache - time(); + $s = is_array($sql) ? $sql[0] : $sql; + if ($inBrowser) $s = ''.htmlspecialchars($s).''; + + ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); + } + } + return $rs; + } + + + /** + * Generates an Update Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table and sql should only + * be a simple select stmt with no groupby/orderby/limit + * + * "Jonathan Younger" + */ + function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false) + { + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq); + } + + + /** + * Generates an Insert Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table. + */ + function GetInsertSQL(&$rs, $arrFields,$magicq=false) + { + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getinsertsql($this,$rs,$arrFields,$magicq); + } + + + /** + * Update a blob column, given a where clause. There are more sophisticated + * blob handling functions that we could have implemented, but all require + * a very complex API. Instead we have chosen something that is extremely + * simple to understand and use. + * + * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course. + * + * Usage to update a $blobvalue which has a primary key blob_id=1 into a + * field blobtable.blobcolumn: + * + * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1'); + * + * Insert example: + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); + */ + + function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + { + return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false; + } + + /** + * Usage: + * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1'); + * + * $blobtype supports 'BLOB' and 'CLOB' + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1'); + */ + function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') + { + $fd = fopen($path,'rb'); + if ($fd === false) return false; + $val = fread($fd,filesize($path)); + fclose($fd); + return $this->UpdateBlob($table,$column,$val,$where,$blobtype); + } + + function BlobDecode($blob) + { + return $blob; + } + + function BlobEncode($blob) + { + return $blob; + } + + /** + * Usage: + * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB'); + * + * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)'); + * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1'); + */ + function UpdateClob($table,$column,$val,$where) + { + return $this->UpdateBlob($table,$column,$val,$where,'CLOB'); + } + + + /** + * $meta contains the desired type, which could be... + * C for character. You will have to define the precision yourself. + * X for teXt. For unlimited character lengths. + * B for Binary + * F for floating point, with no need to define scale and precision + * N for decimal numbers, you will have to define the (scale, precision) yourself + * D for date + * T for timestamp + * L for logical/Boolean + * I for integer + * R for autoincrement counter/integer + * and if you want to use double-byte, add a 2 to the end, like C2 or X2. + * + * + * @return the actual type of the data or false if no such type available + */ + function ActualType($meta) + { + switch($meta) { + case 'C': + case 'X': + return 'VARCHAR'; + case 'B': + + case 'D': + case 'T': + case 'L': + + case 'R': + + case 'I': + case 'N': + return false; + } + } + + /* + * Maximum size of C field + */ + function CharMax() + { + return 255; // make it conservative if not defined + } + + + /* + * Maximum size of X field + */ + function TextMax() + { + return 4000; // make it conservative if not defined + } + + /** + * Close Connection + */ + function Close() + { + return $this->_close(); + + // "Simon Lee" reports that persistent connections need + // to be closed too! + //if ($this->_isPersistentConnection != true) return $this->_close(); + //else return true; + } + + /** + * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). + * + * @return true if succeeded or false if database does not support transactions + */ + function BeginTrans() {return false;} + + + /** + * If database does not support transactions, always return true as data always commited + * + * @param $ok set to false to rollback transaction, true to commit + * + * @return true/false. + */ + function CommitTrans($ok=true) + { return true;} + + + /** + * If database does not support transactions, rollbacks always fail, so return false + * + * @return true/false. + */ + function RollbackTrans() + { return false;} + + + /** + * return the databases that the driver can connect to. + * Some databases will return an empty array. + * + * @return an array of database names. + */ + function MetaDatabases() + { + global $ADODB_FETCH_MODE; + + if ($this->metaDatabasesSQL) { + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $arr = $this->GetCol($this->metaDatabasesSQL); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + return $arr; + } + + return false; + } + + /** + * @return array of tables for current database. + */ + function &MetaTables() + { + global $ADODB_FETCH_MODE; + + if ($this->metaTablesSQL) { + // complicated state saving by the need for backward compat + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $rs = $this->Execute($this->metaTablesSQL); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if ($rs === false) return false; + $arr =& $rs->GetArray(); + $arr2 = array(); + for ($i=0; $i < sizeof($arr); $i++) { + $arr2[] = $arr[$i][0]; + } + $rs->Close(); + return $arr2; + } + return false; + } + + + /** + * List columns in a database as an array of ADOFieldObjects. + * See top of file for definition of object. + * + * @param table table name to query + * @param upper uppercase table name (required by some databases) + * + * @return array of ADOFieldObjects for current table. + */ + function &MetaColumns($table,$upper=true) + { + global $ADODB_FETCH_MODE; + + if (!empty($this->metaColumnsSQL)) { + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table)); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if ($rs === false) return false; + + $retarr = array(); + while (!$rs->EOF) { //print_r($rs->fields); + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + if (isset($rs->fields[3]) && $rs->fields[3]) { + if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3]; + $fld->scale = $rs->fields[4]; + if ($fld->scale>0) $fld->max_length += 1; + } else + $fld->max_length = $rs->fields[2]; + + + $retarr[strtoupper($fld->name)] = $fld; + + $rs->MoveNext(); + } + $rs->Close(); + return $retarr; + } + return false; + } + + /** + * List columns names in a table as an array. + * @param table table name to query + * + * @return array of column names for current table. + */ + function &MetaColumnNames($table) + { + $objarr =& $this->MetaColumns($table); + if (!is_array($objarr)) return false; + + $arr = array(); + foreach($objarr as $v) { + $arr[] = $v->name; + } + return $arr; + } + + /** + * Different SQL databases used different methods to combine strings together. + * This function provides a wrapper. + * + * param s variable number of string parameters + * + * Usage: $db->Concat($str1,$str2); + * + * @return concatenated string + */ + function Concat() + { + $arr = func_get_args(); + return implode($this->concat_operator, $arr); + } + + + /** + * Converts a date "d" to a string that the database can understand. + * + * @param d a date in Unix date time format. + * + * @return date string in database date format + */ + function DBDate($d) + { + + if (empty($d) && $d !== 0) return 'null'; + + if (is_string($d) && !is_numeric($d)) { + if ($d === 'null') return $d; + if ($this->isoDates) return "'$d'"; + $d = ADOConnection::UnixDate($d); + } + + return adodb_date($this->fmtDate,$d); + } + + + /** + * Converts a timestamp "ts" to a string that the database can understand. + * + * @param ts a timestamp in Unix date time format. + * + * @return timestamp string in database timestamp format + */ + function DBTimeStamp($ts) + { + if (empty($ts) && $ts !== 0) return 'null'; + + if (is_string($ts) && !is_numeric($ts)) { + if ($ts === 'null') return $ts; + if ($this->isoDates) return "'$ts'"; + else $ts = ADOConnection::UnixTimeStamp($ts); + } + + return adodb_date($this->fmtTimeStamp,$ts); + } + + /** + * Also in ADORecordSet. + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", + ($v), $rr)) return false; + + if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; + // h-m-s-MM-DD-YY + return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + } + + + /** + * Also in ADORecordSet. + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($v), $rr)) return false; + if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; + + // h-m-s-MM-DD-YY + if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); + } + + /** + * Also in ADORecordSet. + * + * Format database date based on user defined format. + * + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ + + function UserDate($v,$fmt='Y-m-d') + { + $tt = $this->UnixDate($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } + + return adodb_date($fmt,$tt); + + } + + + /** + * Correctly quotes a string so that all strings are escaped. We prefix and append + * to the string single-quotes. + * An example is $db->qstr("Don't bother",magic_quotes_runtime()); + * + * @param s the string to quote + * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). + * This undoes the stupidity of magic quotes for GPC. + * + * @return quoted string to be sent back to database + */ + function qstr($s,$magic_quotes=false) + { + if (!$magic_quotes) { + + if ($this->replaceQuote[0] == '\\'){ + // only since php 4.0.5 + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + } + return "'".str_replace("'",$this->replaceQuote,$s)."'"; + } + + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + return "'$s'"; + else {// change \' to '' for sybase/mssql + $s = str_replace('\\\\','\\',$s); + return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; + } + } + + + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination. + * + * See readme.htm#ex8 for an example of usage. + * + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @param [arg3] is a private parameter only used by jlim + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + * + * NOTE: phpLens uses a different algorithm and does not use PageExecute(). + * + */ + function &PageExecute($sql, $nrows, $page, $inputarr=false, $arg3=false, $secs2cache=0) + { + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + if ($this->pageExecuteCountRows) return _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $arg3, $secs2cache); + return _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $arg3, $secs2cache); + + } + + + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination. + * + * @param secs2cache seconds to cache data, set to 0 to force query + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @param [arg3] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + */ + function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false, $arg3=false) + { + /*switch($this->dataProvider) { + case 'postgres': + case 'mysql': + break; + default: $secs2cache = 0; break; + }*/ + return $this->PageExecute($sql,$nrows,$page,$inputarr,$arg3,$secs2cache); + } + +} // end class ADOConnection + + + + //============================================================================================== + // CLASS ADOFetchObj + //============================================================================================== + + /** + * Internal placeholder for record objects. Used by ADORecordSet->FetchObj(). + */ + class ADOFetchObj { + }; + + //============================================================================================== + // CLASS ADORecordSet_empty + //============================================================================================== + + /** + * Lightweight recordset when there are no records to be returned + */ + class ADORecordSet_empty + { + var $dataProvider = 'empty'; + var $databaseType = false; + var $EOF = true; + var $_numOfRows = 0; + var $fields = false; + var $connection = false; + function RowCount() {return 0;} + function RecordCount() {return 0;} + function PO_RecordCount(){return 0;} + function Close(){return true;} + function FetchRow() {return false;} + function FieldCount(){ return 0;} + } + + //============================================================================================== + // DATE AND TIME FUNCTIONS + //============================================================================================== + include_once(ADODB_DIR.'/adodb-time.inc.php'); + + //============================================================================================== + // CLASS ADORecordSet + //============================================================================================== + + + /** + * RecordSet class that represents the dataset returned by the database. + * To keep memory overhead low, this class holds only the current row in memory. + * No prefetching of data is done, so the RecordCount() can return -1 ( which + * means recordcount not known). + */ + class ADORecordSet { + /* + * public variables + */ + var $dataProvider = "native"; + var $fields = false; /// holds the current row data + var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob + /// in other words, we use a text area for editting. + var $canSeek = false; /// indicates that seek is supported + var $sql; /// sql text + var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object. + + var $emptyTimeStamp = ' '; /// what to display when $time==0 + var $emptyDate = ' '; /// what to display when $time==0 + var $debug = false; + var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets + + var $bind = false; /// used by Fields() to hold array - should be private? + var $fetchMode; /// default fetch mode + var $connection = false; /// the parent connection + /* + * private variables + */ + var $_numOfRows = -1; /** number of rows, or -1 */ + var $_numOfFields = -1; /** number of fields in recordset */ + var $_queryID = -1; /** This variable keeps the result link identifier. */ + var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */ + var $_closed = false; /** has recordset been closed */ + var $_inited = false; /** Init() should only be called once */ + var $_obj; /** Used by FetchObj */ + var $_names; /** Used by FetchObj */ + + var $_currentPage = -1; /** Added by Iv�n Oliva to implement recordset pagination */ + var $_atFirstPage = false; /** Added by Iv�n Oliva to implement recordset pagination */ + var $_atLastPage = false; /** Added by Iv�n Oliva to implement recordset pagination */ + var $_lastPageNo = -1; + var $_maxRecordCount = 0; + var $dateHasTime = false; + + /** + * Constructor + * + * @param queryID this is the queryID returned by ADOConnection->_query() + * + */ + function ADORecordSet($queryID) + { + $this->_queryID = $queryID; + } + + + + function Init() + { + if ($this->_inited) return; + $this->_inited = true; + if ($this->_queryID) @$this->_initrs(); + else { + $this->_numOfRows = 0; + $this->_numOfFields = 0; + } + + if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) { + + $this->_currentRow = 0; + if ($this->EOF = ($this->_fetch() === false)) { + $this->_numOfRows = 0; // _numOfRows could be -1 + } + } else { + $this->EOF = true; + } + } + + + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the FIRST column. + * + * @param name name of SELECT tag + * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox. + * @param [blank1stItem] true to leave the 1st item in list empty + * @param [multiple] true for listbox, false for popup + * @param [size] #rows to show for listbox. not used by popup + * @param [selectAttr] additional attributes to defined for SELECT tag. + * useful for holding javascript onChange='...' handlers. + & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with + * column 0 (1st col) if this is true. This is not documented. + * + * @return HTML + * + * changes by glen.davies@cce.ac.nz to support multiple hilited items + */ + function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) + { + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,$compareFields0); + } + + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the SECOND column. + * + */ + function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') + { + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,false); + } + + + /** + * return recordset as a 2-dimensional array. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetArray($nRows = -1) + { + global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows); + + $results = array(); + $cnt = 0; + while (!$this->EOF && $nRows != $cnt) { + $results[] = $this->fields; + $this->MoveNext(); + $cnt++; + } + return $results; + } + + /* + * Some databases allow multiple recordsets to be returned. This function + * will return true if there is a next recordset, or false if no more. + */ + function NextRecordSet() + { + return false; + } + + /** + * return recordset as a 2-dimensional array. + * Helper function for ADOConnection->SelectLimit() + * + * @param offset is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to return + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetArrayLimit($nrows,$offset=-1) + { + if ($offset <= 0) { + return $this->GetArray($nrows); + } + + $this->Move($offset); + + $results = array(); + $cnt = 0; + while (!$this->EOF && $nrows != $cnt) { + $results[$cnt++] = $this->fields; + $this->MoveNext(); + } + + return $results; + } + + + /** + * Synonym for GetArray() for compatibility with ADO. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function &GetRows($nRows = -1) + { + return $this->GetArray($nRows); + } + + /** + * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. + * The first column is treated as the key and is not included in the array. + * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless + * $force_array == true. + * + * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional + * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, + * read the source. + * + * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and + * instead of returning array[col0] => array(remaining cols), return array[col0] => col1 + * + * @return an associative array indexed by the first column of the array, + * or false if the data has less than 2 cols. + */ + function &GetAssoc($force_array = false, $first2cols = false) { + $cols = $this->_numOfFields; + if ($cols < 2) { + return false; + } + $numIndex = isset($this->fields[0]); + $results = array(); + + if (!$first2cols && ($cols > 2 || $force_array)) { + if ($numIndex) { + while (!$this->EOF) { + $results[trim($this->fields[0])] = array_slice($this->fields, 1); + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + $results[trim(reset($this->fields))] = array_slice($this->fields, 1); + $this->MoveNext(); + } + } + } else { + // return scalar values + if ($numIndex) { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $results[trim(($this->fields[0]))] = $this->fields[1]; + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $v1 = trim(reset($this->fields)); + $v2 = ''.next($this->fields); + $results[$v1] = $v2; + $this->MoveNext(); + } + } + } + return $results; + } + + + /** + * + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() + * + * @return a timestamp formated as user desires + */ + function UserTimeStamp($v,$fmt='Y-m-d H:i:s') + { + $tt = $this->UnixTimeStamp($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + if ($tt == 0) return $this->emptyTimeStamp; + return adodb_date($fmt,$tt); + } + + + /** + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ + function UserDate($v,$fmt='Y-m-d') + { + $tt = $this->UnixDate($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } + return adodb_date($fmt,$tt); + + } + + + /** + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + + if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", + ($v), $rr)) return false; + + if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; + // h-m-s-MM-DD-YY + return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + } + + + /** + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($v), $rr)) return false; + if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; + + // h-m-s-MM-DD-YY + if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); + } + + + /** + * PEAR DB Compat - do not use internally + */ + function Free() + { + return $this->Close(); + } + + + /** + * PEAR DB compat, number of rows + */ + function NumRows() + { + return $this->_numOfRows; + } + + + /** + * PEAR DB compat, number of cols + */ + function NumCols() + { + return $this->_numOfFields; + } + + /** + * Fetch a row, returning false if no more rows. + * This is PEAR DB compat mode. + * + * @return false or array containing the current record + */ + function FetchRow() + { + if ($this->EOF) return false; + $arr = $this->fields; + $this->_currentRow++; + if (!$this->_fetch()) $this->EOF = true; + return $arr; + } + + + /** + * Fetch a row, returning PEAR_Error if no more rows. + * This is PEAR DB compat mode. + * + * @return DB_OK or error object + */ + function FetchInto(&$arr) + { + if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false; + $arr = $this->fields; + $this->MoveNext(); + return 1; // DB_OK + } + + + /** + * Move to the first row in the recordset. Many databases do NOT support this. + * + * @return true or false + */ + function MoveFirst() + { + if ($this->_currentRow == 0) return true; + return $this->Move(0); + } + + + /** + * Move to the last row in the recordset. + * + * @return true or false + */ + function MoveLast() + { + if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1); + if ($this->EOF) return false; + while (!$this->EOF) { + $f = $this->fields; + $this->MoveNext(); + } + $this->fields = $f; + $this->EOF = false; + return true; + } + + + /** + * Move to next record in the recordset. + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function MoveNext() + { + if (!$this->EOF) { + $this->_currentRow++; + if ($this->_fetch()) return true; + } + $this->EOF = true; + /* -- tested error handling when scrolling cursor -- seems useless. + $conn = $this->connection; + if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { + $fn = $conn->raiseErrorFn; + $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); + } + */ + return false; + } + + /** + * Random access to a specific row in the recordset. Some databases do not support + * access to previous rows in the databases (no scrolling backwards). + * + * @param rowNumber is the row to move to (0-based) + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function Move($rowNumber = 0) + { + $this->EOF = false; + if ($rowNumber == $this->_currentRow) return true; + if ($rowNumber >= $this->_numOfRows) + if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2; + + if ($this->canSeek) { + + if ($this->_seek($rowNumber)) { + $this->_currentRow = $rowNumber; + if ($this->_fetch()) { + return true; + } + } else { + $this->EOF = true; + return false; + } + } else { + if ($rowNumber < $this->_currentRow) return false; + global $ADODB_EXTENSION; + if ($ADODB_EXTENSION) { + while (!$this->EOF && $this->_currentRow < $rowNumber) { + adodb_movenext($this); + } + } else { + + while (! $this->EOF && $this->_currentRow < $rowNumber) { + $this->_currentRow++; + + if (!$this->_fetch()) $this->EOF = true; + } + } + return !($this->EOF); + } + + $this->fields = false; + $this->EOF = true; + return false; + } + + + /** + * Get the value of a field in the current row by column name. + * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. + * + * @param colname is the field to access + * + * @return the value of $colname column + */ + function Fields($colname) + { + return $this->fields[$colname]; + } + + function GetAssocKeys($upper=true) + { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + if ($upper === 2) $this->bind[$o->name] = $i; + else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; + } + } + + /** + * Use associative array to get fields array for databases that do not support + * associative arrays. Submitted by Paolo S. Asioli paolo.asioli@libero.it + * + * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC + * before you execute your SQL statement, and access $rs->fields['col'] directly. + * + * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField + */ + function GetRowAssoc($upper=1) + { + + if (!$this->bind) { + $this->GetAssocKeys($upper); + } + + $record = array(); + foreach($this->bind as $k => $v) { + $record[$k] = $this->fields[$v]; + } + + return $record; + } + + + /** + * Clean up recordset + * + * @return true or false + */ + function Close() + { + // free connection object - this seems to globally free the object + // and not merely the reference, so don't do this... + // $this->connection = false; + if (!$this->_closed) { + $this->_closed = true; + return $this->_close(); + } else + return true; + } + + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RecordCount() {return $this->_numOfRows;} + + + /* + * If we are using PageExecute(), this will return the maximum possible rows + * that can be returned when paging a recordset. + */ + function MaxRecordCount() + { + return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); + } + + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RowCount() {return $this->_numOfRows;} + + + /** + * Portable RecordCount. Pablo Roca + * + * @return the number of records from a previous SELECT. All databases support this. + * + * But aware possible problems in multiuser environments. For better speed the table + * must be indexed by the condition. Heavy test this before deploying. + */ + function PO_RecordCount($table="", $condition="") { + + $lnumrows = $this->_numOfRows; + // the database doesn't support native recordcount, so we do a workaround + if ($lnumrows == -1 && $this->connection) { + IF ($table) { + if ($condition) $condition = " WHERE " . $condition; + $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); + if ($resultrows) $lnumrows = reset($resultrows->fields); + } + } + return $lnumrows; + } + + /** + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function CurrentRow() {return $this->_currentRow;} + + /** + * synonym for CurrentRow -- for ADO compat + * + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function AbsolutePosition() {return $this->_currentRow;} + + /** + * @return the number of columns in the recordset. Some databases will set this to 0 + * if no records are returned, others will return the number of columns in the query. + */ + function FieldCount() {return $this->_numOfFields;} + + + /** + * Get the ADOFieldObject of a specific column. + * + * @param fieldoffset is the column position to access(0-based). + * + * @return the ADOFieldObject for that column, or false. + */ + function &FetchField($fieldoffset) + { + // must be defined by child class + } + + /** + * Get the ADOFieldObjects of all columns in an array. + * + */ + function FieldTypesArray() + { + $arr = array(); + for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) + $arr[] = $this->FetchField($i); + return $arr; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default case is lowercase field names. + * + * @return the object with the properties set to the fields of the current row + */ + function &FetchObj() + { + return FetchObject(false); + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default case is uppercase. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row + */ + function &FetchObject($isupper=true) + { + if (empty($this->_obj)) { + $this->_obj = new ADOFetchObj(); + $this->_names = array(); + for ($i=0; $i <$this->_numOfFields; $i++) { + $f = $this->FetchField($i); + $this->_names[] = $f->name; + } + } + $i = 0; + $o = &$this->_obj; + for ($i=0; $i <$this->_numOfFields; $i++) { + $name = $this->_names[$i]; + if ($isupper) $n = strtoupper($name); + else $n = $name; + + $o->$n = $this->Fields($name); + } + return $o; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default is lower-case field names. + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function &FetchNextObj() + { + return $this->FetchNextObject(false); + } + + + /** + * Return the fields array of the current row as an object for convenience. + * The default is upper case field names. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function &FetchNextObject($isupper=true) + { + $o = false; + if ($this->_numOfRows != 0 && !$this->EOF) { + $o = $this->FetchObject($isupper); + $this->_currentRow++; + if ($this->_fetch()) return $o; + } + $this->EOF = true; + return $o; + } + + /** + * Get the metatype of the column. This is used for formatting. This is because + * many databases use different names for the same type, so we transform the original + * type to our standardised version which uses 1 character codes: + * + * @param t is the type passed in. Normally is ADOFieldObject->type. + * @param len is the maximum length of that field. This is because we treat character + * fields bigger than a certain size as a 'B' (blob). + * @param fieldobj is the field object returned by the database driver. Can hold + * additional info (eg. primary_key for mysql). + * + * @return the general type of the data: + * C for character < 200 chars + * X for teXt (>= 200 chars) + * B for Binary + * N for numeric floating point + * D for date + * T for timestamp + * L for logical/Boolean + * I for integer + * R for autoincrement counter/integer + * + * + */ + function MetaType($t,$len=-1,$fieldobj=false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + // changed in 2.32 to hashing instead of switch stmt for speed... + static $typeMap = array( + 'VARCHAR' => 'C', + 'VARCHAR2' => 'C', + 'CHAR' => 'C', + 'C' => 'C', + 'STRING' => 'C', + 'NCHAR' => 'C', + 'NVARCHAR' => 'C', + 'VARYING' => 'C', + 'BPCHAR' => 'C', + 'CHARACTER' => 'C', + 'INTERVAL' => 'C', # Postgres + ## + 'LONGCHAR' => 'X', + 'TEXT' => 'X', + 'NTEXT' => 'X', + 'M' => 'X', + 'X' => 'X', + 'CLOB' => 'X', + 'NCLOB' => 'X', + 'LVARCHAR' => 'X', + ## + 'BLOB' => 'B', + 'IMAGE' => 'B', + 'BINARY' => 'B', + 'VARBINARY' => 'B', + 'LONGBINARY' => 'B', + 'B' => 'B', + ## + 'YEAR' => 'D', // mysql + 'DATE' => 'D', + 'D' => 'D', + ## + 'TIME' => 'T', + 'TIMESTAMP' => 'T', + 'DATETIME' => 'T', + 'TIMESTAMPTZ' => 'T', + 'T' => 'T', + ## + 'BOOLEAN' => 'L', + 'BIT' => 'L', + 'L' => 'L', + ## + 'COUNTER' => 'R', + 'R' => 'R', + 'SERIAL' => 'R', // ifx + 'INT IDENTITY' => 'R', + ## + 'INT' => 'I', + 'INTEGER' => 'I', + 'SHORT' => 'I', + 'TINYINT' => 'I', + 'SMALLINT' => 'I', + 'I' => 'I', + ## + 'LONG' => 'N', // interbase is numeric, oci8 is blob + 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers + 'DECIMAL' => 'N', + 'DEC' => 'N', + 'REAL' => 'N', + 'DOUBLE' => 'N', + 'DOUBLE PRECISION' => 'N', + 'SMALLFLOAT' => 'N', + 'FLOAT' => 'N', + 'NUMBER' => 'N', + 'NUM' => 'N', + 'NUMERIC' => 'N', + 'MONEY' => 'N', + + ## informix 9.2 + 'SQLINT' => 'I', + 'SQLSERIAL' => 'I', + 'SQLSMINT' => 'I', + 'SQLSMFLOAT' => 'N', + 'SQLFLOAT' => 'N', + 'SQLMONEY' => 'N', + 'SQLDECIMAL' => 'N', + 'SQLDATE' => 'D', + 'SQLVCHAR' => 'C', + 'SQLCHAR' => 'C', + 'SQLDTIME' => 'T', + 'SQLINTERVAL' => 'N', + 'SQLBYTES' => 'B', + 'SQLTEXT' => 'X' + ); + + $tmap = false; + $t = strtoupper($t); + $tmap = @$typeMap[$t]; + switch ($tmap) { + case 'C': + + // is the char field is too long, return as text field... + if (!empty($this->blobSize)) { + if ($len > $this->blobSize) return 'X'; + } else if ($len > 250) { + return 'X'; + } + return 'C'; + + case 'I': + if (!empty($fieldobj->primary_key)) return 'R'; + return 'I'; + + case false: + return 'N'; + + case 'B': + if (isset($fieldobj->binary)) + return ($fieldobj->binary) ? 'B' : 'X'; + return 'B'; + + case 'D': + if (!empty($this->dateHasTime)) return 'T'; + return 'D'; + + default: + if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; + return $tmap; + } + } + + function _close() {} + + /** + * set/returns the current recordset page when paginating + */ + function AbsolutePage($page=-1) + { + if ($page != -1) $this->_currentPage = $page; + return $this->_currentPage; + } + + /** + * set/returns the status of the atFirstPage flag when paginating + */ + function AtFirstPage($status=false) + { + if ($status != false) $this->_atFirstPage = $status; + return $this->_atFirstPage; + } + + function LastPageNo($page = false) + { + if ($page != false) $this->_lastPageNo = $page; + return $this->_lastPageNo; + } + + /** + * set/returns the status of the atLastPage flag when paginating + */ + function AtLastPage($status=false) + { + if ($status != false) $this->_atLastPage = $status; + return $this->_atLastPage; + } +} // end class ADORecordSet + + //============================================================================================== + // CLASS ADORecordSet_array + //============================================================================================== + + /** + * This class encapsulates the concept of a recordset created in memory + * as an array. This is useful for the creation of cached recordsets. + * + * Note that the constructor is different from the standard ADORecordSet + */ + + class ADORecordSet_array extends ADORecordSet + { + var $databaseType = 'array'; + + var $_array; // holds the 2-dimensional data array + var $_types; // the array of types of each column (C B I L M) + var $_colnames; // names of each column in array + var $_skiprow1; // skip 1st row because it holds column names + var $_fieldarr; // holds array of field objects + var $canSeek = true; + var $affectedrows = false; + var $insertid = false; + var $sql = ''; + var $compat = false; + /** + * Constructor + * + */ + function ADORecordSet_array($fakeid=1) + { + global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH; + + // fetch() on EOF does not delete $this->fields + $this->compat = !empty($ADODB_COMPAT_FETCH); + $this->ADORecordSet($fakeid); // fake queryID + $this->fetchMode = $ADODB_FETCH_MODE; + } + + + /** + * Setup the Array. Later we will have XML-Data and CSV handlers + * + * @param array is a 2-dimensional array holding the data. + * The first row should hold the column names + * unless paramter $colnames is used. + * @param typearr holds an array of types. These are the same types + * used in MetaTypes (C,B,L,I,N). + * @param [colnames] array of column names. If set, then the first row of + * $array should not hold the column names. + */ + function InitArray($array,$typearr,$colnames=false) + { + $this->_array = $array; + $this->_types = $typearr; + if ($colnames) { + $this->_skiprow1 = false; + $this->_colnames = $colnames; + } else $this->_colnames = $array[0]; + + $this->Init(); + } + /** + * Setup the Array and datatype file objects + * + * @param array is a 2-dimensional array holding the data. + * The first row should hold the column names + * unless paramter $colnames is used. + * @param fieldarr holds an array of ADOFieldObject's. + */ + function InitArrayFields($array,$fieldarr) + { + $this->_array = $array; + $this->_skiprow1= false; + if ($fieldarr) { + $this->_fieldobjects = $fieldarr; + } + $this->Init(); + } + + function &GetArray($nRows=-1) + { + if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) { + return $this->_array; + } else { + return ADORecordSet::GetArray($nRows); + } + } + + function _initrs() + { + $this->_numOfRows = sizeof($this->_array); + if ($this->_skiprow1) $this->_numOfRows -= 1; + + $this->_numOfFields =(isset($this->_fieldobjects)) ? + sizeof($this->_fieldobjects):sizeof($this->_types); + } + + /* Use associative array to get fields array */ + function Fields($colname) + { + if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname]; + + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function &FetchField($fieldOffset = -1) + { + if (isset($this->_fieldobjects)) { + return $this->_fieldobjects[$fieldOffset]; + } + $o = new ADOFieldObject(); + $o->name = $this->_colnames[$fieldOffset]; + $o->type = $this->_types[$fieldOffset]; + $o->max_length = -1; // length not known + + return $o; + } + + function _seek($row) + { + if (sizeof($this->_array) && $row < $this->_numOfRows) { + $this->fields = $this->_array[$row]; + return true; + } + return false; + } + + function MoveNext() + { + if (!$this->EOF) { + $this->_currentRow++; + + $pos = $this->_currentRow; + if ($this->_skiprow1) $pos += 1; + + if ($this->_numOfRows <= $pos) { + if (!$this->compat) $this->fields = false; + } else { + $this->fields = $this->_array[$pos]; + return true; + } + $this->EOF = true; + } + + return false; + } + + function _fetch() + { + $pos = $this->_currentRow; + if ($this->_skiprow1) $pos += 1; + + if ($this->_numOfRows <= $pos) { + if (!$this->compat) $this->fields = false; + return false; + } + + $this->fields = $this->_array[$pos]; + return true; + } + + function _close() + { + return true; + } + + } // ADORecordSet_array + + //============================================================================================== + // HELPER FUNCTIONS + //============================================================================================== + + /** + * Synonym for ADOLoadCode. + * + * @deprecated + */ + function ADOLoadDB($dbType) + { + return ADOLoadCode($dbType); + } + + /** + * Load the code for a specific database driver + */ + function ADOLoadCode($dbType) + { + GLOBAL $ADODB_Database; + + if (!$dbType) return false; + $ADODB_Database = strtolower($dbType); + switch ($ADODB_Database) { + case 'maxsql': $ADODB_Database = 'mysqlt'; break; + case 'postgres': + case 'pgsql': $ADODB_Database = 'postgres7'; break; + } + // Karsten Kraus + return @include_once(ADODB_DIR."/drivers/adodb-".$ADODB_Database.".inc.php"); + } + + /** + * synonym for ADONewConnection for people like me who cannot remember the correct name + */ + function &NewADOConnection($db='') + { + return ADONewConnection($db); + } + + /** + * Instantiate a new Connection class for a specific database driver. + * + * @param [db] is the database Connection object to create. If undefined, + * use the last database driver that was loaded by ADOLoadCode(). + * + * @return the freshly created instance of the Connection class. + */ + function &ADONewConnection($db='') + { + global $ADODB_Database; + + $rez = true; + if ($db) { + if ($ADODB_Database != $db) ADOLoadCode($db); + } else { + if (!empty($ADODB_Database)) { + ADOLoadCode($ADODB_Database); + } else { + $rez = false; + } + } + + $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; + if (!$rez) { + if ($errorfn) { + // raise an error + $errorfn('ADONewConnection', 'ADONewConnection', -998, + "could not load the database driver for '$db", + $dbtype); + } else + ADOConnection::outp( "

ADONewConnection: Unable to load database driver '$db'

",false); + + return false; + } + + $cls = 'ADODB_'.$ADODB_Database; + $obj = new $cls(); + if ($errorfn) $obj->raiseErrorFn = $errorfn; + + return $obj; + } + + function &NewDataDictionary(&$conn) + { + $provider = $conn->dataProvider; + $drivername = $conn->databaseType; + if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado') + $drivername = $conn->dataProvider; + else { + if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5); + else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4); + else + switch($drivername) { + case 'oracle': $drivername = 'oci8';break; + case 'sybase': $drivername = 'mssql';break; + case 'access': + case 'db2': + break; + default: + $drivername = 'generic'; + break; + } + } + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + include_once(ADODB_DIR.'/adodb-datadict.inc.php'); + $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; + + if (!file_exists($path)) { + ADOConnection::outp("Database driver '$path' not available"); + return false; + } + include_once($path); + $class = "ADODB2_$drivername"; + $dict =& new $class(); + $dict->dataProvider = $conn->dataProvider; + $dict->connection = &$conn; + $dict->upperName = strtoupper($drivername); + if (is_resource($conn->_connectionID)) + $dict->serverInfo = $conn->ServerInfo(); + + return $dict; + } + + + /** + * Save a file $filename and its $contents (normally for caching) with file locking + */ + function adodb_write_file($filename, $contents,$debug=false) + { + # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows + # So to simulate locking, we assume that rename is an atomic operation. + # First we delete $filename, then we create a $tempfile write to it and + # rename to the desired $filename. If the rename works, then we successfully + # modified the file exclusively. + # What a stupid need - having to simulate locking. + # Risks: + # 1. $tempfile name is not unique -- very very low + # 2. unlink($filename) fails -- ok, rename will fail + # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs + # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated + if (strpos(strtoupper(PHP_OS),'WIN') !== false) { + // skip the decimal place + $mtime = substr(str_replace(' ','_',microtime()),2); + // unlink will let some latencies develop, so uniqid() is more random + @unlink($filename); + // getmypid() actually returns 0 on Win98 - never mind! + $tmpname = $filename.uniqid($mtime).getmypid(); + if (!($fd = fopen($tmpname,'a'))) return false; + $ok = ftruncate($fd,0); + if (!fwrite($fd,$contents)) $ok = false; + fclose($fd); + chmod($tmpname,0644); + if (!@rename($tmpname,$filename)) { + unlink($tmpname); + $ok = false; + } + if (!$ok) { + if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed')); + } + return $ok; + } + if (!($fd = fopen($filename, 'a'))) return false; + if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) { + $ok = fwrite( $fd, $contents ); + fclose($fd); + chmod($filename,0644); + }else { + fclose($fd); + if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename
\n"); + $ok = false; + } + + return $ok; + } + + + function adodb_backtrace($print=true) + { + $s = ''; + if (PHPVERSION() >= 4.3) { + + $MAXSTRLEN = 64; + + $s = '
';
+			$traceArr = debug_backtrace();
+			array_shift($traceArr);
+			$tabs = sizeof($traceArr)-1;
+			
+			foreach ($traceArr as $arr) {
+				$args = array();
+				for ($i=0; $i < $tabs; $i++) $s .= '   ';
+				$tabs -= 1;
+				$s .= '';
+				if (isset($arr['class'])) $s .= $arr['class'].'.';
+				if (isset($arr['args']))
+				 foreach($arr['args'] as $v) {
+					if (is_null($v)) $args[] = 'null';
+					else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
+					else if (is_object($v)) $args[] = 'Object:'.get_class($v);
+					else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
+					else { 
+						$v = (string) @$v;
+						$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
+						if (strlen($v) > $MAXSTRLEN) $str .= '...';
+						$args[] = $str;
+					}
+				}
+				$s .= $arr['function'].'('.implode(', ',$args).')';
+				$s .= @sprintf(" # line %4d, file: %s",
+					$arr['line'],$arr['file'],$arr['file']);
+				$s .= "\n";
+			}	
+			$s .= '
'; + if ($print) print $s; + } + return $s; + } + +} // defined ?> \ No newline at end of file Index: trunk/kernel/include/searchitems.php =================================================================== diff -u -N -r604 -r642 --- trunk/kernel/include/searchitems.php (.../searchitems.php) (revision 604) +++ trunk/kernel/include/searchitems.php (.../searchitems.php) (revision 642) @@ -1,739 +1,739 @@ - : is required - - : cannot exist in the searched field - "word word" : contents between the quotes are treated as a single entity - +/-"word word" is supported - ignore words are not case sensitive -*/ -class clsSearchLog extends clsItemDB -{ - function clsSearchLog($id=NULL) - { - $this->clsItemDB(); - $this->tablename = GetTablePrefix()."SearchLog"; - $this->id_field = "SearchLogId"; - $this->NoResourceId = 1; - if($id) - $this->LoadFromDatabase($id); - } - - function LoadFromDatabase($Id) - { - global $Errors; - - 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 ".$this->IdField()." = '%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; - - $this->SetFromArray($data); - $this->Clean(); - return true; - } -} - -class clsSearchLogList extends clsItemCollection -{ - var $Page; - var $PerPageVar; - - function clsSearchLogList() - { - $this->clsItemCollection(); - $this->SourceTable = GetTablePrefix()."SearchLog"; - $this->classname = "clsSearchLog"; - $this->Page=1; - $this->PerPageVar = "Perpage_SearchLog"; - $this->AdminSearchFields = array("Keyword"); - } - - function UpdateKeyword($keyword,$SearchType) - { - $sql = "UPDATE ".$this->SourceTable." SET Indices = Indices+1 WHERE Keyword='$keyword' AND SearchType=$SearchType"; - //echo $sql."
\n"; - $this->adodbConnection->Execute($sql); - if($this->adodbConnection->Affected_Rows()==0) - { - //echo "Creating Keyword record..
\n"; - $k = new clsSearchLog(); - $k->Set("Keyword",$keyword); - $k->Set("Indices",1); - $k->Set("SearchType",$SearchType); - $k->Create(); - } - } - - function AddKeywords($Keywords) - { - if(is_array($Keywords)) - { - for($i=0;$iUpdateKeyword($Keywords[$i]); - } - } - else - $this->UpdateKeyword($Keywords); - } -} - -class clsEmailLog extends clsItemDB -{ - function clsEmailLog($id=NULL) - { - $this->clsItemDB(); - $this->tablename = GetTablePrefix()."SearchLog"; - $this->id_field = "SearchLogId"; - $this->NoResourceId = 1; - if($id) - $this->LoadFromDatabase($id); - } - - function LoadFromDatabase($Id) - { - global $Errors; - - 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 ".$this->IdField()." = '%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; - - $this->SetFromArray($data); - $this->Clean(); - return true; - } -} - -class clsEmailLogList extends clsItemCollection -{ - var $Page; - var $PerPageVar; - - function clsEmailLogList() - { - $this->clsItemCollection(); - $this->SourceTable = GetTablePrefix()."SearchLog"; - $this->classname = "clsEmailLog"; - $this->Page=1; - $this->PerPageVar = "Perpage_EmailsL"; - $this->AdminSearchFields = array("event", "fromuser", "addressto", "subject"); - } - - function UpdateKeyword($keyword,$SearchType) - { - $sql = "UPDATE ".$this->SourceTable." SET Indices = Indices+1 WHERE Keyword='$keyword' AND SearchType=$SearchType"; - //echo $sql."
\n"; - $this->adodbConnection->Execute($sql); - if($this->adodbConnection->Affected_Rows()==0) - { - //echo "Creating Keyword record..
\n"; - $k = new clsSearchLog(); - $k->Set("Keyword",$keyword); - $k->Set("Indices",1); - $k->Set("SearchType",$SearchType); - $k->Create(); - } - } - - function AddKeywords($Keywords) - { - if(is_array($Keywords)) - { - for($i=0;$iUpdateKeyword($Keywords[$i]); - } - } - else - $this->UpdateKeyword($Keywords); - } -} - -class clsSearchResults extends clsItemCollection -{ - var $ResultTable; - var $FieldList; - var $FieldWeight; - var $WhereClauses; - var $SourceTable; - var $Relationships; - var $Ignored_Words; - var $CatClause; - var $Keywords; - var $Phrase = ""; - var $SearchType; - var $RequiredRelevance; - var $PctRelevance; - var $PctPop; - var $PctRating; - - function clsSearchResults($SearchSource,$DataClass) - { - global $objConfig; - - $this->clsItemCollection(); - $this->SourceTable = $SearchSource; - $this->SetResultTable($SearchSource,$DataClass); - $this->FieldList = array(); - $this->Relationships = array(); - $this->Ignored_Words = array(); - $this->WhereClauses = array(); - $this->FieldWeight = array(); - $this->Keywords = GetKeywords(""); - $this->SearchType = 0; //simple - $this->RequiredRelevance=0; - $this->PctRelevance = $objConfig->Get("SearchRel_DefaultKeyword")/100; - $this->PctPop = $objConfig->Get("SearchRel_DefaultPop")/100; - $this->PctRating = $objConfig->Get("SearchRel_DefaultRating")/100; - } - - function SetResultTable($SearchSource,$DataClass) - { - global $objSession; - - $this->ResultTable = $objSession->GetSearchTable(); - $this->classname= $DataClass; - } - - function LoadSearchResults($Start=0,$PerPage=NULL) - { - if($PerPage) - { - $limit = "LIMIT $Start,$PerPage"; - } - $sql = "SELECT * FROM ".$this->ResultTable." ".$limit; - - $this->Clear(); - $rs = $this->adodbConnection->Execute($sql); - return $this->Query_Item($sql); - } - - function SetCategoryClause($whereclause) - { - $this->CatClause=$whereclause; - } - - function AddRelationship($JoinTable,$JoinExpression=NULL) - { - - $this->Relationships[$JoinTable]=$JoinExpression; - } - - function SetKeywords($keywords) - { - $this->Phrase=$keywords; - $this->keywords = GetKeywords($keywords); - } - - function AddSimpleCustomFields() - { - $sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND SimpleSearch=1 AND CustomFieldId>0"; - //echo $sql; - foreach($this->Relationships as $Table=>$clause) - { - if(strlen($Table)>0 && $Table != "Category") - $sql .= " OR TableName='".$Table."'"; - } - $ctable = GetTablePrefix()."CustomMetaData"; - $rs = $this->adodbConnection->Execute($sql); - $CustomJoined = FALSE; - while($rs && !$rs->EOF) - { - $x = $rs->fields["CustomFieldId"]; - $t = $ctable." as c".$x; - $join = "(c$x.ResourceId=".GetTablePrefix().$this->SourceTable.".ResourceId AND c$x.CustomFieldId=".$rs->fields["CustomFieldId"].")"; - $this->AddRelationship($t,$join); - $f = "c".$x.".Value "; - $this->FieldList[] = $f; - $this->FieldWeight[$f] = $rs->fields["Priority"]; - $rs->MoveNext(); - } - } - - function AddSimpleFields() - { - $sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND SimpleSearch=1 AND CustomFieldId=0"; - //echo $sql; - foreach($this->Relationships as $Table=>$clause) - { - if(strlen($Table)>0 && $Table != "Category") - $sql .= " OR TableName='".$Table."'"; - } - $rs = $this->adodbConnection->Execute($sql); - - while($rs && !$rs->EOF) - { - $f = GetTablePrefix().$rs->fields["TableName"].".".$rs->fields["FieldName"]; - $this->FieldList[] = $f; - $this->FieldWeight[$f] = $rs->fields["Priority"]; - $rs->MoveNext(); - } - $this->AddSimpleCustomFields(); - } - - function AddSearchWhereClause($FieldName) - { - $req_where = ""; - /* build required keywords string */ - - if(count($this->keywords["required"])>0) - { - $required = $this->keywords["required"]; - for($i=0;$i0) - { - if($i>0) - { - $or =" AND "; - } - else - $or = ""; - $w .= $or." ".$FieldName." LIKE '%".$required[$i]."%'"; - } - } - if(strlen($w)>0) - { - $req_where = "(". $w.")"; - } - else - $req_where = ""; - } - $w = ""; - $not_where=""; - if(count($this->keywords["notallowed"])>0) - { - $words = $this->keywords["notallowed"]; - for($i=0;$i0) - { - if($i>0) - { - $or =" AND "; - } - else - $or = ""; - $w .= $or." ".$FieldName." NOT LIKE '%".$words[$i]."%'"; - } - } - if(strlen($w)>0) - { - $not_where = "(".$w.")"; - } - else - $not_where = ""; - } - - $w=""; - $normal = $this->keywords["normal"]; - if(count($normal)>0) - { - for($i=0;$i0) - { - if($i>0) - { - $or =" OR "; - } - else - $or = ""; - $w .= "$or $FieldName LIKE '%".$normal[$i]."%'"; - } - } - if(count($required)>0) - $w .= " OR "; - for($i=0;$i0) - { - if($i>0) - { - $or = " OR "; - } - else - $or=""; - $w .= "$or $FieldName LIKE '%".$required[$i]."%'"; - } - } - if(strlen($w)>0) - { - $where = "(".$w.")"; - } - else - $where = ""; - } - - $complete= BuildWhereClause($where,$req_where,$not_where); - $this->WhereClauses[$FieldName]="(".$complete.")"; - $this->Ignored_Words=$this->keywords["ignored"]; - } - - function PerformSearch($ItemType,$OrderBy=NULL,$InitTable=FALSE, $idlist=NULL) - { - static $SelectSQL, $OldItemType; - global $objSession, $objItemTypes; - //echo "perfirming Simple Search
"; - //echo "Old Item Type: $OldItemType New: $ItemType
\n"; - if($ItemType != $OldItemType) - $SelectSQL = ""; - $OldItemType = $ItemType; - - $ctype = $objItemTypes->GetItem($ItemType); - $idField = $ctype->Get("SourceTable")."Id"; - $this->SourceTable = GetTablePrefix().$ctype->Get("SourceTable"); - $result=0; - $PopField = $ctype->Get("PopField"); - $RateField = $ctype->Get("RateField"); - - //print_pre($this->keywords); - - if(!strlen($SelectSQL)) - { - $typestr = str_pad($ItemType,2,"0",STR_PAD_LEFT); - $SelectSQL = "SELECT "; - $ifs = array(); - $weightsum = 0; - foreach($this->FieldWeight as $w) - $weightsum += $w; - $wordcount = count($this->keywords["normal"])+count($this->keywords["required"]); - $single = ($wordcount == 1); - foreach($this->FieldList as $f) - { - $weight = (int)$this->FieldWeight[$f]; - $s = array(); - - if(!$single) - { - $full = trim(implode(" ",$this->keywords["normal"])); - $s[] = " (IF ($f LIKE '%$full%', ".$weightsum.", 0))"; - } - foreach($this->keywords["normal"] as $k) - { - if($k != $full || $single) - { - $temp = " (IF ($f LIKE '%$k%', ".$weight.", 0))"; - $s[] = $temp; - } - } - - foreach($this->keywords["required"] as $k) - { - if($this->RequiredRelevance>0) - $weight = $this->FieldWeight[$f] + ($this->FieldWeight[$f]*($this->RequiredRelevance/100)); - - if($k != $full || $single) - { - $s[] = " (IF ($f LIKE '%$k%', ".$weight.", 0))"; - } - } - // echo "
";print_r($s); echo "
"; - $txt = implode("+",$s); - //echo $txt."
\n"; - $ifs[] = $txt; - unset($s); - } -// echo "
";print_r($ifs); echo "
"; - - /* add relevance formula for weighting hits & popularity */ - - if($weightsum==0) - $weightsum=1; - - if(strlen($PopField)>0 && $this->PctPop>0) - { - $popcalc = " + ((($PopField + 1) / (max($PopField)+1)*".$this->PctPop."))"; - } - else - $popcalc = ""; - - if(strlen($RateField)>0 && $this->PctRating>0) - { - $ratecalc = " + ((($RateField + 1) / (max($RateField)+1)*".$this->PctRating."))"; - } - else - $ratecalc = ""; - - if($this->PctRelevance>0) - { - $relcalc = "(((".implode("+",$ifs).")/$weightsum)*".$this->PctRelevance.")"; - } - else - $relcalc = "0"; - - $SelectSQL .= $relcalc.$popcalc.$ratecalc." as Relevance, "; - - $SelectSQL .= $this->SourceTable.".".$idField." as ItemId, ".$this->SourceTable.".ResourceId as ResourceId, CONCAT($typestr) as ItemType, EditorsPick as EdPick FROM ".$this->SourceTable." "; - - foreach($this->Relationships as $JoinTable=>$OnClause) - { - $SelectSQL .= "LEFT JOIN $JoinTable ON $OnClause "; - } - $first=1; - $where=0; - - foreach($this->FieldList as $field) - { - if(strpos($field,"as")>0) - { - $fparts = explode("as",$field,2); - $f = $fparts[1]; - $this->AddSearchWhereClause($field); - } - else { - $this->AddSearchWhereClause($field); - } - } - - $SelectSQL .= " WHERE "; - $SelectSQL .= implode(" or ",$this->WhereClauses); - - if(is_array($idlist)) - { - $SelectSQL .= " AND (ResourceId IN (".implode(",",$idlist)."))"; - } - } - $SelectSQL .= "GROUP BY $idField "; - //echo $SelectSQL."

\n"; - if($InitTable) - { - $this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$this->ResultTable); - //$indexSQL = "(INDEX(Relevance), INDEX(ItemId), INDEX(ItemType), INDEX sorting (EdPick,Relevance)) "; - $full_sql = "CREATE TABLE ".$this->ResultTable." ".$indexSQL.$SelectSQL; - //echo $full_sql."
\n"; - $this->adodbConnection->Execute($full_sql); - //echo $this->adodbConnection->ErrorMsg()."
\n"; - $objSession->SetVariable("Search_Keywords",$this->Phrase); - } - else - { - $full_sql = "INSERT INTO ".$this->ResultTable." (Relevance,ItemId,ResourceId,ItemType,EdPick) ".$SelectSQL; - //echo "[".htmlspecialchars($full_sql)."]
\n"; - $this->adodbConnection->Execute($full_sql); - //echo $this->adodbConnection->ErrorMsg()."
\n"; - } - //Here we need to remove found items which was found by HTML tags matching keywords - //$this->adodbConnection->Execute("DELETE FROM ".$this->ResultTable." WHERE ItemId = 13 AND ItemType = 4"); - } - - function BuildIndexes() - { - $sql = "ALTER TABLE ".$this->ResultTable." ADD INDEX (Relevance), "; - $sql .="ADD INDEX (ItemId), "; - $sql .="ADD INDEX (ItemType), "; - $sql .=" ADD INDEX sorting (EdPick,Relevance)"; - //echo $sql; - $this->adodbConnection->Execute($sql); - } - - function Result_IdList() - { - /* returns an array contain a resource ID list */ - $sql = "SELECT DISTINCT(ResourceId) FROM ".$this->ResultTable; - $rs = $this->adodbConnection->Execute($sql); - $result = array(); - while($rs && !$rs->EOF) - { - $result[] = $rs->fields["ResourceId"]; - $rs->MoveNext(); - } - return $result; - } -} - -function count_words($string) -{ - // below line added to make contiguous spaces count as one space - if(strlen($string)) - { - $string = eregi_replace(" +", " ", $string); - return substr_count($string," ")+1; - } - else - return 0; -} - -function GetKeywords($phrase) -{ - global $KeywordIgnore; - - if(count($KeywordIgnore)==0) - GetIgnoreList(); - $keywords["normal"]= array(); - $keywords["required"]= array(); - $keywords["notallowed"] = array(); - $keywords["ignored"] = array(); - if(!strlen($phrase)) - return $keywords; - $w_array = array(); - $phrase=trim($phrase); - //if(count_words($phrase)>1) - // $keywords["normal"][] = $phrase; - $t_len = strlen($phrase); - $ce=0; - for ($i=0; $i<$t_len; $i++) - { #search for next special tag - switch ($phrase[$i]) - { - case "\"": - $exact_match_close = strpos($phrase,"\"", $i+1); - if(!$exact_match_close) - break; - $exact_word=substr($phrase, $i+1, ($exact_match_close-$i)-1); - $i=$exact_match_close; - if($exact_word) - { - if(strlen($token)==0) - $token="|"; - $w_array[$ce]=$token.addslashes($exact_word); - $token=""; - $ce++; - $exact_word=""; - } - break; - - case "+": - if(strlen($exact_word)==0) - { - $token = "+"; - } - else - $exact_word .= "+"; - break; - case "-": - if(strlen($exact_word)==0) - { - $token = "-"; - } - else - $exact_word .="-"; - break; - case " ": - case ",": - if($exact_word) - { - if(strlen($token)==0) - $token="|"; - if($token=="|") - { - if($KeywordIgnore[strtolower($exact_word)]==1) - { - $w_array[$ce]= "=".addslashes($exact_word); - $ce++; - } - else - { - $w_array[$ce]=$token.addslashes($exact_word); - $ce++; - } - } - else - { - $w_array[$ce]=$token.addslashes($exact_word); - $ce++; - } - $token=""; - $exact_word=""; - } - break; - - default: - $exact_word.=$phrase[$i]; - } - } - if($exact_word) - { - if(strlen($token)==0) - $token="|"; - if($KeywordIgnore[strtolower($exact_word)]==1 && ($token =="|" || $token=="=")) - { - $w_array[$ce]= "=".addslashes($exact_word); - $ce++; - } - else - { - $w_array[$ce]=$token.addslashes($exact_word); - $ce++; - } - } - for ($i=0;$i0 && strlen($notallowed)>0) - { - $return .= " AND "; - } - $return .= $notallowed; - if(strlen($return)>0 && strlen($normal)>0) - { - $return .= " AND "; - } - $return .= $normal; - return $return; -} - -function GetIgnoreList() -{ - global $KeywordIgnore; - - $adodbConnection = &GetADODBConnection(); - - $rs = $adodbConnection->Execute("SELECT * FROM IgnoreKeywords"); - while($rs && !$rs->EOF) - { - $KeywordIgnore[strtolower($rs->fields["keyword"])]=1; - $rs->MoveNext(); - } -// foreach($KeywordIgnore as $word=>$dummy) -// echo $word.","; -// echo "
\n"; -} - -?> + : is required + - : cannot exist in the searched field + "word word" : contents between the quotes are treated as a single entity + +/-"word word" is supported + ignore words are not case sensitive +*/ +class clsSearchLog extends clsItemDB +{ + function clsSearchLog($id=NULL) + { + $this->clsItemDB(); + $this->tablename = GetTablePrefix()."SearchLog"; + $this->id_field = "SearchLogId"; + $this->NoResourceId = 1; + if($id) + $this->LoadFromDatabase($id); + } + + function LoadFromDatabase($Id) + { + global $Errors; + + 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 ".$this->IdField()." = '%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; + + $this->SetFromArray($data); + $this->Clean(); + return true; + } +} + +class clsSearchLogList extends clsItemCollection +{ + var $Page; + var $PerPageVar; + + function clsSearchLogList() + { + $this->clsItemCollection(); + $this->SourceTable = GetTablePrefix()."SearchLog"; + $this->classname = "clsSearchLog"; + $this->Page=1; + $this->PerPageVar = "Perpage_SearchLog"; + $this->AdminSearchFields = array("Keyword"); + } + + function UpdateKeyword($keyword,$SearchType) + { + $sql = "UPDATE ".$this->SourceTable." SET Indices = Indices+1 WHERE Keyword='$keyword' AND SearchType=$SearchType"; + //echo $sql."
\n"; + $this->adodbConnection->Execute($sql); + if($this->adodbConnection->Affected_Rows()==0) + { + //echo "Creating Keyword record..
\n"; + $k = new clsSearchLog(); + $k->Set("Keyword",$keyword); + $k->Set("Indices",1); + $k->Set("SearchType",$SearchType); + $k->Create(); + } + } + + function AddKeywords($Keywords) + { + if(is_array($Keywords)) + { + for($i=0;$iUpdateKeyword($Keywords[$i]); + } + } + else + $this->UpdateKeyword($Keywords); + } +} + +class clsEmailLog extends clsItemDB +{ + function clsEmailLog($id=NULL) + { + $this->clsItemDB(); + $this->tablename = GetTablePrefix()."SearchLog"; + $this->id_field = "SearchLogId"; + $this->NoResourceId = 1; + if($id) + $this->LoadFromDatabase($id); + } + + function LoadFromDatabase($Id) + { + global $Errors; + + 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 ".$this->IdField()." = '%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; + + $this->SetFromArray($data); + $this->Clean(); + return true; + } +} + +class clsEmailLogList extends clsItemCollection +{ + var $Page; + var $PerPageVar; + + function clsEmailLogList() + { + $this->clsItemCollection(); + $this->SourceTable = GetTablePrefix()."SearchLog"; + $this->classname = "clsEmailLog"; + $this->Page=1; + $this->PerPageVar = "Perpage_EmailsL"; + $this->AdminSearchFields = array("event", "fromuser", "addressto", "subject"); + } + + function UpdateKeyword($keyword,$SearchType) + { + $sql = "UPDATE ".$this->SourceTable." SET Indices = Indices+1 WHERE Keyword='$keyword' AND SearchType=$SearchType"; + //echo $sql."
\n"; + $this->adodbConnection->Execute($sql); + if($this->adodbConnection->Affected_Rows()==0) + { + //echo "Creating Keyword record..
\n"; + $k = new clsSearchLog(); + $k->Set("Keyword",$keyword); + $k->Set("Indices",1); + $k->Set("SearchType",$SearchType); + $k->Create(); + } + } + + function AddKeywords($Keywords) + { + if(is_array($Keywords)) + { + for($i=0;$iUpdateKeyword($Keywords[$i]); + } + } + else + $this->UpdateKeyword($Keywords); + } +} + +class clsSearchResults extends clsItemCollection +{ + var $ResultTable; + var $FieldList; + var $FieldWeight; + var $WhereClauses; + var $SourceTable; + var $Relationships; + var $Ignored_Words; + var $CatClause; + var $Keywords; + var $Phrase = ""; + var $SearchType; + var $RequiredRelevance; + var $PctRelevance; + var $PctPop; + var $PctRating; + + function clsSearchResults($SearchSource,$DataClass) + { + global $objConfig; + + $this->clsItemCollection(); + $this->SourceTable = $SearchSource; + $this->SetResultTable($SearchSource,$DataClass); + $this->FieldList = array(); + $this->Relationships = array(); + $this->Ignored_Words = array(); + $this->WhereClauses = array(); + $this->FieldWeight = array(); + $this->Keywords = GetKeywords(""); + $this->SearchType = 0; //simple + $this->RequiredRelevance=0; + $this->PctRelevance = $objConfig->Get("SearchRel_DefaultKeyword")/100; + $this->PctPop = $objConfig->Get("SearchRel_DefaultPop")/100; + $this->PctRating = $objConfig->Get("SearchRel_DefaultRating")/100; + } + + function SetResultTable($SearchSource,$DataClass) + { + global $objSession; + + $this->ResultTable = $objSession->GetSearchTable(); + $this->classname= $DataClass; + } + + function LoadSearchResults($Start=0,$PerPage=NULL) + { + if($PerPage) + { + $limit = "LIMIT $Start,$PerPage"; + } + $sql = "SELECT * FROM ".$this->ResultTable." ".$limit; + + $this->Clear(); + $rs = $this->adodbConnection->Execute($sql); + return $this->Query_Item($sql); + } + + function SetCategoryClause($whereclause) + { + $this->CatClause=$whereclause; + } + + function AddRelationship($JoinTable,$JoinExpression=NULL) + { + + $this->Relationships[$JoinTable]=$JoinExpression; + } + + function SetKeywords($keywords) + { + $this->Phrase=$keywords; + $this->keywords = GetKeywords($keywords); + } + + function AddSimpleCustomFields() + { + $sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND SimpleSearch=1 AND CustomFieldId>0"; + //echo $sql; + foreach($this->Relationships as $Table=>$clause) + { + if(strlen($Table)>0 && $Table != "Category") + $sql .= " OR TableName='".$Table."'"; + } + $ctable = GetTablePrefix()."CustomMetaData"; + $rs = $this->adodbConnection->Execute($sql); + $CustomJoined = FALSE; + while($rs && !$rs->EOF) + { + $x = $rs->fields["CustomFieldId"]; + $t = $ctable." as c".$x; + $join = "(c$x.ResourceId=".GetTablePrefix().$this->SourceTable.".ResourceId AND c$x.CustomFieldId=".$rs->fields["CustomFieldId"].")"; + $this->AddRelationship($t,$join); + $f = "c".$x.".Value "; + $this->FieldList[] = $f; + $this->FieldWeight[$f] = $rs->fields["Priority"]; + $rs->MoveNext(); + } + } + + function AddSimpleFields() + { + $sql = "SELECT * FROM ".GetTablePrefix()."SearchConfig WHERE TableName='".$this->SourceTable."' AND SimpleSearch=1 AND CustomFieldId=0"; + //echo $sql; + foreach($this->Relationships as $Table=>$clause) + { + if(strlen($Table)>0 && $Table != "Category") + $sql .= " OR TableName='".$Table."'"; + } + $rs = $this->adodbConnection->Execute($sql); + + while($rs && !$rs->EOF) + { + $f = GetTablePrefix().$rs->fields["TableName"].".".$rs->fields["FieldName"]; + $this->FieldList[] = $f; + $this->FieldWeight[$f] = $rs->fields["Priority"]; + $rs->MoveNext(); + } + $this->AddSimpleCustomFields(); + } + + function AddSearchWhereClause($FieldName) + { + $req_where = ""; + /* build required keywords string */ + + if(count($this->keywords["required"])>0) + { + $required = $this->keywords["required"]; + for($i=0;$i0) + { + if($i>0) + { + $or =" AND "; + } + else + $or = ""; + $w .= $or." ".$FieldName." LIKE '%".$required[$i]."%'"; + } + } + if(strlen($w)>0) + { + $req_where = "(". $w.")"; + } + else + $req_where = ""; + } + $w = ""; + $not_where=""; + if(count($this->keywords["notallowed"])>0) + { + $words = $this->keywords["notallowed"]; + for($i=0;$i0) + { + if($i>0) + { + $or =" AND "; + } + else + $or = ""; + $w .= $or." ".$FieldName." NOT LIKE '%".$words[$i]."%'"; + } + } + if(strlen($w)>0) + { + $not_where = "(".$w.")"; + } + else + $not_where = ""; + } + + $w=""; + $normal = $this->keywords["normal"]; + if(count($normal)>0) + { + for($i=0;$i0) + { + if($i>0) + { + $or =" OR "; + } + else + $or = ""; + $w .= "$or $FieldName LIKE '%".$normal[$i]."%'"; + } + } + if(count($required)>0) + $w .= " OR "; + for($i=0;$i0) + { + if($i>0) + { + $or = " OR "; + } + else + $or=""; + $w .= "$or $FieldName LIKE '%".$required[$i]."%'"; + } + } + if(strlen($w)>0) + { + $where = "(".$w.")"; + } + else + $where = ""; + } + + $complete= BuildWhereClause($where,$req_where,$not_where); + $this->WhereClauses[$FieldName]="(".$complete.")"; + $this->Ignored_Words=$this->keywords["ignored"]; + } + + function PerformSearch($ItemType,$OrderBy=NULL,$InitTable=FALSE, $idlist=NULL) + { + static $SelectSQL, $OldItemType; + global $objSession, $objItemTypes; + //echo "perfirming Simple Search
"; + //echo "Old Item Type: $OldItemType New: $ItemType
\n"; + if($ItemType != $OldItemType) + $SelectSQL = ""; + $OldItemType = $ItemType; + + $ctype = $objItemTypes->GetItem($ItemType); + $idField = $ctype->Get("SourceTable")."Id"; + $this->SourceTable = GetTablePrefix().$ctype->Get("SourceTable"); + $result=0; + $PopField = $ctype->Get("PopField"); + $RateField = $ctype->Get("RateField"); + + //print_pre($this->keywords); + + if(!strlen($SelectSQL)) + { + $typestr = str_pad($ItemType,2,"0",STR_PAD_LEFT); + $SelectSQL = "SELECT "; + $ifs = array(); + $weightsum = 0; + foreach($this->FieldWeight as $w) + $weightsum += $w; + $wordcount = count($this->keywords["normal"])+count($this->keywords["required"]); + $single = ($wordcount == 1); + foreach($this->FieldList as $f) + { + $weight = (int)$this->FieldWeight[$f]; + $s = array(); + + if(!$single) + { + $full = trim(implode(" ",$this->keywords["normal"])); + $s[] = " (IF ($f LIKE '%$full%', ".$weightsum.", 0))"; + } + foreach($this->keywords["normal"] as $k) + { + if($k != $full || $single) + { + $temp = " (IF ($f LIKE '%$k%', ".$weight.", 0))"; + $s[] = $temp; + } + } + + foreach($this->keywords["required"] as $k) + { + if($this->RequiredRelevance>0) + $weight = $this->FieldWeight[$f] + ($this->FieldWeight[$f]*($this->RequiredRelevance/100)); + + if($k != $full || $single) + { + $s[] = " (IF ($f LIKE '%$k%', ".$weight.", 0))"; + } + } + // echo "
";print_r($s); echo "
"; + $txt = implode("+",$s); + //echo $txt."
\n"; + $ifs[] = $txt; + unset($s); + } +// echo "
";print_r($ifs); echo "
"; + + /* add relevance formula for weighting hits & popularity */ + + if($weightsum==0) + $weightsum=1; + + if(strlen($PopField)>0 && $this->PctPop>0) + { + $popcalc = " + ((($PopField + 1) / (max($PopField)+1)*".$this->PctPop."))"; + } + else + $popcalc = ""; + + if(strlen($RateField)>0 && $this->PctRating>0) + { + $ratecalc = " + ((($RateField + 1) / (max($RateField)+1)*".$this->PctRating."))"; + } + else + $ratecalc = ""; + + if($this->PctRelevance>0) + { + $relcalc = "(((".implode("+",$ifs).")/$weightsum)*".$this->PctRelevance.")"; + } + else + $relcalc = "0"; + + $SelectSQL .= $relcalc.$popcalc.$ratecalc." as Relevance, "; + + $SelectSQL .= $this->SourceTable.".".$idField." as ItemId, ".$this->SourceTable.".ResourceId as ResourceId, CONCAT($typestr) as ItemType, EditorsPick as EdPick FROM ".$this->SourceTable." "; + + foreach($this->Relationships as $JoinTable=>$OnClause) + { + $SelectSQL .= "LEFT JOIN $JoinTable ON $OnClause "; + } + $first=1; + $where=0; + + foreach($this->FieldList as $field) + { + if(strpos($field,"as")>0) + { + $fparts = explode("as",$field,2); + $f = $fparts[1]; + $this->AddSearchWhereClause($field); + } + else { + $this->AddSearchWhereClause($field); + } + } + + $SelectSQL .= " WHERE "; + $SelectSQL .= implode(" or ",$this->WhereClauses); + + if(is_array($idlist)) + { + $SelectSQL .= " AND (ResourceId IN (".implode(",",$idlist)."))"; + } + } + $SelectSQL .= "GROUP BY $idField "; + //echo $SelectSQL."

\n"; + if($InitTable) + { + $this->adodbConnection->Execute("DROP TABLE IF EXISTS ".$this->ResultTable); + //$indexSQL = "(INDEX(Relevance), INDEX(ItemId), INDEX(ItemType), INDEX sorting (EdPick,Relevance)) "; + $full_sql = "CREATE TABLE ".$this->ResultTable." ".$indexSQL.$SelectSQL; + //echo $full_sql."
\n"; + $this->adodbConnection->Execute($full_sql); + //echo $this->adodbConnection->ErrorMsg()."
\n"; + $objSession->SetVariable("Search_Keywords",$this->Phrase); + } + else + { + $full_sql = "INSERT INTO ".$this->ResultTable." (Relevance,ItemId,ResourceId,ItemType,EdPick) ".$SelectSQL; + //echo "[".htmlspecialchars($full_sql)."]
\n"; + $this->adodbConnection->Execute($full_sql); + //echo $this->adodbConnection->ErrorMsg()."
\n"; + } + //Here we need to remove found items which was found by HTML tags matching keywords + //$this->adodbConnection->Execute("DELETE FROM ".$this->ResultTable." WHERE ItemId = 13 AND ItemType = 4"); + } + + function BuildIndexes() + { + $sql = "ALTER TABLE ".$this->ResultTable." ADD INDEX (Relevance), "; + $sql .="ADD INDEX (ItemId), "; + $sql .="ADD INDEX (ItemType), "; + $sql .=" ADD INDEX sorting (EdPick,Relevance)"; + //echo $sql; + $this->adodbConnection->Execute($sql); + } + + function Result_IdList() + { + /* returns an array contain a resource ID list */ + $sql = "SELECT DISTINCT(ResourceId) FROM ".$this->ResultTable; + $rs = $this->adodbConnection->Execute($sql); + $result = array(); + while($rs && !$rs->EOF) + { + $result[] = $rs->fields["ResourceId"]; + $rs->MoveNext(); + } + return $result; + } +} + +function count_words($string) +{ + // below line added to make contiguous spaces count as one space + if(strlen($string)) + { + $string = eregi_replace(" +", " ", $string); + return substr_count($string," ")+1; + } + else + return 0; +} + +function GetKeywords($phrase) +{ + global $KeywordIgnore; + + if(count($KeywordIgnore)==0) + GetIgnoreList(); + $keywords["normal"]= array(); + $keywords["required"]= array(); + $keywords["notallowed"] = array(); + $keywords["ignored"] = array(); + if(!strlen($phrase)) + return $keywords; + $w_array = array(); + $phrase=trim($phrase); + //if(count_words($phrase)>1) + // $keywords["normal"][] = $phrase; + $t_len = strlen($phrase); + $ce=0; + for ($i=0; $i<$t_len; $i++) + { #search for next special tag + switch ($phrase[$i]) + { + case "\"": + $exact_match_close = strpos($phrase,"\"", $i+1); + if(!$exact_match_close) + break; + $exact_word=substr($phrase, $i+1, ($exact_match_close-$i)-1); + $i=$exact_match_close; + if($exact_word) + { + if(strlen($token)==0) + $token="|"; + $w_array[$ce]=$token.addslashes($exact_word); + $token=""; + $ce++; + $exact_word=""; + } + break; + + case "+": + if(strlen($exact_word)==0) + { + $token = "+"; + } + else + $exact_word .= "+"; + break; + case "-": + if(strlen($exact_word)==0) + { + $token = "-"; + } + else + $exact_word .="-"; + break; + case " ": + case ",": + if($exact_word) + { + if(strlen($token)==0) + $token="|"; + if($token=="|") + { + if($KeywordIgnore[strtolower($exact_word)]==1) + { + $w_array[$ce]= "=".addslashes($exact_word); + $ce++; + } + else + { + $w_array[$ce]=$token.addslashes($exact_word); + $ce++; + } + } + else + { + $w_array[$ce]=$token.addslashes($exact_word); + $ce++; + } + $token=""; + $exact_word=""; + } + break; + + default: + $exact_word.=$phrase[$i]; + } + } + if($exact_word) + { + if(strlen($token)==0) + $token="|"; + if($KeywordIgnore[strtolower($exact_word)]==1 && ($token =="|" || $token=="=")) + { + $w_array[$ce]= "=".addslashes($exact_word); + $ce++; + } + else + { + $w_array[$ce]=$token.addslashes($exact_word); + $ce++; + } + } + for ($i=0;$i0 && strlen($notallowed)>0) + { + $return .= " AND "; + } + $return .= $notallowed; + if(strlen($return)>0 && strlen($normal)>0) + { + $return .= " AND "; + } + $return .= $normal; + return $return; +} + +function GetIgnoreList() +{ + global $KeywordIgnore; + + $adodbConnection = &GetADODBConnection(); + + $rs = $adodbConnection->Execute("SELECT * FROM ".GetTablePrefix()."IgnoreKeywords"); + while($rs && !$rs->EOF) + { + $KeywordIgnore[strtolower($rs->fields["keyword"])]=1; + $rs->MoveNext(); + } +// foreach($KeywordIgnore as $word=>$dummy) +// echo $word.","; +// echo "
\n"; +} + +?> Index: trunk/admin/config/addlang.php =================================================================== diff -u -N -r625 -r642 --- trunk/admin/config/addlang.php (.../addlang.php) (revision 625) +++ trunk/admin/config/addlang.php (.../addlang.php) (revision 642) @@ -1,322 +1,322 @@ -Get("Site_Path"); - -$admin = $objConfig->Get("AdminDirectory"); -if(!strlen($admin)) - $admin = "admin"; - -$localURL=$rootURL."kernel/"; -$adminURL = $rootURL.$admin; -$imagesURL = $adminURL."/images"; -$browseURL = $adminURL."/browse"; - -$pathtolocal = $pathtoroot."kernel/"; -require_once ($pathtoroot.$admin."/include/elements.php"); -require_once ($pathtoroot."kernel/admin/include/navmenu.php"); -require_once ($pathtolocal."admin/include/navmenu.php"); -require_once($pathtoroot.$admin."/browse/toolbar.php"); -require_once($pathtoroot.$admin."/listview/listview.php"); - -$m = GetModuleArray(); -foreach($m as $key=>$value) -{ - $path = $pathtoroot. $value."admin/include/parser.php"; - if(file_exists($path)) - { - include_once($path); - } -} - -$objMessages = new clsEmailMessageList(); - -unset($objEditItems); - -$objEditItems = new clsLanguageList(); -$objEditItems->SourceTable = $objSession->GetEditTable("Language"); -$objEditItems->EnablePaging = FALSE; -$objPhraseList = new clsPhraseList(); -$objPhraseList->EnablePaging = FALSE; -if ($_GET["new"] == 1) -{ - $c = new clsLanguage(NULL); - $c->Set("DecimalPoint","."); - $c->Set("ThousandSep",","); - $c->Set("DateFormat","m-d-Y"); - $c->Set("TimeFormat","g:i:s a"); - $en = 0; - $action = "m_lang_add"; - $name = prompt_language("la_Text_New"); - $objLanguages->CreateEmptyEditTable("LanguageId"); - $objPhraseList->CreateEmptyEditTable("PhraseId"); - $objMessages->CreateEmptyEditTable($_POST["itemlist"]); -} -else -{ - $en = (int)$_GET["en"]; - - if (isset($_POST["itemlist"])) - { - $objLanguages->CopyToEditTable("LanguageId",$_POST["itemlist"]); - $objPhraseList->CopyToEditTable("LanguageId",$_POST["itemlist"]); - $objMessages->CopyToEditTable("LanguageId",$_POST["itemlist"]); - } - $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); - $itemcount=$objEditItems->NumItems(); - - $c = $objEditItems->GetItemByIndex($en); - - if($itemcount>1) - { - if ($en+1 == $itemcount) - $en_next = -1; - else - $en_next = $en+1; - - if ($en == 0) - $en_prev = -1; - else - $en_prev = $en-1; - } - $action = "m_lang_edit"; - $name = $c->Get("LocalName"); -} - -$section = "in-portal:lang_general"; - -$envar = "env=".BuildEnv(); - -$title = $title = GetTitle("la_Text_Pack", "la_tab_General", $c->Get('LanguageId'), $c->Get('LocalName'));///prompt_language("la_Text_Configuration")." - ".$name."' ".prompt_language("la_Text_Pack")." - ".prompt_language("la_tab_General"); - -//Display header -$sec = $objSections->GetSection($section); -$objListToolbar = new clsToolBar(); -$objListToolbar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('language','LangEditStatus','".$admin."/config/config_lang.php',1);",$imagesURL."/toolbar/tool_select.gif"); -$objListToolbar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('language','LangEditStatus','".$admin."/config/config_lang.php',2);",$imagesURL."/toolbar/tool_cancel.gif"); - -if ( isset($en_prev) || isset($en_next) ) -{ - $url = $admin."/config/addlang.php"; - $objListToolbar->Add("divider"); - $form = "language"; - if($en_prev>-1) - { - $MouseOver="swap('moveleft','toolbar/tool_prev_f2.gif');"; - $MouseOut="swap('moveleft', 'toolbar/tool_prev.gif');"; - $onClick= $sec->Get("onclick"); - $var="env=".BuildEnv()."&en=$en_prev"; - $link = "javascript:edit_submit('$form','$url',0,'$var');"; - $objListToolbar->Add("moveleft",admin_language("la_ToolTip_Previous")." ".admin_language("la_Text_Category"),$link,$MouseOver,$MouseOut,"","toolbar/tool_prev.gif"); - } - else - { - $MouseOver=""; - $MouseOut=""; - $onClick=""; - $link="#"; - $objListToolbar->Add("moveleft",admin_language("la_ToolTip_Previous")." ".admin_language("la_Text_Category"),"#","","","","toolbar/tool_prev_f3.gif"); - - } - if($en_next>-1) - { - $MouseOver="swap('moveright','toolbar/tool_next_f2.gif');"; - $MouseOut="swap('moveright', 'toolbar/tool_next.gif');"; - $onClick=$sec->Get("onclick"); - $var="env=".BuildEnv()."&en=$en_next"; - $link = "javascript:edit_submit('$form','$url',0,'$var');"; - $objListToolbar->Add("moveright",admin_language("la_ToolTip_Next")." ".admin_language("la_Text_Category"),$link,$MouseOver,$MouseOut,"","toolbar/tool_next.gif"); - } - else - { - $objListToolbar->Add("moveright",admin_language("la_ToolTip_Next")." ".admin_language("la_Text_Category"),$link,$MouseOver,$MouseOut,"","toolbar/tool_next_f3.gif"); - } -} - - int_header($objListToolbar,NULL,$title); -?> -
- - - - > - - - - - - > - - - - - - > - - - - - - > - - - - - - > - - - - - - > - - - - - - > - - - - - - > - - - - - -> - - - - - -> - - - - -> - - - - - "> - - - -
Get("LanguageId"); ?>
">
">
">
"> - Get("DateFormat"))) echo prompt_language("la_Text_example").":".date($c->Get("DateFormat")); ?> -
"> - Get("TimeFormat"))) echo prompt_language("la_Text_example").":".date($c->Get("TimeFormat")); ?> -
">
">
- Get("Enabled") == 1) echo "checked"; ?>> -  
- Get("PrimaryLang") == 1) echo "checked"; ?>> -  
- - - - -
-
- -
" name="viewmenu"> - - - - -
- - +Get("Site_Path"); + +$admin = $objConfig->Get("AdminDirectory"); +if(!strlen($admin)) + $admin = "admin"; + +$localURL=$rootURL."kernel/"; +$adminURL = $rootURL.$admin; +$imagesURL = $adminURL."/images"; +$browseURL = $adminURL."/browse"; + +$pathtolocal = $pathtoroot."kernel/"; +require_once ($pathtoroot.$admin."/include/elements.php"); +require_once ($pathtoroot."kernel/admin/include/navmenu.php"); +require_once ($pathtolocal."admin/include/navmenu.php"); +require_once($pathtoroot.$admin."/browse/toolbar.php"); +require_once($pathtoroot.$admin."/listview/listview.php"); + +$m = GetModuleArray(); +foreach($m as $key=>$value) +{ + $path = $pathtoroot. $value."admin/include/parser.php"; + if(file_exists($path)) + { + include_once($path); + } +} + +$objMessages = new clsEmailMessageList(); + +unset($objEditItems); + +$objEditItems = new clsLanguageList(); +$objEditItems->SourceTable = $objSession->GetEditTable("Language"); +$objEditItems->EnablePaging = FALSE; +$objPhraseList = new clsPhraseList(); +$objPhraseList->EnablePaging = FALSE; +if ($_GET["new"] == 1) +{ + $c = new clsLanguage(NULL); + $c->Set("DecimalPoint","."); + $c->Set("ThousandSep",","); + $c->Set("DateFormat","m-d-Y"); + $c->Set("TimeFormat","g:i:s a"); + $en = 0; + $action = "m_lang_add"; + $name = prompt_language("la_Text_New"); + $objLanguages->CreateEmptyEditTable("LanguageId"); + $objPhraseList->CreateEmptyEditTable("PhraseId"); + $objMessages->CreateEmptyEditTable($_POST["itemlist"]); +} +else +{ + $en = (int)$_GET["en"]; + + if (isset($_POST["itemlist"])) + { + $objLanguages->CopyToEditTable("LanguageId",$_POST["itemlist"]); + $objPhraseList->CopyToEditTable("LanguageId",$_POST["itemlist"]); + $objMessages->CopyToEditTable("LanguageId",$_POST["itemlist"]); + } + $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); + $itemcount=$objEditItems->NumItems(); + + $c = $objEditItems->GetItemByIndex($en); + + if($itemcount>1) + { + if ($en+1 == $itemcount) + $en_next = -1; + else + $en_next = $en+1; + + if ($en == 0) + $en_prev = -1; + else + $en_prev = $en-1; + } + $action = "m_lang_edit"; + $name = $c->Get("LocalName"); +} + +$section = "in-portal:lang_general"; + +$envar = "env=".BuildEnv(); + +$title = $title = GetTitle("la_Text_Pack", "la_tab_General", $c->Get('LanguageId'), $c->Get('LocalName'));///prompt_language("la_Text_Configuration")." - ".$name."' ".prompt_language("la_Text_Pack")." - ".prompt_language("la_tab_General"); + +//Display header +$sec = $objSections->GetSection($section); +$objListToolbar = new clsToolBar(); +$objListToolbar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('language','LangEditStatus','".$admin."/config/config_lang.php',1);",$imagesURL."/toolbar/tool_select.gif"); +$objListToolbar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('language','LangEditStatus','".$admin."/config/config_lang.php',2);",$imagesURL."/toolbar/tool_cancel.gif"); + +if ( isset($en_prev) || isset($en_next) ) +{ + $url = $admin."/config/addlang.php"; + $objListToolbar->Add("divider"); + $form = "language"; + if($en_prev>-1) + { + $MouseOver="swap('moveleft','toolbar/tool_prev_f2.gif');"; + $MouseOut="swap('moveleft', 'toolbar/tool_prev.gif');"; + $onClick= $sec->Get("onclick"); + $var="env=".BuildEnv()."&en=$en_prev"; + $link = "javascript:edit_submit('$form','$url',0,'$var');"; + $objListToolbar->Add("moveleft",admin_language("la_ToolTip_Previous")." ".admin_language("la_Text_Category"),$link,$MouseOver,$MouseOut,"","toolbar/tool_prev.gif"); + } + else + { + $MouseOver=""; + $MouseOut=""; + $onClick=""; + $link="#"; + $objListToolbar->Add("moveleft",admin_language("la_ToolTip_Previous")." ".admin_language("la_Text_Category"),"#","","","","toolbar/tool_prev_f3.gif"); + + } + if($en_next>-1) + { + $MouseOver="swap('moveright','toolbar/tool_next_f2.gif');"; + $MouseOut="swap('moveright', 'toolbar/tool_next.gif');"; + $onClick=$sec->Get("onclick"); + $var="env=".BuildEnv()."&en=$en_next"; + $link = "javascript:edit_submit('$form','$url',0,'$var');"; + $objListToolbar->Add("moveright",admin_language("la_ToolTip_Next")." ".admin_language("la_Text_Category"),$link,$MouseOver,$MouseOut,"","toolbar/tool_next.gif"); + } + else + { + $objListToolbar->Add("moveright",admin_language("la_ToolTip_Next")." ".admin_language("la_Text_Category"),$link,$MouseOver,$MouseOut,"","toolbar/tool_next_f3.gif"); + } +} + + int_header($objListToolbar,NULL,$title); +?> +
+ + +Data=inp_htmlize($c->Data);?> + > + + + + + + > + + + + + + > + + + + + + > + + + + + + > + + + + + + > + + + + + + > + + + + + + > + + + + + +> + + + + + +> + + + + +> + + + + + "> + + + +
Get("LanguageId"); ?>
">
">
">
"> + Get("DateFormat"))) echo prompt_language("la_Text_example").":".date($c->Get("DateFormat")); ?> +
"> + Get("TimeFormat"))) echo prompt_language("la_Text_example").":".date($c->Get("TimeFormat")); ?> +
">
">
+ Get("Enabled") == 1) echo "checked"; ?>> +  
+ Get("PrimaryLang") == 1) echo "checked"; ?>> +  
+ + + + +
+
+ +
" name="viewmenu"> + + + + +
+ + Index: trunk/admin/listview/listview.php =================================================================== diff -u -N -r291 -r642 --- trunk/admin/listview/listview.php (.../listview.php) (revision 291) +++ trunk/admin/listview/listview.php (.../listview.php) (revision 642) @@ -1,472 +1,472 @@ -SetToolBar($ToolBar); - $this->SetListItems($ListItems); - $this->ColumnHeaders = new clsColumnHeaderList(); - $this->CurrentPage=1; - $this->CheckboxName = "itemlist[]"; - $this->SelectorType="checkbox"; - $this->RowIcons = array(); - $this->PageLinks = ""; - $this->SearchAction = ""; - $this->extra_env=""; - $this->PriorityField="Priority"; - $this->TotalItemCount = 0; - - if (!is_null($ToolBar)) - $this->JSCheckboxName = $ToolBar->Get("CheckClass"); - $this->SetFormatters(); // for setting custom formatters - } - - function SetToolbar($ToolBar) - { - $this->ToolBar=$ToolBar; - if(is_object($this->ToolBar)) - $this->CheckArray=$this->ToolBar->Get("CheckClass"); - } - - function GetPage() - { - // get current page - $this->RefreshPageVar(); - return $this->CurrentPage; - } - - function GetLimitSQL() - { - return GetLimitSQL($this->GetPage(), $this->GetPerPage() ); - } - - function SetListItems($ListItems) - { - $this->ListItems = $ListItems; - } - - function SetIDfield($field) - { - $this->IdField = $field; - } - - function SetSort($SortField,$SortOrderVariable) - { - $this->ColumnHeaders->SetSort($SortField,$SortOrder); - } - - function SetRowIcon($index,$url) - { - $this->RowIcons[$index] = $url; - } - - function ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSort,$FilterVar,$FilterValue,$FilterMax) - { - global $objConfig; - - //$FilterVal = $this->CurrentFilter; - //$fMax = $this->Filtermax; - //$sOrder = $this->CurrentSortOrder; - //$sOrderVar = $this->OrderVar; - //$sField = $this->CurrentSortField; - //$sDefault = $this->DefaultSortField; - - $this->ViewMenu = new clsViewMenu(); - $this->ViewMenu->PerPageVar = $this->PerPageVar; - $this->ViewMenu->PerPageValue = (int)$objConfig->Get($this->PerPageVar); - if($this->ViewMenu->PerPageValue==0) - $this->ViewMenu->PerPageValue = 20; - $this->ViewMenu->CurrentSortField = $objConfig->Get($SortFieldVar); - $this->ViewMenu->CurrentSortOrder = $objConfig->get($SortOrderVar); - $this->ViewMenu->SortVar = $SortFieldVar; - $this->ViewMenu->OrderVar = $SortOrderVar; - $this->ViewMenu->CurrentFilter= $FilterValue; - $this->ViewMenu->FilterVar = $FilterVar; - $this->ViewMenu->FilterMax = $FilterMax; - foreach($this->ColumnHeaders->Columns as $col) - { - $this->ViewMenu->AddSortField($col->field,$col->label,$DefaultSort==$col->field); - } - } - - function AddViewMenuFilter($Label,$Bit) - { - if(is_object($this->ViewMenu)) - $this->ViewMenu->AddFilterField($Label,$Bit); - } - - function GetViewMenu($imagesURL) - { - if(is_object($this->ViewMenu)) - { - $this->ViewMenu->CheckboxName = $this->JSCheckboxName; - return $this->ViewMenu->GetViewMenuJS($imagesURL); - } - else - return ""; - } - - function SetFormatters() - { - // for setting custom formatters - // abstract - } - - 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; - } - } - - function PrintItem($index) - { - if( !isset($this->ListItems->Items[$index]) ) return ''; - $li = $this->ListItems->Items[$index]; - - $o = ""; - $first=1; - - if(is_object($li)) - { - // ==== new by Alex: begin ==== - $li->Formatters =& $this->Formatters; - // ==== new by Alex: end ==== - - $id_field = $this->IdField; - $row_id = $li->Get($id_field); - if(is_numeric($li->Get($this->PriorityField))) - { - $Priority = (int)$li->Get($this->PriorityField); - } - else - $Priority=0; - $o = "\n"; - foreach($this->ColumnHeaders->Columns as $col) - { - $width=""; - $ColId = $row_id."_col_".$col->field; - if($first==1) - { - if(strlen($col->width)) - { - $width = $col->width; - } - $o .= ""; - if($this->checkboxes) - { - $onclick = "onclick=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\""; - $onclicksrc = "onclicksrc=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\""; - $o .= "SelectorType."\" name=\"".$this->CheckboxName."\" value=\"$row_id\" $onclick $onclicksrc>"; - } - if(isset($this->RowIcons[$index])) - { - $url = $this->RowIcons[$index]; - if(strlen($url)) - $o .= " "; - } - $first=0; - } - else - { - if(strlen($col->width)) - { - $o .= "width.">"; - } - else - $o .= ""; - } - if($Priority!=0) - { - $o .= "$Priority"; - $Priority=0; - } - $o .= "".stripslashes($li->GetFormatted($col->field))."\n"; - } - $o .= "\n"; - } - return $o; - } - - function PrintItems() - { - $o = ''; - $numitems = $this->ListItems->NumItems(); - for($index=0;$index<=$numitems;$index++) - { - $o .= $this->PrintItem($index); - } - return $o; - } - - function TotalPageNumbers() - { - if($this->PerPage>0) - { - $ret = $this->ListItems->NumItems() / $this->PerPage; - $ret = (int)$ret; - } - else - $ret = 1; - - return $ret; - } - - function GetPerPage() - { - global $objConfig; - $PerPage = $objConfig->Get($this->PerPageVar); - if($PerPage < 1) - { - if( defined('DEBUG_MODE') ) echo 'PerPage Variable ['.$this->PerPageVar.'] not defined in Config
'; - $PerPage = 20; - //$objConfig->Set($this->PerPageVar,20); - //$objConfig->Save(); - } - return $PerPage; - } - - function GetAdminPageLinkList($url) - { - global $objConfig; - - $PerPage = $this->GetPerPage(); - - if($this->TotalItemCount>0) - { - $NumPages = ceil($this->TotalItemCount / $PerPage); - } - else - $NumPages = ceil($this->ListItems->NumItems() / $PerPage); - - if($NumPages<1) - $NumPages =1; - //echo $this->CurrentPage." of ".$NumPages." Pages"; - - $o = ""; - if($this->CurrentPage>$NumPages) - $this->CurrentPage=$NumPages; - - $StartPage = $this->CurrentPage - 5; - if($StartPage<1) - $StartPage=1; - $EndPage = $StartPage+9; - if($EndPage>$NumPages) - { - $EndPage = $NumPages; - $StartPage = $EndPage-10; - if($StartPage<1) - $StartPage=1; - } - - $o .= "".admin_language("la_Page")." "; - if($StartPage>1) - { - $target = $this->CurrentPage-10; - $prev_url = str_replace("{TargetPage}",$target,$url); - $o .= "<<"; - } - - for($p=$StartPage;$p<=$EndPage;$p++) - { - if($p!=$this->CurrentPage) - { - $href = str_replace("{TargetPage}",$p,$url); - $o .= " $p "; - } - else - { - $o .= " $p "; - } - } - if($EndPage<$NumPages-1) - { - $target = $this->CurrentPage+10; - $next_url = str_replace("{TargetPage}",$target,$url); - $o .= " >>"; - } - return $o; - } - - function SliceItems() - { - global $objConfig; - - $PerPage = (int)$objConfig->Get($this->PerPageVar); - if($PerPage<1) - $PerPage=20; - $NumPages = ceil($this->ListItems->NumItems() / $PerPage); - if($NumPages>1) - { - $Start = ($this->CurrentPage-1)*$PerPage; - $this->ListItems->Items = array_slice($this->ListItems->Items,$Start,$PerPage); - } - } - - function RefreshPageVar() - { - global $objSession; - if( (int)GetVar('lpn') > 0) - { - $this->CurrentPage = $_GET["lpn"]; - $objSession->SetVariable($this->CurrentPageVar,$this->CurrentPage); - } - else - $this->CurrentPage = $objSession->GetVariable($this->CurrentPageVar); - - $this->ListItems->Page = $this->CurrentPage; - } - - function PrintPageLinks($add_search = '') - { - global $imagesURL, $objSession, $lvErrorString; - - if(strlen($this->PageLinks)>0) - { - return $this->PageLinks; - } - $this->RefreshPageVar(); - - if($this->CurrentPage<1) - $this->CurrentPage = 1; - if(!strlen($this->PageURL)) - { - $this->PageURL = $_SERVER["PHP_SELF"]."?env=".BuildEnv(); - if(strlen($this->extra_env)) - $this->PageURL .= "&".$this->extra_env; - $this->PageURL .= "&lpn={TargetPage}"; - } - $cols = $this->ColumnHeaders->Count(); - $o = "\n"; - - if(strlen($lvErrorString)) - { - $o .= ""; - - } - if($this->SearchBar==FALSE) - { - $o .= '\n"; - } - else - { - $val = str_replace(","," ", $this->SearchKeywords); - $o .= ""; - $o .= ""; - } - $o .= "
$lvErrorString
'; - $o .= $this->GetAdminPageLinkList($this->PageURL); - $o .= ""; - $o .= $this->GetAdminPageLinkList($this->PageURL)."$add_search".admin_language("la_prompt_Search"); - $o .= " "; - $o .= " SearchAction."');\">"; - $o .= " SearchAction."_reset');\">"; - if(strlen($this->SearchDropdownId)>0) - { - $o .= " SearchDropdownId."');\">"; - } - $o .= "
"; - return $o; - } - - function PrintJavaScriptInit() - { - $o = ''; - if($this->checkboxes) - { - $o = ""; - } - return $o; - } - - - function PrintList($footer = '',$add_search = '') - { - global $objSession; - if((int)$this->CurrentPage<1) - $this->CurrentPage=1; - - $o = "\n"; - - if(is_object($this->ToolBar)) - { - if($this->PrintToolBar) - $o .= $this->ToolBar->Build(); - } - $o .= $this->PrintPageLinks($add_search); - $o .= "\n"; - - if($this->ShowColumnHeaders) - { - $o .= $this->ColumnHeaders->PrintColumns(); - } - if($this->ListItems->NumItems()>0) - { - $o .= $this->PrintItems(); - - } - - $o .= "$footer
"; - if($this->ListItems->NumItems()>0) - $o .= $this->PrintJavaScriptInit(); - return $o; - } -} +SetToolBar($ToolBar); + $this->SetListItems($ListItems); + $this->ColumnHeaders = new clsColumnHeaderList(); + $this->CurrentPage=1; + $this->CheckboxName = "itemlist[]"; + $this->SelectorType="checkbox"; + $this->RowIcons = array(); + $this->PageLinks = ""; + $this->SearchAction = ""; + $this->extra_env=""; + $this->PriorityField="Priority"; + $this->TotalItemCount = 0; + + if (!is_null($ToolBar)) + $this->JSCheckboxName = $ToolBar->Get("CheckClass"); + $this->SetFormatters(); // for setting custom formatters + } + + function SetToolbar($ToolBar) + { + $this->ToolBar=$ToolBar; + if(is_object($this->ToolBar)) + $this->CheckArray=$this->ToolBar->Get("CheckClass"); + } + + function GetPage() + { + // get current page + $this->RefreshPageVar(); + return $this->CurrentPage; + } + + function GetLimitSQL() + { + return GetLimitSQL($this->GetPage(), $this->GetPerPage() ); + } + + function SetListItems($ListItems) + { + $this->ListItems = $ListItems; + } + + function SetIDfield($field) + { + $this->IdField = $field; + } + + function SetSort($SortField,$SortOrderVariable) + { + $this->ColumnHeaders->SetSort($SortField,$SortOrder); + } + + function SetRowIcon($index,$url) + { + $this->RowIcons[$index] = $url; + } + + function ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSort,$FilterVar,$FilterValue,$FilterMax) + { + global $objConfig; + + //$FilterVal = $this->CurrentFilter; + //$fMax = $this->Filtermax; + //$sOrder = $this->CurrentSortOrder; + //$sOrderVar = $this->OrderVar; + //$sField = $this->CurrentSortField; + //$sDefault = $this->DefaultSortField; + + $this->ViewMenu = new clsViewMenu(); + $this->ViewMenu->PerPageVar = $this->PerPageVar; + $this->ViewMenu->PerPageValue = (int)$objConfig->Get($this->PerPageVar); + if($this->ViewMenu->PerPageValue==0) + $this->ViewMenu->PerPageValue = 20; + $this->ViewMenu->CurrentSortField = $objConfig->Get($SortFieldVar); + $this->ViewMenu->CurrentSortOrder = $objConfig->get($SortOrderVar); + $this->ViewMenu->SortVar = $SortFieldVar; + $this->ViewMenu->OrderVar = $SortOrderVar; + $this->ViewMenu->CurrentFilter= $FilterValue; + $this->ViewMenu->FilterVar = $FilterVar; + $this->ViewMenu->FilterMax = $FilterMax; + foreach($this->ColumnHeaders->Columns as $col) + { + $this->ViewMenu->AddSortField($col->field,$col->label,$DefaultSort==$col->field); + } + } + + function AddViewMenuFilter($Label,$Bit) + { + if(is_object($this->ViewMenu)) + $this->ViewMenu->AddFilterField($Label,$Bit); + } + + function GetViewMenu($imagesURL) + { + if(is_object($this->ViewMenu)) + { + $this->ViewMenu->CheckboxName = $this->JSCheckboxName; + return $this->ViewMenu->GetViewMenuJS($imagesURL); + } + else + return ""; + } + + function SetFormatters() + { + // for setting custom formatters + // abstract + } + + 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; + } + } + + function PrintItem($index) + { + if( !isset($this->ListItems->Items[$index]) ) return ''; + $li = $this->ListItems->Items[$index]; + + $o = ""; + $first=1; + + if(is_object($li)) + { + // ==== new by Alex: begin ==== + $li->Formatters =& $this->Formatters; + // ==== new by Alex: end ==== + + $id_field = $this->IdField; + $row_id = $li->Get($id_field); + if(is_numeric($li->Get($this->PriorityField))) + { + $Priority = (int)$li->Get($this->PriorityField); + } + else + $Priority=0; + $o = "\n"; + foreach($this->ColumnHeaders->Columns as $col) + { + $width=""; + $ColId = $row_id."_col_".$col->field; + if($first==1) + { + if(strlen($col->width)) + { + $width = $col->width; + } + $o .= ""; + if($this->checkboxes) + { + $onclick = "onclick=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\""; + $onclicksrc = "onclicksrc=\"if (this.checked) {".$this->CheckArray.".addCheck('$row_id');} else {".$this->CheckArray.".removeCheck('$row_id');}\""; + $o .= "SelectorType."\" name=\"".$this->CheckboxName."\" value=\"$row_id\" $onclick $onclicksrc>"; + } + if(isset($this->RowIcons[$index])) + { + $url = $this->RowIcons[$index]; + if(strlen($url)) + $o .= " "; + } + $first=0; + } + else + { + if(strlen($col->width)) + { + $o .= "width.">"; + } + else + $o .= ""; + } + if($Priority!=0) + { + $o .= "$Priority"; + $Priority=0; + } + $o .= "".stripslashes($li->GetFormatted($col->field))."\n"; + } + $o .= "\n"; + } + return $o; + } + + function PrintItems() + { + $o = ''; + $numitems = $this->ListItems->NumItems(); + for($index=0;$index<=$numitems;$index++) + { + $o .= $this->PrintItem($index); + } + return $o; + } + + function TotalPageNumbers() + { + if($this->PerPage>0) + { + $ret = $this->ListItems->NumItems() / $this->PerPage; + $ret = (int)$ret; + } + else + $ret = 1; + + return $ret; + } + + function GetPerPage() + { + global $objConfig; + $PerPage = $objConfig->Get($this->PerPageVar); + if($PerPage < 1) + { + if( defined('DEBUG_MODE') ) echo 'PerPage Variable ['.$this->PerPageVar.'] not defined in Config
'; + $PerPage = 20; + //$objConfig->Set($this->PerPageVar,20); + //$objConfig->Save(); + } + return $PerPage; + } + + function GetAdminPageLinkList($url) + { + global $objConfig; + + $PerPage = $this->GetPerPage(); + + if($this->TotalItemCount>0) + { + $NumPages = ceil($this->TotalItemCount / $PerPage); + } + else + $NumPages = ceil($this->ListItems->NumItems() / $PerPage); + + if($NumPages<1) + $NumPages =1; + //echo $this->CurrentPage." of ".$NumPages." Pages"; + + $o = ""; + if($this->CurrentPage>$NumPages) + $this->CurrentPage=$NumPages; + + $StartPage = $this->CurrentPage - 5; + if($StartPage<1) + $StartPage=1; + $EndPage = $StartPage+9; + if($EndPage>$NumPages) + { + $EndPage = $NumPages; + $StartPage = $EndPage-10; + if($StartPage<1) + $StartPage=1; + } + + $o .= "".admin_language("la_Page")." "; + if($StartPage>1) + { + $target = $this->CurrentPage-10; + $prev_url = str_replace("{TargetPage}",$target,$url); + $o .= "<<"; + } + + for($p=$StartPage;$p<=$EndPage;$p++) + { + if($p!=$this->CurrentPage) + { + $href = str_replace("{TargetPage}",$p,$url); + $o .= " $p "; + } + else + { + $o .= " $p "; + } + } + if($EndPage<$NumPages-1) + { + $target = $this->CurrentPage+10; + $next_url = str_replace("{TargetPage}",$target,$url); + $o .= " >>"; + } + return $o; + } + + function SliceItems() + { + global $objConfig; + + $PerPage = (int)$objConfig->Get($this->PerPageVar); + if($PerPage<1) + $PerPage=20; + $NumPages = ceil($this->ListItems->NumItems() / $PerPage); + if($NumPages>1) + { + $Start = ($this->CurrentPage-1)*$PerPage; + $this->ListItems->Items = array_slice($this->ListItems->Items,$Start,$PerPage); + } + } + + function RefreshPageVar() + { + global $objSession; + if( (int)GetVar('lpn') > 0) + { + $this->CurrentPage = $_GET["lpn"]; + $objSession->SetVariable($this->CurrentPageVar,$this->CurrentPage); + } + else + $this->CurrentPage = $objSession->GetVariable($this->CurrentPageVar); + + $this->ListItems->Page = $this->CurrentPage; + } + + function PrintPageLinks($add_search = '') + { + global $imagesURL, $objSession, $lvErrorString; + + if(strlen($this->PageLinks)>0) + { + return $this->PageLinks; + } + $this->RefreshPageVar(); + + if($this->CurrentPage<1) + $this->CurrentPage = 1; + if(!strlen($this->PageURL)) + { + $this->PageURL = $_SERVER["PHP_SELF"]."?env=".BuildEnv(); + if(strlen($this->extra_env)) + $this->PageURL .= "&".$this->extra_env; + $this->PageURL .= "&lpn={TargetPage}"; + } + $cols = $this->ColumnHeaders->Count(); + $o = "\n"; + + if(strlen($lvErrorString)) + { + $o .= ""; + + } + if($this->SearchBar==FALSE) + { + $o .= '\n"; + } + else + { + $val = inp_htmlize(str_replace(","," ", $this->SearchKeywords),1); + $o .= ""; + $o .= ""; + } + $o .= "
$lvErrorString
'; + $o .= $this->GetAdminPageLinkList($this->PageURL); + $o .= ""; + $o .= $this->GetAdminPageLinkList($this->PageURL)."$add_search".admin_language("la_prompt_Search"); + $o .= " "; + $o .= " SearchAction."');\">"; + $o .= " SearchAction."_reset');\">"; + if(strlen($this->SearchDropdownId)>0) + { + $o .= " SearchDropdownId."');\">"; + } + $o .= "
"; + return $o; + } + + function PrintJavaScriptInit() + { + $o = ''; + if($this->checkboxes) + { + $o = ""; + } + return $o; + } + + + function PrintList($footer = '',$add_search = '') + { + global $objSession; + if((int)$this->CurrentPage<1) + $this->CurrentPage=1; + + $o = "\n"; + + if(is_object($this->ToolBar)) + { + if($this->PrintToolBar) + $o .= $this->ToolBar->Build(); + } + $o .= $this->PrintPageLinks($add_search); + $o .= "\n"; + + if($this->ShowColumnHeaders) + { + $o .= $this->ColumnHeaders->PrintColumns(); + } + if($this->ListItems->NumItems()>0) + { + $o .= $this->PrintItems(); + + } + + $o .= "$footer
"; + if($this->ListItems->NumItems()>0) + $o .= $this->PrintJavaScriptInit(); + return $o; + } +} Index: trunk/globals.php =================================================================== diff -u -N -r641 -r642 --- trunk/globals.php (.../globals.php) (revision 641) +++ trunk/globals.php (.../globals.php) (revision 642) @@ -1,1464 +1,1483 @@ -\n") { - $resave = true; - } - $ln++; - $line = trim($line); - $line = eregi_replace(';[.]*','',$line); - if(strlen($line) > 0) { - //echo $line . " - "; - if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) { - //echo 'section'; - $section = substr($line,1,(strlen($line)-2)); - if ($parse_section) { - $retval[$section] = array(); - } - continue; - } elseif(eregi('=',$line)) { - //echo 'main element'; - list($key,$val) = explode(' = ',$line); - if (!$parse_section) { - $retval[trim($key)] = str_replace('"', '', $val); - } - else { - $retval[$section][trim($key)] = str_replace('"', '', $val); - } - } //end if - //echo '
'; - } //end if - } //end foreach - if ($resave) { - $fp = fopen($file, "w"); - reset($contents); - fwrite($fp,'<'.'?'.'php die() ?'.">\n\n"); - foreach($contents as $line) fwrite($fp,"$line"); - fclose($fp); - } - - return $retval; -} - -/** - * @return object - * @desc Returns reference to database connection -*/ -function &GetADODBConnection() -{ - static $DB = null; - - global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode; - global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot; - - if( !isset($DB) && strlen($g_DBType) > 0 ) - { - $DB = ADONewConnection($g_DBType); - $connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName); - if(!$connected) die("Error connecting to database $g_DBHost
\n"); - - $ADODB_CACHE_DIR = $pathtoroot."cache"; - $ADODB_FETCH_MODE = 2; - $ADODB_COUNTRECS = false; - $DB->debug = defined('ADODB_OUTP') ? 1 : 0; - $DB->cacheSecs = 3600; - $DB->Execute('SET SQL_BIG_SELECTS = 1'); - } - elseif( !strlen($g_DBType) ) - { - global $rootURL; - echo 'In-Portal is probably not installed, or configuration file is missing.
'; - echo 'Please use the installation script to fix the problem.

'; - if ( !preg_match('/admin/', __FILE__) ) $ins = 'admin/'; - - echo 'Go to installation script

'; - flush(); - exit; - } - return $DB; -} - -function GetNextResourceId($Increment=1) -{ - $sql = "UPDATE ".GetTablePrefix()."IdGenerator SET lastid=lastid+".$Increment; - $adodbConnection = &GetADODBConnection(); - $adodbConnection->Execute($sql); - $rs = $adodbConnection->Execute("SELECT lastid FROM ".GetTablePrefix()."IdGenerator"); - $val = $rs->fields["lastid"]; - if(!$rs || $rs->EOF) - { - echo $adodbConnection->ErrorMsg(); - $sql = "INSERT INTO ".GetTablePrefix()."IdGenerator (lastid) VALUES ($Increment)"; - $adodbConnection->Execute($sql); - $val = 1; - } - $val = $val-($Increment-1); - return $val; -} - -function AddSlash($s) -{ - if(substr($s,-1) != "/") - { - return $s."/"; - } - else - return $s; -} - -function StripNewline($s) -{ - $bfound = false; - while (strlen($s)>0 && !$bfound) - { - if(ord(substr($s,-1))<32) - { - $s = substr($s,0,-1); - } - else - $bfound = true; - } - return $s; -} - -function DeleteElement($array, $indice) -{ - for($i=$indice;$i -1) - unset($haystack[$gotcha]); -} - -function TableCount($TableName, $where="",$JoinCats=1) -{ - $db = &GetADODBConnection(); - if(!$JoinCats) - { - $sql = "SELECT count(*) as TableCount FROM $TableName"; - } - else - $sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId"; - if(strlen($where)>0) - $sql .= " WHERE ".$where; - - $rs = $db->Execute($sql); - -// echo "SQL TABLE COUNT: ".$sql."
\n"; - - $res = $rs->fields["TableCount"]; - return $res; -} - -Function QueryCount($sql) -{ - $sql = preg_replace('/SELECT(.*)FROM[ \n\r](.*)/is','SELECT COUNT(*) AS TableCount FROM $2', $sql); - $sql = preg_replace('/(.*)LIMIT(.*)/is','$1', $sql); - $sql = preg_replace('/(.*)ORDER BY(.*)/is','$1', $sql); - - $db =& GetADODBConnection(); - return $db->GetOne($sql); -} - -function GetPageCount($ItemsPerPage,$NumItems) -{ - if($ItemsPerPage==0 || $NumItems==0) - { - return 1; - } - $value = $NumItems/$ItemsPerPage; - return ceil($value); -} - - -/** - * @return string - * @desc Returns database table prefix entered while installation -*/ -function GetTablePrefix() -{ - global $g_TablePrefix; - - return $g_TablePrefix; -} - -function TableHasPrefix($t) -{ - $pre = GetTablePrefix(); - - if(strlen($pre)>0) - { - if(substr($t,0,strlen($pre))==$pre) - { - return TRUE; - } - else - return FALSE; - } - else - return TRUE; -} - -function AddTablePrefix($t) -{ - if(!TableHasPrefix($t)) - $t = GetTablePrefix().$t; - - return $t; -} - -function ThisDomain() -{ - global $objConfig, $g_Domain; - - if($objConfig->Get("DomainDetect")) - { - $d = $_SERVER['HTTP_HOST']; - } - else - $d = $g_Domain; - - return $d; -} - -function GetIndexUrl($secure=0) -{ - global $indexURL, $rootURL, $secureURL; - switch($secure) - { - case 0: - $ret = $indexURL; - break; - - case 1: - $ret = $secureURL."index.php"; - break; - - case 2: - $ret = $rootURL."index.php"; - break; - - default: - $ret = $i; - break; - } - return $ret; -} - -function GetLimitSQL($Page,$PerPage) -{ - if($Page<1) - $Page=1; - - if(is_numeric($PerPage)) - { - if($PerPage==0) - $PerPage = 20; - $Start = ($Page-1)*$PerPage; - $limit = "LIMIT ".$Start.",".$PerPage; - } - else - $limit = NULL; - return $limit; -} - -function filelist ($currentdir, $startdir=NULL,$ext=NULL) -{ - global $pathchar; - - //chdir ($currentdir); - - // remember where we started from - if (!$startdir) - { - $startdir = $currentdir; - } - - $d = @opendir($currentdir); - - $files = array(); - if(!$d) - return $files; - //list the files in the dir - while (false !== ($file = readdir($d))) - { - if ($file != ".." && $file != ".") - { - if (is_dir($currentdir."/".$file)) - { - // If $file is a directory take a look inside - $a = filelist ($currentdir."/".$file, $startdir,$ext); - if(is_array($a)) - $files = array_merge($files,$a); - } - else - { - if($ext!=NULL) - { - $extstr = stristr($file,".".$ext); - if(strlen($extstr)) - $files[] = $currentdir."/".$file; - } - else - $files[] = $currentdir.'/'.$file; - } - } - } - - closedir ($d); - - return $files; -} - -function DecimalToBin($dec,$WordLength=8) -{ - $bits = array(); - - $str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT); - for($i=$WordLength;$i>0;$i--) - { - $bits[$i-1] = (int)substr($str,$i-1,1); - } - return $bits; -} - -function inp_escape($in, $html_enable=0) -{ - $out = stripslashes($in); - $out = str_replace("\n", "\n^br^", $out); - if($html_enable==0) - { - $out=ereg_replace("<","<",$out); - $out=ereg_replace(">",">",$out); - $out=ereg_replace("\"",""",$out); - $out = str_replace("\n^br^", "\n
", $out); - } - else - $out = str_replace("\n^br^", "\n", $out); - $out=addslashes($out); - - return $out; -} - -function inp_unescape($in) -{ - $out=stripslashes($in); - - return $out; -} - -function inp_textarea_unescape($in) -{ - $out=stripslashes($in); - $out = str_replace("\n
", "\n", $out); - return $out; -} - -function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="") -{ - global $objConfig; - - if(!strlen($OpenTag)) - $OpenTag = ""; - if(!strlen($CloseTag)) - $CloseTag = ""; - - $r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE); - - foreach ($Keywords as $k) { - for ($i = 0; $i < count($r); $i++) { - if ($r[$i] == "<") { - $i++; continue; - } - $r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]); - } - } - return join("", $r); -} - -/* -function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="") -{ - global $objConfig; - - if(!strlen($OpenTag)) - $OpenTag = ""; - if(!strlen($CloseTag)) - $CloseTag = ""; - $ret = strip_tags($html); - - foreach ($Keywords as $k) - { - if(strlen($k)) - { - //$html = str_replace("<$k>", ":#:", $html); - //$html = str_replace("", ":##:", $html); - //$html = strip_tags($html); - if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html)) - //if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html)) - $ret = $html; - //$ret = str_replace(":#:", "<$k>", $ret); - //$ret = str_replace(":##:", "", $ret); - } - } - return $ret; -} -*/ -function ExtractDatePart($part,$datestamp) -{ - switch($part) - { - case "month": - if($datestamp<=0) - { - $ret = ""; - } - else - $ret = adodb_date("m",$datestamp); - break; - case "day": - if($datestamp<=0) - { - $ret = ""; - } - else - $ret = adodb_date("d", $datestamp); - break; - case "year": - if($datestamp<=0) - { - $ret = ""; - } - else - $ret = adodb_date("Y", $datestamp); - break; - case "time_24hr": - if($datestamp<=0) - { - $ret = ""; - } - else - $ret = adodb_date("H:i", $datestamp); - break; - case "time_12hr": - if($datestamp<=0) - { - $ret = ""; - } - else - $ret = adodb_date("g:i a",$datestamp); - break; - default: - $ret = adodb_date($part, $datestamp); - break; - } - return $ret; -} - -function GetLocalTime($TimeStamp,$TargetZone=NULL) -{ - if($TargetZone==NULL) - $TargetZone = $objConfig->Get("Config_Site_Time"); - $server = $objConfig->Get("Config_Server_Time"); - if($TargetZone!=$server) - { - $offset = ($server - $TargetZone) * -1; - $TimeStamp = $TimeStamp + (3600 * $offset); - } - return $TimeStamp; -} - -function _unhtmlentities ($string) -{ - $trans_tbl = get_html_translation_table (HTML_ENTITIES); - $trans_tbl = array_flip ($trans_tbl); - return strtr ($string, $trans_tbl); -} - -function getLastStr($hay, $need){ - $getLastStr = 0; - $pos = strpos($hay, $need); - if (is_int ($pos)){ //this is to decide whether it is "false" or "0" - while($pos) { - $getLastStr = $getLastStr + $pos + strlen($need); - $hay = substr ($hay , $pos + strlen($need)); - $pos = strpos($hay, $need); - } - return $getLastStr - strlen($need); - } else { - return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0". - } -} - -function ReplaceSingleTag($tag,$text) -{ - $tag = strtolower($tag); - $opentag = '['.$tag; - $closetag = '[/'.$tag.']'; - - if( stristr($text,$opentag) ) - { - $pos = strpos( strtolower($text), $opentag.' '); // tag has parameters - if($pos === false) - { - $pos = strpos( strtolower($text), $opentag.']'); - } - - $endopen = strpos($text,']',$pos); - $closepos = strpos( strtolower($text),$closetag,$pos); - - if($closepos) - { - $taglength = ($closepos - $endopen) + strlen($closetag); - $tagText = substr($text,$pos, $closepos + strlen($closetag) - $pos); - $innerText = substr($text,$endopen+1,$closepos - $endopen-1); - if($tag=="UL") - { - $innerText = str_replace("[*]","
  • ",$innerText); - } - $tagText = substr($tagText,1,($endopen - $pos)-1); - //echo "Matched $tagText
    \n"; - $tagText = "<".$tagText.">"; - $replace_text = $tagText.$innerText.""; - $text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag)); - return $text; - } - else - return $text; - } - else - return $text; -} - -function ReplaceTag($tag,$text) -{ - $new_text = ReplaceSingleTag($tag,$text); - - while($new_text != $text) - { - $text = $new_text; - $new_text = ReplaceSingleTag($tag,$text); - } - return $new_text; -} - -function ReplaceURL($text) -{ - - // process url bbtags without href parameter - $text = preg_replace('/\[url\]([^\]]*)\[\/url\]/U', '[url href="$1"]$1[/url]', $text); - - // change bbcode to href's - while( stristr($text,'[url') ) - { - $urlpos = strpos( strtolower($text), '[url'); - $endopen = strpos($text,']',$urlpos); - if($endopen) - { - $url = '',''),$text); - return $text; -} - - -function ReplaceBBCode($text) -{ - global $objConfig; - - // BBCode: [b], [i], [u], [ul], [font] - $tags = explode(",",$objConfig->Get("BBTags")); - for($i = 0; $i < count($tags); $i++) - { - $text = ReplaceTag(strtoupper($tags[$i]),$text); - } - - // BBCode: [url href="xxx"]xxx[/url] - $text = ReplaceURL($text); - - // BBCode: [code]xxx[/code] - $text = preg_replace('/\[code[^\]]*\](.*)\[\/code[^\]]*\]/Ues', 'highlight_string( _unhtmlentities(\'$1\') , true);', $text); - - return $text; -} - -function GetMinValue($Table,$Field, $Where=NULL) -{ - $ret = 0; - $sql = "SELECT min($Field) as val FROM $Table "; - if(strlen($where)) - $sql .= "WHERE $Where"; - $ado = &GetADODBConnection(); - $rs = $ado->execute($sql); - if($rs) - $ret = (int)$rs->fields["val"]; - return $ret; -} - -function getmicrotime() -{ - list($usec, $sec) = explode(" ",microtime()); - return ((float)$usec + (float)$sec); -} - -function SetMissingDataErrors($f) -{ - global $FormError; - - $count = 0; - if(is_array($_POST)) - { - if(is_array($_POST["required"])) - { - foreach($_POST["required"] as $r) - { - $found = FALSE; - if(is_array($_FILES)) - { - if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE; - } - - if(!strlen(trim($_POST[$r])) && !$found) - { - $count++; - - if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year")) - $r = "dob"; - - $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : ''; - if(!strlen($tag)) - $tag = "lu_ferror_".$f."_".$r; - $FormError[$f][$r] = language($tag); - } - } - } - } - return $count; -} - -function makepassword($length=10) -{ - $pass_length=$length; - - $p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'); - $p2=array('a','e','i','o','u'); - $p3=array('1','2','3','4','5','6','7','8','9'); - $p4=array('(','&',')',';','%'); // if you need real strong stuff - - // how much elements in the array - // can be done with a array count but counting once here is faster - - $s1=21;// this is the count of $p1 - $s2=5; // this is the count of $p2 - $s3=9; // this is the count of $p3 - $s4=5; // this is the count of $p4 - - // possible readable combinations - - $c1='121'; // will be like 'bab' - $c2='212'; // will be like 'aba' - $c3='12'; // will be like 'ab' - $c4='3'; // will be just a number '1 to 9' if you dont like number delete the 3 -// $c5='4'; // uncomment to active the strong stuff - - $comb='4'; // the amount of combinations you made above (and did not comment out) - - - - for ($p=0;$p<$pass_length;) - { - mt_srand((double)microtime()*1000000); - $strpart=mt_rand(1,$comb); - // checking if the stringpart is not the same as the previous one - if($strpart<>$previous) - { - $pass_structure.=${'c'.$strpart}; - - // shortcutting the loop a bit - $p=$p+strlen(${'c'.$strpart}); - } - $previous=$strpart; - } - - - // generating the password from the structure defined in $pass_structure - for ($g=0;$g0) - $elapsed = getmicrotime() - $last; - - if(strlen($el)>10) - $el = substr($el,0,10); - $indent = str_repeat(" ",$LogLevel); - $text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT); - $LogData .= "$el:". round($elapsed,6).":$indent $text"; - $last = getmicrotime(); - if($writefile==TRUE && is_writable($g_LogFile)) - { - if(!$LogFile) - { - if(file_exists($g_LogFile)) - unlink($g_LogFile); - $LogFile=@fopen($g_LogFile,"w"); - } - if($LogFile) - { - fputs($LogFile,$LogData); - } - } - } -} - -function ValidEmail($email) -{ - if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email)) - { - return TRUE; - } - else - { - return FALSE; - } -} - -function language($phrase,$LangId=0) -{ - global $objSession, $objLanguageCache, $objLanguages; - - if($LangId==0) - $LangId = $objSession->Get("Language"); - - if($LangId==0) - $LangId = $objLanguages->GetPrimary(); - - $translation = $objLanguageCache->GetTranslation($phrase,$LangId); - - return $translation; -} - -function admin_language($phrase,$lang=0,$LinkMissing=FALSE) -{ - global $objSession, $objLanguageCache, $objLanguages; - - //echo "Language passed: $lang
    "; - - if($lang==0) - $lang = $objSession->Get("Language"); - - //echo "Language from session: $lang
    "; - - if($lang==0) - $lang = $objLanguages->GetPrimary(); - - //echo "Language after primary: $lang
    "; - //echo "Phrase: $phrase
    "; - $translation = $objLanguageCache->GetTranslation($phrase,$lang); - if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!") - { - $res = "$translation"; - return $res; - } - else - return $translation; -} - -function prompt_language($phrase,$lang=0) -{ - return admin_language($phrase,$lang,TRUE); -} - -function GetPrimaryTranslation($Phrase) -{ - global $objLanguages; - - $l = $objLanguages->GetPrimary(); - return language($Phrase,$l); -} - -function CategoryNameCount($ParentId,$Name) -{ - $cat_table = GetTablePrefix()."Category"; - $sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND "; - $sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')"; - - $ado = &GetADODBConnection(); - $rs = $ado->Execute($sql); - $ret = array(); - while($rs && !$rs->EOF) - { - $ret[] = $rs->fields["Name"]; - $rs->MoveNext(); - } - return $ret; -} - -function CategoryItemNameCount($CategoryId,$Table,$Field,$Name) -{ - $cat_table = GetTablePrefix()."CategoryItems"; - $sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) "; - $sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId"; - //echo $sql."
    \n "; - $ado = &GetADODBConnection(); - $rs = $ado->Execute($sql); - $ret = array(); - while($rs && !$rs->EOF) - { - $ret[] = $rs->fields[$Field]; - $rs->MoveNext(); - } - return $ret; -} - -function &GetItemCollection($ItemName) -{ - global $objItemTypes; - - if(is_numeric($ItemName)) - { - $item = $objItemTypes->GetItem($ItemName); - } - else - $item = $objItemTypes->GetTypeByName($ItemName); - if(is_object($item)) - { - $module = $item->Get("Module"); - $prefix = ModuleTagPrefix($module); - $func = $prefix."_ItemCollection"; - if(function_exists($func)) - { - $var =& $func(); - } - } - return $var; -} - - -function UpdateCategoryCount($ItemTypeName=0,$ListType=NULL) -{ - global $objCountCache, $objItemTypes; - - if(is_numeric($ItemTypeName)) - $item = $objItemTypes->GetItem($ItemTypeName); - else - $item = $objItemTypes->GetTypeByName($ItemTypeName); - - if(is_object($item)) - { - $ItemType = $item->Get("ItemType"); - - $sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType"; - if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType"; - $objCountCache->adodbConnection->Execute($sql); - } -} - -function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL) -{ -} - -function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL) -{ -} - -function GetTagCache($module,$tag,$attribs,$env) -{ - global $objSystemCache, $objSession, $objConfig; - - if($objConfig->Get("SystemTagCache")) - { - $name = $tag; - if(is_array($attribs)) - { - foreach($attribs as $n => $val) - { - $name .= "-".$val; - } - } - $CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList")); - } - else - $CachedValue=""; - return $CachedValue; -} - -function SaveTagCache($module, $tag, $attribs, $env, $newvalue) -{ - global $objSystemCache, $objSession, $objConfig; - - if($objConfig->Get("SystemTagCache")) - { - $name = $tag; - if(is_array($attribs)) - { - foreach($attribs as $a => $val) - { - $name .= "-".$val; - } - } - $objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList")); - } -} - -function DeleteTagCache($name,$extraparams, $env="") -{ - global $objSystemCache, $objConfig; - - if($objConfig->Get("SystemTagCache")) - { - $where = "Name LIKE '$name%".$extraparams."'"; - if(strlen($env)) - $where .= " AND Context LIKE $env"; - $objSystemCache->DeleteCachedItem($where); - } -} - -function ParseTagLibrary() -{ - $objTagList = new clsTagList(); - $objTagList->ParseInportalTags(); - unset($objTagList); -} - -function GetDateFormat($LangId=0) -{ - global $objLanguages; - - if(!$LangId) - $LangId= $objLanguages->GetPrimary(); - $l = $objLanguages->GetItem($LangId); - if(is_object($l)) - { - $fmt = $l->Get("DateFormat"); - } - else - $fmt = "m-d-Y"; - - if(isset($GLOBALS['FrontEnd'])&&$GLOBALS['FrontEnd']) - return $fmt; - return preg_replace('/y+/i','Y',$fmt); -} - -function GetTimeFormat($LangId=0) -{ - global $objLanguages; - - if(!$LangId) - $LangId= $objLanguages->GetPrimary(); - $l = $objLanguages->GetItem($LangId); - if(is_object($l)) - { - $fmt = $l->Get("TimeFormat"); - } - else - $fmt = "H:i:s"; - return $fmt; -} - -function LangDate($TimeStamp=NULL,$LangId=0) -{ - $fmt = GetDateFormat($LangId); - $ret = adodb_date($fmt,$TimeStamp); - return $ret; -} - -function LangTime($TimeStamp=NULL,$LangId=0) -{ - $fmt = GetTimeFormat($LangId); - $ret = adodb_date($fmt,$TimeStamp); - return $ret; -} - -function LangNumber($Num,$DecPlaces=NULL,$LangId=0) -{ - global $objLanguages; - - if(!$LangId) - $LangId= $objLanguages->GetPrimary(); - $l = $objLanguages->GetItem($LangId); - if(is_object($l)) - { - $ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep")); - } - else - $ret = $num; - - return $ret; -} - -function replacePngTags($x, $spacer="images/spacer.gif") -{ - global $rootURL,$pathtoroot; - - // make sure that we are only replacing for the Windows versions of Internet - // Explorer 5+, and not Opera identified as MSIE - $msie='/msie\s([5-9])\.?[0-9]*.*(win)/i'; - $opera='/opera\s+[0-9]+/i'; - if(!isset($_SERVER['HTTP_USER_AGENT']) || - !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) || - preg_match($opera,$_SERVER['HTTP_USER_AGENT'])) - return $x; - - // find all the png images in backgrounds - preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background); - for($i=0;$i|)/Uis',$x,$images); - while(list($imgnum,$v)=@each($images[0])){ - $original=$v; - $atts=''; $width=0; $height=0; - // If the size is defined by styles, find - preg_match_all('/style=".*(width: ([0-9]+))px.*'. - '(height: ([0-9]+))px.*"/Ui',$v,$arr2); - if(is_array($arr2) && count($arr2[0])){ - // size was defined by styles, get values - $width=$arr2[2][0]; - $height=$arr2[4][0]; - } - // size was not defined by styles, get values - preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2); - if(is_array($arr2) && count($arr2[0])){ - $width=$arr2[1][0]; - } - preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2); - if(is_array($arr2) && count($arr2[0])){ - $height=$arr2[1][0]; - } - preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2); - if(isset($arr2[1][0]) && !empty($arr2[1][0])) - $image=$arr2[1][0]; - else - $image=NULL; - - // We do this so that we can put our spacer.gif image in the same - // directory as the image - $tmp=split('[\\/]',$image); - array_pop($tmp); - $image_path=join('/',$tmp); - if(substr($image,0,strlen($rootURL))==$rootURL) - { - $path = str_replace($rootURL,$pathtoroot,$image); - } - else - { - $path = $pathtoroot."themes/telestial/$image"; - } -// echo "Sizing $path..
    \n"; -// echo "Full Tag: ".htmlentities($image)."
    \n"; - //if(!$height || !$width) - //{ - - $g = imagecreatefrompng($path); - if($g) - { - $height = imagesy($g); - $width = imagesx($g); - } - //} - if(strlen($image_path)) $image_path.='/'; - - // end quote is already supplied by originial src attribute - $replace_src_with=$spacer.'" style="width: '.$width. - 'px; height: '.$height.'px; filter: progid:DXImageTransform.'. - 'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='. - '\'scale\')'; - - // now create the new tag from the old - $new_tag=str_replace($image,$replace_src_with,$original); - - // now place the new tag into the content - $x=str_replace($original,$new_tag,$x); - } - return $x; -} - -function print_pre($str) -{ - // no comments here :) - echo '
    '.print_r($str, true).'
    '; -} - -function GetOptions($field) // by Alex -{ - // get dropdown values from custom field - $tmp =& new clsCustomField(); - - $tmp->LoadFromDatabase($field, 'FieldName'); - $tmp_values = $tmp->Get('ValueList'); - unset($tmp); - $tmp_values = explode(',', $tmp_values); - - foreach($tmp_values as $mixed) - { - $elem = explode('=', trim($mixed)); - $ret[ $elem[0] ] = $elem[1]; - } - return $ret; -} - -function ResetPage($module_prefix, $page_variable = 'p') -{ - // resets page in specific module when category is changed - global $objSession; - if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG - { - global $var_list, $SessionQueryString, $FrontEnd; - //if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"]; - $objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1)); - } - //echo "SID_RESET: ".$GLOBALS['var_list']["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')
    '; - $last_cat = $objSession->GetVariable('last_category'); - $prev_cat = $objSession->GetVariable('prev_category'); - //echo "Resetting Page [$prev_cat] -> [$last_cat]
    "; - - if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1; -} - -if( !function_exists('GetVar') ) -{ - /** - * @return string - * @param string $name - * @param bool $post_priority - * @desc Get's variable from http query - */ - function GetVar($name, $post_priority = false) - { - if(!$post_priority) // follow gpc_order in php.ini - return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false; - else // get variable from post 1stly if not found then from get - return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false ); - } -} - -function SetVar($VarName, $VarValue) -{ - $_REQUEST[$VarName] = $VarValue; - $_POST[$VarName] = $VarValue; -} - -function PassVar(&$source) -{ - // source array + any count of key names in passed array - $params = func_get_args(); - array_shift($params); - - if( count($params) ) - { - $ret = Array(); - foreach($params as $var_name) - if( isset($source[$var_name]) ) - $ret[] = $var_name.'='.$source[$var_name]; - $ret = '&'.implode('&', $ret); - } - return $ret; -} - -function GetSubmitVariable(&$array, $postfix) -{ - // gets edit status of module - // used in case if some modules share - // common action parsed by kernel parser, - // but each module uses own EditStatus variable - - $modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic'); - foreach($modules as $module => $prefix) - if( isset($array[$prefix.$postfix]) ) - return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]); - return false; -} - -function GetModuleByAction() -{ - $prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin'); - $action = GetVar('Action'); - if($action) - { - $module_prefix = explode('_', $action); - return $prefix2module[ $module_prefix[0] ]; - } - else - return false; -} - -function dir_size($dir) { - // calculates folder size based on filesizes inside it (recursively) - $totalsize=0; - if ($dirstream = @opendir($dir)) { - while (false !== ($filename = readdir($dirstream))) { - if ($filename!="." && $filename!="..") - { - if (is_file($dir."/".$filename)) - $totalsize+=filesize($dir."/".$filename); - - if (is_dir($dir."/".$filename)) - $totalsize+=dir_size($dir."/".$filename); - } - } - } - closedir($dirstream); - return $totalsize; -} - -function size($bytes) { - // shows formatted file/directory size - $types = Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes"); - $current = 0; - while ($bytes > 1024) { - $current++; - $bytes /= 1024; - } - return round($bytes,2)." ".language($types[$current]); -} - -function echod($str) -{ - // echo debug output - echo str_replace( Array('[',']'), Array('[', ']'), $str).'
    '; -} - - -function PrepareParams($source, $to_lower, $mapping) -{ - // prepare array with form values to use with item - $result = Array(); - foreach($to_lower as $field) - $result[ $field ] = $source[ strtolower($field) ]; - - if( is_array($mapping) ) - { - foreach($mapping as $field_from => $field_to) - $result[$field_to] = $source[$field_from]; - } - - return $result; -} - -function GetELT($field, $phrases = Array()) -{ - // returns FieldOptions equivalent in In-Portal - $ret = Array(); - foreach($phrases as $phrase) - $ret[] = admin_language($phrase); - $ret = "'".implode("','", $ret)."'"; - return 'ELT('.$field.','.$ret.')'; -} - -function GetModuleImgPath($module) -{ - global $rootURL, $admin; - return $rootURL.$module.'/'.$admin.'/images'; -} - -function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null) -{ - // each action postprocessing stuff from admin - if( !isset($_REQUEST[$StatusField]) ) return false; - - $list =& $GLOBALS[$ListObjectName]; - if( !is_object($list) ) $list = new $ListClass(); - $SFValue = $_REQUEST[$StatusField]; // status field value - switch($SFValue) - { - case 1: // User hit "Save" button - $list->CopyFromEditTable($IDField); - break; - case 2: // User hit "Cancel" button - $list->PurgeEditTable($IDField); - break; - } - if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue); - if($SFValue == 1 || $SFValue == 2) $list->Clear(); -} - -function GetElem(&$array, $index) -{ - // returns array element by index if - // such index exists - return isset($array[$index]) ? $array[$index] : false; -} - -function MakeHTMLTag($element, $attrib_prefix) -{ - $result = Array(); - $ap_length = strlen($attrib_prefix); - foreach($element->attributes as $attib_name => $attr_value) - if( substr($attib_name, $ap_length) == $ap_length ) - $result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"'; - return count($result) ? implode(' ', $result) : false; -} - -function GetImportScripts() -{ - // return currently installed import scripts - static $import_scripts = Array(); - if( count($import_scripts) == 0 ) - { - $sql = 'SELECT * FROM '.GetTablePrefix().'ImportScripts ORDER BY is_id'; - $db =&GetADODBConnection(); - $rs = $db->Execute($sql); - if( $rs && $rs->RecordCount() > 0 ) - { - while(!$rs->EOF) - { - $rec =& $rs->fields; - $import_scripts[] = Array( 'label' => $rec['is_label'], 'url' => $rec['is_script'], - 'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'], - 'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'], - 'module' => strtolower($rec['is_Module']) ); - $rs->MoveNext(); - } - } - else - { - $import_scripts = Array(); - } - } - return $import_scripts; -} - -function GetImportScript($id) -{ - $scripts = GetImportScripts(); - return isset($scripts[$id]) ? $scripts[$id] : false; -} -function GetNextTemplate($current_template) -{ - // used on front, returns next template to make - // redirect to - $dest = GetVar('dest', true); - if(!$dest) $dest = GetVar('DestTemplate', true); - return $dest ? $dest : $current_template; -} - - -// functions for dealign with enviroment variable construction -function GenerateModuleEnv($prefix, $var_list) -{ - // globalize module varible arrays - $main =& $GLOBALS[$prefix.'_var_list']; - $update =& $GLOBALS[$prefix.'_var_list_update']; - //echo "VAR: [$main]; VAR_UPDATE: [$update]
    "; - - // ensure that we have no empty values in enviroment variable - foreach($update as $vl_key => $vl_value) - if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]); - - // if update var count is zero, then do nothing - if(count($update) == 0) return ''; - - foreach($main as $vl_key => $vl_value) - if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]); - - $ret = Array(); - foreach($var_list as $var_name) - $ret[] = GetEnvVar($prefix, $var_name); - - return ':'.$prefix.implode('-',$ret); -} - -function GetEnvVar($prefix, $name) -{ - // get variable from template variable's list - // (used in module parsers to build env string) - $main =& $GLOBALS[$prefix.'_var_list']; - $update =& $GLOBALS[$prefix.'_var_list_update']; - - return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : ''); -} - -/** - * @return int - * @desc Checks for debug mode -*/ -function IsDebugMode() -{ - return defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 ? 1 : 0; -} - - -?> +\n") { + $resave = true; + } + $ln++; + $line = trim($line); + $line = eregi_replace(';[.]*','',$line); + if(strlen($line) > 0) { + //echo $line . " - "; + if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) { + //echo 'section'; + $section = substr($line,1,(strlen($line)-2)); + if ($parse_section) { + $retval[$section] = array(); + } + continue; + } elseif(eregi('=',$line)) { + //echo 'main element'; + list($key,$val) = explode(' = ',$line); + if (!$parse_section) { + $retval[trim($key)] = str_replace('"', '', $val); + } + else { + $retval[$section][trim($key)] = str_replace('"', '', $val); + } + } //end if + //echo '
    '; + } //end if + } //end foreach + if ($resave) { + $fp = fopen($file, "w"); + reset($contents); + fwrite($fp,'<'.'?'.'php die() ?'.">\n\n"); + foreach($contents as $line) fwrite($fp,"$line"); + fclose($fp); + } + + return $retval; +} + +/** + * @return object + * @desc Returns reference to database connection +*/ +function &GetADODBConnection() +{ + static $DB = null; + + global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode; + global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot; + + if( !isset($DB) && strlen($g_DBType) > 0 ) + { + $DB = ADONewConnection($g_DBType); + $connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName); + if(!$connected) die("Error connecting to database $g_DBHost
    \n"); + + $ADODB_CACHE_DIR = $pathtoroot."cache"; + $ADODB_FETCH_MODE = 2; + $ADODB_COUNTRECS = false; + $DB->debug = defined('ADODB_OUTP') ? 1 : 0; + $DB->cacheSecs = 3600; + $DB->Execute('SET SQL_BIG_SELECTS = 1'); + } + elseif( !strlen($g_DBType) ) + { + global $rootURL; + echo 'In-Portal is probably not installed, or configuration file is missing.
    '; + echo 'Please use the installation script to fix the problem.

    '; + if ( !preg_match('/admin/', __FILE__) ) $ins = 'admin/'; + + echo 'Go to installation script

    '; + flush(); + exit; + } + return $DB; +} + +function GetNextResourceId($Increment=1) +{ + $sql = "UPDATE ".GetTablePrefix()."IdGenerator SET lastid=lastid+".$Increment; + $adodbConnection = &GetADODBConnection(); + $adodbConnection->Execute($sql); + $rs = $adodbConnection->Execute("SELECT lastid FROM ".GetTablePrefix()."IdGenerator"); + $val = $rs->fields["lastid"]; + if(!$rs || $rs->EOF) + { + echo $adodbConnection->ErrorMsg(); + $sql = "INSERT INTO ".GetTablePrefix()."IdGenerator (lastid) VALUES ($Increment)"; + $adodbConnection->Execute($sql); + $val = 1; + } + $val = $val-($Increment-1); + return $val; +} + +function AddSlash($s) +{ + if(substr($s,-1) != "/") + { + return $s."/"; + } + else + return $s; +} + +function StripNewline($s) +{ + $bfound = false; + while (strlen($s)>0 && !$bfound) + { + if(ord(substr($s,-1))<32) + { + $s = substr($s,0,-1); + } + else + $bfound = true; + } + return $s; +} + +function DeleteElement($array, $indice) +{ + for($i=$indice;$i -1) + unset($haystack[$gotcha]); +} + +function TableCount($TableName, $where="",$JoinCats=1) +{ + $db = &GetADODBConnection(); + if(!$JoinCats) + { + $sql = "SELECT count(*) as TableCount FROM $TableName"; + } + else + $sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId"; + if(strlen($where)>0) + $sql .= " WHERE ".$where; + + $rs = $db->Execute($sql); + +// echo "SQL TABLE COUNT: ".$sql."
    \n"; + + $res = $rs->fields["TableCount"]; + return $res; +} + +Function QueryCount($sql) +{ + $sql = preg_replace('/SELECT(.*)FROM[ \n\r](.*)/is','SELECT COUNT(*) AS TableCount FROM $2', $sql); + $sql = preg_replace('/(.*)LIMIT(.*)/is','$1', $sql); + $sql = preg_replace('/(.*)ORDER BY(.*)/is','$1', $sql); + + $db =& GetADODBConnection(); + return $db->GetOne($sql); +} + +function GetPageCount($ItemsPerPage,$NumItems) +{ + if($ItemsPerPage==0 || $NumItems==0) + { + return 1; + } + $value = $NumItems/$ItemsPerPage; + return ceil($value); +} + + +/** + * @return string + * @desc Returns database table prefix entered while installation +*/ +function GetTablePrefix() +{ + global $g_TablePrefix; + + return $g_TablePrefix; +} + +function TableHasPrefix($t) +{ + $pre = GetTablePrefix(); + + if(strlen($pre)>0) + { + if(substr($t,0,strlen($pre))==$pre) + { + return TRUE; + } + else + return FALSE; + } + else + return TRUE; +} + +function AddTablePrefix($t) +{ + if(!TableHasPrefix($t)) + $t = GetTablePrefix().$t; + + return $t; +} + +function ThisDomain() +{ + global $objConfig, $g_Domain; + + if($objConfig->Get("DomainDetect")) + { + $d = $_SERVER['HTTP_HOST']; + } + else + $d = $g_Domain; + + return $d; +} + +function GetIndexUrl($secure=0) +{ + global $indexURL, $rootURL, $secureURL; + switch($secure) + { + case 0: + $ret = $indexURL; + break; + + case 1: + $ret = $secureURL."index.php"; + break; + + case 2: + $ret = $rootURL."index.php"; + break; + + default: + $ret = $i; + break; + } + return $ret; +} + +function GetLimitSQL($Page,$PerPage) +{ + if($Page<1) + $Page=1; + + if(is_numeric($PerPage)) + { + if($PerPage==0) + $PerPage = 20; + $Start = ($Page-1)*$PerPage; + $limit = "LIMIT ".$Start.",".$PerPage; + } + else + $limit = NULL; + return $limit; +} + +function filelist ($currentdir, $startdir=NULL,$ext=NULL) +{ + global $pathchar; + + //chdir ($currentdir); + + // remember where we started from + if (!$startdir) + { + $startdir = $currentdir; + } + + $d = @opendir($currentdir); + + $files = array(); + if(!$d) + return $files; + //list the files in the dir + while (false !== ($file = readdir($d))) + { + if ($file != ".." && $file != ".") + { + if (is_dir($currentdir."/".$file)) + { + // If $file is a directory take a look inside + $a = filelist ($currentdir."/".$file, $startdir,$ext); + if(is_array($a)) + $files = array_merge($files,$a); + } + else + { + if($ext!=NULL) + { + $extstr = stristr($file,".".$ext); + if(strlen($extstr)) + $files[] = $currentdir."/".$file; + } + else + $files[] = $currentdir.'/'.$file; + } + } + } + + closedir ($d); + + return $files; +} + +function DecimalToBin($dec,$WordLength=8) +{ + $bits = array(); + + $str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT); + for($i=$WordLength;$i>0;$i--) + { + $bits[$i-1] = (int)substr($str,$i-1,1); + } + return $bits; +} +/* +function inp_escape($in, $html_enable=0) +{ + $out = stripslashes($in); + $out = str_replace("\n", "\n^br^", $out); + if($html_enable==0) + { + $out=ereg_replace("<","<",$out); + $out=ereg_replace(">",">",$out); + $out=ereg_replace("\"",""",$out); + $out = str_replace("\n^br^", "\n
    ", $out); + } + else + $out = str_replace("\n^br^", "\n", $out); + $out=addslashes($out); + + return $out; +} +*/ +function inp_escape($var,$html=0) +{ + if($html)return $var; + if(is_array($var)) + foreach($var as $k=>$v) + $var[$k]=inp_escape($v); + else +// $var=htmlspecialchars($var,ENT_NOQUOTES); + $var=strtr($var,Array('<'=>'<','>'=>'>',)); + return $var; +} +function inp_striptags($var,$html=0) +{ + if($html)return $var; + if(is_array($var)) + foreach($var as $k=>$v) + $var[$k]=inp_striptags($v); + else + $var=strip_tags($var); + return $var; +} + +function inp_unescape($in) +{ + $out=stripslashes($in); + + return $out; +} + +function inp_textarea_unescape($in) +{ + return $in; + $out=stripslashes($in); + $out = str_replace("\n
    ", "\n", $out); + return $out; +} + +function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="") +{ + global $objConfig; + + if(!strlen($OpenTag)) + $OpenTag = ""; + if(!strlen($CloseTag)) + $CloseTag = ""; + + $r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE); + + foreach ($Keywords as $k) { + for ($i = 0; $i < count($r); $i++) { + if ($r[$i] == "<") { + $i++; continue; + } + $r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]); + } + } + return join("", $r); +} + +/* +function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="") +{ + global $objConfig; + + if(!strlen($OpenTag)) + $OpenTag = ""; + if(!strlen($CloseTag)) + $CloseTag = ""; + $ret = strip_tags($html); + + foreach ($Keywords as $k) + { + if(strlen($k)) + { + //$html = str_replace("<$k>", ":#:", $html); + //$html = str_replace("", ":##:", $html); + //$html = strip_tags($html); + if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html)) + //if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html)) + $ret = $html; + //$ret = str_replace(":#:", "<$k>", $ret); + //$ret = str_replace(":##:", "", $ret); + } + } + return $ret; +} +*/ +function ExtractDatePart($part,$datestamp) +{ + switch($part) + { + case "month": + if($datestamp<=0) + { + $ret = ""; + } + else + $ret = adodb_date("m",$datestamp); + break; + case "day": + if($datestamp<=0) + { + $ret = ""; + } + else + $ret = adodb_date("d", $datestamp); + break; + case "year": + if($datestamp<=0) + { + $ret = ""; + } + else + $ret = adodb_date("Y", $datestamp); + break; + case "time_24hr": + if($datestamp<=0) + { + $ret = ""; + } + else + $ret = adodb_date("H:i", $datestamp); + break; + case "time_12hr": + if($datestamp<=0) + { + $ret = ""; + } + else + $ret = adodb_date("g:i a",$datestamp); + break; + default: + $ret = adodb_date($part, $datestamp); + break; + } + return $ret; +} + +function GetLocalTime($TimeStamp,$TargetZone=NULL) +{ + if($TargetZone==NULL) + $TargetZone = $objConfig->Get("Config_Site_Time"); + $server = $objConfig->Get("Config_Server_Time"); + if($TargetZone!=$server) + { + $offset = ($server - $TargetZone) * -1; + $TimeStamp = $TimeStamp + (3600 * $offset); + } + return $TimeStamp; +} + +function _unhtmlentities ($string) +{ + $trans_tbl = get_html_translation_table (HTML_ENTITIES); + $trans_tbl = array_flip ($trans_tbl); + return strtr ($string, $trans_tbl); +} + +function getLastStr($hay, $need){ + $getLastStr = 0; + $pos = strpos($hay, $need); + if (is_int ($pos)){ //this is to decide whether it is "false" or "0" + while($pos) { + $getLastStr = $getLastStr + $pos + strlen($need); + $hay = substr ($hay , $pos + strlen($need)); + $pos = strpos($hay, $need); + } + return $getLastStr - strlen($need); + } else { + return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0". + } +} + +function ReplaceSingleTag($tag,$text) +{ + $tag = strtolower($tag); + $opentag = '['.$tag; + $closetag = '[/'.$tag.']'; + + if( stristr($text,$opentag) ) + { + $pos = strpos( strtolower($text), $opentag.' '); // tag has parameters + if($pos === false) + { + $pos = strpos( strtolower($text), $opentag.']'); + } + + $endopen = strpos($text,']',$pos); + $closepos = strpos( strtolower($text),$closetag,$pos); + + if($closepos) + { + $taglength = ($closepos - $endopen) + strlen($closetag); + $tagText = substr($text,$pos, $closepos + strlen($closetag) - $pos); + $innerText = substr($text,$endopen+1,$closepos - $endopen-1); + if($tag=="UL") + { + $innerText = str_replace("[*]","
  • ",$innerText); + } + $tagText = substr($tagText,1,($endopen - $pos)-1); + //echo "Matched $tagText
    \n"; + $tagText = "<".$tagText.">"; + $replace_text = $tagText.$innerText.""; + $text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag)); + return $text; + } + else + return $text; + } + else + return $text; +} + +function ReplaceTag($tag,$text) +{ + $new_text = ReplaceSingleTag($tag,$text); + + while($new_text != $text) + { + $text = $new_text; + $new_text = ReplaceSingleTag($tag,$text); + } + return $new_text; +} + +function ReplaceURL($text) +{ + + // process url bbtags without href parameter + $text = preg_replace('/\[url\]([^\]]*)\[\/url\]/U', '[url href="$1"]$1[/url]', $text); + + // change bbcode to href's + while( stristr($text,'[url') ) + { + $urlpos = strpos( strtolower($text), '[url'); + $endopen = strpos($text,']',$urlpos); + if($endopen) + { + $url = '',''),$text); + return $text; +} + + +function ReplaceBBCode($text) +{ + global $objConfig; + + // BBCode: [b], [i], [u], [ul], [font] + $tags = explode(",",$objConfig->Get("BBTags")); + for($i = 0; $i < count($tags); $i++) + { + $text = ReplaceTag(strtoupper($tags[$i]),$text); + } + + // BBCode: [url href="xxx"]xxx[/url] + $text = ReplaceURL($text); + + // BBCode: [code]xxx[/code] + $text = preg_replace('/\[code[^\]]*\](.*)\[\/code[^\]]*\]/Ues', 'highlight_string( _unhtmlentities(\'$1\') , true);', $text); + + return $text; +} + +function GetMinValue($Table,$Field, $Where=NULL) +{ + $ret = 0; + $sql = "SELECT min($Field) as val FROM $Table "; + if(strlen($where)) + $sql .= "WHERE $Where"; + $ado = &GetADODBConnection(); + $rs = $ado->execute($sql); + if($rs) + $ret = (int)$rs->fields["val"]; + return $ret; +} + +function getmicrotime() +{ + list($usec, $sec) = explode(" ",microtime()); + return ((float)$usec + (float)$sec); +} + +function SetMissingDataErrors($f) +{ + global $FormError; + + $count = 0; + if(is_array($_POST)) + { + if(is_array($_POST["required"])) + { + foreach($_POST["required"] as $r) + { + $found = FALSE; + if(is_array($_FILES)) + { + if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE; + } + + if(!strlen(trim($_POST[$r])) && !$found) + { + $count++; + + if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year")) + $r = "dob"; + + $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : ''; + if(!strlen($tag)) + $tag = "lu_ferror_".$f."_".$r; + $FormError[$f][$r] = language($tag); + } + } + } + } + return $count; +} + +function makepassword($length=10) +{ + $pass_length=$length; + + $p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'); + $p2=array('a','e','i','o','u'); + $p3=array('1','2','3','4','5','6','7','8','9'); + $p4=array('(','&',')',';','%'); // if you need real strong stuff + + // how much elements in the array + // can be done with a array count but counting once here is faster + + $s1=21;// this is the count of $p1 + $s2=5; // this is the count of $p2 + $s3=9; // this is the count of $p3 + $s4=5; // this is the count of $p4 + + // possible readable combinations + + $c1='121'; // will be like 'bab' + $c2='212'; // will be like 'aba' + $c3='12'; // will be like 'ab' + $c4='3'; // will be just a number '1 to 9' if you dont like number delete the 3 +// $c5='4'; // uncomment to active the strong stuff + + $comb='4'; // the amount of combinations you made above (and did not comment out) + + + + for ($p=0;$p<$pass_length;) + { + mt_srand((double)microtime()*1000000); + $strpart=mt_rand(1,$comb); + // checking if the stringpart is not the same as the previous one + if($strpart<>$previous) + { + $pass_structure.=${'c'.$strpart}; + + // shortcutting the loop a bit + $p=$p+strlen(${'c'.$strpart}); + } + $previous=$strpart; + } + + + // generating the password from the structure defined in $pass_structure + for ($g=0;$g0) + $elapsed = getmicrotime() - $last; + + if(strlen($el)>10) + $el = substr($el,0,10); + $indent = str_repeat(" ",$LogLevel); + $text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT); + $LogData .= "$el:". round($elapsed,6).":$indent $text"; + $last = getmicrotime(); + if($writefile==TRUE && is_writable($g_LogFile)) + { + if(!$LogFile) + { + if(file_exists($g_LogFile)) + unlink($g_LogFile); + $LogFile=@fopen($g_LogFile,"w"); + } + if($LogFile) + { + fputs($LogFile,$LogData); + } + } + } +} + +function ValidEmail($email) +{ + if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email)) + { + return TRUE; + } + else + { + return FALSE; + } +} + +function language($phrase,$LangId=0) +{ + global $objSession, $objLanguageCache, $objLanguages; + + if($LangId==0) + $LangId = $objSession->Get("Language"); + + if($LangId==0) + $LangId = $objLanguages->GetPrimary(); + + $translation = $objLanguageCache->GetTranslation($phrase,$LangId); + + return $translation; +} + +function admin_language($phrase,$lang=0,$LinkMissing=FALSE) +{ + global $objSession, $objLanguageCache, $objLanguages; + + //echo "Language passed: $lang
    "; + + if($lang==0) + $lang = $objSession->Get("Language"); + + //echo "Language from session: $lang
    "; + + if($lang==0) + $lang = $objLanguages->GetPrimary(); + + //echo "Language after primary: $lang
    "; + //echo "Phrase: $phrase
    "; + $translation = $objLanguageCache->GetTranslation($phrase,$lang); + if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!") + { + $res = "$translation"; + return $res; + } + else + return $translation; +} + +function prompt_language($phrase,$lang=0) +{ + return admin_language($phrase,$lang,TRUE); +} + +function GetPrimaryTranslation($Phrase) +{ + global $objLanguages; + + $l = $objLanguages->GetPrimary(); + return language($Phrase,$l); +} + +function CategoryNameCount($ParentId,$Name) +{ + $cat_table = GetTablePrefix()."Category"; + $sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND "; + $sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')"; + + $ado = &GetADODBConnection(); + $rs = $ado->Execute($sql); + $ret = array(); + while($rs && !$rs->EOF) + { + $ret[] = $rs->fields["Name"]; + $rs->MoveNext(); + } + return $ret; +} + +function CategoryItemNameCount($CategoryId,$Table,$Field,$Name) +{ + $cat_table = GetTablePrefix()."CategoryItems"; + $sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) "; + $sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId"; + //echo $sql."
    \n "; + $ado = &GetADODBConnection(); + $rs = $ado->Execute($sql); + $ret = array(); + while($rs && !$rs->EOF) + { + $ret[] = $rs->fields[$Field]; + $rs->MoveNext(); + } + return $ret; +} + +function &GetItemCollection($ItemName) +{ + global $objItemTypes; + + if(is_numeric($ItemName)) + { + $item = $objItemTypes->GetItem($ItemName); + } + else + $item = $objItemTypes->GetTypeByName($ItemName); + if(is_object($item)) + { + $module = $item->Get("Module"); + $prefix = ModuleTagPrefix($module); + $func = $prefix."_ItemCollection"; + if(function_exists($func)) + { + $var =& $func(); + } + } + return $var; +} + + +function UpdateCategoryCount($ItemTypeName=0,$ListType=NULL) +{ + global $objCountCache, $objItemTypes; + + if(is_numeric($ItemTypeName)) + $item = $objItemTypes->GetItem($ItemTypeName); + else + $item = $objItemTypes->GetTypeByName($ItemTypeName); + + if(is_object($item)) + { + $ItemType = $item->Get("ItemType"); + + $sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType"; + if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType"; + $objCountCache->adodbConnection->Execute($sql); + } +} + +function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL) +{ +} + +function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL) +{ +} + +function GetTagCache($module,$tag,$attribs,$env) +{ + global $objSystemCache, $objSession, $objConfig; + + if($objConfig->Get("SystemTagCache")) + { + $name = $tag; + if(is_array($attribs)) + { + foreach($attribs as $n => $val) + { + $name .= "-".$val; + } + } + $CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList")); + } + else + $CachedValue=""; + return $CachedValue; +} + +function SaveTagCache($module, $tag, $attribs, $env, $newvalue) +{ + global $objSystemCache, $objSession, $objConfig; + + if($objConfig->Get("SystemTagCache")) + { + $name = $tag; + if(is_array($attribs)) + { + foreach($attribs as $a => $val) + { + $name .= "-".$val; + } + } + $objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList")); + } +} + +function DeleteTagCache($name,$extraparams, $env="") +{ + global $objSystemCache, $objConfig; + + if($objConfig->Get("SystemTagCache")) + { + $where = "Name LIKE '$name%".$extraparams."'"; + if(strlen($env)) + $where .= " AND Context LIKE $env"; + $objSystemCache->DeleteCachedItem($where); + } +} + +function ParseTagLibrary() +{ + $objTagList = new clsTagList(); + $objTagList->ParseInportalTags(); + unset($objTagList); +} + +function GetDateFormat($LangId=0) +{ + global $objLanguages; + + if(!$LangId) + $LangId= $objLanguages->GetPrimary(); + $l = $objLanguages->GetItem($LangId); + if(is_object($l)) + { + $fmt = $l->Get("DateFormat"); + } + else + $fmt = "m-d-Y"; + + if(isset($GLOBALS['FrontEnd'])&&$GLOBALS['FrontEnd']) + return $fmt; + return preg_replace('/y+/i','Y',$fmt); +} + +function GetTimeFormat($LangId=0) +{ + global $objLanguages; + + if(!$LangId) + $LangId= $objLanguages->GetPrimary(); + $l = $objLanguages->GetItem($LangId); + if(is_object($l)) + { + $fmt = $l->Get("TimeFormat"); + } + else + $fmt = "H:i:s"; + return $fmt; +} + +function LangDate($TimeStamp=NULL,$LangId=0) +{ + $fmt = GetDateFormat($LangId); + $ret = adodb_date($fmt,$TimeStamp); + return $ret; +} + +function LangTime($TimeStamp=NULL,$LangId=0) +{ + $fmt = GetTimeFormat($LangId); + $ret = adodb_date($fmt,$TimeStamp); + return $ret; +} + +function LangNumber($Num,$DecPlaces=NULL,$LangId=0) +{ + global $objLanguages; + + if(!$LangId) + $LangId= $objLanguages->GetPrimary(); + $l = $objLanguages->GetItem($LangId); + if(is_object($l)) + { + $ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep")); + } + else + $ret = $num; + + return $ret; +} + +function replacePngTags($x, $spacer="images/spacer.gif") +{ + global $rootURL,$pathtoroot; + + // make sure that we are only replacing for the Windows versions of Internet + // Explorer 5+, and not Opera identified as MSIE + $msie='/msie\s([5-9])\.?[0-9]*.*(win)/i'; + $opera='/opera\s+[0-9]+/i'; + if(!isset($_SERVER['HTTP_USER_AGENT']) || + !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) || + preg_match($opera,$_SERVER['HTTP_USER_AGENT'])) + return $x; + + // find all the png images in backgrounds + preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background); + for($i=0;$i|)/Uis',$x,$images); + while(list($imgnum,$v)=@each($images[0])){ + $original=$v; + $atts=''; $width=0; $height=0; + // If the size is defined by styles, find + preg_match_all('/style=".*(width: ([0-9]+))px.*'. + '(height: ([0-9]+))px.*"/Ui',$v,$arr2); + if(is_array($arr2) && count($arr2[0])){ + // size was defined by styles, get values + $width=$arr2[2][0]; + $height=$arr2[4][0]; + } + // size was not defined by styles, get values + preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2); + if(is_array($arr2) && count($arr2[0])){ + $width=$arr2[1][0]; + } + preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2); + if(is_array($arr2) && count($arr2[0])){ + $height=$arr2[1][0]; + } + preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2); + if(isset($arr2[1][0]) && !empty($arr2[1][0])) + $image=$arr2[1][0]; + else + $image=NULL; + + // We do this so that we can put our spacer.gif image in the same + // directory as the image + $tmp=split('[\\/]',$image); + array_pop($tmp); + $image_path=join('/',$tmp); + if(substr($image,0,strlen($rootURL))==$rootURL) + { + $path = str_replace($rootURL,$pathtoroot,$image); + } + else + { + $path = $pathtoroot."themes/telestial/$image"; + } +// echo "Sizing $path..
    \n"; +// echo "Full Tag: ".htmlentities($image)."
    \n"; + //if(!$height || !$width) + //{ + + $g = imagecreatefrompng($path); + if($g) + { + $height = imagesy($g); + $width = imagesx($g); + } + //} + if(strlen($image_path)) $image_path.='/'; + + // end quote is already supplied by originial src attribute + $replace_src_with=$spacer.'" style="width: '.$width. + 'px; height: '.$height.'px; filter: progid:DXImageTransform.'. + 'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='. + '\'scale\')'; + + // now create the new tag from the old + $new_tag=str_replace($image,$replace_src_with,$original); + + // now place the new tag into the content + $x=str_replace($original,$new_tag,$x); + } + return $x; +} + +function print_pre($str) +{ + // no comments here :) + echo '
    '.print_r($str, true).'
    '; +} + +function GetOptions($field) // by Alex +{ + // get dropdown values from custom field + $tmp =& new clsCustomField(); + + $tmp->LoadFromDatabase($field, 'FieldName'); + $tmp_values = $tmp->Get('ValueList'); + unset($tmp); + $tmp_values = explode(',', $tmp_values); + + foreach($tmp_values as $mixed) + { + $elem = explode('=', trim($mixed)); + $ret[ $elem[0] ] = $elem[1]; + } + return $ret; +} + +function ResetPage($module_prefix, $page_variable = 'p') +{ + // resets page in specific module when category is changed + global $objSession; + if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG + { + global $var_list, $SessionQueryString, $FrontEnd; + //if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"]; + $objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1)); + } + //echo "SID_RESET: ".$GLOBALS['var_list']["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')
    '; + $last_cat = $objSession->GetVariable('last_category'); + $prev_cat = $objSession->GetVariable('prev_category'); + //echo "Resetting Page [$prev_cat] -> [$last_cat]
    "; + + if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1; +} + +if( !function_exists('GetVar') ) +{ + /** + * @return string + * @param string $name + * @param bool $post_priority + * @desc Get's variable from http query + */ + function GetVar($name, $post_priority = false) + { + if(!$post_priority) // follow gpc_order in php.ini + return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false; + else // get variable from post 1stly if not found then from get + return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false ); + } +} + +function SetVar($VarName, $VarValue) +{ + $_REQUEST[$VarName] = $VarValue; + $_POST[$VarName] = $VarValue; +} + +function PassVar(&$source) +{ + // source array + any count of key names in passed array + $params = func_get_args(); + array_shift($params); + + if( count($params) ) + { + $ret = Array(); + foreach($params as $var_name) + if( isset($source[$var_name]) ) + $ret[] = $var_name.'='.$source[$var_name]; + $ret = '&'.implode('&', $ret); + } + return $ret; +} + +function GetSubmitVariable(&$array, $postfix) +{ + // gets edit status of module + // used in case if some modules share + // common action parsed by kernel parser, + // but each module uses own EditStatus variable + + $modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic'); + foreach($modules as $module => $prefix) + if( isset($array[$prefix.$postfix]) ) + return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]); + return false; +} + +function GetModuleByAction() +{ + $prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin'); + $action = GetVar('Action'); + if($action) + { + $module_prefix = explode('_', $action); + return $prefix2module[ $module_prefix[0] ]; + } + else + return false; +} + +function dir_size($dir) { + // calculates folder size based on filesizes inside it (recursively) + $totalsize=0; + if ($dirstream = @opendir($dir)) { + while (false !== ($filename = readdir($dirstream))) { + if ($filename!="." && $filename!="..") + { + if (is_file($dir."/".$filename)) + $totalsize+=filesize($dir."/".$filename); + + if (is_dir($dir."/".$filename)) + $totalsize+=dir_size($dir."/".$filename); + } + } + } + closedir($dirstream); + return $totalsize; +} + +function size($bytes) { + // shows formatted file/directory size + $types = Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes"); + $current = 0; + while ($bytes > 1024) { + $current++; + $bytes /= 1024; + } + return round($bytes,2)." ".language($types[$current]); +} + +function echod($str) +{ + // echo debug output + echo str_replace( Array('[',']'), Array('[', ']'), $str).'
    '; +} + + +function PrepareParams($source, $to_lower, $mapping) +{ + // prepare array with form values to use with item + $result = Array(); + foreach($to_lower as $field) + $result[ $field ] = $source[ strtolower($field) ]; + + if( is_array($mapping) ) + { + foreach($mapping as $field_from => $field_to) + $result[$field_to] = $source[$field_from]; + } + + return $result; +} + +function GetELT($field, $phrases = Array()) +{ + // returns FieldOptions equivalent in In-Portal + $ret = Array(); + foreach($phrases as $phrase) + $ret[] = admin_language($phrase); + $ret = "'".implode("','", $ret)."'"; + return 'ELT('.$field.','.$ret.')'; +} + +function GetModuleImgPath($module) +{ + global $rootURL, $admin; + return $rootURL.$module.'/'.$admin.'/images'; +} + +function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null) +{ + // each action postprocessing stuff from admin + if( !isset($_REQUEST[$StatusField]) ) return false; + + $list =& $GLOBALS[$ListObjectName]; + if( !is_object($list) ) $list = new $ListClass(); + $SFValue = $_REQUEST[$StatusField]; // status field value + switch($SFValue) + { + case 1: // User hit "Save" button + $list->CopyFromEditTable($IDField); + break; + case 2: // User hit "Cancel" button + $list->PurgeEditTable($IDField); + break; + } + if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue); + if($SFValue == 1 || $SFValue == 2) $list->Clear(); +} + +function GetElem(&$array, $index) +{ + // returns array element by index if + // such index exists + return isset($array[$index]) ? $array[$index] : false; +} + +function MakeHTMLTag($element, $attrib_prefix) +{ + $result = Array(); + $ap_length = strlen($attrib_prefix); + foreach($element->attributes as $attib_name => $attr_value) + if( substr($attib_name, $ap_length) == $ap_length ) + $result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"'; + return count($result) ? implode(' ', $result) : false; +} + +function GetImportScripts() +{ + // return currently installed import scripts + static $import_scripts = Array(); + if( count($import_scripts) == 0 ) + { + $sql = 'SELECT * FROM '.GetTablePrefix().'ImportScripts ORDER BY is_id'; + $db =&GetADODBConnection(); + $rs = $db->Execute($sql); + if( $rs && $rs->RecordCount() > 0 ) + { + while(!$rs->EOF) + { + $rec =& $rs->fields; + $import_scripts[] = Array( 'label' => $rec['is_label'], 'url' => $rec['is_script'], + 'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'], + 'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'], + 'module' => strtolower($rec['is_Module']) ); + $rs->MoveNext(); + } + } + else + { + $import_scripts = Array(); + } + } + return $import_scripts; +} + +function GetImportScript($id) +{ + $scripts = GetImportScripts(); + return isset($scripts[$id]) ? $scripts[$id] : false; +} +function GetNextTemplate($current_template) +{ + // used on front, returns next template to make + // redirect to + $dest = GetVar('dest', true); + if(!$dest) $dest = GetVar('DestTemplate', true); + return $dest ? $dest : $current_template; +} + + +// functions for dealign with enviroment variable construction +function GenerateModuleEnv($prefix, $var_list) +{ + // globalize module varible arrays + $main =& $GLOBALS[$prefix.'_var_list']; + $update =& $GLOBALS[$prefix.'_var_list_update']; + //echo "VAR: [$main]; VAR_UPDATE: [$update]
    "; + + // ensure that we have no empty values in enviroment variable + foreach($update as $vl_key => $vl_value) + if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]); + + // if update var count is zero, then do nothing + if(count($update) == 0) return ''; + + foreach($main as $vl_key => $vl_value) + if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]); + + $ret = Array(); + foreach($var_list as $var_name) + $ret[] = GetEnvVar($prefix, $var_name); + + return ':'.$prefix.implode('-',$ret); +} + +function GetEnvVar($prefix, $name) +{ + // get variable from template variable's list + // (used in module parsers to build env string) + $main =& $GLOBALS[$prefix.'_var_list']; + $update =& $GLOBALS[$prefix.'_var_list_update']; + + return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : ''); +} + +/** + * @return int + * @desc Checks for debug mode +*/ +function IsDebugMode() +{ + return defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 ? 1 : 0; +} + + +?> Index: trunk/kernel/parser.php =================================================================== diff -u -N -r640 -r642 --- trunk/kernel/parser.php (.../parser.php) (revision 640) +++ trunk/kernel/parser.php (.../parser.php) (revision 642) @@ -1,3416 +1,3416 @@ -";print_r($pieces);echo ""; - $m_var_list["cat"] = $pieces[0]; - $m_var_list["p"] = $pieces[1]; - $objCatList->Page = $m_var_list["p"]; - - $m_var_list["lang"] = $pieces[2]; - $m_var_list["theme"] = $pieces[3]; - } - else - { - $m_var_list["cat"]=0; - $m_var_list["p"] = 1; - $m_var_list["lang"] = $objLanguages->GetPrimary(); - $m_var_list["theme"]= $objThemes->GetPrimaryTheme(); - } -} - -function m_BuildEnv() -{ - global $m_var_list, $m_var_list_update; - $module_vars = Array('cat','p','lang','theme'); - $ret = GenerateModuleEnv('m', $module_vars); - if( isset($GLOBALS['m_var_list_update']['cat']) ) unset($GLOBALS['m_var_list_update']['cat']); - return $ret; -} - -function m_GetVar($name) -{ - // get variable from template variable's list - global $m_var_list, $m_var_list_update; - return isset($m_var_list_update[$name]) ? $m_var_list_update[$name] : $m_var_list[$name]; -} - -function &LoadRelatedItems(&$Relations,&$RelatedItems,$ResourceId) -{ - global $objItemTypes; - - if(!is_object($Relations)) - { - $Relations = new clsRelationshipList(); - } - //$Relations->debuglevel = 2; - if ($ResourceId != '') { - $sql = sprintf("SELECT RelationshipId, Type, Enabled, Priority, - IF(TargetId = %1\$s, TargetId, SourceId) AS SourceId, - IF(TargetId = %1\$s, SourceId, TargetId) AS TargetId, - IF(TargetId = %1\$s, TargetType, SourceType) AS SourceType, - IF(TargetId = %1\$s, SourceType, TargetType) AS TargetType - FROM %%s", $ResourceId); - - $where = "((SourceId=$ResourceId) OR (TargetId=$ResourceId AND Type=1)) AND Enabled=1"; - $Relations->LoadRelated($where,"",$sql); - $ids = array(); - if($Relations->NumItems()>0) - { - foreach($Relations->Items as $r) - { - if($r->Get("SourceId")==$ResourceId) - { - $ids[$r->Get("TargetType")][] = $r->Get("TargetId"); - } - if($r->Get("TargetId")==$ResourceId && $r->Get("Type")==1) - { - $ids[$r->Get("SourceType")][] = $ResourceId; - } - } - foreach($ids as $ItemType=>$idlist) - { - $Item =& $objItemTypes->GetItem($ItemType); - $table = GetTablePrefix().$Item->Get("SourceTable"); - if($ItemType!=1) - { - $cattable = GetTablePrefix()."CategoryItems"; - $sql = "SELECT *,CategoryId FROM $table INNER JOIN $cattable ON "; - $sql .=" ($table.ResourceId=$cattable.ItemResourceId) WHERE $table.Status=1 AND PrimaryCat=1 "; - $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")"; - } - else - { - $sql = "SELECT *,CategoryId FROM $table "; - $sql .="WHERE $table.Status=1 "; - $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")"; - } - // echo $sql."
    \n"; - $RelatedItems->Query_Item($sql,-1,-1,$ItemType); - } - } - } -} - - -/* - @description: Inserts the html from a remote source - @attrib: _url:: Remote URL to include - @attrib: _StartPos:: Numeric start point of text to include, or string match - @attrib: _EndPos:: Numeric end point of text to include, or string match - @example: -*/ -function m_insert_url($attribs=array()) -{ - global $pathtoroot; - - $url = $attribs["_url"]; - $StartPos = $attribs["_startpos"]; - $EndPos = $attribs["_endpos"]; - - $socket = new Socket($url,0,NULL); - $txt = $socket->socket_read_all(); - $lines = explode("\n",$txt); - $txt = substr($txt,strpos($txt,"<")); - $tmp = strtolower($txt); - $bodypos = strpos($tmp,"0) - { - $head = substr($txt,0,$bodypos-1); - $body = substr($txt,$bodypos); - if(substr($tmp,-7)=="") - $body = substr($body,0,-7); - } - else - $body = $txt; - if(strlen($body)) - { - if(strlen($StartPos)) - { - if(!is_numeric($StartPos)) - { - $start = strpos($body,$StartPos); - } - else - $start = (int)$StartPos; - } - else - $start = 0; - if(strlen($EndPos)) - { - if(!is_numeric($EndPos)) - { - $end = strpos($body,$EndPos,$start) + strlen($EndPos); - } - else - $end = (int)$EndPos; - } - else - $end = NULL; - $o = substr($body,$start,$end-$start); - } - return $o; -} - -/* - @description: Displays a template depending on the login status of the user - @attrib: _logintemplate:tpl: template to display when the user is NOT logged in - @attrib: _LoggedinTemplate:tpl: template to display when the user is logged in - @example: -*/ -function m_loginbox($attribs = array()) -{ - global $var_list, $objSession, $objUsers, $objTemplate; - - $userid = $objSession->Get("PortalUserId"); - $groupid = $objSession->Get("GroupId"); - if ($userid == 0) - { - if (strlen($attribs["_logintemplate"])) - $t = $objTemplate->ParseTemplate($attribs["_logintemplate"]); - return $t; - } - else - { - $user =& $objUsers->GetItem($userid); - if (strlen($attribs["_loggedintemplate"])) - $t = $user->ParseTemplate($attribs["_loggedintemplate"]); - return $t; - } -} -/* - @description: result of suggest site action -*/ -function m_suggest_result() -{ - global $suggest_result; - - return $suggest_result; -} - -/* - @description: result of subscribe to mailing list action -*/ -function m_subscribe_result() -{ - global $SubscribeResult; - - if(strlen($SubscribeResult)) - return language($SubscribeResult); - return ""; -} - -/* - @description: email address of user subscribing to mailing list -*/ -function m_subscribe_address() -{ - global $SubscribeAddress; - - if(strlen($SubscribeAddress)) - return $SubscribeAddress; - return ""; -} - -/* - @description: Error message of subscribe to mailing list action -*/ -function m_subscribe_error() -{ - global $SubscribeError; - - if(strlen($SubscribeError)) - return language($SubscribeError); - return ""; -} - - -/* - @description: Displays a prompt for a form field - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _LangText:lang: Language var to use for field label - @attrib: _plaintext:: Plain text to use for field label (langtext is used by default if both are set) - @attrib: _Template:tpl: template used to display the field label (if not set "" is used - @attrib: _ErrorTemplate:tpl: If the field is in an error state (ie missing input) this template is used. Will default to the normal template if not set -*/ -function m_form_prompt($attribs = array()) -{ - global $FormError, $objTemplate, $objConfig; - - $form = strtolower($attribs["_form"]); - $field = strtolower($attribs["_field"]); - - if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto")) - { - $o = ""; - } - else - { - $t = $attribs["_template"]; - if(!strlen($t)) - { - $templateText = ""; - } - $e = $attribs["_errortemplate"]; - if(!strlen($e)) - $e = $t; - if(strlen($attribs["_langtext"])) - { - $txt = language($attribs["_langtext"]); - } - else - $txt = $attribs["_plaintext"]; - - if (strtolower($field) == "dob") - { - if (isset($FormError[strtolower($form)][strtolower($field."_day")]) || isset($FormError[strtolower($form)][strtolower($field."_month")]) || isset($FormError[strtolower($form)][strtolower($field."_year")])) - $rawtext = $objTemplate->GetTemplate($e, true); - } - - if(isset($FormError[strtolower($form)][strtolower($field)])) - { - $rawtext = $objTemplate->GetTemplate($e); - } - elseif (strlen($t)) - $rawtext = $objTemplate->GetTemplate($t); - - if(is_object($rawtext)) - { - $src = $rawtext->source; - $o = str_replace("",$txt, $src); - } - else - $o = str_replace("", $txt, $templateText); - - } - return $o; -} - -/* - @description: Returns text if system is configured to use auto-generated passwords - @attrib:_LangText:lang:Language tag to return - @attrib:_PlainText::Plain text to return (_LangText takes precedece) - @attrib:_Value:bool:Auto Password setting value to match -*/ -function m_autopassword($attribs = array()) -{ - global $objConfig; - if($attribs["_value"]=="true" || $attribs["_value"]==1) - { - $IsAuto = $objConfig->Get("User_Password_Auto"); - } - else - { - $IsAuto = !$objConfig->Get("User_Password_Auto"); - } - - if($IsAuto) - { - if(strlen($attribs["_langtext"])) - { - $ret = language($attribs["_langtext"]); - } - else - $ret = $attribs["_plaintext"]; - if(!$ret) - return "true"; - } - return $ret; -} - -/* - @description: checks if field specified is equals to value specified - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _Value:: Field value to compare to - @example: true -*/ -function m_field_equals($attribs = array()) -{ - global $FormValues; - //print_pre($attribs); - $form = $attribs["_form"]; - $field = $attribs["_field"]; - if(isset($_POST[$field])) - { - $value = $_POST[$field]; - } - else - $value = $FormValues[$form][$field]; - //echo "POST_VALUE: [$value] vs USER_VALUE: [".$attribs['_value']."]
    "; - return $value == $attribs['_value'] ? 1 : ''; -} - -/* - @description: creates an INPUT tag for a form field. All extra attributes are passed to the INPUT tag - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _ForgetValue:bool: if true, forget value - @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting - @example: -*/ -function m_form_input($attribs = array()) -{ - global $FormValues, $objConfig; - - $html_attribs = ExtraAttributes($attribs); - $form = $attribs["_form"]; - $field = strtolower($attribs["_field"]); - if(isset($_POST[$field]) && $attribs['_forgetvalue'] != 1) - { - $value = $_POST[$field]; - } - else { - if ($attribs['_forgetvalue'] != 1) { - $value = $FormValues[$form][$field]; - } - } - //echo $form.".".$field."=".$value." = ".$attribs['_forgetvalue']."
    \n"; - if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto")) - { - $ret = ""; - } - else - { - $ret = ""; - if($attribs["_required"]) - $ret .= ""; - if($attribs["_custom"]) - $ret .= ""; - } - return $ret; -} - -/* - @description: creates an INPUT tag (type checkbox) for a form field. All extra attributes are passed to the INPUT tag - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _Value:bool: If true, the radio button is CHECKED - @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting - @attrib: _Custom:bool: If set, handled as a custom field - @example: -*/ -function m_form_checkbox($attribs = array()) -{ - global $FormValues, $objConfig; - - $html_attribs = ExtraAttributes($attribs); - $form = $attribs["_form"]; - $field = strtolower($attribs["_field"]); - if(isset($_POST[$field])) - { - $value = (int)$_POST[$field]; - if($value==1) - $checked = " CHECKED"; - } - else - { - $value = (int)$FormValues[$form][$field]; - if($value==1) - $checked=" CHECKED"; - } - //echo $form.".".$field."=".$value."
    \n"; - $ret = ""; - if($attribs["_required"]) - $ret .= ""; - if($attribs["_custom"]) - $ret .= ""; - - return $ret; -} - -/* - @description: creates an INPUT tag (type radio) for a form field. All extra attributes are passed to the INPUT tag - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _Value:: Value assigned to radio button. If the form field value matches this attribute, the radio button is CHECKED - @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting - @attrib: _Custom:bool: If set, handled as a custom field - @example: -*/ -function m_form_radio($attribs = array()) -{ - global $FormValues, $objConfig; - - $html_attribs = ExtraAttributes($attribs); - $form = $attribs["_form"]; - $field = strtolower($attribs["_field"]); - $val = $attribs["_value"]; - if(isset($_POST[$field])) - { - $value = (int)$_POST[$field]; - if($value==1) - $checked = " CHECKED"; - } - else - { - $value = (int)$FormValues[$form][$field]; - if($value==$val) - $checked=" CHECKED"; - } - //echo $form.".".$field."=".$value."
    \n"; - $ret = ""; - if($attribs["_required"]) - $ret .= ""; - if($attribs["_custom"]) - $ret .= ""; - - return $ret; -} -/* - @description: returns the value for a form field. This may be defaulted by the system or set by a previus submit (as in an error condition) - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @example: -*/ -function m_form_value($attribs = array()) -{ - global $FormValues; - - $form = $attribs["_form"]; - $field = strtolower($attribs["_field"]); - - if(isset($_POST[$field])) - { - $value = stripslashes($_POST[$field]); - } - else - $value = stripslashes($FormValues[$form][$field]); - //echo "
    "; print_r($FormValues); echo "
    "; - return $value; -} - -/* - @description: creates an form OPTION tag for a form SELECT tag. - All extra attributes are passed to the OPTION tag. - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _Value:: Value to use for this option (ie the value attribute) If the current value of the select - field is the same as this attribute, then this option will be set SELECTED. - @attrib: _langtext:lang: language tag to display for this option in the SELECT dropdown - @attrib: _plaintext:: plain text to display for this option in the SELECT dropdown (if _langtext is set, it is used instead of _plaintext) - @example: $txt"; - - return $o; -} - -/* - @description: creates an form TEXTAREA field. All extra attributes are passed to the TEXTAREA tag - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting - @attrib: _Custom:bool: If set, handled as a custom field - @example: -*/ -function m_form_textarea($attribs = array()) -{ - global $FormValues; - $html_attribs = ExtraAttributes($attribs); - $field = $attribs["_field"]; - $form = $attribs["_form"]; - if(isset($_POST[$field])) - { - $value = stripslashes($_POST[$field]); - } - else - $value = stripslashes($FormValues[$attribs["_form"]][$field]); - $ret = ""; - if($attribs["_required"]) - $ret .= ""; - if($attribs["_custom"]) - $ret .= ""; - return $ret; -} - -/* - @description: creates an form field to upload images. (INPUT type=file) All extra attributes are passed to the INPUT tag - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name - @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting - @attrib: _ImageTypes:: Comma-separated list of file extensions allowed - @attrib: _Thumbnail:bool: If true, image is treated as a thumbnail - @attrib: _ImageName:: System name of image being uploaded - @attrib: _MaxSize:int: Maximum size of image to upload, or 0 to allow all -*/ -function m_form_imageupload($attribs = array()) -{ - $html_attribs = ExtraAttributes($attribs); - $field = $attribs["_field"]; - $form = $attribs["_form"]; - $TypesAllowed = $attribs["_imagetypes"]; - $isthumb = (int)$attribs["_thumbnail"]; - $imgname = $attribs["_imagename"]; - $maxsize = $attribs["_maxsize"]; - - $ret = ""; - $ret .= ""; - $ret .= ""; - $ret .= ""; - $ret .= ""; - if($attribs["_required"]) - $ret .= ""; - return $ret; -} - -/* - @description: Returns the error text for a form field, or nothing if no error exists for the field - @attrib: _Form:: Form name for the field - @attrib: _Field:: Field Name -*/ -function m_form_error($attribs = array()) -{ - global $FormError; - - $form = $attribs["_form"]; - $field = $attribs["_field"]; - - return $FormError[$form][$field]; -} - -/** - @description: Provides a simple solution for displaying a language flag when a form has an error. Generic and limited to 1 language vairable. - @attrib: _Form:: Form name for the field -*/ -function m_form_has_errors($attribs = array()) -{ - // shows specified template once if form has error(-s) - global $FormError; - $f = $attribs["_form"]; - - $ret = is_array($FormError[$f]); - if(!$ret) return ''; - return isset($attribs["_asif"]) ? true : language('lu_errors_on_form'); -} - -/** - @description: Lists form errors for all fields in a form - @attrib: _Form:: Form name for the field - @attrib: _ItemTemplate:tpl: Template used to display each form error (if not set, "" is used) -*/ -function m_list_form_errors($attribs = array()) -{ - global $FormError, $content_set, $objTemplate; - - $t = $attribs["_itemtemplate"]; - if(!strlen($t)) - $templateText = ""; - $f = $attribs["_form"]; - $o = ""; - if (strlen($t)) - { - $rawtext = $objTemplate->GetTemplate($t, true); - $src = $rawtext->source; - } - else - $src = $templateText; - - //echo $f."
    "; - //echo $t."
    "; -// echo "
    "; print_r($FormError); echo "
    "; - if(is_array($FormError[$f])) - { - foreach($FormError[$f] as $e) - { - $o .= str_replace("",$e, $src); - } - } - if(!strlen($o)) - $content_set = 0; - return $o; -} - -function m_form_load_values($FormName,$IdValue) -{ - global $FormValues, $objUsers, $objSession, $objConfig; - - switch($FormName) - { - case "m_acctinfo": - $u =& $objUsers->GetItem($IdValue); - $FormValues[$FormName]["username"] = $u->Get("Login"); - //$FormValues[$FormName]["password"] = $u->Get("Password"); - //$FormValues[$FormName]["passwordverify"] = $u->Get("Password"); - - $FormValues[$FormName]["password"] = ""; - $FormValues[$FormName]["passwordverify"] = ""; - - $FormValues[$FormName]["firstname"] = $u->Get("FirstName"); - $FormValues[$FormName]["lastname"] = $u->Get("LastName"); - $FormValues[$FormName]["email"] = $u->Get("Email"); - $FormValues[$FormName]["phone"] = $u->Get("Phone"); - $FormValues[$FormName]["street"] = $u->Get("Street"); - $FormValues[$FormName]["city"] = $u->Get("City"); - $FormValues[$FormName]["state"] = $u->Get("State"); - $FormValues[$FormName]["zip"] = $u->Get("Zip"); - $FormValues[$FormName]["country"] = $u->Get("Country"); - -// $FormValues[$FormName]["dob"] = LangDate($u->Get("dob")); - $FormValues[$FormName]["dob_day"] = date("d", $u->Get("dob")); - $FormValues[$FormName]["dob_year"] = date("Y", $u->Get("dob")); - $FormValues[$FormName]["dob_month"] = date("m", $u->Get("dob")); - - $u->LoadCustomFields(); - if(is_array($u->CustomFields->Items)) - { - foreach($u->CustomFields->Items as $f) - { - $FormValues[$FormName][$f->Get("FieldName")] = $f->Get("Value"); - } - } - break; - case "m_profile": - $u =& $objUsers->GetItem($IdValue); - if(is_object($u)) - { - $FormValues[$FormName]["pp_firstname"] = $objSession->GetPersistantVariable("pp_firstname"); - $FormValues[$FormName]["pp_lastname"] = $objSession->GetPersistantVariable("pp_lastname"); - $FormValues[$FormName]["pp_dob"] = $objSession->GetPersistantVariable("pp_dob"); - $FormValues[$FormName]["pp_email"] = $objSession->GetPersistantVariable("pp_email"); - $FormValues[$FormName]["pp_phone"] = $objSession->GetPersistantVariable("pp_phone"); - $FormValues[$FormName]["pp_street"] = $objSession->GetPersistantVariable("pp_street"); - $FormValues[$FormName]["pp_city"] = $objSession->GetPersistantVariable("pp_city"); - $FormValues[$FormName]["pp_state"] = $objSession->GetPersistantVariable("pp_state"); - $FormValues[$FormName]["pp_zip"] = $objSession->GetPersistantVariable("pp_zip"); - $FormValues[$FormName]["pp_country"] = $objSession->GetPersistantVariable("pp_country"); - } - break; - case "m_simplesearch": - $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords"); - break; - case "m_simple_subsearch": - $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords"); - break; - - } -} - -/* - @description: Generates the ACTTION property for a FORM tag used by In-Portal - @attrib: _Template:tpl: If set, this is the template the form submits to (default is the current template) - @attrib: _Form:: The form name
    Possible Values: -
      -
    • login: user login -
    • logout: user logout -
    • forgotpw: Form to prompt the user for forgotten password information -
    • forgotpw_confirm: confirmation form for forgotpw -
    • suggest: form to suggest the site to a friend -
    • suggest_confirm: form to confirm suggestion of the site to a friend -
    • m_subscribe: form to subscribe to the mailing list -
    • subscribe_confirm: form to confirm subscription to the mailing list -
    • m_unsubscribe: form to unsubscribe from the mailing list -
    • unsubscribe_confirm: form to confirm un-subscription from the mailing list -
    • m_acctinfo: user account information -
    • m_profile: system-level profile information -
    • m_register: New User registration form -
    • m_addcat: Suggest Category form -
    • m_addcat_confirm: Confirmation for add category -
    • m_simplesearch: Perform a simple search -
    • m_simple_subsearch: Search within results -
    • m_adv_searchtype: Form to select type of advanced search -
    • m_adv_subsearch: Advanced Search -
    • error_access: form displayed on the access denied template -
    • error_template: Form displayed on the template error page -
    • m_set_theme: Form displayed for theme selection -
    - @attrib: _SubscribeTemplate:tpl: The destination template with "m_subscribe", "subscribe_confirm", "unsubscribe_confirm" _Form actions. Can be reused in other scenarios as programmed. - @attrib: _UnSubscribeTemplate:tpl: The destination template for "m_subscribe" _Form action. Can be reused in other scenarios as programmed. - @attrib: _ConfirmTemplate:tpl: The destination template for "m_unsubscribe", "suggest" _Form actions. Can be reused in other scenarios as programmed. - @attrib: _DestTemplate:tpl: The destination template for "suggest_confirm", "suggest" _Form actions. Can be reused in other scenarios as programmed. - @attrib: _ErrorTemplate:tpl: The destination template extensively used in most of _Form actions in case of error. - @attrib: _Referer:bool: The destination template will be taken from referer page we can from. - - @example:
    "> -*/ -function m_form_action($attribs = array()) -{ - global $var_list, $var_list_update, $m_var_list_update, $objSession, $objConfig, $objCatList; - - $target_template = $attribs["_template"]; - if(strlen($target_template)) - { - $var_list_update["t"] = $target_template; - } - else - $var_list_update["t"] = $var_list["t"]; - - $ret = ""; - $form = strtolower($attribs["_form"]); - switch($form) - { - case "login": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_login"; - if($attribs["_successtemplate"]) - { - $ret .= "&dest=".$attribs["_successtemplate"]; - } - else - if(strlen($var_list["dest"])) - $ret .= "&dest=".$var_list["dest"]; - } - break; - case "logout": - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_logout"; - break; - case "forgotpw": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - if(strlen($attribs["_errortemplate"])) - { - $err = $attribs["_errortemplate"]; - } - else - $err = $var_list["t"]; - $ret = GetIndexURL(2)."?env=".BuildEnv()."&Action=m_forgotpw&error=$err"; - } - break; - case "forgotpw_confirm": - $ret = GetIndexURL(2)."?env=".BuildEnv(); - break; - case "suggest": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_suggest_email"; - if(strlen($attribs["_confirmtemplate"])>0) - { - $ret .= "&Confirm=".$attribs["_confirmtemplate"]; - } - if(strlen($Dest)) - { - $ret .= "&DestTemplate=$Dest"; - } - else - { - if(strlen($attribs["_confirmtemplate"])>0) - $ret .="&DestTemplate=".$var_list["t"]; - } - - if(strlen($attribs["_errortemplate"])>0) - { - $ret .= "&Error=".$attribs["_errortemplate"]; - } - } - break; - case "suggest_confirm": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - if(strlen($_GET["DestTemplate"])) - { - $var_list_update["t"] = $_GET["DestTemplate"]; - } - else - $var_list_update["t"] = "index"; - - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - break; - case "m_subscribe": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe_confirm"; - if(strlen($attribs["_subscribetemplate"])) - { - $ret .="&Subscribe=".$attribs["_subscribetemplate"]; - } - - if(strlen($attribs["_unsubscribetemplate"])>0) - { - $ret .= "&Unsubscribe=".$attribs["_unsubscribetemplate"]; - } - if(strlen($attribs["_errortemplate"])>0) - { - $ret .= "&Error=".$attribs["_errortemplate"]; - } - } - break; - - case "subscribe_confirm": - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe"; - if($attribs["_subscribetemplate"]) - $ret .= "&Subscribe=".$attribs["_subscribetemplate"]; - break; - case "unsubscribe_confirm": - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe"; - if($attribs["_subscribetemplate"]) - $ret .= "&Subscribe=".$attribs["_subscribetemplate"]; - break; - case "m_unsubscribe": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe"; - if(strlen($attribs["_confirmtemplate"])>0) - { - $ret .= "&Confirm=".$attribs["_confirmtemplate"]; - } - if(strlen($Dest)) - { - $ret .= "&DestTemplate=$Dest"; - } - else - { - if(strlen($attribs["_confirmtemplate"])>0) - $ret .="&DestTemplate=".$var_list["t"]; - } - } - - if(strlen($attribs["_confirmtemplate"])>0) - { - $ret .="&ErrorTemplate=".$attribs["_confirmtemplate"]; - } - - - break; - case "m_unsubscribe_confirm": - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - break; - case "m_acctinfo": - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_acctinfo&UserId=".$objSession->Get("PortalUserId"); - m_form_load_values($form, $objSession->Get("PortalUserId")); - break; - case "m_profile": - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_profile&UserId=".$objSession->Get("PortalUserId"); - m_form_load_values($form,$objSession->Get("PortalUserId")); - break; - - case "m_set_theme": - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_set_theme"; - break; - - case "m_register": - - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_register"; - - switch ($objConfig->Get("User_Allow_New")) - { - case "1": - if(strlen($attribs["_confirmtemplate"]) && $objConfig->Get("User_Password_Auto")) - $_dest = "&dest=".$attribs["_confirmtemplate"]; - else - $_dest = "&dest=".$attribs["_logintemplate"]; - break; - - case "2": - if(strlen($attribs["_notallowedtemplate"])) - $_dest = "&dest=".$attribs["_notallowedtemplate"]; - break; - - case "3": - if(strlen($attribs["_pendingtemplate"])) - $_dest = "&dest=".$attribs["_pendingtemplate"]; - break; - } - - if (strlen($_dest)) - $ret .= $_dest; - } - break; - - case "register_confirm": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - break; - case "m_addcat": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $action = "m_add_cat"; - if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING")) - { - if(strlen($attribs["_confirmpending"])) - { - $ConfirmTemplate = $attribs["_confirmpending"]; - } - else - $ConfirmTemplate = $attribs["_confirm"]; - $action="m_add_cat_confirm"; - } - - if ($objSession->HasCatPermission("CATEGORY.ADD")) - { - $ConfirmTemplate = $attribs["_confirm"]; - $action="m_add_cat_confirm"; - } - - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=$action"; - if(strlen($ConfirmTemplate)) - $ret .= "&Confirm=$ConfirmTemplate"; - - if (strlen($attribs["_mod_finishtemplate"])) { - - $CurrentCat = $objCatList->CurrentCategoryID(); - if((int)$CurrentCat>0) - { - $c = $objCatList->GetCategory($CurrentCat); - - //will prefix the template with module template root path depending on category - $ids = $c->GetParentIds(); - $tpath = GetModuleArray("template"); - $roots = GetModuleArray("rootcat"); - - // get template path of module, by searching for moudle name - // in this categories first parent category - // and then using found moudle name as a key for module template paths array - $path = $tpath[array_search ($ids[0], $roots)]; - $t = $path . $attribs["_mod_finishtemplate"]; - } - else { - $t = $attribs["_mod_finishtemplate"]; //Just in case - } - } - else { - $t = $attribs["_finishtemplate"]; - } - - $ret .="&DestTemplate=".$t; - } - break; - case "m_addcat_confirm": - $target_template = $_GET["DestTemplate"]; - if(strlen($target_template)) - { - $var_list_update["t"] = $target_template; - } - else - $var_list_update["t"] = $var_list["t"]; - $ret = GetIndexURL(2)."?env=".BuildEnv(); - break; - case "m_simplesearch": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_search"; - - if(strlen($attribs["_errortemplate"])) - $ret.= "&Error=".$attribs["_errortemplate"]; - - m_form_load_values($form, 0); - } - break; - case "m_simple_subsearch": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_subsearch"; - m_form_load_values($form,0); - } - break; - case "m_adv_search_type": - if(!$objSession->SessionEnabled()) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_advsearch_type"; - m_form_load_values($form,0); - } - break; - case "m_adv_search": - $SearchType = $_GET["type"]; - if(!is_numeric($SearchType)) - $SearchType = $_POST["itemtype"]; - if(!$objSession->SessionEnabled() && !strlen($SearchType)) - { - $var_list_update["t"] = "error_session"; - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - } - else - { - $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_adv_search&type=$SearchType"; - m_form_load_values($form,0); - } - break; - - case "error_access": - $target_template = $_GET["DestTemplate"]; - if(!strlen($target_template)) - $target_template="login"; - $var_list_update["t"] = $target_template; - - $ret = GetIndexURL(2)."?env=" . BuildEnv(); - break; - - case "error_template": - - $target_template = $_GET["DestTemplate"]; - - if($attribs["_referer"] == 1) - { - $target_template = "_referer_"; - } - elseif (!strlen($target_template)) - { - $target_template = "index"; - } - - $var_list_update["t"] = $target_template; - -// $m_var_list_update["cat"]=0; - - $ret = GetIndexURL(2)."?env=".BuildEnv(); - - break; - - } - return $ret; -} - -/* - @description: creates a URL to allow the user to log out. Accepts the same attributes as m_template_link - -*/ -function m_logout_link($attribs) -{ - $ret = m_template_link($attribs)."&Action=m_logout"; - return $ret; -} - -/* - @description: returns a URL to the current theme - @attrib: _page:: Additional address to be added to the end of the theme URL -*/ -function m_theme_url($attribs=array()) -{ - global $objConfig,$objSession, $objThemes, $CurrentTheme; - - if(!is_object($CurrentTheme)) - $CurrentTheme = $objThemes->GetItem($m_var_list["theme"]); - - $theme_url = "http://". ThisDomain().$objConfig->Get("Site_Path")."themes/".$CurrentTheme->Get("Name")."/"; - if($attribs["_page"]) - { - if ($attribs["_page"] != 'current') - { - $theme_url .= $attribs["_page"]; - } - else - { - $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv(); - } - } - return $theme_url; -} - -/* - @description: returns a URL to the current theme -*/ -function m_current_page_url($attribs=array()) -{ - global $objConfig,$objSession; - - $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv(); - - return $theme_url; -} - -/* - @description: returns a URL to the current theme - @attrib: _fullpath:bool: Append the title with the full path of the current category - @attrib: _currentcategory:bool: Append the title with the current category - @attrib: _catfield:: If _currentcategory is used, this attribute determines which category field to use (Name, Description, etc) Defaults to Name -*/ -function m_page_title($attribs = array()) -{ - global $objConfig, $objCatList; - - $ret = $objConfig->Get("Site_Name"); - if($attribs["_fullpath"] || $attribs["_currentcategory"]) - { - $CurrentCat = $objCatList->CurrentCategoryID(); - if((int)$CurrentCat>0) - { - $c = $objCatList->GetCategory($CurrentCat); - if($attribs["_fullpath"]) - { - $path = $c->Get("CachedNavbar"); - - if(strlen($path)) - $ret .= " - ".$path; - } - else - { - if($attribs["_currentcategory"]) - { - $f = $attribs["_catfield"]; - if(!strlen($f)) - $f = "Name"; - $ret .= " - ".$c->Get($f); - } - } - } - } - $ret = stripslashes($ret); - return $ret; -} - -/* - @description: list all active themes - @attrib: _ItemTemplate:tpl: Template to display each theme in the list -*/ -function m_list_themes($attribs=array()) -{ - global $objThemes; - - $t = $attribs["_itemtemplate"]; - if(strlen($t)) - { - $objThemes->Clear(); - $objThemes->LoadThemes("Enabled=1","PrimaryTheme DESC"); - - foreach($objThemes->Items as $theme) - { - $o .= $theme->ParseTemplate($t); - } - } - return $o; -} - -/* - @description: display text based on the user's language - @attrib: _Phrase:lang: label to replace with language-specific text - @example: -*/ -function m_language($attribs) -{ - global $objSession, $objLanguages, $ForceLanguage; - - $phrase = $attribs["_phrase"]; - $LangId = (int)$ForceLanguage; - if(strlen($phrase)) - { - $lang = $attribs["_language"]; - if(strlen($lang)) - { - $l = $objLanguages->GetItemByField("PackName",$lang); - if(is_object($l)) - { - $LangId = $l->Get("LanguageId"); - } - } - return language($phrase,$LangId); - } - else - return ""; -} - -/* - @description: Creates a URL used to set the current language for a user - @attrib: _language:: Language to set (this value should be the language Pack Name) -*/ -function m_setlang_link($attribs) -{ - global $m_var_list_update, $objSession,$objLanguages; - - $lang = $attribs["_language"]; - if(strlen($lang)) - { - $l = $objLanguages->GetItemByField("PackName",$lang); - if(is_object($l)) - $LangId = $l->Get("LanguageId"); - } - else - $LangId=$objSession->Get("Language"); - if($LangId) - { - $m_var_list_update["lang"] = $LangId; - $ret = GetIndexURL()."?env=".BuildEnv(); - unset($m_var_list_update["lang"]); - } - else - $ret = ""; - return $ret; -} - -/* - @description: list all active languages - @attrib: _ItemTemplate:tpl: Template to display each language in the list -*/ -function m_list_languages($attribs) -{ - global $objLanguages, $content_set; - - $sql = "SELECT * FROM ".GetTablePrefix()."Language WHERE Enabled=1"; - $objLanguages->Clear(); - $objLanguages->Query_Item($sql); - - if($objLanguages->NumItems()>0) - { - foreach($objLanguages->Items as $l) - $o .= $l->ParseTemplate($attribs["_itemtemplate"]); - } - else - $content_set=0; - return $o; -} - -/* - @description: returns the date format for a language - @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set -*/ -function m_lang_dateformat($attribs=array()) -{ - global $objLanguages, $objSession; - - $lang = $attribs["_lang"]; - if(!strlen($lang)) - { - $LangId = $objSession->Get("Language"); - $l = $objLanguages->GetItem($LangId); - } - else - { - $l = $objLanguages->GetItemByField("PackName",$lang); - } - $fmt = GetDateFormat($LangId); - $fmt = GetStdFormat($fmt); - - return $fmt; -} - -/* - @description: returns a language field value - @attrib: _Field:: Language field to return - @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set -*/ -function m_lang_field($attribs = array()) -{ - global $objLanguages, $objSession; - - if(!strlen($attribs["_field"])) - return ""; - $lang = $attribs["_lang"]; - if(!strlen($lang)) - { - $LangId = $objSession->Get("Language"); - $l = $objLanguages->GetItem($LangId); - } - else - { - $l = $objLanguages->GetItemByField("PackName",$lang); - } - if(is_object($l)) - { - //$ret = $l->Get($attribs["_field"]); - $e = new clsHtmlTag(); - $e->name=$l->TagPrefix; - $e->attributes=$attribs; - $ret = $l->ParseObject($e); - } - return $ret; -} - -/* - @description: Creates a URL used to set the current theme for a user - @attrib: _theme:: Name of Theme to set. The template selected in the new them is always "index" -*/ -function m_settheme_link($attribs) -{ - global $m_var_list_update, $objSession, $objThemes, $CurrentTheme; - - $ThemeName = $attribs["_theme"]; - - if(strlen($ThemeName)) - { - $t = $objThemes->GetItemByField("Name",$ThemeName); - if(is_object($t)) - { - $Id = $t->Get("ThemeId"); - } - else - $Id = 0; - } - else - { - $t = $CurrentTheme; - $Id = 0; - } - $m_var_list_update["theme"] = $Id; - $ret = GetIndexURL()."?env=".BuildEnv(); - unset($m_var_list_update["theme"]); - return $ret; -} - -/* - @description: Initializes categories -*/ -function m_init_cats($attribs = array()) -{ - // save current & previous category (used in pagination) - global $objSession, $objCatList; - global $var_list; - //echo "SID_INIT: ".$var_list["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')
    '; - $objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') ); - $objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() ); - - //$last_cat = $objSession->GetVariable('last_category'); - //$prev_cat = $objSession->GetVariable('prev_category'); - //echo "Last CAT: [$last_cat]
    "; - //echo "Prev CAT: [$prev_cat]
    "; -} - -/* - @description: List all subcategories a user is allowed to view - @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1) - @attrib: _maxlistcount:int: Maximum number of categories to list - @attrib: _FirstItemTemplate:tpl: Template used for the first category listed - @attrib: _LastItemTemplate:tpl: Template used for the last category listed - @attrib: _ItemTemplate:tpl: default template used for category list items - @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag - @example: -*/ -function m_list_cats($attribs = array()) -{ - global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, $objSystemCache; - - $CachedList = GetTagCache("kernel","m_list_cats",$attribs,m_BuildEnv()); - if(strlen($CachedList)) - { - return $CachedList; - } - $cols = $attribs["_columns"]; - if($cols<1) - $cols =1; - $CategoryId = $attribs["_catid"]; - if(!is_numeric($CategoryId)) - $CategoryId = $objCatList->CurrentCategoryID(); - - $cat_count = (int)$attribs["_maxlistcount"]; - /* validation */ - if(strlen($attribs["_itemtemplate"])==0) - { - if($attribs["dataexists"]) - $content_set = 0; - return ""; - } - - $GroupList = $objSession->Get("GroupList"); - if(strlen($GroupList)) - { - $Groups = explode(",",$GroupList); - } - $acl_where = ""; - if(@count($Groups)>0 && is_array($Groups)) - { - $acl_where = array(); - for($i=0;$iClear(); - $OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE); - $objCatList->LoadCategories("ParentId=$CategoryId AND Status=1",$OrderBy); - if ($objCatList->NumItems() == 0) - { - if($attribs["_dataexists"]) - $content_set = 0; - return ""; - } - - $html_attr = ExtraAttributes($attribs); - - $o=""; - $notable = $attribs["_notable"]; - - $count=0; - $row=0; - $var_list_update["t"] = $var_list["t"]; - - if(!$notable) - { - $per_row = ceil($objCatList->NumItems()/$cols); - $o = ""; - $o .= ""; - $o .= "\n
    "; - $CatCount = $objCatList->NumItems(); - foreach($objCatList->Items as $cat) - { - $parsed=0; - if($count==$per_row) - { - $o .= ""; - $count=0; - } - if($row==0 && strlen($attribs["_firstitemtemplate"])) - { - $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); - $parsed=1; - } - if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) - { - $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); - $parsed=1; - } - if(!$parsed) - $o.= $cat->ParseTemplate($attribs["_itemtemplate"]); - $count++; - $row++; - } - if($count != $per_row) - $o .= "
    \n"; - } - else - { - $CatCount = $objCatList->NumItems(); - foreach($objCatList->Items as $cat) - { - if($cat->Get("ParentId")==$CategoryId) - { - - if($row==0 && strlen($attribs["_firstitemtemplate"])) - { - //echo 'Saving ID in m_sub_cats[ first ] '.$cat->UniqueId().'
    '; - //$GLOBALS['cat_ID'] = $cat->UniqueId(); - $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); - $parsed=1; - } - if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) - { - //echo 'Saving ID in m_sub_cats[ last ] '.$cat->UniqueId().'
    '; - //$GLOBALS['cat_ID'] = $cat->UniqueId(); - $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); - $parsed=1; - } - if(!$parsed) - { - //echo 'Saving ID in m_sub_cats[ each ] '.$cat->UniqueId().'
    '; - //$GLOBALS['cat_ID'] = $cat->UniqueId(); - $o .= $cat->ParseTemplate($attribs["_itemtemplate"]); - } - $row++; - $i++; - $count++; - if($count>=$cat_count && $cat_count>0) - break; - } - } - } - unset($var_list_update["t"]); - SaveTagCache("kernel","m_list_cats",$attribs,m_BuildEnv(),$o); - return $o; -} - -function LoadCatSearchResults($attribs) -{ - global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal; - - $GroupList = $objSession->Get("GroupList"); - if(strlen($GroupList)) - $Groups = explode(",",$GroupList); - $acl_where = ""; - if(@count($Groups)>0 && is_array($Groups)) - { - $acl_where = array(); - for($i=0;$iGetPermId("CATEGORY.VIEW"); - $ctable = $objCatList->SourceTable; - $stable = $objSession->GetSearchTable(); // $objSearchCats->SourceTable; - $ptable = GetTablePrefix()."PermCache"; - $sql = "SELECT * FROM $stable INNER JOIN $ctable ON ($stable.ItemId=$ctable.CategoryId) "; - $sql .= "INNER JOIN $ptable ON ($ctable.CategoryId=$ptable.CategoryId) "; - $sql .="WHERE ItemType=1 AND Status=1 AND $acl_where AND PermId=$CAT_VIEW ORDER BY EdPick DESC,Relevance DESC "; - $objSearchCats->Page = $m_var_list["p"]; - if($objSearchCats->Page<1) - $objSearchCats->Page=1; - - if(is_numeric($objConfig->Get($objSearchCats->PerPageVar))) - { - $Start = ($objSearchCats->Page-1)*$objConfig->Get($objSearchCats->PerPageVar); - $limit = "LIMIT ".$Start.",".$objConfig->Get($objSearchCats->PerPageVar); - } - else - $limit = NULL; - - if(strlen($limit)) - $sql .= $limit; - - // echo "TEST:
    $sql
    \n"; - $objSearchCats->Query_Item($sql); - $where = "ItemType=1"; - - if(is_numeric($CountVal[1])) - { - $objSearchCats->QueryItemCount = $CountVal[1]; - } - else - { - $objSearchCats->QueryItemCount = QueryCount($sql); - $CountVal[1]= $objSearchCats->QueryItemCount; - } -} - -/* - @description: Used in conjuction with m_search_list_cats. This function generates a navigation link which is - used to switch from a short list to a longer list. The page number is not changed. - If this tag is called before the list tag, this function will load the category list. - Generally, it is good practice to duplicate all attributes set for m_search_list_cats. - Any extra HTML attributes are passed to the anchor tag - @attrib: _Template:tpl: Template to link to - @attrib: _text:lang: language tag to include as text for the anchor tag - @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence - if both are included. - @attrib: _image:: URL to an image to include inside the anchor tag. -*/ -function m_search_cat_more($attribs = array()) -{ - global $objSearchCats, $objConfig, $m_var_list_update; - - $html_attribs = ExtraAttributes($attribs); - $DestTemplate = $attribs["_template"]; - - if($attribs["_shortlist"]) - $objSearchList->PerPageVar = "Perpage_Category_Short"; - if($objSearchCats->NumItems()==0) - { - LoadCatSearchResults($attribs); - } - $max = $objConfig->Get($objSearchList->PerPageVar); - $val = $objSearchCats->QueryItemCount; - if($val > $max) - { - if($attribs["_root"]) - $attribs["_category"]=0; - - $m_var_list_update["p"]=1; - $url = m_template_link($attribs); - unset($m_var_list_update["p"]); - $o = ""; - $text = $attribs["_text"]; - if(!strlen($text)) - { - $text = $attribs["_plaintext"]; - if(!strlen($text)) - { - } - $o .= $text.""; - } - else - $o .= language($text); - if(strlen($attribs["_image"])) - { - $o .= ""; - } - $o .= ""; - } - return $o; -} -/* - @description: Used in conjuction with m_search_list_cats. This function generates the page navigation - for the list. If this tag is called before the list tag, this function will load - the category list. Generally, it is good practice to duplicate all attributes set for - m_search_list_cats. - @attrib: _PagesToList:int: Number of pages to list (default is 10) - @attrib: _label:lang: language tag to include in the output if there are pages to list. If there are no pages - listed, this text will not be included (resulting in an empty output) -*/ -function m_search_cat_pagenav($attribs = array()) -{ - global $objSearchCats, $objConfig, $objCatList, $objSession; - - $DestTemplate = $attribs["_template"]; - $PagesToList = $attribs["_pagestolist"]; - if(!is_numeric($PagesToList)) - $PagesToList = 10; - - $CatId = $attribs["_catid"]; - if(!is_numeric($CatId)) - $CatId = $objCatList->CurrentCategoryID(); - - $objSearchCats->PerPageVar = "Perpage_Category"; - if($attribs["_shortlist"]) - $objSearchCats->PerPageVar = "Perpage_Category_Short"; - if($objSearchCats->NumItems()==0) - { - LoadCatSearchResults($attribs); - } - $o = $objSearchCats->GetPageLinkList($DestTemplate); - if(strlen($o) && strlen($attribs["_label"])) - $o = language($attribs["_label"]).$o; - return $o; -} - -/* - @description: List all categories matched in a search - @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1) - @attrib: _maxlistcount:int: Maximum number of categories to list - @attrib: _ShortList:bool: If set, the Perpage_Category_Short setting is used instead of Perpage_Category - @attrib: _FirstItemTemplate:tpl: Template used for the first category listed - @attrib: _LastItemTemplate:tpl: Template used for the last category listed - @attrib: _ItemTemplate:tpl: default template used for category list items - @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag - @example: -*/ -function m_search_list_cats($attribs = array()) -{ - global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, - $objSearchCats, $objPermissions, $m_var_list; - - if(!is_object($objSearchCats)) - { - $objSearchCats = new clsCatList(); - $objSearchCats->SourceTable = $objSession->GetSessionTable('Search'); //"ses_".$objSession->GetSessionKey()."_Search" - $objSearchCats->Clear(); - } - $objSearchCats->PerPageVar = "Perpage_Category"; - if($attribs["_shortlist"]) - { - $objSearchCats->Page=1; - $m_var_list["p"] = 1; - $objSearchCats->PerPageVar = "Perpage_Category_Short"; - } - - $keywords = $objSession->GetVariable("Search_Keywords"); // for using in all this func branches - - if($objSearchCats->NumItems()==0) - { - LoadCatSearchResults($attribs); - //echo "Cat count: ". $objSearchCats->QueryItemCount; - $ret = 0; - if ($keywords) { - foreach ($objSearchCats->Items as $cat) { - - if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($_POST['keywords'])) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($_POST['keywords']))) { - $ret++; - } - } - } - else { - $ret = $objSearchCats->QueryItemCount; - } - if ($ret == 0) //if ($objSearchCats->NumItems() == 0) - { - $content_set = 0; - return language("lu_no_categories"); - } - } - - $html_attr = ExtraAttributes($attribs); - $cols = $attribs["_columns"]; - if($cols<1) - $cols =1; - $cat_count = (int)$attribs["_maxlistcount"]; - /* validation */ - if(strlen($attribs["_itemtemplate"])==0) - { - $content_set = 0; - return "ERROR -1"; - } - - $o=""; - $notable = $attribs["_notable"]; - - $count=0; - $row=0; - $var_list_update["t"] = $var_list["t"]; - - if(!$notable) - { - $per_row = ceil($objCatList->NumItems()/$cols); - $o = ""; - $o .= ""; - $o .= "\n
    "; - foreach($objSearchCats->Items as $cat) - { - $parsed=0; - if($count==$per_row) - { - $o .= ""; - $count=0; - } - if($row==0 && strlen($attribs["_firstitemtemplate"])) - { - $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); - $parsed=1; - } - if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) - { - $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); - $parsed=1; - } - if(!$parsed) - $o.= $cat->ParseTemplate($attribs["_itemtemplate"]); - $count++; - } - if($count != $per_row) - $o .= "
    \n"; - } - else - { - //echo "
    "; print_r($objSearchCats->Items); echo "
    "; - foreach($objSearchCats->Items as $cat) - { - //$cat->Keywords = GetKeywords($objSession->GetVariable("Search_Keywords")); - $keywords_found = strstr( strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords)); - if(!$keywords) $keywords_found = true; - if ($keywords_found) { - if($row==0 && strlen($attribs["_firstitemtemplate"])) - { - $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); - $parsed=1; - } - if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) - { - $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); - $parsed=1; - } - if(!$parsed) - $o.= $cat->ParseTemplate($attribs["_itemtemplate"]); - $row++; - $i++; - $count++; - } - } - } - unset($var_list_update["t"]); - return $o; -} - -/* - @description: Parse a template based on the current advanced search type - @attrib:_TypeSelect:tpl:Template to parse if no item type has been selected - @attrib:_ItemSelect:tpl:Template to parse if an item type has been selected to search -*/ -function m_advsearch_include($attribs) -{ - global $objTemplate; - - $TypeSelectTemplate = $attribs["_typeselect"]; - $ItemTemplate = $attribs["_itemselect"]; - if((strlen($_GET["type"])>0 || $_POST["itemtype"]>0) && ($_GET["Action"]=="m_advsearch_type" || $_GET["Action"]=="m_adv_search")) - { - $o = $objTemplate->ParseTemplate($ItemTemplate); - } - else - $o = $objTemplate->ParseTemplate($TypeSelectTemplate); - return $o; -} - -/* - @description: Returns the name of the item type currently being advanced searched - @attrib::_plaintext:bool:If set, simply returns the name of the item if not, builds a language tag (lu_searchtitle_[name]) -*/ -function m_advsearch_type($attribs) -{ - global $objItemTypes; - - if($_GET["Action"]=="m_advsearch_type") - { - $ItemType = $_POST["itemtype"]; - } - elseif($_GET["Action"]=="m_adv_search") - $ItemType = $_GET["type"]; - - $o = ""; - if((int)$ItemType>0) - { - $Item = $objItemTypes->GetItem($ItemType); - if(is_object($Item)) - { - $name = strtolower($Item->Get("ItemName")); - if($attribs["_plaintext"]) - { - $o .= $name; - } - else - $o = language("lu_searchtitle_".strtolower($name)); - } - } - return $o; -} - -/* - @description: Lists advanced search fields for the selected item type - @attrib: _FirstItemTemplate:tpl: Template used for the first field listed - @attrib: _LastItemTemplate:tpl: Template used for the last field listed - @attrib: _AltLastItemTemplate:tpl: Altername Template used for the last field listed - @attrib: _ItemTemplate:tpl: default template used for field list items - @attrib: _AltTemplate:tpl: Alternate template used for field list items -*/ -function m_advsearch_fields($attribs) -{ - global $objItemTypes, $objTemplate, $objSearchConfig; - - if(!is_object($objSearchConfig)) - $objSearchConfig = new clsSearchConfigList(); - - if($_GET["Action"]=="m_advsearch_type") - { - $ItemType = $_POST["itemtype"]; - } - elseif($_GET["Action"]=="m_adv_search") - $ItemType = $_GET["type"]; - - $o = ""; - if((int)$ItemType>0) - { - $Item = $objItemTypes->GetItem($ItemType); - if(is_object($Item)) - { - $name = strtolower($Item->Get("ItemName")); - - $table = $Item->Get("SourceTable"); - $sql = "SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$table' AND AdvancedSearch=1 ORDER BY DisplayOrder"; - $objSearchConfig->Query_Item($sql); - $row=0; - if(is_array($objSearchConfig->Items)) - { - $ItemCount = count($objSearchConfig->Items); - foreach($objSearchConfig->Items as $s) - { - $even = (($row+1) % 2 == 0); - $parsed=0; - if($row==0 && strlen($attribs["_firstitemtemplate"])) - { - $o .= $s->ParseTemplate($attribs["_firstitemtemplate"]); - $parsed=1; - } - if($row==$ItemCount-1 && $even && !$parsed && strlen($attribs["_altlastitemtemplate"])>0) - { - $o .= $s->ParseTemplate($attribs["_altlastitemtemplate"]); - $parsed=1; - } - if($row==$ItemCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) - { - $o .= $s->ParseTemplate($attribs["_lastitemtemplate"]); - $parsed=1; - } - if(!$parsed) - { - if($even && strlen($attribs["_altitemtemplate"])>0) - { - $o .= $s->ParseTemplate($attribs["_altitemtemplate"]); - } - else - $o .= $s->ParseTemplate($attribs["_itemtemplate"]); - } - $row++; - - } - } - } - } - return $o; -} - -/* - @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes - are passed to the anchor tag created. - @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index") - @attrib: _Module:: Module being linked to (ie In-Bulletin or In-News or In-Link) - @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, - the link will be generated. (If the _DeniedTemplate attribute is set, this template is used - and the link is created.) - @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm - attribute. If this attirbute is not included and the user does not have access, - nothing is returned. (The link is not created.) - @attrib: _Root:bool: If set, the current category is set to the module's root category - @attrib: _text:lang: language tag to include as text for the anchor tag - @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence - if both are included. - @attrib: _image:: URL to an image to include inside the anchor tag. - @attrib: _image_actions:: Image events. -*/ -function m_module_link($attribs = array()) -{ - global $objCatList, $objSession; - - $permission = $attribs["_perm"]; - $o = ""; - $tpath = GetModuleArray("template"); - if(strlen($permission)) - { - $perms = explode(",",$permission); - $hasperm = FALSE; - for($x=0;$xHasCatPermission($perms[$x])) - { - $hasperm = TRUE; - break; - } - } - } - else - $hasperm = TRUE; - if(!$hasperm && strlen($attribs["_deniedtemplate"])>0) - { - $hasperm = TRUE; - $attribs["_template"]=$attribs["_deniedtemplate"]; - } - if($hasperm) - { - $module = $attribs["_module"]; - if(ModuleEnabled($module)) - { - $t = $tpath[$attribs["_module"]]; - $t .= $attribs["_template"]; - $attribs["_template"] = $t; - $html_attr = ExtraAttributes($attribs); - if($attribs["_root"]) - { - $func = ModuleTagPrefix($module)."_root_link"; - if(function_exists($func)) - { - $url = $func($attribs); - } - else - $url = m_template_link($attribs); - } - else - $url = m_template_link($attribs); - $o = " "; - $text = $attribs["_text"]; - if(!strlen($text)) - { - $text = $attribs["_plaintext"]; - if(!strlen($text)) - { - if(strlen($attribs["_image"])) - { - $text = ""; - } - } - $o .= $text.""; - } - else - $o .= language($text).""; - } - else - { - $o = ""; - } - } - return $o; -} -/* - @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes - are passed to the anchor tag created. - @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index") - @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, - the link will be generated. (If the _DeniedTemplate attribute is set, this template is used - and the link is created.) - @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm - attribute. If this attirbute is not included and the user does not have access, - nothing is returned. (The link is not created.) - @attrib: _text:lang: language tag to include as text for the anchor tag - @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence - if both are included. - @attrib: _image:: URL to an image to include inside the anchor tag. -*/ -function m_permission_link($attribs = array()) -{ - global $objCatList, $objSession; - - $permission = $attribs["_perm"]; - $o = ""; - if(strlen($permission)) - { - $perms = explode(",",$permission); - $hasperm = FALSE; - for($x=0;$xHasCatPermission($perms[$x])) - { - $hasperm = TRUE; - break; - } - } - } - else - $hasperm = TRUE; - if(!$hasperm && strlen($attribs["_deniedtemplate"])>0) - { - $hasperm = TRUE; - $attribs["_template"]=$attribs["_deniedtemplate"]; - } - if($hasperm) - { - $url = m_template_link($attribs); - $o = " "; - $text = $attribs["_text"]; - if(!strlen($text)) - { - $text = $attribs["_plaintext"]; - if(!strlen($text)) - { - if(strlen($attribs["_image"])) - { - $text = ""; - } - } - $o .= $text.""; - } - else - $o .= language($text).""; - } - else - { - $o = ""; - } - - return $o; -} - -/* - @description: Create a link to a template. - @attrib: _Template:tpl: Template to link to (ex: "inbulletin/post_list") - @attrib: _Query:str: Extra query sring to be added to link URL (ex: "&test=test") - @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged - @attrib: _anchor:: If included, a local anchor (#) is added. (ex: _anchor="top" results in ) - @attrib: _Secure:bool:If set, creates an https URL - @attrib: _Root:bool:If set, gets module root category id - @attrib: _Module:str:Module Name - @attrib: _Unsecure:bool: Is set, creates an insecure full url (http://...) - @example: "> -*/ -function m_template_link($attribs = array()) -{ - global $var_list, $var_list_update, $m_var_list_update, $objCatList; - - $template = $attribs["_template"]; - - $query = trim($attribs["_query"]); - $query = !ereg("^&", $query)? "&$query" : $query; - - if(!strlen($template)) - $template = $var_list["t"]; - $cat = $attribs["_category"]; - $var_list_update["t"] = $template; - - if(strlen($cat)) - { - if($cat=="NULL") - { - $m_var_list_update["cat"]=0; - } - else - { - $m_var_list_update["cat"] = $cat; - } - } - - if($attribs["_secure"]) - { - $ret = GetIndexURL(1)."?env=".BuildEnv().$query; - } - elseif($attribs["_unsecure"]) - { - $ret = GetIndexURL(2)."?env=".BuildEnv().$query; - } - else - $ret = GetIndexURL()."?env=".BuildEnv().$query; - - if(strlen($attribs["_anchor"])) - $ret .= "#".$attribs["_anchor"]; - unset($var_list_update["t"]); - if(strlen($cat)) - unset($m_var_list_update["cat"]); - return $ret; -} - -/* - @description: create a link to a template based on user permissions. All extra HTML attributes are passed to the anchor tag created. - @attrib: _Template:tpl: Template to link to if the user has access - @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm - attribute. If this attirbute is not included and the user does not have access, - the "login" template is used. - @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, - the link will be generated. (If the _DeniedTemplate attribute is set, this template is used - and the link is created.) - @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN) - @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged - @example: "> -*/ -function m_access_template_link($attribs = array(), $Permission="") -{ - global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession; - - $cat = $attribs["_category"]; - if(strlen($cat)) - { - if($cat=="NULL") - $cat = 0; - } - else - $cat = $objCatList->CurrentCategoryID(); - - if(!strlen($Permission)) - { - $Permission = strtoupper($attribs["_perm"]); - } - - $o = ""; - $hasperm = FALSE; - if(strlen($Permission)) - { - $perms = explode(",",$Permission); - - for($x=0;$xHasCatPermission(trim($perms[$x]),$cat)) - { - $hasperm = TRUE; - break; - } - } - - if(!$hasperm && $attribs["_system"]) - { - for($x=0;$xHasSystemPermission(trim($perms[$x]))) - { - $hasperm = TRUE; - break; - } - } - } - } - $access = $attribs["_template"]; - $denied = $attribs["_deniedtemplate"]; - if(!strlen($denied)) - $denied = "login"; - - $m_var_list_update["cat"] = $cat; - if($hasperm) - { - $template = $access; - if(!strlen($template)) - $template = $var_list["t"]; - $var_list_update["t"] = $template; - } - else - { - $template = $denied; - if(!strlen($template)) - $template = $var_list["t"]; - if($template == "login") - { - $dest = $access; - } - $var_list_update["t"] = $template; - } - - $ret = GetIndexURL()."?env=".BuildEnv(); - unset($var_list_update["t"]); - if(strlen($dest)) - $ret .= "&dest=$dest"; - return $ret; -} - -/* - @description: returns a text based on user permissions. Text from inside of the tag will be returned if text attributes are not specified and user has permissions to category, or if _NoPerm attribute set to 1 and user doesn't have permissions. Otherwise entire section will be excluded. - @attrib: _Text:lang: Template to link to if the user has access - @attrib: _PlainText:: This template is used if the user does not have a permission listed in the _perm attribute. If this attirbute is not included and the user does not have access, the "login" template is used. - @attrib: _DenyText:lang: Template to link to if the user has access - @attrib: _PlainDenyText:: This exact text is used if the user does not have a permission listed in the _perm attribute and _DenyText attribute is not set. - @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, the link will be generated. - @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN) - @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged - @attrib: _MatchAllPerms:int: Checks for all listed Permissions to be TRUE. Note: this attribute is rarely used. - @attrib: _NoPerm:int: The whole tag will return inner text if user has no permissions and attribute set to 1. Default value is 0. - @example: Some HTML here! -*/ -function m_perm_text($attribs = array()) -{ - global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession; - - $cat = $attribs["_category"]; - if(strlen($cat)) - { - if($cat=="NULL") - $cat = 0; - } - else - $cat = $objCatList->CurrentCategoryID(); - - if(!strlen($Permission)) - { - $Permission = strtoupper($attribs["_perm"]); - } - - $o = ""; - $hasperm = FALSE; - - $count = 0; - - if(strlen($Permission)) - { - $perms = explode(",",$Permission); - - for($x=0;$xHasCatPermission($perms[$x],$cat)) - { - $hasperm = TRUE; - $_AllPermsCount[$count] = 1; -// break; - } - - $count++; - } - - if(!$hasperm && $attribs["_system"]) - { - for($x=0; $xHasSystemPermission($perms[$x])) - { - $hasperm = TRUE; - $_AllPermsCount[$count] = 1; -// break; - } - - $count++; - } - } - } - - if ((int)$attribs["_matchallperms"]) - { - if (count($_AllPermsCount) != array_sum($_AllPermsCount)) - $hasperm = FALSE; - } - - $text = $attribs["_text"]; - $plaintext = $attribs["_plaintext"]; - $denytext = $attribs["_denytext"]; - $plaindenytext = $attribs["_plaindenytext"]; - $nopermissions_status = (int)$attribs["_noperm"]? 1 : 0; - - if(!strlen($denied)) - $denied = "login"; - - if (!$nopermissions_status) - { - if ($hasperm) - { - if (strlen($text) || strlen($plaintext)) - $ret = strlen($text)? language($text) : $plaintext; - else - $ret = "1"; - } - else - $ret = strlen($denytext)? language($denytext) : $plaindenytext; - } - elseif (!$hasperm) - { - $ret = "1"; - } - - return $ret; -} - - -/* - @description: Returns the error string associated with a permission -*/ -function m_permission_error($attribs = array()) -{ - global $objPermissions; - - $ret = ""; - $perm = strtoupper($_GET["error"]); - if(strlen($perm)) - { - $ado = &GetADODBConnection(); - $sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName ='$perm'"; - $rs = $ado->Execute($sql); - if($rs && !$rs->EOF) - { - $data = $rs->fields; - $error_tag = $data["ErrorMessage"]; - } - else - $error_tag = "lu_unknown_error"; - $ret = language($error_tag); - } - return $ret; -} - -/* - @description: Returns the error text encountered when parsing templates -*/ -function m_template_error($attribs = array()) -{ - global $objTemplate; - - $ret = ""; - if($objTemplate->ErrorNo<0) - { - $ret = $objTemplate->ErrorStr; - } - return $ret; -} - -/* - @description: Creates a category navigation bar - @attrib: _Template:tpl: template to use for navigation links - @attrib: _RootTemplate:bool: If set, this template is linked to for the root category - @attrib: _LinkCurrent:bool: If set, the last (current) category is linked. Otherwise the current category is simply displayed - @attrib: _Separator:: text to display between levels of the navigation bar - @attrib: _Root:: Root category configuration variable to use. (ex: Link for In-Link's root category) If not set, the system root is used - @example: -*/ -function m_navbar($attribs = array()) -{ - global $m_var_list_update, $var_list, $objCatList, $objConfig, $objModules; - - $separator = GetElem($attribs, '_separator'); - if(!$separator) $separator = " > "; - - $admin = (int)GetElem($attribs, 'admin'); - - $t = GetElem($attribs, '_template'); - $LinkLeafNode = GetElem($attribs, '_linkcurrent'); - $catid = (int)GetElem($attribs, '_catid'); - - if( GetElem($attribs, '_root') ) - { - $var = GetElem($attribs, '_root')."_Root"; - $Root = (int)$objConfig->Get($var); - } - else - $Root = 0; - - $RootTemplate = GetElem($attribs, '_roottemplate') ? GetElem($attribs, '_roottemplate') : ''; - $Module = GetElem($attribs, '_module'); - $ModuleRootTemplate = ''; - if($Module) - { - $ModuleRootCat = $objModules->GetModuleRoot($Module); - if($ModuleRootCat>0) - { - $modkey = "_moduleroottemplate"; - $ModuleRootTemplate = GetElem($attribs, $modkey); - } - else - $ModuleRootTemplate=""; - } - else - $ModuleRootCat = 0; - - if(!$catid) - $catid = $objCatList->CurrentCategoryID(); - - $ret = $objCatList->cat_navbar($admin, $catid, $t, $separator,$LinkLeafNode,$Root,$RootTemplate,$ModuleRootCat,$ModuleRootTemplate); - return $ret; -} - -/* - @description: Parse a category field and return the value - @attrib: _Field:: Category field to parse - @attrib: _CatId:int: Category ID to parse (uses current category if not set) - @attrib: _StripHTML:bool: if set, all HTML is removed from the output -*/ -function m_category_field($attribs) -{ - global $objCatList; - - $ret = ""; - $catid = (int)$attribs["_catid"]; - $field = $attribs["_field"]; - if(!$catid) - $catid = $objCatList->CurrentCategoryID(); - - if(strlen($field)) - { - $cat =& $objCatList->GetCategory($catid); - if(is_object($cat)) - { - $element = new clsHtmlTag(); - $element->name=$cat->TagPrefix; - $element->attributes = $attribs; - $ret = $cat->ParseObject($element); - } - } - if($attribs["_striphtml"]) - $ret = strip_tags($ret); - return $ret; -} - -/* - @description: returns the date of the last modification to a category - @attrib: _Part:: part of the date to display - @attrib: _Local:bool: If set, only subcategories of the current category is checked - @example: -*/ -function m_category_modified($attribs) -{ - global $objConfig, $objCatList; - - $ado = &GetADODBConnection(); - - if($attribs["_local"] && $objCatList->CurrentCategoryID() != 0) - { - $c =& $objCatList->GetItem($objCatList->CurrentCategoryID()); - $catlist = $c->GetSubCatIds(); - - $catwhere = "CategoryId IN (".explode(",",$catlist).")"; - $sql = "SELECT MAX(Modified) as ModDate,MAX(CreatedOn) as NewDate FROM ".GetTablePrefix()."Category "; - $sql .= "INNER JOIN ".GetTablePrefix()."CategoryItems ON (".GetTablePrefix()."Category.ResourceId=".GetTablePrefix()."CategoryItems.ItemResourceId) "; - $sql .= "WHERE $catwhere LIMIT 1"; - } - else - $sql = "SELECT MAX(Modified) as ModDate FROM ".GetTablePrefix()."Category LIMIT 1"; - $rs = $ado->Execute($sql); - if($rs && ! $rs->EOF) - { - $mod = $rs->fields["ModDate"]; - if($mod) - { - $part = strtolower($attribs["_part"]); - if(strlen($part)) - { - $ret = ExtractDatePart($part,$mod); - } - else - { - $ret = LangDate($mod); - } - } - } - return $ret; -} - -/* - @description: creates LINK tags to include all module style sheets - @attrib: _Modules:: Accepts a comma-separated list of modules to include (ie: "In-Link, In-News, In-Bulletin") - @attrib: _*css:none: Each module may set a custom-named stylesheet. For example, for In-Link the attribute would be _In-Linkcss="..". - If a module does not have a *css attribute, the default (style.css) is assumed. - @example: -*/ -function m_module_stylesheets($attribs) -{ - global $TemplateRoot; - - $IncludeList = explode(",",trim($attribs["_modules"])); - $tpath = GetModuleArray("template"); - for($inc=0;$inc\n"; - } - return $ret; -} - -/* - @description: lists items related to a category - @attrib:CatId:int: Category ID of category, or current category if not set - @attrib:_ListItem: Comma-separated list of item types (ie: Link, Topic, Category, News) The items are listed in the order this list provides, then by priority. - Each item should have its own template passed in as an attribute (_{ItemType}Template) -*/ -function m_related_items($attribs) -{ - global $objItemTypes, $objCatList, $content_set; - static $Related; - - global $CatRelations; - - $cat = $attribs["_catid"]; - if(!is_numeric($cat)) - { - $cat = $objCatList->CurrentCategoryID(); - } - $c =& $objCatList->GetCategory($cat); - $data_sent=0; - if(is_object($c)) - { - $ResourceId = $c->Get("ResourceId"); - $IncludeList = explode(",",trim(strtolower($attribs["_listitems"]))); - $o = ""; - - if(!is_object($CatRelations)) - { - $CatRelations = new clsMultiTypeList(); - LoadRelatedItems($Related, $CatRelations,$c->Get("ResourceId")); - } - - if($CatRelations->NumItems()>0) - { - for($inc=0;$incGetTypeByName($item_type); - if(is_object($objType)) - { - foreach($CatRelations->Items as $item) - { - if(is_object($item)) - { - if(strtolower($objType->Get("ItemName")) == strtolower($item_type) && $item->type==$objType->Get("ItemType")) - { - if(strlen($item->BasePermissionName)) - { - $perm = $item->BasePermissionName.".VIEW"; - $haspem = $objSession->HasCatPermission($perm,$item->Get("CategoryId")); - } - else - $hasperm = 1; - - if($hasperm) - { - $data_sent =1; - $classname = $objType->Get("ClassName"); - if(strlen($classname)) - { - $l = new $classname; - $l->Data = $item->Data; - $o .= $l->ParseTemplate($t); - } - } - } - } - $item = NULL; - } - } - else - echo $item_type." not found
    \n"; - } - } - if($data_sent) - { - return $o; - } - else - { - $content_set=0; - return ""; - } - } - else - { - $content_set = 0; - return ""; - } - } - else - { - $content_set = 0; - return ""; - } -} - -/* - @description: Returns the number of items related to the current category - @attrib:_CatId:int: If set, this is the category ID to use, otherwise the current category is used - @attrib:_ItemType::Name of item to count. If not set, all related items are counted -*/ -function m_related_count($attribs) -{ - global $objItemTypes, $objCatList, $content_set; - - $cat = $attribs["_catid"]; - - if(!is_numeric($cat)) - { - $cat = $objCatList->CurrentCategoryID(); - } - $c =& $objCatList->GetCategory($cat); - $data_sent=0; - //echo "Category: $cat
    ";  print_r($c); echo " 
    "; - if(is_object($c)) - { - $ResourceId = $c->Get("ResourceId"); - if(!is_object($CatRelations)) - { - $CatRelations = new clsMultiTypeList(); - LoadRelatedItems($Related, $CatRelations, $c->Get("ResourceId")); - } - - $item_type = $attribs["_itemtype"]; - if(strlen($item_type)) - { - $objType = $objItemTypes->GetTypeByName($item_type); - if(is_object($objType)) - { - $TargetType = $objType->Get("ItemType"); - } - else - $TargetType=""; - } - - if($CatRelations->NumItems()>0) - { - for($x=0;$x<$CatRelations->NumItems();$x++) - { - $a = $CatRelations->GetItemByIndex($x); - if($a->type == $TargetType || !strlen($TargetType)) - { - $count++; - } - } - } - } - return $count; -} - -/* - @description: Returns the MetaKeywords field for a category, or the system MetaKeywords value - if the category doesn't have a value for MetaKeywords - @attrib: _CatId:int: Category to use (The current category is used by default) -*/ -function m_meta_keywords($attribs = array()) -{ - global $objCatList, $objConfig; - $catid = (int)$attribs["_catid"]; - if(!$catid) - { - $catid = $objCatList->CurrentCategoryID(); - } - if($catid) - { - $c = $objCatList->GetItem($catid); - $keywords = $c->Get("MetaKeywords"); - } - if(!strlen($keywords)) - { - $keywords = $objConfig->Get("MetaKeywords"); - } - return $keywords; -} - -/* - @description: Returns the MetaDescription field for a category, or the system MetaDescription value - if the category doesn't have a value for MetaDescription - @attrib: _CatId:int: Category to use (The current category is used by default) -*/ -function m_meta_description($attribs = array()) -{ - global $objCatList, $objConfig; - - $catid = (int)$attribs["_catid"]; - if(!$catid) - { - $catid = $objCatList->CurrentCategoryID(); - } - if($catid) - { - $c = $objCatList->GetItem($catid); - $desc = $c->Get("MetaDescription"); - } - if(!strlen($desc)) - { - $desc = $objConfig->Get("MetaDescription"); - } - return $desc; -} - -/* - @description: return the number of items in the database - @attrib: _ItemType:: Name of item to count - @attrib: _ListType:: Type of item to count (ie: favorites, editor's pick, etc) - @attrib: _CategoryCount:int: Limit scope to the current category - @attrib: _SubCats:bool: Count items in all subcategories (_CategoryCount must be set) - @attrib: _Today:bool: Count items added today - @attrib: _GroupOnly:bool: Only count items the current user can view - @attrib: _NoCache:bool: Count without using cache -*/ -function m_itemcount($attribs = array()) -{ - global $objItemTypes, $objCatList, $objSession, $objCountCache; - - $Bit_None = 0; - $Bit_Today = 1; - $Bit_Owner = 2; - $Bit_Global = 4; - $Bit_SubCats=8; - - if($attribs["_categorycount"]) - { - $evar = m_BuildEnv(); - } - else - $evar = ""; - - $cat = $attribs["_catid"]; - if(!is_numeric($cat)) - { - $cat = $objCatList->CurrentCategoryID(); - } - - if((int)$cat>0) - $c = $objCatList->GetCategory($cat); - - if(is_numeric($attribs["_itemtype"])) - { - $item = $objItemTypes->GetItem($attribs["_itemtype"]); - } - else - $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]); - - $DoUpdate=0; - - //echo "
    "; print_r($item); echo "
    "; - - $ExtraId=""; - - if(is_object($item)) - { - if($item->Get("ItemType")==1) /* counting categories */ - { - $ret = $objCatList->CountCategories($attribs); - } - else - { - $ListVar =& GetItemCollection($attribs["_itemtype"]); - if(is_object($ListVar)) - { - $ret = $ListVar->PerformItemCount($attribs); - } - } - } - else - $ret = 0; - - return !$ret ? 0 : $ret; -} - -/* - @description: Parse a User field and return the value - @attrib: _Field:: User field to parse - @attrib: _UserId:int: Category ID to parse (uses current user if not set) -*/ -function m_user_field($attribs) -{ - global $objUsers, $objSession; - - $o = ""; - $userid = $attribs["_userid"]; - if(!is_numeric($userid) || $userid=="0") - $userid = $objSession->Get("PortalUserId"); - - if($userid) - { - $u =& $objUsers->GetItem($userid); - if(is_object($u)) - { - $element = new clsHtmlTag(); - $element->name = $u->TagPrefix; - $element->attributes = $attribs; - $o = $u->ParseObject($element); - } - } - return $o; -} - -/* - @description: Parses a user template - @attrib:_Template:tpl: Template to parse - @attrib:_UserId:int: User ID to parse. If not set, the current user is used -*/ -function m_user_detail($attribs = array()) -{ - global $objTemplate, $objUsers, $objSession; - - $tname = $attribs["_template"]; - $UserId = (int)$attribs["_userid"]; - if(!$UserId) - { - $UserId=$objSession->Get("PortalUserId"); - } - if($UserId>0) - { - $u = $objUsers->GetUser($UserId); - $o = $u->ParseTemplate($tname); - } - else - { - $u = new clsPortalUser(NULL); - $o = $u->ParseTemplate($tname); - } - - return $o; -} - -/* - @description: returns a user field from the current profile being viewed - @example: -*/ -function m_user_profile_field($attribs = array()) -{ - if((int)$_GET["UserId"]) - { - $attribs["_userid"] = $_GET["UserId"]; - } - - $ret = m_user_field($attribs); - -/* if ($ret == '') { - $ret = admin_language("lu_Guest"); - }*/ - - return $ret; -} - -/* - @description: Parses a user profile template - @attrib:_Template:tpl: Template to parse - @attrib:_UserId:int: User ID to parse. If not set, the current user is used -*/ -function m_user_profile_detail($attribs) -{ - if((int)$_GET["UserId"]) - { - $attribs["_userid"] = $_GET["UserId"]; - } - $ret = m_user_detail($attribs); - return $ret; -} - -/* - @description: Lists all user profile fields the user has indicated to be public - @attrib: _ItemTemplate:tpl: Template used to list each field - @example: -*/ -function m_user_profile($attribs = array()) -{ - global $objTemplate, $objUsers; - - $tname = $attribs["_itemtemplate"]; - $t = $objTemplate->GetTemplate($tname); - if(is_object($t)) - { - $html = $t->source; - } - - $userid = $_GET["UserId"]; - $o = ""; - - if((int)$userid>0) - { - $u = $objUsers->GetItem($userid); - $vars = $u->GetAllPersistantVars(); - foreach($vars as $field=>$value) - { - if(substr($field,0,3)=="pp_") - { - if($value==1) - { - $src = $html; - $src = str_replace("","",$src); - $src = str_replace("lu_profile_field","lu_".$field,$src); - $o .= $u->ParseTemplateText($src); - } - } - - } - } - - return $o; -} - -/* - @description: List users the current user has marked as 'friend' - @attrib: _Status:: Determines which online status to list, either "online" or "offline". - @attrib: _ItemTemplate:tpl: Template used to parse list items -*/ -function m_list_friends($attribs = array()) -{ - global $objUsers, $objSession; - - global $online_friends; - - $ado = &GetADODBConnection(); - - $status = strtolower($attribs["_status"]); - - $logedin_user = $objSession->Get("PortalUserId"); - $u =& $objUsers->GetUser($logedin_user); - - //echo "
    "; print_r($u); echo "
    "; - if(!isset($online_friends) || $status=="online") - { - $ftable = GetTablePrefix()."Favorites"; - $stable = GetTablePrefix()."UserSession"; - $ptable = GetTablePrefix()."PortalUser"; - if(isset($online_friends)) - { - foreach($online_friends as $id=>$name) - { - $u =& $objUsers->GetUser($id); - $o .= $u->ParseTemplate($attribs["_itemtemplate"]); - } - } - else - { - $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable "; - $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON "; - $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; - //echo $sql; - $rs = $ado->Execute($sql); - while($rs && ! $rs->EOF) - { - $u =& $objUsers->GetItem($rs->fields["PortalUserId"]); - if($status=="online") - { - $o .= $u->ParseTemplate($attribs["_itemtemplate"]); - } - $online_friends[]=$rs->fields["PortalUserId"]; - if(ADODB_EXTENSION>0) - { - adodb_movenext($rs); - } - else - $rs->MoveNext(); - } - } - } - - if($status=="offline") - { - $ftable = GetTablePrefix()."Favorites"; - $stable = GetTablePrefix()."UserSession"; - $ptable = GetTablePrefix()."PortalUser"; - - $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable"; - if(count($online_friends)>0) - { - $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable "; - $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND "; - $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; - } - else - { - $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable "; - $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; - } - - //echo $sql; - $rs = $ado->Execute($sql); - while($rs && ! $rs->EOF) - { - $u = $objUsers->GetItem($rs->fields["PortalUserId"]); - $o .= $u->ParseTemplate($attribs["_itemtemplate"]); - if(ADODB_EXTENSION>0) - { - adodb_movenext($rs); - } - else - $rs->MoveNext(); - } - } - $t = $attribs["_itemtemplate"]; - return $o; -} - -/* - @description: Returns the number of users the current user has marked as 'friend' - @attrib: _Status:: Determines which online status to count, either "online" or "offline". -*/ -function m_friend_count($attribs=array()) -{ - global $objUsers, $objSession; - - global $online_friends; - - $ado = &GetADODBConnection(); - - $logedin_user = $objSession->Get("PortalUserId"); - $u =& $objUsers->GetUser($logedin_user); - - $status = strtolower($attribs["_status"]); - if(!isset($online_friends) || $status=="online") - { - $ftable = GetTablePrefix()."Favorites"; - $stable = GetTablePrefix()."UserSession"; - $ptable = GetTablePrefix()."PortalUser"; - if(isset($online_friends) && $status="online") - { - return count($online_friends); - } - else - { - $online_friends = array(); - $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable "; - $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON "; - $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; - //echo $sql."
    \n"; - $rs = $ado->Execute($sql); - while($rs && ! $rs->EOF) - { - $online_friends[$rs->fields["PortalUserId"]]=$rs->fields["PortalUserId"]; - if(ADODB_EXTENSION>0) - { - adodb_movenext($rs); - } - else - $rs->MoveNext(); - } - if($status=="online") - return count($online_friends); - } - } - - if($status=="offline") - { - $ftable = GetTablePrefix()."Favorites"; - $stable = GetTablePrefix()."UserSession"; - $ptable = GetTablePrefix()."PortalUser"; - - $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable"; - - if(count($online_friends)>0) - { - $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable "; - $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND "; - $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; - } - else - { - $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable "; - $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; - } - $rs = $ado->Execute($sql); - return $rs->fields["ItemCount"]; - } -} - -/* - @description: Returns the number of users the current user has marked as 'friend' today -*/ -function m_friend_count_today($attribs) -{ - global $objSession; - - $logedin_user = $objSession->Get("PortalUserId"); - - $ret =0; - $ado = &GetADODBConnection(); - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $sql = "SELECT count(*) as c FROM ".GetTablePrefix()."Favorites WHERE ItemTypeId=6 and PortalUserId=".$objSession->Get("PortalUserId")." AND Modified>$today"; - $rs = $ado->Execute($sql); - if($rs && !$rs->EOF) - $ret = $rs->fields["c"]; - return $ret; -} - -/* - @description: Returns the number of items in a search result - - @Example: () -*/ -function m_search_item_count($attribs) -{ - global $objItemTypes, $objCatList, $objSession, $CountVal; - - if(!is_array($CountVal)) - $CountVal=array(); - $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]); - if(is_object($item)) - { - $val = $CountVal[$item->Get("ItemType")]; - if(is_numeric($val)) - return $val; - $where = "ItemType=".$item->Get("ItemType"); - $table = $objSession->GetSearchTable(); - $ret = TableCount($table,$where,0); - $CountVal[$item->Get("ItemType")]=(int)$ret; - } - - return $ret; -} -/* - @description: Returns the number of categories in a search result - @Example: () -*/ -function m_search_cat_count($attribs = array()) -{ - global $objItemTypes, $objCatList, $objSession, $CountVal, $objSearchCats; - - if(!is_object($objSearchCats)) - { - $objSearchCats = new clsCatList(); - $objSearchCats->SourceTable = $objSession->GetSearchTable(); - $objSearchCats->Clear(); - } - - LoadCatSearchResults($attribs); - //echo "
    "; print_r($objSearchCats->Items); echo "
    "; - $ret = 0; - $keywords = $objSession->GetVariable("Search_Keywords"); - - if ($keywords) { - foreach ($objSearchCats->Items as $cat) { - - if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords))) { - $ret++; - } - } - } - else { - $ret = $objSearchCats->QueryItemCount; - } - - if ($ret == '') { - $ret = 0; - } - - //echo $ret; - //$objSearchCats->QueryItemCount = $ret; - - return $ret; -} - -/* - @description: Returns super global variable by type and name - @attrib: _Name:: Name of variable - @attrib: _Type:: Type super global variable
    Possible Values: -
      -
    • get: $_GET super variable -
    • post: $_POST super variable -
    • cookie: $_COOKIE super variable -
    • env: $_ENV super variable -
    • server: $_SERVER super variable -
    • session: $_SESSION super variable -
    - @Example: -*/ -function m_get_var($attribs = array()) -{ - global $_GET, $_POST, $_COOKIE, $_FILES, $_ENV, $_SERVER, $_SESSION; - - $type = strtolower($attribs['_type']); - $name = $attribs['_name']; - - switch ($type) - { - case "get": - $vars = $_GET; - break; - case "cookie": - $vars = $_COOKIE; - break; - case "files": - $vars = $_FILES; - break; - case "server": - $vars = $_SERVER; - break; - case "session": - $vars = $_SESSION; - break; - case "env": - $vars = $_ENV; - break; - case "post": - $vars = $_POST; - break; - default : - $vars = $_POST; - break; - } - $ret = $vars[$name]; - - return $ret; -} - -/* - @description: Returns number of users currently on-line - @attrib: _LastActive:: Last user/session activity in seconds - @attrib: _OwnCount:bool: Count user's own session -*/ -function m_users_online($attribs = array()) -{ - global $objSession; - - $LastActive = (int)($attribs['_lastactive']); - $OwnCount = (int)($attribs['_owncount']); - - if ($LastActive && !is_null($LastActive)) - $sql_add = " AND LastAccessed>".(time()-$LastActive); - - if (!$OwnCount || is_null($OwnCount)) - $sql_add.= " AND SessionKey!='".$objSession->GetSessionKey()."'"; - - $ado = &GetADODBConnection(); - $sql = "SELECT COUNT(*) AS Counter FROM ".GetTablePrefix()."UserSession WHERE Status=1".$sql_add; - $rs = $ado->Execute($sql); - $ret = ($rs && !$rs->EOF)? $rs->fields["Counter"] : 0; - - return $ret; -} - -function m_debug_mode($attribs = array()) -{ - $const_name = $attribs['_debugconst']; - return defined($const_name) && (constant($const_name) == 1) ? 'yes' : ''; -} - -function m_info($attribs = array()) -{ - switch ($attribs['_infotype']) - { - case 'site': - global $objConfig; - $ret = ThisDomain().$objConfig->Get('Site_Path'); - break; - - default: - $ret = ''; - break; - } - return $ret; -} - -function m_module_enabled($attribs = array()) -{ - global $objModules; - $module = $attribs['_module']; - - // check if module is installed - $ModuleItem = $objModules->GetItemByField('Name', $module); - if( !is_object($ModuleItem) ) return ''; - - // module is enabled - $ret = $ModuleItem->Get('Loaded') == 1; - - // check if installed module is licensed - return $ret && _ModuleLicensed($module) ? 'yes' : ''; -} - -function m_recall($attribs = array()) -{ - global $objSession; - return $objSession->GetVariable($attribs['_name']); -} - -?> +";print_r($pieces);echo ""; + $m_var_list["cat"] = $pieces[0]; + $m_var_list["p"] = $pieces[1]; + $objCatList->Page = $m_var_list["p"]; + + $m_var_list["lang"] = $pieces[2]; + $m_var_list["theme"] = $pieces[3]; + } + else + { + $m_var_list["cat"]=0; + $m_var_list["p"] = 1; + $m_var_list["lang"] = $objLanguages->GetPrimary(); + $m_var_list["theme"]= $objThemes->GetPrimaryTheme(); + } +} + +function m_BuildEnv() +{ + global $m_var_list, $m_var_list_update; + $module_vars = Array('cat','p','lang','theme'); + $ret = GenerateModuleEnv('m', $module_vars); + if( isset($GLOBALS['m_var_list_update']['cat']) ) unset($GLOBALS['m_var_list_update']['cat']); + return $ret; +} + +function m_GetVar($name) +{ + // get variable from template variable's list + global $m_var_list, $m_var_list_update; + return isset($m_var_list_update[$name]) ? $m_var_list_update[$name] : $m_var_list[$name]; +} + +function &LoadRelatedItems(&$Relations,&$RelatedItems,$ResourceId) +{ + global $objItemTypes; + + if(!is_object($Relations)) + { + $Relations = new clsRelationshipList(); + } + //$Relations->debuglevel = 2; + if ($ResourceId != '') { + $sql = sprintf("SELECT RelationshipId, Type, Enabled, Priority, + IF(TargetId = %1\$s, TargetId, SourceId) AS SourceId, + IF(TargetId = %1\$s, SourceId, TargetId) AS TargetId, + IF(TargetId = %1\$s, TargetType, SourceType) AS SourceType, + IF(TargetId = %1\$s, SourceType, TargetType) AS TargetType + FROM %%s", $ResourceId); + + $where = "((SourceId=$ResourceId) OR (TargetId=$ResourceId AND Type=1)) AND Enabled=1"; + $Relations->LoadRelated($where,"",$sql); + $ids = array(); + if($Relations->NumItems()>0) + { + foreach($Relations->Items as $r) + { + if($r->Get("SourceId")==$ResourceId) + { + $ids[$r->Get("TargetType")][] = $r->Get("TargetId"); + } + if($r->Get("TargetId")==$ResourceId && $r->Get("Type")==1) + { + $ids[$r->Get("SourceType")][] = $ResourceId; + } + } + foreach($ids as $ItemType=>$idlist) + { + $Item =& $objItemTypes->GetItem($ItemType); + $table = GetTablePrefix().$Item->Get("SourceTable"); + if($ItemType!=1) + { + $cattable = GetTablePrefix()."CategoryItems"; + $sql = "SELECT *,CategoryId FROM $table INNER JOIN $cattable ON "; + $sql .=" ($table.ResourceId=$cattable.ItemResourceId) WHERE $table.Status=1 AND PrimaryCat=1 "; + $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")"; + } + else + { + $sql = "SELECT *,CategoryId FROM $table "; + $sql .="WHERE $table.Status=1 "; + $sql .=" AND ResourceId IN (".implode(",",$ids[$ItemType]).")"; + } + // echo $sql."
    \n"; + $RelatedItems->Query_Item($sql,-1,-1,$ItemType); + } + } + } +} + + +/* + @description: Inserts the html from a remote source + @attrib: _url:: Remote URL to include + @attrib: _StartPos:: Numeric start point of text to include, or string match + @attrib: _EndPos:: Numeric end point of text to include, or string match + @example: +*/ +function m_insert_url($attribs=array()) +{ + global $pathtoroot; + + $url = $attribs["_url"]; + $StartPos = $attribs["_startpos"]; + $EndPos = $attribs["_endpos"]; + + $socket = new Socket($url,0,NULL); + $txt = $socket->socket_read_all(); + $lines = explode("\n",$txt); + $txt = substr($txt,strpos($txt,"<")); + $tmp = strtolower($txt); + $bodypos = strpos($tmp,"0) + { + $head = substr($txt,0,$bodypos-1); + $body = substr($txt,$bodypos); + if(substr($tmp,-7)=="") + $body = substr($body,0,-7); + } + else + $body = $txt; + if(strlen($body)) + { + if(strlen($StartPos)) + { + if(!is_numeric($StartPos)) + { + $start = strpos($body,$StartPos); + } + else + $start = (int)$StartPos; + } + else + $start = 0; + if(strlen($EndPos)) + { + if(!is_numeric($EndPos)) + { + $end = strpos($body,$EndPos,$start) + strlen($EndPos); + } + else + $end = (int)$EndPos; + } + else + $end = NULL; + $o = substr($body,$start,$end-$start); + } + return $o; +} + +/* + @description: Displays a template depending on the login status of the user + @attrib: _logintemplate:tpl: template to display when the user is NOT logged in + @attrib: _LoggedinTemplate:tpl: template to display when the user is logged in + @example: +*/ +function m_loginbox($attribs = array()) +{ + global $var_list, $objSession, $objUsers, $objTemplate; + + $userid = $objSession->Get("PortalUserId"); + $groupid = $objSession->Get("GroupId"); + if ($userid == 0) + { + if (strlen($attribs["_logintemplate"])) + $t = $objTemplate->ParseTemplate($attribs["_logintemplate"]); + return $t; + } + else + { + $user =& $objUsers->GetItem($userid); + if (strlen($attribs["_loggedintemplate"])) + $t = $user->ParseTemplate($attribs["_loggedintemplate"]); + return $t; + } +} +/* + @description: result of suggest site action +*/ +function m_suggest_result() +{ + global $suggest_result; + + return $suggest_result; +} + +/* + @description: result of subscribe to mailing list action +*/ +function m_subscribe_result() +{ + global $SubscribeResult; + + if(strlen($SubscribeResult)) + return language($SubscribeResult); + return ""; +} + +/* + @description: email address of user subscribing to mailing list +*/ +function m_subscribe_address() +{ + global $SubscribeAddress; + + if(strlen($SubscribeAddress)) + return $SubscribeAddress; + return ""; +} + +/* + @description: Error message of subscribe to mailing list action +*/ +function m_subscribe_error() +{ + global $SubscribeError; + + if(strlen($SubscribeError)) + return language($SubscribeError); + return ""; +} + + +/* + @description: Displays a prompt for a form field + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _LangText:lang: Language var to use for field label + @attrib: _plaintext:: Plain text to use for field label (langtext is used by default if both are set) + @attrib: _Template:tpl: template used to display the field label (if not set "" is used + @attrib: _ErrorTemplate:tpl: If the field is in an error state (ie missing input) this template is used. Will default to the normal template if not set +*/ +function m_form_prompt($attribs = array()) +{ + global $FormError, $objTemplate, $objConfig; + + $form = strtolower($attribs["_form"]); + $field = strtolower($attribs["_field"]); + + if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto")) + { + $o = ""; + } + else + { + $t = $attribs["_template"]; + if(!strlen($t)) + { + $templateText = ""; + } + $e = $attribs["_errortemplate"]; + if(!strlen($e)) + $e = $t; + if(strlen($attribs["_langtext"])) + { + $txt = language($attribs["_langtext"]); + } + else + $txt = $attribs["_plaintext"]; + + if (strtolower($field) == "dob") + { + if (isset($FormError[strtolower($form)][strtolower($field."_day")]) || isset($FormError[strtolower($form)][strtolower($field."_month")]) || isset($FormError[strtolower($form)][strtolower($field."_year")])) + $rawtext = $objTemplate->GetTemplate($e, true); + } + + if(isset($FormError[strtolower($form)][strtolower($field)])) + { + $rawtext = $objTemplate->GetTemplate($e); + } + elseif (strlen($t)) + $rawtext = $objTemplate->GetTemplate($t); + + if(is_object($rawtext)) + { + $src = $rawtext->source; + $o = str_replace("",$txt, $src); + } + else + $o = str_replace("", $txt, $templateText); + + } + return $o; +} + +/* + @description: Returns text if system is configured to use auto-generated passwords + @attrib:_LangText:lang:Language tag to return + @attrib:_PlainText::Plain text to return (_LangText takes precedece) + @attrib:_Value:bool:Auto Password setting value to match +*/ +function m_autopassword($attribs = array()) +{ + global $objConfig; + if($attribs["_value"]=="true" || $attribs["_value"]==1) + { + $IsAuto = $objConfig->Get("User_Password_Auto"); + } + else + { + $IsAuto = !$objConfig->Get("User_Password_Auto"); + } + + if($IsAuto) + { + if(strlen($attribs["_langtext"])) + { + $ret = language($attribs["_langtext"]); + } + else + $ret = $attribs["_plaintext"]; + if(!$ret) + return "true"; + } + return $ret; +} + +/* + @description: checks if field specified is equals to value specified + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _Value:: Field value to compare to + @example: true +*/ +function m_field_equals($attribs = array()) +{ + global $FormValues; + //print_pre($attribs); + $form = $attribs["_form"]; + $field = $attribs["_field"]; + if(isset($_POST[$field])) + { + $value = $_POST[$field]; + } + else + $value = $FormValues[$form][$field]; + //echo "POST_VALUE: [$value] vs USER_VALUE: [".$attribs['_value']."]
    "; + return $value == $attribs['_value'] ? 1 : ''; +} + +/* + @description: creates an INPUT tag for a form field. All extra attributes are passed to the INPUT tag + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _ForgetValue:bool: if true, forget value + @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting + @example: +*/ +function m_form_input($attribs = array()) +{ + global $FormValues, $objConfig; + + $html_attribs = ExtraAttributes($attribs); + $form = $attribs["_form"]; + $field = strtolower($attribs["_field"]); + if(isset($_POST[$field]) && $attribs['_forgetvalue'] != 1) + { + $value = inp_htmlize($_POST[$field],1); + } + else { + if ($attribs['_forgetvalue'] != 1) { + $value = $FormValues[$form][$field]; + } + } + //echo $form.".".$field."=".$value." = ".$attribs['_forgetvalue']."
    \n"; + if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto")) + { + $ret = ""; + } + else + { + $ret = ""; + if($attribs["_required"]) + $ret .= ""; + if($attribs["_custom"]) + $ret .= ""; + } + return $ret; +} + +/* + @description: creates an INPUT tag (type checkbox) for a form field. All extra attributes are passed to the INPUT tag + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _Value:bool: If true, the radio button is CHECKED + @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting + @attrib: _Custom:bool: If set, handled as a custom field + @example: +*/ +function m_form_checkbox($attribs = array()) +{ + global $FormValues, $objConfig; + + $html_attribs = ExtraAttributes($attribs); + $form = $attribs["_form"]; + $field = strtolower($attribs["_field"]); + if(isset($_POST[$field])) + { + $value = (int)$_POST[$field]; + if($value==1) + $checked = " CHECKED"; + } + else + { + $value = (int)$FormValues[$form][$field]; + if($value==1) + $checked=" CHECKED"; + } + //echo $form.".".$field."=".$value."
    \n"; + $ret = ""; + if($attribs["_required"]) + $ret .= ""; + if($attribs["_custom"]) + $ret .= ""; + + return $ret; +} + +/* + @description: creates an INPUT tag (type radio) for a form field. All extra attributes are passed to the INPUT tag + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _Value:: Value assigned to radio button. If the form field value matches this attribute, the radio button is CHECKED + @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting + @attrib: _Custom:bool: If set, handled as a custom field + @example: +*/ +function m_form_radio($attribs = array()) +{ + global $FormValues, $objConfig; + + $html_attribs = ExtraAttributes($attribs); + $form = $attribs["_form"]; + $field = strtolower($attribs["_field"]); + $val = $attribs["_value"]; + if(isset($_POST[$field])) + { + $value = (int)$_POST[$field]; + if($value==1) + $checked = " CHECKED"; + } + else + { + $value = (int)$FormValues[$form][$field]; + if($value==$val) + $checked=" CHECKED"; + } + //echo $form.".".$field."=".$value."
    \n"; + $ret = ""; + if($attribs["_required"]) + $ret .= ""; + if($attribs["_custom"]) + $ret .= ""; + + return $ret; +} +/* + @description: returns the value for a form field. This may be defaulted by the system or set by a previus submit (as in an error condition) + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @example: +*/ +function m_form_value($attribs = array()) +{ + global $FormValues; + + $form = $attribs["_form"]; + $field = strtolower($attribs["_field"]); + + if(isset($_POST[$field])) + { + $value = inp_htmlize($_POST[$field],1); + } + else + $value = inp_htmlize($FormValues[$form][$field]); + //echo "
    "; print_r($FormValues); echo "
    "; + return $value; +} + +/* + @description: creates an form OPTION tag for a form SELECT tag. + All extra attributes are passed to the OPTION tag. + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _Value:: Value to use for this option (ie the value attribute) If the current value of the select + field is the same as this attribute, then this option will be set SELECTED. + @attrib: _langtext:lang: language tag to display for this option in the SELECT dropdown + @attrib: _plaintext:: plain text to display for this option in the SELECT dropdown (if _langtext is set, it is used instead of _plaintext) + @example: $txt"; + + return $o; +} + +/* + @description: creates an form TEXTAREA field. All extra attributes are passed to the TEXTAREA tag + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting + @attrib: _Custom:bool: If set, handled as a custom field + @example: +*/ +function m_form_textarea($attribs = array()) +{ + global $FormValues; + $html_attribs = ExtraAttributes($attribs); + $field = $attribs["_field"]; + $form = $attribs["_form"]; + if(isset($_POST[$field])) + { + $value = stripslashes($_POST[$field]); + } + else + $value = stripslashes($FormValues[$attribs["_form"]][$field]); + $ret = ""; + if($attribs["_required"]) + $ret .= ""; + if($attribs["_custom"]) + $ret .= ""; + return $ret; +} + +/* + @description: creates an form field to upload images. (INPUT type=file) All extra attributes are passed to the INPUT tag + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name + @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting + @attrib: _ImageTypes:: Comma-separated list of file extensions allowed + @attrib: _Thumbnail:bool: If true, image is treated as a thumbnail + @attrib: _ImageName:: System name of image being uploaded + @attrib: _MaxSize:int: Maximum size of image to upload, or 0 to allow all +*/ +function m_form_imageupload($attribs = array()) +{ + $html_attribs = ExtraAttributes($attribs); + $field = $attribs["_field"]; + $form = $attribs["_form"]; + $TypesAllowed = $attribs["_imagetypes"]; + $isthumb = (int)$attribs["_thumbnail"]; + $imgname = $attribs["_imagename"]; + $maxsize = $attribs["_maxsize"]; + + $ret = ""; + $ret .= ""; + $ret .= ""; + $ret .= ""; + $ret .= ""; + if($attribs["_required"]) + $ret .= ""; + return $ret; +} + +/* + @description: Returns the error text for a form field, or nothing if no error exists for the field + @attrib: _Form:: Form name for the field + @attrib: _Field:: Field Name +*/ +function m_form_error($attribs = array()) +{ + global $FormError; + + $form = $attribs["_form"]; + $field = $attribs["_field"]; + + return $FormError[$form][$field]; +} + +/** + @description: Provides a simple solution for displaying a language flag when a form has an error. Generic and limited to 1 language vairable. + @attrib: _Form:: Form name for the field +*/ +function m_form_has_errors($attribs = array()) +{ + // shows specified template once if form has error(-s) + global $FormError; + $f = $attribs["_form"]; + + $ret = is_array($FormError[$f]); + if(!$ret) return ''; + return isset($attribs["_asif"]) ? true : language('lu_errors_on_form'); +} + +/** + @description: Lists form errors for all fields in a form + @attrib: _Form:: Form name for the field + @attrib: _ItemTemplate:tpl: Template used to display each form error (if not set, "" is used) +*/ +function m_list_form_errors($attribs = array()) +{ + global $FormError, $content_set, $objTemplate; + + $t = $attribs["_itemtemplate"]; + if(!strlen($t)) + $templateText = ""; + $f = $attribs["_form"]; + $o = ""; + if (strlen($t)) + { + $rawtext = $objTemplate->GetTemplate($t, true); + $src = $rawtext->source; + } + else + $src = $templateText; + + //echo $f."
    "; + //echo $t."
    "; +// echo "
    "; print_r($FormError); echo "
    "; + if(is_array($FormError[$f])) + { + foreach($FormError[$f] as $e) + { + $o .= str_replace("",$e, $src); + } + } + if(!strlen($o)) + $content_set = 0; + return $o; +} + +function m_form_load_values($FormName,$IdValue) +{ + global $FormValues, $objUsers, $objSession, $objConfig; + + switch($FormName) + { + case "m_acctinfo": + $u =& $objUsers->GetItem($IdValue); + $FormValues[$FormName]["username"] = $u->Get("Login"); + //$FormValues[$FormName]["password"] = $u->Get("Password"); + //$FormValues[$FormName]["passwordverify"] = $u->Get("Password"); + + $FormValues[$FormName]["password"] = ""; + $FormValues[$FormName]["passwordverify"] = ""; + + $FormValues[$FormName]["firstname"] = $u->Get("FirstName"); + $FormValues[$FormName]["lastname"] = $u->Get("LastName"); + $FormValues[$FormName]["email"] = $u->Get("Email"); + $FormValues[$FormName]["phone"] = $u->Get("Phone"); + $FormValues[$FormName]["street"] = $u->Get("Street"); + $FormValues[$FormName]["city"] = $u->Get("City"); + $FormValues[$FormName]["state"] = $u->Get("State"); + $FormValues[$FormName]["zip"] = $u->Get("Zip"); + $FormValues[$FormName]["country"] = $u->Get("Country"); + +// $FormValues[$FormName]["dob"] = LangDate($u->Get("dob")); + $FormValues[$FormName]["dob_day"] = date("d", $u->Get("dob")); + $FormValues[$FormName]["dob_year"] = date("Y", $u->Get("dob")); + $FormValues[$FormName]["dob_month"] = date("m", $u->Get("dob")); + + $u->LoadCustomFields(); + if(is_array($u->CustomFields->Items)) + { + foreach($u->CustomFields->Items as $f) + { + $FormValues[$FormName][$f->Get("FieldName")] = $f->Get("Value"); + } + } + break; + case "m_profile": + $u =& $objUsers->GetItem($IdValue); + if(is_object($u)) + { + $FormValues[$FormName]["pp_firstname"] = $objSession->GetPersistantVariable("pp_firstname"); + $FormValues[$FormName]["pp_lastname"] = $objSession->GetPersistantVariable("pp_lastname"); + $FormValues[$FormName]["pp_dob"] = $objSession->GetPersistantVariable("pp_dob"); + $FormValues[$FormName]["pp_email"] = $objSession->GetPersistantVariable("pp_email"); + $FormValues[$FormName]["pp_phone"] = $objSession->GetPersistantVariable("pp_phone"); + $FormValues[$FormName]["pp_street"] = $objSession->GetPersistantVariable("pp_street"); + $FormValues[$FormName]["pp_city"] = $objSession->GetPersistantVariable("pp_city"); + $FormValues[$FormName]["pp_state"] = $objSession->GetPersistantVariable("pp_state"); + $FormValues[$FormName]["pp_zip"] = $objSession->GetPersistantVariable("pp_zip"); + $FormValues[$FormName]["pp_country"] = $objSession->GetPersistantVariable("pp_country"); + } + break; + case "m_simplesearch": + $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords"); + break; + case "m_simple_subsearch": + $FormValues[$FormName]["keywords"] = $objSession->GetVariable("Search_Keywords"); + break; + + } +} + +/* + @description: Generates the ACTTION property for a FORM tag used by In-Portal + @attrib: _Template:tpl: If set, this is the template the form submits to (default is the current template) + @attrib: _Form:: The form name
    Possible Values: +
      +
    • login: user login +
    • logout: user logout +
    • forgotpw: Form to prompt the user for forgotten password information +
    • forgotpw_confirm: confirmation form for forgotpw +
    • suggest: form to suggest the site to a friend +
    • suggest_confirm: form to confirm suggestion of the site to a friend +
    • m_subscribe: form to subscribe to the mailing list +
    • subscribe_confirm: form to confirm subscription to the mailing list +
    • m_unsubscribe: form to unsubscribe from the mailing list +
    • unsubscribe_confirm: form to confirm un-subscription from the mailing list +
    • m_acctinfo: user account information +
    • m_profile: system-level profile information +
    • m_register: New User registration form +
    • m_addcat: Suggest Category form +
    • m_addcat_confirm: Confirmation for add category +
    • m_simplesearch: Perform a simple search +
    • m_simple_subsearch: Search within results +
    • m_adv_searchtype: Form to select type of advanced search +
    • m_adv_subsearch: Advanced Search +
    • error_access: form displayed on the access denied template +
    • error_template: Form displayed on the template error page +
    • m_set_theme: Form displayed for theme selection +
    + @attrib: _SubscribeTemplate:tpl: The destination template with "m_subscribe", "subscribe_confirm", "unsubscribe_confirm" _Form actions. Can be reused in other scenarios as programmed. + @attrib: _UnSubscribeTemplate:tpl: The destination template for "m_subscribe" _Form action. Can be reused in other scenarios as programmed. + @attrib: _ConfirmTemplate:tpl: The destination template for "m_unsubscribe", "suggest" _Form actions. Can be reused in other scenarios as programmed. + @attrib: _DestTemplate:tpl: The destination template for "suggest_confirm", "suggest" _Form actions. Can be reused in other scenarios as programmed. + @attrib: _ErrorTemplate:tpl: The destination template extensively used in most of _Form actions in case of error. + @attrib: _Referer:bool: The destination template will be taken from referer page we can from. + + @example: "> +*/ +function m_form_action($attribs = array()) +{ + global $var_list, $var_list_update, $m_var_list_update, $objSession, $objConfig, $objCatList; + + $target_template = $attribs["_template"]; + if(strlen($target_template)) + { + $var_list_update["t"] = $target_template; + } + else + $var_list_update["t"] = $var_list["t"]; + + $ret = ""; + $form = strtolower($attribs["_form"]); + switch($form) + { + case "login": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_login"; + if($attribs["_successtemplate"]) + { + $ret .= "&dest=".$attribs["_successtemplate"]; + } + else + if(strlen($var_list["dest"])) + $ret .= "&dest=".$var_list["dest"]; + } + break; + case "logout": + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_logout"; + break; + case "forgotpw": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + if(strlen($attribs["_errortemplate"])) + { + $err = $attribs["_errortemplate"]; + } + else + $err = $var_list["t"]; + $ret = GetIndexURL(2)."?env=".BuildEnv()."&Action=m_forgotpw&error=$err"; + } + break; + case "forgotpw_confirm": + $ret = GetIndexURL(2)."?env=".BuildEnv(); + break; + case "suggest": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_suggest_email"; + if(strlen($attribs["_confirmtemplate"])>0) + { + $ret .= "&Confirm=".$attribs["_confirmtemplate"]; + } + if(strlen($Dest)) + { + $ret .= "&DestTemplate=$Dest"; + } + else + { + if(strlen($attribs["_confirmtemplate"])>0) + $ret .="&DestTemplate=".$var_list["t"]; + } + + if(strlen($attribs["_errortemplate"])>0) + { + $ret .= "&Error=".$attribs["_errortemplate"]; + } + } + break; + case "suggest_confirm": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + if(strlen($_GET["DestTemplate"])) + { + $var_list_update["t"] = $_GET["DestTemplate"]; + } + else + $var_list_update["t"] = "index"; + + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + break; + case "m_subscribe": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe_confirm"; + if(strlen($attribs["_subscribetemplate"])) + { + $ret .="&Subscribe=".$attribs["_subscribetemplate"]; + } + + if(strlen($attribs["_unsubscribetemplate"])>0) + { + $ret .= "&Unsubscribe=".$attribs["_unsubscribetemplate"]; + } + if(strlen($attribs["_errortemplate"])>0) + { + $ret .= "&Error=".$attribs["_errortemplate"]; + } + } + break; + + case "subscribe_confirm": + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_subscribe"; + if($attribs["_subscribetemplate"]) + $ret .= "&Subscribe=".$attribs["_subscribetemplate"]; + break; + case "unsubscribe_confirm": + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe"; + if($attribs["_subscribetemplate"]) + $ret .= "&Subscribe=".$attribs["_subscribetemplate"]; + break; + case "m_unsubscribe": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_unsubscribe"; + if(strlen($attribs["_confirmtemplate"])>0) + { + $ret .= "&Confirm=".$attribs["_confirmtemplate"]; + } + if(strlen($Dest)) + { + $ret .= "&DestTemplate=$Dest"; + } + else + { + if(strlen($attribs["_confirmtemplate"])>0) + $ret .="&DestTemplate=".$var_list["t"]; + } + } + + if(strlen($attribs["_confirmtemplate"])>0) + { + $ret .="&ErrorTemplate=".$attribs["_confirmtemplate"]; + } + + + break; + case "m_unsubscribe_confirm": + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + break; + case "m_acctinfo": + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_acctinfo&UserId=".$objSession->Get("PortalUserId"); + m_form_load_values($form, $objSession->Get("PortalUserId")); + break; + case "m_profile": + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_profile&UserId=".$objSession->Get("PortalUserId"); + m_form_load_values($form,$objSession->Get("PortalUserId")); + break; + + case "m_set_theme": + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_set_theme"; + break; + + case "m_register": + + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_register"; + + switch ($objConfig->Get("User_Allow_New")) + { + case "1": + if(strlen($attribs["_confirmtemplate"]) && $objConfig->Get("User_Password_Auto")) + $_dest = "&dest=".$attribs["_confirmtemplate"]; + else + $_dest = "&dest=".$attribs["_logintemplate"]; + break; + + case "2": + if(strlen($attribs["_notallowedtemplate"])) + $_dest = "&dest=".$attribs["_notallowedtemplate"]; + break; + + case "3": + if(strlen($attribs["_pendingtemplate"])) + $_dest = "&dest=".$attribs["_pendingtemplate"]; + break; + } + + if (strlen($_dest)) + $ret .= $_dest; + } + break; + + case "register_confirm": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + break; + case "m_addcat": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $action = "m_add_cat"; + if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING")) + { + if(strlen($attribs["_confirmpending"])) + { + $ConfirmTemplate = $attribs["_confirmpending"]; + } + else + $ConfirmTemplate = $attribs["_confirm"]; + $action="m_add_cat_confirm"; + } + + if ($objSession->HasCatPermission("CATEGORY.ADD")) + { + $ConfirmTemplate = $attribs["_confirm"]; + $action="m_add_cat_confirm"; + } + + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=$action"; + if(strlen($ConfirmTemplate)) + $ret .= "&Confirm=$ConfirmTemplate"; + + if (strlen($attribs["_mod_finishtemplate"])) { + + $CurrentCat = $objCatList->CurrentCategoryID(); + if((int)$CurrentCat>0) + { + $c = $objCatList->GetCategory($CurrentCat); + + //will prefix the template with module template root path depending on category + $ids = $c->GetParentIds(); + $tpath = GetModuleArray("template"); + $roots = GetModuleArray("rootcat"); + + // get template path of module, by searching for moudle name + // in this categories first parent category + // and then using found moudle name as a key for module template paths array + $path = $tpath[array_search ($ids[0], $roots)]; + $t = $path . $attribs["_mod_finishtemplate"]; + } + else { + $t = $attribs["_mod_finishtemplate"]; //Just in case + } + } + else { + $t = $attribs["_finishtemplate"]; + } + + $ret .="&DestTemplate=".$t; + } + break; + case "m_addcat_confirm": + $target_template = $_GET["DestTemplate"]; + if(strlen($target_template)) + { + $var_list_update["t"] = $target_template; + } + else + $var_list_update["t"] = $var_list["t"]; + $ret = GetIndexURL(2)."?env=".BuildEnv(); + break; + case "m_simplesearch": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_search"; + + if(strlen($attribs["_errortemplate"])) + $ret.= "&Error=".$attribs["_errortemplate"]; + + m_form_load_values($form, 0); + } + break; + case "m_simple_subsearch": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_simple_subsearch"; + m_form_load_values($form,0); + } + break; + case "m_adv_search_type": + if(!$objSession->SessionEnabled()) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_advsearch_type"; + m_form_load_values($form,0); + } + break; + case "m_adv_search": + $SearchType = $_GET["type"]; + if(!is_numeric($SearchType)) + $SearchType = $_POST["itemtype"]; + if(!$objSession->SessionEnabled() && !strlen($SearchType)) + { + $var_list_update["t"] = "error_session"; + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + } + else + { + $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=m_adv_search&type=$SearchType"; + m_form_load_values($form,0); + } + break; + + case "error_access": + $target_template = $_GET["DestTemplate"]; + if(!strlen($target_template)) + $target_template="login"; + $var_list_update["t"] = $target_template; + + $ret = GetIndexURL(2)."?env=" . BuildEnv(); + break; + + case "error_template": + + $target_template = $_GET["DestTemplate"]; + + if($attribs["_referer"] == 1) + { + $target_template = "_referer_"; + } + elseif (!strlen($target_template)) + { + $target_template = "index"; + } + + $var_list_update["t"] = $target_template; + +// $m_var_list_update["cat"]=0; + + $ret = GetIndexURL(2)."?env=".BuildEnv(); + + break; + + } + return $ret; +} + +/* + @description: creates a URL to allow the user to log out. Accepts the same attributes as m_template_link + +*/ +function m_logout_link($attribs) +{ + $ret = m_template_link($attribs)."&Action=m_logout"; + return $ret; +} + +/* + @description: returns a URL to the current theme + @attrib: _page:: Additional address to be added to the end of the theme URL +*/ +function m_theme_url($attribs=array()) +{ + global $objConfig,$objSession, $objThemes, $CurrentTheme; + + if(!is_object($CurrentTheme)) + $CurrentTheme = $objThemes->GetItem($m_var_list["theme"]); + + $theme_url = "http://". ThisDomain().$objConfig->Get("Site_Path")."themes/".$CurrentTheme->Get("Name")."/"; + if($attribs["_page"]) + { + if ($attribs["_page"] != 'current') + { + $theme_url .= $attribs["_page"]; + } + else + { + $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv(); + } + } + return $theme_url; +} + +/* + @description: returns a URL to the current theme +*/ +function m_current_page_url($attribs=array()) +{ + global $objConfig,$objSession; + + $theme_url = "http://".ThisDomain().$objConfig->Get("Site_Path")."index.php?env=".BuildEnv(); + + return $theme_url; +} + +/* + @description: returns a URL to the current theme + @attrib: _fullpath:bool: Append the title with the full path of the current category + @attrib: _currentcategory:bool: Append the title with the current category + @attrib: _catfield:: If _currentcategory is used, this attribute determines which category field to use (Name, Description, etc) Defaults to Name +*/ +function m_page_title($attribs = array()) +{ + global $objConfig, $objCatList; + + $ret = $objConfig->Get("Site_Name"); + if($attribs["_fullpath"] || $attribs["_currentcategory"]) + { + $CurrentCat = $objCatList->CurrentCategoryID(); + if((int)$CurrentCat>0) + { + $c = $objCatList->GetCategory($CurrentCat); + if($attribs["_fullpath"]) + { + $path = $c->Get("CachedNavbar"); + + if(strlen($path)) + $ret .= " - ".$path; + } + else + { + if($attribs["_currentcategory"]) + { + $f = $attribs["_catfield"]; + if(!strlen($f)) + $f = "Name"; + $ret .= " - ".$c->Get($f); + } + } + } + } + $ret = stripslashes($ret); + return $ret; +} + +/* + @description: list all active themes + @attrib: _ItemTemplate:tpl: Template to display each theme in the list +*/ +function m_list_themes($attribs=array()) +{ + global $objThemes; + + $t = $attribs["_itemtemplate"]; + if(strlen($t)) + { + $objThemes->Clear(); + $objThemes->LoadThemes("Enabled=1","PrimaryTheme DESC"); + + foreach($objThemes->Items as $theme) + { + $o .= $theme->ParseTemplate($t); + } + } + return $o; +} + +/* + @description: display text based on the user's language + @attrib: _Phrase:lang: label to replace with language-specific text + @example: +*/ +function m_language($attribs) +{ + global $objSession, $objLanguages, $ForceLanguage; + + $phrase = $attribs["_phrase"]; + $LangId = (int)$ForceLanguage; + if(strlen($phrase)) + { + $lang = $attribs["_language"]; + if(strlen($lang)) + { + $l = $objLanguages->GetItemByField("PackName",$lang); + if(is_object($l)) + { + $LangId = $l->Get("LanguageId"); + } + } + return language($phrase,$LangId); + } + else + return ""; +} + +/* + @description: Creates a URL used to set the current language for a user + @attrib: _language:: Language to set (this value should be the language Pack Name) +*/ +function m_setlang_link($attribs) +{ + global $m_var_list_update, $objSession,$objLanguages; + + $lang = $attribs["_language"]; + if(strlen($lang)) + { + $l = $objLanguages->GetItemByField("PackName",$lang); + if(is_object($l)) + $LangId = $l->Get("LanguageId"); + } + else + $LangId=$objSession->Get("Language"); + if($LangId) + { + $m_var_list_update["lang"] = $LangId; + $ret = GetIndexURL()."?env=".BuildEnv(); + unset($m_var_list_update["lang"]); + } + else + $ret = ""; + return $ret; +} + +/* + @description: list all active languages + @attrib: _ItemTemplate:tpl: Template to display each language in the list +*/ +function m_list_languages($attribs) +{ + global $objLanguages, $content_set; + + $sql = "SELECT * FROM ".GetTablePrefix()."Language WHERE Enabled=1"; + $objLanguages->Clear(); + $objLanguages->Query_Item($sql); + + if($objLanguages->NumItems()>0) + { + foreach($objLanguages->Items as $l) + $o .= $l->ParseTemplate($attribs["_itemtemplate"]); + } + else + $content_set=0; + return $o; +} + +/* + @description: returns the date format for a language + @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set +*/ +function m_lang_dateformat($attribs=array()) +{ + global $objLanguages, $objSession; + + $lang = $attribs["_lang"]; + if(!strlen($lang)) + { + $LangId = $objSession->Get("Language"); + $l = $objLanguages->GetItem($LangId); + } + else + { + $l = $objLanguages->GetItemByField("PackName",$lang); + } + $fmt = GetDateFormat($LangId); + $fmt = GetStdFormat($fmt); + + return $fmt; +} + +/* + @description: returns a language field value + @attrib: _Field:: Language field to return + @attrib: _lang:: Pack Name of language to use. The current language is used if this is not set +*/ +function m_lang_field($attribs = array()) +{ + global $objLanguages, $objSession; + + if(!strlen($attribs["_field"])) + return ""; + $lang = $attribs["_lang"]; + if(!strlen($lang)) + { + $LangId = $objSession->Get("Language"); + $l = $objLanguages->GetItem($LangId); + } + else + { + $l = $objLanguages->GetItemByField("PackName",$lang); + } + if(is_object($l)) + { + //$ret = $l->Get($attribs["_field"]); + $e = new clsHtmlTag(); + $e->name=$l->TagPrefix; + $e->attributes=$attribs; + $ret = $l->ParseObject($e); + } + return $ret; +} + +/* + @description: Creates a URL used to set the current theme for a user + @attrib: _theme:: Name of Theme to set. The template selected in the new them is always "index" +*/ +function m_settheme_link($attribs) +{ + global $m_var_list_update, $objSession, $objThemes, $CurrentTheme; + + $ThemeName = $attribs["_theme"]; + + if(strlen($ThemeName)) + { + $t = $objThemes->GetItemByField("Name",$ThemeName); + if(is_object($t)) + { + $Id = $t->Get("ThemeId"); + } + else + $Id = 0; + } + else + { + $t = $CurrentTheme; + $Id = 0; + } + $m_var_list_update["theme"] = $Id; + $ret = GetIndexURL()."?env=".BuildEnv(); + unset($m_var_list_update["theme"]); + return $ret; +} + +/* + @description: Initializes categories +*/ +function m_init_cats($attribs = array()) +{ + // save current & previous category (used in pagination) + global $objSession, $objCatList; + global $var_list; + //echo "SID_INIT: ".$var_list["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')
    '; + $objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') ); + $objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() ); + + //$last_cat = $objSession->GetVariable('last_category'); + //$prev_cat = $objSession->GetVariable('prev_category'); + //echo "Last CAT: [$last_cat]
    "; + //echo "Prev CAT: [$prev_cat]
    "; +} + +/* + @description: List all subcategories a user is allowed to view + @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1) + @attrib: _maxlistcount:int: Maximum number of categories to list + @attrib: _FirstItemTemplate:tpl: Template used for the first category listed + @attrib: _LastItemTemplate:tpl: Template used for the last category listed + @attrib: _ItemTemplate:tpl: default template used for category list items + @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag + @example: +*/ +function m_list_cats($attribs = array()) +{ + global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, $objSystemCache; + + $CachedList = GetTagCache("kernel","m_list_cats",$attribs,m_BuildEnv()); + if(strlen($CachedList)) + { + return $CachedList; + } + $cols = $attribs["_columns"]; + if($cols<1) + $cols =1; + $CategoryId = $attribs["_catid"]; + if(!is_numeric($CategoryId)) + $CategoryId = $objCatList->CurrentCategoryID(); + + $cat_count = (int)$attribs["_maxlistcount"]; + /* validation */ + if(strlen($attribs["_itemtemplate"])==0) + { + if($attribs["dataexists"]) + $content_set = 0; + return ""; + } + + $GroupList = $objSession->Get("GroupList"); + if(strlen($GroupList)) + { + $Groups = explode(",",$GroupList); + } + $acl_where = ""; + if(@count($Groups)>0 && is_array($Groups)) + { + $acl_where = array(); + for($i=0;$iClear(); + $OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE); + $objCatList->LoadCategories("ParentId=$CategoryId AND Status=1",$OrderBy); + if ($objCatList->NumItems() == 0) + { + if($attribs["_dataexists"]) + $content_set = 0; + return ""; + } + + $html_attr = ExtraAttributes($attribs); + + $o=""; + $notable = $attribs["_notable"]; + + $count=0; + $row=0; + $var_list_update["t"] = $var_list["t"]; + + if(!$notable) + { + $per_row = ceil($objCatList->NumItems()/$cols); + $o = ""; + $o .= ""; + $o .= "\n
    "; + $CatCount = $objCatList->NumItems(); + foreach($objCatList->Items as $cat) + { + $parsed=0; + if($count==$per_row) + { + $o .= ""; + $count=0; + } + if($row==0 && strlen($attribs["_firstitemtemplate"])) + { + $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); + $parsed=1; + } + if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) + { + $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); + $parsed=1; + } + if(!$parsed) + $o.= $cat->ParseTemplate($attribs["_itemtemplate"]); + $count++; + $row++; + } + if($count != $per_row) + $o .= "
    \n"; + } + else + { + $CatCount = $objCatList->NumItems(); + foreach($objCatList->Items as $cat) + { + if($cat->Get("ParentId")==$CategoryId) + { + + if($row==0 && strlen($attribs["_firstitemtemplate"])) + { + //echo 'Saving ID in m_sub_cats[ first ] '.$cat->UniqueId().'
    '; + //$GLOBALS['cat_ID'] = $cat->UniqueId(); + $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); + $parsed=1; + } + if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) + { + //echo 'Saving ID in m_sub_cats[ last ] '.$cat->UniqueId().'
    '; + //$GLOBALS['cat_ID'] = $cat->UniqueId(); + $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); + $parsed=1; + } + if(!$parsed) + { + //echo 'Saving ID in m_sub_cats[ each ] '.$cat->UniqueId().'
    '; + //$GLOBALS['cat_ID'] = $cat->UniqueId(); + $o .= $cat->ParseTemplate($attribs["_itemtemplate"]); + } + $row++; + $i++; + $count++; + if($count>=$cat_count && $cat_count>0) + break; + } + } + } + unset($var_list_update["t"]); + SaveTagCache("kernel","m_list_cats",$attribs,m_BuildEnv(),$o); + return $o; +} + +function LoadCatSearchResults($attribs) +{ + global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal; + + $GroupList = $objSession->Get("GroupList"); + if(strlen($GroupList)) + $Groups = explode(",",$GroupList); + $acl_where = ""; + if(@count($Groups)>0 && is_array($Groups)) + { + $acl_where = array(); + for($i=0;$iGetPermId("CATEGORY.VIEW"); + $ctable = $objCatList->SourceTable; + $stable = $objSession->GetSearchTable(); // $objSearchCats->SourceTable; + $ptable = GetTablePrefix()."PermCache"; + $sql = "SELECT * FROM $stable INNER JOIN $ctable ON ($stable.ItemId=$ctable.CategoryId) "; + $sql .= "INNER JOIN $ptable ON ($ctable.CategoryId=$ptable.CategoryId) "; + $sql .="WHERE ItemType=1 AND Status=1 AND $acl_where AND PermId=$CAT_VIEW ORDER BY EdPick DESC,Relevance DESC "; + $objSearchCats->Page = $m_var_list["p"]; + if($objSearchCats->Page<1) + $objSearchCats->Page=1; + + if(is_numeric($objConfig->Get($objSearchCats->PerPageVar))) + { + $Start = ($objSearchCats->Page-1)*$objConfig->Get($objSearchCats->PerPageVar); + $limit = "LIMIT ".$Start.",".$objConfig->Get($objSearchCats->PerPageVar); + } + else + $limit = NULL; + + if(strlen($limit)) + $sql .= $limit; + + // echo "TEST:
    $sql
    \n"; + $objSearchCats->Query_Item($sql); + $where = "ItemType=1"; + + if(is_numeric($CountVal[1])) + { + $objSearchCats->QueryItemCount = $CountVal[1]; + } + else + { + $objSearchCats->QueryItemCount = QueryCount($sql); + $CountVal[1]= $objSearchCats->QueryItemCount; + } +} + +/* + @description: Used in conjuction with m_search_list_cats. This function generates a navigation link which is + used to switch from a short list to a longer list. The page number is not changed. + If this tag is called before the list tag, this function will load the category list. + Generally, it is good practice to duplicate all attributes set for m_search_list_cats. + Any extra HTML attributes are passed to the anchor tag + @attrib: _Template:tpl: Template to link to + @attrib: _text:lang: language tag to include as text for the anchor tag + @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence + if both are included. + @attrib: _image:: URL to an image to include inside the anchor tag. +*/ +function m_search_cat_more($attribs = array()) +{ + global $objSearchCats, $objConfig, $m_var_list_update; + + $html_attribs = ExtraAttributes($attribs); + $DestTemplate = $attribs["_template"]; + + if($attribs["_shortlist"]) + $objSearchList->PerPageVar = "Perpage_Category_Short"; + if($objSearchCats->NumItems()==0) + { + LoadCatSearchResults($attribs); + } + $max = $objConfig->Get($objSearchList->PerPageVar); + $val = $objSearchCats->QueryItemCount; + if($val > $max) + { + if($attribs["_root"]) + $attribs["_category"]=0; + + $m_var_list_update["p"]=1; + $url = m_template_link($attribs); + unset($m_var_list_update["p"]); + $o = ""; + $text = $attribs["_text"]; + if(!strlen($text)) + { + $text = $attribs["_plaintext"]; + if(!strlen($text)) + { + } + $o .= $text.""; + } + else + $o .= language($text); + if(strlen($attribs["_image"])) + { + $o .= ""; + } + $o .= ""; + } + return $o; +} +/* + @description: Used in conjuction with m_search_list_cats. This function generates the page navigation + for the list. If this tag is called before the list tag, this function will load + the category list. Generally, it is good practice to duplicate all attributes set for + m_search_list_cats. + @attrib: _PagesToList:int: Number of pages to list (default is 10) + @attrib: _label:lang: language tag to include in the output if there are pages to list. If there are no pages + listed, this text will not be included (resulting in an empty output) +*/ +function m_search_cat_pagenav($attribs = array()) +{ + global $objSearchCats, $objConfig, $objCatList, $objSession; + + $DestTemplate = $attribs["_template"]; + $PagesToList = $attribs["_pagestolist"]; + if(!is_numeric($PagesToList)) + $PagesToList = 10; + + $CatId = $attribs["_catid"]; + if(!is_numeric($CatId)) + $CatId = $objCatList->CurrentCategoryID(); + + $objSearchCats->PerPageVar = "Perpage_Category"; + if($attribs["_shortlist"]) + $objSearchCats->PerPageVar = "Perpage_Category_Short"; + if($objSearchCats->NumItems()==0) + { + LoadCatSearchResults($attribs); + } + $o = $objSearchCats->GetPageLinkList($DestTemplate); + if(strlen($o) && strlen($attribs["_label"])) + $o = language($attribs["_label"]).$o; + return $o; +} + +/* + @description: List all categories matched in a search + @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1) + @attrib: _maxlistcount:int: Maximum number of categories to list + @attrib: _ShortList:bool: If set, the Perpage_Category_Short setting is used instead of Perpage_Category + @attrib: _FirstItemTemplate:tpl: Template used for the first category listed + @attrib: _LastItemTemplate:tpl: Template used for the last category listed + @attrib: _ItemTemplate:tpl: default template used for category list items + @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag + @example: +*/ +function m_search_list_cats($attribs = array()) +{ + global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, + $objSearchCats, $objPermissions, $m_var_list; + + if(!is_object($objSearchCats)) + { + $objSearchCats = new clsCatList(); + $objSearchCats->SourceTable = $objSession->GetSessionTable('Search'); //"ses_".$objSession->GetSessionKey()."_Search" + $objSearchCats->Clear(); + } + $objSearchCats->PerPageVar = "Perpage_Category"; + if($attribs["_shortlist"]) + { + $objSearchCats->Page=1; + $m_var_list["p"] = 1; + $objSearchCats->PerPageVar = "Perpage_Category_Short"; + } + + $keywords = $objSession->GetVariable("Search_Keywords"); // for using in all this func branches + + if($objSearchCats->NumItems()==0) + { + LoadCatSearchResults($attribs); + //echo "Cat count: ". $objSearchCats->QueryItemCount; + $ret = 0; + if ($keywords) { + foreach ($objSearchCats->Items as $cat) { + + if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($_POST['keywords'])) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($_POST['keywords']))) { + $ret++; + } + } + } + else { + $ret = $objSearchCats->QueryItemCount; + } + if ($ret == 0) //if ($objSearchCats->NumItems() == 0) + { + $content_set = 0; + return language("lu_no_categories"); + } + } + + $html_attr = ExtraAttributes($attribs); + $cols = $attribs["_columns"]; + if($cols<1) + $cols =1; + $cat_count = (int)$attribs["_maxlistcount"]; + /* validation */ + if(strlen($attribs["_itemtemplate"])==0) + { + $content_set = 0; + return "ERROR -1"; + } + + $o=""; + $notable = $attribs["_notable"]; + + $count=0; + $row=0; + $var_list_update["t"] = $var_list["t"]; + + if(!$notable) + { + $per_row = ceil($objCatList->NumItems()/$cols); + $o = ""; + $o .= ""; + $o .= "\n
    "; + foreach($objSearchCats->Items as $cat) + { + $parsed=0; + if($count==$per_row) + { + $o .= ""; + $count=0; + } + if($row==0 && strlen($attribs["_firstitemtemplate"])) + { + $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); + $parsed=1; + } + if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) + { + $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); + $parsed=1; + } + if(!$parsed) + $o.= $cat->ParseTemplate($attribs["_itemtemplate"]); + $count++; + } + if($count != $per_row) + $o .= "
    \n"; + } + else + { + //echo "
    "; print_r($objSearchCats->Items); echo "
    "; + foreach($objSearchCats->Items as $cat) + { + //$cat->Keywords = GetKeywords($objSession->GetVariable("Search_Keywords")); + $keywords_found = strstr( strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords)); + if(!$keywords) $keywords_found = true; + if ($keywords_found) { + if($row==0 && strlen($attribs["_firstitemtemplate"])) + { + $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]); + $parsed=1; + } + if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) + { + $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); + $parsed=1; + } + if(!$parsed) + $o.= $cat->ParseTemplate($attribs["_itemtemplate"]); + $row++; + $i++; + $count++; + } + } + } + unset($var_list_update["t"]); + return $o; +} + +/* + @description: Parse a template based on the current advanced search type + @attrib:_TypeSelect:tpl:Template to parse if no item type has been selected + @attrib:_ItemSelect:tpl:Template to parse if an item type has been selected to search +*/ +function m_advsearch_include($attribs) +{ + global $objTemplate; + + $TypeSelectTemplate = $attribs["_typeselect"]; + $ItemTemplate = $attribs["_itemselect"]; + if((strlen($_GET["type"])>0 || $_POST["itemtype"]>0) && ($_GET["Action"]=="m_advsearch_type" || $_GET["Action"]=="m_adv_search")) + { + $o = $objTemplate->ParseTemplate($ItemTemplate); + } + else + $o = $objTemplate->ParseTemplate($TypeSelectTemplate); + return $o; +} + +/* + @description: Returns the name of the item type currently being advanced searched + @attrib::_plaintext:bool:If set, simply returns the name of the item if not, builds a language tag (lu_searchtitle_[name]) +*/ +function m_advsearch_type($attribs) +{ + global $objItemTypes; + + if($_GET["Action"]=="m_advsearch_type") + { + $ItemType = $_POST["itemtype"]; + } + elseif($_GET["Action"]=="m_adv_search") + $ItemType = $_GET["type"]; + + $o = ""; + if((int)$ItemType>0) + { + $Item = $objItemTypes->GetItem($ItemType); + if(is_object($Item)) + { + $name = strtolower($Item->Get("ItemName")); + if($attribs["_plaintext"]) + { + $o .= $name; + } + else + $o = language("lu_searchtitle_".strtolower($name)); + } + } + return $o; +} + +/* + @description: Lists advanced search fields for the selected item type + @attrib: _FirstItemTemplate:tpl: Template used for the first field listed + @attrib: _LastItemTemplate:tpl: Template used for the last field listed + @attrib: _AltLastItemTemplate:tpl: Altername Template used for the last field listed + @attrib: _ItemTemplate:tpl: default template used for field list items + @attrib: _AltTemplate:tpl: Alternate template used for field list items +*/ +function m_advsearch_fields($attribs) +{ + global $objItemTypes, $objTemplate, $objSearchConfig; + + if(!is_object($objSearchConfig)) + $objSearchConfig = new clsSearchConfigList(); + + if($_GET["Action"]=="m_advsearch_type") + { + $ItemType = $_POST["itemtype"]; + } + elseif($_GET["Action"]=="m_adv_search") + $ItemType = $_GET["type"]; + + $o = ""; + if((int)$ItemType>0) + { + $Item = $objItemTypes->GetItem($ItemType); + if(is_object($Item)) + { + $name = strtolower($Item->Get("ItemName")); + + $table = $Item->Get("SourceTable"); + $sql = "SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$table' AND AdvancedSearch=1 ORDER BY DisplayOrder"; + $objSearchConfig->Query_Item($sql); + $row=0; + if(is_array($objSearchConfig->Items)) + { + $ItemCount = count($objSearchConfig->Items); + foreach($objSearchConfig->Items as $s) + { + $even = (($row+1) % 2 == 0); + $parsed=0; + if($row==0 && strlen($attribs["_firstitemtemplate"])) + { + $o .= $s->ParseTemplate($attribs["_firstitemtemplate"]); + $parsed=1; + } + if($row==$ItemCount-1 && $even && !$parsed && strlen($attribs["_altlastitemtemplate"])>0) + { + $o .= $s->ParseTemplate($attribs["_altlastitemtemplate"]); + $parsed=1; + } + if($row==$ItemCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0) + { + $o .= $s->ParseTemplate($attribs["_lastitemtemplate"]); + $parsed=1; + } + if(!$parsed) + { + if($even && strlen($attribs["_altitemtemplate"])>0) + { + $o .= $s->ParseTemplate($attribs["_altitemtemplate"]); + } + else + $o .= $s->ParseTemplate($attribs["_itemtemplate"]); + } + $row++; + + } + } + } + } + return $o; +} + +/* + @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes + are passed to the anchor tag created. + @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index") + @attrib: _Module:: Module being linked to (ie In-Bulletin or In-News or In-Link) + @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, + the link will be generated. (If the _DeniedTemplate attribute is set, this template is used + and the link is created.) + @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm + attribute. If this attirbute is not included and the user does not have access, + nothing is returned. (The link is not created.) + @attrib: _Root:bool: If set, the current category is set to the module's root category + @attrib: _text:lang: language tag to include as text for the anchor tag + @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence + if both are included. + @attrib: _image:: URL to an image to include inside the anchor tag. + @attrib: _image_actions:: Image events. +*/ +function m_module_link($attribs = array()) +{ + global $objCatList, $objSession; + + $permission = $attribs["_perm"]; + $o = ""; + $tpath = GetModuleArray("template"); + if(strlen($permission)) + { + $perms = explode(",",$permission); + $hasperm = FALSE; + for($x=0;$xHasCatPermission($perms[$x])) + { + $hasperm = TRUE; + break; + } + } + } + else + $hasperm = TRUE; + if(!$hasperm && strlen($attribs["_deniedtemplate"])>0) + { + $hasperm = TRUE; + $attribs["_template"]=$attribs["_deniedtemplate"]; + } + if($hasperm) + { + $module = $attribs["_module"]; + if(ModuleEnabled($module)) + { + $t = $tpath[$attribs["_module"]]; + $t .= $attribs["_template"]; + $attribs["_template"] = $t; + $html_attr = ExtraAttributes($attribs); + if($attribs["_root"]) + { + $func = ModuleTagPrefix($module)."_root_link"; + if(function_exists($func)) + { + $url = $func($attribs); + } + else + $url = m_template_link($attribs); + } + else + $url = m_template_link($attribs); + $o = " "; + $text = $attribs["_text"]; + if(!strlen($text)) + { + $text = $attribs["_plaintext"]; + if(!strlen($text)) + { + if(strlen($attribs["_image"])) + { + $text = ""; + } + } + $o .= $text.""; + } + else + $o .= language($text).""; + } + else + { + $o = ""; + } + } + return $o; +} +/* + @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes + are passed to the anchor tag created. + @attrib: _Template:tpl: Template to link to. Just the template name is listed here. (ex: use "index" instead if "inlink/index") + @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, + the link will be generated. (If the _DeniedTemplate attribute is set, this template is used + and the link is created.) + @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm + attribute. If this attirbute is not included and the user does not have access, + nothing is returned. (The link is not created.) + @attrib: _text:lang: language tag to include as text for the anchor tag + @attrib: _plaintext:: plain text to include as text for the anchor tag. The _text attribute takes presedence + if both are included. + @attrib: _image:: URL to an image to include inside the anchor tag. +*/ +function m_permission_link($attribs = array()) +{ + global $objCatList, $objSession; + + $permission = $attribs["_perm"]; + $o = ""; + if(strlen($permission)) + { + $perms = explode(",",$permission); + $hasperm = FALSE; + for($x=0;$xHasCatPermission($perms[$x])) + { + $hasperm = TRUE; + break; + } + } + } + else + $hasperm = TRUE; + if(!$hasperm && strlen($attribs["_deniedtemplate"])>0) + { + $hasperm = TRUE; + $attribs["_template"]=$attribs["_deniedtemplate"]; + } + if($hasperm) + { + $url = m_template_link($attribs); + $o = " "; + $text = $attribs["_text"]; + if(!strlen($text)) + { + $text = $attribs["_plaintext"]; + if(!strlen($text)) + { + if(strlen($attribs["_image"])) + { + $text = ""; + } + } + $o .= $text.""; + } + else + $o .= language($text).""; + } + else + { + $o = ""; + } + + return $o; +} + +/* + @description: Create a link to a template. + @attrib: _Template:tpl: Template to link to (ex: "inbulletin/post_list") + @attrib: _Query:str: Extra query sring to be added to link URL (ex: "&test=test") + @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged + @attrib: _anchor:: If included, a local anchor (#) is added. (ex: _anchor="top" results in ) + @attrib: _Secure:bool:If set, creates an https URL + @attrib: _Root:bool:If set, gets module root category id + @attrib: _Module:str:Module Name + @attrib: _Unsecure:bool: Is set, creates an insecure full url (http://...) + @example: "> +*/ +function m_template_link($attribs = array()) +{ + global $var_list, $var_list_update, $m_var_list_update, $objCatList; + + $template = $attribs["_template"]; + + $query = trim($attribs["_query"]); + $query = !ereg("^&", $query)? "&$query" : $query; + + if(!strlen($template)) + $template = $var_list["t"]; + $cat = $attribs["_category"]; + $var_list_update["t"] = $template; + + if(strlen($cat)) + { + if($cat=="NULL") + { + $m_var_list_update["cat"]=0; + } + else + { + $m_var_list_update["cat"] = $cat; + } + } + + if($attribs["_secure"]) + { + $ret = GetIndexURL(1)."?env=".BuildEnv().$query; + } + elseif($attribs["_unsecure"]) + { + $ret = GetIndexURL(2)."?env=".BuildEnv().$query; + } + else + $ret = GetIndexURL()."?env=".BuildEnv().$query; + + if(strlen($attribs["_anchor"])) + $ret .= "#".$attribs["_anchor"]; + unset($var_list_update["t"]); + if(strlen($cat)) + unset($m_var_list_update["cat"]); + return $ret; +} + +/* + @description: create a link to a template based on user permissions. All extra HTML attributes are passed to the anchor tag created. + @attrib: _Template:tpl: Template to link to if the user has access + @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm + attribute. If this attirbute is not included and the user does not have access, + the "login" template is used. + @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, + the link will be generated. (If the _DeniedTemplate attribute is set, this template is used + and the link is created.) + @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN) + @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged + @example: "> +*/ +function m_access_template_link($attribs = array(), $Permission="") +{ + global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession; + + $cat = $attribs["_category"]; + if(strlen($cat)) + { + if($cat=="NULL") + $cat = 0; + } + else + $cat = $objCatList->CurrentCategoryID(); + + if(!strlen($Permission)) + { + $Permission = strtoupper($attribs["_perm"]); + } + + $o = ""; + $hasperm = FALSE; + if(strlen($Permission)) + { + $perms = explode(",",$Permission); + + for($x=0;$xHasCatPermission(trim($perms[$x]),$cat)) + { + $hasperm = TRUE; + break; + } + } + + if(!$hasperm && $attribs["_system"]) + { + for($x=0;$xHasSystemPermission(trim($perms[$x]))) + { + $hasperm = TRUE; + break; + } + } + } + } + $access = $attribs["_template"]; + $denied = $attribs["_deniedtemplate"]; + if(!strlen($denied)) + $denied = "login"; + + $m_var_list_update["cat"] = $cat; + if($hasperm) + { + $template = $access; + if(!strlen($template)) + $template = $var_list["t"]; + $var_list_update["t"] = $template; + } + else + { + $template = $denied; + if(!strlen($template)) + $template = $var_list["t"]; + if($template == "login") + { + $dest = $access; + } + $var_list_update["t"] = $template; + } + + $ret = GetIndexURL()."?env=".BuildEnv(); + unset($var_list_update["t"]); + if(strlen($dest)) + $ret .= "&dest=$dest"; + return $ret; +} + +/* + @description: returns a text based on user permissions. Text from inside of the tag will be returned if text attributes are not specified and user has permissions to category, or if _NoPerm attribute set to 1 and user doesn't have permissions. Otherwise entire section will be excluded. + @attrib: _Text:lang: Template to link to if the user has access + @attrib: _PlainText:: This template is used if the user does not have a permission listed in the _perm attribute. If this attirbute is not included and the user does not have access, the "login" template is used. + @attrib: _DenyText:lang: Template to link to if the user has access + @attrib: _PlainDenyText:: This exact text is used if the user does not have a permission listed in the _perm attribute and _DenyText attribute is not set. + @attrib: _perm:: A list of permissions to check. If the user has any of the the permissions in the list, the link will be generated. + @attrib: _System:bool: Set this attribute if one of the permissions in the list is a system permission (ie: LOGIN) + @attrib: _Category:int: Set the current category to this ID. If not set, the current category is unchanged + @attrib: _MatchAllPerms:int: Checks for all listed Permissions to be TRUE. Note: this attribute is rarely used. + @attrib: _NoPerm:int: The whole tag will return inner text if user has no permissions and attribute set to 1. Default value is 0. + @example: Some HTML here! +*/ +function m_perm_text($attribs = array()) +{ + global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession; + + $cat = $attribs["_category"]; + if(strlen($cat)) + { + if($cat=="NULL") + $cat = 0; + } + else + $cat = $objCatList->CurrentCategoryID(); + + if(!strlen($Permission)) + { + $Permission = strtoupper($attribs["_perm"]); + } + + $o = ""; + $hasperm = FALSE; + + $count = 0; + + if(strlen($Permission)) + { + $perms = explode(",",$Permission); + + for($x=0;$xHasCatPermission($perms[$x],$cat)) + { + $hasperm = TRUE; + $_AllPermsCount[$count] = 1; +// break; + } + + $count++; + } + + if(!$hasperm && $attribs["_system"]) + { + for($x=0; $xHasSystemPermission($perms[$x])) + { + $hasperm = TRUE; + $_AllPermsCount[$count] = 1; +// break; + } + + $count++; + } + } + } + + if ((int)$attribs["_matchallperms"]) + { + if (count($_AllPermsCount) != array_sum($_AllPermsCount)) + $hasperm = FALSE; + } + + $text = $attribs["_text"]; + $plaintext = $attribs["_plaintext"]; + $denytext = $attribs["_denytext"]; + $plaindenytext = $attribs["_plaindenytext"]; + $nopermissions_status = (int)$attribs["_noperm"]? 1 : 0; + + if(!strlen($denied)) + $denied = "login"; + + if (!$nopermissions_status) + { + if ($hasperm) + { + if (strlen($text) || strlen($plaintext)) + $ret = strlen($text)? language($text) : $plaintext; + else + $ret = "1"; + } + else + $ret = strlen($denytext)? language($denytext) : $plaindenytext; + } + elseif (!$hasperm) + { + $ret = "1"; + } + + return $ret; +} + + +/* + @description: Returns the error string associated with a permission +*/ +function m_permission_error($attribs = array()) +{ + global $objPermissions; + + $ret = ""; + $perm = strtoupper($_GET["error"]); + if(strlen($perm)) + { + $ado = &GetADODBConnection(); + $sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName ='$perm'"; + $rs = $ado->Execute($sql); + if($rs && !$rs->EOF) + { + $data = $rs->fields; + $error_tag = $data["ErrorMessage"]; + } + else + $error_tag = "lu_unknown_error"; + $ret = language($error_tag); + } + return $ret; +} + +/* + @description: Returns the error text encountered when parsing templates +*/ +function m_template_error($attribs = array()) +{ + global $objTemplate; + + $ret = ""; + if($objTemplate->ErrorNo<0) + { + $ret = $objTemplate->ErrorStr; + } + return $ret; +} + +/* + @description: Creates a category navigation bar + @attrib: _Template:tpl: template to use for navigation links + @attrib: _RootTemplate:bool: If set, this template is linked to for the root category + @attrib: _LinkCurrent:bool: If set, the last (current) category is linked. Otherwise the current category is simply displayed + @attrib: _Separator:: text to display between levels of the navigation bar + @attrib: _Root:: Root category configuration variable to use. (ex: Link for In-Link's root category) If not set, the system root is used + @example: +*/ +function m_navbar($attribs = array()) +{ + global $m_var_list_update, $var_list, $objCatList, $objConfig, $objModules; + + $separator = GetElem($attribs, '_separator'); + if(!$separator) $separator = " > "; + + $admin = (int)GetElem($attribs, 'admin'); + + $t = GetElem($attribs, '_template'); + $LinkLeafNode = GetElem($attribs, '_linkcurrent'); + $catid = (int)GetElem($attribs, '_catid'); + + if( GetElem($attribs, '_root') ) + { + $var = GetElem($attribs, '_root')."_Root"; + $Root = (int)$objConfig->Get($var); + } + else + $Root = 0; + + $RootTemplate = GetElem($attribs, '_roottemplate') ? GetElem($attribs, '_roottemplate') : ''; + $Module = GetElem($attribs, '_module'); + $ModuleRootTemplate = ''; + if($Module) + { + $ModuleRootCat = $objModules->GetModuleRoot($Module); + if($ModuleRootCat>0) + { + $modkey = "_moduleroottemplate"; + $ModuleRootTemplate = GetElem($attribs, $modkey); + } + else + $ModuleRootTemplate=""; + } + else + $ModuleRootCat = 0; + + if(!$catid) + $catid = $objCatList->CurrentCategoryID(); + + $ret = $objCatList->cat_navbar($admin, $catid, $t, $separator,$LinkLeafNode,$Root,$RootTemplate,$ModuleRootCat,$ModuleRootTemplate); + return $ret; +} + +/* + @description: Parse a category field and return the value + @attrib: _Field:: Category field to parse + @attrib: _CatId:int: Category ID to parse (uses current category if not set) + @attrib: _StripHTML:bool: if set, all HTML is removed from the output +*/ +function m_category_field($attribs) +{ + global $objCatList; + + $ret = ""; + $catid = (int)$attribs["_catid"]; + $field = $attribs["_field"]; + if(!$catid) + $catid = $objCatList->CurrentCategoryID(); + + if(strlen($field)) + { + $cat =& $objCatList->GetCategory($catid); + if(is_object($cat)) + { + $element = new clsHtmlTag(); + $element->name=$cat->TagPrefix; + $element->attributes = $attribs; + $ret = $cat->ParseObject($element); + } + } + if($attribs["_striphtml"]) + $ret = strip_tags($ret); + return $ret; +} + +/* + @description: returns the date of the last modification to a category + @attrib: _Part:: part of the date to display + @attrib: _Local:bool: If set, only subcategories of the current category is checked + @example: +*/ +function m_category_modified($attribs) +{ + global $objConfig, $objCatList; + + $ado = &GetADODBConnection(); + + if($attribs["_local"] && $objCatList->CurrentCategoryID() != 0) + { + $c =& $objCatList->GetItem($objCatList->CurrentCategoryID()); + $catlist = $c->GetSubCatIds(); + + $catwhere = "CategoryId IN (".explode(",",$catlist).")"; + $sql = "SELECT MAX(Modified) as ModDate,MAX(CreatedOn) as NewDate FROM ".GetTablePrefix()."Category "; + $sql .= "INNER JOIN ".GetTablePrefix()."CategoryItems ON (".GetTablePrefix()."Category.ResourceId=".GetTablePrefix()."CategoryItems.ItemResourceId) "; + $sql .= "WHERE $catwhere LIMIT 1"; + } + else + $sql = "SELECT MAX(Modified) as ModDate FROM ".GetTablePrefix()."Category LIMIT 1"; + $rs = $ado->Execute($sql); + if($rs && ! $rs->EOF) + { + $mod = $rs->fields["ModDate"]; + if($mod) + { + $part = strtolower($attribs["_part"]); + if(strlen($part)) + { + $ret = ExtractDatePart($part,$mod); + } + else + { + $ret = LangDate($mod); + } + } + } + return $ret; +} + +/* + @description: creates LINK tags to include all module style sheets + @attrib: _Modules:: Accepts a comma-separated list of modules to include (ie: "In-Link, In-News, In-Bulletin") + @attrib: _*css:none: Each module may set a custom-named stylesheet. For example, for In-Link the attribute would be _In-Linkcss="..". + If a module does not have a *css attribute, the default (style.css) is assumed. + @example: +*/ +function m_module_stylesheets($attribs) +{ + global $TemplateRoot; + + $IncludeList = explode(",",trim($attribs["_modules"])); + $tpath = GetModuleArray("template"); + for($inc=0;$inc\n"; + } + return $ret; +} + +/* + @description: lists items related to a category + @attrib:CatId:int: Category ID of category, or current category if not set + @attrib:_ListItem: Comma-separated list of item types (ie: Link, Topic, Category, News) The items are listed in the order this list provides, then by priority. + Each item should have its own template passed in as an attribute (_{ItemType}Template) +*/ +function m_related_items($attribs) +{ + global $objItemTypes, $objCatList, $content_set; + static $Related; + + global $CatRelations; + + $cat = $attribs["_catid"]; + if(!is_numeric($cat)) + { + $cat = $objCatList->CurrentCategoryID(); + } + $c =& $objCatList->GetCategory($cat); + $data_sent=0; + if(is_object($c)) + { + $ResourceId = $c->Get("ResourceId"); + $IncludeList = explode(",",trim(strtolower($attribs["_listitems"]))); + $o = ""; + + if(!is_object($CatRelations)) + { + $CatRelations = new clsMultiTypeList(); + LoadRelatedItems($Related, $CatRelations,$c->Get("ResourceId")); + } + + if($CatRelations->NumItems()>0) + { + for($inc=0;$incGetTypeByName($item_type); + if(is_object($objType)) + { + foreach($CatRelations->Items as $item) + { + if(is_object($item)) + { + if(strtolower($objType->Get("ItemName")) == strtolower($item_type) && $item->type==$objType->Get("ItemType")) + { + if(strlen($item->BasePermissionName)) + { + $perm = $item->BasePermissionName.".VIEW"; + $haspem = $objSession->HasCatPermission($perm,$item->Get("CategoryId")); + } + else + $hasperm = 1; + + if($hasperm) + { + $data_sent =1; + $classname = $objType->Get("ClassName"); + if(strlen($classname)) + { + $l = new $classname; + $l->Data = $item->Data; + $o .= $l->ParseTemplate($t); + } + } + } + } + $item = NULL; + } + } + else + echo $item_type." not found
    \n"; + } + } + if($data_sent) + { + return $o; + } + else + { + $content_set=0; + return ""; + } + } + else + { + $content_set = 0; + return ""; + } + } + else + { + $content_set = 0; + return ""; + } +} + +/* + @description: Returns the number of items related to the current category + @attrib:_CatId:int: If set, this is the category ID to use, otherwise the current category is used + @attrib:_ItemType::Name of item to count. If not set, all related items are counted +*/ +function m_related_count($attribs) +{ + global $objItemTypes, $objCatList, $content_set; + + $cat = $attribs["_catid"]; + + if(!is_numeric($cat)) + { + $cat = $objCatList->CurrentCategoryID(); + } + $c =& $objCatList->GetCategory($cat); + $data_sent=0; + //echo "Category: $cat
    ";  print_r($c); echo " 
    "; + if(is_object($c)) + { + $ResourceId = $c->Get("ResourceId"); + if(!is_object($CatRelations)) + { + $CatRelations = new clsMultiTypeList(); + LoadRelatedItems($Related, $CatRelations, $c->Get("ResourceId")); + } + + $item_type = $attribs["_itemtype"]; + if(strlen($item_type)) + { + $objType = $objItemTypes->GetTypeByName($item_type); + if(is_object($objType)) + { + $TargetType = $objType->Get("ItemType"); + } + else + $TargetType=""; + } + + if($CatRelations->NumItems()>0) + { + for($x=0;$x<$CatRelations->NumItems();$x++) + { + $a = $CatRelations->GetItemByIndex($x); + if($a->type == $TargetType || !strlen($TargetType)) + { + $count++; + } + } + } + } + return $count; +} + +/* + @description: Returns the MetaKeywords field for a category, or the system MetaKeywords value + if the category doesn't have a value for MetaKeywords + @attrib: _CatId:int: Category to use (The current category is used by default) +*/ +function m_meta_keywords($attribs = array()) +{ + global $objCatList, $objConfig; + $catid = (int)$attribs["_catid"]; + if(!$catid) + { + $catid = $objCatList->CurrentCategoryID(); + } + if($catid) + { + $c = $objCatList->GetItem($catid); + $keywords = $c->Get("MetaKeywords"); + } + if(!strlen($keywords)) + { + $keywords = $objConfig->Get("MetaKeywords"); + } + return $keywords; +} + +/* + @description: Returns the MetaDescription field for a category, or the system MetaDescription value + if the category doesn't have a value for MetaDescription + @attrib: _CatId:int: Category to use (The current category is used by default) +*/ +function m_meta_description($attribs = array()) +{ + global $objCatList, $objConfig; + + $catid = (int)$attribs["_catid"]; + if(!$catid) + { + $catid = $objCatList->CurrentCategoryID(); + } + if($catid) + { + $c = $objCatList->GetItem($catid); + $desc = $c->Get("MetaDescription"); + } + if(!strlen($desc)) + { + $desc = $objConfig->Get("MetaDescription"); + } + return $desc; +} + +/* + @description: return the number of items in the database + @attrib: _ItemType:: Name of item to count + @attrib: _ListType:: Type of item to count (ie: favorites, editor's pick, etc) + @attrib: _CategoryCount:int: Limit scope to the current category + @attrib: _SubCats:bool: Count items in all subcategories (_CategoryCount must be set) + @attrib: _Today:bool: Count items added today + @attrib: _GroupOnly:bool: Only count items the current user can view + @attrib: _NoCache:bool: Count without using cache +*/ +function m_itemcount($attribs = array()) +{ + global $objItemTypes, $objCatList, $objSession, $objCountCache; + + $Bit_None = 0; + $Bit_Today = 1; + $Bit_Owner = 2; + $Bit_Global = 4; + $Bit_SubCats=8; + + if($attribs["_categorycount"]) + { + $evar = m_BuildEnv(); + } + else + $evar = ""; + + $cat = $attribs["_catid"]; + if(!is_numeric($cat)) + { + $cat = $objCatList->CurrentCategoryID(); + } + + if((int)$cat>0) + $c = $objCatList->GetCategory($cat); + + if(is_numeric($attribs["_itemtype"])) + { + $item = $objItemTypes->GetItem($attribs["_itemtype"]); + } + else + $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]); + + $DoUpdate=0; + + //echo "
    "; print_r($item); echo "
    "; + + $ExtraId=""; + + if(is_object($item)) + { + if($item->Get("ItemType")==1) /* counting categories */ + { + $ret = $objCatList->CountCategories($attribs); + } + else + { + $ListVar =& GetItemCollection($attribs["_itemtype"]); + if(is_object($ListVar)) + { + $ret = $ListVar->PerformItemCount($attribs); + } + } + } + else + $ret = 0; + + return !$ret ? 0 : $ret; +} + +/* + @description: Parse a User field and return the value + @attrib: _Field:: User field to parse + @attrib: _UserId:int: Category ID to parse (uses current user if not set) +*/ +function m_user_field($attribs) +{ + global $objUsers, $objSession; + + $o = ""; + $userid = $attribs["_userid"]; + if(!is_numeric($userid) || $userid=="0") + $userid = $objSession->Get("PortalUserId"); + + if($userid) + { + $u =& $objUsers->GetItem($userid); + if(is_object($u)) + { + $element = new clsHtmlTag(); + $element->name = $u->TagPrefix; + $element->attributes = $attribs; + $o = $u->ParseObject($element); + } + } + return $o; +} + +/* + @description: Parses a user template + @attrib:_Template:tpl: Template to parse + @attrib:_UserId:int: User ID to parse. If not set, the current user is used +*/ +function m_user_detail($attribs = array()) +{ + global $objTemplate, $objUsers, $objSession; + + $tname = $attribs["_template"]; + $UserId = (int)$attribs["_userid"]; + if(!$UserId) + { + $UserId=$objSession->Get("PortalUserId"); + } + if($UserId>0) + { + $u = $objUsers->GetUser($UserId); + $o = $u->ParseTemplate($tname); + } + else + { + $u = new clsPortalUser(NULL); + $o = $u->ParseTemplate($tname); + } + + return $o; +} + +/* + @description: returns a user field from the current profile being viewed + @example: +*/ +function m_user_profile_field($attribs = array()) +{ + if((int)$_GET["UserId"]) + { + $attribs["_userid"] = $_GET["UserId"]; + } + + $ret = m_user_field($attribs); + +/* if ($ret == '') { + $ret = admin_language("lu_Guest"); + }*/ + + return $ret; +} + +/* + @description: Parses a user profile template + @attrib:_Template:tpl: Template to parse + @attrib:_UserId:int: User ID to parse. If not set, the current user is used +*/ +function m_user_profile_detail($attribs) +{ + if((int)$_GET["UserId"]) + { + $attribs["_userid"] = $_GET["UserId"]; + } + $ret = m_user_detail($attribs); + return $ret; +} + +/* + @description: Lists all user profile fields the user has indicated to be public + @attrib: _ItemTemplate:tpl: Template used to list each field + @example: +*/ +function m_user_profile($attribs = array()) +{ + global $objTemplate, $objUsers; + + $tname = $attribs["_itemtemplate"]; + $t = $objTemplate->GetTemplate($tname); + if(is_object($t)) + { + $html = $t->source; + } + + $userid = $_GET["UserId"]; + $o = ""; + + if((int)$userid>0) + { + $u = $objUsers->GetItem($userid); + $vars = $u->GetAllPersistantVars(); + foreach($vars as $field=>$value) + { + if(substr($field,0,3)=="pp_") + { + if($value==1) + { + $src = $html; + $src = str_replace("","",$src); + $src = str_replace("lu_profile_field","lu_".$field,$src); + $o .= $u->ParseTemplateText($src); + } + } + + } + } + + return $o; +} + +/* + @description: List users the current user has marked as 'friend' + @attrib: _Status:: Determines which online status to list, either "online" or "offline". + @attrib: _ItemTemplate:tpl: Template used to parse list items +*/ +function m_list_friends($attribs = array()) +{ + global $objUsers, $objSession; + + global $online_friends; + + $ado = &GetADODBConnection(); + + $status = strtolower($attribs["_status"]); + + $logedin_user = $objSession->Get("PortalUserId"); + $u =& $objUsers->GetUser($logedin_user); + + //echo "
    "; print_r($u); echo "
    "; + if(!isset($online_friends) || $status=="online") + { + $ftable = GetTablePrefix()."Favorites"; + $stable = GetTablePrefix()."UserSession"; + $ptable = GetTablePrefix()."PortalUser"; + if(isset($online_friends)) + { + foreach($online_friends as $id=>$name) + { + $u =& $objUsers->GetUser($id); + $o .= $u->ParseTemplate($attribs["_itemtemplate"]); + } + } + else + { + $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable "; + $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON "; + $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; + //echo $sql; + $rs = $ado->Execute($sql); + while($rs && ! $rs->EOF) + { + $u =& $objUsers->GetItem($rs->fields["PortalUserId"]); + if($status=="online") + { + $o .= $u->ParseTemplate($attribs["_itemtemplate"]); + } + $online_friends[]=$rs->fields["PortalUserId"]; + if(ADODB_EXTENSION>0) + { + adodb_movenext($rs); + } + else + $rs->MoveNext(); + } + } + } + + if($status=="offline") + { + $ftable = GetTablePrefix()."Favorites"; + $stable = GetTablePrefix()."UserSession"; + $ptable = GetTablePrefix()."PortalUser"; + + $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable"; + if(count($online_friends)>0) + { + $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable "; + $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND "; + $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; + } + else + { + $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable "; + $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; + } + + //echo $sql; + $rs = $ado->Execute($sql); + while($rs && ! $rs->EOF) + { + $u = $objUsers->GetItem($rs->fields["PortalUserId"]); + $o .= $u->ParseTemplate($attribs["_itemtemplate"]); + if(ADODB_EXTENSION>0) + { + adodb_movenext($rs); + } + else + $rs->MoveNext(); + } + } + $t = $attribs["_itemtemplate"]; + return $o; +} + +/* + @description: Returns the number of users the current user has marked as 'friend' + @attrib: _Status:: Determines which online status to count, either "online" or "offline". +*/ +function m_friend_count($attribs=array()) +{ + global $objUsers, $objSession; + + global $online_friends; + + $ado = &GetADODBConnection(); + + $logedin_user = $objSession->Get("PortalUserId"); + $u =& $objUsers->GetUser($logedin_user); + + $status = strtolower($attribs["_status"]); + if(!isset($online_friends) || $status=="online") + { + $ftable = GetTablePrefix()."Favorites"; + $stable = GetTablePrefix()."UserSession"; + $ptable = GetTablePrefix()."PortalUser"; + if(isset($online_friends) && $status="online") + { + return count($online_friends); + } + else + { + $online_friends = array(); + $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable "; + $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON "; + $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; + //echo $sql."
    \n"; + $rs = $ado->Execute($sql); + while($rs && ! $rs->EOF) + { + $online_friends[$rs->fields["PortalUserId"]]=$rs->fields["PortalUserId"]; + if(ADODB_EXTENSION>0) + { + adodb_movenext($rs); + } + else + $rs->MoveNext(); + } + if($status=="online") + return count($online_friends); + } + } + + if($status=="offline") + { + $ftable = GetTablePrefix()."Favorites"; + $stable = GetTablePrefix()."UserSession"; + $ptable = GetTablePrefix()."PortalUser"; + + $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable"; + + if(count($online_friends)>0) + { + $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable "; + $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND "; + $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; + } + else + { + $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable "; + $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId']; + } + $rs = $ado->Execute($sql); + return $rs->fields["ItemCount"]; + } +} + +/* + @description: Returns the number of users the current user has marked as 'friend' today +*/ +function m_friend_count_today($attribs) +{ + global $objSession; + + $logedin_user = $objSession->Get("PortalUserId"); + + $ret =0; + $ado = &GetADODBConnection(); + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $sql = "SELECT count(*) as c FROM ".GetTablePrefix()."Favorites WHERE ItemTypeId=6 and PortalUserId=".$objSession->Get("PortalUserId")." AND Modified>$today"; + $rs = $ado->Execute($sql); + if($rs && !$rs->EOF) + $ret = $rs->fields["c"]; + return $ret; +} + +/* + @description: Returns the number of items in a search result + + @Example: () +*/ +function m_search_item_count($attribs) +{ + global $objItemTypes, $objCatList, $objSession, $CountVal; + + if(!is_array($CountVal)) + $CountVal=array(); + $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]); + if(is_object($item)) + { + $val = $CountVal[$item->Get("ItemType")]; + if(is_numeric($val)) + return $val; + $where = "ItemType=".$item->Get("ItemType"); + $table = $objSession->GetSearchTable(); + $ret = TableCount($table,$where,0); + $CountVal[$item->Get("ItemType")]=(int)$ret; + } + + return $ret; +} +/* + @description: Returns the number of categories in a search result + @Example: () +*/ +function m_search_cat_count($attribs = array()) +{ + global $objItemTypes, $objCatList, $objSession, $CountVal, $objSearchCats; + + if(!is_object($objSearchCats)) + { + $objSearchCats = new clsCatList(); + $objSearchCats->SourceTable = $objSession->GetSearchTable(); + $objSearchCats->Clear(); + } + + LoadCatSearchResults($attribs); + //echo "
    "; print_r($objSearchCats->Items); echo "
    "; + $ret = 0; + $keywords = $objSession->GetVariable("Search_Keywords"); + + if ($keywords) { + foreach ($objSearchCats->Items as $cat) { + + if (strstr(strip_tags(strtolower($cat->Data['Name'])), strtolower($keywords)) || strstr(strip_tags(strtolower($cat->Data['Description'])), strtolower($keywords))) { + $ret++; + } + } + } + else { + $ret = $objSearchCats->QueryItemCount; + } + + if ($ret == '') { + $ret = 0; + } + + //echo $ret; + //$objSearchCats->QueryItemCount = $ret; + + return $ret; +} + +/* + @description: Returns super global variable by type and name + @attrib: _Name:: Name of variable + @attrib: _Type:: Type super global variable
    Possible Values: +
      +
    • get: $_GET super variable +
    • post: $_POST super variable +
    • cookie: $_COOKIE super variable +
    • env: $_ENV super variable +
    • server: $_SERVER super variable +
    • session: $_SESSION super variable +
    + @Example: +*/ +function m_get_var($attribs = array()) +{ + global $_GET, $_POST, $_COOKIE, $_FILES, $_ENV, $_SERVER, $_SESSION; + + $type = strtolower($attribs['_type']); + $name = $attribs['_name']; + + switch ($type) + { + case "get": + $vars = $_GET; + break; + case "cookie": + $vars = $_COOKIE; + break; + case "files": + $vars = $_FILES; + break; + case "server": + $vars = $_SERVER; + break; + case "session": + $vars = $_SESSION; + break; + case "env": + $vars = $_ENV; + break; + case "post": + $vars = $_POST; + break; + default : + $vars = $_POST; + break; + } + $ret = $vars[$name]; + + return $ret; +} + +/* + @description: Returns number of users currently on-line + @attrib: _LastActive:: Last user/session activity in seconds + @attrib: _OwnCount:bool: Count user's own session +*/ +function m_users_online($attribs = array()) +{ + global $objSession; + + $LastActive = (int)($attribs['_lastactive']); + $OwnCount = (int)($attribs['_owncount']); + + if ($LastActive && !is_null($LastActive)) + $sql_add = " AND LastAccessed>".(time()-$LastActive); + + if (!$OwnCount || is_null($OwnCount)) + $sql_add.= " AND SessionKey!='".$objSession->GetSessionKey()."'"; + + $ado = &GetADODBConnection(); + $sql = "SELECT COUNT(*) AS Counter FROM ".GetTablePrefix()."UserSession WHERE Status=1".$sql_add; + $rs = $ado->Execute($sql); + $ret = ($rs && !$rs->EOF)? $rs->fields["Counter"] : 0; + + return $ret; +} + +function m_debug_mode($attribs = array()) +{ + $const_name = $attribs['_debugconst']; + return defined($const_name) && (constant($const_name) == 1) ? 'yes' : ''; +} + +function m_info($attribs = array()) +{ + switch ($attribs['_infotype']) + { + case 'site': + global $objConfig; + $ret = ThisDomain().$objConfig->Get('Site_Path'); + break; + + default: + $ret = ''; + break; + } + return $ret; +} + +function m_module_enabled($attribs = array()) +{ + global $objModules; + $module = $attribs['_module']; + + // check if module is installed + $ModuleItem = $objModules->GetItemByField('Name', $module); + if( !is_object($ModuleItem) ) return ''; + + // module is enabled + $ret = $ModuleItem->Get('Loaded') == 1; + + // check if installed module is licensed + return $ret && _ModuleLicensed($module) ? 'yes' : ''; +} + +function m_recall($attribs = array()) +{ + global $objSession; + return $objSession->GetVariable($attribs['_name']); +} + +?> Index: trunk/admin/install/inportal_schema.sql =================================================================== diff -u -N -r431 -r642 --- trunk/admin/install/inportal_schema.sql (.../inportal_schema.sql) (revision 431) +++ trunk/admin/install/inportal_schema.sql (.../inportal_schema.sql) (revision 642) @@ -1,523 +1,523 @@ -CREATE TABLE BanRules ( - RuleId int(11) NOT NULL auto_increment, - RuleType tinyint(4) NOT NULL default '0', - ItemField varchar(255) default NULL, - ItemVerb tinyint(4) NOT NULL default '0', - ItemValue varchar(255) NOT NULL default '', - ItemType int(11) NOT NULL default '0', - Priority int(11) NOT NULL default '0', - Status tinyint(4) NOT NULL default '1', - ErrorTag varchar(255) default NULL, - PRIMARY KEY (RuleId) -) -# -------------------------------------------------------- -CREATE TABLE Category ( - CategoryId int(11) NOT NULL auto_increment, - Type int(11) NOT NULL default '0', - ParentId int(11) NOT NULL default '0', - Name varchar(255) NOT NULL default '', - Description text NOT NULL, - CreatedOn double NOT NULL default '0', - EditorsPick tinyint(4) default NULL, - Status tinyint(4) NOT NULL default '0', - Pop tinyint(4) default NULL, - Priority int(11) default NULL, - MetaKeywords varchar(255) default NULL, - CachedDescendantCatsQty int(11) default NULL, - CachedNavbar text NOT NULL, - CreatedById int(11) NOT NULL default '0', - ResourceId int(11) default NULL, - ParentPath text NOT NULL, - MetaDescription varchar(255) default NULL, - HotItem int(11) NOT NULL default '2', - NewItem int(11) NOT NULL default '2', - PopItem int(11) NOT NULL default '2', - Modified double NOT NULL default '0', - ModifiedById int(11) NOT NULL default '0', - PRIMARY KEY (CategoryId), - KEY ParentId (ParentId), - KEY ResourceId (ResourceId), - KEY Modified (Modified), - KEY Priority (Priority), - KEY sorting (Name,Priority) -) -# -------------------------------------------------------- -CREATE TABLE CategoryItems ( - CategoryId int(11) NOT NULL default '0', - ItemResourceId int(11) NOT NULL default '0', - PrimaryCat tinyint(4) NOT NULL default '0', - PRIMARY KEY (CategoryId,ItemResourceId), - KEY ItemResourceId (ItemResourceId), - KEY PrimaryCat (PrimaryCat) -) -# -------------------------------------------------------- -CREATE TABLE ConfigurationAdmin ( - VariableName varchar(80) NOT NULL default '', - heading varchar(255) default NULL, - prompt varchar(255) default NULL, - element_type varchar(20) NOT NULL default '', - validation varchar(255) default NULL, - ValueList varchar(255) default NULL, - DisplayOrder int(11) NOT NULL default '0', - Install int(11) NOT NULL default '1', - PRIMARY KEY (VariableName) -) -# -------------------------------------------------------- -CREATE TABLE ConfigurationValues ( - VariableName varchar(255) NOT NULL default '', - VariableValue varchar(255) default NULL, - ModuleOwner varchar(20) default 'In-Portal', - Section varchar(255) NOT NULL default '', - PRIMARY KEY (VariableName) -) -# -------------------------------------------------------- -CREATE TABLE CountCache ( - ListType int(11) NOT NULL default '0', - ItemType int(11) NOT NULL default '-1', - Value int(11) NOT NULL default '0', - CountCacheId int(11) NOT NULL auto_increment, - LastUpdate int(11) NOT NULL default '0', - ExtraId varchar(50) default NULL, - TodayOnly tinyint(4) NOT NULL default '0', - PRIMARY KEY (CountCacheId) -) -# -------------------------------------------------------- -CREATE TABLE CustomField ( - CustomFieldId int(11) NOT NULL auto_increment, - Type int(11) NOT NULL default '0', - FieldName varchar(255) NOT NULL default '', - FieldLabel varchar(40) default NULL, - Heading varchar(60) default NULL, - Prompt varchar(60) default NULL, - ElementType varchar(50) NOT NULL default '', - ValueList varchar(255) default NULL, - DisplayOrder int(11) NOT NULL default '0', - OnGeneralTab tinyint(4) NOT NULL default '0', - PRIMARY KEY (CustomFieldId), - KEY Type (Type) -) -# -------------------------------------------------------- -CREATE TABLE CustomMetaData ( - CustomDataId int(11) NOT NULL auto_increment, - ResourceId int(11) NOT NULL default '0', - CustomFieldId int(11) NOT NULL default '0', - Value text NOT NULL, - PRIMARY KEY (CustomDataId) -) -# -------------------------------------------------------- -CREATE TABLE EmailMessage ( - EmailMessageId int(10) NOT NULL auto_increment, - Template longtext, - MessageType enum('html','text') NOT NULL default 'text', - LanguageId int(11) NOT NULL default '0', - EventId int(11) NOT NULL default '0', - PRIMARY KEY (EmailMessageId) -) -# -------------------------------------------------------- -CREATE TABLE EmailQueue ( - Subject text NOT NULL, - toaddr text NOT NULL, - fromaddr text NOT NULL, - message blob, - headers blob, - queued timestamp NOT NULL -) -# -------------------------------------------------------- -CREATE TABLE EmailSubscribers ( - EmailMessageId int(11) NOT NULL default '0', - PortalUserId int(11) NOT NULL default '0' -) -# -------------------------------------------------------- -CREATE TABLE Events ( - EventId int(11) NOT NULL auto_increment, - Event varchar(40) NOT NULL default '', - Enabled int(11) NOT NULL default '1', - FromUserId int(11) NOT NULL default '0', - Module varchar(40) NOT NULL default '', - Description varchar(255) NOT NULL default '', - Type int(11) NOT NULL default '0', - PRIMARY KEY (EventId) -) -# -------------------------------------------------------- -CREATE TABLE Favorites ( - FavoriteId int(11) NOT NULL auto_increment, - PortalUserId int(11) NOT NULL default '0', - ResourceId int(11) NOT NULL default '0', - ItemTypeId int(11) NOT NULL default '0', - Modified int(11) NOT NULL default '0', - PRIMARY KEY (FavoriteId), - UNIQUE KEY main (PortalUserId,ResourceId) -) -# -------------------------------------------------------- -CREATE TABLE IdGenerator ( - lastid int(11) default NULL -) -# -------------------------------------------------------- -CREATE TABLE Images ( - ImageId int(11) NOT NULL auto_increment, - ResourceId int(11) NOT NULL default '0', - Url varchar(255) NOT NULL default '', - Name varchar(255) NOT NULL default '', - AltName varchar(255) default NULL, - ImageIndex int(11) NOT NULL default '0', - LocalImage tinyint(4) NOT NULL default '1', - LocalPath varchar(240) NOT NULL default '', - Enabled int(11) NOT NULL default '1', - DefaultImg int(11) NOT NULL default '0', - ThumbUrl varchar(255) default NULL, - Priority int(11) NOT NULL default '0', - ThumbPath varchar(255) default NULL, - LocalThumb tinyint(4) NOT NULL default '0', - SameImages tinyint(4) NOT NULL default '0', - PRIMARY KEY (ImageId), - KEY ResourceId (ResourceId) -) -# -------------------------------------------------------- -CREATE TABLE ItemRating ( - RatingId int(11) NOT NULL auto_increment, - IPAddress varchar(255) NOT NULL default '', - CreatedOn double NOT NULL default '0', - RatingValue int(11) NOT NULL default '0', - ItemId int(11) NOT NULL default '0', - PRIMARY KEY (RatingId) -) -# -------------------------------------------------------- -CREATE TABLE ItemReview ( - ReviewId int(11) NOT NULL auto_increment, - CreatedOn double NOT NULL default '0', - ReviewText longtext NOT NULL, - IPAddress varchar(255) NOT NULL default '', - ItemId int(11) NOT NULL default '0', - CreatedById int(11) NOT NULL default '0', - ItemType tinyint(4) NOT NULL default '0', - Priority int(11) NOT NULL default '0', - Status tinyint(4) NOT NULL default '0', - TextFormat int(11) NOT NULL default '0', - Module varchar(255) NOT NULL default '', - PRIMARY KEY (ReviewId) -) -# -------------------------------------------------------- -CREATE TABLE ItemTypes ( - ItemType int(11) NOT NULL default '0', - Module varchar(50) NOT NULL default '', - SourceTable varchar(100) NOT NULL default '', - TitleField varchar(50) default NULL, - CreatorField varchar(255) NOT NULL default '', - PopField varchar(255) default NULL, - RateField varchar(255) default NULL, - LangVar varchar(255) NOT NULL default '', - PrimaryItem int(11) NOT NULL default '0', - EditUrl varchar(255) NOT NULL default '', - ClassName varchar(40) NOT NULL default '', - ItemName varchar(50) NOT NULL default '', - PRIMARY KEY (ItemType), - KEY Module (Module) -) -# -------------------------------------------------------- -CREATE TABLE Language ( - LanguageId int(11) NOT NULL auto_increment, - PackName varchar(40) NOT NULL default '', - LocalName varchar(40) NOT NULL default '', - Enabled int(11) NOT NULL default '0', - PrimaryLang int(11) NOT NULL default '0', - IconURL varchar(255) default NULL, - DateFormat varchar(50) NOT NULL default '', - TimeFormat varchar(50) NOT NULL default '', - DecimalPoint char(2) NOT NULL default '.', - ThousandSep char(1) NOT NULL default ',', - PRIMARY KEY (LanguageId) -) -# -------------------------------------------------------- -CREATE TABLE Modules ( - Name varchar(255) NOT NULL default '', - Path varchar(255) NOT NULL default '', - Var varchar(10) NOT NULL default '', - Version varchar(10) NOT NULL default '', - Loaded tinyint(4) NOT NULL default '1', - LoadOrder tinyint(4) NOT NULL default '0', - TemplatePath varchar(255) NOT NULL default '', - RootCat int(11) NOT NULL default '0', - BuildDate double NOT NULL default '0', - PRIMARY KEY (Name) -) -# -------------------------------------------------------- -CREATE TABLE PermCache ( - PermCacheId int(11) NOT NULL auto_increment, - CategoryId int(11) NOT NULL default '0', - PermId int(11) NOT NULL default '0', - ACL varchar(255) NOT NULL default '', - DACL varchar(255) NOT NULL default '', - PRIMARY KEY (PermCacheId), - KEY CategoryId (CategoryId), - KEY PermId (PermId) -) -# -------------------------------------------------------- -CREATE TABLE PermissionConfig ( - PermissionConfigId int(11) NOT NULL auto_increment, - PermissionName varchar(30) NOT NULL default '', - Description varchar(255) NOT NULL default '', - ErrorMessage varchar(255) NOT NULL default '', - ModuleId varchar(20) NOT NULL default '0', - PRIMARY KEY (PermissionConfigId), - KEY PermissionName (PermissionName) -) -# -------------------------------------------------------- -CREATE TABLE Permissions ( - PermissionId int(11) NOT NULL auto_increment, - Permission varchar(30) NOT NULL default '', - GroupId int(11) default '0', - PermissionValue int(11) NOT NULL default '0', - Type tinyint(4) NOT NULL default '0', - CatId int(11) NOT NULL default '0', - PRIMARY KEY (PermissionId) -) -# -------------------------------------------------------- -CREATE TABLE PersistantSessionData ( - PortalUserId int(11) NOT NULL default '0', - VariableName varchar(255) NOT NULL default '', - VariableValue text NOT NULL, - KEY UserId (PortalUserId), - KEY VariableName (VariableName) -) -# -------------------------------------------------------- -CREATE TABLE Phrase ( - Phrase varchar(255) NOT NULL default '', - Translation varchar(255) NOT NULL default '', - PhraseType int(11) NOT NULL default '0', - PhraseId int(11) NOT NULL auto_increment, - LanguageId int(11) NOT NULL default '0', - PRIMARY KEY (PhraseId), - INDEX Phrase_Index (Phrase) -) -# -------------------------------------------------------- -CREATE TABLE PhraseCache ( - Template varchar(40) NOT NULL default '', - PhraseList text NOT NULL, - CacheDate int(11) NOT NULL default '0', - ThemeId int(11) NOT NULL default '0', - PRIMARY KEY (Template) -) -# -------------------------------------------------------- -CREATE TABLE PortalGroup ( - GroupId int(11) NOT NULL auto_increment, - Name varchar(255) NOT NULL default '', - Description varchar(255) default NULL, - CreatedOn double NOT NULL default '0', - System tinyint(4) NOT NULL default '0', - Personal tinyint(4) NOT NULL default '0', - Enabled tinyint(4) NOT NULL default '1', - ResourceId int(11) NOT NULL default '0', - PRIMARY KEY (GroupId), - UNIQUE KEY Name (Name), - KEY ResourceId (ResourceId), - KEY Personal (Personal), - KEY Enabled (Enabled) -) -# -------------------------------------------------------- -CREATE TABLE PortalUser ( - PortalUserId int(11) NOT NULL auto_increment, - Login varchar(255) default NULL, - Password varchar(255) default NULL, - FirstName varchar(255) default NULL, - LastName varchar(255) default NULL, - Email varchar(255) NOT NULL default '', - CreatedOn double NOT NULL default '0', - Phone varchar(20) default NULL, - Street varchar(255) default NULL, - City varchar(20) default NULL, - State varchar(20) default NULL, - Zip varchar(20) default NULL, - Country varchar(20) NOT NULL default '', - ResourceId int(11) NOT NULL default '0', - Status tinyint(4) NOT NULL default '2', - Modified int(11) NOT NULL default '0', - dob double NOT NULL default '0', - tz int(11) default NULL, - ip varchar(20) default NULL, - IsBanned tinyint(1) NOT NULL default '0', - PRIMARY KEY (PortalUserId), - UNIQUE KEY Login (Login), - KEY ResourceId (ResourceId), - KEY CreatedOn (CreatedOn) -) -# -------------------------------------------------------- -CREATE TABLE Relationship ( - RelationshipId int(11) NOT NULL auto_increment, - SourceId int(11) default NULL, - TargetId int(11) default NULL, - SourceType tinyint(4) NOT NULL default '0', - TargetType tinyint(4) NOT NULL default '0', - Type int(11) NOT NULL default '0', - Enabled int(11) NOT NULL default '1', - Priority int(11) NOT NULL default '0', - PRIMARY KEY (RelationshipId), - KEY RelSource (SourceId), - KEY RelTarget (TargetId) -) -# -------------------------------------------------------- -CREATE TABLE SearchConfig ( - TableName varchar(40) NOT NULL default '', - FieldName varchar(40) NOT NULL default '', - SimpleSearch tinyint(4) NOT NULL default '0', - AdvancedSearch tinyint(4) NOT NULL default '0', - Description varchar(255) default NULL, - DisplayName varchar(80) default NULL, - ModuleName varchar(20) default NULL, - ConfigHeader varchar(255) default NULL, - DisplayOrder int(11) NOT NULL default '0', - SearchConfigId int(11) NOT NULL auto_increment, - Priority int(11) NOT NULL default '0', - FieldType varchar(20) NOT NULL default 'text', - ForeignField varchar(255) default NULL, - JoinClause varchar(255) default NULL, - IsWhere text, - IsNotWhere text, - ContainsWhere text, - NotContainsWhere text, - CustomFieldId int(11) NOT NULL default '0', - PRIMARY KEY (SearchConfigId) -) -# -------------------------------------------------------- -CREATE TABLE SearchLog ( - SearchLogId int(11) NOT NULL auto_increment, - Keyword varchar(255) NOT NULL default '', - Indices bigint(20) NOT NULL default '0', - SearchType int(11) NOT NULL default '0', - PRIMARY KEY (SearchLogId) -) -# -------------------------------------------------------- -CREATE TABLE SessionData ( - SessionKey varchar(50) NOT NULL default '', - VariableName varchar(255) NOT NULL default '', - VariableValue text NOT NULL, - KEY SessionKey (SessionKey), - KEY VariableName (VariableName) -) -# -------------------------------------------------------- -CREATE TABLE SpamControl ( - ItemResourceId int(11) NOT NULL default '0', - IPaddress varchar(20) NOT NULL default '', - Expire double NOT NULL default '0', - PortalUserId int(11) NOT NULL default '0', - DataType varchar(20) default NULL -) -# -------------------------------------------------------- -CREATE TABLE StatItem ( - StatItemId int(11) NOT NULL auto_increment, - Module varchar(20) NOT NULL default '', - ValueSQL varchar(255) default NULL, - ResetSQL varchar(255) default NULL, - ListLabel varchar(255) NOT NULL default '', - Priority int(11) NOT NULL default '0', - AdminSummary int(11) NOT NULL default '0', - PRIMARY KEY (StatItemId) -) -# -------------------------------------------------------- -CREATE TABLE Theme ( - ThemeId int(11) NOT NULL auto_increment, - Name varchar(40) NOT NULL default '', - Enabled int(11) NOT NULL default '1', - Description varchar(255) default NULL, - PrimaryTheme int(11) NOT NULL default '0', - CacheTimeout int(11) NOT NULL default '0', - PRIMARY KEY (ThemeId) -) -# -------------------------------------------------------- -CREATE TABLE ThemeFiles ( - FileId int(11) NOT NULL auto_increment, - ThemeId int(11) NOT NULL default '0', - FileName varchar(255) NOT NULL default '', - FilePath varchar(255) NOT NULL default '', - Description varchar(255) default NULL, - FileType int(11) NOT NULL default '0', - PRIMARY KEY (FileId), - KEY theme (ThemeId) -) -# -------------------------------------------------------- -CREATE TABLE UserGroup ( - PortalUserId int(11) NOT NULL default '0', - GroupId int(11) NOT NULL default '0', - PrimaryGroup tinyint(4) NOT NULL default '1', - PRIMARY KEY (PortalUserId,GroupId), - KEY GroupId (GroupId), - KEY PrimaryGroup (PrimaryGroup) -) -# -------------------------------------------------------- - -CREATE TABLE UserSession ( - SessionKey varchar(50) NOT NULL default '', - CurrentTempKey varchar(50) default NULL, - PrevTempKey varchar(50) default NULL, - LastAccessed double NOT NULL default '0', - PortalUserId varchar(255) NOT NULL default '', - Language varchar(255) NOT NULL default '', - Theme varchar(255) NOT NULL default '', - GroupId int(11) NOT NULL default '0', - IpAddress varchar(20) NOT NULL default '0.0.0.0', - Status int(11) NOT NULL default '1', - GroupList varchar(255) default NULL, - tz int(11) default NULL, - PRIMARY KEY (SessionKey), - KEY UserId (PortalUserId), - KEY LastAccessed (LastAccessed) -) -# -------------------------------------------------------- -CREATE TABLE SuggestMail ( - email varchar(255) NOT NULL default '', - sent double, - PRIMARY KEY (email) -) -# -------------------------------------------------------- -CREATE TABLE SysCache ( - SysCacheId int(11) NOT NULL auto_increment, - Name varchar(255) NOT NULL default '', - Value mediumtext, - Expire double NOT NULL default '0', - Module varchar(20) default NULL, - Context varchar(255) default NULL, - GroupList varchar(255) NOT NULL default '', - PRIMARY KEY (SysCacheId), - KEY Name (Name) -) -# -------------------------------------------------------- -CREATE TABLE TagLibrary ( - TagId int(11) NOT NULL auto_increment, - name varchar(255) NOT NULL default '', - description text, - example text, - scope varchar(20) NOT NULL default 'global', - PRIMARY KEY (TagId) -) -# -------------------------------------------------------- -CREATE TABLE TagAttributes ( - AttrId int(11) NOT NULL auto_increment, - TagId int(11) NOT NULL default '0', - Name varchar(255) NOT NULL default '', - AttrType varchar(20) default NULL, - DefValue varchar(255) default NULL, - Description TEXT, - Required int(11) NOT NULL default '0', - PRIMARY KEY (AttrId) -) -# -------------------------------------------------------- -CREATE TABLE EmailLog ( - EmailLogId int(11) NOT NULL auto_increment, - fromuser varchar(200) default NULL, - addressto varchar(255) default NULL, - subject varchar(255) default NULL, - timestamp bigint(20) default '0', - event varchar(100) default NULL, - PRIMARY KEY (EmailLogId) -) -# -------------------------------------------------------- -CREATE TABLE ImportScripts ( - is_id smallint(5) unsigned NOT NULL auto_increment, - is_Module varchar(50) NOT NULL default '', - is_string_id varchar(10) NOT NULL default '', - is_script varchar(100) NOT NULL default '', - is_label varchar(255) NOT NULL default '', - is_field_prefix varchar(50) NOT NULL default '', - is_requred_fields varchar(255) NOT NULL default '', - is_enabled tinyint(1) unsigned NOT NULL default '0', - PRIMARY KEY (is_id) +CREATE TABLE BanRules ( + RuleId int(11) NOT NULL auto_increment, + RuleType tinyint(4) NOT NULL default '0', + ItemField varchar(255) default NULL, + ItemVerb tinyint(4) NOT NULL default '0', + ItemValue varchar(255) NOT NULL default '', + ItemType int(11) NOT NULL default '0', + Priority int(11) NOT NULL default '0', + Status tinyint(4) NOT NULL default '1', + ErrorTag varchar(255) default NULL, + PRIMARY KEY (RuleId) +) +# -------------------------------------------------------- +CREATE TABLE Category ( + CategoryId int(11) NOT NULL auto_increment, + Type int(11) NOT NULL default '0', + ParentId int(11) NOT NULL default '0', + Name varchar(255) NOT NULL default '', + Description text NOT NULL, + CreatedOn double NOT NULL default '0', + EditorsPick tinyint(4) default NULL, + Status tinyint(4) NOT NULL default '0', + Pop tinyint(4) default NULL, + Priority int(11) default NULL, + MetaKeywords varchar(255) default NULL, + CachedDescendantCatsQty int(11) default NULL, + CachedNavbar text NOT NULL, + CreatedById int(11) NOT NULL default '0', + ResourceId int(11) default NULL, + ParentPath text NOT NULL, + MetaDescription varchar(255) default NULL, + HotItem int(11) NOT NULL default '2', + NewItem int(11) NOT NULL default '2', + PopItem int(11) NOT NULL default '2', + Modified double NOT NULL default '0', + ModifiedById int(11) NOT NULL default '0', + PRIMARY KEY (CategoryId), + KEY ParentId (ParentId), + KEY ResourceId (ResourceId), + KEY Modified (Modified), + KEY Priority (Priority), + KEY sorting (Name,Priority) +) +# -------------------------------------------------------- +CREATE TABLE CategoryItems ( + CategoryId int(11) NOT NULL default '0', + ItemResourceId int(11) NOT NULL default '0', + PrimaryCat tinyint(4) NOT NULL default '0', + PRIMARY KEY (CategoryId,ItemResourceId), + KEY ItemResourceId (ItemResourceId), + KEY PrimaryCat (PrimaryCat) +) +# -------------------------------------------------------- +CREATE TABLE ConfigurationAdmin ( + VariableName varchar(80) NOT NULL default '', + heading varchar(255) default NULL, + prompt varchar(255) default NULL, + element_type varchar(20) NOT NULL default '', + validation varchar(255) default NULL, + ValueList text default NULL, + DisplayOrder int(11) NOT NULL default '0', + Install int(11) NOT NULL default '1', + PRIMARY KEY (VariableName) +) +# -------------------------------------------------------- +CREATE TABLE ConfigurationValues ( + VariableName varchar(255) NOT NULL default '', + VariableValue varchar(255) default NULL, + ModuleOwner varchar(20) default 'In-Portal', + Section varchar(255) NOT NULL default '', + PRIMARY KEY (VariableName) +) +# -------------------------------------------------------- +CREATE TABLE CountCache ( + ListType int(11) NOT NULL default '0', + ItemType int(11) NOT NULL default '-1', + Value int(11) NOT NULL default '0', + CountCacheId int(11) NOT NULL auto_increment, + LastUpdate int(11) NOT NULL default '0', + ExtraId varchar(50) default NULL, + TodayOnly tinyint(4) NOT NULL default '0', + PRIMARY KEY (CountCacheId) +) +# -------------------------------------------------------- +CREATE TABLE CustomField ( + CustomFieldId int(11) NOT NULL auto_increment, + Type int(11) NOT NULL default '0', + FieldName varchar(255) NOT NULL default '', + FieldLabel varchar(40) default NULL, + Heading varchar(60) default NULL, + Prompt varchar(60) default NULL, + ElementType varchar(50) NOT NULL default '', + ValueList varchar(255) default NULL, + DisplayOrder int(11) NOT NULL default '0', + OnGeneralTab tinyint(4) NOT NULL default '0', + PRIMARY KEY (CustomFieldId), + KEY Type (Type) +) +# -------------------------------------------------------- +CREATE TABLE CustomMetaData ( + CustomDataId int(11) NOT NULL auto_increment, + ResourceId int(11) NOT NULL default '0', + CustomFieldId int(11) NOT NULL default '0', + Value text NOT NULL, + PRIMARY KEY (CustomDataId) +) +# -------------------------------------------------------- +CREATE TABLE EmailMessage ( + EmailMessageId int(10) NOT NULL auto_increment, + Template longtext, + MessageType enum('html','text') NOT NULL default 'text', + LanguageId int(11) NOT NULL default '0', + EventId int(11) NOT NULL default '0', + PRIMARY KEY (EmailMessageId) +) +# -------------------------------------------------------- +CREATE TABLE EmailQueue ( + Subject text NOT NULL, + toaddr text NOT NULL, + fromaddr text NOT NULL, + message blob, + headers blob, + queued timestamp NOT NULL +) +# -------------------------------------------------------- +CREATE TABLE EmailSubscribers ( + EmailMessageId int(11) NOT NULL default '0', + PortalUserId int(11) NOT NULL default '0' +) +# -------------------------------------------------------- +CREATE TABLE Events ( + EventId int(11) NOT NULL auto_increment, + Event varchar(40) NOT NULL default '', + Enabled int(11) NOT NULL default '1', + FromUserId int(11) NOT NULL default '0', + Module varchar(40) NOT NULL default '', + Description varchar(255) NOT NULL default '', + Type int(11) NOT NULL default '0', + PRIMARY KEY (EventId) +) +# -------------------------------------------------------- +CREATE TABLE Favorites ( + FavoriteId int(11) NOT NULL auto_increment, + PortalUserId int(11) NOT NULL default '0', + ResourceId int(11) NOT NULL default '0', + ItemTypeId int(11) NOT NULL default '0', + Modified int(11) NOT NULL default '0', + PRIMARY KEY (FavoriteId), + UNIQUE KEY main (PortalUserId,ResourceId) +) +# -------------------------------------------------------- +CREATE TABLE IdGenerator ( + lastid int(11) default NULL +) +# -------------------------------------------------------- +CREATE TABLE Images ( + ImageId int(11) NOT NULL auto_increment, + ResourceId int(11) NOT NULL default '0', + Url varchar(255) NOT NULL default '', + Name varchar(255) NOT NULL default '', + AltName varchar(255) default NULL, + ImageIndex int(11) NOT NULL default '0', + LocalImage tinyint(4) NOT NULL default '1', + LocalPath varchar(240) NOT NULL default '', + Enabled int(11) NOT NULL default '1', + DefaultImg int(11) NOT NULL default '0', + ThumbUrl varchar(255) default NULL, + Priority int(11) NOT NULL default '0', + ThumbPath varchar(255) default NULL, + LocalThumb tinyint(4) NOT NULL default '0', + SameImages tinyint(4) NOT NULL default '0', + PRIMARY KEY (ImageId), + KEY ResourceId (ResourceId) +) +# -------------------------------------------------------- +CREATE TABLE ItemRating ( + RatingId int(11) NOT NULL auto_increment, + IPAddress varchar(255) NOT NULL default '', + CreatedOn double NOT NULL default '0', + RatingValue int(11) NOT NULL default '0', + ItemId int(11) NOT NULL default '0', + PRIMARY KEY (RatingId) +) +# -------------------------------------------------------- +CREATE TABLE ItemReview ( + ReviewId int(11) NOT NULL auto_increment, + CreatedOn double NOT NULL default '0', + ReviewText longtext NOT NULL, + IPAddress varchar(255) NOT NULL default '', + ItemId int(11) NOT NULL default '0', + CreatedById int(11) NOT NULL default '0', + ItemType tinyint(4) NOT NULL default '0', + Priority int(11) NOT NULL default '0', + Status tinyint(4) NOT NULL default '0', + TextFormat int(11) NOT NULL default '0', + Module varchar(255) NOT NULL default '', + PRIMARY KEY (ReviewId) +) +# -------------------------------------------------------- +CREATE TABLE ItemTypes ( + ItemType int(11) NOT NULL default '0', + Module varchar(50) NOT NULL default '', + SourceTable varchar(100) NOT NULL default '', + TitleField varchar(50) default NULL, + CreatorField varchar(255) NOT NULL default '', + PopField varchar(255) default NULL, + RateField varchar(255) default NULL, + LangVar varchar(255) NOT NULL default '', + PrimaryItem int(11) NOT NULL default '0', + EditUrl varchar(255) NOT NULL default '', + ClassName varchar(40) NOT NULL default '', + ItemName varchar(50) NOT NULL default '', + PRIMARY KEY (ItemType), + KEY Module (Module) +) +# -------------------------------------------------------- +CREATE TABLE Language ( + LanguageId int(11) NOT NULL auto_increment, + PackName varchar(40) NOT NULL default '', + LocalName varchar(40) NOT NULL default '', + Enabled int(11) NOT NULL default '0', + PrimaryLang int(11) NOT NULL default '0', + IconURL varchar(255) default NULL, + DateFormat varchar(50) NOT NULL default '', + TimeFormat varchar(50) NOT NULL default '', + DecimalPoint char(2) NOT NULL default '.', + ThousandSep char(1) NOT NULL default ',', + PRIMARY KEY (LanguageId) +) +# -------------------------------------------------------- +CREATE TABLE Modules ( + Name varchar(255) NOT NULL default '', + Path varchar(255) NOT NULL default '', + Var varchar(10) NOT NULL default '', + Version varchar(10) NOT NULL default '', + Loaded tinyint(4) NOT NULL default '1', + LoadOrder tinyint(4) NOT NULL default '0', + TemplatePath varchar(255) NOT NULL default '', + RootCat int(11) NOT NULL default '0', + BuildDate double NOT NULL default '0', + PRIMARY KEY (Name) +) +# -------------------------------------------------------- +CREATE TABLE PermCache ( + PermCacheId int(11) NOT NULL auto_increment, + CategoryId int(11) NOT NULL default '0', + PermId int(11) NOT NULL default '0', + ACL varchar(255) NOT NULL default '', + DACL varchar(255) NOT NULL default '', + PRIMARY KEY (PermCacheId), + KEY CategoryId (CategoryId), + KEY PermId (PermId) +) +# -------------------------------------------------------- +CREATE TABLE PermissionConfig ( + PermissionConfigId int(11) NOT NULL auto_increment, + PermissionName varchar(30) NOT NULL default '', + Description varchar(255) NOT NULL default '', + ErrorMessage varchar(255) NOT NULL default '', + ModuleId varchar(20) NOT NULL default '0', + PRIMARY KEY (PermissionConfigId), + KEY PermissionName (PermissionName) +) +# -------------------------------------------------------- +CREATE TABLE Permissions ( + PermissionId int(11) NOT NULL auto_increment, + Permission varchar(30) NOT NULL default '', + GroupId int(11) default '0', + PermissionValue int(11) NOT NULL default '0', + Type tinyint(4) NOT NULL default '0', + CatId int(11) NOT NULL default '0', + PRIMARY KEY (PermissionId) +) +# -------------------------------------------------------- +CREATE TABLE PersistantSessionData ( + PortalUserId int(11) NOT NULL default '0', + VariableName varchar(255) NOT NULL default '', + VariableValue text NOT NULL, + KEY UserId (PortalUserId), + KEY VariableName (VariableName) +) +# -------------------------------------------------------- +CREATE TABLE Phrase ( + Phrase varchar(255) NOT NULL default '', + Translation varchar(255) NOT NULL default '', + PhraseType int(11) NOT NULL default '0', + PhraseId int(11) NOT NULL auto_increment, + LanguageId int(11) NOT NULL default '0', + PRIMARY KEY (PhraseId), + INDEX Phrase_Index (Phrase) +) +# -------------------------------------------------------- +CREATE TABLE PhraseCache ( + Template varchar(40) NOT NULL default '', + PhraseList text NOT NULL, + CacheDate int(11) NOT NULL default '0', + ThemeId int(11) NOT NULL default '0', + PRIMARY KEY (Template) +) +# -------------------------------------------------------- +CREATE TABLE PortalGroup ( + GroupId int(11) NOT NULL auto_increment, + Name varchar(255) NOT NULL default '', + Description varchar(255) default NULL, + CreatedOn double NOT NULL default '0', + System tinyint(4) NOT NULL default '0', + Personal tinyint(4) NOT NULL default '0', + Enabled tinyint(4) NOT NULL default '1', + ResourceId int(11) NOT NULL default '0', + PRIMARY KEY (GroupId), + UNIQUE KEY Name (Name), + KEY ResourceId (ResourceId), + KEY Personal (Personal), + KEY Enabled (Enabled) +) +# -------------------------------------------------------- +CREATE TABLE PortalUser ( + PortalUserId int(11) NOT NULL auto_increment, + Login varchar(255) default NULL, + Password varchar(255) default NULL, + FirstName varchar(255) default NULL, + LastName varchar(255) default NULL, + Email varchar(255) NOT NULL default '', + CreatedOn double NOT NULL default '0', + Phone varchar(20) default NULL, + Street varchar(255) default NULL, + City varchar(20) default NULL, + State varchar(20) default NULL, + Zip varchar(20) default NULL, + Country varchar(20) NOT NULL default '', + ResourceId int(11) NOT NULL default '0', + Status tinyint(4) NOT NULL default '2', + Modified int(11) NOT NULL default '0', + dob double NOT NULL default '0', + tz int(11) default NULL, + ip varchar(20) default NULL, + IsBanned tinyint(1) NOT NULL default '0', + PRIMARY KEY (PortalUserId), + UNIQUE KEY Login (Login), + KEY ResourceId (ResourceId), + KEY CreatedOn (CreatedOn) +) +# -------------------------------------------------------- +CREATE TABLE Relationship ( + RelationshipId int(11) NOT NULL auto_increment, + SourceId int(11) default NULL, + TargetId int(11) default NULL, + SourceType tinyint(4) NOT NULL default '0', + TargetType tinyint(4) NOT NULL default '0', + Type int(11) NOT NULL default '0', + Enabled int(11) NOT NULL default '1', + Priority int(11) NOT NULL default '0', + PRIMARY KEY (RelationshipId), + KEY RelSource (SourceId), + KEY RelTarget (TargetId) +) +# -------------------------------------------------------- +CREATE TABLE SearchConfig ( + TableName varchar(40) NOT NULL default '', + FieldName varchar(40) NOT NULL default '', + SimpleSearch tinyint(4) NOT NULL default '0', + AdvancedSearch tinyint(4) NOT NULL default '0', + Description varchar(255) default NULL, + DisplayName varchar(80) default NULL, + ModuleName varchar(20) default NULL, + ConfigHeader varchar(255) default NULL, + DisplayOrder int(11) NOT NULL default '0', + SearchConfigId int(11) NOT NULL auto_increment, + Priority int(11) NOT NULL default '0', + FieldType varchar(20) NOT NULL default 'text', + ForeignField varchar(255) default NULL, + JoinClause varchar(255) default NULL, + IsWhere text, + IsNotWhere text, + ContainsWhere text, + NotContainsWhere text, + CustomFieldId int(11) NOT NULL default '0', + PRIMARY KEY (SearchConfigId) +) +# -------------------------------------------------------- +CREATE TABLE SearchLog ( + SearchLogId int(11) NOT NULL auto_increment, + Keyword varchar(255) NOT NULL default '', + Indices bigint(20) NOT NULL default '0', + SearchType int(11) NOT NULL default '0', + PRIMARY KEY (SearchLogId) +) +# -------------------------------------------------------- +CREATE TABLE SessionData ( + SessionKey varchar(50) NOT NULL default '', + VariableName varchar(255) NOT NULL default '', + VariableValue text NOT NULL, + KEY SessionKey (SessionKey), + KEY VariableName (VariableName) +) +# -------------------------------------------------------- +CREATE TABLE SpamControl ( + ItemResourceId int(11) NOT NULL default '0', + IPaddress varchar(20) NOT NULL default '', + Expire double NOT NULL default '0', + PortalUserId int(11) NOT NULL default '0', + DataType varchar(20) default NULL +) +# -------------------------------------------------------- +CREATE TABLE StatItem ( + StatItemId int(11) NOT NULL auto_increment, + Module varchar(20) NOT NULL default '', + ValueSQL varchar(255) default NULL, + ResetSQL varchar(255) default NULL, + ListLabel varchar(255) NOT NULL default '', + Priority int(11) NOT NULL default '0', + AdminSummary int(11) NOT NULL default '0', + PRIMARY KEY (StatItemId) +) +# -------------------------------------------------------- +CREATE TABLE Theme ( + ThemeId int(11) NOT NULL auto_increment, + Name varchar(40) NOT NULL default '', + Enabled int(11) NOT NULL default '1', + Description varchar(255) default NULL, + PrimaryTheme int(11) NOT NULL default '0', + CacheTimeout int(11) NOT NULL default '0', + PRIMARY KEY (ThemeId) +) +# -------------------------------------------------------- +CREATE TABLE ThemeFiles ( + FileId int(11) NOT NULL auto_increment, + ThemeId int(11) NOT NULL default '0', + FileName varchar(255) NOT NULL default '', + FilePath varchar(255) NOT NULL default '', + Description varchar(255) default NULL, + FileType int(11) NOT NULL default '0', + PRIMARY KEY (FileId), + KEY theme (ThemeId) +) +# -------------------------------------------------------- +CREATE TABLE UserGroup ( + PortalUserId int(11) NOT NULL default '0', + GroupId int(11) NOT NULL default '0', + PrimaryGroup tinyint(4) NOT NULL default '1', + PRIMARY KEY (PortalUserId,GroupId), + KEY GroupId (GroupId), + KEY PrimaryGroup (PrimaryGroup) +) +# -------------------------------------------------------- + +CREATE TABLE UserSession ( + SessionKey varchar(50) NOT NULL default '', + CurrentTempKey varchar(50) default NULL, + PrevTempKey varchar(50) default NULL, + LastAccessed double NOT NULL default '0', + PortalUserId varchar(255) NOT NULL default '', + Language varchar(255) NOT NULL default '', + Theme varchar(255) NOT NULL default '', + GroupId int(11) NOT NULL default '0', + IpAddress varchar(20) NOT NULL default '0.0.0.0', + Status int(11) NOT NULL default '1', + GroupList varchar(255) default NULL, + tz int(11) default NULL, + PRIMARY KEY (SessionKey), + KEY UserId (PortalUserId), + KEY LastAccessed (LastAccessed) +) +# -------------------------------------------------------- +CREATE TABLE SuggestMail ( + email varchar(255) NOT NULL default '', + sent double, + PRIMARY KEY (email) +) +# -------------------------------------------------------- +CREATE TABLE SysCache ( + SysCacheId int(11) NOT NULL auto_increment, + Name varchar(255) NOT NULL default '', + Value mediumtext, + Expire double NOT NULL default '0', + Module varchar(20) default NULL, + Context varchar(255) default NULL, + GroupList varchar(255) NOT NULL default '', + PRIMARY KEY (SysCacheId), + KEY Name (Name) +) +# -------------------------------------------------------- +CREATE TABLE TagLibrary ( + TagId int(11) NOT NULL auto_increment, + name varchar(255) NOT NULL default '', + description text, + example text, + scope varchar(20) NOT NULL default 'global', + PRIMARY KEY (TagId) +) +# -------------------------------------------------------- +CREATE TABLE TagAttributes ( + AttrId int(11) NOT NULL auto_increment, + TagId int(11) NOT NULL default '0', + Name varchar(255) NOT NULL default '', + AttrType varchar(20) default NULL, + DefValue varchar(255) default NULL, + Description TEXT, + Required int(11) NOT NULL default '0', + PRIMARY KEY (AttrId) +) +# -------------------------------------------------------- +CREATE TABLE EmailLog ( + EmailLogId int(11) NOT NULL auto_increment, + fromuser varchar(200) default NULL, + addressto varchar(255) default NULL, + subject varchar(255) default NULL, + timestamp bigint(20) default '0', + event varchar(100) default NULL, + PRIMARY KEY (EmailLogId) +) +# -------------------------------------------------------- +CREATE TABLE ImportScripts ( + is_id smallint(5) unsigned NOT NULL auto_increment, + is_Module varchar(50) NOT NULL default '', + is_string_id varchar(10) NOT NULL default '', + is_script varchar(100) NOT NULL default '', + is_label varchar(255) NOT NULL default '', + is_field_prefix varchar(50) NOT NULL default '', + is_requred_fields varchar(255) NOT NULL default '', + is_enabled tinyint(1) unsigned NOT NULL default '0', + PRIMARY KEY (is_id) ) \ No newline at end of file Index: trunk/admin/install/upgrades/inportal_upgrade_v1.0.8.sql =================================================================== diff -u -N -r616 -r642 --- trunk/admin/install/upgrades/inportal_upgrade_v1.0.8.sql (.../inportal_upgrade_v1.0.8.sql) (revision 616) +++ trunk/admin/install/upgrades/inportal_upgrade_v1.0.8.sql (.../inportal_upgrade_v1.0.8.sql) (revision 642) @@ -1,4 +1,7 @@ -UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Name' AND TableName = 'Category'; -UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Description' AND TableName = 'Category'; - +UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Name' AND TableName = 'Category'; +UPDATE SearchConfig SET Priority = 2 WHERE FieldName = 'Description' AND TableName = 'Category'; +ALTER TABLE ConfigurationAdmin CHANGE ValueList ValueList TEXT; +UPDATE ConfigurationAdmin SET ValueList='Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0' WHERE VariableName='Category_Sortfield'; +UPDATE ConfigurationAdmin SET ValueList='Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0' WHERE VariableName='Category_Sortfield2'; + UPDATE Modules SET Version = '1.0.8' WHERE Name = 'In-Portal'; \ No newline at end of file Index: trunk/admin/browse.php =================================================================== diff -u -N -r547 -r642 --- trunk/admin/browse.php (.../browse.php) (revision 547) +++ trunk/admin/browse.php (.../browse.php) (revision 642) @@ -1,472 +1,472 @@ -

    "; - -if(!strlen($pathtoroot)) -{ - $path=dirname(realpath(__FILE__)); - if(strlen($path)) - { - /* determine the OS type for path parsing */ - $pos = strpos($path,":"); - if ($pos === false) - { - $gOS_TYPE="unix"; - $pathchar = "/"; - } - else - { - $gOS_TYPE="win"; - $pathchar="\\"; - } - $p = $path.$pathchar; - /*Start looking for the root flag file */ - while(!strlen($pathtoroot) && strlen($p)) - { - $sub = substr($p,strlen($pathchar)*-1); - if($sub==$pathchar) - { - $filename = $p."root.flg"; - } - else - $filename = $p.$pathchar."root.flg"; - if(file_exists($filename)) - { - $pathtoroot = $p; - } - else - { - $parent = realpath($p.$pathchar."..".$pathchar); - if($parent!=$p) - { - $p = $parent; - } - else - $p = ""; - } - } - if(!strlen($pathtoroot)) - $pathtoroot = ".".$pathchar; - } - else - { - $pathtoroot = ".".$pathchar; - } -} - -$sub = substr($pathtoroot,strlen($pathchar)*-1); -if($sub!=$pathchar) -{ - $pathtoroot = $pathtoroot.$pathchar; -} -//echo $pathtoroot; - -require_once($pathtoroot."kernel/startup.php"); - -if (!admin_login()) -{ - if(!headers_sent()) - setcookie("sid"," ",time()-3600); - $objSession->Logout(); - header("Location: ".$adminURL."/login.php"); - die(); - //require_once($pathtoroot."admin/login.php"); -} - -$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path"); -$admin = $objConfig->Get("AdminDirectory"); -if(!strlen($admin)) - $admin = "admin"; - -$localURL=$rootURL."kernel/"; -$adminURL = $rootURL.$admin; -$imagesURL = $adminURL."/images"; -$browseURL = $adminURL."/browse"; -$cssURL = $adminURL."/include"; - -$indexURL = $rootURL."index.php"; - -$m_var_list_update["cat"] = 0; -$homeURL = "javascript:AdminCatNav('".$_SERVER["PHP_SELF"]."?env=".BuildEnv()."');"; -unset($m_var_list_update["cat"]); - -$envar = "env=" . BuildEnv(); - -if($objCatList->CurrentCategoryID()>0) -{ - $c = $objCatList->CurrentCat(); - $upURL = "javascript:AdminCatNav('".$c->Admin_Parent_Link()."');"; -} -else - $upURL = $_SERVER["PHP_SELF"]."?".$envar; - -//admin only util - -$pathtolocal = $pathtoroot."kernel/"; -require_once ($pathtoroot.$admin."/include/elements.php"); -//require_once ($pathtoroot."kernel/admin/include/navmenu.php"); -require_once ($pathtolocal."admin/include/navmenu.php"); -require_once($pathtoroot.$admin."/browse/toolbar.php"); - -$m = GetModuleArray(); -foreach($m as $key=>$value) -{ - $path = $pathtoroot.$value."admin/include/parser.php"; - if(file_exists($path)) - { - //echo ""; - @include_once($path); - } -} -if(!defined('IS_INSTALL'))define('IS_INSTALL',0); -if(!IS_INSTALL) -{ - if (!admin_login()) - { - if(!headers_sent()) - setcookie("sid"," ",time()-3600); - $objSession->Logout(); - header("Location: ".$adminURL."/login.php"); - die(); - //require_once($pathtoroot."admin/login.php"); - } -} -//Set Section -$section = 'in-portal:browse'; - -//Set Environment Variable - -//echo $objCatList->ItemsOnClipboard()." Categories on the clipboard
    \n"; -//echo $objTopicList->ItemsOnClipboard()." Topics on the clipboard
    \n"; -//echo $objLinkList->ItemsOnClipboard()." Links on the clipboard
    \n"; -//echo $objArticleList->ItemsOnClipboard()." Articles on the clipboard
    \n"; - -// save last category visited -$objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') ); -$objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() ); - -/* // for testing -$last_cat = $objSession->GetVariable('last_category'); -$prev_cat = $objSession->GetVariable('prev_category'); -echo "Last CAT: [$last_cat]
    "; -echo "Prev CAT: [$prev_cat]
    "; -*/ -$SearchType = $objSession->GetVariable("SearchType"); -if(!strlen($SearchType)) - $SearchType = "all"; -$SearchLabel = "la_SearchLabel"; - -if( GetVar('SearchWord') !== false ) $objSession->SetVariable('admin_seach_words', GetVar('SearchWord') ); -$SearchWord = $objSession->GetVariable('admin_seach_words'); - -$objSession->SetVariable("HasChanges", 0); - -// where should all edit popups submit changes -$objSession->SetVariable("ReturnScript", basename($_SERVER['PHP_SELF']) ); -/* page header */ -print << - - In-portal - - - - -END; - - require_once($pathtoroot.$admin."/include/mainscript.php"); - -print << - if (window.opener != null) { - theMainScript.CloseAndRefreshParent(); - } - -END; - -print << - - - - - -END; -load_module_styles(); -if( !isset($list) ) $list = ''; -if(($SearchType=="categories" || $SearchType="all") && strlen($list)) -{ - int_SectionHeader(NULL,NULL,NULL,admin_language("la_Title_SearchResults")); -} -else - int_SectionHeader(); - -$filter = false; // always initialize variables before use - -if($objSession->GetVariable("SearchWord") != '') { - $filter = true; -} -else { - $bit_combo = $objModules->ExecuteFunction('GetModuleInfo', 'all_bitmask'); - $bit_combo = $objModules->MergeReturn($bit_combo); - foreach($bit_combo['VarName'] as $mod_name => $VarName) - { - //echo "VarName: [$VarName] = [".$objConfig->Get($VarName)."], ALL = [".$bit_combo['Bits'][$mod_name]."]
    "; - if( $objConfig->Get($VarName) ) - if( $objConfig->Get($VarName) != $bit_combo['Bits'][$mod_name] ) - { - $filter = true; - break; - } - } -} -?> -
    - - - - - - - -
    -
    - " ImagePath=""> - " ImagePath=""> - "> - " ImagePath=""> - " ImagePath=""> - -0) - print "tab=\"".$btn["Tab"]."\""; - print ">\n"; - } -?> - " ImagePath=""> - " ImagePath=""> - "> - " ImagePath=""> - " ImagePath=""> - "> - " ImagePath=""> - " ImagePath=""> - " ImagePath=""> - "> - " ImagePath=""> - " ImagePath=""> - "> - " ImagePath=""> - " ImagePath=""> -
    -
    - - - - - - - -
    - - - " NAME="admin_search" ID="admin_search">">"> - - - - -
     /icon16_search.gif" alt="" align="absMiddle" onclick="this.action = this.getAttribute('action'); actionHandler(this);" src="/arrow16.gif" onmouseover="this.src='/icon16_search_f2.gif'" onmouseout="this.src='/icon16_search.gif'" style="cursor:hand" width="22" width="22"><?php echo admin_language(" align="absMiddle" onclick="this.action = this.getAttribute('action'); actionHandler(this);" src="/arrow16.gif" onmouseover="this.src='/arrow16_f2.gif'" onmouseout="this.src='/arrow16.gif'" style="cursor:hand"> - /icon16_search_reset.gif" alt="" align="absMiddle" onclick="document.all.SearchWord.value = ''; this.action = this.getAttribute('action'); actionHandler(this);" onmouseover="this.src='/icon16_search_reset_f2.gif'" onmouseout="this.src='/icon16_search_reset.gif'" style="cursor:hand" width="22" width="22">  -
    - - -
    - - - - - -
    - -
    - -
    - -QueryOrderByClause(TRUE,TRUE,TRUE); - $objCatList->Clear(); - $IsSearch = FALSE; - if($SearchType == 'categories' || $SearchType == 'all') - { - $list = $objSession->GetVariable("SearchWord"); - $SearchQuery = $objCatList->AdminSearchWhereClause($list); - if(strlen($SearchQuery)) - { - $SearchQuery = " (".$SearchQuery.") "; - if( strlen($CatScopeClause) ) $SearchQuery .= " AND ".$CatScopeClause; - $objCatList->LoadCategories($SearchQuery.$CategoryFilter,$OrderBy); - $IsSearch = TRUE; - } - else - $objCatList->LoadCategories("ParentId=".$objCatList->CurrentCategoryID()." ".$CategoryFilter,$OrderBy); - } - else - $objCatList->LoadCategories("ParentId=".$objCatList->CurrentCategoryID()." ".$CategoryFilter, $OrderBy); - - $TotalItemCount += $objCatList->QueryItemCount; - -?> -GetAdminUserErrors(); - if(count($e)>0) - { - echo ""; - for($ex = 0; $ex"; - } - echo "
    ".prompt_language($e[$ex])."

    "; - } -?> - - - - - - - -
    - - - - - - - -
    - - - :  - - (QueryItemCount; ?>)  - - -
    -
     
    -
    - - -
    -
    - -
    -
    - - CurrentCategoryID(),$template); - ?> -
    -
    -
    - - TabRow(); - if(count($ItemTabs->Tabs)) - { - ?> -
    - -
    - $value) - { - $path = $pathtoroot.$value."admin/browse.php"; - if(file_exists($path)) - { - //echo "\n\n"; - include_once($path); - } - } - ?> -
    - - - - -
    -
    - - - - +

    "; + +if(!strlen($pathtoroot)) +{ + $path=dirname(realpath(__FILE__)); + if(strlen($path)) + { + /* determine the OS type for path parsing */ + $pos = strpos($path,":"); + if ($pos === false) + { + $gOS_TYPE="unix"; + $pathchar = "/"; + } + else + { + $gOS_TYPE="win"; + $pathchar="\\"; + } + $p = $path.$pathchar; + /*Start looking for the root flag file */ + while(!strlen($pathtoroot) && strlen($p)) + { + $sub = substr($p,strlen($pathchar)*-1); + if($sub==$pathchar) + { + $filename = $p."root.flg"; + } + else + $filename = $p.$pathchar."root.flg"; + if(file_exists($filename)) + { + $pathtoroot = $p; + } + else + { + $parent = realpath($p.$pathchar."..".$pathchar); + if($parent!=$p) + { + $p = $parent; + } + else + $p = ""; + } + } + if(!strlen($pathtoroot)) + $pathtoroot = ".".$pathchar; + } + else + { + $pathtoroot = ".".$pathchar; + } +} + +$sub = substr($pathtoroot,strlen($pathchar)*-1); +if($sub!=$pathchar) +{ + $pathtoroot = $pathtoroot.$pathchar; +} +//echo $pathtoroot; + +require_once($pathtoroot."kernel/startup.php"); + +if (!admin_login()) +{ + if(!headers_sent()) + setcookie("sid"," ",time()-3600); + $objSession->Logout(); + header("Location: ".$adminURL."/login.php"); + die(); + //require_once($pathtoroot."admin/login.php"); +} + +$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path"); +$admin = $objConfig->Get("AdminDirectory"); +if(!strlen($admin)) + $admin = "admin"; + +$localURL=$rootURL."kernel/"; +$adminURL = $rootURL.$admin; +$imagesURL = $adminURL."/images"; +$browseURL = $adminURL."/browse"; +$cssURL = $adminURL."/include"; + +$indexURL = $rootURL."index.php"; + +$m_var_list_update["cat"] = 0; +$homeURL = "javascript:AdminCatNav('".$_SERVER["PHP_SELF"]."?env=".BuildEnv()."');"; +unset($m_var_list_update["cat"]); + +$envar = "env=" . BuildEnv(); + +if($objCatList->CurrentCategoryID()>0) +{ + $c = $objCatList->CurrentCat(); + $upURL = "javascript:AdminCatNav('".$c->Admin_Parent_Link()."');"; +} +else + $upURL = $_SERVER["PHP_SELF"]."?".$envar; + +//admin only util + +$pathtolocal = $pathtoroot."kernel/"; +require_once ($pathtoroot.$admin."/include/elements.php"); +//require_once ($pathtoroot."kernel/admin/include/navmenu.php"); +require_once ($pathtolocal."admin/include/navmenu.php"); +require_once($pathtoroot.$admin."/browse/toolbar.php"); + +$m = GetModuleArray(); +foreach($m as $key=>$value) +{ + $path = $pathtoroot.$value."admin/include/parser.php"; + if(file_exists($path)) + { + //echo ""; + @include_once($path); + } +} +if(!defined('IS_INSTALL'))define('IS_INSTALL',0); +if(!IS_INSTALL) +{ + if (!admin_login()) + { + if(!headers_sent()) + setcookie("sid"," ",time()-3600); + $objSession->Logout(); + header("Location: ".$adminURL."/login.php"); + die(); + //require_once($pathtoroot."admin/login.php"); + } +} +//Set Section +$section = 'in-portal:browse'; + +//Set Environment Variable + +//echo $objCatList->ItemsOnClipboard()." Categories on the clipboard
    \n"; +//echo $objTopicList->ItemsOnClipboard()." Topics on the clipboard
    \n"; +//echo $objLinkList->ItemsOnClipboard()." Links on the clipboard
    \n"; +//echo $objArticleList->ItemsOnClipboard()." Articles on the clipboard
    \n"; + +// save last category visited +$objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') ); +$objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() ); + +/* // for testing +$last_cat = $objSession->GetVariable('last_category'); +$prev_cat = $objSession->GetVariable('prev_category'); +echo "Last CAT: [$last_cat]
    "; +echo "Prev CAT: [$prev_cat]
    "; +*/ +$SearchType = $objSession->GetVariable("SearchType"); +if(!strlen($SearchType)) + $SearchType = "all"; +$SearchLabel = "la_SearchLabel"; + +if( GetVar('SearchWord') !== false ) $objSession->SetVariable('admin_seach_words', GetVar('SearchWord') ); +$SearchWord = $objSession->GetVariable('admin_seach_words'); + +$objSession->SetVariable("HasChanges", 0); + +// where should all edit popups submit changes +$objSession->SetVariable("ReturnScript", basename($_SERVER['PHP_SELF']) ); +/* page header */ +print << + + In-portal + + + + +END; + + require_once($pathtoroot.$admin."/include/mainscript.php"); + +print << + if (window.opener != null) { + theMainScript.CloseAndRefreshParent(); + } + +END; + +print << + + + + + +END; +load_module_styles(); +if( !isset($list) ) $list = ''; +if(($SearchType=="categories" || $SearchType="all") && strlen($list)) +{ + int_SectionHeader(NULL,NULL,NULL,admin_language("la_Title_SearchResults")); +} +else + int_SectionHeader(); + +$filter = false; // always initialize variables before use + +if($objSession->GetVariable("SearchWord") != '') { + $filter = true; +} +else { + $bit_combo = $objModules->ExecuteFunction('GetModuleInfo', 'all_bitmask'); + $bit_combo = $objModules->MergeReturn($bit_combo); + foreach($bit_combo['VarName'] as $mod_name => $VarName) + { + //echo "VarName: [$VarName] = [".$objConfig->Get($VarName)."], ALL = [".$bit_combo['Bits'][$mod_name]."]
    "; + if( $objConfig->Get($VarName) ) + if( $objConfig->Get($VarName) != $bit_combo['Bits'][$mod_name] ) + { + $filter = true; + break; + } + } +} +?> +
    + + + + + + + +
    +
    + " ImagePath=""> + " ImagePath=""> + "> + " ImagePath=""> + " ImagePath=""> + +0) + print "tab=\"".$btn["Tab"]."\""; + print ">\n"; + } +?> + " ImagePath=""> + " ImagePath=""> + "> + " ImagePath=""> + " ImagePath=""> + "> + " ImagePath=""> + " ImagePath=""> + " ImagePath=""> + "> + " ImagePath=""> + " ImagePath=""> + "> + " ImagePath=""> + " ImagePath=""> +
    +
    + + + + + + + +
    + + +
    " NAME="admin_search" ID="admin_search">">"> + + + + +
     /icon16_search.gif" alt="" align="absMiddle" onclick="this.action = this.getAttribute('action'); actionHandler(this);" src="/arrow16.gif" onmouseover="this.src='/icon16_search_f2.gif'" onmouseout="this.src='/icon16_search.gif'" style="cursor:hand" width="22" width="22"><?php echo admin_language(" align="absMiddle" onclick="this.action = this.getAttribute('action'); actionHandler(this);" src="/arrow16.gif" onmouseover="this.src='/arrow16_f2.gif'" onmouseout="this.src='/arrow16.gif'" style="cursor:hand"> + /icon16_search_reset.gif" alt="" align="absMiddle" onclick="document.all.SearchWord.value = ''; this.action = this.getAttribute('action'); actionHandler(this);" onmouseover="this.src='/icon16_search_reset_f2.gif'" onmouseout="this.src='/icon16_search_reset.gif'" style="cursor:hand" width="22" width="22">  +
    +
    + +
    + + + + + +
    + +
    + +
    + +QueryOrderByClause(TRUE,TRUE,TRUE); + $objCatList->Clear(); + $IsSearch = FALSE; + if($SearchType == 'categories' || $SearchType == 'all') + { + $list = $objSession->GetVariable("SearchWord"); + $SearchQuery = $objCatList->AdminSearchWhereClause($list); + if(strlen($SearchQuery)) + { + $SearchQuery = " (".$SearchQuery.") "; + if( strlen($CatScopeClause) ) $SearchQuery .= " AND ".$CatScopeClause; + $objCatList->LoadCategories($SearchQuery.$CategoryFilter,$OrderBy); + $IsSearch = TRUE; + } + else + $objCatList->LoadCategories("ParentId=".$objCatList->CurrentCategoryID()." ".$CategoryFilter,$OrderBy); + } + else + $objCatList->LoadCategories("ParentId=".$objCatList->CurrentCategoryID()." ".$CategoryFilter, $OrderBy); + + $TotalItemCount += $objCatList->QueryItemCount; + +?> +GetAdminUserErrors(); + if(count($e)>0) + { + echo ""; + for($ex = 0; $ex"; + } + echo "
    ".prompt_language($e[$ex])."

    "; + } +?> + + + + + + + +
    + + + + + + + +
    + + + :  + + (QueryItemCount; ?>)  + + +
    +
     
    +
    + + +
    +
    + +
    +
    + + CurrentCategoryID(),$template); + ?> +
    +
    +
    + + TabRow(); + if(count($ItemTabs->Tabs)) + { + ?> +
    + +
    + $value) + { + $path = $pathtoroot.$value."admin/browse.php"; + if(file_exists($path)) + { + //echo "\n\n"; + include_once($path); + } + } + ?> +
    + + + + +
    +
    + + + + Index: trunk/kernel/startup.php =================================================================== diff -u -N -r563 -r642 --- trunk/kernel/startup.php (.../startup.php) (revision 563) +++ trunk/kernel/startup.php (.../startup.php) (revision 642) @@ -1,148 +1,184 @@ -Load(); /* Populate our configuration data */ -LogEntry("Done Loading Configuration\n"); -if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 ) - LogEntry("ADO Extension: ".ADODB_EXTENSION."\n"); - -require_once($pathtoroot."kernel/include/parseditem.php"); -require_once($pathtoroot."kernel/include/item.php"); -require_once($pathtoroot."kernel/include/syscache.php"); -require_once($pathtoroot."kernel/include/modlist.php"); -require_once($pathtoroot."kernel/include/searchconfig.php"); -require_once($pathtoroot."kernel/include/banrules.php"); - -$objModules = new clsModList(); -$objSystemCache = new clsSysCacheList(); -$objSystemCache->PurgeExpired(); -$objBanList = new clsBanRuleList(); - -require_once($pathtoroot."kernel/include/image.php"); - -require_once($pathtoroot."kernel/include/itemtypes.php"); -$objItemTypes = new clsItemTypeList(); - -require_once($pathtoroot."kernel/include/theme.php"); -$objThemes = new clsThemeList(); - -require_once($pathtoroot."kernel/include/language.php"); -$objLanguages = new clsLanguageList(); -$objImageList = new clsImageList(); - -/* Load session and user class definitions */ -//require_once("include/customfield.php"); -//require_once("include/custommetadata.php"); -require_once($pathtoroot."kernel/include/usersession.php"); -require_once($pathtoroot."kernel/include/favorites.php"); -require_once($pathtoroot."kernel/include/portaluser.php"); -require_once($pathtoroot."kernel/include/portalgroup.php"); - -/* create the user management class */ -$objFavorites = new clsFavoriteList(); -$objUsers = new clsUserManager(); -$objGroups = new clsGroupList(); - -require_once($pathtoroot."kernel/include/cachecount.php"); -require_once($pathtoroot."kernel/include/customfield.php"); -require_once($pathtoroot."kernel/include/custommetadata.php"); -require_once($pathtoroot."kernel/include/permissions.php"); -require_once($pathtoroot."kernel/include/relationship.php"); -require_once($pathtoroot."kernel/include/category.php"); -require_once($pathtoroot."kernel/include/statitem.php"); -/* category base class, used by all the modules at some point */ -$objPermissions = new clsPermList(); -$objPermCache = new clsPermCacheList(); - -$objCatList = new clsCatList(); -$objCustomFieldList = new clsCustomFieldList(); -$objCustomDataList = new clsCustomDataList(); -$objCountCache = new clsCacheCountList(); - -require_once($pathtoroot."kernel/include/smtp.php"); -require_once($pathtoroot."kernel/include/emailmessage.php"); -require_once($pathtoroot."kernel/include/events.php"); -LogEntry("Creating Mail Queue..\n"); -$objMessageList = new clsEmailMessageList(); -$objEmailQueue = new clsEmailQueue(); -LogEntry("Done creating Mail Queue Objects\n"); - -require_once($pathtoroot."kernel/include/searchitems.php"); -require_once($pathtoroot."kernel/include/advsearch.php"); - -require_once($pathtoroot."kernel/include/parse.php"); -require_once($pathtoroot."kernel/include/socket.php"); - -/* responsible for including module code as required - This script also creates an instance of the user session onject and - handles all session management. The global session object is created - and populated, then the global user object is created and populated - - each module's parser functions and action code is included here -*/ - -LogEntry("Startup complete\n"); -include_once("include/modules.php"); - -if( defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 && function_exists('DebugByFile') ) DebugByFile(); - -/* startup is complete, so now check the mail queue to see if there's anything that needs to be sent*/ -$objEmailQueue->SendMailQeue(); - - $ado=&GetADODBConnection(); - $rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Modules WHERE LoadOrder = 0"); - - $kernel_version = $rs->fields['Version']; - - -$adminDir = $objConfig->Get("AdminDirectory"); -if ($adminDir == '') { - $adminDir = 'admin'; -} - -if (strstr(__FILE__, $adminDir) && !GetVar('logout') && !strstr(__FILE__, "install") && !strstr(__FILE__, "index")) { - //echo "testz [".admin_login()."]
    "; - - if (!admin_login()) - { - if( !headers_sent() ) setcookie("sid"," ",time()-3600); - $objSession->Logout(); - $url_add = isset($_GET['expired']) && $_GET['expired'] ? '?expired=1' : ''; - header("Location: ".$adminURL.'/login.php'.$url_add); - die(); - //require_once($pathtoroot."admin/login.php"); - } -} - +$v) +// $a[$k]=is_array($v)?stripSlashesA($v):stripslashes($v); +// return $a; +// } +// foreach(Array( +// 'HTTP_GET_VARS','HTTP_POST_VARS','HTTP_COOKIE_VARS','HTTP_SESSION_VARS','HTTP_SERVER_VARS','$HTTP_POST_FILES', +// '_POST','_GET','_COOKIE','_SESSION','_SERVER','_FILES','_REQUEST') as $_) +// if(isset($GLOBALS[$_])) +// $GLOBALS[$_]=stripSlashesA($GLOBALS[$_]); +//} + +if(!get_magic_quotes_gpc()) +{ + function addSlashesA($a) + { + foreach($a as $k=>$v) + $a[$k]=is_array($v)?addSlashesA($v):addslashes($v); + return $a; + } + foreach(Array( + 'HTTP_GET_VARS','HTTP_POST_VARS','HTTP_COOKIE_VARS','HTTP_SESSION_VARS','HTTP_SERVER_VARS','$HTTP_POST_FILES', + '_POST','_GET','_COOKIE','_SESSION','_SERVER','_FILES','_REQUEST') as $_) + if(isset($GLOBALS[$_])) + $GLOBALS[$_]=addSlashesA($GLOBALS[$_]); +} +function inp_htmlize($var,$strip=0) +{ + if(is_array($var)) + foreach($var as $k=>$v) + $var[$k]=inp_htmlize($v,$strip); + else + $var=htmlspecialchars($strip?stripslashes($var):$var); + return $var; +} +/* + startup.php: this is the primary startup sequence for in-portal services +*/ +if( file_exists($pathtoroot.'debug.php') && !defined('DEBUG_MODE') ) include_once($pathtoroot.'debug.php'); +if( !defined('DEBUG_MODE') ) error_reporting(0); + +ini_set('memory_limit', '16M'); +ini_set('include_path', '.'); + +$kernel_version = "1.0.0"; +$FormError = array(); +$FormValues = array(); +/* include PHP version compatibility functions */ +require_once($pathtoroot."compat.php"); +/* set global variables and module lists */ +require_once($pathtoroot."globals.php"); + +LogEntry("Initalizing System..\n"); +/* for 64 bit timestamps */ +require_once($pathtoroot."kernel/include/adodb/adodb-time.inc.php"); +require_once($pathtoroot."kernel/include/dates.php"); + +/* create the global error object */ +require_once($pathtoroot."kernel/include/error.php"); +$Errors = new clsErrorManager(); + +require_once($pathtoroot."kernel/include/itemdb.php"); +require_once($pathtoroot."kernel/include/config.php"); +/* create the global configuration object */ +LogEntry("Creating Config Object..\n"); +$objConfig = new clsConfig(); +$objConfig->Load(); /* Populate our configuration data */ +LogEntry("Done Loading Configuration\n"); +if( defined('ADODB_EXTENSION') && constant('ADODB_EXTENSION') > 0 ) + LogEntry("ADO Extension: ".ADODB_EXTENSION."\n"); + +require_once($pathtoroot."kernel/include/parseditem.php"); +require_once($pathtoroot."kernel/include/item.php"); +require_once($pathtoroot."kernel/include/syscache.php"); +require_once($pathtoroot."kernel/include/modlist.php"); +require_once($pathtoroot."kernel/include/searchconfig.php"); +require_once($pathtoroot."kernel/include/banrules.php"); + +$objModules = new clsModList(); +$objSystemCache = new clsSysCacheList(); +$objSystemCache->PurgeExpired(); +$objBanList = new clsBanRuleList(); + +require_once($pathtoroot."kernel/include/image.php"); + +require_once($pathtoroot."kernel/include/itemtypes.php"); +$objItemTypes = new clsItemTypeList(); + +require_once($pathtoroot."kernel/include/theme.php"); +$objThemes = new clsThemeList(); + +require_once($pathtoroot."kernel/include/language.php"); +$objLanguages = new clsLanguageList(); +$objImageList = new clsImageList(); + +/* Load session and user class definitions */ +//require_once("include/customfield.php"); +//require_once("include/custommetadata.php"); +require_once($pathtoroot."kernel/include/usersession.php"); +require_once($pathtoroot."kernel/include/favorites.php"); +require_once($pathtoroot."kernel/include/portaluser.php"); +require_once($pathtoroot."kernel/include/portalgroup.php"); + +/* create the user management class */ +$objFavorites = new clsFavoriteList(); +$objUsers = new clsUserManager(); +$objGroups = new clsGroupList(); + +require_once($pathtoroot."kernel/include/cachecount.php"); +require_once($pathtoroot."kernel/include/customfield.php"); +require_once($pathtoroot."kernel/include/custommetadata.php"); +require_once($pathtoroot."kernel/include/permissions.php"); +require_once($pathtoroot."kernel/include/relationship.php"); +require_once($pathtoroot."kernel/include/category.php"); +require_once($pathtoroot."kernel/include/statitem.php"); +/* category base class, used by all the modules at some point */ +$objPermissions = new clsPermList(); +$objPermCache = new clsPermCacheList(); + +$objCatList = new clsCatList(); +$objCustomFieldList = new clsCustomFieldList(); +$objCustomDataList = new clsCustomDataList(); +$objCountCache = new clsCacheCountList(); + +require_once($pathtoroot."kernel/include/smtp.php"); +require_once($pathtoroot."kernel/include/emailmessage.php"); +require_once($pathtoroot."kernel/include/events.php"); +LogEntry("Creating Mail Queue..\n"); +$objMessageList = new clsEmailMessageList(); +$objEmailQueue = new clsEmailQueue(); +LogEntry("Done creating Mail Queue Objects\n"); + +require_once($pathtoroot."kernel/include/searchitems.php"); +require_once($pathtoroot."kernel/include/advsearch.php"); + +require_once($pathtoroot."kernel/include/parse.php"); +require_once($pathtoroot."kernel/include/socket.php"); + +/* responsible for including module code as required + This script also creates an instance of the user session onject and + handles all session management. The global session object is created + and populated, then the global user object is created and populated + + each module's parser functions and action code is included here +*/ + +LogEntry("Startup complete\n"); +include_once("include/modules.php"); + +if( defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 && function_exists('DebugByFile') ) DebugByFile(); + +/* startup is complete, so now check the mail queue to see if there's anything that needs to be sent*/ +$objEmailQueue->SendMailQeue(); + + $ado=&GetADODBConnection(); + $rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Modules WHERE LoadOrder = 0"); + + $kernel_version = $rs->fields['Version']; + + +$adminDir = $objConfig->Get("AdminDirectory"); +if ($adminDir == '') { + $adminDir = 'admin'; +} + +if (strstr(__FILE__, $adminDir) && !GetVar('logout') && !strstr(__FILE__, "install") && !strstr(__FILE__, "index")) { + //echo "testz [".admin_login()."]
    "; + + if (!admin_login()) + { + if( !headers_sent() ) setcookie("sid"," ",time()-3600); + $objSession->Logout(); + $url_add = isset($_GET['expired']) && $_GET['expired'] ? '?expired=1' : ''; + header("Location: ".$adminURL.'/login.php'.$url_add); + die(); + //require_once($pathtoroot."admin/login.php"); + } +} + ?> \ No newline at end of file Index: trunk/admin/include/mainscript.php =================================================================== diff -u -N -r326 -r642 --- trunk/admin/include/mainscript.php (.../mainscript.php) (revision 326) +++ trunk/admin/include/mainscript.php (.../mainscript.php) (revision 642) @@ -53,6 +53,7 @@ else $Cal = str_replace("Y","y",$Cal); + $Cal = str_replace("m","mm",$Cal); $Cal = str_replace("n","m",$Cal); $Cal = str_replace("d","dd",$Cal); Index: trunk/admin/config/module_email.php =================================================================== diff -u -N -r374 -r642 --- trunk/admin/config/module_email.php (.../module_email.php) (revision 374) +++ trunk/admin/config/module_email.php (.../module_email.php) (revision 642) @@ -1,376 +1,377 @@ -Logout(); - header("Location: ".$adminURL."/login.php"); - die(); - //require_once($pathtoroot."admin/login.php"); -} - -//admin only util -$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path"); -$admin = $objConfig->Get("AdminDirectory"); -if(!strlen($admin)) - $admin = "admin"; - -$localURL=$rootURL."kernel/"; -$adminURL = $rootURL.$admin; -$imagesURL = $adminURL."/images"; - -require_once ($pathtoroot.$admin."/include/elements.php"); -require_once ($pathtoroot."kernel/admin/include/navmenu.php"); -require_once($pathtoroot.$admin."/toolbar.php"); -require_once($pathtoroot.$admin."/listview/listview.php"); - -$m = GetModuleArray(); -foreach($m as $key=>$value) -{ - $path = $pathtoroot. $value."admin/include/parser.php"; - if(file_exists($path)) - { - include_once($path); - } -} - -unset($objEditItems); - -//$objEditItems = new clsPhraseList(); -//$objEditItems->SourceTable = $objSession->GetEditTable("Language"); - -/* -------------------------------------- Section configuration ------------------------------------------- */ -$section = $_GET["section"]; -$sec = $objSections->GetSection($section); - -$module = $_GET["module"]; -$envar = "env=" . BuildEnv()."&module=$module§ion=$section"; - -//$title = prompt_language("la_Text_Configuration")." - '".$module."' - ".prompt_language("la_tab_EmailEvents"); - -$SortFieldVar = "Event_LV_SortField"; -$SortOrderVar = "Event_LV_SortOrder"; -$DefaultSortField = "Description"; -$PerPageVar = "Perpage_Event"; -$CurrentPageVar = "Page_Event"; -$CurrentFilterVar = "EmailEvent_View"; - -$ListForm = "language"; -$CheckClass = "EmailChecks"; - - -//echo $envar."
    \n"; -/* ------------------------------------- Configure the toolbar ------------------------------------------- */ -$objListToolBar = new clsToolBar(); -$objListToolBar->Set("section",$section); -$objListToolBar->Set("load_menu_func",""); -$objListToolBar->Set("CheckClass","EmailChecks"); -$objListToolBar->Set("CheckClass",$CheckClass); -$objListToolBar->Set("CheckForm",$ListForm); - -$listImages = array(); - -/* -$objListToolBar->Add("email_edit", "la_ToolTip_Edit","#","if (EmailChecks.itemChecked()) swap('email_edit','toolbar/tool_edit_f2.gif');", - "if (EmailChecks.itemChecked()) swap('email_edit', 'toolbar/tool_edit.gif');", - "EmailChecks.check_submit('email_edit', '');", - "tool_edit.gif"); -$listImages[] = "EmailChecks.addImage('email_edit','$imagesURL/toolbar/tool_edit.gif','$imagesURL/toolbar/tool_edit_f3.gif',1); "; -*/ - -$EditVar = "env=".BuildEnv(); - -$objListToolBar->Add("email_user", "la_ToolTip_Email_UserSelect","#","if (EmailChecks.itemChecked()) swap('email_user','toolbar/tool_usertogroup_f2.gif');", - "if (EmailChecks.itemChecked()) swap('email_user', 'toolbar/tool_usertogroup.gif');", - "OpenUserSelector('EventId',$CheckClass,'".$EditVar."&Selector=radio&destform=userpopup&destfield=FromUserId&IdField=PortalUserId&dosubmit=1');", - "tool_usertogroup.gif",TRUE,TRUE); - -$listImages[] = "EmailChecks.addImage('email_user','$imagesURL/toolbar/tool_usertogroup.gif','$imagesURL/toolbar/tool_usertogroup_f3.gif',1); "; - -$objListToolBar->Add("email_enable", "la_ToolTip_Email_Enable","#","if (EmailChecks.itemChecked()) swap('email_enable','toolbar/tool_approve_f2.gif');", - "if (EmailChecks.itemChecked()) swap('email_enable', 'toolbar/tool_approve.gif');", - "EmailChecks.check_submit('module_email', 'm_emailevent_enable');", - "tool_approve.gif",FALSE,TRUE); - -$listImages[] = "EmailChecks.addImage('email_enable','$imagesURL/toolbar/tool_approve.gif','$imagesURL/toolbar/tool_approve_f3.gif',1); "; - -$objListToolBar->Add("email_disable", "la_ToolTip_Email_Disable","#","if (EmailChecks.itemChecked()) swap('email_disable','toolbar/tool_deny_f2.gif');", - "if (EmailChecks.itemChecked()) swap('email_disable', 'toolbar/tool_deny.gif');", - "EmailChecks.check_submit('module_email', 'm_emailevent_disable');", - "tool_deny.gif",FALSE,TRUE); - -$listImages[] = "EmailChecks.addImage('email_disable','$imagesURL/toolbar/tool_deny.gif','$imagesURL/toolbar/tool_deny_f3.gif',1); "; - -$objListToolBar->Add("email_front", "la_ToolTip_Email_FrontOnly","#","if (EmailChecks.itemChecked()) swap('email_front','toolbar/tool_frontend_mail_f2.gif');", - "if (EmailChecks.itemChecked()) swap('email_front', 'toolbar/tool_frontend_mail.gif');", - "EmailChecks.check_submit('module_email', 'm_emailevent_frontonly');", - "tool_frontend_mail.gif",FALSE,TRUE); - -$listImages[] = "EmailChecks.addImage('email_front','$imagesURL/toolbar/tool_frontend_mail.gif','$imagesURL/toolbar/tool_frontend_mail_f3.gif',1); "; - - -$objListToolBar->Add("divider"); - -$objListToolBar->Add("viewmenubutton", "la_ToolTip_View","#","swap('viewmenubutton','toolbar/tool_view_f2.gif'); ", - "swap('viewmenubutton', 'toolbar/tool_view.gif');", - "ShowViewMenu();","tool_view.gif"); - - -$objListToolBar->AddToInitScript($listImages); -$objListToolBar->AddToInitScript("fwLoadMenus();"); - -$objEvents = new clsEventList(); -//$objEvents->SourceTable = $objSession->GetEditTable("Events"); - -$order = trim($objConfig->Get("Event_LV_SortField")." ".$objConfig->Get("Event_LV_SortOrder")); - -$SearchWords = $objSession->GetVariable("EmailEventSearchWord"); -$where = "(Module='$module')"; -if(strlen($SearchWords)) - $where .= ' AND '.$objEvents->AdminSearchWhereClause($SearchWords); - -/* ----------------------------------------- Set the View Filter ---------------------------------------- */ -$ViewNormal=1; -$Bit_Disabled=2; -$Bit_Enabled=1; -$Bit_FrontOnly=4; -$Bit_All = 7; -$FilterLabels[0] = admin_language("la_Text_Enabled"); -$FilterLabels[1] = admin_language("la_Text_Disabled"); -$FilterLabels[2] = admin_language("la_Text_FrontOnly"); - -/* determine current view menu settings */ -$MsgView = $objConfig->Get("EmailEvent_View"); - -$ViewNormal=0; - -if(!is_numeric($MsgView)) -{ - $MsgView = $Bit_All; //Set all bits ON - $MsgFilter = ""; -} -unset($Status); -$Status = array(); - -if($MsgView & $Bit_Disabled) - $Status[] = 0; - -if($MsgView & $Bit_Enabled) - $Status[] = 1; - -if($MsgView & $Bit_FrontOnly) - $Status[] = 2; - -if(count($Status)>0) -{ - $MsgFilter = "Enabled IN (".implode(",",$Status).")"; -} -else - $MsgFilter = "Enabled = -1"; - -$UserTable = GetTablePrefix()."PortalUser"; -$EventTable = GetTablePrefix()."Events"; -$MessageTable = GetTablePrefix()."EmailMessage"; - -$sql = "SELECT e.Description as Description, e.Module as Module, e.EventId as EventId, "; -$sql .="ELT(e.Enabled+1,'".admin_language("la_Text_Disabled")." ','".admin_language("la_Text_Enabled")."','".admin_language("la_Text_FrontOnly")." ') as EmailStatus, "; -$sql .="ELT(e.Type+1,'".admin_language("la_Text_User")." ','".admin_language("la_Text_Admin")." ') as EventType, "; -$sql .="u.Login as FromUser FROM $EventTable as e LEFT JOIN $UserTable as u ON (e.FromUserId=u.PortalUserId) WHERE $where "; -if(strlen($MsgFilter)) - $sql .= "AND $MsgFilter "; - -if(strlen(trim($objConfig->Get($SortFieldVar)))) -{ - $order = " ORDER BY ".$objConfig->Get($SortFieldVar)." ".$objConfig->Get($SortOrderVar); -} -else - $order = ""; - -if($objConfig->Get($CurrentPageVar)>0) -{ - $objEvents->Page = $objConfig->Get($CurrentPageVar); -} - -if($objConfig->Get($PerPageVar)>0) -{ - $objListView->PerPage = $objConfig->Get($PerPageVar); -} - -$sql .= $order." "; - -if($objSession->HasSystemPermission("DEBUG.LIST")) - echo htmlentities($sql,ENT_NOQUOTES)."
    \n"; - -$objListView = new clsListView($objListToolBar); -$objListView->CurrentPageVar = $CurrentPageVar; -$objListView->PerPageVar = $PerPageVar; - -$objEvents->Query_Item($sql, $objListView->GetLimitSQL() ); -$itemcount = TableCount($objEvents->SourceTable, $where, 0); - -$objListView->SetListItems($objEvents); -$objListView->IdField = "EventId"; - -$order = $objConfig->Get($PerPageVar); - -$objListView->ColumnHeaders->Add("Description",admin_language("la_prompt_Description"),1,0,$order,"width=\"50%\"",$SortFieldVar,$SortOrderVar,"Description"); -//$objListView->ColumnHeaders->Add("Module",admin_language("la_prompt_Module"),1,0,$order,"width=\"10%\"","Email_LV_SortField","Email_LV_SortOrder","Module"); -$objListView->ColumnHeaders->Add("EventType",admin_language("la_prompt_Type"),1,0,$order,"width=\"10%\"",$SortFieldVar,$SortOrderVar,"EventType"); -$objListView->ColumnHeaders->Add("EmailStatus",admin_language("la_prompt_Status"),1,0,$order,"width=\"10%\"",$SortFieldVar,$SortOrderVar,"EmailStatus"); -$objListView->ColumnHeaders->Add("FromUser",admin_language("la_prompt_FromUser"),1,0,$order,"width=\"15%\"",$SortFieldVar,$SortOrderVar,"FromUser"); - -$objListView->ColumnHeaders->SetSort($objConfig->Get($SortFieldVar), $objConfig->Get($SortOrderVar)); - -$objListView->PrintToolBar = FALSE; -$objListView->checkboxes = TRUE; -$objListView->CheckboxName = "itemlist[]"; -$objListView->SearchBar = TRUE; -$objListView->SearchKeywords = $SearchWords; -$objListView->SearchAction="m_emailevent_search"; - -$objListView->TotalItemCount = $itemcount; - -$objListView->ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSortField, - $CurrentFilterVar,$MsgView,$Bit_All); - -foreach($FilterLabels as $Bit=>$Label) -{ - $objListView->AddViewMenuFilter($Label,$Bit); -} - -for($i=0;$iItems);$i++) -{ - $e =& $objEvents->GetItemRefByIndex($i); - $e->Set("Description",prompt_language($e->Get("Description"))); -} - -$h = "\n\n\n"; -int_header($objListToolBar,NULL, $title,NULL,$h); -?> -
    " method=POST> - - -PrintList(); -?> - - - - - - > - - - -
    -
    - - -
    " name="viewmenu"> - - - - -
    -
    "> - - -
    - -
    " ID="popup"> - - - - - - - -
    - -
    " ID="userpopup"> - - - -
    - - - - +Logout(); + header("Location: ".$adminURL."/login.php"); + die(); + //require_once($pathtoroot."admin/login.php"); +} + +//admin only util +$rootURL="http://".ThisDomain().$objConfig->Get("Site_Path"); +$admin = $objConfig->Get("AdminDirectory"); +if(!strlen($admin)) + $admin = "admin"; + +$localURL=$rootURL."kernel/"; +$adminURL = $rootURL.$admin; +$imagesURL = $adminURL."/images"; + +require_once ($pathtoroot.$admin."/include/elements.php"); +require_once ($pathtoroot."kernel/admin/include/navmenu.php"); +require_once($pathtoroot.$admin."/toolbar.php"); +require_once($pathtoroot.$admin."/listview/listview.php"); + +$m = GetModuleArray(); +foreach($m as $key=>$value) +{ + $path = $pathtoroot. $value."admin/include/parser.php"; + if(file_exists($path)) + { + include_once($path); + } +} + +unset($objEditItems); + +//$objEditItems = new clsPhraseList(); +//$objEditItems->SourceTable = $objSession->GetEditTable("Language"); + +/* -------------------------------------- Section configuration ------------------------------------------- */ +$section = $_GET["section"]; +$sec = $objSections->GetSection($section); + +$module = $_GET["module"]; +$envar = "env=" . BuildEnv()."&module=$module§ion=$section"; + +//$title = prompt_language("la_Text_Configuration")." - '".$module."' - ".prompt_language("la_tab_EmailEvents"); + +$SortFieldVar = "Event_LV_SortField"; +$SortOrderVar = "Event_LV_SortOrder"; +$DefaultSortField = "Description"; +$PerPageVar = "Perpage_Event"; +$CurrentPageVar = "Page_Event"; +$CurrentFilterVar = "EmailEvent_View"; + +$ListForm = "language"; +$CheckClass = "EmailChecks"; + + +//echo $envar."
    \n"; +/* ------------------------------------- Configure the toolbar ------------------------------------------- */ +$objListToolBar = new clsToolBar(); +$objListToolBar->Set("section",$section); +$objListToolBar->Set("load_menu_func",""); +$objListToolBar->Set("CheckClass","EmailChecks"); +$objListToolBar->Set("CheckClass",$CheckClass); +$objListToolBar->Set("CheckForm",$ListForm); + +$listImages = array(); + +/* +$objListToolBar->Add("email_edit", "la_ToolTip_Edit","#","if (EmailChecks.itemChecked()) swap('email_edit','toolbar/tool_edit_f2.gif');", + "if (EmailChecks.itemChecked()) swap('email_edit', 'toolbar/tool_edit.gif');", + "EmailChecks.check_submit('email_edit', '');", + "tool_edit.gif"); +$listImages[] = "EmailChecks.addImage('email_edit','$imagesURL/toolbar/tool_edit.gif','$imagesURL/toolbar/tool_edit_f3.gif',1); "; +*/ + +$EditVar = "env=".BuildEnv(); + +$objListToolBar->Add("email_user", "la_ToolTip_Email_UserSelect","#","if (EmailChecks.itemChecked()) swap('email_user','toolbar/tool_usertogroup_f2.gif');", + "if (EmailChecks.itemChecked()) swap('email_user', 'toolbar/tool_usertogroup.gif');", + "OpenUserSelector('EventId',$CheckClass,'".$EditVar."&Selector=radio&destform=userpopup&destfield=FromUserId&IdField=PortalUserId&dosubmit=1');", + "tool_usertogroup.gif",TRUE,TRUE); + +$listImages[] = "EmailChecks.addImage('email_user','$imagesURL/toolbar/tool_usertogroup.gif','$imagesURL/toolbar/tool_usertogroup_f3.gif',1); "; + +$objListToolBar->Add("email_enable", "la_ToolTip_Email_Enable","#","if (EmailChecks.itemChecked()) swap('email_enable','toolbar/tool_approve_f2.gif');", + "if (EmailChecks.itemChecked()) swap('email_enable', 'toolbar/tool_approve.gif');", + "EmailChecks.check_submit('module_email', 'm_emailevent_enable');", + "tool_approve.gif",FALSE,TRUE); + +$listImages[] = "EmailChecks.addImage('email_enable','$imagesURL/toolbar/tool_approve.gif','$imagesURL/toolbar/tool_approve_f3.gif',1); "; + +$objListToolBar->Add("email_disable", "la_ToolTip_Email_Disable","#","if (EmailChecks.itemChecked()) swap('email_disable','toolbar/tool_deny_f2.gif');", + "if (EmailChecks.itemChecked()) swap('email_disable', 'toolbar/tool_deny.gif');", + "EmailChecks.check_submit('module_email', 'm_emailevent_disable');", + "tool_deny.gif",FALSE,TRUE); + +$listImages[] = "EmailChecks.addImage('email_disable','$imagesURL/toolbar/tool_deny.gif','$imagesURL/toolbar/tool_deny_f3.gif',1); "; + +$objListToolBar->Add("email_front", "la_ToolTip_Email_FrontOnly","#","if (EmailChecks.itemChecked()) swap('email_front','toolbar/tool_frontend_mail_f2.gif');", + "if (EmailChecks.itemChecked()) swap('email_front', 'toolbar/tool_frontend_mail.gif');", + "EmailChecks.check_submit('module_email', 'm_emailevent_frontonly');", + "tool_frontend_mail.gif",FALSE,TRUE); + +$listImages[] = "EmailChecks.addImage('email_front','$imagesURL/toolbar/tool_frontend_mail.gif','$imagesURL/toolbar/tool_frontend_mail_f3.gif',1); "; + + +$objListToolBar->Add("divider"); + +$objListToolBar->Add("viewmenubutton", "la_ToolTip_View","#","swap('viewmenubutton','toolbar/tool_view_f2.gif'); ", + "swap('viewmenubutton', 'toolbar/tool_view.gif');", + "ShowViewMenu();","tool_view.gif"); + + +$objListToolBar->AddToInitScript($listImages); +$objListToolBar->AddToInitScript("fwLoadMenus();"); + +$objEvents = new clsEventList(); +//$objEvents->SourceTable = $objSession->GetEditTable("Events"); + +$order = trim($objConfig->Get("Event_LV_SortField")." ".$objConfig->Get("Event_LV_SortOrder")); + +$SearchWords = $objSession->GetVariable("EmailEventSearchWord"); +$where = "(Module='$module')"; +if(strlen($SearchWords)) + $where .= ' AND '.$objEvents->AdminSearchWhereClause($SearchWords); + +/* ----------------------------------------- Set the View Filter ---------------------------------------- */ +$ViewNormal=1; +$Bit_Disabled=2; +$Bit_Enabled=1; +$Bit_FrontOnly=4; +$Bit_All = 7; +$FilterLabels[0] = admin_language("la_Text_Enabled"); +$FilterLabels[1] = admin_language("la_Text_Disabled"); +$FilterLabels[2] = admin_language("la_Text_FrontOnly"); + +/* determine current view menu settings */ +$MsgView = $objConfig->Get("EmailEvent_View"); + +$ViewNormal=0; + +if(!is_numeric($MsgView)) +{ + $MsgView = $Bit_All; //Set all bits ON + $MsgFilter = ""; +} +unset($Status); +$Status = array(); + +if($MsgView & $Bit_Disabled) + $Status[] = 0; + +if($MsgView & $Bit_Enabled) + $Status[] = 1; + +if($MsgView & $Bit_FrontOnly) + $Status[] = 2; + +if(count($Status)>0) +{ + $MsgFilter = "Enabled IN (".implode(",",$Status).")"; +} +else + $MsgFilter = "Enabled = -1"; + +$UserTable = GetTablePrefix()."PortalUser"; +$EventTable = GetTablePrefix()."Events"; +$MessageTable = GetTablePrefix()."EmailMessage"; + +$sql = "SELECT e.Description as Description, e.Module as Module, e.EventId as EventId, "; +$sql .="ELT(e.Enabled+1,'".admin_language("la_Text_Disabled")." ','".admin_language("la_Text_Enabled")."','".admin_language("la_Text_FrontOnly")." ') as EmailStatus, "; +$sql .="ELT(e.Type+1,'".admin_language("la_Text_User")." ','".admin_language("la_Text_Admin")." ') as EventType, "; +$sql .="u.Login as FromUser FROM $EventTable as e LEFT JOIN $UserTable as u ON (e.FromUserId=u.PortalUserId) WHERE $where "; +if(strlen($MsgFilter)) + $sql .= "AND $MsgFilter "; + +if(strlen(trim($objConfig->Get($SortFieldVar)))) +{ + $order = " ORDER BY ".$objConfig->Get($SortFieldVar)." ".$objConfig->Get($SortOrderVar); +} +else + $order = ""; + +if($objConfig->Get($CurrentPageVar)>0) +{ + $objEvents->Page = $objConfig->Get($CurrentPageVar); +} + +if($objConfig->Get($PerPageVar)>0) +{ + $objListView->PerPage = $objConfig->Get($PerPageVar); +} + +$sql .= $order." "; + +if($objSession->HasSystemPermission("DEBUG.LIST")) + echo htmlentities($sql,ENT_NOQUOTES)."
    \n"; + +$objListView = new clsListView($objListToolBar); +$objListView->CurrentPageVar = $CurrentPageVar; +$objListView->PerPageVar = $PerPageVar; + +$objEvents->Query_Item($sql, $objListView->GetLimitSQL() ); +//$itemcount = TableCount($objEvents->SourceTable, $where, 0); +$itemcount = QueryCount($sql); + +$objListView->SetListItems($objEvents); +$objListView->IdField = "EventId"; + +$order = $objConfig->Get($PerPageVar); + +$objListView->ColumnHeaders->Add("Description",admin_language("la_prompt_Description"),1,0,$order,"width=\"50%\"",$SortFieldVar,$SortOrderVar,"Description"); +//$objListView->ColumnHeaders->Add("Module",admin_language("la_prompt_Module"),1,0,$order,"width=\"10%\"","Email_LV_SortField","Email_LV_SortOrder","Module"); +$objListView->ColumnHeaders->Add("EventType",admin_language("la_prompt_Type"),1,0,$order,"width=\"10%\"",$SortFieldVar,$SortOrderVar,"EventType"); +$objListView->ColumnHeaders->Add("EmailStatus",admin_language("la_prompt_Status"),1,0,$order,"width=\"10%\"",$SortFieldVar,$SortOrderVar,"EmailStatus"); +$objListView->ColumnHeaders->Add("FromUser",admin_language("la_prompt_FromUser"),1,0,$order,"width=\"15%\"",$SortFieldVar,$SortOrderVar,"FromUser"); + +$objListView->ColumnHeaders->SetSort($objConfig->Get($SortFieldVar), $objConfig->Get($SortOrderVar)); + +$objListView->PrintToolBar = FALSE; +$objListView->checkboxes = TRUE; +$objListView->CheckboxName = "itemlist[]"; +$objListView->SearchBar = TRUE; +$objListView->SearchKeywords = $SearchWords; +$objListView->SearchAction="m_emailevent_search"; + +$objListView->TotalItemCount = $itemcount; + +$objListView->ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSortField, + $CurrentFilterVar,$MsgView,$Bit_All); + +foreach($FilterLabels as $Bit=>$Label) +{ + $objListView->AddViewMenuFilter($Label,$Bit); +} + +for($i=0;$iItems);$i++) +{ + $e =& $objEvents->GetItemRefByIndex($i); + $e->Set("Description",prompt_language($e->Get("Description"))); +} + +$h = "\n\n\n"; +int_header($objListToolBar,NULL, $title,NULL,$h); +?> +
    " method=POST> + + +PrintList(); +?> + + + + + + > + + + +
    +
    + + +
    " name="viewmenu"> + + + + +
    +
    "> + + +
    + +
    " ID="popup"> + + + + + + + +
    + +
    " ID="userpopup"> + + + +
    + + + + Index: trunk/kernel/frontaction.php =================================================================== diff -u -N -r579 -r642 --- trunk/kernel/frontaction.php (.../frontaction.php) (revision 579) +++ trunk/kernel/frontaction.php (.../frontaction.php) (revision 642) @@ -1,864 +1,867 @@ -Front, Kernel Action ['.$Action."]
    \n"; -} - -if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & FRONT_SHOW_REQUEST) == FRONT_SHOW_REQUEST ) -{ - // don't show debug output in tree & header of admin & while logging in - $script = basename($_SERVER['PHP_SELF']); - - echo '
    '; - echo "
    ScriptName: $script (".dirname($_SERVER['PHP_SELF']).")

    "; - $div_height = (count($_REQUEST)+1)*26; - if($div_height > 300) $div_height = 300; - echo '
    '; - echo ''; - echo ''; - - foreach($_REQUEST as $key => $value) - { - if( !is_array($value) && trim($value) == '' ) $value = ' '; - $src = isset($_GET[$key]) ? 'GE' : (isset($_POST[$key]) ? 'PO' : (isset($_COOKIE[$key]) ? 'CO' : '?') ); - echo ''; - } - echo '
    SrcNameValue
    '.$src.''.$key.''.print_r($value, true).'
    '; - echo '
    '; - unset($script); -// echo "SID: ".$objSession->GetSessionKey().'
    '; -} - -switch($Action) -{ - case "m_login": - // if($objSession->ValidSession()) $objSession->Logout(); - //echo $objSession->GetSessionKey()."
    \n"; - if ($objConfig->Get("CookieSessions") == 1 && $_COOKIE["CookiesTest"] != "1") { - $FormError["login"]["login_user"] = language("lu_cookies_error"); - } - else - { - $MissingCount = SetMissingDataErrors("login"); - if($MissingCount==2) - { - $FormError["login"]["login_user"]= language("lu_ferror_loginboth"); - unset($FormError["login"]["login_password"]); - } - - if($MissingCount==0) - { - if($_POST["login_user"]=="root") - { - $FormError["login"]["login_user"]= language("lu_access_denied"); - } - else - { - $LoginCheck = $objSession->Login( $_POST["login_user"], md5($_POST["login_password"]) ); - if($LoginCheck === true) - { - if( !headers_sent() && GetVar('usercookie') == 1 ) - { - $c = $_POST["login_user"]."|"; - $pw = $_POST["login_password"]; - if(strlen($pw) < 31) $pw = md5($pw); - $c .= $pw; - setcookie("login",$c,time()+2592000); - } - - // set new destination template if passed - $dest = GetVar('dest', true); - if(!$dest) $dest = GetVar('DestTemplate', true); - if($dest) $var_list['t'] = $dest; - } - else - { - switch($LoginCheck) - { - case -1: // user or/and pass wrong - $FormError["login"]["login_password"] = language("lu_incorrect_login"); - break; - - case -2: // user ok, but has no permission - $FormError["login"]["login_password"] = language("la_text_nopermissions"); - break; - } - } - } - } - } - break; - - case "m_forgotpw": - $MissingCount = SetMissingDataErrors("forgotpw"); - if($MissingCount==0) - { - $username = $_POST["username"]; - $email = $_POST["email"]; - $found = FALSE; - if(strlen($username)) - { - $u = $objUsers->GetItemByField("Login",$username); - if(is_object($u)) - $found = ($u->Get("Login")==$username && $u->Get("Status")==1) && strlen($u->Get("Password")); - } - else if(strlen($email)) - { - $u = $objUsers->GetItemByField("Email",$email); - if(is_object($u)) - $found = ($u->Get("Email")==$email && $u->Get("Status")==1) && strlen($u->Get("Password")); - } - if($found) - { - $newpw = makepassword(); - $objSession->Set('password', $newpw); - $u->Set("Password",$newpw); - $u->Update(); - $u->SendUserEventMail("USER.PSWD",$u->Get("PortalUserId")); - $u->SendAdminEventMail("USER.PSWD"); - $u->Set("Password",md5($newpw)); - $u->Update(); - $u->Clean(); - } - else - { - if(!strlen($username) && !strlen($email)) - { - $FormError["forgotpw"]["username"] = language("lu_ferror_forgotpw_nodata"); - $MissingCount++; - } - else - { - if(strlen($username)) - $FormError["forgotpw"]["username"] = language("lu_ferror_unknown_username"); - if(strlen($email)) - $FormError["forgotpw"]["email"] = language("lu_ferror_unknown_email"); - $MissingCount++; - } - if(strlen($_GET["error"])) - $var_list["t"] = $_GET["error"]; - } - } - else - if(strlen($_GET["error"])) - $var_list["t"] = $_GET["error"]; - break; - case "m_subscribe_confirm": - $t = ""; - $SubscribeAddress = $_POST["subscribe_email"]; - if(!ValidEmail($SubscribeAddress)&& strlen($SubscribeAddress)) - { - $t = $_GET["Error"]; - $SubscribeError = "lu_invalid_emailaddress"; - } - else - { - if((int)$objConfig->Get("User_SubscriberGroup")>0) - { - $g = $objGroups->GetItem($objConfig->Get("User_SubscriberGroup")); - if(is_object($g)) - { - $email = $_POST["subscribe_email"]; - if(strlen($email)>0) - { - $u = $objUsers->GetItemByField("Email",$email); - - if(is_object($u)) - { - if($u->CheckBanned()) - { - $t = $_GET["Error"]; - $SubscribeError ="lu_subscribe_banned"; - } - else - { - if($u->IsInGroup($g->Get("GroupId"))) - { - $t = $_GET["Unsubscribe"]; - } - else - $t = $_GET["Subscribe"]; - } - } - else - $t = $_GET["Subscribe"]; - } - else - { - $t = $_GET["Error"]; - $SubscribeError ="lu_subscribe_no_address"; - } - } - else - { - $t = $_GET["Error"]; - $SubscribeError ="lu_subscribe_unknown_error"; - } - } - } - if(strlen($t)) - { - $var_list["t"] = $t; - $var_list_update["t"] = $t; - } - break; - case "m_subscribe": - //phpinfo(INFO_VARIABLES); - if($_POST["buttons"][0]==language("lu_button_yes")) - { - $SubscribeAddress = $_POST["subscribe_email"]; - if(strlen($SubscribeAddress)>0) - { - if(ValidEmail($SubscribeAddress)) - { - $GroupId = (int)$objConfig->Get("User_SubscriberGroup"); - if ($GroupId) - { - $g = $objGroups->GetItem($GroupId); - $u = $objUsers->GetItemByField("Email",$SubscribeAddress); - if(is_object($u)) - { - if(strtolower($u->Get("Email"))==strtolower($SubscribeAddress)) - { - $bExists = TRUE; - } - else - $bExists = FALSE; - } - if($bExists) - { - $g->AddUser($u->Get("PortalUserId")); - } - else - { - $u = new clsPortalUser(NULL); - $u->Set("Email",$SubscribeAddress); - $u->Set("ip",$_SERVER['REMOTE_ADDR']); - $u->Set("CreatedOn",date("U")); - $u->Set("Status",1); - if(!$u->CheckBanned()) - { - $u->Create(); - $g->AddUser($u->Get("PortalUserId"),1); - } - else - $SubscribeResult = "lu_subscribe_banned"; - } - $SubscribeResult = "lu_subscribe_success"; - $u->SendUserEventMail("USER.SUBSCRIBE",$u->Get("PortalUserId")); - $u->SendAdminEventMail("USER.SUBSCRIBE"); - if(strlen($_GET["Subscribe"])>0) - $var_list["t"] = $_GET["Subscribe"]; - } - } - else - { - $SubscribeResult = "lu_invalid_emailaddress"; - } - } - else - $SubscribeResult = "lu_subscribe_missing_address"; - } - - if(!strlen($SubscribeResult)) - $SubscribeResult = "lu_subscribe_success"; - break; - case "m_unsubscribe": - - if($_POST["buttons"][0]==language("lu_button_yes")) - { - $MissingCount = SetMissingDataErrors("m_unsubscribe"); - - if($MissingCount==0) - { - $email = $_POST["subscribe_email"]; - $u = $objUsers->GetItemByField("Email",$email); - if(is_object($u)) - { - if(strtolower($u->Get("Email"))==strtolower($email)) - { - $GroupId = (int)$objConfig->Get("User_SubscriberGroup"); - if($u->PrimaryGroup()==$GroupId) - { - $u_gorup_list = $u->GetGroupList(); - - if (count($u_gorup_list) > 1) { - $u->RemoveFromGroup($GroupId); - } - else { - $u->RemoveFromAllGroups(); - $u->Delete(); - } - } - else - { - $u->RemoveFromGroup($GroupId); - } - } - } - if(strlen($_GET["Subscribe"])>0) - $var_list["t"] = $_GET["Subscribe"]; - } - } - - break; - case "m_logout": -// $objSession->Logout(); - //unset($objSession); - //$objSession = new clsUserSession(); -// $var_list_update["t"] = "index"; -// setcookie("login","",time()-3600); - break; - case "m_register": - $MissingCount = SetMissingDataErrors("m_register"); - - if(!$objConfig->Get("User_Password_Auto")) - { - if(($_POST["password"] != $_POST["passwordverify"]) || !strlen($_POST["passwordverify"])) - { - $MissingCount++; - $FormError["m_register"]["passwordverify"] = language("lu_ferror_pswd_mismatch"); - } - - if(strlen($_POST["password"])>30) - { - // echo "VAR: ".$_POST["password"]; die(); - $MissingCount++; - $FormError["m_register"]["password"] = language("lu_ferror_pswd_toolong"); - } - - if (strlen($_POST['password']) < $objConfig->Get("Min_Password")) - { - $MissingCount++; - $FormError["m_register"]["password"] = language("lu_ferror_pswd_tooshort"); - } - } - - $u = $objUsers->GetItemByField("Login",$_POST["username"]); - - if(is_object($u)) - { - if($u->Get("Login")==$_POST["username"]) - { - $MissingCount++; - $FormError["m_register"]["username"] = language("lu_user_exists"); - } - } - - if (strlen($_POST['username']) < $objConfig->Get("Min_UserName")) - { - $MissingCount++; - $FormError["m_register"]["username"] = language("lu_ferror_username_tooshort"); - } - - if(!$MissingCount) - { - $CreatedOn = adodb_date("U"); - $GroupId = $objConfig->Get("User_NewGroup"); - $Status=0; - - /* determine the status of new users */ - switch ($objConfig->Get("User_Allow_New")) - { - case "1": - $Status=1; - break; - case "3": - $Status=2; - break; - } - - /* set Destination template */ - $var_list["t"] = strlen($_GET["dest"])? $_GET["dest"] : "index"; - - if($Status>0) - { - if($objConfig->Get("User_Password_Auto")) - { - $password = makepassword(); - $objSession->Set("password", $password); - } - else - $password = $_POST["password"]; - - $_POST["dob"] = $_POST["dob_month"]."/".$_POST["dob_day"]."/".$_POST["dob_year"]; - $dob = DateTimestamp($_POST["dob"],GetDateFormat()); - $ip = $_SERVER['REMOTE_ADDR']; - - $u = &$objUsers->Add_User($_POST["username"], md5($password), $_POST["email"], $CreatedOn, inp_escape($_POST["firstname"]), inp_escape($_POST["lastname"]), $Status, $_POST["phone"], $_POST["street"], $_POST["city"], $_POST["state"], $_POST["zip"], $_POST["country"], $dob, $ip, TRUE); - - if(!is_object($u)) - { - $RuleId=$u; - $r = $objBanList->GetItem($RuleId); - $err = $r->Get("ErrorTag"); - - if(strlen($err)) - { - $FormError["m_register"][$r->Get("ItemField")] = language($err); - $MissingCount++; - } - } - else - { - $u->Set("Password",$password); - $u->Clean(); - if($GroupId>0) - { - $g = $objGroups->GetItem($GroupId); - $g->AddUser($u->Get("PortalUserId"),1); - } - - $custom = $_POST["custom"]; - if(is_array($custom)) - { - for($x=0;$xSetCustomField($custom[$x],$_POST[$custom[$x]]); - } - $u->SaveCustomFields(); - } - - if($Status==1) - { - if($objConfig->Get("User_Password_Auto")) - { - $u->SendUserEventMail("USER.VALIDATE",$u->Get("PortalUserId")); - $u->SendAdminEventMail("USER.VALIDATE"); - } - else - { - $doLoginNow = true; - $u->SendUserEventMail("USER.ADD",$u->Get("PortalUserId")); - $u->SendAdminEventMail("USER.ADD"); - } - } - else - { - $u->SendUserEventMail("USER.ADD.PENDING",$u->Get("PortalUserId")); - $u->SendAdminEventMail("USER.ADD.PENDING"); - } - - if ($doLoginNow) - $objSession->Login($_POST["username"], md5($password)); - - } - } - } - break; - case "m_add_friend": - $id = $_GET["UserId"]; - $userid = $objSession->Get("PortalUserId"); - if($id!=$userid) - { - $u =& $objUsers->GetItem($id); - $u->AddFavorite($userid); - } - break; - case "m_del_friend": - $id = $_GET["UserId"]; - $userid = $objSession->Get("PortalUserId"); - $u =& $objUsers->GetItem($id); - $u->DeleteFavorite(); - break; - case "m_acctinfo": -// phpinfo(INFO_VARIABLES); - $MissingCount = SetMissingDataErrors("m_acctinfo"); - $UserId = $_GET["UserId"]; - if($UserId != $objSession->Get("PortalUserId")) - { - $MissingCount++; - $FormError["m_acctinfo"]["UserId"] = language("lu_ferror_m_profile_userid"); - } - if(strlen($_POST["password"])>0) - { - if(($_POST["password"] != $_POST["passwordverify"]) || !strlen($_POST["passwordverify"])) - { - $MissingCount++; - $FormError["m_acctinfo"]["passwordverify"] = language("lu_ferror_pswd_mismatch"); - } - - if(strlen($_POST["password"])>30) - { - // echo "VAR: ".$_POST["password"]; die(); - $MissingCount++; - $FormError["m_acctinfo"]["password"] = language("lu_ferror_pswd_toolong"); - } - - if (strlen($_POST['password']) < $objConfig->Get("Min_Password")) - { - $MissingCount++; - $FormError["m_acctinfo"]["password"] = language("lu_ferror_pswd_tooshort"); - } - } - if(!$MissingCount) - { - /* save profile */ - $u =& $objUsers->GetItem($UserId); - $status = $u->Get("Status"); - $_POST["dob"] = $_POST["dob_month"]."/".$_POST["dob_day"]."/".$_POST["dob_year"]; - $dob = DateTimestamp($_POST["dob"], GetDateFormat()); - if(strlen($_POST["password"])>0) - { - $password = md5($_POST["password"]); - } - else - $password = ""; - $objUsers->Edit_User($UserId, $_POST["username"], $password, $_POST["email"], 0, - inp_escape($_POST["firstname"]), inp_escape($_POST["lastname"]), $status, $_POST["phone"], - $_POST["street"], $_POST["city"], $_POST["state"], $_POST["zip"], - $_POST["country"], $dob); - } - break; - case "m_profile": - $userid = $objSession->Get("PortalUserId"); - if($userid>0) - { - $u = $objUsers->GetItem($userid); - foreach($_POST as $field=>$value) - { - if(substr($field,0,3)=="pp_") - { - $objSession->SetPersistantVariable($field,$value); - } - } - } - break; - case "m_set_lang": - $lang = $_GET["lang"]; - $LangId = 0; - if(strlen($lang)) - { - $l = $objLanguages->GetItemByField("PackName",$lang); - if(is_object($l)) - { - $LangId = $l->Get("LanguageId"); - } - } - if($LangId) - { - if($objSession->Get("PortalUserId")>0) - { - $objSession->SetPersistantVariable("Language",$LangId); - } - $objSession->Set("Language",$LangId); - $objSession->Update(); - $m_var_list_update["lang"] = $LangId; - $m_var_list["lang"] = $LangId; - } - break; - - case "m_set_theme": - $id = $_POST["ThemeId"]; - if(!is_numeric($id)) - $id = $_GET["ThemeId"]; - if($id) - { - $objSession->SetThemeName($id); - $m_var_list["t"] = "index"; - $m_var_list_update["theme"] = $id; - $m_var_list["theme"] = $id; - unset($CurrentTheme); - } - break; - - case "m_sort_cats": - $objSession->SetVariable("Category_Sortfield",$_POST["cat_field_sort"]); - $objSession->SetVariable("Category_Sortorder",$_POST["cat_sort_order"]); - break; - case "m_add_cat_confirm": -// phpinfo(INFO_VARIABLES); - $perm = 0; - $CategoryId=$objCatList->CurrentCategoryID(); - if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING")) - $perm = 2; - if ($objSession->HasCatPermission("CATEGORY.ADD")) - $perm = 1; - if ($perm == 0) - { - $MissingCount++; - $FormError["m_addcat"]["name"] = language("lu_ferror_no_access"); - } - else - { - $MissingCount = SetMissingDataErrors("m_addcat"); - if(is_array($_FILES)) - { - foreach($_FILES as $field => $file) - { - $allowed = TRUE; - if(strlen($_POST["imagetypes"][$field])) - { - $types = explode(",",strtolower($_POST["imagetypes"][$field])); - if(is_array($types)) - { - if(count($types)>0) - { - $path_parts = pathinfo($file["name"]); - $ext = $path_parts["extension"]; - $allowed = in_array($ext,$types); - if(!$allowed) - { - $MissingCount++; - $FormError["m_addcat"][$field] = language("lu_ferror_wrongtype"); - } - } - } - } - $maxsize = (int)$_POST["maxsize"][$field]; - if($maxsize>0 && $allowed && $file["size"]>$maxsize) - { - $allowed = FALSE; - $MissingCount++; - $FormError["m_addcat"][$field] = language("lu_ferror_toolarge"); - } - } - } - if($MissingCount==0) - { - $CreatedOn = date("U"); - $name = $_POST["name"]; - $desc = $_POST["description"]; - $metadesc = $_POST["meta_description"]; - $keywords = $_POST["meta_keywords"]; - $parent = $objCatList->CurrentCategoryID(); - $cat =& $objCatList->Add($parent, $name, inp_escape($desc,0), $CreatedOn, - 0, $perm, 2, 2, 2, 0, $keywords,$metadesc); - $cat->UpdateCachedPath(); - $cat->Update(); - $cat->UpdateACL(); - $objCatList->UpdateMissingCacheData(); - - if(strlen($_GET["Confirm"])) - { - $var_list["t"] = $_GET["Confirm"]; - } - else - $var_list["t"] = $_GET["DestTemplate"]; - } - } - break; - case "m_front_review_add": - if($objSession->InSpamControl($_POST["ItemId"])) - { - $StatusMessage["review"] = language("la_Review_AlreadyReviewed"); - } - else - { - $objReviews = new clsItemReviewList(); - $Status = $objConfig->Get("Review_DefaultStatus"); - $CreatedOn = adodb_date("U"); - $html = (int)$objConfig->Get("Review_Html"); - $ReviewText = inp_escape($_POST["review_text"],$html); - - $r = $objReviews->AddReview($CreatedOn,$ReviewText,$Status, $IPAddress, - 0, $_POST["ItemId"], $_POST["ItemType"], $objSession->Get("PortalUserId")); - foreach($ItemTypes as $type=>$id) - { - if($id==$_POST["ItemType"]) - { - $ValName = $type."_ReviewDelay_Value"; - $IntName = $type."_ReviewDelay_Interval"; - break; - } - } - if(strlen($ValName) && strlen($IntName)) - { - $exp_secs = $objConfig->Get($ValName) * $objConfig->Get($IntName); - $objSession->AddToSpamControl($_POST["ItemId"],$exp_secs); - if(is_object($r)) - { - if($Status) - { - $StatusMessage["review"] = language("la_Review_Added"); - } - else - $StatusMessage["review"] = language("la_Review_Pending"); - } - else - $StatusMessage["review"] = language("la_Review_Error"); - } - else - $StatusMessage["error"] = language("la_ConfigError_Review"); - } - break; - case "m_suggest_email": - $cutoff = time()+(int)$objConfig->Get("Suggest_MinInterval"); - $email = $_POST["suggest_email"]; - - if (strlen($email)) - { - if(ValidEmail($email)) - { - $sql = "SELECT * FROM ".GetTablePrefix()."SuggestMail WHERE email='".inp_escape($email,0)."' and sent<".$cutoff; - $adodbConnection = &GetADODBConnection(); - $rs = $adodbConnection->Execute($sql); - - $rs = false; - - if($rs && !$rs->EOF) - { - if(strlen($_GET["Error"])>0) - $var_list["t"] = $_GET["Error"]; - $suggest_result = "$email ".language("lu_already_suggested ")." ".LangDate($rs->fields["sent"]); - } - else - { - $Event =& $objMessageList->GetEmailEventObject("USER.SUGGEST"); - if(is_object($Event)) - { - if($Event->Get("Enabled")=="1") - { - $Event->Item = $this; - $Event->SendToAddress($email); - - $sql = "INSERT INTO ".GetTablePrefix()."SuggestMail (email,sent) VALUES ('".inp_escape($email,0)."','".time()."')"; - - $rs = $adodbConnection->Execute($sql); - $suggest_result=language("lu_suggest_success")." ".$email; - } - } - $e =& $objMessageList->GetEmailEventObject("USER.SUGGEST",1); - - if($e->Get("Enabled")==1) - $e->SendAdmin(); - - if(strlen($_GET["Confirm"])>0) - $var_list["t"] = $_GET["Confirm"]; - } - } - else - { - if(strlen($_GET["Error"])>0) - $var_list["t"] = $_GET["Error"]; - $suggest_result=language("lu_invalid_emailaddress"); - } - } - else - { - if(strlen($_GET["Error"])>0) - $var_list["t"] = $_GET["Error"]; - $suggest_result=language("lu_suggest_no_address"); - } - break; - case "m_simple_search": - $keywords = $_POST["keywords"]; - $type = $objItemTypes->GetTypeByName("Category"); - $objSearch = new clsSearchResults("Category","clsCategory"); - - if(strlen($keywords)) - { - $objSearchList = new clsSearchLogList(); - $objSearchList->UpdateKeyword($keywords,0); - - $objSearch->SetKeywords($keywords); - $objSearch->AddSimpleFields(); - if(is_numeric($objConfig->Get("SearchRel_Pop_category"))) - $objSearch->PctPop = ($objConfig->Get("SearchRel_Pop_category")/100); - if(is_numeric($objConfig->Get("SearchRel_Keyword_category"))) - $objSearch->PctRelevance = ($objConfig->Get("SearchRel_Keyword_category")/100); - if(is_numeric($objConfig->Get("SearchRel_Rating_article"))) - $objSearch->PctRating = ($objConfig->Get("SearchRel_Rating_category")/100); - - //echo "Searching On $keywords
    \n"; - $objSearch->PerformSearch(1,$SortOrder,TRUE); - $SearchPerformed = TRUE; - //$objSearch->SetRelevence($type->Get("ItemType"), "CategoryId"); - //echo "Finished Setting Category Relevence
    \n"; - } - else - { - if(strlen($_GET["Error"])>0) - $var_list["t"] = $_GET["Error"]; - - $MissingCount = SetMissingDataErrors("m_simplesearch"); - $MissingCount++; - $FormError["m_simplesearch"]["keywords"] = language("lu_no_keyword"); - } - break; - case "m_adv_search": - if( !is_object($objSearchConfig) ) $objSearchConfig = new clsSearchConfigList(); - switch($_GET["type"]) - { - case 1: /* category */ - //echo "Searching for categories
    "; - $objAdvSearch = new clsAdvancedSearchResults("Category","clsCategory"); - foreach($objSearchConfig->Items as $field) - { - $fld = $field->Get("FieldName"); - - $Verb = $_POST["verb"][$field->Get("FieldName")]; - if(!strlen($Verb) && $field->Get("FieldType")=="boolean") - { - if($_POST["value"][$field->Get("FieldName")]!=-1) - { - $Value = $_POST["value"][$field->Get("FieldName")]; - $Verb = "is"; - } - } - else - { - $Value = $_POST["value"][$field->Get("FieldName")]; - } - switch( $_POST["andor"][$field->Get("FieldName")]) - { - case 1: - $Conjuction = "AND"; - break; - case 2: - $Conjuction = "OR"; - break; - default: - $Conjuction = ""; - break; - } - if(strlen($Verb)>0 && $Verb!="any") - { - //echo "Adding CAT SearchField: [".$field->Get("TableName")."]; [".$field->Get("FieldName")."]; [$Verb]; [$Value]; [$Conjuction]
    "; - $objAdvSearch->AddAdvancedField($field->Get("TableName"),$field->Get("FieldName"),$Verb,$Value,$Conjuction); - } - - } - $objAdvSearch->PerformSearch(1,NULL,TRUE); - break; - } - break; - case "m_id": - echo $Action.":".$DownloadId; - die(); - break; - case "m_simple_subsearch": - $keywords = $_POST["keywords"]; - $type = $objItemTypes->GetTypeByName("Category"); - $objSearch = new clsSearchResults("Category","clsCategory"); - if(strlen($keywords)) - { - $objSearchList = new clsSearchLogList(); - $objSearchList->UpdateKeyword($keywords,0); - - $objSearch->SetKeywords($keywords); - $objSearch->AddSimpleFields(); - if(is_numeric($objConfig->Get("SearchRel_Pop_category"))) - $objSearch->PctPop = ($objConfig->Get("SearchRel_Pop_category")/100); - if(is_numeric($objConfig->Get("SearchRel_Keyword_category"))) - $objSearch->PctRelevance = ($objConfig->Get("SearchRel_Keyword_category")/100); - if(is_numeric($objConfig->Get("SearchRel_Rating_article"))) - $objSearch->PctRating = ($objConfig->Get("SearchRel_Rating_category")/100); - - $SearchResultIdList = $objSearch->Result_IdList(); - if(count($SearchResultIdList)>0) - { - $objSearch->PerformSearch(1,$SortOrder,TRUE,$SearchResultIdList); - //$objSearch->SetRelevence($type->Get("ItemType"), "CategoryId"); - } - $SearchPerformed = TRUE; - } - else { - $MissingCount = SetMissingDataErrors("m_simplesearch"); - $MissingCount++; - $FormError["m_simplesearch"]["keywords"] = language("lu_no_keyword"); - } - break; -} -?> +Front, Kernel Action ['.$Action."]
    \n"; +} + +if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & FRONT_SHOW_REQUEST) == FRONT_SHOW_REQUEST ) +{ + // don't show debug output in tree & header of admin & while logging in + $script = basename($_SERVER['PHP_SELF']); + + echo '
    '; + echo "
    ScriptName: $script (".dirname($_SERVER['PHP_SELF']).")

    "; + $div_height = (count($_REQUEST)+1)*26; + if($div_height > 300) $div_height = 300; + echo '
    '; + echo ''; + echo ''; + + foreach($_REQUEST as $key => $value) + { + if( !is_array($value) && trim($value) == '' ) $value = ' '; + $src = isset($_GET[$key]) ? 'GE' : (isset($_POST[$key]) ? 'PO' : (isset($_COOKIE[$key]) ? 'CO' : '?') ); + echo ''; + } + echo '
    SrcNameValue
    '.$src.''.$key.''.print_r($value, true).'
    '; + echo '
    '; + unset($script); +// echo "SID: ".$objSession->GetSessionKey().'
    '; +} + +switch($Action) +{ + case "m_login": + // if($objSession->ValidSession()) $objSession->Logout(); + //echo $objSession->GetSessionKey()."
    \n"; + if ($objConfig->Get("CookieSessions") == 1 && $_COOKIE["CookiesTest"] != "1") { + $FormError["login"]["login_user"] = language("lu_cookies_error"); + } + else + { + $MissingCount = SetMissingDataErrors("login"); + if($MissingCount==2) + { + $FormError["login"]["login_user"]= language("lu_ferror_loginboth"); + unset($FormError["login"]["login_password"]); + } + + if($MissingCount==0) + { + if($_POST["login_user"]=="root") + { + $FormError["login"]["login_user"]= language("lu_access_denied"); + } + else + { + $LoginCheck = $objSession->Login( $_POST["login_user"], md5($_POST["login_password"]) ); + if($LoginCheck === true) + { + if( !headers_sent() && GetVar('usercookie') == 1 ) + { + $c = $_POST["login_user"]."|"; + $pw = $_POST["login_password"]; + if(strlen($pw) < 31) $pw = md5($pw); + $c .= $pw; + setcookie("login",$c,time()+2592000); + } + + // set new destination template if passed + $dest = GetVar('dest', true); + if(!$dest) $dest = GetVar('DestTemplate', true); + if($dest) $var_list['t'] = $dest; + } + else + { + switch($LoginCheck) + { + case -1: // user or/and pass wrong + $FormError["login"]["login_password"] = language("lu_incorrect_login"); + break; + + case -2: // user ok, but has no permission + $FormError["login"]["login_password"] = language("la_text_nopermissions"); + break; + } + } + } + } + } + break; + + case "m_forgotpw": + $MissingCount = SetMissingDataErrors("forgotpw"); + if($MissingCount==0) + { + $username = $_POST["username"]; + $email = $_POST["email"]; + $found = FALSE; + if(strlen($username)) + { + $u = $objUsers->GetItemByField("Login",$username); + if(is_object($u)) + $found = ($u->Get("Login")==$username && $u->Get("Status")==1) && strlen($u->Get("Password")); + } + else if(strlen($email)) + { + $u = $objUsers->GetItemByField("Email",$email); + if(is_object($u)) + $found = ($u->Get("Email")==$email && $u->Get("Status")==1) && strlen($u->Get("Password")); + } + if($found) + { + $newpw = makepassword(); + $objSession->Set('password', $newpw); + $u->Set("Password",$newpw); + $u->Update(); + $u->SendUserEventMail("USER.PSWD",$u->Get("PortalUserId")); + $u->SendAdminEventMail("USER.PSWD"); + $u->Set("Password",md5($newpw)); + $u->Update(); + $u->Clean(); + } + else + { + if(!strlen($username) && !strlen($email)) + { + $FormError["forgotpw"]["username"] = language("lu_ferror_forgotpw_nodata"); + $MissingCount++; + } + else + { + if(strlen($username)) + $FormError["forgotpw"]["username"] = language("lu_ferror_unknown_username"); + if(strlen($email)) + $FormError["forgotpw"]["email"] = language("lu_ferror_unknown_email"); + $MissingCount++; + } + if(strlen($_GET["error"])) + $var_list["t"] = $_GET["error"]; + } + } + else + if(strlen($_GET["error"])) + $var_list["t"] = $_GET["error"]; + break; + case "m_subscribe_confirm": + $t = ""; + $SubscribeAddress = $_POST["subscribe_email"]; + if(!ValidEmail($SubscribeAddress)&& strlen($SubscribeAddress)) + { + $t = $_GET["Error"]; + $SubscribeError = "lu_invalid_emailaddress"; + } + else + { + if((int)$objConfig->Get("User_SubscriberGroup")>0) + { + $g = $objGroups->GetItem($objConfig->Get("User_SubscriberGroup")); + if(is_object($g)) + { + $email = $_POST["subscribe_email"]; + if(strlen($email)>0) + { + $u = $objUsers->GetItemByField("Email",$email); + + if(is_object($u)) + { + if($u->CheckBanned()) + { + $t = $_GET["Error"]; + $SubscribeError ="lu_subscribe_banned"; + } + else + { + if($u->IsInGroup($g->Get("GroupId"))) + { + $t = $_GET["Unsubscribe"]; + } + else + $t = $_GET["Subscribe"]; + } + } + else + $t = $_GET["Subscribe"]; + } + else + { + $t = $_GET["Error"]; + $SubscribeError ="lu_subscribe_no_address"; + } + } + else + { + $t = $_GET["Error"]; + $SubscribeError ="lu_subscribe_unknown_error"; + } + } + } + if(strlen($t)) + { + $var_list["t"] = $t; + $var_list_update["t"] = $t; + } + break; + case "m_subscribe": + //phpinfo(INFO_VARIABLES); + if($_POST["buttons"][0]==language("lu_button_yes")) + { + $SubscribeAddress = $_POST["subscribe_email"]; + if(strlen($SubscribeAddress)>0) + { + if(ValidEmail($SubscribeAddress)) + { + $GroupId = (int)$objConfig->Get("User_SubscriberGroup"); + if ($GroupId) + { + $g = $objGroups->GetItem($GroupId); + $u = $objUsers->GetItemByField("Email",$SubscribeAddress); + if(is_object($u)) + { + if(strtolower($u->Get("Email"))==strtolower($SubscribeAddress)) + { + $bExists = TRUE; + } + else + $bExists = FALSE; + } + if($bExists) + { + $g->AddUser($u->Get("PortalUserId")); + } + else + { + $u = new clsPortalUser(NULL); + $u->Set("Email",$SubscribeAddress); + $u->Set("ip",$_SERVER['REMOTE_ADDR']); + $u->Set("CreatedOn",date("U")); + $u->Set("Status",1); + if(!$u->CheckBanned()) + { + $u->Create(); + $g->AddUser($u->Get("PortalUserId"),1); + } + else + $SubscribeResult = "lu_subscribe_banned"; + } + $SubscribeResult = "lu_subscribe_success"; + $u->SendUserEventMail("USER.SUBSCRIBE",$u->Get("PortalUserId")); + $u->SendAdminEventMail("USER.SUBSCRIBE"); + if(strlen($_GET["Subscribe"])>0) + $var_list["t"] = $_GET["Subscribe"]; + } + } + else + { + $SubscribeResult = "lu_invalid_emailaddress"; + } + } + else + $SubscribeResult = "lu_subscribe_missing_address"; + } + + if(!strlen($SubscribeResult)) + $SubscribeResult = "lu_subscribe_success"; + break; + case "m_unsubscribe": + + if($_POST["buttons"][0]==language("lu_button_yes")) + { + $MissingCount = SetMissingDataErrors("m_unsubscribe"); + + if($MissingCount==0) + { + $email = $_POST["subscribe_email"]; + $u = $objUsers->GetItemByField("Email",$email); + if(is_object($u)) + { + if(strtolower($u->Get("Email"))==strtolower($email)) + { + $GroupId = (int)$objConfig->Get("User_SubscriberGroup"); + if($u->PrimaryGroup()==$GroupId) + { + $u_gorup_list = $u->GetGroupList(); + + if (count($u_gorup_list) > 1) { + $u->RemoveFromGroup($GroupId); + } + else { + $u->RemoveFromAllGroups(); + $u->Delete(); + } + } + else + { + $u->RemoveFromGroup($GroupId); + } + } + } + if(strlen($_GET["Subscribe"])>0) + $var_list["t"] = $_GET["Subscribe"]; + } + } + + break; + case "m_logout": +// $objSession->Logout(); + //unset($objSession); + //$objSession = new clsUserSession(); +// $var_list_update["t"] = "index"; +// setcookie("login","",time()-3600); + break; + case "m_register": + $_POST=inp_escape($_POST); + $MissingCount = SetMissingDataErrors("m_register"); + + if(!$objConfig->Get("User_Password_Auto")) + { + if(($_POST["password"] != $_POST["passwordverify"]) || !strlen($_POST["passwordverify"])) + { + $MissingCount++; + $FormError["m_register"]["passwordverify"] = language("lu_ferror_pswd_mismatch"); + } + + if(strlen($_POST["password"])>30) + { + // echo "VAR: ".$_POST["password"]; die(); + $MissingCount++; + $FormError["m_register"]["password"] = language("lu_ferror_pswd_toolong"); + } + + if (strlen($_POST['password']) < $objConfig->Get("Min_Password")) + { + $MissingCount++; + $FormError["m_register"]["password"] = language("lu_ferror_pswd_tooshort"); + } + } + + $u = $objUsers->GetItemByField("Login",$_POST["username"]); + + if(is_object($u)) + { + if($u->Get("Login")==$_POST["username"]) + { + $MissingCount++; + $FormError["m_register"]["username"] = language("lu_user_exists"); + } + } + + if (strlen($_POST['username']) < $objConfig->Get("Min_UserName")) + { + $MissingCount++; + $FormError["m_register"]["username"] = language("lu_ferror_username_tooshort"); + } + + if(!$MissingCount) + { + $CreatedOn = adodb_date("U"); + $GroupId = $objConfig->Get("User_NewGroup"); + $Status=0; + + /* determine the status of new users */ + switch ($objConfig->Get("User_Allow_New")) + { + case "1": + $Status=1; + break; + case "3": + $Status=2; + break; + } + + /* set Destination template */ + $var_list["t"] = strlen($_GET["dest"])? $_GET["dest"] : "index"; + + if($Status>0) + { + if($objConfig->Get("User_Password_Auto")) + { + $password = makepassword(); + $objSession->Set("password", $password); + } + else + $password = $_POST["password"]; + + $_POST["dob"] = $_POST["dob_month"]."/".$_POST["dob_day"]."/".$_POST["dob_year"]; + $dob = DateTimestamp($_POST["dob"],GetDateFormat()); + $ip = $_SERVER['REMOTE_ADDR']; + + $u = &$objUsers->Add_User($_POST["username"], md5($password), $_POST["email"], $CreatedOn, $_POST["firstname"], $_POST["lastname"], $Status, $_POST["phone"], $_POST["street"], $_POST["city"], $_POST["state"], $_POST["zip"], $_POST["country"], $dob, $ip, TRUE); + + if(!is_object($u)) + { + $RuleId=$u; + $r = $objBanList->GetItem($RuleId); + $err = $r->Get("ErrorTag"); + + if(strlen($err)) + { + $FormError["m_register"][$r->Get("ItemField")] = language($err); + $MissingCount++; + } + } + else + { + $u->Set("Password",$password); + $u->Clean(); + if($GroupId>0) + { + $g = $objGroups->GetItem($GroupId); + $g->AddUser($u->Get("PortalUserId"),1); + } + + $custom = $_POST["custom"]; + if(is_array($custom)) + { + for($x=0;$xSetCustomField($custom[$x],$_POST[$custom[$x]]); + } + $u->SaveCustomFields(); + } + + if($Status==1) + { + if($objConfig->Get("User_Password_Auto")) + { + $u->SendUserEventMail("USER.VALIDATE",$u->Get("PortalUserId")); + $u->SendAdminEventMail("USER.VALIDATE"); + } + else + { + $doLoginNow = true; + $u->SendUserEventMail("USER.ADD",$u->Get("PortalUserId")); + $u->SendAdminEventMail("USER.ADD"); + } + } + else + { + $u->SendUserEventMail("USER.ADD.PENDING",$u->Get("PortalUserId")); + $u->SendAdminEventMail("USER.ADD.PENDING"); + } + + if ($doLoginNow) + $objSession->Login($_POST["username"], md5($password)); + + } + } + } + break; + case "m_add_friend": + $id = $_GET["UserId"]; + $userid = $objSession->Get("PortalUserId"); + if($id!=$userid) + { + $u =& $objUsers->GetItem($id); + $u->AddFavorite($userid); + } + break; + case "m_del_friend": + $id = $_GET["UserId"]; + $userid = $objSession->Get("PortalUserId"); + $u =& $objUsers->GetItem($id); + $u->DeleteFavorite(); + break; + case "m_acctinfo": +// phpinfo(INFO_VARIABLES); + $_POST=inp_escape($_POST); + $MissingCount = SetMissingDataErrors("m_acctinfo"); + $UserId = $_GET["UserId"]; + if($UserId != $objSession->Get("PortalUserId")) + { + $MissingCount++; + $FormError["m_acctinfo"]["UserId"] = language("lu_ferror_m_profile_userid"); + } + if(strlen($_POST["password"])>0) + { + if(($_POST["password"] != $_POST["passwordverify"]) || !strlen($_POST["passwordverify"])) + { + $MissingCount++; + $FormError["m_acctinfo"]["passwordverify"] = language("lu_ferror_pswd_mismatch"); + } + + if(strlen($_POST["password"])>30) + { + // echo "VAR: ".$_POST["password"]; die(); + $MissingCount++; + $FormError["m_acctinfo"]["password"] = language("lu_ferror_pswd_toolong"); + } + + if (strlen($_POST['password']) < $objConfig->Get("Min_Password")) + { + $MissingCount++; + $FormError["m_acctinfo"]["password"] = language("lu_ferror_pswd_tooshort"); + } + } + if(!$MissingCount) + { + /* save profile */ + $u =& $objUsers->GetItem($UserId); + $status = $u->Get("Status"); + $_POST["dob"] = $_POST["dob_month"]."/".$_POST["dob_day"]."/".$_POST["dob_year"]; + $dob = DateTimestamp($_POST["dob"], GetDateFormat()); + if(strlen($_POST["password"])>0) + { + $password = md5($_POST["password"]); + } + else + $password = ""; + $objUsers->Edit_User($UserId, $_POST["username"], $password, $_POST["email"], 0, + $_POST["firstname"], $_POST["lastname"], $status, $_POST["phone"], + $_POST["street"], $_POST["city"], $_POST["state"], $_POST["zip"], + $_POST["country"], $dob); + } + break; + case "m_profile": + $userid = $objSession->Get("PortalUserId"); + if($userid>0) + { + $u = $objUsers->GetItem($userid); + foreach($_POST as $field=>$value) + { + if(substr($field,0,3)=="pp_") + { + $objSession->SetPersistantVariable($field,$value); + } + } + } + break; + case "m_set_lang": + $lang = $_GET["lang"]; + $LangId = 0; + if(strlen($lang)) + { + $l = $objLanguages->GetItemByField("PackName",$lang); + if(is_object($l)) + { + $LangId = $l->Get("LanguageId"); + } + } + if($LangId) + { + if($objSession->Get("PortalUserId")>0) + { + $objSession->SetPersistantVariable("Language",$LangId); + } + $objSession->Set("Language",$LangId); + $objSession->Update(); + $m_var_list_update["lang"] = $LangId; + $m_var_list["lang"] = $LangId; + } + break; + + case "m_set_theme": + $id = $_POST["ThemeId"]; + if(!is_numeric($id)) + $id = $_GET["ThemeId"]; + if($id) + { + $objSession->SetThemeName($id); + $m_var_list["t"] = "index"; + $m_var_list_update["theme"] = $id; + $m_var_list["theme"] = $id; + unset($CurrentTheme); + } + break; + + case "m_sort_cats": + $objSession->SetVariable("Category_Sortfield",$_POST["cat_field_sort"]); + $objSession->SetVariable("Category_Sortorder",$_POST["cat_sort_order"]); + break; + case "m_add_cat_confirm": +// phpinfo(INFO_VARIABLES); + $perm = 0; + $CategoryId=$objCatList->CurrentCategoryID(); + if ($objSession->HasCatPermission("CATEGORY.ADD.PENDING")) + $perm = 2; + if ($objSession->HasCatPermission("CATEGORY.ADD")) + $perm = 1; + if ($perm == 0) + { + $MissingCount++; + $FormError["m_addcat"]["name"] = language("lu_ferror_no_access"); + } + else + { + $MissingCount = SetMissingDataErrors("m_addcat"); + if(is_array($_FILES)) + { + foreach($_FILES as $field => $file) + { + $allowed = TRUE; + if(strlen($_POST["imagetypes"][$field])) + { + $types = explode(",",strtolower($_POST["imagetypes"][$field])); + if(is_array($types)) + { + if(count($types)>0) + { + $path_parts = pathinfo($file["name"]); + $ext = $path_parts["extension"]; + $allowed = in_array($ext,$types); + if(!$allowed) + { + $MissingCount++; + $FormError["m_addcat"][$field] = language("lu_ferror_wrongtype"); + } + } + } + } + $maxsize = (int)$_POST["maxsize"][$field]; + if($maxsize>0 && $allowed && $file["size"]>$maxsize) + { + $allowed = FALSE; + $MissingCount++; + $FormError["m_addcat"][$field] = language("lu_ferror_toolarge"); + } + } + } + if($MissingCount==0) + { + $CreatedOn = date("U"); + $_POST=inp_striptags($_POST); + $name = $_POST["name"]; + $desc = $_POST["description"]; + $metadesc = $_POST["meta_description"]; + $keywords = $_POST["meta_keywords"]; + $parent = $objCatList->CurrentCategoryID(); + $cat =& $objCatList->Add($parent, $name, $desc, $CreatedOn, + 0, $perm, 2, 2, 2, 0, $keywords,$metadesc); + $cat->UpdateCachedPath(); + $cat->Update(); + $cat->UpdateACL(); + $objCatList->UpdateMissingCacheData(); + + if(strlen($_GET["Confirm"])) + { + $var_list["t"] = $_GET["Confirm"]; + } + else + $var_list["t"] = $_GET["DestTemplate"]; + } + } + break; + case "m_front_review_add": + if($objSession->InSpamControl($_POST["ItemId"])) + { + $StatusMessage["review"] = language("la_Review_AlreadyReviewed"); + } + else + { + $objReviews = new clsItemReviewList(); + $Status = $objConfig->Get("Review_DefaultStatus"); + $CreatedOn = adodb_date("U"); + $html = (int)$objConfig->Get("Review_Html"); + $ReviewText = inp_striptags($_POST["review_text"]); + + $r = $objReviews->AddReview($CreatedOn,$ReviewText,$Status, $IPAddress, + 0, $_POST["ItemId"], $_POST["ItemType"], $objSession->Get("PortalUserId")); + foreach($ItemTypes as $type=>$id) + { + if($id==$_POST["ItemType"]) + { + $ValName = $type."_ReviewDelay_Value"; + $IntName = $type."_ReviewDelay_Interval"; + break; + } + } + if(strlen($ValName) && strlen($IntName)) + { + $exp_secs = $objConfig->Get($ValName) * $objConfig->Get($IntName); + $objSession->AddToSpamControl($_POST["ItemId"],$exp_secs); + if(is_object($r)) + { + if($Status) + { + $StatusMessage["review"] = language("la_Review_Added"); + } + else + $StatusMessage["review"] = language("la_Review_Pending"); + } + else + $StatusMessage["review"] = language("la_Review_Error"); + } + else + $StatusMessage["error"] = language("la_ConfigError_Review"); + } + break; + case "m_suggest_email": + $cutoff = time()+(int)$objConfig->Get("Suggest_MinInterval"); + $email = inp_striptags($_POST["suggest_email"]); + + if (strlen($email)) + { + if(ValidEmail($email)) + { + $sql = "SELECT * FROM ".GetTablePrefix()."SuggestMail WHERE email='".$email."' and sent<".$cutoff; + $adodbConnection = &GetADODBConnection(); + $rs = $adodbConnection->Execute($sql); + + $rs = false; + + if($rs && !$rs->EOF) + { + if(strlen($_GET["Error"])>0) + $var_list["t"] = $_GET["Error"]; + $suggest_result = "$email ".language("lu_already_suggested ")." ".LangDate($rs->fields["sent"]); + } + else + { + $Event =& $objMessageList->GetEmailEventObject("USER.SUGGEST"); + if(is_object($Event)) + { + if($Event->Get("Enabled")=="1") + { + $Event->Item = $this; + $Event->SendToAddress($email); + + $sql = "INSERT INTO ".GetTablePrefix()."SuggestMail (email,sent) VALUES ('".$email."','".time()."')"; + + $rs = $adodbConnection->Execute($sql); + $suggest_result=language("lu_suggest_success")." ".$email; + } + } + $e =& $objMessageList->GetEmailEventObject("USER.SUGGEST",1); + + if($e->Get("Enabled")==1) + $e->SendAdmin(); + + if(strlen($_GET["Confirm"])>0) + $var_list["t"] = $_GET["Confirm"]; + } + } + else + { + if(strlen($_GET["Error"])>0) + $var_list["t"] = $_GET["Error"]; + $suggest_result=language("lu_invalid_emailaddress"); + } + } + else + { + if(strlen($_GET["Error"])>0) + $var_list["t"] = $_GET["Error"]; + $suggest_result=language("lu_suggest_no_address"); + } + break; + case "m_simple_search": + $keywords = $_POST["keywords"]; + $type = $objItemTypes->GetTypeByName("Category"); + $objSearch = new clsSearchResults("Category","clsCategory"); + + if(strlen($keywords)) + { + $objSearchList = new clsSearchLogList(); + $objSearchList->UpdateKeyword($keywords,0); + + $objSearch->SetKeywords($keywords); + $objSearch->AddSimpleFields(); + if(is_numeric($objConfig->Get("SearchRel_Pop_category"))) + $objSearch->PctPop = ($objConfig->Get("SearchRel_Pop_category")/100); + if(is_numeric($objConfig->Get("SearchRel_Keyword_category"))) + $objSearch->PctRelevance = ($objConfig->Get("SearchRel_Keyword_category")/100); + if(is_numeric($objConfig->Get("SearchRel_Rating_article"))) + $objSearch->PctRating = ($objConfig->Get("SearchRel_Rating_category")/100); + + //echo "Searching On $keywords
    \n"; + $objSearch->PerformSearch(1,$SortOrder,TRUE); + $SearchPerformed = TRUE; + //$objSearch->SetRelevence($type->Get("ItemType"), "CategoryId"); + //echo "Finished Setting Category Relevence
    \n"; + } + else + { + if(strlen($_GET["Error"])>0) + $var_list["t"] = $_GET["Error"]; + + $MissingCount = SetMissingDataErrors("m_simplesearch"); + $MissingCount++; + $FormError["m_simplesearch"]["keywords"] = language("lu_no_keyword"); + } + break; + case "m_adv_search": + if( !is_object($objSearchConfig) ) $objSearchConfig = new clsSearchConfigList(); + switch($_GET["type"]) + { + case 1: /* category */ + //echo "Searching for categories
    "; + $objAdvSearch = new clsAdvancedSearchResults("Category","clsCategory"); + foreach($objSearchConfig->Items as $field) + { + $fld = $field->Get("FieldName"); + + $Verb = $_POST["verb"][$field->Get("FieldName")]; + if(!strlen($Verb) && $field->Get("FieldType")=="boolean") + { + if($_POST["value"][$field->Get("FieldName")]!=-1) + { + $Value = $_POST["value"][$field->Get("FieldName")]; + $Verb = "is"; + } + } + else + { + $Value = $_POST["value"][$field->Get("FieldName")]; + } + switch( $_POST["andor"][$field->Get("FieldName")]) + { + case 1: + $Conjuction = "AND"; + break; + case 2: + $Conjuction = "OR"; + break; + default: + $Conjuction = ""; + break; + } + if(strlen($Verb)>0 && $Verb!="any") + { + //echo "Adding CAT SearchField: [".$field->Get("TableName")."]; [".$field->Get("FieldName")."]; [$Verb]; [$Value]; [$Conjuction]
    "; + $objAdvSearch->AddAdvancedField($field->Get("TableName"),$field->Get("FieldName"),$Verb,$Value,$Conjuction); + } + + } + $objAdvSearch->PerformSearch(1,NULL,TRUE); + break; + } + break; + case "m_id": + echo $Action.":".$DownloadId; + die(); + break; + case "m_simple_subsearch": + $keywords = $_POST["keywords"]; + $type = $objItemTypes->GetTypeByName("Category"); + $objSearch = new clsSearchResults("Category","clsCategory"); + if(strlen($keywords)) + { + $objSearchList = new clsSearchLogList(); + $objSearchList->UpdateKeyword($keywords,0); + + $objSearch->SetKeywords($keywords); + $objSearch->AddSimpleFields(); + if(is_numeric($objConfig->Get("SearchRel_Pop_category"))) + $objSearch->PctPop = ($objConfig->Get("SearchRel_Pop_category")/100); + if(is_numeric($objConfig->Get("SearchRel_Keyword_category"))) + $objSearch->PctRelevance = ($objConfig->Get("SearchRel_Keyword_category")/100); + if(is_numeric($objConfig->Get("SearchRel_Rating_article"))) + $objSearch->PctRating = ($objConfig->Get("SearchRel_Rating_category")/100); + + $SearchResultIdList = $objSearch->Result_IdList(); + if(count($SearchResultIdList)>0) + { + $objSearch->PerformSearch(1,$SortOrder,TRUE,$SearchResultIdList); + //$objSearch->SetRelevence($type->Get("ItemType"), "CategoryId"); + } + $SearchPerformed = TRUE; + } + else { + $MissingCount = SetMissingDataErrors("m_simplesearch"); + $MissingCount++; + $FormError["m_simplesearch"]["keywords"] = language("lu_no_keyword"); + } + break; +} +?> Index: trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php =================================================================== diff -u -N -r13 -r642 --- trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php (.../adodb-mysql.inc.php) (revision 13) +++ trunk/kernel/include/adodb/drivers/adodb-mysql.inc.php (.../adodb-mysql.inc.php) (revision 642) @@ -1,564 +1,588 @@ -GetOne("select version()"); - $arr['version'] = ADOConnection::_findvers($arr['description']); - return $arr; - } - - // if magic quotes disabled, use mysql_real_escape_string() - function qstr($s,$magic_quotes=false) - { - if (!$magic_quotes) { - - if (ADODB_PHPVER >= 0x4300) { - if (is_resource($this->_connectionID)) - return "'".mysql_real_escape_string($s,$this->_connectionID)."'"; - } - if ($this->replaceQuote[0] == '\\'){ - $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); - } - return "'".str_replace("'",$this->replaceQuote,$s)."'"; - } - - // undo magic quotes for " - $s = str_replace('\\"','"',$s); - return "'$s'"; - } - - function _insertid() - { - return mysql_insert_id($this->_connectionID); - } - - function _affectedrows() - { - return mysql_affected_rows($this->_connectionID); - } - - // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html - // Reference on Last_Insert_ID on the recommended way to simulate sequences - var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; - var $_genSeqSQL = "create table %s (id int not null)"; - var $_genSeq2SQL = "insert into %s values (%s)"; - var $_dropSeqSQL = "drop table %s"; - - function CreateSequence($seqname='adodbseq',$startID=1) - { - if (empty($this->_genSeqSQL)) return false; - $u = strtoupper($seqname); - - $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - if (!$ok) return false; - return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); - } - - function GenID($seqname='adodbseq',$startID=1) - { - // post-nuke sets hasGenID to false - if (!$this->hasGenID) return false; - - $getnext = sprintf($this->_genIDSQL,$seqname); - $rs = @$this->Execute($getnext); - if (!$rs) { - $u = strtoupper($seqname); - $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); - $rs = $this->Execute($getnext); - } - $this->genID = mysql_insert_id($this->_connectionID); - - if ($rs) $rs->Close(); - - return $this->genID; - } - - function &MetaDatabases() - { - $qid = mysql_list_dbs($this->_connectionID); - $arr = array(); - $i = 0; - $max = mysql_num_rows($qid); - while ($i < $max) { - $db = mysql_tablename($qid,$i); - if ($db != 'mysql') $arr[] = $db; - $i += 1; - } - return $arr; - } - - - // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) - { - if (!$col) $col = $this->sysTimeStamp; - $s = 'DATE_FORMAT('.$col.",'"; - $concat = false; - $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { - $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= '%Y'; - break; - case 'Q': - case 'q': - $s .= "'),Quarter($col)"; - - if ($len > $i+1) $s .= ",DATE_FORMAT($col,'"; - else $s .= ",('"; - $concat = true; - break; - case 'M': - $s .= '%b'; - break; - - case 'm': - $s .= '%m'; - break; - case 'D': - case 'd': - $s .= '%d'; - break; - - case 'H': - $s .= '%H'; - break; - - case 'h': - $s .= '%I'; - break; - - case 'i': - $s .= '%i'; - break; - - case 's': - $s .= '%s'; - break; - - case 'a': - case 'A': - $s .= '%p'; - break; - - default: - - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - $s .= $ch; - break; - } - } - $s.="')"; - if ($concat) $s = "CONCAT($s)"; - return $s; - } - - - // returns concatenated string - // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator - function Concat() - { - $s = ""; - $arr = func_get_args(); - $first = true; - /* - foreach($arr as $a) { - if ($first) { - $s = $a; - $first = false; - } else $s .= ','.$a; - }*/ - - // suggestion by andrew005@mnogo.ru - $s = implode(',',$arr); - if (strlen($s) > 0) return "CONCAT($s)"; - else return ''; - } - - function OffsetDate($dayFraction,$date=false) - { - if (!$date) $date = $this->sysDate; - return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; - } - - // returns true or false - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - if (ADODB_PHPVER >= 0x4300) - $this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword, - $this->forceNewConnect,$this->clientFlags); - else if (ADODB_PHPVER >= 0x4200) - $this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword, - $this->forceNewConnect); - else - $this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword); - - if ($this->_connectionID === false) return false; - if ($argDatabasename) return $this->SelectDB($argDatabasename); - return true; - } - - // returns true or false - function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - if (ADODB_PHPVER >= 0x4300) - $this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags); - else - $this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword); - if ($this->_connectionID === false) return false; - if ($this->autoRollback) $this->RollbackTrans(); - if ($argDatabasename) return $this->SelectDB($argDatabasename); - return true; - } - - function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - $this->forceNewConnect = true; - $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); - } - - function &MetaColumns($table) - { - - if ($this->metaColumnsSQL) { - global $ADODB_FETCH_MODE; - - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - - $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); - - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - if ($rs === false) return false; - - $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $type = $rs->fields[1]; - - // split type into type(length): - if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { - $fld->type = $query_array[1]; - $fld->max_length = $query_array[2]; - } else { - $fld->max_length = -1; - $fld->type = $type; - } - $fld->not_null = ($rs->fields[2] != 'YES'); - $fld->primary_key = ($rs->fields[3] == 'PRI'); - $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); - $fld->binary = (strpos($fld->type,'blob') !== false); - if (!$fld->binary) { - $d = $rs->fields[4]; - if ($d != "" && $d != "NULL") { - $fld->has_default = true; - $fld->default_value = $d; - } else { - $fld->has_default = false; - } - } - - $retarr[strtoupper($fld->name)] = $fld; - $rs->MoveNext(); - } - $rs->Close(); - return $retarr; - } - return false; - } - - // returns true or false - function SelectDB($dbName) - { - $this->databaseName = $dbName; - if ($this->_connectionID) { - return @mysql_select_db($dbName,$this->_connectionID); - } - else return false; - } - - // parameters use PostgreSQL convention, not MySQL - function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs=0) - { - $offsetStr =($offset>=0) ? "$offset," : ''; - - return ($secs) ? $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr,$arg3) - : $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr,$arg3); - - } - - - // returns queryID or false - function _query($sql,$inputarr) - { - //global $ADODB_COUNTRECS; - //if($ADODB_COUNTRECS) - return mysql_query($sql,$this->_connectionID); - //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6 - } - - /* Returns: the last error message from previous database operation */ - function ErrorMsg() - { - if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error(); - else $this->_errorMsg = @mysql_error($this->_connectionID); - return $this->_errorMsg; - } - - /* Returns: the last error number from previous database operation */ - function ErrorNo() - { - if (empty($this->_connectionID)) return @mysql_errno(); - else return @mysql_errno($this->_connectionID); - } - - - - // returns true or false - function _close() - { - @mysql_close($this->_connectionID); - $this->_connectionID = false; - } - - - /* - * Maximum size of C field - */ - function CharMax() - { - return 255; - } - - /* - * Maximum size of X field - */ - function TextMax() - { - return 4294967295; - } - -} - -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ - -class ADORecordSet_mysql extends ADORecordSet{ - - var $databaseType = "mysql"; - var $canSeek = true; - - function ADORecordSet_mysql($queryID,$mode=false) - { - if ($mode === false) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) - { - case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - default: - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break; - } - - $this->ADORecordSet($queryID); - } - - function _initrs() - { - //GLOBAL $ADODB_COUNTRECS; - // $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1; - $this->_numOfRows = @mysql_num_rows($this->_queryID); - $this->_numOfFields = @mysql_num_fields($this->_queryID); - } - - function &FetchField($fieldOffset = -1) - { - - if ($fieldOffset != -1) { - $o = @mysql_fetch_field($this->_queryID, $fieldOffset); - $f = @mysql_field_flags($this->_queryID,$fieldOffset); - $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com) - //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable - $o->binary = (strpos($f,'binary')!== false); - } - else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ - $o = @mysql_fetch_field($this->_queryID); - $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com) - //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable - } - - return $o; - } - - function &GetRowAssoc($upper=true) - { - if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields; - return ADORecordSet::GetRowAssoc($upper); - } - - /* Use associative array to get fields array */ - function Fields($colname) - { - // added @ by "Michael William Miller" - if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname]; - - if (!$this->bind) { - $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { - $o = $this->FetchField($i); - $this->bind[strtoupper($o->name)] = $i; - } - } - return $this->fields[$this->bind[strtoupper($colname)]]; - } - - function _seek($row) - { - if ($this->_numOfRows == 0) return false; - return @mysql_data_seek($this->_queryID,$row); - } - - - // 10% speedup to move MoveNext to child class - function MoveNext() - { - //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this); - - if ($this->EOF) return false; - - $this->_currentRow++; - $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); - if (is_array($this->fields)) return true; - - $this->EOF = true; - - /* -- tested raising an error -- appears pointless - $conn = $this->connection; - if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { - $fn = $conn->raiseErrorFn; - $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); - } - */ - return false; - } - - function _fetch() - { - $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); - return is_array($this->fields); - } - - function _close() { - @mysql_free_result($this->_queryID); - $this->_queryID = false; - } - - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } - - $len = -1; // mysql max_length is not accurate - switch (strtoupper($t)) { - case 'STRING': - case 'CHAR': - case 'VARCHAR': - case 'TINYBLOB': - case 'TINYTEXT': - case 'ENUM': - case 'SET': - if ($len <= $this->blobSize) return 'C'; - - case 'TEXT': - case 'LONGTEXT': - case 'MEDIUMTEXT': - return 'X'; - - // php_mysql extension always returns 'blob' even if 'text' - // so we have to check whether binary... - case 'IMAGE': - case 'LONGBLOB': - case 'BLOB': - case 'MEDIUMBLOB': - return !empty($fieldobj->binary) ? 'B' : 'X'; - case 'YEAR': - case 'DATE': return 'D'; - - case 'TIME': - case 'DATETIME': - case 'TIMESTAMP': return 'T'; - - case 'INT': - case 'INTEGER': - case 'BIGINT': - case 'TINYINT': - case 'MEDIUMINT': - case 'SMALLINT': - - if (!empty($fieldobj->primary_key)) return 'R'; - else return 'I'; - - default: return 'N'; - } - } - -} -} +GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; + } + + // if magic quotes disabled, use mysql_real_escape_string() + function qstr($s,$magic_quotes=false) + { + if (!$magic_quotes) { + + if (ADODB_PHPVER >= 0x4300) { + if (is_resource($this->_connectionID)) + return "'".mysql_real_escape_string($s,$this->_connectionID)."'"; + } + if ($this->replaceQuote[0] == '\\'){ + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + } + return "'".str_replace("'",$this->replaceQuote,$s)."'"; + } + + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + return "'$s'"; + } + + function _insertid() + { + return mysql_insert_id($this->_connectionID); + } + + function _affectedrows() + { + return mysql_affected_rows($this->_connectionID); + } + + // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html + // Reference on Last_Insert_ID on the recommended way to simulate sequences + var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; + var $_genSeqSQL = "create table %s (id int not null)"; + var $_genSeq2SQL = "insert into %s values (%s)"; + var $_dropSeqSQL = "drop table %s"; + + function CreateSequence($seqname='adodbseq',$startID=1) + { + if (empty($this->_genSeqSQL)) return false; + $u = strtoupper($seqname); + + $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + if (!$ok) return false; + return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); + } + + function GenID($seqname='adodbseq',$startID=1) + { + // post-nuke sets hasGenID to false + if (!$this->hasGenID) return false; + + $getnext = sprintf($this->_genIDSQL,$seqname); + $rs = @$this->Execute($getnext); + if (!$rs) { + $u = strtoupper($seqname); + $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); + $rs = $this->Execute($getnext); + } + $this->genID = mysql_insert_id($this->_connectionID); + + if ($rs) $rs->Close(); + + return $this->genID; + } + + function &MetaDatabases() + { + $qid = mysql_list_dbs($this->_connectionID); + $arr = array(); + $i = 0; + $max = mysql_num_rows($qid); + while ($i < $max) { + $db = mysql_tablename($qid,$i); + if ($db != 'mysql') $arr[] = $db; + $i += 1; + } + return $arr; + } + + + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col=false) + { + if (!$col) $col = $this->sysTimeStamp; + $s = 'DATE_FORMAT('.$col.",'"; + $concat = false; + $len = strlen($fmt); + for ($i=0; $i < $len; $i++) { + $ch = $fmt[$i]; + switch($ch) { + case 'Y': + case 'y': + $s .= '%Y'; + break; + case 'Q': + case 'q': + $s .= "'),Quarter($col)"; + + if ($len > $i+1) $s .= ",DATE_FORMAT($col,'"; + else $s .= ",('"; + $concat = true; + break; + case 'M': + $s .= '%b'; + break; + + case 'm': + $s .= '%m'; + break; + case 'D': + case 'd': + $s .= '%d'; + break; + + case 'H': + $s .= '%H'; + break; + + case 'h': + $s .= '%I'; + break; + + case 'i': + $s .= '%i'; + break; + + case 's': + $s .= '%s'; + break; + + case 'a': + case 'A': + $s .= '%p'; + break; + + default: + + if ($ch == '\\') { + $i++; + $ch = substr($fmt,$i,1); + } + $s .= $ch; + break; + } + } + $s.="')"; + if ($concat) $s = "CONCAT($s)"; + return $s; + } + + + // returns concatenated string + // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator + function Concat() + { + $s = ""; + $arr = func_get_args(); + $first = true; + /* + foreach($arr as $a) { + if ($first) { + $s = $a; + $first = false; + } else $s .= ','.$a; + }*/ + + // suggestion by andrew005@mnogo.ru + $s = implode(',',$arr); + if (strlen($s) > 0) return "CONCAT($s)"; + else return ''; + } + + function OffsetDate($dayFraction,$date=false) + { + if (!$date) $date = $this->sysDate; + return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; + } + + // returns true or false + function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (ADODB_PHPVER >= 0x4300) + $this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword, + $this->forceNewConnect,$this->clientFlags); + else if (ADODB_PHPVER >= 0x4200) + $this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword, + $this->forceNewConnect); + else + $this->_connectionID = @mysql_connect($argHostname,$argUsername,$argPassword); + + if ($this->_connectionID === false) return false; + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } + + // returns true or false + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + if (ADODB_PHPVER >= 0x4300) + $this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags); + else + $this->_connectionID = @mysql_pconnect($argHostname,$argUsername,$argPassword); + if ($this->_connectionID === false) return false; + if ($this->autoRollback) $this->RollbackTrans(); + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } + + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + $this->forceNewConnect = true; + $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); + } + + function &MetaColumns($table) + { + + if ($this->metaColumnsSQL) { + global $ADODB_FETCH_MODE; + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if ($rs === false) return false; + + $retarr = array(); + while (!$rs->EOF){ + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $type = $rs->fields[1]; + + // split type into type(length): + if (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = $query_array[2]; + } else { + $fld->max_length = -1; + $fld->type = $type; + } + $fld->not_null = ($rs->fields[2] != 'YES'); + $fld->primary_key = ($rs->fields[3] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); + $fld->binary = (strpos($fld->type,'blob') !== false); + if (!$fld->binary) { + $d = $rs->fields[4]; + if ($d != "" && $d != "NULL") { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } + } + + $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + $rs->Close(); + return $retarr; + } + return false; + } + + // returns true or false + function SelectDB($dbName) + { + $this->databaseName = $dbName; + if ($this->_connectionID) { + return @mysql_select_db($dbName,$this->_connectionID); + } + else return false; + } + + // parameters use PostgreSQL convention, not MySQL + function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs=0) + { + $offsetStr =($offset>=0) ? "$offset," : ''; + + return ($secs) ? $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr,$arg3) + : $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr,$arg3); + + } + + + // returns queryID or false + function _query($sql,$inputarr) + { + //global $ADODB_COUNTRECS; + //if($ADODB_COUNTRECS) + if(defined('EDD')) + { + $explain=''; +// if($result=mysql_query('EXPLAIN '.$sql,$this->_connectionID)) +// { +// $dd=Array(); +// while($d=mysql_fetch_assoc($result))$dd[]=$d; +// mysql_free_result($result); +// $h='';$r=''; +// foreach($dd as $i=>$d) +// { +// foreach($d as $th=>$td) +// { +// if(!$i)$h.=''.$th.''; +// $r.=''.$td.''; +// } +// if(!$i)$h=''.$h.''; +// $h.=''.$r.''; +// $r=''; +// } +// $explain='
    '.$h.'
    '; +// } + $GLOBALS['_Q'][]=$sql.$explain; + } + return mysql_query($sql,$this->_connectionID); + //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6 + } + + /* Returns: the last error message from previous database operation */ + function ErrorMsg() + { + if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error(); + else $this->_errorMsg = @mysql_error($this->_connectionID); + return $this->_errorMsg; + } + + /* Returns: the last error number from previous database operation */ + function ErrorNo() + { + if (empty($this->_connectionID)) return @mysql_errno(); + else return @mysql_errno($this->_connectionID); + } + + + + // returns true or false + function _close() + { + @mysql_close($this->_connectionID); + $this->_connectionID = false; + } + + + /* + * Maximum size of C field + */ + function CharMax() + { + return 255; + } + + /* + * Maximum size of X field + */ + function TextMax() + { + return 4294967295; + } + +} + +/*-------------------------------------------------------------------------------------- + Class Name: Recordset +--------------------------------------------------------------------------------------*/ + +class ADORecordSet_mysql extends ADORecordSet{ + + var $databaseType = "mysql"; + var $canSeek = true; + + function ADORecordSet_mysql($queryID,$mode=false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch ($mode) + { + case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; + case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; + default: + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH:$this->fetchMode = MYSQL_BOTH; break; + } + + $this->ADORecordSet($queryID); + } + + function _initrs() + { + //GLOBAL $ADODB_COUNTRECS; + // $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1; + $this->_numOfRows = @mysql_num_rows($this->_queryID); + $this->_numOfFields = @mysql_num_fields($this->_queryID); + } + + function &FetchField($fieldOffset = -1) + { + + if ($fieldOffset != -1) { + $o = @mysql_fetch_field($this->_queryID, $fieldOffset); + $f = @mysql_field_flags($this->_queryID,$fieldOffset); + $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich@att.com) + //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable + $o->binary = (strpos($f,'binary')!== false); + } + else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */ + $o = @mysql_fetch_field($this->_queryID); + $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich@att.com) + //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable + } + + return $o; + } + + function &GetRowAssoc($upper=true) + { + if ($this->fetchMode == MYSQL_ASSOC && !$upper) return $this->fields; + return ADORecordSet::GetRowAssoc($upper); + } + + /* Use associative array to get fields array */ + function Fields($colname) + { + // added @ by "Michael William Miller" + if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname]; + + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function _seek($row) + { + if ($this->_numOfRows == 0) return false; + return @mysql_data_seek($this->_queryID,$row); + } + + + // 10% speedup to move MoveNext to child class + function MoveNext() + { + //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return adodb_movenext($this); + + if ($this->EOF) return false; + + $this->_currentRow++; + $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); + if (is_array($this->fields)) return true; + + $this->EOF = true; + + /* -- tested raising an error -- appears pointless + $conn = $this->connection; + if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { + $fn = $conn->raiseErrorFn; + $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); + } + */ + return false; + } + + function _fetch() + { + $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); + return is_array($this->fields); + } + + function _close() { + @mysql_free_result($this->_queryID); + $this->_queryID = false; + } + + function MetaType($t,$len=-1,$fieldobj=false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + + $len = -1; // mysql max_length is not accurate + switch (strtoupper($t)) { + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'TINYBLOB': + case 'TINYTEXT': + case 'ENUM': + case 'SET': + if ($len <= $this->blobSize) return 'C'; + + case 'TEXT': + case 'LONGTEXT': + case 'MEDIUMTEXT': + return 'X'; + + // php_mysql extension always returns 'blob' even if 'text' + // so we have to check whether binary... + case 'IMAGE': + case 'LONGBLOB': + case 'BLOB': + case 'MEDIUMBLOB': + return !empty($fieldobj->binary) ? 'B' : 'X'; + case 'YEAR': + case 'DATE': return 'D'; + + case 'TIME': + case 'DATETIME': + case 'TIMESTAMP': return 'T'; + + case 'INT': + case 'INTEGER': + case 'BIGINT': + case 'TINYINT': + case 'MEDIUMINT': + case 'SMALLINT': + + if (!empty($fieldobj->primary_key)) return 'R'; + else return 'I'; + + default: return 'N'; + } + } + +} +} ?> \ No newline at end of file Index: trunk/kernel/include/category.php =================================================================== diff -u -N -r537 -r642 --- trunk/kernel/include/category.php (.../category.php) (revision 537) +++ trunk/kernel/include/category.php (.../category.php) (revision 642) @@ -1,2318 +1,2318 @@ -clsItem(TRUE); - //$this->adodbConnection = &GetADODBConnection(); - $this->tablename = GetTablePrefix()."Category"; - $this->type=1; - $this->BasePermission ="CATEGORY"; - $this->id_field = "CategoryId"; - $this->TagPrefix = "cat"; - - $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 ClearCacheData() - { - $env = "':m".$this->Get("CategoryId")."%'"; - DeleteTagCache("m_itemcount","Category%"); - DeleteTagCache("m_list_cats","",$env); - } - - - function Delete() - { - global $CatDeleteList; - - if(!is_array($CatDeleteList)) - $CatDeleteList = array(); - if($this->UsingTempTable()==FALSE) - { - $this->Permissions->Delete_CatPerms($this->Get("CategoryId")); - $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); - if($this->tablename==GetTablePrefix()."Category") - $this->ClearCacheData(); - } - - function Create() - { - if((int)$this->Get("CreatedOn")==0) - $this->Set("CreatedOn",date("U")); - parent::Create(); - 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, Name 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) - { - - if(!is_null($target_template)) - { - $var_list_update["t"] = $target_template; - } - $m_var_list_update["cat"] = $rs->fields["CategoryId"]; - $m_var_list_update["p"] = "1"; - $cat_name = $rs->fields['Name']; - if (!is_null($anchor)) - $ret .= "$cat_name"; - else - $ret .= "$cat_name"; - - $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; - $NavPath = ""; - $path = array(); - do - { - $rs = $this->adodbConnection->Execute("SELECT ParentId,Name from ".$this->tablename." where CategoryId='$Id2'"); - $path[] = $Id2; - $nav[] = $rs->fields["Name"]; - if ($rs && !$rs->EOF) - { - //echo $path; - $Id2 = $rs->fields["ParentId"]; - - } - else - $Id2="0"; //to prevent infinite loop - } while ($Id2 != "0"); - $parentpath = "|".implode("|",array_reverse($path))."|"; - $NavBar = implode(">",array_reverse($nav)); - //echo "
    \n"; - //$rs = $this->adodbConnection->Execute("update Category set ParentPath='$path' where CategoryId='$Id'"); - if($this->Get("ParentPath")!=$parentpath || $this->Get("CachedNavbar")!=$NavBar) - { - $this->Set("ParentPath",$parentpath); - $this->Set("CachedNavbar",$NavBar); - $this->Update(); - } - } - - function GetCachedNavBar() - { - $res = $this->Get("CachedNavbar"); - if(!strlen($res)) - { - $this->UpdateCachedPath(); - $res = $this->Get("CachedNavbar"); - } - return $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 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->SourceTable." 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")."
    \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
    \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; - - $dacl = array(); - if(!is_array($allgroups)) - { - global $objGroups; - $allgroups = $objGroups->GetAllGroupList(); - } - - for($i=0;$iPermissions->GetPermId($PermName); - $pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId); - if(is_object($pc)) - { - $pc->Set("ACL",$aval); - $pc->Set("DACL",$dval); - $pc->Update(); - } - else - $objPermCache->AddPermCache($this->Get("CategoryId"),$PermId,$aval,$dval); - - //$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() - { - global $objGroups, $objPermCache; - - $glist = $objGroups->GetAllGroupList(); - - $ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$glist); - $perms = $this->Permissions->GetAllViewPermGroups($this,$glist); - //echo "
    ";print_r($perms); echo "
    "; - foreach($perms as $PermName => $l) - { - $this->SetViewPerms($PermName,$l,$glist); - } - } - - function Cat_Link() - { - global $m_var_list_update; - - $m_var_list_update["cat"] = $this->Get("CategoryId"); - $ret = GetIndexURL()."?env=".BuildEnv(); - 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 = GetIndexURL()."?env=".BuildEnv(); - 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 ParseObject($element) - { - global $objConfig, $objCatList, $rootURL, $var_list, $var_list_update, $m_var_list_update, $objItemTypes,$objCountCache; - $extra_attribs = ExtraAttributes($element->attributes); - - //print_r($element); - if(strtolower($element->name)==$this->TagPrefix) - { - $field = strtolower( $element->GetAttributeByName('_field') ); - switch($field) - { - case "name": - case "Name": - /* - @field:cat.name - @description:Category name - */ - $ret = $this->HighlightField("Name"); - break; - case "description": - /* - @field:cat.description - @description:Category Description - */ - $ret = inp_unescape($this->Get("Description")); - $ret = $this->HighlightText($ret); - break; - case "cachednavbar": - /* - @field:cat.cachednavbar - @description: Category cached navbar - */ - $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 = ""; - } - 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"; - } - $u = $objUsers->GetUser($this->Get("CreatedById")); - $ret = $u->parsetag($field); - 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; - $template = strlen($element->attributes["_TargetTemplate"])? $element->attributes["_TargetTemplate"] : 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)]; - $t = $path . $element->GetAttributeByName('_mod_template'); - } - else - $t = $element->GetAttributeByName('_template'); - - - 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 = GetIndexURL()."?env=" . BuildEnv(); - 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 = GetIndexURL()."?env=" . BuildEnv(); - 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(); - - // pass through selector - if( isset($_REQUEST['Selector']) ) $ret .= '&Selector='.$_REQUEST['Selector']; - - // pass new status - if( isset($_REQUEST['new']) ) $ret .= '&new='.$_REQUEST['new']; - - unset($m_var_list_update["cat"]); - return $ret; - break; - case "admin_icon": - if( $element->GetAttributeByName('fulltag') ) - { - $ret = "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 = "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)) - { - $TypeId = $type->Get("ItemType"); - $GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0; - $txt = "Get("CategoryId")."\" _SubCats=\"1\" "; - $txt .=" _ListType=\"category\" _CountCurrent=\"1\" _ItemType=\"$TypeId\" _GroupOnly=\"$GroupOnly\" />"; - $tag = new clsHtmlTag($txt); - $ret = $tag->Execute(); - } - 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
    -
      -
    • "Numerical": Show the decimal value -
    • "Bar": Show the HTML representing the relevance. Returns two HTML cells ≶td< with specified background colors -
    • "Graphical":Show image representing the relevance -
    - @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->Get("CachedNavbar"); - break; - case "cat_name": - return inp_unescape($this->Get("Name")); - break; - case "cat_desc": - return inp_unescape($this->Get("Description")); - 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("Name"); - 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 inp_unescape($this->Get("MetaKeywords")); - break; - case "cat_metadesc": - return inp_unescape($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")); - 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..
    \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("Name"))) - $names[] = $cat->Get("Name"); - - } - } - $nav = implode(">", $names); - $this->Set("CachedNavbar",$nav); - $this->Update(); - } - $res = explode(">",$this->Get("CachedNavbar")); - return $res; - } - - function UpdateCacheCounts() - { - global $objItemTypes; - - $CatId = $this->Get("CategoryId"); - - if($CatId>0) - { - //echo "Updating count for ".$this->Get("CachedNavbar")."
    \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'); - $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; - - function clsCatList() - { - global $m_var_list; - $this->clsItemCollection(); - $this->classname="clsCategory"; - $this->AdminSearchFields = array("Name","Description"); - $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; - - $cat = $attribs["_catid"]; - if(!is_numeric($cat)) - { - $cat = $this->CurrentCategoryID(); - } - if((int)$cat>0) - $c = $this->GetCategory($cat); - - if($attribs["_subcats"] && $cat>0) - { - $ParentWhere = "(ParentPath LIKE '".$c->Get("ParentPath")."%' AND ".$this->SourceTable.".CategoryId != $cat)"; - } - if($attribs["_today"]) - { - $today = mktime(0,0,0,date("m"),date("d"),date("Y")); - $TodayWhere = "(CreatedOn>=$today)"; - } - if($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."
    "; - - $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)); - } - } - - - 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 = ($this->Page-1) * $PerPage; - $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; - - 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) - { - global $objConfig, $m_var_list_update, $var_list_update, $var_list; - - if(!strlen($page)) - $page = GetIndexURL(); - - $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 = $page."?env=".BuildEnv(); - $o .= "<<"; - } - - - for($p=$StartPage;$p<=$EndPage;$p++) - { - if($p!=$this->Page) - { - $m_var_list_update["p"]=$p; - $href = $page."?env=".BuildEnv(); - $o .= " $p "; - } - else - { - $o .= "$p"; - } - } - if($EndPage<$NumPages && $EndPage>0) - { - $m_var_list_update["p"]=$this->Page+$PagesToList; - $next_url = $page."?env=".BuildEnv(); - $o .= " >>"; - } - 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 .= "<<"; - } - - 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 .= " $p "; - } - else - $o .= "$p"; - } - - if($this->Page < $NumPages) - $o .= ">>"; - - 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; - - $selector = isset($_REQUEST['Selector']) ? '&Selector='.$_REQUEST['Selector'] : ''; - $new = isset($_REQUEST['new']) ? '&new='.$_REQUEST['new'] : ''; - - $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 = "$cat_name"; } - else - $nav = "$cat_name"; - } - 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("Name"); - $m_var_list_update["cat"] = $root; - if($cat == $catid && !$LinkLeaf) - { - $nav[] = "".$cat_name.""; //href=\"browse.php?env=". BuildEnv() ."\" - } - else - { - if ($admin == 1) - { - $nav[] = "".$cat_name.""; - } - else - { - if(strlen($RootTemplate)) - { - $var_list_update["t"] = $RootTemplate; - } - else - { - $var_list_update["t"] = $target_template; - } - $nav[] = "".$cat_name.""; - } - } - } - 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[] = "".$cat_name.""; //href=\"browse.php?env=". BuildEnv() ."\" - } - else - { - if ($admin == 1) - { - $nav[] = "".$cat_name.""; - } - else - { - if(strlen($RootTemplate)) - { - $var_list_update["t"] = $RootTemplate; - } - else - $var_list_update["t"] = $target_template; - $nav[] = "".$cat_name.""; - } - } - - } - //echo " After $nav_unparsed
    \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("Name"); - - $m_var_list_update["cat"] = $catid; - if($catid==$modcat && strlen($ModTemplate)>0) - { - $t = $ModTemplate; - } - else - $t = $target_template; - if($cat == $catid && !$LinkLeaf) - { - $nav[] = "".$cat_name.""; - } - else - { - if ($admin == 1) - { - $nav[] = "".$cat_name.""; - } - else - { - $var_list_update["t"] = $t; - $nav[] = "".$cat_name.""; - unset($var_list_update["t"]); - } - } - unset($m_var_list_update["cat"]); - } - } - } - $nav = implode($separator, $nav); - } - return $nav; - } - - function &Add($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New, $Pop, - $Priority, $MetaKeywords,$MetaDesc) - { - global $objSession; - - $UserId = $objSession->Get("UserId"); - - $d = new clsCategory(NULL); - $d->tablename = $this->SourceTable; - if($d->UsingTempTable()) - $d->Set("CategoryId",-1); - $d->idfield = "CategoryId"; - $d->Set(array("ParentId", "Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem", - "NewItem","PopItem", "Priority", "MetaKeywords", "MetaDescription", "CreatedById"), - array($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New, - $Pop, $Priority, $MetaKeywords,$MetaDesc, $UserId)); - - $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($CategoryId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, - $NewItem, $Pop, $Priority, $MetaKeywords,$MetaDesc) - { - $d =& $this->GetCategory($CategoryId); - $d->Set(array("Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem", - "NewItem", "PopItem", "Priority", "MetaKeywords","MetaDescription"), - array($Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $NewItem, - $Pop, $Priority, $MetaKeywords,$MetaDesc)); - $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
    \n"; - echo "
    ";print_r($ChildList); echo "
    "; - echo "Old Parent: $oldparent
    \n"; - echo "ID: $Id
    \n"; - */ - /* sanity checks */ - - if(!in_array($ParentTo,$ChildList) && $oldparent != $ParentTo && $oldparent != $Id && - $Id != $ParentTo) - { - $d->Set("ParentId", $ParentTo); - $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("Name"); - 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
    "; - $dest->Set("Name", $Name); - $Names = CategoryNameCount($ParentTo,$Name); - //echo "Names Count: ".count($Names)."
    "; - if(count($Names)>0) - { - $NameCount = count($Names); - $found = FALSE; - $NewName = "Copy of $Name"; - - if(!in_array($NewName,$Names)) - { - //echo "Matched on $NewName in:
    \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
    "; - $dest->Set("Name",$NewName); - } - - } - $dest->UnsetIdField(); - $dest->Set("CachedDescendantCatsQty",0); - $dest->Set("ResourceId",NULL); - $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) - { - global $objSession; - - $d =& $this->GetCategory($Id); - - if(is_object($d)) - { - if($d->Get("CategoryId")==$Id) - { - $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;$iGetItem($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(Name) 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(); - } - - $rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE CachedNavbar IS NULL or CachedNavBar=''"); - 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; - - $objPermList = new clsPermList(); - $edit_table = $objSession->GetEditTable($this->SourceTable); - - $sql = "SELECT * FROM $edit_table"; - $rs = $this->adodbConnection->Execute($sql); - - 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")); - } - - //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"); - - //$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]
    \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); -} -?> +clsItem(TRUE); + //$this->adodbConnection = &GetADODBConnection(); + $this->tablename = GetTablePrefix()."Category"; + $this->type=1; + $this->BasePermission ="CATEGORY"; + $this->id_field = "CategoryId"; + $this->TagPrefix = "cat"; + + $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 ClearCacheData() + { + $env = "':m".$this->Get("CategoryId")."%'"; + DeleteTagCache("m_itemcount","Category%"); + DeleteTagCache("m_list_cats","",$env); + } + + + function Delete() + { + global $CatDeleteList; + + if(!is_array($CatDeleteList)) + $CatDeleteList = array(); + if($this->UsingTempTable()==FALSE) + { + $this->Permissions->Delete_CatPerms($this->Get("CategoryId")); + $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); + if($this->tablename==GetTablePrefix()."Category") + $this->ClearCacheData(); + } + + function Create() + { + if((int)$this->Get("CreatedOn")==0) + $this->Set("CreatedOn",date("U")); + parent::Create(); + 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, Name 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) + { + + if(!is_null($target_template)) + { + $var_list_update["t"] = $target_template; + } + $m_var_list_update["cat"] = $rs->fields["CategoryId"]; + $m_var_list_update["p"] = "1"; + $cat_name = $rs->fields['Name']; + if (!is_null($anchor)) + $ret .= "$cat_name"; + else + $ret .= "$cat_name"; + + $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; + $NavPath = ""; + $path = array(); + do + { + $rs = $this->adodbConnection->Execute("SELECT ParentId,Name from ".$this->tablename." where CategoryId='$Id2'"); + $path[] = $Id2; + $nav[] = $rs->fields["Name"]; + if ($rs && !$rs->EOF) + { + //echo $path; + $Id2 = $rs->fields["ParentId"]; + + } + else + $Id2="0"; //to prevent infinite loop + } while ($Id2 != "0"); + $parentpath = "|".implode("|",array_reverse($path))."|"; + $NavBar = implode(">",array_reverse($nav)); + //echo "
    \n"; + //$rs = $this->adodbConnection->Execute("update Category set ParentPath='$path' where CategoryId='$Id'"); + if($this->Get("ParentPath")!=$parentpath || $this->Get("CachedNavbar")!=$NavBar) + { + $this->Set("ParentPath",$parentpath); + $this->Set("CachedNavbar",$NavBar); + $this->Update(); + } + } + + function GetCachedNavBar() + { + $res = $this->Get("CachedNavbar"); + if(!strlen($res)) + { + $this->UpdateCachedPath(); + $res = $this->Get("CachedNavbar"); + } + return $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 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->SourceTable." 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")."
    \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
    \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; + + $dacl = array(); + if(!is_array($allgroups)) + { + global $objGroups; + $allgroups = $objGroups->GetAllGroupList(); + } + + for($i=0;$iPermissions->GetPermId($PermName); + $pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId); + if(is_object($pc)) + { + $pc->Set("ACL",$aval); + $pc->Set("DACL",$dval); + $pc->Update(); + } + else + $objPermCache->AddPermCache($this->Get("CategoryId"),$PermId,$aval,$dval); + + //$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() + { + global $objGroups, $objPermCache; + + $glist = $objGroups->GetAllGroupList(); + + $ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$glist); + $perms = $this->Permissions->GetAllViewPermGroups($this,$glist); + //echo "
    ";print_r($perms); echo "
    "; + foreach($perms as $PermName => $l) + { + $this->SetViewPerms($PermName,$l,$glist); + } + } + + function Cat_Link() + { + global $m_var_list_update; + + $m_var_list_update["cat"] = $this->Get("CategoryId"); + $ret = GetIndexURL()."?env=".BuildEnv(); + 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 = GetIndexURL()."?env=".BuildEnv(); + 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 ParseObject($element) + { + global $objConfig, $objCatList, $rootURL, $var_list, $var_list_update, $m_var_list_update, $objItemTypes,$objCountCache; + $extra_attribs = ExtraAttributes($element->attributes); + + //print_r($element); + if(strtolower($element->name)==$this->TagPrefix) + { + $field = strtolower( $element->GetAttributeByName('_field') ); + switch($field) + { + case "name": + case "Name": + /* + @field:cat.name + @description:Category name + */ + $ret = $this->HighlightField("Name"); + break; + case "description": + /* + @field:cat.description + @description:Category Description + */ + $ret = ($this->Get("Description")); + $ret = $this->HighlightText($ret); + break; + case "cachednavbar": + /* + @field:cat.cachednavbar + @description: Category cached navbar + */ + $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 = ""; + } + 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"; + } + $u = $objUsers->GetUser($this->Get("CreatedById")); + $ret = $u->parsetag($field); + 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; + $template = strlen($element->attributes["_TargetTemplate"])? $element->attributes["_TargetTemplate"] : 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)]; + $t = $path . $element->GetAttributeByName('_mod_template'); + } + else + $t = $element->GetAttributeByName('_template'); + + + 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 = GetIndexURL()."?env=" . BuildEnv(); + 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 = GetIndexURL()."?env=" . BuildEnv(); + 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(); + + // pass through selector + if( isset($_REQUEST['Selector']) ) $ret .= '&Selector='.$_REQUEST['Selector']; + + // pass new status + if( isset($_REQUEST['new']) ) $ret .= '&new='.$_REQUEST['new']; + + unset($m_var_list_update["cat"]); + return $ret; + break; + case "admin_icon": + if( $element->GetAttributeByName('fulltag') ) + { + $ret = "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 = "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)) + { + $TypeId = $type->Get("ItemType"); + $GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0; + $txt = "Get("CategoryId")."\" _SubCats=\"1\" "; + $txt .=" _ListType=\"category\" _CountCurrent=\"1\" _ItemType=\"$TypeId\" _GroupOnly=\"$GroupOnly\" />"; + $tag = new clsHtmlTag($txt); + $ret = $tag->Execute(); + } + 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
    +
      +
    • "Numerical": Show the decimal value +
    • "Bar": Show the HTML representing the relevance. Returns two HTML cells ≶td< with specified background colors +
    • "Graphical":Show image representing the relevance +
    + @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->Get("CachedNavbar"); + break; + case "cat_name": + return $this->Get("Name"); + break; + case "cat_desc": + return $this->Get("Description"); + 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("Name"); + 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")); + 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..
    \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("Name"))) + $names[] = $cat->Get("Name"); + + } + } + $nav = implode(">", $names); + $this->Set("CachedNavbar",$nav); + $this->Update(); + } + $res = explode(">",$this->Get("CachedNavbar")); + return $res; + } + + function UpdateCacheCounts() + { + global $objItemTypes; + + $CatId = $this->Get("CategoryId"); + + if($CatId>0) + { + //echo "Updating count for ".$this->Get("CachedNavbar")."
    \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'); + $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; + + function clsCatList() + { + global $m_var_list; + $this->clsItemCollection(); + $this->classname="clsCategory"; + $this->AdminSearchFields = array("Name","Description"); + $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; + + $cat = $attribs["_catid"]; + if(!is_numeric($cat)) + { + $cat = $this->CurrentCategoryID(); + } + if((int)$cat>0) + $c = $this->GetCategory($cat); + + if($attribs["_subcats"] && $cat>0) + { + $ParentWhere = "(ParentPath LIKE '".$c->Get("ParentPath")."%' AND ".$this->SourceTable.".CategoryId != $cat)"; + } + if($attribs["_today"]) + { + $today = mktime(0,0,0,date("m"),date("d"),date("Y")); + $TodayWhere = "(CreatedOn>=$today)"; + } + if($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."
    "; + + $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)); + } + } + + + 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 = ($this->Page-1) * $PerPage; + $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; + + 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) + { + global $objConfig, $m_var_list_update, $var_list_update, $var_list; + + if(!strlen($page)) + $page = GetIndexURL(); + + $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 = $page."?env=".BuildEnv(); + $o .= "<<"; + } + + + for($p=$StartPage;$p<=$EndPage;$p++) + { + if($p!=$this->Page) + { + $m_var_list_update["p"]=$p; + $href = $page."?env=".BuildEnv(); + $o .= " $p "; + } + else + { + $o .= "$p"; + } + } + if($EndPage<$NumPages && $EndPage>0) + { + $m_var_list_update["p"]=$this->Page+$PagesToList; + $next_url = $page."?env=".BuildEnv(); + $o .= " >>"; + } + 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 .= "<<"; + } + + 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 .= " $p "; + } + else + $o .= "$p"; + } + + if($this->Page < $NumPages) + $o .= ">>"; + + 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; + + $selector = isset($_REQUEST['Selector']) ? '&Selector='.$_REQUEST['Selector'] : ''; + $new = isset($_REQUEST['new']) ? '&new='.$_REQUEST['new'] : ''; + + $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 = "$cat_name"; } + else + $nav = "$cat_name"; + } + 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("Name"); + $m_var_list_update["cat"] = $root; + if($cat == $catid && !$LinkLeaf) + { + $nav[] = "".$cat_name.""; //href=\"browse.php?env=". BuildEnv() ."\" + } + else + { + if ($admin == 1) + { + $nav[] = "".$cat_name.""; + } + else + { + if(strlen($RootTemplate)) + { + $var_list_update["t"] = $RootTemplate; + } + else + { + $var_list_update["t"] = $target_template; + } + $nav[] = "".$cat_name.""; + } + } + } + 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[] = "".$cat_name.""; //href=\"browse.php?env=". BuildEnv() ."\" + } + else + { + if ($admin == 1) + { + $nav[] = "".$cat_name.""; + } + else + { + if(strlen($RootTemplate)) + { + $var_list_update["t"] = $RootTemplate; + } + else + $var_list_update["t"] = $target_template; + $nav[] = "".$cat_name.""; + } + } + + } + //echo " After $nav_unparsed
    \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("Name"); + + $m_var_list_update["cat"] = $catid; + if($catid==$modcat && strlen($ModTemplate)>0) + { + $t = $ModTemplate; + } + else + $t = $target_template; + if($cat == $catid && !$LinkLeaf) + { + $nav[] = "".$cat_name.""; + } + else + { + if ($admin == 1) + { + $nav[] = "".$cat_name.""; + } + else + { + $var_list_update["t"] = $t; + $nav[] = "".$cat_name.""; + unset($var_list_update["t"]); + } + } + unset($m_var_list_update["cat"]); + } + } + } + $nav = implode($separator, $nav); + } + return $nav; + } + + function &Add($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New, $Pop, + $Priority, $MetaKeywords,$MetaDesc) + { + global $objSession; + + $UserId = $objSession->Get("UserId"); + + $d = new clsCategory(NULL); + $d->tablename = $this->SourceTable; + if($d->UsingTempTable()) + $d->Set("CategoryId",-1); + $d->idfield = "CategoryId"; + $d->Set(array("ParentId", "Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem", + "NewItem","PopItem", "Priority", "MetaKeywords", "MetaDescription", "CreatedById"), + array($ParentId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $New, + $Pop, $Priority, $MetaKeywords,$MetaDesc, $UserId)); + + $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($CategoryId, $Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, + $NewItem, $Pop, $Priority, $MetaKeywords,$MetaDesc) + { + $d =& $this->GetCategory($CategoryId); + $d->Set(array("Name", "Description", "CreatedOn", "EditorsPick", "Status", "HotItem", + "NewItem", "PopItem", "Priority", "MetaKeywords","MetaDescription"), + array($Name, $Description, $CreatedOn, $EditorsPick, $Status, $Hot, $NewItem, + $Pop, $Priority, $MetaKeywords,$MetaDesc)); + $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
    \n"; + echo "
    ";print_r($ChildList); echo "
    "; + echo "Old Parent: $oldparent
    \n"; + echo "ID: $Id
    \n"; + */ + /* sanity checks */ + + if(!in_array($ParentTo,$ChildList) && $oldparent != $ParentTo && $oldparent != $Id && + $Id != $ParentTo) + { + $d->Set("ParentId", $ParentTo); + $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("Name"); + 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
    "; + $dest->Set("Name", $Name); + $Names = CategoryNameCount($ParentTo,$Name); + //echo "Names Count: ".count($Names)."
    "; + if(count($Names)>0) + { + $NameCount = count($Names); + $found = FALSE; + $NewName = "Copy of $Name"; + + if(!in_array($NewName,$Names)) + { + //echo "Matched on $NewName in:
    \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
    "; + $dest->Set("Name",$NewName); + } + + } + $dest->UnsetIdField(); + $dest->Set("CachedDescendantCatsQty",0); + $dest->Set("ResourceId",NULL); + $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) + { + global $objSession; + + $d =& $this->GetCategory($Id); + + if(is_object($d)) + { + if($d->Get("CategoryId")==$Id) + { + $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;$iGetItem($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(Name) 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(); + } + + $rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE CachedNavbar IS NULL or CachedNavBar=''"); + 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; + + $objPermList = new clsPermList(); + $edit_table = $objSession->GetEditTable($this->SourceTable); + + $sql = "SELECT * FROM $edit_table"; + $rs = $this->adodbConnection->Execute($sql); + + 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")); + } + + //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"); + + //$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]
    \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); +} +?> Index: trunk/kernel/include/modules.php =================================================================== diff -u -N -r553 -r642 --- trunk/kernel/include/modules.php (.../modules.php) (revision 553) +++ trunk/kernel/include/modules.php (.../modules.php) (revision 642) @@ -310,8 +310,7 @@ function admin_login() { global $objSession,$login_error, $objConfig,$g_Allow,$g_Deny; - - //echo "
    "; print_r($objSession); echo "
    "; +// echo "
    "; print_r($objSession); echo "
    "; if( GetVar('help_usage') == 'install' ) return true; Index: trunk/admin/category/addcategory.php =================================================================== diff -u -N -r521 -r642 --- trunk/admin/category/addcategory.php (.../addcategory.php) (revision 521) +++ trunk/admin/category/addcategory.php (.../addcategory.php) (revision 642) @@ -1,384 +1,385 @@ -Get("Site_Path"); -$admin = $objConfig->Get("AdminDirectory"); -if(!strlen($admin)) - $admin = "admin"; -$localURL=$rootURL."kernel/"; -$adminURL = $rootURL.$admin; -$imagesURL = $adminURL."/images"; -//$pathtolocal = $pathtoroot."in-news/"; - -require_once ($pathtoroot.$admin."/include/elements.php"); -require_once ($pathtoroot."kernel/admin/include/navmenu.php"); -//require_once ($pathtolocal."admin/include/navmenu.php"); -require_once($pathtoroot.$admin."/toolbar.php"); - -unset($objEditItems); - -if($_REQUEST['item']) -{ - // smulate like normal edit button pressed - $tmp_cat =& $objCatList->GetItemByField('ResourceId', $_REQUEST['item']); - $_POST['catlist'][] = $tmp_cat->UniqueId(); -} - -$objEditItems = new clsCatList(); -$objEditItems->SourceTable = $objSession->GetEditTable("Category"); -$objCustomFields = new clsCustomFieldList(1); -$objCustomDataList = new clsCustomDataList(); -$objRelList = new clsRelationshipList(); -$objImages = new clsImageList(); - -//Multiedit init -if ($_GET["new"] == 1) -{ - $c = new clsCategory(NULL); - $c->Set("CreatedOn", time()); - $c->Set("EndOn", time()); - $c->Set("ParentId",$objCatList->CurrentCategoryID()); - $c->Set("NewItem",2); //auto - $c->Set("Status",2); //pending - $en = 0; - $action = "m_add_category"; - $objCatList->CreateEmptyEditTable("CategoryId"); - $objRelList->CreateEmptyEditTable("RelationshipId"); - $objCustomDataList->CreateEmptyEditTable("CustomDataId"); - $objImages->CreateEmptyEditTable("ResourceId"); - - $TitleVerb = prompt_language("la_Text_Adding"); -} -else -{ - if(isset($_POST["catlist"])) - { - $cats = $_POST["catlist"]; - $objCatList->CopyToEditTable("CategoryId",$cats); - $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); - /* make a copy of the relationship records */ - $ids = $objEditItems->GetResourceIDList(); - $objRelList->CopyToEditTable("SourceId", $ids); - $objCustomDataList->CopyToEditTable("ResourceId",$ids); - $objImages->CopyToEditTable("ResourceId", $ids); - $c = $objEditItems->GetItemByIndex(0); - $itemcount=$objEditItems->NumItems(); - $en = 0; - } - else - { - if($_GET["item"]) - { - /*shortcut to edit link */ - $objCatList->CopyToEditTable("ResourceId",$_GET["item"]); - $backurl = $_GET["return"]; - } - - //Multiedit init - $en = (int)$_GET["en"]; - $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); - - //$ids = $objEditItems->GetResourceIDList(); - //$objRelList->CopyToEditTable("SourceId", $ids); - //$objCustomDataList->CopyToEditTable("ResourceId",$ids); - //$objImages->CopyToEditTable("ResourceId", $ids); - - $itemcount=$objEditItems->NumItems(); - $c = $objEditItems->GetItemByIndex($en); - } - - if($itemcount>1) - { - if ($en+1 == $itemcount) - $en_next = -1; - else - $en_next = $en+1; - - if ($en == 0) - $en_prev = -1; - else - $en_prev = $en-1; - } - - $action = "m_edit_category"; - $TitleVerb = prompt_language("la_Text_Editing"); -} - -$envar = "env=" . BuildEnv() . "&en=$en"; -$section = 'in-portal:editcategory_general'; - -if (strlen($c->Get("Name"))) - $editing_category_title = "'".$c->Get("Name")."' "; -else - $editing_category_title = ""; - -$title = $TitleVerb." ".prompt_language("la_Text_Category")." $editing_category_title- ".prompt_language("la_tab_General"); - -//$saveURL = $admin."/browse.php"; -$saveURL = $admin."/category/category_maint.php"; -$cancelURL = $admin."/".$objSession->GetVariable('ReturnScript'); - -//Display header -$sec = $objSections->GetSection($section); - -$objCatToolBar = new clsToolBar(); -$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('category','CatEditStatus','$saveURL',1,'');","tool_select.gif"); -$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('category','CatEditStatus','$cancelURL',2,'');","tool_cancel.gif"); - -if ( isset($en_prev) || isset($en_next) ) -{ - $url = $RootUrl.$admin."/category/addcategory.php"; - $StatusField = "CatEditStatus"; - $form = "category"; - MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevCategory','la_NextCategory'); -} - -int_header($objCatToolBar,NULL,$title); - -if ($objSession->GetVariable("HasChanges") == 1) { -?> - - - - -
    - -
    - - - - > - - - - Get("CategoryId") > 0 ) { ?> - > - - - - - - > - - - - - > - - - - - - - > - - - - - > - - - - - > - - - - - > - - - - - > - - - - - - - > - - - - - > - - - - -GetFieldUIList(TRUE); -if($CustomFieldUI->NumItems()>0) -{ - $objCustomDataList->SourceTable = $objSession->GetEditTable("CustomMetaData"); - if((int)$c->Get("ResourceId")>0) - { - $objCustomDataList->LoadResource($c->Get("ResourceId")); - } - $headings = $CustomFieldUI->GetHeadingList(); - //echo "
    ";print_r($objCustomFields); echo "
    "; - for($i=0;$i<=count($headings);$i++) - { - $h = $headings[$i]; - if(strlen($h)) - { - int_subsection_title(prompt_language($h)); - $Items = $CustomFieldUI->GetHeadingItems($h); - foreach($Items as $f) - { - $n = substr($f->name,1); - $cfield = $objCustomFields->GetItemByField("FieldName",$n,FALSE); - if(is_object($cfield)) - { - $cv = $objCustomDataList->GetDataItem($cfield->Get("CustomFieldId")); - if(is_object($cv)) - { - $f->default_value = $cv->Get("Value"); - } - } - print "\n"; - print " \n"; - print " "; - if(is_object($f->NextItem)) - { - $n = $f->NextItem; - print " "; - } - else - print " \n"; - print "\n"; - } - } - } -} -?> - "> - "> - - - - -
    - -
    - -
    Get("CategoryId"); ?> 
    - "> -
    -
    - - - -
    - -
    - Get("Status") == 1) echo "checked"; ?>> - Get("Status") == 2) echo "checked"; ?>> - Get("Status") == 0) echo "checked"; ?>> -  
    - Get("NewItem") == 2) echo "checked"; ?>> - Get("NewItem") == 1) echo "checked"; ?>> - Get("NewItem") == 0) echo "checked"; ?>> - -  
    - Get("EditorsPick") == 1) echo "checked"; ?>> -  
    "> 
    - "> - - - DBG: '.date('M d. Y H:i:s', $c->get('Modified') ); ?> -
    - "> -  
    - -  
    ".$f->GetPrompt()."".$f->ItemFormElement()."".$n->ItemFormElement()." 
    - - - -
    - -
    - - - - +Get("Site_Path"); +$admin = $objConfig->Get("AdminDirectory"); +if(!strlen($admin)) + $admin = "admin"; +$localURL=$rootURL."kernel/"; +$adminURL = $rootURL.$admin; +$imagesURL = $adminURL."/images"; +//$pathtolocal = $pathtoroot."in-news/"; + +require_once ($pathtoroot.$admin."/include/elements.php"); +require_once ($pathtoroot."kernel/admin/include/navmenu.php"); +//require_once ($pathtolocal."admin/include/navmenu.php"); +require_once($pathtoroot.$admin."/toolbar.php"); + +unset($objEditItems); + +if($_REQUEST['item']) +{ + // smulate like normal edit button pressed + $tmp_cat =& $objCatList->GetItemByField('ResourceId', $_REQUEST['item']); + $_POST['catlist'][] = $tmp_cat->UniqueId(); +} + +$objEditItems = new clsCatList(); +$objEditItems->SourceTable = $objSession->GetEditTable("Category"); +$objCustomFields = new clsCustomFieldList(1); +$objCustomDataList = new clsCustomDataList(); +$objRelList = new clsRelationshipList(); +$objImages = new clsImageList(); + +//Multiedit init +if ($_GET["new"] == 1) +{ + $c = new clsCategory(NULL); + $c->Set("CreatedOn", time()); + $c->Set("EndOn", time()); + $c->Set("ParentId",$objCatList->CurrentCategoryID()); + $c->Set("NewItem",2); //auto + $c->Set("Status",2); //pending + $en = 0; + $action = "m_add_category"; + $objCatList->CreateEmptyEditTable("CategoryId"); + $objRelList->CreateEmptyEditTable("RelationshipId"); + $objCustomDataList->CreateEmptyEditTable("CustomDataId"); + $objImages->CreateEmptyEditTable("ResourceId"); + + $TitleVerb = prompt_language("la_Text_Adding"); +} +else +{ + if(isset($_POST["catlist"])) + { + $cats = $_POST["catlist"]; + $objCatList->CopyToEditTable("CategoryId",$cats); + $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); + /* make a copy of the relationship records */ + $ids = $objEditItems->GetResourceIDList(); + $objRelList->CopyToEditTable("SourceId", $ids); + $objCustomDataList->CopyToEditTable("ResourceId",$ids); + $objImages->CopyToEditTable("ResourceId", $ids); + $c = $objEditItems->GetItemByIndex(0); + $itemcount=$objEditItems->NumItems(); + $en = 0; + } + else + { + if($_GET["item"]) + { + /*shortcut to edit link */ + $objCatList->CopyToEditTable("ResourceId",$_GET["item"]); + $backurl = $_GET["return"]; + } + + //Multiedit init + $en = (int)$_GET["en"]; + $objEditItems->Query_Item("SELECT * FROM ".$objEditItems->SourceTable); + + //$ids = $objEditItems->GetResourceIDList(); + //$objRelList->CopyToEditTable("SourceId", $ids); + //$objCustomDataList->CopyToEditTable("ResourceId",$ids); + //$objImages->CopyToEditTable("ResourceId", $ids); + + $itemcount=$objEditItems->NumItems(); + $c = $objEditItems->GetItemByIndex($en); + } + + if($itemcount>1) + { + if ($en+1 == $itemcount) + $en_next = -1; + else + $en_next = $en+1; + + if ($en == 0) + $en_prev = -1; + else + $en_prev = $en-1; + } + + $action = "m_edit_category"; + $TitleVerb = prompt_language("la_Text_Editing"); +} + +$envar = "env=" . BuildEnv() . "&en=$en"; +$section = 'in-portal:editcategory_general'; + +if (strlen($c->Get("Name"))) + $editing_category_title = "'".$c->Get("Name")."' "; +else + $editing_category_title = ""; + +$title = $TitleVerb." ".prompt_language("la_Text_Category")." $editing_category_title- ".prompt_language("la_tab_General"); + +//$saveURL = $admin."/browse.php"; +$saveURL = $admin."/category/category_maint.php"; +$cancelURL = $admin."/".$objSession->GetVariable('ReturnScript'); + +//Display header +$sec = $objSections->GetSection($section); + +$objCatToolBar = new clsToolBar(); +$objCatToolBar->Add("img_save", "la_Save","#","swap('img_save','toolbar/tool_select_f2.gif');", "swap('img_save', 'toolbar/tool_select.gif');","edit_submit('category','CatEditStatus','$saveURL',1,'');","tool_select.gif"); +$objCatToolBar->Add("img_cancel", "la_Cancel","#","swap('img_cancel','toolbar/tool_cancel_f2.gif');", "swap('img_cancel', 'toolbar/tool_cancel.gif');","edit_submit('category','CatEditStatus','$cancelURL',2,'');","tool_cancel.gif"); + +if ( isset($en_prev) || isset($en_next) ) +{ + $url = $RootUrl.$admin."/category/addcategory.php"; + $StatusField = "CatEditStatus"; + $form = "category"; + MultiEditButtons($objCatToolBar,$en_next,$en_prev,$form,$StatusField,$url,$sec->Get("OnClick"),'','la_PrevCategory','la_NextCategory'); +} + +int_header($objCatToolBar,NULL,$title); +$c->Data=inp_htmlize($c->Data); +if ($objSession->GetVariable("HasChanges") == 1) { +?> + + + + +
    + +
    + + + + > + + + + Get("CategoryId") > 0 ) { ?> + > + + + + + + > + + + + + > + + + + + + + > + + + + + > + + + + + > + + + + + > + + + + + > + + + + + + + > + + + + + > + + + + +GetFieldUIList(TRUE); +if($CustomFieldUI->NumItems()>0) +{ + $objCustomDataList->SourceTable = $objSession->GetEditTable("CustomMetaData"); + if((int)$c->Get("ResourceId")>0) + { + $objCustomDataList->LoadResource($c->Get("ResourceId")); + } + $headings = $CustomFieldUI->GetHeadingList(); + //echo "
    ";print_r($objCustomFields); echo "
    "; + for($i=0;$i<=count($headings);$i++) + { + $h = $headings[$i]; + if(strlen($h)) + { + int_subsection_title(prompt_language($h)); + $Items = $CustomFieldUI->GetHeadingItems($h); + foreach($Items as $f) + { + $n = substr($f->name,1); + + $cfield = $objCustomFields->GetItemByField("FieldName",$n,FALSE); + if(is_object($cfield)) + { + $cv = $objCustomDataList->GetDataItem($cfield->Get("CustomFieldId")); + if(is_object($cv)) + { + $f->default_value = $cv->Get("Value"); + } + } + print "\n"; + print " \n"; + print " "; + if(is_object($f->NextItem)) + { + $n = $f->NextItem; + print " "; + } + else + print " \n"; + print "\n"; + } + } + } +} +?> + "> + "> + + + + +
    + +
    + +
    Get("CategoryId"); ?> 
    + "> +
    +
    + + + +
    + +
    + Get("Status") == 1) echo "checked"; ?>> + Get("Status") == 2) echo "checked"; ?>> + Get("Status") == 0) echo "checked"; ?>> +  
    + Get("NewItem") == 2) echo "checked"; ?>> + Get("NewItem") == 1) echo "checked"; ?>> + Get("NewItem") == 0) echo "checked"; ?>> + +  
    + Get("EditorsPick") == 1) echo "checked"; ?>> +  
    "> 
    + "> + + + DBG: '.date('M d. Y H:i:s', $c->get('Modified') ); ?> +
    + "> +  
    + +  
    ".$f->GetPrompt()."".$f->ItemFormElement()."".$n->ItemFormElement()." 
    + + + +
    + +
    + + + + Index: trunk/admin/install/inportal_data.sql =================================================================== diff -u -N -r616 -r642 --- trunk/admin/install/inportal_data.sql (.../inportal_data.sql) (revision 616) +++ trunk/admin/install/inportal_data.sql (.../inportal_data.sql) (revision 642) @@ -1,282 +1,282 @@ -INSERT INTO ConfigurationAdmin VALUES ('Site_Name', 'la_Text_Website', 'la_config_website_name', 'text', '', '', 7, 1); -INSERT INTO ConfigurationAdmin VALUES ('Site_Path', 'la_Text_Website', 'la_config_web_address', 'text', '', '', 6, 1); -INSERT INTO ConfigurationAdmin VALUES ('Backup_Path', 'la_Text_BackupPath', 'la_config_backup_path', 'text', '', '', 6, 1); -INSERT INTO ConfigurationAdmin VALUES ('Domain_Detect', 'la_Text_Website', 'la_config_detect_domain', 'text', '', '', 8, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_Sortfield', 'la_Text_General', 'la_category_sortfield_prompt', 'select', '', 'Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0', 1, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_Sortorder', 'la_Text_General', 'la_category_sortfield_prompt', 'select', '', 'asc=la_common_ascending,desc=la_common_descending', 2, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_Sortfield2', 'la_Text_General', 'la_category_sortfield2_prompt', 'select', '', 'Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0', 3, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_Sortorder2', 'la_text_General', 'la_category_sortfield2_prompt', 'select', '', 'asc=la_common_ascending,desc=la_common_descending', 4, 1); -INSERT INTO ConfigurationAdmin VALUES ('Perpage_Category', 'la_Text_General', 'la_category_perpage_prompt', 'text', '', '', 5, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_DaysNew', 'la_Text_General', 'la_category_daysnew_prompt', 'text', '', '', 6, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_ShowPick', 'la_Text_General', 'la_category_showpick_prompt', 'checkbox', '', '', 7, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_MetaKey', 'la_Text_MetaInfo', 'la_category_metakey', 'text', '', '', 8, 1); -INSERT INTO ConfigurationAdmin VALUES ('Category_MetaDesc', 'la_Text_MetaInfo', 'la_category_metadesc', 'text', '', '', 9, 1); -INSERT INTO ConfigurationAdmin VALUES ('User_NewGroup', 'la_Text_General', 'la_users_new_group', 'select', NULL, '0=lu_none,SELECT GroupId as OptionName, Name as OptionValue FROM PortalGroup WHERE Enabled=1 AND Personal=0', 3, 1); -INSERT INTO ConfigurationAdmin VALUES ('User_GuestGroup', 'la_Text_General', 'la_users_guest_group', 'select', NULL, '0=lu_none,SELECT GroupId as OptionName, Name as OptionValue FROM PortalGroup WHERE Enabled=1 AND Personal=0', 4, 1); -INSERT INTO ConfigurationAdmin VALUES ('RootPass', 'la_Text_General', 'la_prompt_root_pass', 'password', NULL, NULL, 11, 0); -INSERT INTO ConfigurationAdmin VALUES ('RootPassVerify', 'la_Text_General', 'la_prompt_root_pass_verify', 'password', NULL, NULL, 11, 0); -INSERT INTO ConfigurationAdmin VALUES ('User_Allow_New', 'la_Text_General', 'la_users_allow_new', 'radio', '', '1=la_User_Instant,2=la_User_Not_Allowed,3=la_User_Upon_Approval', 1, 1); -INSERT INTO ConfigurationAdmin VALUES ('User_Password_Auto', 'la_Text_General', 'la_users_password_auto', 'checkbox', '', '', 10, 1); -INSERT INTO ConfigurationAdmin VALUES ('User_Votes_Deny', 'la_Text_Restrictions', 'la_users_votes_deny', 'text', '', '', 4, 1); -INSERT INTO ConfigurationAdmin VALUES ('User_Review_Deny', 'la_Text_Restrictions', 'la_users_review_deny', 'text', '', '', 5, 1); -INSERT INTO ConfigurationAdmin VALUES ('Server_Name', 'la_Text_Website', 'la_config_server_name', 'text', '', '', 4, 0); -INSERT INTO ConfigurationAdmin VALUES ('Config_Server_Time', 'la_Text_Date_Time_Settings', 'la_config_time_server', 'select', '', '1=la_m12,2=la_m11,3=la_m10,5=la_m9,6=la_m8,7=la_m7,8=la_m6,9=la_m5,10=la_m4,11=la_m3,12=la_m2,13=la_m1,14=la_m0,15=la_p1,16=la_p2,17=la_p3,18=la_p4,19=la_p5,20=la_p6,21=la_p7,22=la_p8,23=la_p9,24=la_p10,25=la_p11,26=la_p12,27=la_p13', 6, 1); -INSERT INTO ConfigurationAdmin VALUES ('Config_Site_Time', 'la_Text_Date_Time_Settings', 'la_config_site_zone', 'select', '', '1=la_m12,2=la_m11,3=la_m10,5=la_m9,6=la_m8,7=la_m7,8=la_m6,9=la_m5,10=la_m4,11=la_m3,12=la_m2,13=la_m1,14=la_m0,15=la_p1,16=la_p2,17=la_p3,18=la_p4,19=la_p5,20=la_p6,21=la_p7,22=la_p8,23=la_p9,24=la_p10,25=la_p11,26=la_p12,27=la_p13', 7, 1); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_Server', 'la_Text_smtp_server', 'la_prompt_mailserver', 'text', NULL, NULL, 10, 1); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_Port', 'la_Text_smtp_server', 'la_prompt_mailport', 'text', NULL, NULL, 11, 1); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_Authenticate', 'la_Text_smtp_server', 'la_prompt_mailauthenticate', 'checkbox', NULL, NULL, 12, 1); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_User', 'la_Text_smtp_server', 'la_prompt_smtp_user', 'text', NULL, NULL, 13, 1); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_Pass', 'la_Text_smtp_server', 'la_prompt_smtp_pass', 'text', NULL, NULL, 14, 1); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_SendHTML', 'la_Text_smtp_server', 'la_prompt_mailhtml', 'checkbox', NULL, NULL, 15, 0); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_DefaultHeaders', 'la_Text_smtp_server', 'la_prompt_smtpheaders', 'textarea', NULL, 'COLS=40 ROWS=5', 16, 0); -INSERT INTO ConfigurationAdmin VALUES ('Smtp_AdminMailFrom', 'la_Text_smtp_server', 'la_prompt_AdminMailFrom', 'text', NULL, NULL, 17, 1); -INSERT INTO ConfigurationAdmin VALUES ('Perpage_Category_Short', 'la_Text_General', 'la_category_perpage__short_prompt', 'text', '', '', 5, 1); -INSERT INTO ConfigurationAdmin VALUES ('CookieSessions', 'la_Text_Website', 'la_prompt_session_management', 'select', NULL, '0=lu_query_string,1=lu_cookies,2=lu_auto', 8, 1); -INSERT INTO ConfigurationAdmin VALUES ('SessionTimeout', 'la_Text_Website', 'la_prompt_session_timeout', 'text','', '', 9, 1); -INSERT INTO ConfigurationAdmin VALUES ('SystemTagCache', 'la_Text_Website', 'la_prompt_syscache_enable', 'checkbox', NULL, NULL, 10, 0); -INSERT INTO ConfigurationAdmin VALUES ('User_SubscriberGroup', 'la_Text_General', 'la_users_subscriber_group', 'select', NULL, '0=lu_none,SELECT GroupId as OptionName, Name as OptionValue FROM PortalGroup WHERE Enabled=1 AND Personal=0', 5, 1); -INSERT INTO ConfigurationAdmin VALUES ('Root_Name', 'la_Text_General', 'la_prompt_root_name', 'text', '', '', 8, 1); -INSERT INTO ConfigurationAdmin VALUES ('SocketBlockingMode', 'la_Text_Website', 'la_prompt_socket_blocking_mode', 'checkbox', NULL, NULL, 11, 0); -INSERT INTO ConfigurationAdmin VALUES ('Min_UserName', 'la_Text_General', 'la_text_min_username', 'text', '', '', 1, 0); -INSERT INTO ConfigurationAdmin VALUES ('Min_Password', 'la_Text_General', 'la_text_min_password', 'text', '', '', 2, 0); - -INSERT INTO ConfigurationValues VALUES ('Columns_Category', '2', 'In-Portal', 'Categories') -INSERT INTO ConfigurationValues VALUES ('DomainSelect','1','In-Portal','in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Site_Path', '/', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Perpage_Archive', '25', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('debug', '1', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('Perpage_User', '100', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('Perpage_LangEmail', '20', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('Default_FromAddr', '', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('email_replyto', '', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('email_footer', 'message footer goes here', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('Default_Theme', 'default', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Default_Language', 'English', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('SessionTimeout', '3600', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('User_SortOrder', 'asc', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Suggest_MinInterval', '3600', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('SubCat_ListCount', '3', 'inportal', '') -INSERT INTO ConfigurationValues VALUES ('Timeout_Rating', '3600', 'In-Portal', 'System') -INSERT INTO ConfigurationValues VALUES ('User_SortField', 'u.CreatedOn', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Perpage_Relations', '10', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Group_SortField', 'GroupName', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Group_SortOrder', 'asc', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Default_FromName', 'Webmaster', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Perpage_Category', '10', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_Sortfield', 'Name', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_Sortorder', 'asc', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('MetaKeywords', NULL, 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Relation_LV_Sortfield', 'ItemType', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('ampm_time', '1', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Perpage_Template', '10', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Perpage_Phrase', '40', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Perpage_Sessionlist', '20', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Category_Sortfield2', 'Description', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_Sortorder2', 'asc', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_DaysNew', '8', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_ShowPick', '', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_MetaKey', '', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_MetaDesc', '', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('MetaDescription', NULL, 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('User_NewGroup', '13', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('User_Allow_New', '3', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('User_Password_Auto', '0', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('User_Votes_Deny', '5', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('User_Review_Deny', '5', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('Config_Name', '', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Config_Company', '', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Config_Reg_Number', '', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Config_Website_Name', '', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Config_Web_Address', '', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Config_Server_Time', '14', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Config_Site_Time', '14', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Site_Name', 'In-Portal', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Backup_Path', '', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Perpage_Items', '20', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('GuestSessions', '1', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Smtp_Server', NULL, 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Smtp_Port', NULL, 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Smtp_User', NULL, 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Smtp_Pass', NULL, 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Smtp_SendHTML', '1', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Smtp_Authenticate', '0', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Perpage_Email', '10', 'In-Portal', '') -INSERT INTO ConfigurationValues VALUES ('Smtp_DefaultHeaders', 'X-Priority: 1\r\nX-MSMail-Priority: High\r\nX-Mailer: In-Portal', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Smtp_AdminMailFrom', 'portal@user.domain.name', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('Category_Highlight_OpenTag', '', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('Category_Highlight_CloseTag', '', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('User_GuestGroup', '14', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('RootPass', '', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('RootPassVerify', '', 'In-Portal:Users', 'in-portal:configure_users') -INSERT INTO ConfigurationValues VALUES ('Perpage_Category_Short', '3', 'In-Portal', 'in-portal:configure_categories') -INSERT INTO ConfigurationValues VALUES ('CookieSessions', '2', 'In-Portal', 'in-portal:configure_general') -INSERT INTO ConfigurationValues VALUES ('SearchRel_Increase_category', '30', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('SearchRel_Keyword_category', '90', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('SearchRel_Pop_category', '5', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('SearchRel_Rating_category', '5', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultIncrease', '30', 'In-Portal', 'inportal:configure_searchdefault'); -INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultKeyword', '80', 'In-Portal', 'SearchRel_DefaultKeyword'); -INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultPop', '10', 'In-Portal', 'inportal:configuration_searchdefault'); -INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultRating', '10', 'In-Portal', 'inportal:configure_searchdefault'); -INSERT INTO ConfigurationValues VALUES ('SystemTagCache', '0', 'In-Portal', 'in-portal:configure_general'); -INSERT INTO ConfigurationValues VALUES ('Root_Name', 'lu_rootcategory_name', 'In-Portal', 'in-portal:configure_categories'); -INSERT INTO ConfigurationValues VALUES ('User_SubscriberGroup', '12', 'In-Portal:Users', 'in-portal:configure_users'); -INSERT INTO ConfigurationValues VALUES ('SocketBlockingMode', '0', 'In-Portal', 'in-portal:configure_general'); -INSERT INTO ConfigurationValues VALUES ('Min_UserName', '3', 'In-Portal:Users', 'in-portal:configure_users'); -INSERT INTO ConfigurationValues VALUES ('Min_Password', '5', 'In-Portal:Users', 'in-portal:configure_users'); -INSERT INTO ConfigurationValues VALUES ('LinksValidation_LV_Sortfield', 'ValidationTime', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('CustomConfig_LV_Sortfield', 'FieldName', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Event_LV_SortField', 'Description', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Theme_LV_SortField', 'Name', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Template_LV_SortField', 'FileName', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Lang_LV_SortField', 'PackName', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Phrase_LV_SortField', 'Phrase', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('LangEmail_LV_SortField', 'Description', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('CustomData_LV_SortField', 'FieldName', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Summary_SortField', 'Module', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Session_SortField', 'UserName', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('SearchLog_SortField', 'Keyword', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_StatItem', '10', 'inportal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_Groups', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_Event', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_BanRules', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_SearchLog', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_LV_lang', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_LV_Themes', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_LV_Catlist', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_Reviews', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_Modules', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_Grouplist', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_Images', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('EmailsL_SortField', 'time_sent', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_EmailsL', '20', 'In-Portal', ''); -INSERT INTO ConfigurationValues VALUES ('Perpage_CustomData', '20', 'In-Portal', ''); - -INSERT INTO Events VALUES (30, 'USER.ADD', 1, 0, 'In-Portal:Users', 'la_event_user.add', 0) -INSERT INTO Events VALUES (32, 'USER.ADD', 2, 0, 'In-Portal:Users', 'la_event_user.add', 1) -INSERT INTO Events VALUES (31, 'USER.APPROVE', 1, 0, 'In-Portal:Users', 'la_event_user.approve', 0) -INSERT INTO Events VALUES (33, 'USER.APPROVE', 2, 0, 'In-Portal:Users', 'la_event_user.approve', 1) -INSERT INTO Events VALUES (34, 'USER.VALIDATE', 1, 0, 'In-Portal:Users', 'la_event_user.validate', 0) -INSERT INTO Events VALUES (35, 'USER.VALIDATE', 2, 0, 'In-Portal:Users', 'la_event_user.validate', 1) -INSERT INTO Events VALUES (36, 'USER.DENY', 1, 0, 'In-Portal:Users', 'la_event_user.deny', 0) -INSERT INTO Events VALUES (37, 'USER.DENY', 2, 0, 'In-Portal:Users', 'la_event_user.deny', 1) -INSERT INTO Events VALUES (38, 'USER.PSWD', 2, 0, 'In-Portal:Users', 'la_event_user.forgotpw', 1) -INSERT INTO Events VALUES (39, 'USER.PSWD', 1, 0, 'In-Portal:Users', 'la_event_user.forgotpw', 0) -INSERT INTO Events VALUES (45, 'USER.ADD.PENDING', 1, 0, 'In-Portal:Users', 'la_event_user.add.pending', 0) -INSERT INTO Events VALUES (47, 'CATEGORY.ADD', 1, 0, 'In-Portal:Category', 'la_event_category.add', 0) -INSERT INTO Events VALUES (48, 'CATEGORY.ADD.PENDING', 1, 0, 'In-Portal:Category', 'la_event_category.add.pending', 0) -INSERT INTO Events VALUES (49, 'CATEGORY.ADD.PENDING', 2, 0, 'In-Portal:Category', 'la_event_category.add.pending', 1) -INSERT INTO Events VALUES (50, 'CATEGORY.ADD', 2, 0, 'In-Portal:Category', 'la_event_category.add', 1) -INSERT INTO Events VALUES (51, 'CATEGORY.DELETE', 1, 0, 'In-Portal:Category', 'la_event_category_delete', 0) -INSERT INTO Events VALUES (52, 'CATEGORY.DELETE', 2, 0, 'In-Portal:Category', 'la_event_category_delete', 1) -INSERT INTO Events VALUES (53, 'CATEGORY.MODIFY', 1, 0, 'In-Portal:Category', 'la_event_category.modify', 0) -INSERT INTO Events VALUES (54, 'CATEGORY.MODIFY', 2, 0, 'In-Portal:Category', 'la_event_category.modify', 1) -INSERT INTO Events VALUES (56, 'CATEGORY.APPROVE', 1, 0, 'In-Portal:Category', 'la_event_category.approve', 0) -INSERT INTO Events VALUES (57, 'CATEGORY.APPROVE', 2, 0, 'In-Portal:Category', 'la_event_category.approve', 1) -INSERT INTO Events VALUES (58, 'CATEGORY.DENY', 1, 0, 'In-Portal:Category', 'la_event_category.deny', 0) -INSERT INTO Events VALUES (59, 'CATEGORY.DENY', 2, 0, 'In-Portal:Category', 'la_event_category.deny', 1) -INSERT INTO Events VALUES (60, 'USER.SUBSCRIBE', 1, 0, 'In-Portal:Users', 'la_event_user.subscribe', 0); -INSERT INTO Events VALUES (61, 'USER.SUBSCRIBE', 2, 0, 'In-Portal:Users', 'la_event_user.subscribe', 1); -INSERT INTO Events VALUES (62, 'USER.UNSUBSCRIBE', 1, 0, 'In-Portal:Users', 'la_event_user.unsubscribe', 0); -INSERT INTO Events VALUES (63, 'USER.UNSUBSCRIBE', 2, 0, 'In-Portal:Users', 'la_event_user.unsubscribe', 1); -INSERT INTO Events VALUES (64,'USER.SUGGEST', '1', '0', 'In-Portal:Users', 'la_event_user.suggest', '0'); -INSERT INTO Events VALUES (65,'USER.SUGGEST', '2', '0', 'In-Portal:Users', 'la_event_user.suggest', '1'); - -INSERT INTO IdGenerator VALUES ('100'); - -INSERT INTO ItemTypes VALUES (1, 'In-Portal', 'Category', 'Name', 'CreatedById', NULL, NULL, 'la_ItemTab_Categories', 1, 'admin/category/addcategory.php', 'clsCategory', 'Category'); -INSERT INTO ItemTypes VALUES (6, 'In-Portal', 'PortalUser', 'Login', '', NULL, NULL, '', 0, '', 'clsPortalUser', 'User'); - -INSERT INTO Modules (Name, Path, Var, Version, Loaded, LoadOrder, TemplatePath, RootCat, BuildDate) VALUES ('In-Portal', 'kernel/', 'm', '1.0.8', 1, 0, '', 0, '1054738405'); - -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.VIEW', 'lu_PermName_Category.View_desc', 'lu_PermName_Category.View_error', 'In-Portal'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.ADD', 'lu_PermName_Category.Add_desc', 'lu_PermName_Category.Add_error', 'In-Portal'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.DELETE', 'lu_PermName_Category.Delete_desc', 'lu_PermName_Category.Delete_error', 'In-Portal'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.ADD.PENDING', 'lu_PermName_Category.AddPending_desc', 'lu_PermName_Category.AddPending_error', 'In-Portal'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.MODIFY', 'lu_PermName_Category.Modify_desc', 'lu_PermName_Category.Modify_error', 'In-Portal'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('ADMIN', 'lu_PermName_Admin_desc', 'lu_PermName_Admin_error', 'Admin'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('LOGIN', 'lu_PermName_Login_desc', 'lu_PermName_Admin_error', 'Front'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('DEBUG.ITEM', 'lu_PermName_Debug.Item_desc', '', 'Admin'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('DEBUG.LIST', 'lu_PermName_Debug.List_desc', '', 'Admin'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('DEBUG.INFO', 'lu_PermName_Debug.Info_desc', '', 'Admin'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('PROFILE.MODIFY', 'lu_PermName_Profile.Modify_desc', '', 'Admin'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('SHOWLANG', 'lu_PermName_ShowLang_desc', '', 'Admin'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('FAVORITES', 'lu_PermName_favorites_desc', 'lu_PermName_favorites_error', 'In-Portal'); -INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('SYSTEM_ACCESS.READONLY', 'la_PermName_SystemAccess.ReadOnly_desc', 'la_PermName_SystemAccess.ReadOnly_error', 'Admin'); - -INSERT INTO PortalGroup VALUES (13, 'Member', '', '1054738682', 0, 0, 1, 13); -INSERT INTO PortalGroup VALUES (12, 'Subscribers', '', '1054738670', 0, 0, 1, 12); -INSERT INTO PortalGroup VALUES (14, 'Guest', 'Guest User', '0', 1, 0, 1, 14); -INSERT INTO PortalGroup VALUES (11, 'admin', '', '1054738405', 0, 0, 1, 11); - -INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('LOGIN', 13, 1, 1, 0); -INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('LOGIN', 11, 1, 1, 0); -INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('LOGIN', 12, 1, 1, 0); -INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('ADMIN', 11, 1, 1, 0); - -INSERT INTO SearchConfig VALUES ('Category', 'NewItem', 0, 1, 'lu_fielddesc_category_newitem', 'lu_field_newitem', 'In-Portal', 'la_Text_Category', 18, 80, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'PopItem', 0, 1, 'lu_fielddesc_category_popitem', 'lu_field_popitem', 'In-Portal', 'la_Text_Category', 19, 81, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'HotItem', 0, 1, 'lu_fielddesc_category_hotitem', 'lu_field_hotitem', 'In-Portal', 'la_Text_Category', 17, 79, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'MetaDescription', 0, 1, 'lu_fielddesc_category_metadescription', 'lu_field_metadescription', 'In-Portal', 'la_Text_Category', 16, 78, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'ParentPath', 0, 1, 'lu_fielddesc_category_parentpath', 'lu_field_parentpath', 'In-Portal', 'la_Text_Category', 15, 77, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'ResourceId', 0, 1, 'lu_fielddesc_category_resourceid', 'lu_field_resourceid', 'In-Portal', 'la_Text_Category', 14, 76, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'CreatedById', 0, 1, 'lu_fielddesc_category_createdbyid', 'lu_field_createdbyid', 'In-Portal', 'la_Text_Category', 13, 75, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'CachedNavbar', 0, 1, 'lu_fielddesc_category_cachednavbar', 'lu_field_cachednavbar', 'In-Portal', 'la_Text_Category', 12, 74, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'CachedDescendantCatsQty', 0, 1, 'lu_fielddesc_category_cacheddescendantcatsqty', 'lu_field_cacheddescendantcatsqty', 'In-Portal', 'la_Text_Category', 11, 73, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'MetaKeywords', 0, 1, 'lu_fielddesc_category_metakeywords', 'lu_field_metakeywords', 'In-Portal', 'la_Text_Category', 10, 72, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'Priority', 0, 1, 'lu_fielddesc_category_priority', 'lu_field_priority', 'In-Portal', 'la_Text_Category', 9, 71, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'Status', 0, 1, 'lu_fielddesc_category_status', 'lu_field_status', 'In-Portal', 'la_Text_Category', 7, 69, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'EditorsPick', 0, 1, 'lu_fielddesc_category_editorspick', 'lu_field_editorspick', 'In-Portal', 'la_Text_Category', 6, 68, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'CreatedOn', 0, 1, 'lu_fielddesc_category_createdon', 'lu_field_createdon', 'In-Portal', 'la_Text_Category', 5, 67, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'Description', 1, 1, 'lu_fielddesc_category_description', 'lu_field_description', 'In-Portal', 'la_Text_Category', 4, 66, 2, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'Name', 1, 1, 'lu_fielddesc_category_name', 'lu_field_name', 'In-Portal', 'la_Text_Category', 3, 65, 2, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'ParentId', 0, 1, 'lu_fielddesc_category_parentid', 'lu_field_parentid', 'In-Portal', 'la_Text_Category', 2, 64, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'CategoryId', 0, 1, 'lu_fielddesc_category_categoryid', 'lu_field_categoryid', 'In-Portal', 'la_Text_Category', 0, 62, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'Modified', 0, 1, 'lu_fielddesc_category_modified', 'lu_field_modified', 'In-Portal', 'la_Text_Category', 20, 82, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('Category', 'ModifiedById', 0, 1, 'lu_fielddesc_category_modifiedbyid', 'lu_field_modifiedbyid', 'In-Portal', 'la_Text_Category', 21, 83, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'PortalUserId', 0, 0, 'lu_fielddesc_user_portaluserid', 'lu_field_portaluserid', 'In-Portal', 'la_text_user', 0, 173, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Login', 0, 0, 'lu_fielddesc_user_login', 'lu_field_login', 'In-Portal', 'la_text_user', 1, 174, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Password', 0, 0, 'lu_fielddesc_user_password', 'lu_field_password', 'In-Portal', 'la_text_user', 2, 175, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'tz', 0, 0, 'lu_fielddesc_user_tz', 'lu_field_tz', 'In-Portal', 'la_text_user', 17, 190, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'dob', 0, 0, 'lu_fielddesc_user_dob', 'lu_field_dob', 'In-Portal', 'la_text_user', 16, 189, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Modified', 0, 0, 'lu_fielddesc_user_modified', 'lu_field_modified', 'In-Portal', 'la_text_user', 15, 188, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Status', 0, 0, 'lu_fielddesc_user_status', 'lu_field_status', 'In-Portal', 'la_text_user', 14, 187, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'ResourceId', 0, 0, 'lu_fielddesc_user_resourceid', 'lu_field_resourceid', 'In-Portal', 'la_text_user', 13, 186, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Country', 0, 0, 'lu_fielddesc_user_country', 'lu_field_country', 'In-Portal', 'la_text_user', 12, 185, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Zip', 0, 0, 'lu_fielddesc_user_zip', 'lu_field_zip', 'In-Portal', 'la_text_user', 11, 184, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'State', 0, 0, 'lu_fielddesc_user_state', 'lu_field_state', 'In-Portal', 'la_text_user', 10, 183, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'City', 0, 0, 'lu_fielddesc_user_city', 'lu_field_city', 'In-Portal', 'la_text_user', 9, 182, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Street', 0, 0, 'lu_fielddesc_user_street', 'lu_field_street', 'In-Portal', 'la_text_user', 8, 181, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Phone', 0, 0, 'lu_fielddesc_user_phone', 'lu_field_phone', 'In-Portal', 'la_text_user', 7, 180, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'CreatedOn', 0, 0, 'lu_fielddesc_user_createdon', 'lu_field_createdon', 'In-Portal', 'la_text_user', 6, 179, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'Email', 0, 0, 'lu_fielddesc_user_email', 'lu_field_email', 'In-Portal', 'la_text_user', 5, 178, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'LastName', 0, 0, 'lu_fielddesc_user_lastname', 'lu_field_lastname', 'In-Portal', 'la_text_user', 4, 177, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); -INSERT INTO SearchConfig VALUES ('PortalUser', 'FirstName', 0, 0, 'lu_fielddesc_user_firstname', 'lu_field_firstname', 'In-Portal', 'la_text_user', 3, 176, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); - -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT count(*) FROM <%prefix%>Category WHERE Status=1 ', NULL, 'la_prompt_ActiveCategories', '0', '1'); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT count(*) FROM <%prefix%>PortalUser WHERE Status=1 ', NULL, 'la_prompt_ActiveUsers', '0', '1'); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT count(*) FROM <%prefix%>UserSession', NULL, 'la_prompt_CurrentSessions', '0', '1'); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) as CategoryCount FROM <%prefix%>Category', NULL, 'la_prompt_TotalCategories', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS ActiveCategories FROM <%prefix%>Category WHERE Status = 1', NULL, 'la_prompt_ActiveCategories', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS PendingCategories FROM <%prefix%>Category WHERE Status = 2', NULL, 'la_prompt_PendingCategories', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS DisabledCategories FROM <%prefix%>Category WHERE Status = 0', NULL, 'la_prompt_DisabledCategories', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS NewCategories FROM <%prefix%>Category WHERE (NewItem = 1) OR ( (UNIX_TIMESTAMP() - CreatedOn) <= <%m:config name="Category_DaysNew"%>*86400 AND (NewItem = 2) )', NULL, 'la_prompt_NewCategories', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) FROM <%prefix%>Category WHERE EditorsPick = 1', NULL, 'la_prompt_CategoryEditorsPick', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT <%m:post_format field="MAX(CreatedOn)" type="date"%> FROM <%prefix%>Category', NULL, 'la_prompt_NewestCategoryDate', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT <%m:post_format field="MAX(Modified)" type="date"%> FROM <%prefix%>Category', NULL, 'la_prompt_LastCategoryUpdate', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS TotalUsers FROM <%prefix%>PortalUser', NULL, 'la_prompt_TopicsUsers', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS ActiveUsers FROM <%prefix%>PortalUser WHERE Status = 1', NULL, 'la_prompt_UsersActive', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS PendingUsers FROM <%prefix%>PortalUser WHERE Status = 2', NULL, 'la_prompt_UsersPending', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS DisabledUsers FROM <%prefix%>PortalUser WHERE Status = 0', NULL, 'la_prompt_UsersDisabled', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT <%m:post_format field="MAX(CreatedOn)" type="date"%> FROM <%prefix%>PortalUser', NULL, 'la_prompt_NewestUserDate', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT( DISTINCT LOWER( Country ) ) FROM <%prefix%>PortalUser WHERE LENGTH(Country) > 0', NULL, 'la_prompt_UsersUniqueCountries', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT( DISTINCT LOWER( State ) ) FROM <%prefix%>PortalUser WHERE LENGTH(State) > 0', NULL, 'la_prompt_UsersUniqueStates', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS TotalUserGroups FROM <%prefix%>PortalGroup', NULL, 'la_prompt_TotalUserGroups', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS BannedUsers FROM <%prefix%>PortalUser WHERE IsBanned = 1', NULL, 'la_prompt_BannedUsers', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS NonExipedSessions FROM <%prefix%>UserSession WHERE Status = 1', NULL, 'la_prompt_NonExpiredSessions', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS ThemeCount FROM <%prefix%>Theme', NULL, 'la_prompt_ThemeCount', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS RegionsCount FROM <%prefix%>Language', NULL, 'la_prompt_RegionsCount', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', '<%m:sql_action sql="SHOW+TABLES" action="COUNT" field="*"%>', NULL, 'la_prompt_TablesCount', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', '<%m:sql_action sql="SHOW+TABLE+STATUS" action="SUM" field="Rows"%>', NULL, 'la_prompt_RecordsCount', 0, 2); -INSERT INTO StatItem VALUES (0, 'In-Portal', '<%m:custom_action sql="empty" action="SysFileSize"%>', NULL, 'la_prompt_SystemFileSize', 0, 2); +INSERT INTO ConfigurationAdmin VALUES ('Site_Name', 'la_Text_Website', 'la_config_website_name', 'text', '', '', 7, 1); +INSERT INTO ConfigurationAdmin VALUES ('Site_Path', 'la_Text_Website', 'la_config_web_address', 'text', '', '', 6, 1); +INSERT INTO ConfigurationAdmin VALUES ('Backup_Path', 'la_Text_BackupPath', 'la_config_backup_path', 'text', '', '', 6, 1); +INSERT INTO ConfigurationAdmin VALUES ('Domain_Detect', 'la_Text_Website', 'la_config_detect_domain', 'text', '', '', 8, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_Sortfield', 'la_Text_General', 'la_category_sortfield_prompt', 'select', '', 'Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0', 1, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_Sortorder', 'la_Text_General', 'la_category_sortfield_prompt', 'select', '', 'asc=la_common_ascending,desc=la_common_descending', 2, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_Sortfield2', 'la_Text_General', 'la_category_sortfield2_prompt', 'select', '', 'Name=la_Category_Name,Description=la_Category_Description,CreatedOn=la_Category_Date,EditorsPick=la_Category_Pick,Pop=la_Category_Pop,SELECT FieldLabel as OptionName, FieldName as OptionValue FROM CustomField WHERE Type=0', 3, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_Sortorder2', 'la_text_General', 'la_category_sortfield2_prompt', 'select', '', 'asc=la_common_ascending,desc=la_common_descending', 4, 1); +INSERT INTO ConfigurationAdmin VALUES ('Perpage_Category', 'la_Text_General', 'la_category_perpage_prompt', 'text', '', '', 5, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_DaysNew', 'la_Text_General', 'la_category_daysnew_prompt', 'text', '', '', 6, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_ShowPick', 'la_Text_General', 'la_category_showpick_prompt', 'checkbox', '', '', 7, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_MetaKey', 'la_Text_MetaInfo', 'la_category_metakey', 'text', '', '', 8, 1); +INSERT INTO ConfigurationAdmin VALUES ('Category_MetaDesc', 'la_Text_MetaInfo', 'la_category_metadesc', 'text', '', '', 9, 1); +INSERT INTO ConfigurationAdmin VALUES ('User_NewGroup', 'la_Text_General', 'la_users_new_group', 'select', NULL, '0=lu_none,SELECT GroupId as OptionName, Name as OptionValue FROM PortalGroup WHERE Enabled=1 AND Personal=0', 3, 1); +INSERT INTO ConfigurationAdmin VALUES ('User_GuestGroup', 'la_Text_General', 'la_users_guest_group', 'select', NULL, '0=lu_none,SELECT GroupId as OptionName, Name as OptionValue FROM PortalGroup WHERE Enabled=1 AND Personal=0', 4, 1); +INSERT INTO ConfigurationAdmin VALUES ('RootPass', 'la_Text_General', 'la_prompt_root_pass', 'password', NULL, NULL, 11, 0); +INSERT INTO ConfigurationAdmin VALUES ('RootPassVerify', 'la_Text_General', 'la_prompt_root_pass_verify', 'password', NULL, NULL, 11, 0); +INSERT INTO ConfigurationAdmin VALUES ('User_Allow_New', 'la_Text_General', 'la_users_allow_new', 'radio', '', '1=la_User_Instant,2=la_User_Not_Allowed,3=la_User_Upon_Approval', 1, 1); +INSERT INTO ConfigurationAdmin VALUES ('User_Password_Auto', 'la_Text_General', 'la_users_password_auto', 'checkbox', '', '', 10, 1); +INSERT INTO ConfigurationAdmin VALUES ('User_Votes_Deny', 'la_Text_Restrictions', 'la_users_votes_deny', 'text', '', '', 4, 1); +INSERT INTO ConfigurationAdmin VALUES ('User_Review_Deny', 'la_Text_Restrictions', 'la_users_review_deny', 'text', '', '', 5, 1); +INSERT INTO ConfigurationAdmin VALUES ('Server_Name', 'la_Text_Website', 'la_config_server_name', 'text', '', '', 4, 0); +INSERT INTO ConfigurationAdmin VALUES ('Config_Server_Time', 'la_Text_Date_Time_Settings', 'la_config_time_server', 'select', '', '1=la_m12,2=la_m11,3=la_m10,5=la_m9,6=la_m8,7=la_m7,8=la_m6,9=la_m5,10=la_m4,11=la_m3,12=la_m2,13=la_m1,14=la_m0,15=la_p1,16=la_p2,17=la_p3,18=la_p4,19=la_p5,20=la_p6,21=la_p7,22=la_p8,23=la_p9,24=la_p10,25=la_p11,26=la_p12,27=la_p13', 6, 1); +INSERT INTO ConfigurationAdmin VALUES ('Config_Site_Time', 'la_Text_Date_Time_Settings', 'la_config_site_zone', 'select', '', '1=la_m12,2=la_m11,3=la_m10,5=la_m9,6=la_m8,7=la_m7,8=la_m6,9=la_m5,10=la_m4,11=la_m3,12=la_m2,13=la_m1,14=la_m0,15=la_p1,16=la_p2,17=la_p3,18=la_p4,19=la_p5,20=la_p6,21=la_p7,22=la_p8,23=la_p9,24=la_p10,25=la_p11,26=la_p12,27=la_p13', 7, 1); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_Server', 'la_Text_smtp_server', 'la_prompt_mailserver', 'text', NULL, NULL, 10, 1); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_Port', 'la_Text_smtp_server', 'la_prompt_mailport', 'text', NULL, NULL, 11, 1); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_Authenticate', 'la_Text_smtp_server', 'la_prompt_mailauthenticate', 'checkbox', NULL, NULL, 12, 1); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_User', 'la_Text_smtp_server', 'la_prompt_smtp_user', 'text', NULL, NULL, 13, 1); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_Pass', 'la_Text_smtp_server', 'la_prompt_smtp_pass', 'text', NULL, NULL, 14, 1); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_SendHTML', 'la_Text_smtp_server', 'la_prompt_mailhtml', 'checkbox', NULL, NULL, 15, 0); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_DefaultHeaders', 'la_Text_smtp_server', 'la_prompt_smtpheaders', 'textarea', NULL, 'COLS=40 ROWS=5', 16, 0); +INSERT INTO ConfigurationAdmin VALUES ('Smtp_AdminMailFrom', 'la_Text_smtp_server', 'la_prompt_AdminMailFrom', 'text', NULL, NULL, 17, 1); +INSERT INTO ConfigurationAdmin VALUES ('Perpage_Category_Short', 'la_Text_General', 'la_category_perpage__short_prompt', 'text', '', '', 5, 1); +INSERT INTO ConfigurationAdmin VALUES ('CookieSessions', 'la_Text_Website', 'la_prompt_session_management', 'select', NULL, '0=lu_query_string,1=lu_cookies,2=lu_auto', 8, 1); +INSERT INTO ConfigurationAdmin VALUES ('SessionTimeout', 'la_Text_Website', 'la_prompt_session_timeout', 'text','', '', 9, 1); +INSERT INTO ConfigurationAdmin VALUES ('SystemTagCache', 'la_Text_Website', 'la_prompt_syscache_enable', 'checkbox', NULL, NULL, 10, 0); +INSERT INTO ConfigurationAdmin VALUES ('User_SubscriberGroup', 'la_Text_General', 'la_users_subscriber_group', 'select', NULL, '0=lu_none,SELECT GroupId as OptionName, Name as OptionValue FROM PortalGroup WHERE Enabled=1 AND Personal=0', 5, 1); +INSERT INTO ConfigurationAdmin VALUES ('Root_Name', 'la_Text_General', 'la_prompt_root_name', 'text', '', '', 8, 1); +INSERT INTO ConfigurationAdmin VALUES ('SocketBlockingMode', 'la_Text_Website', 'la_prompt_socket_blocking_mode', 'checkbox', NULL, NULL, 11, 0); +INSERT INTO ConfigurationAdmin VALUES ('Min_UserName', 'la_Text_General', 'la_text_min_username', 'text', '', '', 1, 0); +INSERT INTO ConfigurationAdmin VALUES ('Min_Password', 'la_Text_General', 'la_text_min_password', 'text', '', '', 2, 0); + +INSERT INTO ConfigurationValues VALUES ('Columns_Category', '2', 'In-Portal', 'Categories') +INSERT INTO ConfigurationValues VALUES ('DomainSelect','1','In-Portal','in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Site_Path', '/', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Perpage_Archive', '25', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('debug', '1', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('Perpage_User', '100', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('Perpage_LangEmail', '20', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('Default_FromAddr', '', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('email_replyto', '', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('email_footer', 'message footer goes here', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('Default_Theme', 'default', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Default_Language', 'English', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('SessionTimeout', '3600', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('User_SortOrder', 'asc', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Suggest_MinInterval', '3600', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('SubCat_ListCount', '3', 'inportal', '') +INSERT INTO ConfigurationValues VALUES ('Timeout_Rating', '3600', 'In-Portal', 'System') +INSERT INTO ConfigurationValues VALUES ('User_SortField', 'u.CreatedOn', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Perpage_Relations', '10', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Group_SortField', 'GroupName', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Group_SortOrder', 'asc', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Default_FromName', 'Webmaster', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Perpage_Category', '10', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_Sortfield', 'Name', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_Sortorder', 'asc', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('MetaKeywords', NULL, 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Relation_LV_Sortfield', 'ItemType', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('ampm_time', '1', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Perpage_Template', '10', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Perpage_Phrase', '40', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Perpage_Sessionlist', '20', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Category_Sortfield2', 'Description', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_Sortorder2', 'asc', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_DaysNew', '8', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_ShowPick', '', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_MetaKey', '', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_MetaDesc', '', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('MetaDescription', NULL, 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('User_NewGroup', '13', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('User_Allow_New', '3', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('User_Password_Auto', '0', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('User_Votes_Deny', '5', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('User_Review_Deny', '5', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('Config_Name', '', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Config_Company', '', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Config_Reg_Number', '', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Config_Website_Name', '', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Config_Web_Address', '', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Config_Server_Time', '14', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Config_Site_Time', '14', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Site_Name', 'In-Portal', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Backup_Path', '', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Perpage_Items', '20', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('GuestSessions', '1', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Smtp_Server', NULL, 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Smtp_Port', NULL, 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Smtp_User', NULL, 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Smtp_Pass', NULL, 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Smtp_SendHTML', '1', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Smtp_Authenticate', '0', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Perpage_Email', '10', 'In-Portal', '') +INSERT INTO ConfigurationValues VALUES ('Smtp_DefaultHeaders', 'X-Priority: 1\r\nX-MSMail-Priority: High\r\nX-Mailer: In-Portal', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Smtp_AdminMailFrom', 'portal@user.domain.name', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('Category_Highlight_OpenTag', '', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('Category_Highlight_CloseTag', '', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('User_GuestGroup', '14', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('RootPass', '', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('RootPassVerify', '', 'In-Portal:Users', 'in-portal:configure_users') +INSERT INTO ConfigurationValues VALUES ('Perpage_Category_Short', '3', 'In-Portal', 'in-portal:configure_categories') +INSERT INTO ConfigurationValues VALUES ('CookieSessions', '2', 'In-Portal', 'in-portal:configure_general') +INSERT INTO ConfigurationValues VALUES ('SearchRel_Increase_category', '30', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('SearchRel_Keyword_category', '90', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('SearchRel_Pop_category', '5', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('SearchRel_Rating_category', '5', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultIncrease', '30', 'In-Portal', 'inportal:configure_searchdefault'); +INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultKeyword', '80', 'In-Portal', 'SearchRel_DefaultKeyword'); +INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultPop', '10', 'In-Portal', 'inportal:configuration_searchdefault'); +INSERT INTO ConfigurationValues VALUES ('SearchRel_DefaultRating', '10', 'In-Portal', 'inportal:configure_searchdefault'); +INSERT INTO ConfigurationValues VALUES ('SystemTagCache', '0', 'In-Portal', 'in-portal:configure_general'); +INSERT INTO ConfigurationValues VALUES ('Root_Name', 'lu_rootcategory_name', 'In-Portal', 'in-portal:configure_categories'); +INSERT INTO ConfigurationValues VALUES ('User_SubscriberGroup', '12', 'In-Portal:Users', 'in-portal:configure_users'); +INSERT INTO ConfigurationValues VALUES ('SocketBlockingMode', '0', 'In-Portal', 'in-portal:configure_general'); +INSERT INTO ConfigurationValues VALUES ('Min_UserName', '3', 'In-Portal:Users', 'in-portal:configure_users'); +INSERT INTO ConfigurationValues VALUES ('Min_Password', '5', 'In-Portal:Users', 'in-portal:configure_users'); +INSERT INTO ConfigurationValues VALUES ('LinksValidation_LV_Sortfield', 'ValidationTime', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('CustomConfig_LV_Sortfield', 'FieldName', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Event_LV_SortField', 'Description', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Theme_LV_SortField', 'Name', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Template_LV_SortField', 'FileName', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Lang_LV_SortField', 'PackName', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Phrase_LV_SortField', 'Phrase', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('LangEmail_LV_SortField', 'Description', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('CustomData_LV_SortField', 'FieldName', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Summary_SortField', 'Module', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Session_SortField', 'UserName', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('SearchLog_SortField', 'Keyword', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_StatItem', '10', 'inportal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_Groups', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_Event', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_BanRules', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_SearchLog', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_LV_lang', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_LV_Themes', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_LV_Catlist', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_Reviews', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_Modules', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_Grouplist', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_Images', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('EmailsL_SortField', 'time_sent', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_EmailsL', '20', 'In-Portal', ''); +INSERT INTO ConfigurationValues VALUES ('Perpage_CustomData', '20', 'In-Portal', ''); + +INSERT INTO Events VALUES (30, 'USER.ADD', 1, 0, 'In-Portal:Users', 'la_event_user.add', 0) +INSERT INTO Events VALUES (32, 'USER.ADD', 2, 0, 'In-Portal:Users', 'la_event_user.add', 1) +INSERT INTO Events VALUES (31, 'USER.APPROVE', 1, 0, 'In-Portal:Users', 'la_event_user.approve', 0) +INSERT INTO Events VALUES (33, 'USER.APPROVE', 2, 0, 'In-Portal:Users', 'la_event_user.approve', 1) +INSERT INTO Events VALUES (34, 'USER.VALIDATE', 1, 0, 'In-Portal:Users', 'la_event_user.validate', 0) +INSERT INTO Events VALUES (35, 'USER.VALIDATE', 2, 0, 'In-Portal:Users', 'la_event_user.validate', 1) +INSERT INTO Events VALUES (36, 'USER.DENY', 1, 0, 'In-Portal:Users', 'la_event_user.deny', 0) +INSERT INTO Events VALUES (37, 'USER.DENY', 2, 0, 'In-Portal:Users', 'la_event_user.deny', 1) +INSERT INTO Events VALUES (38, 'USER.PSWD', 2, 0, 'In-Portal:Users', 'la_event_user.forgotpw', 1) +INSERT INTO Events VALUES (39, 'USER.PSWD', 1, 0, 'In-Portal:Users', 'la_event_user.forgotpw', 0) +INSERT INTO Events VALUES (45, 'USER.ADD.PENDING', 1, 0, 'In-Portal:Users', 'la_event_user.add.pending', 0) +INSERT INTO Events VALUES (47, 'CATEGORY.ADD', 1, 0, 'In-Portal:Category', 'la_event_category.add', 0) +INSERT INTO Events VALUES (48, 'CATEGORY.ADD.PENDING', 1, 0, 'In-Portal:Category', 'la_event_category.add.pending', 0) +INSERT INTO Events VALUES (49, 'CATEGORY.ADD.PENDING', 2, 0, 'In-Portal:Category', 'la_event_category.add.pending', 1) +INSERT INTO Events VALUES (50, 'CATEGORY.ADD', 2, 0, 'In-Portal:Category', 'la_event_category.add', 1) +INSERT INTO Events VALUES (51, 'CATEGORY.DELETE', 1, 0, 'In-Portal:Category', 'la_event_category_delete', 0) +INSERT INTO Events VALUES (52, 'CATEGORY.DELETE', 2, 0, 'In-Portal:Category', 'la_event_category_delete', 1) +INSERT INTO Events VALUES (53, 'CATEGORY.MODIFY', 1, 0, 'In-Portal:Category', 'la_event_category.modify', 0) +INSERT INTO Events VALUES (54, 'CATEGORY.MODIFY', 2, 0, 'In-Portal:Category', 'la_event_category.modify', 1) +INSERT INTO Events VALUES (56, 'CATEGORY.APPROVE', 1, 0, 'In-Portal:Category', 'la_event_category.approve', 0) +INSERT INTO Events VALUES (57, 'CATEGORY.APPROVE', 2, 0, 'In-Portal:Category', 'la_event_category.approve', 1) +INSERT INTO Events VALUES (58, 'CATEGORY.DENY', 1, 0, 'In-Portal:Category', 'la_event_category.deny', 0) +INSERT INTO Events VALUES (59, 'CATEGORY.DENY', 2, 0, 'In-Portal:Category', 'la_event_category.deny', 1) +INSERT INTO Events VALUES (60, 'USER.SUBSCRIBE', 1, 0, 'In-Portal:Users', 'la_event_user.subscribe', 0); +INSERT INTO Events VALUES (61, 'USER.SUBSCRIBE', 2, 0, 'In-Portal:Users', 'la_event_user.subscribe', 1); +INSERT INTO Events VALUES (62, 'USER.UNSUBSCRIBE', 1, 0, 'In-Portal:Users', 'la_event_user.unsubscribe', 0); +INSERT INTO Events VALUES (63, 'USER.UNSUBSCRIBE', 2, 0, 'In-Portal:Users', 'la_event_user.unsubscribe', 1); +INSERT INTO Events VALUES (64,'USER.SUGGEST', '1', '0', 'In-Portal:Users', 'la_event_user.suggest', '0'); +INSERT INTO Events VALUES (65,'USER.SUGGEST', '2', '0', 'In-Portal:Users', 'la_event_user.suggest', '1'); + +INSERT INTO IdGenerator VALUES ('100'); + +INSERT INTO ItemTypes VALUES (1, 'In-Portal', 'Category', 'Name', 'CreatedById', NULL, NULL, 'la_ItemTab_Categories', 1, 'admin/category/addcategory.php', 'clsCategory', 'Category'); +INSERT INTO ItemTypes VALUES (6, 'In-Portal', 'PortalUser', 'Login', '', NULL, NULL, '', 0, '', 'clsPortalUser', 'User'); + +INSERT INTO Modules (Name, Path, Var, Version, Loaded, LoadOrder, TemplatePath, RootCat, BuildDate) VALUES ('In-Portal', 'kernel/', 'm', '1.0.8', 1, 0, '', 0, '1054738405'); + +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.VIEW', 'lu_PermName_Category.View_desc', 'lu_PermName_Category.View_error', 'In-Portal'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.ADD', 'lu_PermName_Category.Add_desc', 'lu_PermName_Category.Add_error', 'In-Portal'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.DELETE', 'lu_PermName_Category.Delete_desc', 'lu_PermName_Category.Delete_error', 'In-Portal'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.ADD.PENDING', 'lu_PermName_Category.AddPending_desc', 'lu_PermName_Category.AddPending_error', 'In-Portal'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('CATEGORY.MODIFY', 'lu_PermName_Category.Modify_desc', 'lu_PermName_Category.Modify_error', 'In-Portal'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('ADMIN', 'lu_PermName_Admin_desc', 'lu_PermName_Admin_error', 'Admin'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('LOGIN', 'lu_PermName_Login_desc', 'lu_PermName_Admin_error', 'Front'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('DEBUG.ITEM', 'lu_PermName_Debug.Item_desc', '', 'Admin'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('DEBUG.LIST', 'lu_PermName_Debug.List_desc', '', 'Admin'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('DEBUG.INFO', 'lu_PermName_Debug.Info_desc', '', 'Admin'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('PROFILE.MODIFY', 'lu_PermName_Profile.Modify_desc', '', 'Admin'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('SHOWLANG', 'lu_PermName_ShowLang_desc', '', 'Admin'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('FAVORITES', 'lu_PermName_favorites_desc', 'lu_PermName_favorites_error', 'In-Portal'); +INSERT INTO PermissionConfig (PermissionName, Description, ErrorMessage, ModuleId) VALUES ('SYSTEM_ACCESS.READONLY', 'la_PermName_SystemAccess.ReadOnly_desc', 'la_PermName_SystemAccess.ReadOnly_error', 'Admin'); + +INSERT INTO PortalGroup VALUES (13, 'Member', '', '1054738682', 0, 0, 1, 13); +INSERT INTO PortalGroup VALUES (12, 'Subscribers', '', '1054738670', 0, 0, 1, 12); +INSERT INTO PortalGroup VALUES (14, 'Guest', 'Guest User', '0', 1, 0, 1, 14); +INSERT INTO PortalGroup VALUES (11, 'admin', '', '1054738405', 0, 0, 1, 11); + +INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('LOGIN', 13, 1, 1, 0); +INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('LOGIN', 11, 1, 1, 0); +INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('LOGIN', 12, 1, 1, 0); +INSERT INTO Permissions (Permission, GroupId, PermissionValue, Type, CatId) VALUES ('ADMIN', 11, 1, 1, 0); + +INSERT INTO SearchConfig VALUES ('Category', 'NewItem', 0, 1, 'lu_fielddesc_category_newitem', 'lu_field_newitem', 'In-Portal', 'la_Text_Category', 18, 80, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'PopItem', 0, 1, 'lu_fielddesc_category_popitem', 'lu_field_popitem', 'In-Portal', 'la_Text_Category', 19, 81, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'HotItem', 0, 1, 'lu_fielddesc_category_hotitem', 'lu_field_hotitem', 'In-Portal', 'la_Text_Category', 17, 79, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'MetaDescription', 0, 1, 'lu_fielddesc_category_metadescription', 'lu_field_metadescription', 'In-Portal', 'la_Text_Category', 16, 78, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'ParentPath', 0, 1, 'lu_fielddesc_category_parentpath', 'lu_field_parentpath', 'In-Portal', 'la_Text_Category', 15, 77, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'ResourceId', 0, 1, 'lu_fielddesc_category_resourceid', 'lu_field_resourceid', 'In-Portal', 'la_Text_Category', 14, 76, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'CreatedById', 0, 1, 'lu_fielddesc_category_createdbyid', 'lu_field_createdbyid', 'In-Portal', 'la_Text_Category', 13, 75, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'CachedNavbar', 0, 1, 'lu_fielddesc_category_cachednavbar', 'lu_field_cachednavbar', 'In-Portal', 'la_Text_Category', 12, 74, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'CachedDescendantCatsQty', 0, 1, 'lu_fielddesc_category_cacheddescendantcatsqty', 'lu_field_cacheddescendantcatsqty', 'In-Portal', 'la_Text_Category', 11, 73, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'MetaKeywords', 0, 1, 'lu_fielddesc_category_metakeywords', 'lu_field_metakeywords', 'In-Portal', 'la_Text_Category', 10, 72, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'Priority', 0, 1, 'lu_fielddesc_category_priority', 'lu_field_priority', 'In-Portal', 'la_Text_Category', 9, 71, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'Status', 0, 1, 'lu_fielddesc_category_status', 'lu_field_status', 'In-Portal', 'la_Text_Category', 7, 69, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'EditorsPick', 0, 1, 'lu_fielddesc_category_editorspick', 'lu_field_editorspick', 'In-Portal', 'la_Text_Category', 6, 68, 0, 'boolean', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'CreatedOn', 0, 1, 'lu_fielddesc_category_createdon', 'lu_field_createdon', 'In-Portal', 'la_Text_Category', 5, 67, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'Description', 1, 1, 'lu_fielddesc_category_description', 'lu_field_description', 'In-Portal', 'la_Text_Category', 4, 66, 2, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'Name', 1, 1, 'lu_fielddesc_category_name', 'lu_field_name', 'In-Portal', 'la_Text_Category', 3, 65, 2, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'ParentId', 0, 1, 'lu_fielddesc_category_parentid', 'lu_field_parentid', 'In-Portal', 'la_Text_Category', 2, 64, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'CategoryId', 0, 1, 'lu_fielddesc_category_categoryid', 'lu_field_categoryid', 'In-Portal', 'la_Text_Category', 0, 62, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'Modified', 0, 1, 'lu_fielddesc_category_modified', 'lu_field_modified', 'In-Portal', 'la_Text_Category', 20, 82, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('Category', 'ModifiedById', 0, 1, 'lu_fielddesc_category_modifiedbyid', 'lu_field_modifiedbyid', 'In-Portal', 'la_Text_Category', 21, 83, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'PortalUserId', 0, 0, 'lu_fielddesc_user_portaluserid', 'lu_field_portaluserid', 'In-Portal', 'la_text_user', 0, 173, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Login', 0, 0, 'lu_fielddesc_user_login', 'lu_field_login', 'In-Portal', 'la_text_user', 1, 174, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Password', 0, 0, 'lu_fielddesc_user_password', 'lu_field_password', 'In-Portal', 'la_text_user', 2, 175, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'tz', 0, 0, 'lu_fielddesc_user_tz', 'lu_field_tz', 'In-Portal', 'la_text_user', 17, 190, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'dob', 0, 0, 'lu_fielddesc_user_dob', 'lu_field_dob', 'In-Portal', 'la_text_user', 16, 189, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Modified', 0, 0, 'lu_fielddesc_user_modified', 'lu_field_modified', 'In-Portal', 'la_text_user', 15, 188, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Status', 0, 0, 'lu_fielddesc_user_status', 'lu_field_status', 'In-Portal', 'la_text_user', 14, 187, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'ResourceId', 0, 0, 'lu_fielddesc_user_resourceid', 'lu_field_resourceid', 'In-Portal', 'la_text_user', 13, 186, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Country', 0, 0, 'lu_fielddesc_user_country', 'lu_field_country', 'In-Portal', 'la_text_user', 12, 185, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Zip', 0, 0, 'lu_fielddesc_user_zip', 'lu_field_zip', 'In-Portal', 'la_text_user', 11, 184, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'State', 0, 0, 'lu_fielddesc_user_state', 'lu_field_state', 'In-Portal', 'la_text_user', 10, 183, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'City', 0, 0, 'lu_fielddesc_user_city', 'lu_field_city', 'In-Portal', 'la_text_user', 9, 182, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Street', 0, 0, 'lu_fielddesc_user_street', 'lu_field_street', 'In-Portal', 'la_text_user', 8, 181, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Phone', 0, 0, 'lu_fielddesc_user_phone', 'lu_field_phone', 'In-Portal', 'la_text_user', 7, 180, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'CreatedOn', 0, 0, 'lu_fielddesc_user_createdon', 'lu_field_createdon', 'In-Portal', 'la_text_user', 6, 179, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'Email', 0, 0, 'lu_fielddesc_user_email', 'lu_field_email', 'In-Portal', 'la_text_user', 5, 178, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'LastName', 0, 0, 'lu_fielddesc_user_lastname', 'lu_field_lastname', 'In-Portal', 'la_text_user', 4, 177, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); +INSERT INTO SearchConfig VALUES ('PortalUser', 'FirstName', 0, 0, 'lu_fielddesc_user_firstname', 'lu_field_firstname', 'In-Portal', 'la_text_user', 3, 176, 0, 'text', NULL, NULL, NULL, NULL, NULL, NULL, 0); + +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT count(*) FROM <%prefix%>Category WHERE Status=1 ', NULL, 'la_prompt_ActiveCategories', '0', '1'); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT count(*) FROM <%prefix%>PortalUser WHERE Status=1 ', NULL, 'la_prompt_ActiveUsers', '0', '1'); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT count(*) FROM <%prefix%>UserSession', NULL, 'la_prompt_CurrentSessions', '0', '1'); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) as CategoryCount FROM <%prefix%>Category', NULL, 'la_prompt_TotalCategories', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS ActiveCategories FROM <%prefix%>Category WHERE Status = 1', NULL, 'la_prompt_ActiveCategories', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS PendingCategories FROM <%prefix%>Category WHERE Status = 2', NULL, 'la_prompt_PendingCategories', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS DisabledCategories FROM <%prefix%>Category WHERE Status = 0', NULL, 'la_prompt_DisabledCategories', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS NewCategories FROM <%prefix%>Category WHERE (NewItem = 1) OR ( (UNIX_TIMESTAMP() - CreatedOn) <= <%m:config name="Category_DaysNew"%>*86400 AND (NewItem = 2) )', NULL, 'la_prompt_NewCategories', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) FROM <%prefix%>Category WHERE EditorsPick = 1', NULL, 'la_prompt_CategoryEditorsPick', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT <%m:post_format field="MAX(CreatedOn)" type="date"%> FROM <%prefix%>Category', NULL, 'la_prompt_NewestCategoryDate', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT <%m:post_format field="MAX(Modified)" type="date"%> FROM <%prefix%>Category', NULL, 'la_prompt_LastCategoryUpdate', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS TotalUsers FROM <%prefix%>PortalUser', NULL, 'la_prompt_TopicsUsers', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS ActiveUsers FROM <%prefix%>PortalUser WHERE Status = 1', NULL, 'la_prompt_UsersActive', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS PendingUsers FROM <%prefix%>PortalUser WHERE Status = 2', NULL, 'la_prompt_UsersPending', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS DisabledUsers FROM <%prefix%>PortalUser WHERE Status = 0', NULL, 'la_prompt_UsersDisabled', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT <%m:post_format field="MAX(CreatedOn)" type="date"%> FROM <%prefix%>PortalUser', NULL, 'la_prompt_NewestUserDate', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT( DISTINCT LOWER( Country ) ) FROM <%prefix%>PortalUser WHERE LENGTH(Country) > 0', NULL, 'la_prompt_UsersUniqueCountries', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT( DISTINCT LOWER( State ) ) FROM <%prefix%>PortalUser WHERE LENGTH(State) > 0', NULL, 'la_prompt_UsersUniqueStates', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS TotalUserGroups FROM <%prefix%>PortalGroup', NULL, 'la_prompt_TotalUserGroups', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS BannedUsers FROM <%prefix%>PortalUser WHERE IsBanned = 1', NULL, 'la_prompt_BannedUsers', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS NonExipedSessions FROM <%prefix%>UserSession WHERE Status = 1', NULL, 'la_prompt_NonExpiredSessions', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS ThemeCount FROM <%prefix%>Theme', NULL, 'la_prompt_ThemeCount', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', 'SELECT COUNT(*) AS RegionsCount FROM <%prefix%>Language', NULL, 'la_prompt_RegionsCount', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', '<%m:sql_action sql="SHOW+TABLES" action="COUNT" field="*"%>', NULL, 'la_prompt_TablesCount', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', '<%m:sql_action sql="SHOW+TABLE+STATUS" action="SUM" field="Rows"%>', NULL, 'la_prompt_RecordsCount', 0, 2); +INSERT INTO StatItem VALUES (0, 'In-Portal', '<%m:custom_action sql="empty" action="SysFileSize"%>', NULL, 'la_prompt_SystemFileSize', 0, 2); INSERT INTO StatItem VALUES (0, 'In-Portal', '<%m:sql_action sql="SHOW+TABLE+STATUS" action="SUM" format_as="file" field="Data_length"%>', NULL, 'la_prompt_DataSize', 0, 2); \ No newline at end of file