Index: trunk/kernel/parser.php
===================================================================
--- trunk/kernel/parser.php	(revision 666)
+++ trunk/kernel/parser.php	(revision 667)
@@ -1,3416 +1,3418 @@
 <?php
 $ItemTypes["category"]=1;
 $ItemTables[1] = "Category";
 
 $ParserFiles[] = "kernel/parser.php";
 
 function m_ParseEnv($str = NULL)
 {  
    global $m_var_list, $objConfig, $objCatList, $objLanguages, $objThemes;   
    if ($str != NULL)
    {
       $str = substr($str,1);
       $pieces = explode("-", $str);
       //echo "<PRE>";print_r($pieces);echo "</PRE>";
       $m_var_list["cat"] = $pieces[0];
       $m_var_list["p"] = $pieces[1];
       $objCatList->Page = $m_var_list["p"];
       
       $m_var_list["lang"] = $pieces[2];
       $m_var_list["theme"] = $pieces[3];
    }
    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."<br>\n";
 	        	$RelatedItems->Query_Item($sql,-1,-1,$ItemType);        	
 	    	 }
 	    }
    	}
 }
 
 
 /*
    @description:  Inserts the html from a remote source
    @attrib: _url:: Remote URL to include
    @attrib: _StartPos:: Numeric start point of text to include, or string match
    @attrib: _EndPos:: Numeric end point of text to include, or string match
    @example: <inp:m_insert_url _Url="http://www.google.com" _StartPos="\<center\>" _EndPos="\</center\>" />  
 */ 
 function m_insert_url($attribs=array())
 {
 	global $pathtoroot;
 	
 	$url = $attribs["_url"];
 	$StartPos = $attribs["_startpos"];
 	$EndPos = $attribs["_endpos"];
 
 	$socket = new Socket($url,0,NULL);
 	$txt = $socket->socket_read_all();
 	$lines = explode("\n",$txt);
 	$txt = substr($txt,strpos($txt,"<"));
 	$tmp = strtolower($txt);
 	$bodypos = strpos($tmp,"<body");
 	if(strlen($bodypos)>0)
 	{
 	  $head = substr($txt,0,$bodypos-1);
 	  $body = substr($txt,$bodypos);
 	  if(substr($tmp,-7)=="</html>")
 	    $body = substr($body,0,-7);
 	}
 	else  
 	  $body = $txt;
 	if(strlen($body))
 	{	
 		if(strlen($StartPos))
 		{
 			if(!is_numeric($StartPos))
 			{
 				$start = strpos($body,$StartPos);
 			}
 			else 
 			  $start = (int)$StartPos;
 		}
 		else
 		  $start = 0;
 		if(strlen($EndPos))
 		{
 			if(!is_numeric($EndPos))
 			{
 				$end = strpos($body,$EndPos,$start) + strlen($EndPos);
 			}
 			else
 			  $end = (int)$EndPos;
 		}
 		else
 		  $end = NULL;
 		$o = substr($body,$start,$end-$start);	  
 	}
 	return $o;	
 }
 
 /*
    @description:  Displays a template depending on the login status of the user
    @attrib: _logintemplate:tpl: template to display when the user is NOT logged in
    @attrib: _LoggedinTemplate:tpl: template to display when the user is logged in
    @example: <inp:m_loginbox _LoginTemplate="right_login" _LoggedInTemplate="right_loggedin" />  
 */ 
 function m_loginbox($attribs = array())
 {  
    global $var_list, $objSession, $objUsers, $objTemplate;
     
    $userid = $objSession->Get("PortalUserId");
    $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 "<inp:form_prompt />" is used
   @attrib: _ErrorTemplate:tpl: If the field is in an error state (ie missing input) this template is used.  Will default to the normal template if not set  
 */
 function m_form_prompt($attribs = array())
 {
     global $FormError, $objTemplate, $objConfig;
 
     $form = strtolower($attribs["_form"]);
     $field = strtolower($attribs["_field"]);
 
     if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
     {
         $o = "";
     }
     else
     {    
         $t = $attribs["_template"];
         if(!strlen($t))
         {
             $templateText = "<inp:form_prompt />";
         }
         $e = $attribs["_errortemplate"];
         if(!strlen($e))
             $e = $t;
         if(strlen($attribs["_langtext"]))
         {
             $txt = language($attribs["_langtext"]);
         }
         else
             $txt = $attribs["_plaintext"];
      
           if (strtolower($field) == "dob")  
           {
           	if (isset($FormError[strtolower($form)][strtolower($field."_day")]) || isset($FormError[strtolower($form)][strtolower($field."_month")]) || isset($FormError[strtolower($form)][strtolower($field."_year")])) 
 				$rawtext = $objTemplate->GetTemplate($e, true);
           }
            
           if(isset($FormError[strtolower($form)][strtolower($field)]))
           {
              $rawtext = $objTemplate->GetTemplate($e);
           }
           elseif (strlen($t))
             $rawtext = $objTemplate->GetTemplate($t);         
            
         if(is_object($rawtext))
         {
           $src = $rawtext->source;
           $o = str_replace("<inp:form_prompt />",$txt, $src);
         }
         else
         	$o = str_replace("<inp:form_prompt />", $txt, $templateText);
         	
     }
     return $o;
 }
 
 /*
   @description: Returns text if system is configured to use auto-generated passwords
   @attrib:_LangText:lang:Language tag to return
   @attrib:_PlainText::Plain text to return (_LangText takes precedece)
   @attrib:_Value:bool:Auto Password setting value to match
 */
 function m_autopassword($attribs = array())
 {
 	global $objConfig;
 	if($attribs["_value"]=="true" || $attribs["_value"]==1)
 	{
 	  $IsAuto = $objConfig->Get("User_Password_Auto");
 	}
 	else
 	{
 	  $IsAuto = !$objConfig->Get("User_Password_Auto");
 	}
 	 	
 	if($IsAuto)
 	{
     	if(strlen($attribs["_langtext"]))
     	{
         	$ret = language($attribs["_langtext"]);
     	}
     	else
         	$ret = $attribs["_plaintext"];	
         if(!$ret)
           return "true";	
 	}
 	return $ret;
 }
 
 /*
   @description: checks if field specified is equals to value specified
   @attrib: _Form:: Form name for the field
   @attrib: _Field:: Field Name
   @attrib: _Value:: Field value to compare to
   @example: <inp:m_field_equals _field="topic_subject" _Form="edit_topic" _Value="test" />true</inp:m_field_equals>
 */
 function m_field_equals($attribs = array())
 {
 	global $FormValues;
 	//print_pre($attribs);
 	$form = $attribs["_form"];
     $field = $attribs["_field"];
     if(isset($_POST[$field]))
     {
       $value = $_POST[$field];
     }
     else
         $value = $FormValues[$form][$field];
     //echo "POST_VALUE: [$value] vs USER_VALUE: [".$attribs['_value']."]<br>";
 	return $value == $attribs['_value'] ? 1 : '';
 }
 
 /*
   @description: creates an INPUT tag for a form field. All extra attributes are passed to the INPUT tag
   @attrib: _Form:: Form name for the field
   @attrib: _Field:: Field Name
   @attrib: _ForgetValue:bool: if true, forget value
   @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
   @example: <inp:m_form_input type="text" class="input" style="width:600px;" _field="topic_subject" _Form="edit_topic" _Required="1" />
 */
 function m_form_input($attribs = array())
 {
     global $FormValues, $objConfig;
 
     $html_attribs = ExtraAttributes($attribs);
     $form = $attribs["_form"];
     $field = strtolower($attribs["_field"]);
     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']."<br>\n";
     if($form=="m_register" && ($field=="password" || $field=="passwordverify") && $objConfig->Get("User_Password_Auto"))
     {
       $ret = "";
     }
     else
     {
       $ret = "<INPUT ".$html_attribs." name=\"$field\" VALUE=\"$value\" />";
       if($attribs["_required"])
         $ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
       if($attribs["_custom"])
       	$ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
     }
     return $ret;
 }
 
 /*
   @description: creates an INPUT tag (type checkbox) for a form field. All extra attributes are passed to the INPUT tag
   @attrib: _Form:: Form name for the field
   @attrib: _Field:: Field Name
   @attrib: _Value:bool: If true, the radio button is CHECKED  
   @attrib: _Required:bool: If set, In-Portal requires this field have a value when submitting
   @attrib: _Custom:bool: If set, handled as a custom field  
   @example: <inp:m_form_checkbox _field="owner_notify" _Form="edit_topic" />
 */
 function m_form_checkbox($attribs = array())
 {
     global $FormValues, $objConfig;
 
     $html_attribs = ExtraAttributes($attribs);
     $form = $attribs["_form"];
     $field = strtolower($attribs["_field"]);
     if(isset($_POST[$field]))
     {
       $value = (int)$_POST[$field];
       if($value==1)
           $checked = " CHECKED";
     }
     else
     {    
         $value = (int)$FormValues[$form][$field];
         if($value==1)
             $checked=" CHECKED";
     }
      //echo $form.".".$field."=".$value."<br>\n";
        $ret = "<INPUT TYPE=\"checkbox\" $html_attribs name=\"$field\" VALUE=\"1\" $checked />";
     if($attribs["_required"])
         $ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
     if($attribs["_custom"])
         $ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";        
 
     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: <inp:m_form_checkbox _field="owner_notify" _Form="edit_topic" />
 */
 function m_form_radio($attribs = array())
 {
     global $FormValues, $objConfig;
 
     $html_attribs = ExtraAttributes($attribs);
     $form = $attribs["_form"];
     $field = strtolower($attribs["_field"]);
     $val = $attribs["_value"];
     if(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."<br>\n";
        $ret = "<INPUT TYPE=\"radio\" $html_attribs name=\"$field\" VALUE=\"$val\" $checked />";
     if($attribs["_required"])
         $ret .= "<input type=hidden name=\"required[]\" VALUE=\"$field\" />";
     if($attribs["_custom"])
         $ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";        
 
     return $ret;
 }
 /*
   @description: returns the value for a form field.  This may be defaulted by the system or set by a previus submit (as in an error condition)
   @attrib: _Form:: Form name for the field
   @attrib: _Field:: Field Name
   @example: <inp:m_form_value _field="owner_notify" _Form="edit_topic" />
 */
 function m_form_value($attribs = array())
 {
     global $FormValues;
 
     $form = $attribs["_form"];
     $field = strtolower($attribs["_field"]);
 
     if(isset($_POST[$field]))
     {
       $value = inp_htmlize($_POST[$field],1);
     }
     else
         $value =  inp_htmlize($FormValues[$form][$field]);
     //echo "<pre>"; print_r($FormValues); echo "</pre>";
     return $value;
 }
 
 /*
   @description: creates an form OPTION tag for a form SELECT tag. 
                 All extra attributes are passed to the OPTION tag.
   @attrib: _Form:: Form name for the field
   @attrib: _Field:: Field Name
   @attrib: _Value:: Value to use for this option (ie the value attribute)  If the current value of the select
                     field is the same as this attribute, then this option will be set SELECTED.
   @attrib: _langtext:lang: language tag to display for this option in the SELECT dropdown  
   @attrib: _plaintext:: plain text to display for this option in the SELECT dropdown (if _langtext is set, it is used instead of _plaintext)                   
   @example: <inp:m_form_option _value="3321" _field="formfield" _form="formname" _langtext="lu..."
 */
 function m_form_option($attribs = array())
 {
     global $FormValues;
 
     $html_attribs = ExtraAttributes($attribs); 
     $field = $attribs["_field"];
     $val = $attribs["_value"];
     
     if(isset($_POST[$field]))
     {    
         $value = $_POST[$field];
     }
     else
     { 
     	$value = $FormValues[$attribs['_form']][$field];
     }   
     
     $selected = ($val == $value)? "SELECTED" : "";
     
     if(strlen($attribs["_langtext"]))
     {
         $txt = language($attribs["_langtext"]);
     }
     else
         $txt = $attribs["_plaintext"];
         
     $o = "<OPTION $html_attribs VALUE=\"$val\" $selected>$txt</OPTION>";
     
     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: <inp:m_form_textarea class="textarea" _field="bb_signature" _Form="bb_profile" ID="textbody"  style="width:300px;" ROWS=10 COLS=65 WRAP="VIRTUAL" />
 */
 function m_form_textarea($attribs = array())
 {
     global $FormValues;
     $html_attribs = ExtraAttributes($attribs); 
     $field = $attribs["_field"];
     $form = $attribs["_form"];
     if(isset($_POST[$field]))
     {    
       $value = stripslashes($_POST[$field]);
     }
     else
         $value = stripslashes($FormValues[$attribs["_form"]][$field]);
     $ret = "<TEXTAREA NAME=\"$field\" $html_attribs>$value</TEXTAREA>";
     if($attribs["_required"])
       $ret .= "<input type=hidden name=required[] VALUE=\"$field\" />";
     if($attribs["_custom"])
       $ret .= "<input type=hidden name=\"custom[]\" VALUE=\"$field\" />";
     return $ret;
 }
 
 /*
   @description: 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 = "<INPUT $html_attribs TYPE=file NAME=\"$field\" >";
     $ret .= "<INPUT TYPE=HIDDEN name=\"isthumb[$field]\" VALUE=\"$isthumb\">";
     $ret .= "<INPUT TYPE=HIDDEN name=\"imagetypes[$field]\" VALUE=\"$TypesAllowed\">";
     $ret .= "<INPUT TYPE=HIDDEN name=\"imagename[$field]\" VALUE=\"$imgname\">";
     $ret .= "<INPUT TYPE=HIDDEN name=\"maxsize[$field]\" VALUE=\"$maxsize\">";
     if($attribs["_required"])
       $ret .= "<input type=hidden name=required[] VALUE=\"$field\" />";
     return $ret;
 }
 
 /*
   @description: Returns the error text for a form field, or nothing if no error exists for the field
   @attrib: _Form:: Form name for the field
   @attrib: _Field:: Field Name
 */  
 function m_form_error($attribs = array())
 {
     global $FormError;
 
     $form = $attribs["_form"];
     $field = $attribs["_field"];
         
     return $FormError[$form][$field];
 }
 
 /**
   @description: Provides a simple solution for displaying a language flag when a form has an error. Generic and limited to 1 language vairable.
   @attrib: _Form:: Form name for the field
 */
 function m_form_has_errors($attribs = array())
 {
 	// shows specified template once if form has error(-s)
 	global $FormError;
 	$f = $attribs["_form"];
 	
 	$ret = is_array($FormError[$f]);
 	if(!$ret) return '';
 	return isset($attribs["_asif"]) ? true : language('lu_errors_on_form');
 }
 
 /**
   @description: Lists form errors for all fields in a form 
   @attrib: _Form:: Form name for the field
   @attrib: _ItemTemplate:tpl: Template used to display each form error (if not set, "<inp:form_error />" is used) 
 */  
 function m_list_form_errors($attribs = array())
 {
     global $FormError, $content_set, $objTemplate;
 
     $t = $attribs["_itemtemplate"];
     if(!strlen($t))
         $templateText = "<inp:form_error />";
     $f = $attribs["_form"];
     $o = "";
     if (strlen($t))
     {   
     	$rawtext = $objTemplate->GetTemplate($t, true);
     	$src = $rawtext->source;  
     }   
     else
     	$src = $templateText;
     	
     //echo $f."<br>";  
     //echo $t."<br>";  
 //    echo "<PRE>"; print_r($FormError); echo "</pre>";
     if(is_array($FormError[$f]))
     {    
       foreach($FormError[$f] as $e)
       {
         $o .= str_replace("<inp:form_error />",$e, $src);
       }
     }
     if(!strlen($o))      
         $content_set = 0;
     return $o;
 }
 
 function m_form_load_values($FormName,$IdValue)
 {
     global $FormValues, $objUsers, $objSession, $objConfig;
 
     switch($FormName)
     {
     case "m_acctinfo":
        $u =& $objUsers->GetItem($IdValue);
        $FormValues[$FormName]["username"] = $u->Get("Login");
        //$FormValues[$FormName]["password"] = $u->Get("Password");
        //$FormValues[$FormName]["passwordverify"] = $u->Get("Password");
        
        $FormValues[$FormName]["password"] = "";
        $FormValues[$FormName]["passwordverify"] = "";
        
        $FormValues[$FormName]["firstname"] = $u->Get("FirstName");
        $FormValues[$FormName]["lastname"] = $u->Get("LastName");
        $FormValues[$FormName]["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<br>Possible Values:
             <UL>
                 <LI>login: user login
                 <LI>logout: user logout
                 <LI>forgotpw: Form to prompt the user for forgotten password information
                 <LI>forgotpw_confirm: confirmation form for forgotpw
                 <LI>suggest: form to suggest the site to a friend
                 <LI>suggest_confirm: form to confirm suggestion of the site to a friend
                 <LI>m_subscribe: form to subscribe to the mailing list
                 <LI>subscribe_confirm: form to confirm subscription to the mailing list
                 <LI>m_unsubscribe: form to unsubscribe from the mailing list
                 <LI>unsubscribe_confirm: form to confirm un-subscription from the mailing list                
                 <LI>m_acctinfo: user account information 
                 <LI>m_profile: system-level profile information
                 <LI>m_register: New User registration form                
                 <LI>m_addcat: Suggest Category form
                 <LI>m_addcat_confirm: Confirmation for add category
                 <LI>m_simplesearch: Perform a simple search 
                 <LI>m_simple_subsearch: Search within results
                 <LI>m_adv_searchtype: Form to select type of advanced search
                 <LI>m_adv_subsearch: Advanced Search
                 <LI>error_access: form displayed on the access denied template
                 <LI>error_template: Form displayed on the template error page                
                 <LI>m_set_theme: Form displayed for theme selection                
            </UL>
     @attrib: _SubscribeTemplate:tpl: The destination template with "m_subscribe", "subscribe_confirm", "unsubscribe_confirm" _Form actions. Can  be reused in other scenarios as programmed.
     @attrib: _UnSubscribeTemplate:tpl: The destination template for "m_subscribe" _Form action. Can be reused in other scenarios as programmed.
     @attrib: _ConfirmTemplate:tpl: The destination template for "m_unsubscribe", "suggest" _Form actions. Can be reused in other scenarios as programmed.
     @attrib: _DestTemplate:tpl: The destination template for "suggest_confirm", "suggest" _Form actions. Can be reused in other scenarios as programmed.    	
     @attrib: _ErrorTemplate:tpl: The destination template extensively used in most of _Form actions in case of error.    	
     @attrib: _Referer:bool: The destination template will be taken from referer page we can from.    	
     
     @example: <FORM enctype="multipart/form-data" method="POST" NAME="article_review" ACTION="<inp:m_form_action _Form="register" _confirm="join_confirm" />">                
 */
 function m_form_action($attribs = array())
 {
     global $var_list, $var_list_update, $m_var_list_update, $objSession, $objConfig, $objCatList;
     
     $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: <inp:m_language _Phrase="lu_hello_world" />
 */
 function m_language($attribs)
 {
     global $objSession, $objLanguages, $ForceLanguage;
 
     $phrase = $attribs["_phrase"];
     $LangId = (int)$ForceLanguage;
     if(strlen($phrase))
     {    
       $lang = $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"].')<br>';
    	$objSession->SetVariable('prev_category', $objSession->GetVariable('last_category') );
    	$objSession->SetVariable('last_category', $objCatList->CurrentCategoryID() );
 	
 	//$last_cat = $objSession->GetVariable('last_category');
 	//$prev_cat = $objSession->GetVariable('prev_category');
 	//echo "Last CAT: [$last_cat]<br>";
 	//echo "Prev CAT: [$prev_cat]<br>";
 }
 
 /*
   @description: List all subcategories a user is allowed to view
   @attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
   @attrib: _maxlistcount:int: Maximum number of categories to list
   @attrib: _FirstItemTemplate:tpl: Template used for the first category listed
   @attrib: _LastItemTemplate:tpl: Template used for the last category listed
   @attrib: _ItemTemplate:tpl: default template used for category list items
   @attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
   @example: <inp:m_list_cats _NoTable="0" _columns="2" _ItemTemplate="catlist_element" border="0" cellspacing="0" cellpadding="0" width="98%" />                     
 */ 
 function m_list_cats($attribs = array())
 {
    global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set, $objSystemCache;
 
    $CachedList = GetTagCache("kernel","m_list_cats",$attribs,m_BuildEnv());
    if(strlen($CachedList))
    {
        return $CachedList;
    }
    $cols = $attribs["_columns"];
    if($cols<1)
        $cols =1;
    $CategoryId = $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;$i<count($Groups);$i++)
      {
          $g = $Groups[$i];
          $acl_where[] = "(FIND_IN_SET($g,acl) OR ((NOT FIND_IN_SET($g,dacl)) AND acl='')) ";
      }
      if(count($acl_where))
      {
          $acl_where = "(".implode(" OR ",$acl_where).")";
      }
      else
        $acl_where = "(FIND_IN_SET(0,acl))";
    }
    else
        $acl_where = "(FIND_IN_SET(0,acl))";
    $objCatList->Clear();
    $OrderBy = $objCatList->QueryOrderByClause(TRUE,TRUE,TRUE);
    $objCatList->LoadCategories("ParentId=$CategoryId AND Status=1",$OrderBy);
    if ($objCatList->NumItems() == 0)
    {
    	   if($attribs["_dataexists"])
        		$content_set = 0;
       return "";
    }
        
    $html_attr = ExtraAttributes($attribs);
 
    $o="";
    $notable = $attribs["_notable"];
 
    $count=0;
    $row=0;
    $var_list_update["t"] = $var_list["t"];
 
    if(!$notable)
    {
        $per_row = ceil($objCatList->NumItems()/$cols);
        $o = "<TABLE $html_attr><TR CLASS=\"m_list_cats\">";
        $o .= "<TD valign=\"top\">";
        $CatCount = $objCatList->NumItems();
        foreach($objCatList->Items as $cat)
        {
          $parsed=0;
          if($count==$per_row)
          {
              $o .= "</TD><TD valign=\"top\">";
              $count=0;
          }
          if($row==0 && strlen($attribs["_firstitemtemplate"]))
          {
              $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
              $parsed=1;
          }
          if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
          {
              $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
              $parsed=1;
          }
          if(!$parsed)
            $o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
          $count++;
          $row++;
        }
        if($count != $per_row)
            $o .= "</TD>";
        $o .= "\n</tr></table>\n";
    }
 	else
    	{
    		$CatCount = $objCatList->NumItems();
    		foreach($objCatList->Items as $cat)
    		{
    			if($cat->Get("ParentId")==$CategoryId)
    			{
    				
    				if($row==0 && strlen($attribs["_firstitemtemplate"]))
    				{
 					//echo 'Saving <b>ID</b> in <b>m_sub_cats</b>[ first ] '.$cat->UniqueId().'<br>';
    					//$GLOBALS['cat_ID'] = $cat->UniqueId();
    					$o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
    					$parsed=1;
    				}
    				if($row==$CatCount-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
    				{
    					//echo 'Saving <b>ID</b> in <b>m_sub_cats</b>[ last ] '.$cat->UniqueId().'<br>';
    					//$GLOBALS['cat_ID'] = $cat->UniqueId();
    					$o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]);
    					$parsed=1;
    				}
    				if(!$parsed)
    				{
    					//echo 'Saving <b>ID</b> in <b>m_sub_cats</b>[ each ] '.$cat->UniqueId().'<br>';
    					//$GLOBALS['cat_ID'] = $cat->UniqueId();
    					$o .= $cat->ParseTemplate($attribs["_itemtemplate"]);
    				}
    				$row++;
    				$i++;
    				$count++;
    				if($count>=$cat_count && $cat_count>0)
    				break;
    			}
    		}
    	}
 	unset($var_list_update["t"]);
 	SaveTagCache("kernel","m_list_cats",$attribs,m_BuildEnv(),$o);
 	return $o;
 }
 
 function LoadCatSearchResults($attribs)
 {
-    global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal;
+    global $objSession, $objPermissions, $objCatList, $objSearchCats, $objConfig, $CountVal, $m_var_list;
 
     $GroupList = $objSession->Get("GroupList");
     if(strlen($GroupList))
         $Groups = explode(",",$GroupList);
     $acl_where = "";
     if(@count($Groups)>0 && is_array($Groups))
     {
         $acl_where = array();
         for($i=0;$i<count($Groups);$i++)
         {
             $g = $Groups[$i];
             $acl_where[] = "(FIND_IN_SET($g,acl) OR ((NOT FIND_IN_SET($g,dacl)) AND acl='')) ";
         }
         if(count($acl_where))
         {
             $acl_where = "(".implode(" OR ",$acl_where).")";
         }
         else
             $acl_where = "(FIND_IN_SET(0,acl))";
     }
     else
         $acl_where = "(FIND_IN_SET(0,acl))";
 
     $CAT_VIEW = $objPermissions->GetPermId("CATEGORY.VIEW");
     $ctable = $objCatList->SourceTable;
     $stable = $objSession->GetSearchTable(); // $objSearchCats->SourceTable;
     $ptable = GetTablePrefix()."PermCache";
     $sql = "SELECT * FROM $stable INNER JOIN $ctable ON ($stable.ItemId=$ctable.CategoryId) ";
     $sql .= "INNER JOIN $ptable ON ($ctable.CategoryId=$ptable.CategoryId) ";
     $sql .="WHERE ItemType=1 AND Status=1 AND $acl_where AND PermId=$CAT_VIEW ORDER BY 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:<BR>$sql<br>\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 = "<A $html_attribs HREF=\"$url\">";
       $text = $attribs["_text"];
       if(!strlen($text))
       {
         $text = $attribs["_plaintext"];
         if(!strlen($text))
         {
         }
         $o .= $text."</A>";
       }
       else
         $o .= language($text);
       if(strlen($attribs["_image"]))
       {
           $o .= "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\" />";
       }      
       $o .= "</A>";
     }
     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: <inp:m_search_list_cats _NoTable="1" _ItemTemplate="category_search_results_element" />                     
 */ 
 function m_search_list_cats($attribs = array())
 {
    global $var_list, $objConfig, $objSession, $objCatList, $var_list_update, $content_set,
           $objSearchCats, $objPermissions, $m_var_list;
 
    if(!is_object($objSearchCats))
    {
       $objSearchCats = new clsCatList();
       $objSearchCats->SourceTable = $objSession->GetSessionTable('Search'); //"ses_".$objSession->GetSessionKey()."_Search"
       $objSearchCats->Clear();
    }
    $objSearchCats->PerPageVar = "Perpage_Category";
    if($attribs["_shortlist"])
    {
        $objSearchCats->Page=1;
        $m_var_list["p"] = 1;
        $objSearchCats->PerPageVar = "Perpage_Category_Short";
    }
    
-   $keywords = $objSession->GetVariable("Search_Keywords"); // for using in all this func branches
+   $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"];
       
+   $max_categories = $objConfig->Get($objSearchCats->PerPageVar);
    $count=0;
    $row=0;
    $var_list_update["t"] = $var_list["t"];
-
+   
    if(!$notable)
    {       
        $per_row = ceil($objCatList->NumItems()/$cols);
        $o = "<TABLE $html_attr><TR CLASS=\"m_list_cats\">";
        $o .= "<TD valign=\"top\">";
        foreach($objSearchCats->Items as $cat)
        {  
          $parsed=0;
          if($count==$per_row)
          {         
              $o .= "</TD><TD valign=\"top\">";
              $count=0;
          }
          if($row==0 && strlen($attribs["_firstitemtemplate"]))
          {
              $o.= $cat->ParseTemplate($attribs["_firstitemtemplate"]);
              $parsed=1;
          }
          if($row==$objSearchCats->NumItems()-1 && !$parsed && strlen($attribs["_lastitemtemplate"])>0)
          {
              $o .= $cat->ParseTemplate($attribs["_lastitemtemplate"]); 
              $parsed=1; 
          }
          if(!$parsed)
            $o.= $cat->ParseTemplate($attribs["_itemtemplate"]);
          $count++;
        }
        if($count != $per_row)
            $o .= "</TD>";
        $o .= "\n</tr></table>\n";
    }
    else
    {   
    		//echo "<pre>"; print_r($objSearchCats->Items); echo "</pre>";
      foreach($objSearchCats->Items as $cat)
      {
         //$cat->Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
         $keywords_found = strstr( strip_tags(strtolower($cat->Data['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++;
+	        if($count == $max_categories) break;
       	}
      }
    }
    unset($var_list_update["t"]);
    return $o;
 }
 
 /*
   @description: Parse a template based on the current advanced search type 
   @attrib:_TypeSelect:tpl:Template to parse if no item type has been selected
   @attrib:_ItemSelect:tpl:Template to parse if an item type has been selected to search
 */
 function m_advsearch_include($attribs)
 {
 	global $objTemplate;
 	
 	$TypeSelectTemplate = $attribs["_typeselect"];
 	$ItemTemplate = $attribs["_itemselect"];
 	if((strlen($_GET["type"])>0 || $_POST["itemtype"]>0) && ($_GET["Action"]=="m_advsearch_type" || $_GET["Action"]=="m_adv_search"))
 	{
 		$o	= $objTemplate->ParseTemplate($ItemTemplate);
 	}
 	else
 	  $o = $objTemplate->ParseTemplate($TypeSelectTemplate);
 	return $o;
 }
 
 /*
   @description: Returns the name of the item type currently being advanced searched
   @attrib::_plaintext:bool:If set, simply returns the name of the item if not, builds a language tag (lu_searchtitle_[name])  
 */
 function m_advsearch_type($attribs)
 {
   global $objItemTypes;	
   
   if($_GET["Action"]=="m_advsearch_type")
   {
   	$ItemType = $_POST["itemtype"];
   }
   elseif($_GET["Action"]=="m_adv_search")
     $ItemType = $_GET["type"];
 
   $o = "";
   if((int)$ItemType>0)
   {
   	 $Item = $objItemTypes->GetItem($ItemType);
   	 if(is_object($Item))
   	 {
   	 	$name = strtolower($Item->Get("ItemName"));
   	 	if($attribs["_plaintext"])
   	 	{
   	 	  $o .= $name;  
   	 	}
   	 	else
   	 	  $o = language("lu_searchtitle_".strtolower($name));
   	 }
   }
   return $o;
 }
 
 /*
   @description: Lists advanced search fields for the selected item type
   @attrib: _FirstItemTemplate:tpl: Template used for the first field listed
   @attrib: _LastItemTemplate:tpl: Template used for the last field listed
   @attrib: _AltLastItemTemplate:tpl: Altername Template used for the last field listed
   @attrib: _ItemTemplate:tpl: default template used for field list items
   @attrib: _AltTemplate:tpl: Alternate template used for field list items 
 */  
 function m_advsearch_fields($attribs)
 {
   global $objItemTypes, $objTemplate, $objSearchConfig;
 	
   if(!is_object($objSearchConfig))
     $objSearchConfig = new clsSearchConfigList();
     
   if($_GET["Action"]=="m_advsearch_type")
   {
   	$ItemType = $_POST["itemtype"];
   }
   elseif($_GET["Action"]=="m_adv_search")
     $ItemType = $_GET["type"];
 
   $o = "";
   if((int)$ItemType>0)
   {
   	 $Item = $objItemTypes->GetItem($ItemType);
   	 if(is_object($Item))
   	 {
   	 	$name = strtolower($Item->Get("ItemName"));
 
   	 	  $table = $Item->Get("SourceTable");
   	 	  $sql = "SELECT * FROM ".$objSearchConfig->SourceTable." WHERE TableName='$table' AND AdvancedSearch=1 ORDER BY DisplayOrder";
   	 	  $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;$x<count($perms);$x++)
        {
            if($objSession->HasCatPermission($perms[$x]))
            {           
                $hasperm = TRUE;
                break;
            }
        }
    }
    else
        $hasperm = TRUE;
    if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
    {
        $hasperm = TRUE;
        $attribs["_template"]=$attribs["_deniedtemplate"];
    }
    if($hasperm)
    {
         $module = $attribs["_module"];
         if(ModuleEnabled($module))
         {        
           $t = $tpath[$attribs["_module"]];
           $t .= $attribs["_template"];
           $attribs["_template"] = $t;
           $html_attr = ExtraAttributes($attribs);
           if($attribs["_root"])
           {
               $func = ModuleTagPrefix($module)."_root_link";
               if(function_exists($func))
               {              
                 $url = $func($attribs);
               }
               else
                  $url = m_template_link($attribs);
           }
           else          
             $url = m_template_link($attribs);        
           $o = "<A $html_attr HREF=\"";
           $o .= $url;
           $o .= "\"> ";
           $text = $attribs["_text"];
           if(!strlen($text))
           {
             $text = $attribs["_plaintext"];
             if(!strlen($text))
             {
                 if(strlen($attribs["_image"]))
                 {
                     $text = "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\">";
                 }
             }
             $o .= $text."</A>";
           }
           else
             $o .= language($text)."</A>";
         }
         else
         {        
             $o = "";
         }
    }
    return $o;
 }
 /*
   @description: create a link to a template based on attributes passed into the tag. All extra HTML attributes
                 are passed to the anchor tag created.
   @attrib: _Template:tpl: Template to link to.  Just the template name is listed here. (ex: use "index" instead if "inlink/index")
   @attrib: _perm:: A list of permissions to check.  If the user has any of the the permissions in the list,
                   the link will be generated.  (If the _DeniedTemplate attribute is set, this template is used
                   and the link is created.)
   @attrib: _DeniedTemplate:tpl: This template is used if the user does not have a permission listed in the _perm 
                                attribute.  If this attirbute is not included and the user does not have access,
                                nothing is returned. (The link is not created.) 
   @attrib: _text:lang: language tag to include as text for the anchor tag
   @attrib: _plaintext:: plain text to include as text for the anchor tag.  The _text attribute takes presedence
            if both are included.
   @attrib: _image:: URL to an image to include inside the anchor tag.    
 */  
 function m_permission_link($attribs = array())
 {
    global $objCatList, $objSession;
 
    $permission = $attribs["_perm"];
    $o = "";
    if(strlen($permission))
    {   
        $perms = explode(",",$permission);
        $hasperm = FALSE;
        for($x=0;$x<count($perms);$x++)
        {
            if($objSession->HasCatPermission($perms[$x]))
            {           
                $hasperm = TRUE;
                break;
            }
        }
    }
    else
        $hasperm = TRUE;
    if(!$hasperm && strlen($attribs["_deniedtemplate"])>0)
    {
        $hasperm = TRUE;
        $attribs["_template"]=$attribs["_deniedtemplate"];
    }
    if($hasperm)
    {
        $url = m_template_link($attribs);        
        $o = "<A $html_attr HREF=\"";
        $o .= $url;
        $o .= "\"> ";
        $text = $attribs["_text"];
        if(!strlen($text))
        {
           $text = $attribs["_plaintext"];
           if(!strlen($text))
           {
               if(strlen($attribs["_image"]))
               {
                   $text = "<IMG SRC=\"".$attribs["_image"]."\" BORDER=\"0\">";
               }
           }
           $o .= $text."</A>";
         }
         else
           $o .= language($text)."</A>";
     }
     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 <A HREF="..#top">)
   @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: <a href="<inp:m_template_link _Template="index" _Category=0 />"><inp:m_language _Phrase="lu_home" /></a>
 */  
 function m_template_link($attribs = array())
 {
     global $var_list, $var_list_update, $m_var_list_update, $objCatList;
     
     $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: <a href="<inp:m_access_template_link _Template="my_account" _DeniedTemplate="login" _Perm="login" />"><inp:m_language _Phrase="lu_myaccount" /></A> 
 */  
 function m_access_template_link($attribs = array(), $Permission="")
 {
   global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
 
   $cat = $attribs["_category"];
   if(strlen($cat))
   {       
      if($cat=="NULL")
         $cat = 0;
   }
   else
     $cat = $objCatList->CurrentCategoryID();
 
   if(!strlen($Permission))                
   {  
      $Permission = strtoupper($attribs["_perm"]);
   }
      
   $o = "";
   $hasperm = FALSE;
   if(strlen($Permission))
   {  
     $perms = explode(",",$Permission);   
     
     for($x=0;$x<count($perms);$x++)
     {
         if($objSession->HasCatPermission(trim($perms[$x]),$cat))
         {           
             $hasperm = TRUE;
             break;
         }
     }
     
     if(!$hasperm && $attribs["_system"])
     {
    		for($x=0;$x<count($perms);$x++)
     	{
         	if($objSession->HasSystemPermission(trim($perms[$x])))
         	{           
             	$hasperm = TRUE;
             	break;
         	}
     	} 
     }
   }
   $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: <inp:m_perm_text _Text="!lu_allow_language_tag!" _PlainText="Just a text" _DenyText="!lu_deny_language_tag!" _PlainDenyText="Just a plain text" _Perm="login" _MatchAllPerms="1" _NoPerm="0">Some HTML here!</inp>
 */  
 function m_perm_text($attribs = array())
 {
 	 global $var_list, $var_list_update, $m_var_list_update, $objCatList, $objSession;
 
   $cat = $attribs["_category"];
   if(strlen($cat))
   {       
      if($cat=="NULL")
         $cat = 0;
   }
   else
     $cat = $objCatList->CurrentCategoryID();
 
   if(!strlen($Permission))                
   {  
      $Permission = strtoupper($attribs["_perm"]);
   }
      
   $o = "";
   $hasperm = FALSE;
   
   $count = 0;
   
   if(strlen($Permission))
   {  
     $perms = explode(",",$Permission);   
     
     for($x=0;$x<count($perms);$x++)
     {
         $_AllPermsCount[$count] = 0; 
     	if($objSession->HasCatPermission($perms[$x],$cat))
         {           
             $hasperm = TRUE;
             $_AllPermsCount[$count] = 1; 
 //            break;
         }
         
         $count++;
     }
     
     if(!$hasperm && $attribs["_system"])
     {
    		for($x=0; $x<count($perms); $x++)
     	{
     		$_AllPermsCount[$count] = 0;    		        	
         	if($objSession->HasSystemPermission($perms[$x]))
         	{           
             	$hasperm = TRUE;
             	$_AllPermsCount[$count] = 1;    		      
 //            	break;
         	}
         	
         	$count++;
     	} 
     }
   }
   
   if ((int)$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: <inp:m_navbar _RootTemplate="index" _Template="inbulletin/index" _LinkCurrent="1" _separator=" &gt; " />    
 */
 function m_navbar($attribs = array())
 {
     global $m_var_list_update, $var_list, $objCatList, $objConfig, $objModules;
 	
     $separator = GetElem($attribs, '_separator');
     if(!$separator) $separator = "<span class=\"NAV_ARROW\"> > </span>";
     
     $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: <inp:m_category_modified />
 */
 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: <inp:m_module_stylesheets _Modules="In-Portal,In-News,In-Bulletin,In-Link" _In-PortalCss="incs/inportal_main.css" />  
 */  
 function m_module_stylesheets($attribs)
 {
     global $TemplateRoot;
 
     $IncludeList = explode(",",trim($attribs["_modules"]));
     $tpath = GetModuleArray("template");
     for($inc=0;$inc<count($IncludeList);$inc++)
     {    
         $css_attr =  "_".strtolower($IncludeList[$inc])."css";
         if(strlen($attribs[$css_attr]))
         {        
           $mod_css = $tpath[$IncludeList[$inc]].$attribs[$css_attr];  
         } 
         else
           $mod_css = $tpath[$IncludeList[$inc]]."style.css";
         $file = $TemplateRoot.$mod_css;
         if(file_exists($file))
             $ret .= "<link rel=\"stylesheet\" href=\"$mod_css\" type=\"text/css\" />\n";
     }
     return $ret;
 }
 
 /*
   @description: lists items related to a category
   @attrib:CatId:int: Category ID of category, or current category if not set
   @attrib:_ListItem: 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;$inc<count($IncludeList);$inc++)
         {   
           $t_attr = "_".$IncludeList[$inc]."template";
           $t = $attribs[$t_attr];  
           $item_type = $IncludeList[$inc];
 
           if(strlen($item_type))
           {          
             $objType = $objItemTypes->GetTypeByName($item_type);
             if(is_object($objType))
             {            
               foreach($CatRelations->Items as $item)
               {         
                 if(is_object($item))
                 {           
                   if(strtolower($objType->Get("ItemName")) == strtolower($item_type) && $item->type==$objType->Get("ItemType"))
                   {            
                   	if(strlen($item->BasePermissionName))
                   	{
                   	  $perm = $item->BasePermissionName.".VIEW";
                   	  $haspem = $objSession->HasCatPermission($perm,$item->Get("CategoryId")); 
                   	}
                   	else
                   	  $hasperm = 1;
                   	
                   	if($hasperm)
                   	{
                       $data_sent =1;                    
                       $classname = $objType->Get("ClassName");  
                       if(strlen($classname))
                       {
                         $l = new $classname;
                         $l->Data = $item->Data;
                         $o .= $l->ParseTemplate($t);
                       }
                   	}
                   }
                 }
                 $item = NULL;
               }
             }
             else
                 echo $item_type." not found <br>\n";
           }
         }
         if($data_sent)
         {        
           return $o;
         }
         else
         {
             $content_set=0;
             return "";
         }
       }
       else
       {  
         $content_set = 0;
         return "";
       }
     }
     else
     {
         $content_set = 0;
         return "";
     }
 }
 
 /*
   @description: Returns the number of items related to the current category
   @attrib:_CatId:int: If set, this is the category ID to use, otherwise the current category is used
   @attrib:_ItemType::Name of item to count.  If not set, all related items are counted
 */
 function m_related_count($attribs)
 {
     global $objItemTypes, $objCatList, $content_set;
 
     $cat = $attribs["_catid"];
 
     if(!is_numeric($cat))
     {    
       $cat = $objCatList->CurrentCategoryID();
     }
     $c =& $objCatList->GetCategory($cat);
     $data_sent=0;
 	//echo "Category: $cat<pre>";  print_r($c); echo " </pre>";
     if(is_object($c))
     {
       $ResourceId = $c->Get("ResourceId");
       if(!is_object($CatRelations))
       {      	      	
       	$CatRelations = new clsMultiTypeList();
         LoadRelatedItems($Related, $CatRelations, $c->Get("ResourceId"));
       }      
       
       $item_type = $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 "<pre>"; print_r($item); echo "</pre>";
     
     $ExtraId="";
     
     if(is_object($item))
     {                   
     	if($item->Get("ItemType")==1) /* counting categories */
     	{    		
     		$ret = $objCatList->CountCategories($attribs);
     	}
     	else
     	{
     	  $ListVar =& GetItemCollection($attribs["_itemtype"]);	
 		  if(is_object($ListVar))
   		  {     		  		  	  		  			      		      	
   		      	$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:<inp:m_user_profile_field _Field="login" />
 */
 function m_user_profile_field($attribs = array())
 {
     if((int)$_GET["UserId"])
     {
       $attribs["_userid"] = $_GET["UserId"];
     }    	
     
     $ret = m_user_field($attribs);
     
 /*    if ($ret == '') {
     	$ret = admin_language("lu_Guest");
     }*/
 
     return $ret;
 }
 
 /*
   @description: Parses a user profile template
   @attrib:_Template:tpl: Template to parse
   @attrib:_UserId:int: User ID to parse.  If not set, the current user is used  
 */
 function m_user_profile_detail($attribs)
 {
     if((int)$_GET["UserId"])
     {
       $attribs["_userid"] = $_GET["UserId"];
     }
     $ret = m_user_detail($attribs);	
     return $ret;
 }
 
 /*
   @description: Lists all user profile fields the user has indicated to be public
   @attrib: _ItemTemplate:tpl: Template used to list each field
   @example:<inp:m_user_profile  _ItemTemplate="view_profile_field" />
 */
 function m_user_profile($attribs = array())
 {
     global $objTemplate, $objUsers;
 
     $tname = $attribs["_itemtemplate"];
     $t = $objTemplate->GetTemplate($tname);
     if(is_object($t))
     {
         $html = $t->source;
     }
 
     $userid = $_GET["UserId"];
     $o = "";
 
     if((int)$userid>0)
     {
         $u = $objUsers->GetItem($userid);
         $vars = $u->GetAllPersistantVars();
         foreach($vars as $field=>$value)
         {
             if(substr($field,0,3)=="pp_")
             {
                 if($value==1)
                 {
                     $src = $html;
                     $src = str_replace("<inp:user_profile_field />","<inp:user _field=\"".substr($field,3)."\" />",$src);
                     $src = str_replace("lu_profile_field","lu_".$field,$src);
                     $o .= $u->ParseTemplateText($src);                                                               
                 }
             }
 
         }
     }
 
     return $o;
 }
 
 /*
   @description: List users the current user has marked as 'friend'
   @attrib: _Status:: Determines which online status to list, either "online" or "offline". 
   @attrib: _ItemTemplate:tpl: Template used to parse list items
 */  
 function m_list_friends($attribs = array())
 {
     global $objUsers, $objSession;
 
     global $online_friends;
 
     $ado = &GetADODBConnection();
 
     $status = strtolower($attribs["_status"]);
     
     $logedin_user = $objSession->Get("PortalUserId");
     $u =& $objUsers->GetUser($logedin_user);
     
     //echo "<pre>"; print_r($u); echo "</pre>";
     if(!isset($online_friends) || $status=="online")
     {
         $ftable = GetTablePrefix()."Favorites";
         $stable = GetTablePrefix()."UserSession";
         $ptable = GetTablePrefix()."PortalUser";
         if(isset($online_friends))
         {
           foreach($online_friends as $id=>$name)
           {
               $u =& $objUsers->GetUser($id);
               $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
           }
         }
         else
         {       
           $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
           $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
           $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];        
           //echo $sql;
           $rs = $ado->Execute($sql);
           while($rs && ! $rs->EOF)
           {
             $u =& $objUsers->GetItem($rs->fields["PortalUserId"]);
             if($status=="online")
             {            
               $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
             }
             $online_friends[]=$rs->fields["PortalUserId"];
             if(ADODB_EXTENSION>0)
             {
                 adodb_movenext($rs);
             }
             else
               $rs->MoveNext();
           }
         }
     }
         
     if($status=="offline")
     {
         $ftable = GetTablePrefix()."Favorites";
         $stable = GetTablePrefix()."UserSession";
         $ptable = GetTablePrefix()."PortalUser";
         
         $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
         if(count($online_friends)>0)
         {  
           $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
           $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
           $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];        
         }
         else
         {
             $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId FROM $ftable ";
             $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];        
         }
         
         //echo $sql;
         $rs = $ado->Execute($sql);
         while($rs && ! $rs->EOF)
         {
             $u = $objUsers->GetItem($rs->fields["PortalUserId"]);
             $o .= $u->ParseTemplate($attribs["_itemtemplate"]);
             if(ADODB_EXTENSION>0)
             {
                 adodb_movenext($rs);
             }
             else
               $rs->MoveNext();
         }
     }
     $t = $attribs["_itemtemplate"];
     return $o;
 }
 
 /*
   @description: Returns the number of users the current user has marked as 'friend'
   @attrib: _Status:: Determines which online status to count, either "online" or "offline". 
 */  
 function m_friend_count($attribs=array())
 {
     global $objUsers, $objSession;
 
     global $online_friends;
 
     $ado = &GetADODBConnection();
     
     $logedin_user = $objSession->Get("PortalUserId");
     $u =& $objUsers->GetUser($logedin_user);    
 
     $status = strtolower($attribs["_status"]);
     if(!isset($online_friends) || $status=="online")
     {
         $ftable = GetTablePrefix()."Favorites";
         $stable = GetTablePrefix()."UserSession";
         $ptable = GetTablePrefix()."PortalUser";
         if(isset($online_friends) && $status="online")
         {
           return count($online_friends);
         }
         else
         {       
           $online_friends = array();
           $sql = "SELECT $ftable.ResourceId,$ftable.ItemTypeId, $ptable.PortalUserId,$stable.PortalUserId FROM $ftable ";
           $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) INNER JOIN $stable ON ";
           $sql .= "($ptable.PortalUserId=$stable.PortalUserId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];        
           //echo $sql."<br>\n";
           $rs = $ado->Execute($sql);
           while($rs && ! $rs->EOF)
           {
             $online_friends[$rs->fields["PortalUserId"]]=$rs->fields["PortalUserId"];
             if(ADODB_EXTENSION>0)
             {
                 adodb_movenext($rs);
             }
             else
               $rs->MoveNext();
           }
           if($status=="online")
             return count($online_friends);
         }
     }
         
     if($status=="offline")
     {
         $ftable = GetTablePrefix()."Favorites";
         $stable = GetTablePrefix()."UserSession";
         $ptable = GetTablePrefix()."PortalUser";
         
         $sessql = "SELECT DISTINCT(PortalUserId) FROM $stable";
 
         if(count($online_friends)>0)
         {        
           $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
           $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND ";
           $sql .= " $ptable.PortalUserId NOT IN (".implode(",",$online_friends).") AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];        
         }
         else
         {
           $sql = "SELECT count($ftable.ResourceId) as ItemCount FROM $ftable ";
           $sql .="INNER JOIN $ptable ON ($ftable.ResourceId=$ptable.ResourceId) WHERE ItemTypeId=6 AND $ftable.PortalUserId = ".$logedin_user; //$u->Data['ResourceId'];        
         }
         $rs = $ado->Execute($sql);
         return $rs->fields["ItemCount"];
     }
 }
 
 /*
   @description: Returns the number of users the current user has marked as 'friend' today
 */  
 function m_friend_count_today($attribs)
 {
     global $objSession;
     
     $logedin_user = $objSession->Get("PortalUserId");
 
     $ret =0;
     $ado = &GetADODBConnection();
     $today = 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:  <span>(<inp:m_search_item_count _ItemType="Topic" />)</span>
 */  
 function m_search_item_count($attribs)
 {
     global $objItemTypes, $objCatList, $objSession, $CountVal;
 
     if(!is_array($CountVal))
 	    $CountVal=array();	
     $item = $objItemTypes->GetTypeByName($attribs["_itemtype"]); 
     if(is_object($item))
     {        
     	$val = $CountVal[$item->Get("ItemType")];
     	if(is_numeric($val))
     	  return $val;    	
         $where = "ItemType=".$item->Get("ItemType");
         $table = $objSession->GetSearchTable();
         $ret = TableCount($table,$where,0);
         $CountVal[$item->Get("ItemType")]=(int)$ret;
     }
     
     return $ret;
 }
 /*
   @description: Returns the number of categories in a search result
   @Example:  <span>(<inp:m_search_cat_count />)</span>
 */  
 function m_search_cat_count($attribs = array())
 {
    global $objItemTypes, $objCatList, $objSession, $CountVal, $objSearchCats;
 
    if(!is_object($objSearchCats))
    {
       $objSearchCats = new clsCatList();
       $objSearchCats->SourceTable = $objSession->GetSearchTable();
       $objSearchCats->Clear();
    }
    
     LoadCatSearchResults($attribs);
   	//echo "<pre>"; print_r($objSearchCats->Items); echo "</pre>";
     $ret = 0;
 	$keywords = $objSession->GetVariable("Search_Keywords");   
     
     if ($keywords) {
     	foreach ($objSearchCats->Items as $cat) {
 
     		if (strstr(strip_tags(strtolower($cat->Data['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 <br>Possible Values:
             <UL>
                 <LI>get: $_GET super variable
                 <LI>post: $_POST super variable
                 <LI>cookie: $_COOKIE super variable
                 <LI>env: $_ENV super variable
                 <LI>server: $_SERVER super variable
                 <LI>session: $_SESSION super variable                
            </UL>
   @Example: <inp:m_get_var _name="url" _type="get" />
 */  
 function m_get_var($attribs = array())
 {
 	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']);	
 }
 
 ?>

Property changes on: trunk/kernel/parser.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.19
\ No newline at end of property
+1.20
\ No newline at end of property
Index: trunk/kernel/action.php
===================================================================
--- trunk/kernel/action.php	(revision 666)
+++ trunk/kernel/action.php	(revision 667)
@@ -1,2423 +1,2423 @@
 <?php
 
 $ro_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
 
 $AdminLogin = admin_login();
 if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & KERNEL_ACTIONS) == KERNEL_ACTIONS && $AdminLogin )
 {
 	if($Action) echo '<span class="debug_text">Kernel Action [<b>'.$Action."</b>]</span><br>\n";
 }
 
 if( defined('DEBUG_ACTIONS') && (DEBUG_ACTIONS & SHOW_REQUEST) == SHOW_REQUEST && $AdminLogin )
 {
 	// don't show debug output in tree & header of admin & while logging in
 	$script = basename($_SERVER['PHP_SELF']);
 	$skip_debug = Array('index.php','tree.php','head.php','credits.php');
 	if( !in_array($script, $skip_debug) )
 	{
 		//echo '<a href="file:///'.WINDOWS_ROOT.$_SERVER['PHP_SELF'].'">Open This File</a><br>';
 		echo "ScriptName: <b>$script</b> (<b>".dirname($_SERVER['PHP_SELF'])."</b>)<br><br>";
 		$div_height = (count($_REQUEST)+1)*26;
 		if($div_height > 300) $div_height = 300;
 		echo '<div class="debug_layer" style="height: '.$div_height.'px;">';
 		echo '<table border="0" cellspacing="0" cellpadding="4" class="debug_table">';
 		echo '<thead style="font-weight: bold;"><td>Src</td><td>Name</td><td>Value</td></thead>';
 		
 		foreach($_REQUEST as $key => $value)
 		{
 			if( !is_array($value) && trim($value) == '' ) $value = '&nbsp;';
 			$src = isset($_GET[$key]) ? 'GE' : (isset($_POST[$key]) ? 'PO' : (isset($_COOKIE[$key]) ? 'CO' : '?') );	
 			echo '<tr><td>'.$src.'</td><td>'.$key.'</td><td>'.print_r($value, true).'</td></tr>';
 		}
 		echo '</table></div>';
 		echo '<a href="javascript:self.location.reload();">Reload Frame</a><br>';
 	}
 	unset($script, $skip_debug);
 }
 
 	switch($Action)
 	{
 		case "m_save_import_config":
          	// Set New Import Category
          	if( GetVar('categorylist', true) !== false )
          	{
    		 		$cat_id = $_POST['categorylist'];
 			  	$objSession->SetVariable('categoryid', $cat_id); 		  	
    			  	
 			  	if($cat_id > 0)
 			  	{
 				  	$cat = $objCatList->GetByResource($cat_id);
 	    			if(is_object($cat))
 				    {    
 	      				$navbar = $cat->Get('CachedNavbar');
 	      				$objSession->SetVariable('catnavbar', $navbar);
 	      				$objSession->SetVariable('import_category_id', $cat->UniqueId() );
 				    }
 			  	}elseif($cat_id == 0)
 			  	{
 			  		global $objConfig;
 	      			$objSession->SetVariable('import_category_id', 0);
 			  	}
 			    
 			    $objSession->SetVariable('categorylist', $_POST['categorylist']);
 			}
 			
 			// Set Import Admin Group
 			if( GetVar('grouplist1', true) )
 			{              
 				$group_id = $_POST['grouplist1'];
 				$group = $objGroups->GetItemByField('ResourceId',$group_id);
                 $objSession->SetVariable('user_admin_names', $group->Get('Name')); 
                 $objSession->SetVariable('user_admin_values', $group->Get('GroupId'));
                 $objSession->SetVariable('grouplist1', $_POST['grouplist1']);
 			}   
               
 			// Set Import User Group
 			if( GetVar('grouplist2', true) )
 			{              
             	$group_id = $_POST['grouplist2'];
 				$group = $objGroups->GetItemByField('ResourceId', $group_id);
                 $objSession->SetVariable('user_regular_names', $group->Get('Name')); 
                 $objSession->SetVariable('user_regular_values', $group->Get('GroupId'));
                 $objSession->SetVariable('grouplist2', $_POST['grouplist2']);
 			}
         	break;
 		
 		case "m_add_user":		  
 	  	  	$dupe_user = '';
 			//$user_pending = (int)$_POST["user_pending"];
 			//$user_enabled = (int)$_POST["user_enabled"];
 			$CreatedOn = DateTimestamp($_POST["user_date"],GetDateFormat()); 
          	$CreatedOn += SecondsSinceMidnight($_POST["user_time"]);
          
 			$dob = DateTimestamp($_POST["user_dob"],GetDateFormat());
 			
 		  	$objEditItems = new clsUserManager();
 		  	$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
 
 		  	if(strlen($_POST["user_login"]))
           		$id = $objUsers->GetUserId($_POST["user_login"]);
 		  	else
 		    	$dob = 0;
 		    
           	if($id)
           	{
               	$lvErrorString = language('la_error_duplicate_username');
               	$dupe_user = $_POST["user_login"];
               	$_POST["user_login"] = '';
             }
           	         
           		$password = md5($_POST["password"]);
 		    	$u = $objEditItems->Add_User($_POST["user_login"], $password,
                 	                    $_POST["user_email"], $CreatedOn, $_POST["user_firstname"], 
                     	                $_POST["user_lastname"], $_POST["status"], 
                         	            $_POST["user_phone"], 
                             	        $_POST["user_street"], $_POST["user_city"], 
                                 	    $_POST["user_state"], $_POST["user_zip"], $_POST["user_country"], $dob);
      
             	$objCustomEdit = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));
             	$objCustomEdit->SetTable('edit');
             	$objCustomEdit->LoadResource($u->Get("ResourceId"));
             	$CustomFields = new clsCustomFieldList(6);
             	$DataChanged = FALSE;
             	foreach($_POST as $key=>$value)
             	{
             		if(substr($key,0,1)=="_")
             		{
             			$field = substr($key,1);
             			$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             			if(is_object($cvalue))
             			{
             				$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$u->Get("ResourceId"),$value);
             				$DataChanged = TRUE;
             			}
             		}
             	}          	
             	if($DataChanged) $objCustomEdit->SaveData();
             	$objCustomEdit->SetTable('live');
           	
           	
 			break;
 			    
 		case "m_edit_user":
 		    //$CreatedOn = DateTimestamp($_POST["user_date"],GetDateFormat()); 
          	//$CreatedOn += SecondsSinceMidnight($_POST["user_time"]);
             $dob = DateTimestamp($_POST["user_dob"],GetDateFormat());
 			$objEditItems = new clsUserManager();
 			$objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
 			//$user_pending = (int)$_POST["user_pending"];
             //$user_enabled = (int)$_POST["user_enabled"];
             $UserId = (int)$_POST["user_id"];
             //echo $UserId."<br>\n";
             if(!strlen($_POST["user_login"]))
               $dob = 0;
             if(strlen($_POST["password"]))
             {
               $password = md5($_POST["password"]);	
             }  
             else
               $password = "";
 			$u = $objEditItems->Edit_User($UserId, $_POST["user_login"], $password,
                                      $_POST["user_email"], $CreatedOn, $_POST["user_firstname"], 
                                      $_POST["user_lastname"], $_POST["status"], 
                                      $_POST["user_phone"], 
                                      $_POST["user_street"], $_POST["user_city"], 
                                      $_POST["user_state"], $_POST["user_zip"], $_POST["user_country"],
                                      $dob);
            
             $objCustomEdit = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));
             $objCustomEdit->SetTable('edit');
            	$DataChanged = false;
            	
             $objCustomEdit->LoadResource($u->Get("ResourceId"));
             $CustomFields = new clsCustomFieldList(6);
             
             foreach($_POST as $key=>$value)
             {
             	if(substr($key,0,1)=="_")
             	{
             		$field = substr($key,1);
             		$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             		if(is_object($cvalue))
             		{
             			//echo "Saving CF: (".$cvalue->Get("CustomFieldId")." ; ".$u->Get("ResourceId")." ; $value)<br>";
             			$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$u->Get("ResourceId"),$value);
             			$DataChanged = TRUE;
             		}
             	}
             }
         	
             if($DataChanged)
             	$objCustomEdit->SaveData();
             $objCustomEdit->SetTable('live');
 			break;
 			
 		case "m_user_primarygroup":		 
 		  	if($ro_perm) break;
 		  	$users = explode(',', $_POST["userlist"]);
 		  	$GroupResourceId = $_POST['grouplist'];
 		  	$g = $objGroups->GetItemByField("ResourceId", $GroupResourceId);
 		  	$GroupId = $g->UniqueId();
 		  	
 		  	if( is_array($users) )
 		  		foreach($users as $user_id)
 		  		{
 		  			$u = $objUsers->GetItemByField("ResourceId", $user_id);
 		  			$g->AddUser($u->Get("PortalUserId"), 1);
 		  		}
      		break;
      		
 		case "m_edit_group":		   
 			$objEditItems = new clsGroupList();
 			$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
 			$objEditItems->Edit_Group($_POST["group_id"], $_POST["group_name"],$_POST["group_comments"]);
 		break;
         case "m_add_group":
 			$objEditItems = new clsGroupList();
 			$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
 			$objEditItems->Add_Group($_POST["group_name"], $_POST["group_comments"],0);
 		break;
      case "m_group_sysperm":
 	     if($ro_perm) break;
 	     if($_POST["GroupEditStatus"]==0)
 	     {
 	     	$objSession->ResetSysPermCache();
 	     	$GroupId = $_POST["GroupId"];
 	     	if($GroupId)
 	     	{
 	     		$objEditItems = new clsGroupList();
 	     		$objEditItems->SourceTable = $objSession->GetEditTable("PortalGroup");
 	     		$g = $objEditItems->GetItemByField("ResourceId",$GroupId);
 	     		if(is_object($g))
 	     		{
 	
 	     			$PermList = explode(",",$_POST["PermList"]);
 	     			for($i=0;$i<count($PermList);$i++)
 	     			{
 	     				if(@in_array($PermList[$i],$_POST["inherit"]))
 	     				{
 	     					$value = -1;
 	     				}
 	     				else
 	     				{
 	     					$value = 0;
 	     					if(@in_array($PermList[$i],$_POST["permvalue"]))
 	     					$value = 1;
 	     				}
 	     				$g->SetSystemPermission($PermList[$i],$value);
 	     			}
 	     		}
 	     	}
 	     }
 	     break;
 	     
         case "m_user_sysperm":
           if($ro_perm) break;
           if($_POST["UserEditStatus"]==0)
           {
 		    $UserId = $_POST["ItemId"];
 			if($UserId)
 			{
 			  $objEditItems = new clsUserManager();
 			  $objEditItems->SourceTable = $objSession->GetEditTable("PortalUser");
 			  $u = $objEditItems->GetItemByField("ResourceId",$UserId);
 			  unset($g);
               if(is_object($u))
 			  {
                 $objSession->ResetSysPermCache();
 			    $g = $u->GetPersonalGroup(FALSE);
 			    $PermList = explode(",",$_POST["PermList"]);
 				for($i=0;$i<count($PermList);$i++)
 				{
 				  if(!@in_array($PermList[$i],$_POST["inherit"]))
 				  {
                     if(!is_object($g))
 					  $g = $u->GetPersonalGroup(TRUE);
 
 					$value = 0;					
 					if(is_array($_POST["permvalue"]))
 					{
 				      if(in_array($PermList[$i],$_POST["permvalue"]))
 				        $value =1;
 					  $g->SetSystemPermission($PermList[$i],$value);
 					}
 					else {
 					  $g->SetSystemPermission($PermList[$i], 0);
 					}
 				  }
 				  else
                   {
 				    if(is_object($g))
 					  $g->SetSystemPermission($PermList[$i],-1);
 				  }
 				}
 			  }
 			}
           }
 	    break;
 	    
 		case "m_approve_user":
 			if($ro_perm) break;
 			foreach($_POST["itemlist"] as $userid)
 			{
 				$user = $objUsers->GetItemByField("ResourceId",$userid);
 				$user->Approve();
 			}
             $objUsers->Clear();
 		break;
 
         case "m_deny_user":
             if($ro_perm) break;
             foreach($_POST["itemlist"] as $userid)
             {
                 $user = $objUsers->GetItemByField("ResourceId",$userid);
                 $user->Deny();
             }
             $objUsers->Clear();
         break;
         
 		case "m_delete_user":
 				if($ro_perm) break;
 				foreach($_POST["itemlist"] as $userid)
 					$objUsers->Delete_User($userid);
 		break;
 		
 		case "m_delete_group":
             if($ro_perm) break;
             foreach($_POST["itemlist"] as $groupid)
             {            
 			  	$objGroups->Delete_Group($groupid);
 			}
 		break;
 		
 		case "m_user_assign": // not sure if action is used anywhere
 			if($ro_perm) break;
 			$useridlist = implode("-", $userlist);
 			$objSession->SetUserStatus($useridlist, "g_usergroup_status");
 			$g_usergroup_status = $useridlist;
 			break;
 			
 		case "m_group_assign": // not sure if action is used anywhere
 			if($ro_perm) break;
 			foreach($grouplist as $group) $objGroups->Add_Users_To_Group($group);
 			break;
 			
 		case "m_remove_group":
 			if($ro_perm) break;
 			$adodbConnection = &GetADODBConnection();
 			$adodbConnection->Execute("DELETE FROM UserGroup where UserId='$UserId' AND GroupId='$GroupId'");
 			break;
 
         case "m_SetVariable":  
             $objSession->SetPersistantVariable($_POST["fieldname"], $_POST["varvalue"]);
         	break;
         	
         case "m_SetSessionVariable":
             $objSession->SetVariable($_POST["fieldname"], $_POST["varvalue"]);
             //echo "Setting $fieldname to $varvalue<br>\n";
             if($_POST["fieldname"]=="SearchType")
                 $objSession->SetVariable("SearchWord","");
         	break;
  
        case "m_edit_permissions":           
           if($ro_perm) break;
           
           if($_POST["CatEditStatus"] != -1)
           {
           	$objSession->SetVariable('PermCache_UpdateRequired', 1);
             $GroupId = $_POST["GroupId"];
             $CatId = $_POST["CategoryId"];
             $Module = $_POST["Module"];
             $ado = &GetADODBConnection();
             $sql = "SELECT * FROM ".GetTablePrefix()."PermissionConfig WHERE ModuleId='$Module'";
             $rs = $ado->Execute($sql);
             $PermNames = array();
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $PermNames[] = $data["PermissionName"];
                 $rs->MoveNext();
             }
             
             $inherit = array();
             if(is_array($_POST["inherit"]))
             {            
               foreach($_POST["inherit"] as $perm)
               {
                 $inherit[$perm] = 1;
               }
             }
             $access = array();
             if(is_array($_POST["permvalue"]))
             {            
               foreach($_POST["permvalue"] as $perm)
               {
                 $access[$perm] = 1;
               }
             }
             $objPermList = new clsPermList($CatId,$GroupId);
             $objPermList->LoadCategory($CatId);
 
             for($i=0;$i<count($PermNames);$i++)
             {                 
                if(!array_key_exists($PermNames[$i],$inherit))
                {
                    $PermValue = (int)$access[$PermNames[$i]];
                    
                    $Perm = $objPermList->GetPermByName($PermNames[$i]);                   
                    if($Perm)
                    {
                        $Id = $Perm->Get("PermissionId");
                        //echo "Editing $Id<br>\n";
                        $objPermList->Edit_Permission($Id,$CatId,$GroupId,$PermNames[$i],$PermValue,0);
                    }
                    else
                    {
                        //echo "Adding ".$PermNames[$i];
                        $objPermList->Add_Permission($CatId,$GroupId,$PermNames[$i],$PermValue,0);
                    }
                }
                else
                {        
                   $Perm = $objPermList->GetPermByName($PermNames[$i]);
                   if($Perm)
                   {
                       $Id = $Perm->Get("PermissionId");
                       $objPermList->Delete_Permission($Id);
                   }
                }
             }
             //$c = $objCatList->GetItem($CatId);
             //$glist = $objGroups->GetAllGroupList();
             //$ViewList = $objPermList->GetGroupPermList($c,"CATEGORY.VIEW",$glist );
             //$c->SetViewPerms("CATEGORY.VIEW",$ViewList,$glist);
             //$c->Update();
           }
         break; 
      	case "m_perm_delete_group":
 			if($ro_perm) break;
 			$ado = &GetADODBConnection();
 			$CatId = $_POST["CategoryId"];
 			foreach($_POST["itemlist"] as $groupid)
 			{
 			$g = $objGroups->GetItemByField("ResourceId",$groupid);
 			if(is_object($g))
 			{                
 			    $sql = "DELETE FROM ".GetTablePrefix()."Permissions WHERE CatId=$CatId AND GroupId=".$g->Get("GroupId");
 			    if($objSession->HasSystemPermission("DEBUG.LIST"))
 			        echo $sql."<br>\n";
 			    $ado->Execute($sql);                  
 			}
 			}
         	break;
 
       case "m_user_addto_group":      	
 	      if($ro_perm) break;
 	      $user = $_POST["UserId"];
 	      if(is_numeric($user))
 	      {
 	      	if(strlen($_POST["grouplist"]))
 	      	{
 	      		$groups = explode(",",$_POST["grouplist"]);
 	      		if(is_array($groups))
 	      		{
 	      			for($i=0; $i<count($groups);$i++)
 	      			{
 	      				$g = $objGroups->GetItemByField("ResourceId",$groups[$i]);
 	      				$g->AddUser($user);
 	      			}
 	      		}
 	      		else
 	      		{
 	      			$g = $objGroups->GetItem($groups);
 	      			$g->AddUser($user);
 	      		}
 	      	}
 	      }
 	      break;
 	      
      case "m_group_add_user":       
          if($ro_perm) break;
          $group = $_POST["GroupId"];
          $EditGroups = new clsGroupList();
          $EditGroups->SourceTable = $objSession->GetEditTable($objGroups->SourceTable);
          $g = $EditGroups->GetItem($group);
 //         echo "Group: $group <br>\n";
          if(is_numeric($group))
          {
              $users = explode(",",$_POST["userlist"]);
              foreach($users as $userid)
              {
                 $u = $objUsers->GetItemByField("ResourceId",$userid);
                 $g->AddUser($u->Get("PortalUserId"));
              }
          }
 
       break;
       case "m_group_removeuser":
           if($ro_perm) break;
           $group = $_POST["GroupId"];
           $g =  $objGroups->GetItem($group);
           if($group>0)
           {
               foreach($_POST["itemlist"] as $user_id)
               {
                   $u = $objUsers->GetItemByField("ResourceId",$user_id);
                   $g->DeleteUser($u->Get("PortalUserId"));
               }
           }
       break;    
       case "m_user_removegroup":
            if($ro_perm) break;
            $user = $_POST["UserId"];
            if($user>0)
            {  
              foreach($_POST["itemlist"] as $groupid)
              {
                 $g = $objGroups->GetItem($groupid);
                 $g->DeleteUser($user);
              }
            }
       break;
       case "m_sendmail":
           if($ro_perm) break;
 	      $idlist = explode(",",$_POST["idlist"]);
 	      $html = (int)$_POST["html_enable"];
 	      $body = inp_escape($_POST["email_body"],$html);
 	      $subject = inp_escape($_POST["email_body"],$html);
 	      $Email = new clsEmailMessage();
 	      $Email->Set("Subject",$subject);
 	      $Email->Set("Template",$body);
 	      if($html)
 	      $Email->Set("MessageType","HTML");
 	      if(count($idlist)>0)
 	      {
 	      	switch($_POST["IdType"])
 	      	{
 	      		case "group":
 	      		foreach($idlist as $id)
 	      		$Email->SendToGroup($id);
 	      		break;
 	      		case "user":
 	      		foreach($idlist as $id)
 	      		$Email->SendToUser($id);
 	      		break;
 	      	}/*switch*/
 	      }
      	break;
      	
      case "m_item_recount":
       	if($ro_perm) break;
      	RunDown($m_var_list["cat"],"UpdateCacheCounts");
      	break;
      	
      case "m_cat_delete":         
         if($ro_perm) break; 
      	if($objSession->HasCatPermission("CATEGORY.DELETE",$objCatList->CurrentCategoryID()))
          {         
            if(isset($_POST["catlist"]))
            {
              if(is_array($_POST["catlist"]))
                foreach($_POST["catlist"]  as $catid)
                {
                   $objCatList->Delete_Category($catid);
 
                }
            }
          }
      break;
      case "m_cat_cut":
      	if($ro_perm) break;    
      	if(isset($_POST["catlist"]))
         { 
         	if($objSession->HasCatPermission("CATEGORY.DELETE",$catid))
         	{
         		$objCatList->CopyToClipboard("CUT","CategoryId",$_POST["catlist"]);
         	}
         	else
         	$objCatList->CopyToClipboard("COPY","CategoryId",$_POST["catlist"]);
         }
      	break;
      	
      case "m_cat_copy":
      	if($ro_perm) break;    
      	if(isset($_POST["catlist"]))
         {
 			$objCatList->CopyToClipboard("COPY","CategoryId",$_POST["catlist"]);
         }
      break;
 
      case "m_paste":
 	    if($ro_perm) break; 
      	if($objCatList->ItemsOnClipboard()>0)
      	{
      		/* category's paste function populates a sparse array where array[old_id]=new_id */
      		$PastedCatIds = array();
      		$objCatList->PasteFromClipboard($objCatList->CurrentCategoryID(),"Name");
      	}
      	else
      	{
      		$clip = $objSession->GetVariable("ClipBoard");
      		if(strlen($clip))
      		{
      			$ClipBoard = ParseClipboard($clip);
      			$Action= strtolower($ClipBoard["table"])."_paste";
      		}
      	}
        	break;
        	
      case "m_cat_move_up":
         if($ro_perm) break; 
      	if (isset($_POST["catlist"]))
          {         
              foreach($_POST["catlist"] as $catid)
              {
                  $cat =& $objCatList->GetCategory($catid);
                  $cat->MoveUp();
              }
          }
      	break;
      	
      case "m_cat_move_down":
         if($ro_perm) break; 
      	if (isset($_POST["catlist"]))
          {
              $catlist=array_reverse($_POST["catlist"]);
              foreach($catlist as $catid)
              {
                  $cat =& $objCatList->GetCategory($catid);
                  $cat->MoveDown();
              }
          }
      break;
      case "m_cat_approve":
      	if($ro_perm) break;
      	if (isset($_POST["catlist"]))
      	{
      		foreach($_POST["catlist"] as $catid)
      		{
      			$cat =& $objCatList->GetCategory($catid);
      			$cat->Approve();
      		}
      	}
      break;
      case "m_cat_decline":
 	     if($ro_perm) break;
 	     if (isset($_POST["catlist"]))
 	     {
 	     	foreach($_POST["catlist"] as $catid)
 	     	{
 	     		$cat =& $objCatList->GetCategory($catid);
 	     		//$cat->Deny();
 	     		RunDown($catid,"Deny");
 	     	}
 	     }
      break;     
 
      case "m_rel_delete":
          $adodbConnection= &GetADODBConnection();
          $table = $objSession->GetEditTable("Relationship");
          if(isset($_POST["itemlist"]))
          {
            if(is_array($_POST["itemlist"]))
            {
              foreach($_POST["itemlist"] as $id)
              {
                $sql = "DELETE FROM ".$table." WHERE RelationshipId=".$id;
                $adodbConnection->Execute($sql);
                if($objSession->HasSystemPermission("DEBUG.LIST"))
                    echo $sql."<br>\n";
              }
            }
            else
            {
               $sql = "DELETE FROM ".$table." WHERE RelationshipId=".$_POST["itemlist"];
               $adodbConnection->Execute($sql);
               if($objSession->HasSystemPermission("DEBUG.LIST"))
                   echo $sql."<br>\n";
            }
          }
          break;
      case "m_add_relation":
          $RelList = new clsRelationshipList();
          $RelList->SourceTable = $objSession->GetEditTable("Relationship");
 
          //$r = $RelList->Add($_POST["SourceId"],$_POST["SourceType"],$_POST["TargetId"],$_POST["TargetType"],
            //               0,(int)$_POST["Enabled"],$_POST["RelType"], $Rel);
          $ado = &GetADODBConnection();
          $NewId = $ado->GetOne('SELECT MIN(RelationshipId) as MinValue FROM '.$RelList->SourceTable);
          if($NewId > 0) $NewId = 0;
          $NewId--;
          
          $r = $RelList->Add($_POST["SourceId"],$_POST["SourceType"],$_POST["TargetId"],$_POST["TargetType"],
                           0,(int)$_POST["Enabled"],$_POST["RelType"], $NewId);         
          
          $sql = "UPDATE ".$RelList->SourceTable." SET RelationshipId=".$NewId." WHERE RelationshipId=".$r->Get("RelationshipId");         
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          $ado->Execute($sql);
        
      break;
      case "m_edit_relation":
        if($_POST["CatEditStatus"]==0)
        {
          $RelList = new clsRelationshipList();
          $RelList->SourceTable = $objSession->GetEditTable("Relationship");
 
          $r = $RelList->GetItem($_POST["RelationshipId"]);
          if(is_object($r))
          {
            $r->Set("Enabled",(int)$_POST["Enabled"]);
            $r->Set("Type",(int)$_POST["RelType"]);
            $r->Set("Priority",(int)$_POST["priority"]);
            $r->Update();
          }
        }
      break;
      case "m_rel_move_up":
          $objRelList = new clsRelationshipList();
          $objRelList->SourceTable = $objSession->GetEditTable("Relationship");
          if (isset($_POST["itemlist"]))
          {         
              foreach($_POST["itemlist"] as $id)
              {
                  $r = $objRelList->GetItem($id);
                  $r->MoveUp($_POST["SourceId"]);
              }
          }
      break;
      case "m_rel_move_down":
          $objRelList = new clsRelationshipList();
          $objRelList->SourceTable = $objSession->GetEditTable("Relationship");
          if (isset($_POST["itemlist"]))
          {
              $itemlist=array_reverse($_POST["itemlist"]);
              foreach($itemlist as $id)
              {
                  $r = $objRelList->GetItem($id);
                  $r->MoveDown($_POST["SourceId"]);
              }
          }
      break;
 
 
      case "m_add_category":
          if(ValidDate($_POST["cat_date"],GetDateFormat()))
          {         
            $CreatedOn = DateTimestamp($_POST["cat_date"],GetDateFormat());
          }
          else
            $CreatedOn = time();
          $html = (int)$_POST["html_enable"];
 
          $cat_pick = $_POST["cat_pick"];
          $Status = (int)$_POST["status"];
          $Hot=(int)$_POST["itemhot"];
          $Pop = (int)$_POST["itempop"];      
          $New = (int)$_POST["itemnew"];
 
          $objEditItems = new clsCatList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Category");
          $cat = $objEditItems->Add($_POST["ParentId"], $_POST["cat_name"], inp_escape($_POST["cat_desc"],$html), $CreatedOn, 
                             $cat_pick, $Status, $Hot, $New, $Pop, $_POST["Priority"], 
                             $_POST["meta_keywords"],$_POST["meta_desc"]);
             $objCustomEdit = new clsCustomDataList($objSession->GetEditTable("CustomMetaData"));
             $objCustomEdit->LoadResource($cat->Get("ResourceId"));
             $CustomFields = new clsCustomFieldList(1);
             $DataChanged = FALSE;
             foreach($_POST as $key=>$value)
             {
             	if(substr($key,0,1)=="_")
             	{
             		$field = substr($key,1);
             		$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             		if(is_object($cvalue))
             		{
             			$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$cat->Get("ResourceId"),$value);
             			$DataChanged = TRUE;
             		}
             	}
             }          	
             if($DataChanged)
             	$objCustomEdit->SaveData();                            
                          
      break;              
 
      case "m_edit_category":                 
          $CreatedOn = DateTimestamp($_POST["cat_date"],GetDateFormat());
          $cat_pick = GetVar('cat_pick', true);
          $Status = (int)$_POST["status"];
          $Hot = false; //(int)$_POST["itemhot"];
          $Pop = false; //(int)$_POST["itempop"];      
          $New = (int)$_POST["itemnew"];
 
          $html = (int)$_POST["html_enable"];
          $objEditItems = new clsCatList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Category");
          
          // check if name of cat isn't changed: begin
          if( GetVar('CategoryId') > 0 )
          {
 	         $original_cats = new clsCatList();
 	         $original_cat = $original_cats->GetItemByField('CategoryId', GetVar('CategoryId'));
 	         if( $original_cat->Get('Name') != $_POST['cat_name'] ) 
 	         	$objSession->SetVariable('PermCache_UpdateRequired', 1);
 	         unset($original_cat, $original_cats);
          }
          else
          {
          	$objSession->SetVariable('PermCache_UpdateRequired', 1);
          }
          // check if name of cat isn't changed: end
          
          $cat = $objEditItems->Edit_Category($_POST["CategoryId"],inp_escape($_POST["cat_name"],$html), inp_escape($_POST["cat_desc"],$html), $CreatedOn, $cat_pick, $Status, $Hot, $New, $Pop, $_POST["Priority"], $_POST["meta_keywords"], $_POST["meta_desc"]);         
                                       
          $objCustomEdit = new clsCustomDataList($objSession->GetEditTable("CustomMetaData"));
          $objCustomEdit->LoadResource($cat->Get("ResourceId"));
          $CustomFields = new clsCustomFieldList(1);
          $DataChanged = FALSE;
          foreach($_POST as $key=>$value)
          {
 	       	if(substr($key,0,1)=="_")
             	{
             		$field = substr($key,1);
             		$cvalue = $CustomFields->GetItemByField("FieldName",$field,FALSE);
             		
             		if(is_object($cvalue))
             		{
             			$objCustomEdit->SetFieldValue($cvalue->Get("CustomFieldId"),$cat->Get("ResourceId"),$value);
             			$DataChanged = TRUE;
             		}
             	}
          }          	
          if($DataChanged)
          	$objCustomEdit->SaveData();  
          	                                      
      break;
      case "m_edit_custom_data":
      	$id = $_POST["ItemId"];                   
         $objEditData = new clsCustomDataList(); //$objSession->GetEditTable("CustomMetaData"));		
         $objEditData->SetTable('edit');
         $ado = &GetADODBConnection();
 
         if($id && is_array($_POST["CustomData"]))
         {
             foreach($_POST["CustomData"] as $FieldId => $Value)
             {                                
                 $sql = "SELECT count(*) as reccount FROM ".$objEditData->SourceTable." WHERE CustomFieldId=$FieldId AND ResourceId=".$_POST["ItemId"];
                 $rs = $ado->Execute($sql);            
                 $intable = $rs->fields["reccount"];
                 if(!$intable)
                 {                
                     $sql = "INSERT INTO ".$objEditData->SourceTable." (ResourceId,CustomFieldId,Value) VALUES ('".$id."','$FieldId','$Value')";
                     $ado->Execute($sql);
                     //echo $sql."<br>\n";
                 }
                 else
                 {
                   $sql = "UPDATE ".$objEditData->SourceTable." SET Value='".$Value."' WHERE CustomFieldId=$FieldId AND ResourceId=".$_POST["ItemId"];
                   $ado->Execute($sql);
                   //echo $sql."<br>\n";
                 }
             }            
         }
         $objEditData->SetTable('live');
      break;
      case "m_customfield_edit":
        	if($ro_perm) break;
         $DataType = $_POST["DataType"];
         $FieldId = $_POST["CustomFieldId"];
         $FieldName = $_POST["fieldname"];
         //$FieldLabel = $_POST["fieldlabel"];
         if(strlen($FieldName))
         {        
         	$objCustomFields = new clsCustomFieldList($DataType);
         	$objCustomFields->EditField($FieldId,$DataType,$FieldName,"",(int)$_POST["generaltab"],
           							    $_POST["heading"],$_POST["fieldprompt"],$_POST["input_type"],
           							    $_POST["valuelist"]);
         }
         unset($objCustomFields);
      break;
      case "m_customfield_add":
         if($ro_perm) break;
         $DataType = $_POST["DataType"];        
         $FieldName = $_POST["fieldname"];
         //$FieldLabel = $_POST["fieldlabel"];
         if(strlen($FieldName))
         {
           $objCustomFields = new clsCustomFieldList($DataType);
           $objCustomFields->AddField($DataType,$FieldName,"",(int)$_POST["generaltab"],
           							 $_POST["heading"],$_POST["fieldprompt"],$_POST["input_type"],
           							 $_POST["valuelist"]);
           unset($objCustomFields);
         }
      break;
      case "m_customfield_delete":
      	if($ro_perm) break;
         $DataType = $_POST["DataType"];        
         $objCustomFields = new clsCustomFieldList($DataType);
 
         foreach($_POST["itemlist"] as $f)
         {
             $objCustomFields->DeleteField($f);
         	//$c = $objCustomFields->GetItem($f);
             //$c->Delete();
         }
         unset($objCustomFields);
      break;
      case "m_SearchConfig_Edit":
      	if($ro_perm) break;
         $SimpleValues = $_POST["simple"];
         $AdvValues = $_POST["advanced"];
         $module = $_POST["module"];
         $priority = $_POST["pri"];
         //phpinfo(INFO_VARIABLES);
         $objSearchConfig = new clsSearchConfigList($module);
         foreach($objSearchConfig->Items as $i)
         {
           $id = $i->Get("SearchConfigId");
           $objSearchConfig->EditFieldSettings($id,(int)$SimpleValues[$id],(int)$AdvValues[$id],$priority[$id]);       
         }
         $objSearchConfig->Clear();
         /* save relevence settings */
         $vals = $_POST["req_increase"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Increase_".$var;
             $objConfig->Set($cfg,$value);
         }
         $vals = $_POST["rel_keyword"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Keyword_".$var;
             $objConfig->Set($cfg,$value);
         }
         $vals = $_POST["rel_pop"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Pop_".$var;
             $objConfig->Set($cfg,$value);
         }
         $vals = $_POST["rel_rating"];
         foreach($vals as $var=>$value)
         {
             $cfg = "SearchRel_Rating_".$var;
             $objConfig->Set($cfg,$value);
         }
      break;
      case "m_keyword_reset":
          if($ro_perm) break;
          $objSearchList = new clsSearchLogList();
          foreach($_POST["itemlist"] as $k)
          {
              $c = $objSearchList->GetItem($k);
              $c->Delete();
          }
      break;
      case "m_review_add":     
        $post_info = GetSubmitVariable($_POST, 'EditStatus');
        if($post_info['variable'] > -1)
        {
          $objReviews = new clsItemReviewList();
          $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
          $Pending = (int)$_POST["review_pending"];
          $Enabled = (int)$_POST["review_enabled"];
          $Status = (int)$_POST["status"];
          $CreatedOn = DateTimestamp($_POST["review_date"],GetDateFormat()); 
          $CreatedOn += SecondsSinceMidnight($_POST["review_time"]);
          $html = (int)$_POST["html_enable"];         
          $ReviewText = inp_escape($_POST["review_body"],1);
          
          $CreatedById = 0;
          if(strlen($_POST["createdby"])>0)
          {
          	if(strtolower($_POST["createdby"])=="root")
          	{
          	  $CreatedById = -1;
          	}
          	else 
          	{
            	  $u = $objUsers->GetItemByField("Login",$_POST["createdby"]);
            	  if(is_object($u))
            	  {
            	    $CreatedById = $u->Get("PortalUserId");
            	    if($CreatedById<1)
            	    {
            	  	  $CreatedById = $objSession->Get("PortalUserId");
            	    }
            	  }
            	  else
            	    $CreatedById = $objSession->Get("PortalUserId");
          	}
          }
          else
            $CreatedById = $objSession->Get("PortalUserId");
          
          $r = $objReviews->AddReview($CreatedOn,$ReviewText,$Status, $IPAddress, 
                                      (int)$_POST["review_priority"], $_POST["ItemId"],$_POST["ItemType"],
                                      $CreatedById,$html, $post_info['Module']);                                    
          $ado = &GetADODBConnection();
          $rs = $ado->Execute("SELECT MIN(ReviewId) as MinValue FROM ".$objReviews->SourceTable);
          $NewId = $rs->fields["MinValue"]-1;
          $sql = "UPDATE ".$objReviews->SourceTable." SET ReviewId=".$NewId." WHERE ReviewId=".$r->Get("ReviewId");
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          $ado->Execute($sql);
        }
      break;
      case "m_review_edit":     
        $post_info = GetSubmitVariable($_POST, 'EditStatus');
        if($post_info['variable'] > -1)
        {
          $objReviews = new clsItemReviewList();
          $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
          $Status = (int)$_POST["status"];
          $CreatedOn = DateTimestamp($_POST["review_date"],GetDateFormat()); 
          $CreatedOn += SecondsSinceMidnight($_POST["review_time"]);
          $html = (int)$_POST["html_enable"];
          $ReviewText = inp_escape($_POST["review_body"],1);
          $ReviewId = $_POST["ReviewId"];         
          $CreatedById = 0;
          if(strlen($_POST["createdby"])>0)
          {
          	if(strtolower($_POST["createdby"])=="root")
          	{
          	  $CreatedById = -1;
          	}
          	else 
          	{
            	  $u = $objUsers->GetItemByField("Login",$_POST["createdby"]);
            	  if(is_object($u))
            	  {
            	    $CreatedById = $u->Get("PortalUserId");
            	    if($CreatedById<1)
            	    {
            	  	  $CreatedById = $objSession->Get("PortalUserId");
            	    }
            	  }
            	  else
            	    $CreatedById = $objSession->Get("PortalUserId");
          	}
          }         
          $r = $objReviews->EditReview($ReviewId,$CreatedOn,$ReviewText,$Status, $IPAddress, 
                                       (int)$_POST["review_priority"],$_POST["ItemId"],$_POST["ItemType"],
                                       $CreatedById,$html, $post_info['Module']);  
        }
      break;
      case "m_review_delete":
          $objReviews = new clsItemReviewList();
          $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
          foreach($_POST["itemlist"] as $id)
          {
              $objReviews->DeleteReview($id);
          }         
      break;
      case "m_review_approve":
          if (isset($_POST["itemlist"]))
          {   
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              foreach($_POST["itemlist"] as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->Set("Status",1);
                  $i->Update();
              }
          }
      break;
      case "m_review_deny":
          if (isset($_POST["itemlist"]))
          {   
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              foreach($_POST["itemlist"] as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->Set("Status",0);
                  $i->Update();
              }
          }
      break;     
      case "m_review_move_up":
          if (isset($_POST["itemlist"]))
          {   
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              foreach($_POST["itemlist"] as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->MoveUp();
              }
          }
      break;
      case "m_review_move_down":
          if (isset($_POST["itemlist"]))
          {
              $objReviews = new clsItemReviewList();
              $objReviews->SourceTable = $objSession->GetEditTable("ItemReview");
              $itemlist=array_reverse($_POST["itemlist"]);
              foreach($itemlist as $id)
              {
                  $i = $objReviews->GetItem($id);
                  $i->MoveDown();
              }
          }
      break;
      case "m_theme_add":
          $objEditItems = new clsThemeList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Theme");
          $Primary = (int)$_POST["primary"];
          if(!(int)$_POST["enabled"])
            $Primary = 0;
          $t = $objEditItems->AddTheme($_POST["name"],$_POST["description"],(int)$_POST["enabled"],
                                       (int)$_POST["CacheTimeout"],$Primary);
 
          $ado = &GetADODBConnection();
          $rs = $ado->Execute("SELECT MIN(ThemeId) as MinValue FROM ".$objEditItems->SourceTable);
          $NewId = $rs->fields["MinValue"]-1;
          $sql = "UPDATE ".$objEditItems->SourceTable." SET ThemeId=".$NewId." WHERE ThemeId=".$t->Get("ThemeId");
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          if ($Primary==1) 
          {
              $objEditItems->SetPrimaryTheme($_POST["ThemeId"]);
          }
          $ado->Execute($sql);
      break;
      case "m_theme_edit":        
          $objEditItems = new clsThemeList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Theme");
          $Primary = (int)$_POST["primary"];
          if(!(int)$_POST["enabled"])
            $Primary = 0;         
            
          $objEditItems->EditTheme($_POST["ThemeId"],$_POST["name"],$_POST["description"],
                                   (int)$_POST["enabled"],$Primary,(int)$_POST["CacheTimeout"]);
          if ($Primary==1) 
          {
              $objEditItems->SetPrimaryTheme($_POST["ThemeId"]);
          }
          
      break;
      case "m_theme_delete":
      	if($ro_perm) break;    
      	if (isset($_POST["itemlist"]))
          {   
              $Themes = new clsThemeList();
              foreach($_POST["itemlist"] as $id)
              {
                  $Themes->DeleteTheme($id);
              }
          }
      break;
      case "m_theme_primary":
      	if($ro_perm) break;
      	if( count($_POST['itemlist']) )
      	{
      		$ThemeId = array_shift( $_POST['itemlist'] );
      		$t = new clsThemeList();
      		$t->SetPrimaryTheme($ThemeId);
      	}
      	break;
      
      case "m_template_edit":
        	if($ro_perm) break;
        	$ThemeId = $_POST["ThemeId"];
        	$FileId = $_POST["FileId"];
        	$f = new clsThemeFile($FileId);
        
        	$f->Set("Description", $_POST["Description"] );
        	$f->Update();
        	$c = stripslashes($_POST["contents"]);
        	$f->SaveFileContents($c);
        	break;    
      case "m_template_add":
       	if($ro_perm) break;
       	$ThemeId = $_POST["ThemeId"];
       	if( !is_object($f) ) $f = new clsThemeFile();
        	
        	$FilePath = $_POST['name'];
       
        	if(!$FilePath)
        	{
        		$f->SetError('Template Name is required',3);
        		break;
        	}
        	else
        	{
        		if( substr($FilePath,1) != '/' ) $FilePath = '/'.$FilePath;
        		if( substr($FilePath,-3) != '.tpl' ) $FilePath .= '.tpl';
        		$FileName = basename($FilePath);
        		$FilePath = dirname($FilePath);
  			
  			// test if such file not already created
        		
        		$f->LoadFromDataBase( Array($FilePath,$FileName), Array('FilePath','FileName') );      	
        		if( !$f->Get('FileId') )
        		{
        			$f->Set( 	Array('FilePath','FileName','ThemeId', 'Description'),
        						Array($FilePath, $FileName,$_POST['ThemeId'], $_POST["Description"])
        					);
        			
        			if( $f->IsWriteablePath(true) )
        			{	
        				$f->Create();
        				$c = stripslashes($_POST["contents"]);
        				$f->SaveFileContents($c, true);
        			}
        		}
        		else
        			$f->SetError('Template with this name already exists',4);
 		}
      	break;
      case "m_template_delete":
      	if($ro_perm) break;
 		$dummy = new clsThemeFile();
 		foreach($_POST["itemlist"] as $FileId)
         {            
 			$dummy->LoadFromDatabase($FileId);
 			$dummy->Delete();
 		}		
      	break;
      	
      case "m_lang_add":         
          $objEditItems = new clsLanguageList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Language");
          $l = $objEditItems->AddLanguage($_POST["packname"],$_POST["localname"],
                                          (int)$_POST["enabled"],(int)$_POST["primary"],
                                          $_POST["icon"],$_POST["date_format"],$_POST["time_format"],
                                          $_POST["decimal"],$_POST["thousand"]);
 
          $ado = &GetADODBConnection();
          $rs = $ado->Execute("SELECT MIN(LanguageId) as MinValue FROM ".$objEditItems->SourceTable);
          $NewId = $rs->fields["MinValue"]-1;
          $sql = "UPDATE ".$objEditItems->SourceTable." SET LanguageId=".$NewId." WHERE LanguageId=".$l->Get("LanguageId");
          if($objSession->HasSystemPermission("DEBUG.LIST"))
              echo $sql."<br>\n";
          $ado->Execute($sql);         
          if($_POST["importlabels"]==1 && $_POST["srcpack"]>0)
          {         	
             // Phrase import
          	$sql = "SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$_POST["srcpack"];
             if($objSession->HasSystemPermission("DEBUG.LIST"))
                 echo $sql."<br>\n";
 
             $rs = $ado->Execute($sql);            
             $plist = new clsPhraseList();
             $plist->SourceTable = $objSession->GetEditTable("Phrase");
             $sql = "SELECT MIN(PhraseId) as MinId FROM ".$plist->SourceTable;
             $as = $ado->Execute($sql);
             if($as && !$as->EOF)
             {
             	$MinId = (int)$as->fields["MinId"];
             }
             else
               $MinId = 0;
             $MinId--;              
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $plist->AddPhrase($data["Phrase"],$NewId,$data["Translation"],$data["PhraseType"]);
                 $sql = "UPDATE ".$plist->SourceTable." SET PhraseId=$MinId WHERE PhraseId=0 LIMIT 1";
                 $ado->Execute($sql);
                 $MinId--;
                 $rs->MoveNext();
             }
             
             // Events import
             $sql = "SELECT * FROM ".GetTablePrefix()."EmailMessage WHERE LanguageId=".$_POST["srcpack"];
             if($objSession->HasSystemPermission("DEBUG.LIST"))
                 echo $sql."<br>\n";
 
             $rs = $ado->Execute($sql); 
             
             $eList = new clsEmailMessageList();
             //$eList->SourceTable = $objSession->GetEditTable("EmailMessage");
             
        		if (!$l->TableExists($objSession->GetEditTable("EmailMessage"))) {
        			$eList->CreateEmptyEditTable("EmailMessageId", true);
        			$eList->SourceTable = $objSession->GetEditTable("EmailMessage");
        		}
        		else {
        			$eList->SourceTable = $objSession->GetEditTable("EmailMessage");
        		}
             
             $sql = "SELECT MIN(EmailMessageId) as MinId FROM ".$eList->SourceTable;
             $as = $ado->Execute($sql);
             
             if($as && !$as->EOF)
             {
             	$MinId = (int)$as->fields["MinId"];
             }
             else {
               $MinId = 0;
             }
             
             $MinId--;
 
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $eList->AddEmailEvent($data["Template"], $data["MessageType"], $NewId, $data["EventId"]);
                 
                 $sql = "UPDATE ".$eList->SourceTable." SET EmailMessageId=$MinId WHERE EmailMessageId=0 LIMIT 1";
                 $ado->Execute($sql);
                 
                 $MinId--;
                 
                 $rs->MoveNext();
             }            
          }
      break;
      case "m_lang_export":
      	if($ro_perm) break;
      	include_once($pathtoroot."kernel/include/xml.php");
      	$Ids = $_POST["LangList"]; // language ids list to export phrases from
 
      	$phrase_types = GetVar('langtypes');
      	$phrase_types = ($phrase_types !== false) ? implode(',',$phrase_types) : null;
 
      	$filename=$_POST["filename"];
      	if(strlen($filename)>0)
      	{
      		$ExportFilename = $pathtoroot.$admin."/export/".$filename;
      		$ExportResult = $objLanguages->ExportPhrases($ExportFilename,$Ids, $phrase_types);
      	}
      	break;
      	
      case "m_lang_edit":
          $objEditItems = new clsLanguageList();
          $objEditItems->SourceTable = $objSession->GetEditTable("Language");
          $objEditItems->EditLanguage($_POST["LanguageId"],$_POST["packname"],
                                      $_POST["localname"],(int)$_POST["enabled"],
                                      (int)$_POST["primary"], $_POST["icon"],$_POST["date_format"],
                                      $_POST["time_format"], $_POST["decimal"],$_POST["thousand"]);
                                      
          if($_POST["importlabels"]==1 && $_POST["srcpack"]>0)
          {
             $ado = &GetADODBConnection();
             $rs = $ado->Execute("SELECT * FROM ".GetTablePrefix()."Phrase WHERE LanguageId=".$_POST["srcpack"]);
             $plist = new clsPhraseList();
             $plist->SourceTable = $objSession->GetEditTable("Phrase");
             $sql = "SELECT MIN(PhraseId) as MinId FROM ".$plist->SourceTable;
             $as = $ado->Execute($sql);
             if($as && !$as->EOF)
             {
             	$MinId = (int)$as->fields["MinId"];
             }
             else
               $MinId = 0;
             $MinId--;  
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $plist->AddPhrase($data["Phrase"],$_POST["LanguageId"],$data["Translation"],$data["PhraseType"]);
                 $sql = "UPDATE ".$plist->SourceTable." SET PhraseId=$MinId WHERE PhraseId=0 LIMIT 1";
                 $ado->Execute($sql);
                 $MinId--;
                 $rs->MoveNext();
             }
             unset($plist);
             
             // Events import
             $sql = "SELECT * FROM ".GetTablePrefix()."EmailMessage WHERE LanguageId=".$_POST["srcpack"];
             if($objSession->HasSystemPermission("DEBUG.LIST"))
                 echo $sql."<br>\n";
 
             $rs = $ado->Execute($sql); 
             
             $eList = new clsEmailMessageList();
             //$eList->SourceTable = $objSession->GetEditTable("EmailMessage");
             $l = new clsEmailMessage();
        		if (!$l->TableExists($objSession->GetEditTable("EmailMessage"))) {
        			$eList->CreateEmptyEditTable("EmailMessageId", true);
        			$eList->SourceTable = $objSession->GetEditTable("EmailMessage");
        		}
        		else {
        			$eList->SourceTable = $objSession->GetEditTable("EmailMessage");
        		}
             
             $sql = "SELECT MIN(EmailMessageId) as MinId FROM ".$eList->SourceTable;
             $as = $ado->Execute($sql);
             
             if($as && !$as->EOF)
             {
             	$MinId = (int)$as->fields["MinId"];
             }
             else {
               $MinId = 0;
             }
             
             $MinId--;
             
             while($rs && !$rs->EOF)
             {
                 $data = $rs->fields;
                 $eList->AddEmailEvent($data["Template"], $data["MessageType"], $_POST["LanguageId"], $data["EventId"]);
                 
                 $sql = "UPDATE ".$eList->SourceTable." SET EmailMessageId=$MinId WHERE EmailMessageId=0 LIMIT 1";
                 $ado->Execute($sql);
                 
                 $MinId--;
                 
                 $rs->MoveNext();
             }
             unset($eList);
          }
 
      break;
      case "m_lang_delete":
 	     if($ro_perm) break;
 	     if (isset($_POST["itemlist"]))
 	     {
 	     	$Phrases = new clsPhraseList();
 	     	$Messages = new clsEmailMessageList();
 	     	foreach($_POST["itemlist"] as $id)
 	     	{
 	     		$objLanguages->DeleteLanguage($id);
 	     		$Phrases->DeleteLanguage($id);
 	     		$Messages->DeleteLanguage($id);
 	     	}
 	     	unset($Phrases);
 	     	unset($Messages);
 	     }
 	     break;
 	     
      case "m_lang_select":
         if($ro_perm) break; 
      	$LangId = (int)$_POST["langselect"];         
      	if($LangId)
      	{
      		if($objSession->Get("PortalUserId")>0)
      		{
      			//echo "$LangId";
      			$objSession->SetPersistantVariable("Language",$LangId);
      		}
      		$objSession->Set("Language",$LangId);
      		$objSession->Update();
      		$m_var_list_update["lang"] = $LangId;
      		$m_var_list["lang"] = $LangId;
      	}
      	break;     
      	
      case "m_phrase_edit":     
          $objPhraseList = new clsPhraseList();
          if((int)$_POST["direct"] != 1)                 	
          	$objPhraseList->SourceTable = $objSession->GetEditTable("Phrase");
          $Phrases = $_POST["name"];
          foreach($Phrases as $PhraseId =>$name)
          {
            if($PhraseId>0)
            {         
            		$objPhraseList->EditPhrase($PhraseId,$_POST["name"][$PhraseId],$_POST["LanguageId"],$_POST["translation"][$PhraseId],$_POST["phrasetype"][$PhraseId]);
            }
          }
          
          if(strlen($_POST["name"][0]) && strlen($_POST["translation"][0]) && $_POST['Action1'] == "new")
          {
            		$r = $objPhraseList->AddPhrase($_POST["name"][0],$_POST["LanguageId"],$_POST["translation"][0],$_POST["phrasetype"][0]);           
            		if ($r != "Error") {
 	           		$ado = &GetADODBConnection();
 	           		$rs = $ado->Execute("SELECT MIN(PhraseId) as MinValue FROM ".$objPhraseList->SourceTable);
 	           		$NewId = $rs->fields["MinValue"]-1;
 	           		$sql = "UPDATE ".$objPhraseList->SourceTable." SET PhraseId=".$NewId." WHERE PhraseId=$PhraseId";
 	           		if($objSession->HasSystemPermission("DEBUG.LIST"))
 	               		echo $sql."<br>\n";
 	           		$ado->Execute($sql);    
            		}
            		else {
            			$add_error = "Language tag with the same name already exists!";
            		}
          }
          else if ($_POST['Action1'] == "new") {
          	$add_error = "Fields name and translation are required!";
          }
          unset($objPhraseList);
      break;
      case "m_config_missing_phrase":
         if($ro_perm) break;
         $LangId = $_POST["LangId"];
         $ThemeId = $_POST["ThemeId"];
         if(is_array($_POST["Phrase"]))
         {
             $objPhraseList = new clsPhraseList();
             $objPhraseList->SourceTable = $objSession->GetSessionKey()."_".$ThemeId."_labels";
 
             foreach($_POST["Phrase"] as $p => $value)
             {
                 if(strlen($value))
                 {           
                   $obj = $objPhraseList->GetItemByField("Phrase",$p,TRUE);
                   if(is_object($obj))
                   {                  
                       if($obj->Get("Phrase")==$p)
                       {
                           $obj->Set("Translation",$value);
                           $obj->Update();
                       }
                       else
                           $objPhraseList->AddPhrase($p,$LangId,$value,1);
                   }
                   else
                     $objPhraseList->AddPhrase($p,$LangId,$value,1);
                 }
             }
         }
      break;
      case "m_phrase_delete":
      	if (isset($_POST["itemlist"]))
         {   
            foreach($_POST["itemlist"] as $id)
            {
            	 $sql = "UPDATE ".$objSession->GetEditTable("Phrase")." SET LanguageId = 0 WHERE PhraseId = ".$id;
            	 $ado = &GetADODBConnection();
            	 $ado->Execute($sql);
            }
         }
         unset($objPhraseList);
      break;
      case "m_emailevent_disable":
         if($ro_perm) break;
         $objEvents = new clsEventList();
         if (isset($_POST["itemlist"]))
          {   
             foreach($_POST["itemlist"] as $id)
             {
               $m =& $objEvents->GetItem($id);
               $m->Set("Enabled",0);
               $m->Update();
             }
          }
          unset($objEvents);
      break;
      case "m_emailevent_enable":
          if($ro_perm) break;
          $objEvents = new clsEventList();
          if (isset($_POST["itemlist"]))
          {   
             foreach($_POST["itemlist"] as $id)
             {
               $m =& $objEvents->GetItem($id);
               $m->Set("Enabled",1);
               $m->Update();
             }
          }
          unset($objEvents);
      break;
      case "m_emailevent_frontonly":
         if($ro_perm) break;
         $objEvents = new clsEventList();
         if (isset($_POST["itemlist"]))
          {   
             foreach($_POST["itemlist"] as $id)
             {
               $m =& $objEvents->GetItem($id);
               $m->Set("Enabled",2);
               $m->Update();
             }
          }
          unset($objEvents);
      break;     
      case "m_dlid":
          echo $Action.":".$DownloadId;
          die();
      break;
      case "m_emailevent_user":
          if($ro_perm) break;
          $objEvents = new clsEventList();
          //phpinfo(INFO_VARIABLES);
          //$objEvents->SourceTable = $objSession->GetEditTable("Events");
          $ids = $_POST["EventId"];
 		 $ids = str_replace("[","",$ids);
 		 $ids = str_replace("]","",$ids);
 		 $ids = str_replace("\"","",$ids);
 		 $ids = str_replace("\\","",$ids);
 		 
          
          $idlist = explode(",",$ids);
          foreach($idlist as $EventId)
          {
          	$id = (int)stripslashes($EventId);
              $e =& $objEvents->GetItem((int)$EventId);
              $e->Set("FromUserId", $_POST["FromUserId"]);
              $e->Update();
          }
          $objEvents->Clear();
          unset($objEvents);
      break;
      case "m_emailevent_edit":         
          $Template = $_POST["headers"];
          if(strlen($Template))
          {
          	$Template .= "\n";
          }
 		 $Template = str_replace("\n\n","",$Template);                     
          $Template .= "Subject: "._unhtmlentities($_POST['subject'])."\n\n";
          $Template .= $_POST["messageBody"];
          $objMessages = new clsEmailMessageList();
          $objMessages->SourceTable = $objSession->GetEditTable("EmailMessage");
          $m =& $objMessages->GetItem($_POST["MessageId"]);
          if(is_object($m))
          {
              if($_POST["sendhtml"]==1)
              {             
                $m->Set("MessageType","html");
              }
              else
                $m->Set("MessageType","text");
 
              $m->Set("Template",$Template);
              $m->Update();
          }
      break;
      case "m_config_edit":
      	 //phpinfo(INFO_VARIABLES);
          if($ro_perm) break;
          $objAdmin = new clsConfigAdmin();
          $objAdmin->module = $_POST["module"];
          $objAdmin->section = $_POST["section"];
          if($objAdmin->section=="in-portal:configure_users")
          {
          	if(strlen($_POST["RootPass"]) && strlen($_POST["RootPassVerify"]))
          	{
          	  if($_POST["RootPass"]==$_POST["RootPassVerify"])
          	  {
          	  	$_POST["RootPass"] = md5($_POST["RootPass"]);
          	  }	
          	}
          	else
          	{
          	  $_POST["RootPass"] = $objConfig->Get("RootPass");
          	  $_POST["RootPassVerify"] = $objConfig->Get("RootPassVerify");         	  
          	}
          }
          $objAdmin->LoadItems(FALSE);
          $objAdmin->SaveItems($_POST);
      break;
 
      case "m_mod_enable":
         if($ro_perm) break;
          if (isset($_POST["itemlist"]))
          {   
              foreach($_POST["itemlist"] as $id)
              {
                  $m =& $objModules->GetItemByField("Name",$id);
                  if(is_object($m))
                  {
                    $m->Set("Loaded",1);
                    $m->Update();                 
                  }                
              }
              $_GET["Refresh"] = 1;
          }
      break;
      case "m_mod_disable":
      	if($ro_perm) break;
          if (isset($_POST["itemlist"]))
          {   
              foreach($_POST["itemlist"] as $id)
              {
              	if($id != "In-Portal")
              	{
                    $m =& $objModules->GetItemByField("Name",$id);
                    if(is_object($m))
                    {
                      $m->Set("Loaded",0);
                      $m->Update();                 
                    }
              	}
              }
              $_GET["Refresh"] = 1;
          }
      break;
 
      case "m_img_add":
        $objImageList = new clsImageList();
 	   $objImageList->SourceTable = $objSession->GetEditTable("Images");
        $LocalImage=0;
        $LocalThumb=0;
        $DestDir = "kernel/images/";
        
        $UserThumbSource = (int)$_POST["imgLocalThumb"];
 	   $LocalThumb = $UserThumbSource;
        
 	   $thumb_url = !$LocalThumb? $_POST["imgThumbUrl"] : "";
               
        if($_POST["imgSameImages"])
        {
            	$LocalImage = $LocalThumb;
            	$full_url = $thumb_url;
        }
        else
        {
        		$LocalImage = (int)$_POST["imgLocalFull"];
          	$file = $_FILES["imgFullFile"];
          	$full_url = $LocalImage? "" : $_POST["imgFullUrl"];
        }
 
        if((!strlen($thumb_url) && !$LocalThumb) || (!strlen($full_url) && !$LocalImage))
        {
          break;
        }
        
        $ado = &GetADODBConnection();
        $NewId = $ado->GetOne('SELECT MIN(ImageId) as MinValue FROM '.$objImageList->SourceTable);
        if($NewId > 0) $NewId = 0;
        $NewId--;
        $img = $objImageList->Add($_POST["imgName"], $_POST["imgAlt"], $_POST["ResourceId"], $LocalImage, $LocalThumb, $full_url, $thumb_url, (int)$_POST["imgEnabled"], 0, (int)$_POST["imgDefault"], 0,(int)$_POST["imgSameImages"], $NewId);
        $img->Set("ImageId", $NewId);
        
 //       $img->debuglevel=1;
        
        /*
        $sql = "UPDATE ".$objImageList->SourceTable." SET ImageId=".$NewId." WHERE ImageId=0";
        $ado->Execute($sql);
        
 //       $img->Update();
        */
 //       echo "SL: $sql $NewId<BR>";
        
 //       $img->debuglevel=1;
         
 	   $img->Pending=TRUE;	                                 
        if($LocalImage)
        {
            $file = $_FILES["imgFullFile"];
            if(is_array($file))
            {
              if($file["size"]>0)
              {
                $img->Set("LocalPath",$img->StoreUploadedImage($file,1, $DestDir,0));
                $uploaded=1;
              }
            }
        }
        
        if($LocalThumb)
        {
            $thumb = $_FILES["imgThumbFile"];
            if(is_array($thumb))
            {
              if($thumb["size"]>0)
              {
                $img->Set("ThumbPath",$img->StoreUploadedImage($thumb,1, $DestDir,1));
                $uploaded=1;
              }
            }
        }  
        if($uploaded==1)
           $img->Update();
        
      break;
      
      case "m_img_edit":
      
        	$objImageList = new clsImageList();
        	$objImageList->SourceTable = $objSession->GetEditTable("Images");
        
 //       $img->debuglevel=1;
        
        	$img = $objImageList->GetItem($_POST["ImageId"]);
 
 	    ## Get original values
        	$LocalImage = $img->Get("LocalImage");
        	$LocalThumb = $img->Get("LocalThumb");
        	$SameImages = $img->Get("SameImages");
        	$ThumbPath = $img->Get("ThumbPath");
        
        	## New values
        	$LocalThumbN = (int)$_POST["imgLocalThumb"];
        	$LocalImageN = (int)$_POST["imgLocalFull"];
        	
  		$FULLFile = $_FILES["imgFullFile"];
         $THFile = $_FILES["imgThumbFile"]; 
         
         $DestDir = "kernel/images/";
         $img->Pending = FALSE;
         
         $SameImagesN = 0;
         $uploaded = 0;
 
        	## Images were the same, but not any more
        	if ($SameImages && !$_POST["imgSameImages"])
        	{	
        		## TH was a local file
         	if ($LocalThumb)
         	{
         		## TH image
         		{	
         			## Try to Delete OLD FULL
 				   	$img->DeleteLocalImage(FALSE, TRUE);
 				   	
 				   	## FULL image select, but field EMPTY - make a copy of old TH as FULL 
         			if ($LocalImageN && !(int)$FULLFile["size"])
         			{   
 //        				echo $pathToPending = $img->GetImageDir();
         				if (!eregi("pending/$", $pathToPending))
 	        				$pathToPending.= "pending/"; 
         					
         				$LocalThumb_File = $img->GetFileName(1);
         				
 //        				echo "<b>CAN'T FIND FILE:</b> ".$pathToPending.$LocalThumb_File."<BR>";
         				
         				if (file_exists($pathToPending.$LocalThumb_File))
 						{							
 				   			$LocalThumb_FileN = eregi_replace("^th_", "", $LocalThumb_File);		   			
 							$LocalThumb_FullFileN = $pathToPending.$LocalThumb_FileN;						
 							@unlink($LocalThumb_FullFileN);
 							@copy($pathToPending.$LocalThumb_File, $LocalThumb_FullFileN);
 					
 			   				$uploaded = 1;
 			   				$copied = 1;
 //			   				echo "COPING: ".$DestDir."pending/".$LocalThumb_FileN." <BR>";
 						}
 						else
 						{
 //							echo "CAN'T FIND FILE: ".$pathToPending.$LocalThumb_File."<BR>";
         				}					
         			}
         			## Upload new FULL image
         			elseif ($LocalImageN && (int)$FULLFile['size'])
         			{
         				$FULL_FileToUpload = $FULLFile;
         				$FULL_URL = "";         
         				
 //        				echo "	Upload new FULL image";				
         			}
         			## Full is URL
         			elseif (!$LocalImageN)
         			{
         				$img->DeleteLocalImage(FALSE, TRUE);
         				$FULL_URL = $_POST['imgFullUrl'];  
         				$FULL_FileToUpload = "";      			
         			}
         			else
         			{
 //        				echo "	## Unknow condition";
         			}
         				
         			## Take care of Thumbnail here
         			if ($LocalThumbN)
         			{     			        			
         				## Delete old if NEW TH image selected
         				if ((int)$THFile['size'])
         				{
         					$img->DeleteLocalImage(TRUE, FALSE);
         					$TH_FileToUpload = $THFile;
         				}
         				else
         					$TH_FileToUpload = "";        			
         			}
         			else
         			{
         				$img->DeleteLocalImage(TRUE, FALSE);
         				$TH_FileToUpload = "";
         				$TH_URL = $_POST['imgThumbUrl'];     
         			}
         		}
         	}
         	## TH was URL
         	else
         	{
         		## Take care of FULL image here
         		if ($LocalImageN && (int)$FULLFile["size"])
         		{
         			$FULL_FileToUpload = $FULLFile; 
         			$FULL_URL = "";        				
         		}
         		## Full is URL (or image size 0)
         		else
         		{
         			$FULL_FileToUpload = "";
         			$FULL_URL = $_POST['imgFullUrl'];        	      		
         		}
         		
         		## Take care of Thumbnail here
         		if ($LocalThumbN)    
         		{ 			        			
         			$TH_FileToUpload = (int)$THFile['size']? $THFile : "";        			
         			$TH_URL = "";
         		}
         		else
         		{
         			$TH_FileToUpload = "";
         			$TH_URL = $_POST['imgThumbUrl'];     
         		}     		
         	}
        	}
       	## Images were the same, and still the same
        	elseif ($SameImages && $_POST['imgSameImages'])
        	{       		
        		## Take care of Thumbnail & FULL here
         	if ($LocalThumbN)
         	{	        			        		
         		if ((int)$THFile['size'])
         		{
         			$img->DeleteLocalImage(TRUE, FALSE);
         			$TH_FileToUpload = $THFile;
         		}
         		else 
         			$TH_FileToUpload = "";
         			
         		$FULL_URL = $TH_URL = "";      			
         	}
         	else
         	{
         		$TH_FileToUpload = $FULL_FileToUpload = "";
         		$FULL_URL = $TH_URL = $_POST['imgThumbUrl'];            		 
         	}
         	
         	## Delete old FULL image    		
        		$img->DeleteLocalImage(FALSE,TRUE);
         	
         	$SameImagesN = 1;        	
        	}
        	## Images were NOT the same, and selected as the same now
        	elseif (!$SameImages && $_POST["imgSameImages"])
        	{
        		## Take care of Thumbnail & FULL here
         	if ($LocalThumbN)
         	{	        			
         		if ((int)$THFile['size'])
         		{
         			$img->DeleteLocalImage(TRUE, FALSE);
         			$TH_FileToUpload = $THFile;
         		}
         		else 
         			$TH_FileToUpload = "";
         		
         		
         		$FULL_URL = $TH_URL = "";        			
         	}
         	else
         	{   
         		$img->DeleteLocalImage(TRUE, FALSE);
         		$TH_FileToUpload = $FULL_FileToUpload = "";
         		$FULL_URL = $TH_URL = $_POST['imgThumbUrl'];         		           		 
         	}
         	
         	## Clean up FULL image
         	$img->DeleteLocalImage(FALSE, TRUE);	
         	
         	$SameImagesN = 1;
        	}
        	## Images were NOT the same, and selected as NOT the same
        	elseif (!$SameImages && !$_POST["imgSameImages"])
        	{
        		## Take care of Thumbnail
         	if ($LocalThumbN)
         	{	        			
         		if ((int)$THFile['size'])
         		{
         			$img->DeleteLocalImage(TRUE, FALSE);
         			$TH_FileToUpload = $THFile;        			
         		}
         		else 
         			$TH_FileToUpload = "";       		
         		
         		$TH_URL = "";
         	}
         	else
         	{
         		$img->DeleteLocalImage(TRUE, FALSE);
         		$TH_FileToUpload = "";
         		$TH_URL = $_POST['imgThumbUrl'];            		 
         	}
         	
         	## Take care of FULL here
         	if ($LocalImageN)
         	{
         		if ((int)$FULLFile['size'])
         		{
         			$img->DeleteLocalImage(FALSE, TRUE);
         			$FULL_FileToUpload = $FULLFile;
         		}
         		else
         			$FULL_FileToUpload = "";       	        	
         		
         		$FULL_URL = "";
         	}
         	else
         	{        		
         		$img->DeleteLocalImage(FALSE, TRUE);        		
         		$FULL_FileToUpload = "";
         		$FULL_URL = $_POST['imgFullUrl'];
         	}        	
        	}
        	## Unknow condition	
        	else
        	{
        		;
        	}
      
 		$img = $objImageList->Edit($_POST["ImageId"],$_POST["imgName"], $_POST["imgAlt"], $_POST["ResourceId"], $LocalImageN, $LocalThumbN, $FULL_URL, $TH_URL, (int)$_POST["imgEnabled"], (int)$_POST["imgPriority"], (int)$_POST["imgDefault"], 0, $SameImagesN);
 		
 //		echo "<B>DATA:</B> <BR> LocalImageN: $LocalImageN, LocalThumbN: $LocalThumbN, FULL_URL: $FULL_URL, TH_URL: $TH_URL, SameImagesN: $SameImagesN <BR>";
        
 	   
 	   	$img->Pending = TRUE;
 	   	
 		if (!empty($FULL_FileToUpload))
 		{
 			$img->Set("LocalPath",$img->StoreUploadedImage($FULL_FileToUpload, 1, $DestDir, 0));
 			$uploaded = 1;
 		}
 		/*
 		elseif (!$LocalImageN)
 		{
 			$img->Set("LocalPath", "");
 			$uploaded = 1;
 		}
 		*/
 		
 		if (!empty($TH_FileToUpload))
 		{
 			$img->Set("ThumbPath", $img->StoreUploadedImage($TH_FileToUpload, 1, $DestDir, 1));
 			$uploaded = 1;
 		}
 		
 		if ($copied)
 		{
 			$img->Set("LocalPath", $DestDir."pending/".$LocalThumb_FileN);	
 			$uploaded = 1;
 		}
 		      
        if($uploaded==1)
           $img->Update();   
               
      break;
      case "m_img_move_up":
          if (isset($_POST["itemlist"]))
          {
              $objImageList = new clsImageList();
              $objImageList->SourceTable = $objSession->GetEditTable("Images");
              foreach($_POST["itemlist"] as $id)
              {
                  $img = $objImageList->GetItem($id);
                  $img->MoveUp();
              }
          }
      break;
      case "m_img_move_down":
          if (isset($_POST["itemlist"]))
          {
              $objImageList = new clsImageList();
              $objImageList->SourceTable = $objSession->GetEditTable("Images");
              $itemlist=array_reverse($_POST["itemlist"]);
              foreach($itemlist as $id)
              {
                  $img = $objImageList->GetItem($id);
                  $img->MoveDown();
              }
          }
      break;
 
      case "m_img_delete":
        if(isset($_POST["itemlist"]))
        {       
          $objImageList = new clsImageList();
          $objImageList->SourceTable = $objSession->GetEditTable("Images");
          foreach($_POST["itemlist"] as $id)
          {
              $img = $objImageList->GetItem($id);
              $img->Set("ResourceId", 0);
              $img->Update();
              //$img->Delete();
          }
        }
      break;
      case "m_restore_delete":
      	if($ro_perm) break;
      	$bdate = $_POST["backupdate"];
      	if($bdate>0)
      	{
      		$BackupFile = $objConfig->Get("Backup_Path")."/dump".$bdate.".txt";
      		if(file_exists($BackupFile))
      		unlink($BackupFile);
      	}
      	break;
      	
      case "m_taglib":
      	include($pathtoroot."kernel/include/tag-class.php");
      	ParseTagLibrary();
     	break;
     	
     case "m_sql_query":
 		if($ro_perm) break;
     	$SqlQuery = $_POST["sql"];
 		$ado = &GetADODBConnection();
 		if(strlen($sql))
 		{
 		  $SqlResult = $ado->Execute(stripslashes($SqlQuery));
   	  	  $SqlError = $ado->ErrorMsg();
 		  $SqlErrorNum = $ado->ErrorNo();
 		}
     break;
     case "m_purge_email_log":
 	 	 if($ro_perm) break;
 	 	 $ado = &GetADODBConnection();       	
 
 		$sql = "DELETE FROM ".GetTablePrefix()."EmailLog";
 		$ado->Execute($sql);
     break;    
     case "m_session_delete":
 	 	 if($ro_perm) break;
 	 	 $ado = &GetADODBConnection();       	
          if (count($_POST['itemlist']) > 0) {
 	 	 	foreach($_POST["itemlist"] as $id)
          	{
       			$sql = "DELETE FROM ".GetTablePrefix()."UserSession WHERE SessionKey='$id'";
       			$ado->Execute($sql);
          	}
          }
          else {
       		$sql = "DELETE FROM ".GetTablePrefix()."UserSession WHERE Status='0'";
       		$ado->Execute($sql);         	
          }
     break;
     case "m_add_rule":
     	$objEditItems = new clsBanRuleList();
     	$objEditItems->SourceTable = $objSession->GetEditTable("BanRules");
     	//$ItemType,$RuleType,$ItemField,$ItemVerb,$ItemValue,$Priority,$Status;
     	$objEditItems->AddRule($_POST["rule_itemtype"],$_POST["rule_type"],$_POST["rule_field"],
     				   $_POST["rule_verb"],$_POST["rule_value"],(int)$_POST["rule_priority"],
     				   (int)$_POST["rule_status"], $_POST['rule_error']);
     break;
     case "m_edit_rule":    	
     	$objEditItems = new clsBanRuleList();
     	$objEditItems->SourceTable = $objSession->GetEditTable("BanRules");
     	//$ItemType,$RuleType,$ItemField,$ItemVerb,$ItemValue,$Priority,$Status;
     	$objEditItems->EditRule($_POST["rule_id"],$_POST["rule_itemtype"],$_POST["rule_type"],$_POST["rule_field"],
     				   $_POST["rule_verb"],$_POST["rule_value"],(int)$_POST["rule_priority"],
     				   (int)$_POST["rule_status"], $_POST['rule_error']);
     break;    
     case "m_rule_move_up":
        if($ro_perm) break;
        if(isset($_POST["itemlist"]))
        {                
          foreach($_POST["itemlist"] as $id)
          {
              $i = $objBanList->GetItem($id);
              $i->Increment("Priority");
          }
        }	      
     break;
     case "m_rule_move_down":
        if($ro_perm) break;
        if(isset($_POST["itemlist"]))
        {                
          foreach($_POST["itemlist"] as $id)
          {
              $i = $objBanList->GetItem($id);
              $i->Decrement("Priority");
          }
        }	      
     break;
     
 	case "m_rule_delete":
        if($ro_perm) break;
        if(isset($_POST["itemlist"]))
        {                
          foreach($_POST["itemlist"] as $id)
          {
              $i = $objBanList->GetItem($id);
              $i->Delete();
          }
        }		
     break;    
     case "m_ban_user":
       if($ro_perm) break;
       if($_POST["UserEditStatus"]==1)
       {
         $UserId = $_POST["user_id"];
         $u = $objUsers->GetItem($UserId);
         if(is_object($u))
         {
         	if((int)$_POST["ban_login"])
         	{
         		if(strlen($_POST["user_login"]))
         			$objBanList->AddRule(6,0,"Login",3,$_POST["user_login"],0,1);
         	}
         	if((int)$_POST["ban_email"])
         	{
         		if(strlen($_POST["user_email"]))
         			$objBanList->AddRule(6,0,"Email",3,$_POST["user_email"],0,1);
         	}
         	if((int)$_POST["ban_ip"])
         	{
         		if(strlen($_POST["user_ip"]))
         			$objBanList->AddRule(6,0,"ip",3,$_POST["user_ip"],0,1);
         	}       
         	$u->Deny(); 	
         }
       }
     	break;  
     	
     }
 
 /* image upload management */
 if( isset($_POST['img']) && $_POST['img'] == 1 )
 {
     foreach($_FILES as $img => $FILE)
     {
         $name = $_POST["img_Name_$img"];
         $alt = $_POST["img_Alt_$img"];
         $url = $_POST["img_Url_$img"];
         $res_id = $_POST["img_Res_$img"];
         $relvalue = $_POST["img_Rel_$img"];
         $thumb = (int)$_POST["img_Thumb_$img"];
         $dest = AddSlash($_POST["img_DestDir_$img"]);
         if($_POST["img_Del_$img"]=="Delete")
         {
             $img = $objImageList->GetImageByResource($res_id,$relvalue);
             $img->Delete();
             unset($img);
             $objImageList->Clear();
         }
         else
         {
           if($FILE["size"]>0)
           {
             /* an image was uploaded */
             $objImageList->HandleImageUpload($FILE,$res_id,$relvalue,$dest, $name,$alt,$thumb);
           }
           else
           {    /* remote images handled here */
             if(strlen($url)>0)
             {                   
               if($relvalue>0)
               {                                            
                $img = $objImageList->GetImageByResource($res_id,$relvalue);
                $img->Set("Name",$name);
                $img->Set("AltName", $alt);
                $img->Set("IsThumbnail",$thumb);
                $img->Set("Url",$url);
                $img->Update();
               }
               else
               {
                $relvalue = $objImageList->GetNextRelateValue($res_id);
                $objImageList->NewRemoteImage($url,$res_id,$relvalue, $name, $alt, $thumb);
               }
             }
           }
         }
     }
 }
 
 // ALL Saving Stuff From Temp Tables Heppens Here
 
 //echo "==== BEGIN ==== <br>";
 $has_perm = $objSession->HasSystemPermission("SYSTEM_ACCESS.READONLY");
 //echo "PortalUserID: [".$objSession->Get("PortalUserId")."]<br>";
 //print_pre($objSession);
 //echo "PermSet: [".$has_perm."]<br>";
 
 if( !$has_perm )
 {
 
 	/* category Edit */
 	if( GetVar('CatEditStatus') == 1 )
 	{ 
 	    $adodbConnection = &GetADODBConnection();
 	//    $sql = "SELECT * FROM ".$objSession->GetEditTable("Category")." WHERE CategoryId=0";    
 	    $sql = "SELECT ParentId FROM ".$objSession->GetEditTable("Category")." WHERE CategoryId=-1";
 	    
 	    $rs = $adodbConnection->Execute($sql);
 	    while ($rs && !$rs->EOF) 
 	    {
 	        if($rs->fields["ParentId"] > 0) RunUp($rs->fields["ParentId"],"Increment_Count");
 	        $rs->MoveNext();
 	    }
 	  
 	    $objCatList->CopyFromEditTable("CategoryId");
 	    $objCustomDataList->CopyFromEditTable("CustomDataId");
 	    $objCatList->Clear();
 
 	    if($_REQUEST['CategoryId'] > 0) // not root category is updated
 	    {
 	    	$objImages = new clsImageList();
 	    	$objImages->CopyFromEditTable("ImageId");
 		}
 	}
 	
 	if( GetVar('CatEditStatus') == 2 )
 	{ 
 	    $objCatList->PurgeEditTable("CategoryId");
 	    $objCustomDataList->PurgeEditTable("CustomDataId");
 	  	if($_REQUEST['CategoryId'] > 0) // not root category is updated
 	    {
 	    	$objImages = new clsImageList();
 	    	$objImages->CopyFromEditTable("ImageId");
 	    	//$objImages->PurgeEditTable("ImageId");
 	    }
 	    $objCatList->Clear();
 	}
 	
 	/* User Edit */
 	if( GetVar('UserEditStatus') == 1 )
 	{
 	    $objUsers->CopyFromEditTable("PortalUserId");
 	    $objCustomDataList->CopyFromEditTable("CustomDataId");
 	    $objGroups->Clear();
 	    $objImages = new clsImageList();
 	    $objImages->CopyFromEditTable("ImageId");    
 	}
 	if( GetVar('UserEditStatus') == 2 )
 	{
 	    $objGroups->PurgeEditTable("PortalUserId");
 	    $objCustomDataList->PurgeEditTable("CustomDataId");
 	    $objGroups->Clear();
 	}
 	
 	/* Group Edit */
 	if( GetVar('GroupEditStatus') == 1 )
 	{
 	    $objGroups->CopyFromEditTable("GroupId");
 	    $objCustomDataList->CopyFromEditTable("CustomDataId");
 	    $objGroups->Clear();
 	}
 	if( GetVar('GroupEditStatus') == 2 )
 	{
 	    $objGroups->PurgeEditTable("GroupId");
 	    $objCustomDataList->PurgeEditTable("CustomDataId");
 	    $objGroups->Clear();
 	}
 	
 	/* Theme Edit */
 	if( GetVar('ThemeEditStatus') == 1 )
 	{    
 	    $objThemes->CopyFromEditTable();
 	    $objThemes->Clear();
 	}
 	
 	if( GetVar('ThemeEditStatus') == 2 )
 	{
 	    $objThemes->PurgeEditTable();
 	    $objThemes->Clear();
 	}
 	
 	/* Language Edit */
 	if( GetVar('LangEditStatus') == 1 )
 	{
 	    $objLanguages->CopyFromEditTable();
 	    $objLanguages->Clear();
 	
 	    $Phrases = new clsPhraseList();
 	    $Phrases->CopyFromEditTable();
 	    $Phrases->Clear();
 	    $Phrases->PurgeEditTable();
 	    
 	    $Messages = new clsEmailMessageList();
 	    $Messages->CopyFromEditTable();
 	    $Messages->Clear();	    
 	}          
 	if( GetVar('LangEditStatus') == 2 )
 	{
 	    $objLanguages->PurgeEditTable();
 	    $objLanguages->Clear();
 	    $Phrases = new clsPhraseList();
 	    $Phrases->PurgeEditTable();    
 	    $Messages = new clsEmailMessageList();
 	    $Messages->PurgeEditTable();
 	}
 	
 	if( GetVar('MissingLangEditStatus') == 1 )
 	{
 	   $objPhraseList = new clsPhraseList();
 	   $objPhraseList->SourceTable = $objSession->GetSessionKey()."_".$ThemeId."_labels";
 	   
 	   $objEditList = new clsPhraseList();
 	   $objEditList->SourceTable = $objSession->GetEditTable("Phrase");
 	
 	   $ado = &GetADODBConnection();
 	   $rs = $ado->Execute("SELECT MIN(PhraseId) as MinValue FROM ".$objEditList->SourceTable);
 	   $NewId = $rs->fields["MinValue"]-1;
 	   
 	   $objPhraseList->Query_Item("SELECT * FROM ".$objPhraseList->SourceTable);
 	   foreach($objPhraseList->Items as $p)
 	   {
 	       if(strlen($p->Get("Translation"))>0)
 	       {       
 	         $p->tablename = $objEditList->SourceTable;
 	         $p->Dirty();
 	         $p->UnsetIDField();
 	         $p->Set("PhraseId",$NewId);
 	         $NewId--;
 	         $p->Create();
 	       }
 	   }
 	   $ado->Execute("DROP TABLE IF EXISTS ".$objPhraseList->SourceTable);
 	}
 	
 	if( GetVar('MissingLangEditStatus') == 2 )
 	{
 	  $table = $objSession->GetSessionKey()."_".$ThemeId."_labels";
 	  $ado = &GetADODBConnection();
 	  $ado->Execute("DROP TABLE IF EXISTS ".$table);
 	}
 	
 	/* Ban Rule Edit */
 	if( GetVar('RuleEditStatus') == 1 )
 	{    
 	    $objBanList->CopyFromEditTable("RuleId");
 	    $objBanList->Clear();
 	}
 	if( GetVar('RuleEditStatus') == 2 )
 	{
 	    $objBanList->PurgeEditTable("RuleId");
 	    $objBanList->Clear();
 	}
 }
 elseif( defined('DEBUG_ACTIONS') )
 {
 	if( isset($_REQUEST['Action']) && $_REQUEST['Action'] )
 		echo "<b>USER HAS RO-ACCESS</b> on action [<b>".$_REQUEST['Action']."</b>]<br>";
 }
 
 //echo "==== END ==== <br>";
 
-?>
+?>
\ No newline at end of file

Property changes on: trunk/kernel/action.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.48
\ No newline at end of property
+1.49
\ No newline at end of property
Index: trunk/kernel/include/parseditem.php
===================================================================
--- trunk/kernel/include/parseditem.php	(revision 666)
+++ trunk/kernel/include/parseditem.php	(revision 667)
@@ -1,2959 +1,5917 @@
-<?php
-global $ItemTypePrefixes;
-
-$ItemTypePrefixes = array();
-$ItemTagFiles = array();
-
-function RegisterPrefix($class,$prefix,$file)
-{
- 	global $ItemTypePrefixes, $ItemTagFiles;
-    	
- 	$ItemTypePrefixes[$class] = $prefix;
- 	$ItemTagFiles[$prefix] = $file;
-}
-
-class clsParsedItem extends clsItemDB
-{
-    var $TagPrefix;
-    var $Parser;
-    var $AdminParser;    
-
-    function clsParsedItem($id=NULL)
-    {
-        global $TemplateRoot;
-
-        $this->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 = "<td width=\"$percentsOn%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td><td width=\"$percentsOff%\" bgcolor=\"$OffColor\"><img src=\"img/s.gif\"></td>";        	
-	                	}
-	                	else
-	                		$ret = "<td width=\"100%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td>";      	                	
-	                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 = "<img src=\"$img_src\" border=\"0\" alt=\"".(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 .= "<IMG src=\"$url\" $extra_attribs >";
-                          $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 = "<IMG $extra_attribs SRC=\"".$this->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 = "<IMG src=\"$url\" $extra_attribs >";
-                   }
-                   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."<br>";
-            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,"<inp:");
-          while($next_tag)
-          {
-              $end_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,"<inp:");
-          }
-          array_pop($this->AdminParser->stack);
-      }
-      return $html;
-    }
-
-    function ParseTemplateText($text)
-    {
-    	$html = $text;
-      $search = "<inp:".$this->TagPrefix;
-      //$next_tag = strpos($html,"<inp:");
-      $next_tag = strpos($html,$search);
-      
-
-      while($next_tag)
-      { 
-      	  $closer = strpos(strtolower($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 = "</inp>";
-          	
-          	## Try to find end of TagName
-          	$TagNameEnd = strpos($html, " ", $next_tag);
-          	
-          	## Support Old version
-//          	$closer = strpos(strtolower($html),"</inp>",$next_tag);          
-          	if ($TagNameEnd)
-          	{   			
-          		$Tag = strtolower(substr($html, $next_tag, $TagNameEnd-$next_tag));
-          		$TagName = explode(":", $Tag);          		
-          		if (strlen($TagName[1]))
-          			$CloserTag = "</inp:".$TagName[1].">";
-          	}          	
-          	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<br>';
-      //$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 <br>\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 <br>\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)."<BR>";
-            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 <b>$i</b>:<br>";
-			$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."<br>\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;$x<count($this->Items);$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 [<b>".get_class($this).'</b>], sql: ['.$sql.']<br>';
-       	//if( get_class($this) == 'clsthemefilelist') trace();
-        $dummy =& $this->GetDummy();
-       	if( !$dummy->TableExists() )
-       	{
-       		if($this->debuglevel) echo "ERROR: table <b>".$dummy->tablename."</b> missing.<br>";
-       		$this->Clear();
-       	 	return false;
-       	}
-       	
-        if($rows>-1 && $offset>-1)
-        {
-        	//print_pre(debug_backtrace());
-	       	//echo "<b>Executing SelectLimit</b> $sql <b>Offset:</b> $offset,$rows<br>\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 '<br><br>'.$sql.'<br><br>';
-            	echo "Error: ".$this->adodbConnection->ErrorMsg()."<br>";            	
-            }
-            $this->Clear();
-            return false;
-        }
-       
-        $this->Clear();
-
-        if($this->debuglevel > 0)
-        {
-        	 echo "This SQL: $sql<br><br>";
-        	 if( ($this->debuglevel > 1) && ($result->RecordCount() > 0) )
-        	 {
-        	 	echo '<pre>'.print_r($result->GetRows(), true).'</pre>';
-        	 	$result->MoveFirst();
-        	 }
-       	}
-		//echo "SQL: $sql<br><br>";
-        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)."<br>\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)."<br>\n";
-        $this->adodbConnection->Execute($insert);
-        //echo $insert."<br>";
-    }
-
-    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 <b>CopyFromEditTable</b> in class <b>".get_class($this).'</b><br>';
-        //echo $sql."<BR>";
-    	
-        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)."<br>\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)."<br>\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<br>\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).")<br>";
-    		$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."<br>\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 "=====<br>";
-      	echo "Class <b>".get_class($this)."</b>: Page ".$this->Page." of $NumPages<br>";
-      	echo "PerPage: $PerPage<br>";
-      	echo "Items Queries: ".$this->QueryItemCount."<br>";
-      	echo "=====<br>";
-*/      	
-      	if($this->Page > $NumPages)
-      	{
-      		switch($fix_method)
-      		{
-      			case 'set_first': 
-      				$this->Page = 1; 
-      				//echo "Move 2 First (class <b>".get_class($this)."</b>)<br>"; 
-      				break;
-      			case 'set_last': 
-      				$this->Page = $NumPages; 
-      				//echo "Move 2 Last (class <b>".get_class($this)."</b>)<br>"; 
-      				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 .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
-        }
-
-        for($p=$StartPage;$p<=$EndPage;$p++)
-        {
-            if($p!=$this->Page)
-            {
-                ${$v}[$this->PageEnvarIndex]=$p;
-                $href = $page."?env=".BuildEnv().$EnvSuffix;
-                $o .= " <A HREF=\"$href\">$p</A> ";
-            }
-            else
-            {
-                $o .= " <SPAN class=\"current-page\">$p</SPAN>";
-            }
-        }
-        if($EndPage<$NumPages && $EndPage>0)
-        {
-          ${$v}[$this->PageEnvarIndex]=$this->Page+$PagesToList;
-
-          $next_url = $page."?env=".BuildEnv().$EnvSuffix;
-          $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
-        }
-        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 .= '<a href="'.$prev_url.'">&lt;&lt;</a>';
-        }
-
-        
-        for($p = $StartPage; $p <= $EndPage; $p++)
-        {
-            if($p != $this->Page)
-            {
-                $update[$this->PageEnvarIndex] = $p;
-                $href = $url.'?env='.BuildEnv();
-                $o .= ' <a href="'.$href.'" class="NAV_URL">'.$p.'</a> ';
-            }
-            else
-            {
-                $o .= '<SPAN class="CURRENT_PAGE">'.$p.'</SPAN>';
-            }
-        }
-        if($EndPage < $NumPages)
-        {
-          $update[$this->PageEnvarIndex] = $this->Page + 10;
-          $next_url = $url.'?env='.BuildEnv();
-          $o .= '<a href="'.$next_url.'"> &gt;&gt;</a>';
-        }
-        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;$i<count($NewCatList);$i++)
-  {
-      $cat = $NewCatList[$i];
-      if(!in_array($cat,$CurrentList))
-         $ins_list[] = $cat;
-  }
-  for($i=0;$i<count($CurrentList);$i++)
-  {
-      $cat = $CurrentList[$i];
-      if(!in_array($cat,$NewCatList))
-          $del_list[] = $cat;
-  }
-  for($i=0;$i<count($ins_list);$i++)
-  {
-      $cat = $ins_list[$i];
-      $item->AddToCategory($cat);
-  }
-  for($i=0;$i<count($del_list);$i++)
-  {
-      $cat = $del_list[$i];      
-      $item->RemoveFromCategory($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; $x<count($this->Query_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."<br><br>\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)<br>\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<br>";
-  	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)."<br>\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)."<br>\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)."<br>\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)."<br>\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)."<br>\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)."<br>\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 <b>".get_class($this)."</b> Search Items<br>";
-		$sql = $this->SqlSearchItems($attribs);
-        //echo "$sql<br>";
-        $this->Query_Item($sql);
-        $Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
-        //echo "SQL Loaded ItemCount (<b>".get_class($this).'</b>): '.$this->NumItems().'<br>';
-        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: <pre>"; print_r($CountVal); echo "</pre><BR>";
-        }
-        else
-        {
-          $this->QueryItemCount = QueryCount($sql);
-          //echo "<b>SQL</b>: ".$sql."<br><br>";
-          $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;$i<count($item_ids);$i++)
-          {              
-              $item = $this->GetItem($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 = '<table border="0" cellspacing="2" width="100%"><tbody><tr>';
-	
-		$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 .= "</tr>\n<tr>";
-				$i = 1;
-			}
-			$o .= $item->AdminParseTemplate($template);
-			$i++;
-	        
-	        //printingright
-	        if ($rightcount < $topright && ( ($x + $topleft) < $total_items) ) 
-	        {
-	            $item = $this->Items[ $x + $topleft ];
-				if ($i > 2)
-				{	
-				    $o.="</tr>\n<tr>";
-				    $i = 1;
-				}
-				$o .= $item->AdminParseTemplate($template);
-				$i++;
-	            $rightcount++;
-	        }
-	    }
-		$o .= "\n</tr></tbody></table>\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<br>";
-		$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;
-	}
-}
-
-
-?>
+<?php
+
+global $ItemTypePrefixes;
+
+
+
+$ItemTypePrefixes = array();
+
+$ItemTagFiles = array();
+
+
+
+function RegisterPrefix($class,$prefix,$file)
+
+{
+
+ 	global $ItemTypePrefixes, $ItemTagFiles;
+
+    	
+
+ 	$ItemTypePrefixes[$class] = $prefix;
+
+ 	$ItemTagFiles[$prefix] = $file;
+
+}
+
+
+
+class clsParsedItem extends clsItemDB
+
+{
+
+    var $TagPrefix;
+
+    var $Parser;
+
+    var $AdminParser;    
+
+
+
+    function clsParsedItem($id=NULL)
+
+    {
+
+        global $TemplateRoot;
+
+
+
+        $this->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 = "<td width=\"$percentsOn%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td><td width=\"$percentsOff%\" bgcolor=\"$OffColor\"><img src=\"img/s.gif\"></td>";        	
+
+	                	}
+
+	                	else
+
+	                		$ret = "<td width=\"100%\" bgcolor=\"$OnColor\"><img src=\"img/s.gif\"></td>";      	                	
+
+	                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 = "<img src=\"$img_src\" border=\"0\" alt=\"".(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 .= "<IMG src=\"$url\" $extra_attribs >";
+
+                          $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 = "<IMG $extra_attribs SRC=\"".$this->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 = "<IMG src=\"$url\" $extra_attribs >";
+
+                   }
+
+                   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."<br>";
+
+            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,"<inp:");
+
+          while($next_tag)
+
+          {
+
+              $end_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,"<inp:");
+
+          }
+
+          array_pop($this->AdminParser->stack);
+
+      }
+
+      return $html;
+
+    }
+
+
+
+    function ParseTemplateText($text)
+
+    {
+
+    	$html = $text;
+
+      $search = "<inp:".$this->TagPrefix;
+
+      //$next_tag = strpos($html,"<inp:");
+
+      $next_tag = strpos($html,$search);
+
+      
+
+
+
+      while($next_tag)
+
+      { 
+
+      	  $closer = strpos(strtolower($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 = "</inp>";
+
+          	
+
+          	## Try to find end of TagName
+
+          	$TagNameEnd = strpos($html, " ", $next_tag);
+
+          	
+
+          	## Support Old version
+
+//          	$closer = strpos(strtolower($html),"</inp>",$next_tag);          
+
+          	if ($TagNameEnd)
+
+          	{   			
+
+          		$Tag = strtolower(substr($html, $next_tag, $TagNameEnd-$next_tag));
+
+          		$TagName = explode(":", $Tag);          		
+
+          		if (strlen($TagName[1]))
+
+          			$CloserTag = "</inp:".$TagName[1].">";
+
+          	}          	
+
+          	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<br>';
+
+      //$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 <br>\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 <br>\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)."<BR>";
+
+            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 <b>$i</b>:<br>";
+
+			$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."<br>\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;$x<count($this->Items);$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 [<b>".get_class($this).'</b>], sql: ['.$sql.']<br>';
+
+       	//if( get_class($this) == 'clsthemefilelist') trace();
+
+        $dummy =& $this->GetDummy();
+
+       	if( !$dummy->TableExists() )
+
+       	{
+
+       		if($this->debuglevel) echo "ERROR: table <b>".$dummy->tablename."</b> missing.<br>";
+
+       		$this->Clear();
+
+       	 	return false;
+
+       	}
+
+       	
+
+        if($rows>-1 && $offset>-1)
+
+        {
+
+        	//print_pre(debug_backtrace());
+
+	       	//echo "<b>Executing SelectLimit</b> $sql <b>Offset:</b> $offset,$rows<br>\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 '<br><br>'.$sql.'<br><br>';
+
+            	echo "Error: ".$this->adodbConnection->ErrorMsg()."<br>";            	
+
+            }
+
+            $this->Clear();
+
+            return false;
+
+        }
+
+       
+
+        $this->Clear();
+
+
+
+        if($this->debuglevel > 0)
+
+        {
+
+        	 echo "This SQL: $sql<br><br>";
+
+        	 if( ($this->debuglevel > 1) && ($result->RecordCount() > 0) )
+
+        	 {
+
+        	 	echo '<pre>'.print_r($result->GetRows(), true).'</pre>';
+
+        	 	$result->MoveFirst();
+
+        	 }
+
+       	}
+
+		//echo "SQL: $sql<br><br>";
+
+        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)."<br>\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)."<br>\n";
+
+        $this->adodbConnection->Execute($insert);
+
+        //echo $insert."<br>";
+
+    }
+
+
+
+    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 <b>CopyFromEditTable</b> in class <b>".get_class($this).'</b><br>';
+
+        //echo $sql."<BR>";
+
+    	
+
+        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)."<br>\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)."<br>\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<br>\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).")<br>";
+
+    		$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."<br>\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 "=====<br>";
+
+      	echo "Class <b>".get_class($this)."</b>: Page ".$this->Page." of $NumPages<br>";
+
+      	echo "PerPage: $PerPage<br>";
+
+      	echo "Items Queries: ".$this->QueryItemCount."<br>";
+
+      	echo "=====<br>";
+
+*/      	
+
+      	if($this->Page > $NumPages)
+
+      	{
+
+      		switch($fix_method)
+
+      		{
+
+      			case 'set_first': 
+
+      				$this->Page = 1; 
+
+      				//echo "Move 2 First (class <b>".get_class($this)."</b>)<br>"; 
+
+      				break;
+
+      			case 'set_last': 
+
+      				$this->Page = $NumPages; 
+
+      				//echo "Move 2 Last (class <b>".get_class($this)."</b>)<br>"; 
+
+      				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 .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
+
+        }
+
+
+
+        for($p=$StartPage;$p<=$EndPage;$p++)
+
+        {
+
+            if($p!=$this->Page)
+
+            {
+
+                ${$v}[$this->PageEnvarIndex]=$p;
+
+                $href = $page."?env=".BuildEnv().$EnvSuffix;
+
+                $o .= " <A HREF=\"$href\">$p</A> ";
+
+            }
+
+            else
+
+            {
+
+                $o .= " <SPAN class=\"current-page\">$p</SPAN>";
+
+            }
+
+        }
+
+        if($EndPage<$NumPages && $EndPage>0)
+
+        {
+
+          ${$v}[$this->PageEnvarIndex]=$this->Page+$PagesToList;
+
+
+
+          $next_url = $page."?env=".BuildEnv().$EnvSuffix;
+
+          $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
+
+        }
+
+        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 .= '<a href="'.$prev_url.'">&lt;&lt;</a>';
+
+        }
+
+
+
+        
+
+        for($p = $StartPage; $p <= $EndPage; $p++)
+
+        {
+
+            if($p != $this->Page)
+
+            {
+
+                $update[$this->PageEnvarIndex] = $p;
+
+                $href = $url.'?env='.BuildEnv();
+
+                $o .= ' <a href="'.$href.'" class="NAV_URL">'.$p.'</a> ';
+
+            }
+
+            else
+
+            {
+
+                $o .= '<SPAN class="CURRENT_PAGE">'.$p.'</SPAN>';
+
+            }
+
+        }
+
+        if($EndPage < $NumPages)
+
+        {
+
+          $update[$this->PageEnvarIndex] = $this->Page + 10;
+
+          $next_url = $url.'?env='.BuildEnv();
+
+          $o .= '<a href="'.$next_url.'"> &gt;&gt;</a>';
+
+        }
+
+        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;$i<count($NewCatList);$i++)
+
+  {
+
+      $cat = $NewCatList[$i];
+
+      if(!in_array($cat,$CurrentList))
+
+         $ins_list[] = $cat;
+
+  }
+
+  for($i=0;$i<count($CurrentList);$i++)
+
+  {
+
+      $cat = $CurrentList[$i];
+
+      if(!in_array($cat,$NewCatList))
+
+          $del_list[] = $cat;
+
+  }
+
+  for($i=0;$i<count($ins_list);$i++)
+
+  {
+
+      $cat = $ins_list[$i];
+
+      $item->AddToCategory($cat);
+
+  }
+
+  for($i=0;$i<count($del_list);$i++)
+
+  {
+
+      $cat = $del_list[$i];      
+
+      $item->RemoveFromCategory($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; $x<count($this->Query_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."<br><br>\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)<br>\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<br>";
+
+  	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)."<br>\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)."<br>\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)."<br>\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)."<br>\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)."<br>\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)."<br>\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 <b>".get_class($this)."</b> Search Items<br>";
+
+		$sql = $this->SqlSearchItems($attribs);
+
+        //echo "$sql<br>";
+
+        $this->Query_Item($sql);
+
+        $Keywords = GetKeywords($objSession->GetVariable("Search_Keywords"));
+
+        //echo "SQL Loaded ItemCount (<b>".get_class($this).'</b>): '.$this->NumItems().'<br>';
+
+        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: <pre>"; print_r($CountVal); echo "</pre><BR>";
+
+        }
+
+        else
+
+        {
+
+          $this->QueryItemCount = QueryCount($sql);
+
+          //echo "<b>SQL</b>: ".$sql."<br><br>";
+
+          $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;$i<count($item_ids);$i++)
+
+          {              
+
+              $item = $this->GetItem($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 = '<table border="0" cellspacing="2" width="100%"><tbody><tr>';
+
+	
+
+		$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 .= "</tr>\n<tr>";
+
+				$i = 1;
+
+			}
+
+			$o .= $item->AdminParseTemplate($template);
+
+			$i++;
+
+	        
+
+	        //printingright
+
+	        if ($rightcount < $topright && ( ($x + $topleft) < $total_items) ) 
+
+	        {
+
+	            $item = $this->Items[ $x + $topleft ];
+
+				if ($i > 2)
+
+				{	
+
+				    $o.="</tr>\n<tr>";
+
+				    $i = 1;
+
+				}
+
+				$o .= $item->AdminParseTemplate($template);
+
+				$i++;
+
+	            $rightcount++;
+
+	        }
+
+	    }
+
+		$o .= "\n</tr></tbody></table>\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<br>";
+
+		$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;
+
+	}
+
+}
+
+
+
+
+
+?>
\ No newline at end of file

Property changes on: trunk/kernel/include/parseditem.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.35
\ No newline at end of property
+1.36
\ No newline at end of property
Index: trunk/kernel/include/searchitems.php
===================================================================
--- trunk/kernel/include/searchitems.php	(revision 666)
+++ trunk/kernel/include/searchitems.php	(revision 667)
@@ -1,739 +1,1477 @@
-<?php
-/* search string syntax:
-   +<word> : <word> is required
-   -<word> : <word> 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."<br>\n";
-        $this->adodbConnection->Execute($sql);
-        if($this->adodbConnection->Affected_Rows()==0)
-        {
-            //echo "Creating Keyword record..<br>\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;$i<count($Keywords);$i++)
-            {
-                $this->UpdateKeyword($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."<br>\n";
-        $this->adodbConnection->Execute($sql);
-        if($this->adodbConnection->Affected_Rows()==0)
-        {
-            //echo "Creating Keyword record..<br>\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;$i<count($Keywords);$i++)
-            {
-                $this->UpdateKeyword($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;$i<count($required);$i++)
-            {
-              if(strlen($required[$i])>0)
-              {
-                  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;$i<count($words);$i++)
-            {
-              if(strlen($words[$i])>0)
-              {
-                  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;$i<count($normal);$i++)
-            { 
-              if (strlen($normal[$i])>0) 
-              {             
-                if($i>0)
-                {              
-                  $or =" OR ";
-                }
-                else
-                  $or = "";
-                $w  .= "$or $FieldName LIKE '%".$normal[$i]."%'";
-              }
-            }     
-           if(count($required)>0)
-               $w .= " OR ";
-           for($i=0;$i<count($required);$i++)
-           {
-               if(strlen($required[$i])>0)
-               {
-                   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<br>";
-        //echo "Old Item Type: $OldItemType  New: $ItemType <br>\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 "<PRE>";print_r($s); echo "</PRE>";     
-              $txt = implode("+",$s);
-              //echo $txt."<br>\n";
-              $ifs[] = $txt;  
-              unset($s);
-          }
-//          echo "<PRE>";print_r($ifs); echo "</PRE>";
-
-          /* 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."<br><br>\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."<br>\n";
-           $this->adodbConnection->Execute($full_sql);
-           //echo $this->adodbConnection->ErrorMsg()."<br>\n";
-           $objSession->SetVariable("Search_Keywords",$this->Phrase);
-        }
-        else
-        {
-          $full_sql = "INSERT INTO ".$this->ResultTable." (Relevance,ItemId,ResourceId,ItemType,EdPick) ".$SelectSQL;
-        //echo "[<b>".htmlspecialchars($full_sql)."</b>]<br>\n";
-          $this->adodbConnection->Execute($full_sql);
-          //echo $this->adodbConnection->ErrorMsg()."<br>\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;$i<count($w_array);$i++) 
-  {
-      $keyword = $w_array[$i];
-      switch(substr($keyword,0,1))
-      {
-        case "|":
-           $keywords["normal"][]=substr($keyword,1);
-           break;
-        case "+":
-           $keywords["required"][] = substr($keyword,1);
-           break;
-        case "-":
-           $keywords["notallowed"][] = substr($keyword,1);
-           break;
-        case "=":
-           $keywords["ignored"][] = substr($keyword,1);
-           break;
-      }
-  }
-  return($keywords);
-}
-
-function BuildWhereClause($normal,$required,$notallowed)
-{
-    $return="";
-    
-    $return = $required;
-    
-    if(strlen($return)>0 && 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 "<br>\n";
-}
-
-?>
+<?php
+
+/* search string syntax:
+
+   +<word> : <word> is required
+
+   -<word> : <word> 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."<br>\n";
+
+        $this->adodbConnection->Execute($sql);
+
+        if($this->adodbConnection->Affected_Rows()==0)
+
+        {
+
+            //echo "Creating Keyword record..<br>\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;$i<count($Keywords);$i++)
+
+            {
+
+                $this->UpdateKeyword($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."<br>\n";
+
+        $this->adodbConnection->Execute($sql);
+
+        if($this->adodbConnection->Affected_Rows()==0)
+
+        {
+
+            //echo "Creating Keyword record..<br>\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;$i<count($Keywords);$i++)
+
+            {
+
+                $this->UpdateKeyword($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;$i<count($required);$i++)
+
+            {
+
+              if(strlen($required[$i])>0)
+
+              {
+
+                  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;$i<count($words);$i++)
+
+            {
+
+              if(strlen($words[$i])>0)
+
+              {
+
+                  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;$i<count($normal);$i++)
+
+            { 
+
+              if (strlen($normal[$i])>0) 
+
+              {             
+
+                if($i>0)
+
+                {              
+
+                  $or =" OR ";
+
+                }
+
+                else
+
+                  $or = "";
+
+                $w  .= "$or $FieldName LIKE '%".$normal[$i]."%'";
+
+              }
+
+            }     
+
+           if(count($required)>0)
+
+               $w .= " OR ";
+
+           for($i=0;$i<count($required);$i++)
+
+           {
+
+               if(strlen($required[$i])>0)
+
+               {
+
+                   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<br>";
+
+        //echo "Old Item Type: $OldItemType  New: $ItemType <br>\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 "<PRE>";print_r($s); echo "</PRE>";     
+
+              $txt = implode("+",$s);
+
+              //echo $txt."<br>\n";
+
+              $ifs[] = $txt;  
+
+              unset($s);
+
+          }
+
+//          echo "<PRE>";print_r($ifs); echo "</PRE>";
+
+
+
+          /* 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."<br><br>\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."<br>\n";
+
+           $this->adodbConnection->Execute($full_sql);
+
+           //echo $this->adodbConnection->ErrorMsg()."<br>\n";
+
+           $objSession->SetVariable("Search_Keywords",$this->Phrase);
+
+        }
+
+        else
+
+        {
+
+          $full_sql = "INSERT INTO ".$this->ResultTable." (Relevance,ItemId,ResourceId,ItemType,EdPick) ".$SelectSQL;
+
+        //echo "[<b>".htmlspecialchars($full_sql)."</b>]<br>\n";
+
+          $this->adodbConnection->Execute($full_sql);
+
+          //echo $this->adodbConnection->ErrorMsg()."<br>\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;$i<count($w_array);$i++) 
+
+  {
+
+      $keyword = $w_array[$i];
+
+      switch(substr($keyword,0,1))
+
+      {
+
+        case "|":
+
+           $keywords["normal"][]=substr($keyword,1);
+
+           break;
+
+        case "+":
+
+           $keywords["required"][] = substr($keyword,1);
+
+           break;
+
+        case "-":
+
+           $keywords["notallowed"][] = substr($keyword,1);
+
+           break;
+
+        case "=":
+
+           $keywords["ignored"][] = substr($keyword,1);
+
+           break;
+
+      }
+
+  }
+
+  return($keywords);
+
+}
+
+
+
+function BuildWhereClause($normal,$required,$notallowed)
+
+{
+
+    $return="";
+
+    
+
+    $return = $required;
+
+    
+
+    if(strlen($return)>0 && 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 "<br>\n";
+
+}
+
+
+
+?>
\ No newline at end of file

Property changes on: trunk/kernel/include/searchitems.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.9
\ No newline at end of property
+1.10
\ No newline at end of property
Index: trunk/kernel/include/category.php
===================================================================
--- trunk/kernel/include/category.php	(revision 666)
+++ trunk/kernel/include/category.php	(revision 667)
@@ -1,2318 +1,4635 @@
-<?php
-define('TYPE_CATEGORY', 0);
-$DownloadId=0;
-RegisterPrefix("clsCategory","cat","kernel/include/category.php");
-
-class clsCategory extends clsItem
-{
-    var $Permissions;
-
-    function clsCategory($CategoryId=NULL)
-    {
-        global $objSession;
-
-        $this->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 .= "<a class=\"$class_name\" href=\"".GetIndexURL()."?env=" . BuildEnv() . "\">$cat_name</a>";            
-		else
-			$ret .= "<span=\"$class_name\">$cat_name</span>";       
-        
-            $rs->MoveNext();
-            if(!$rs->EOF)
-            {
-                $ret.= is_null($separator)? ", " : $separator;
-            }
-      	}
-        if(strlen($ret))
-          $ret .= is_null($ending)? " ..." : $ending;
-          
-      	unset($var_list_update["t"], $m_var_list_update["cat"], $m_var_list_update["p"]);
-      	
-        return $ret;
-   }
-
-    function Validate()
-    {
-      global $objSession;
-      
-        $dataValid = true;             
-      if(!isset($this->m_Type))
-        {
-            $Errors->AddError("error.fieldIsRequired",'Type',"","","clsCategory","Validate");
-            $dataValid = false;
-        }
-        
-        if(!isset($this->m_Name))
-        {
-            $Errors->AddError("error.fieldIsRequired",'Name',"","","clsCategory","Validate");
-            $dataValid = false;
-        }
-        
-        if(!isset($this->m_Description))
-        {
-            $Errors->AddError("error.fieldIsRequired",'Description',"","","clsCategory","Validate");
-            $dataValid = false;
-        }
-        
-        if(!isset($this->m_Visible))
-        {
-            $Errors->AddError("error.fieldIsRequired",'Visible',"","","clsCategory","Validate");
-            $dataValid = false;
-        }
-        
-        if(!isset($this->m_CreatedById))
-        {
-            $Errors->AddError("error.fieldIsRequired",'CreatedBy',"","","clsCategory","Validate");
-            $dataValid = false;
-        }
-        return $dataValid;
-    }
-    
-    function UpdateCachedPath()
-   {
-   	  if($this->UsingTempTable()==TRUE)
-   	    return;
-      $Id = $this->Get("CategoryId");
-      $Id2 = $Id;
-        $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 "<BR>\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")."<br>\n";
-        if(!$perm)
-        {
-            $perm=$objSession->HasSystemPermission("ROOT");
-        }
-        return ($perm==1);
-    }
-
-    function PermissionValue($PermissionName,$GroupID)
-    {
-      //$this->LoadPermissions();            
-      $ret=NULL;
-      //echo "Looping though ".count($this->Permissions)." permissions Looking for $PermissionName of $GroupID<br>\n";
-      if($this->Permissions->GroupId != $GroupID)
-      {
-          $this->Permissions->Clear();
-          $this->Permissions->GroupId = $GroupID;
-      }
-
-      $this->Permissions->CatId=$this->Get("CategoryId");
-      $ret = $this->Permissions->GetPermissionValue($PermissionName);
-      if($ret == NULL)
-      {
-         $cats = explode("|",substr($this->Get("ParentPath"),1,-1));
-
-       if(is_array($cats))
-        { 
-          $cats = array_reverse($cats);          
-          $cats[] = 0;
-          foreach($cats as $catid)
-          {  
-            $this->Permissions->LoadCategory($catid);
-            $ret = $this->Permissions->GetPermissionValue($PermissionName);
-            if(is_numeric($ret))
-              break;
-          }
-        }
-      }
-      return $ret;
-    }
-
-    function SetPermission($PermName,$GroupID,$Value,$Type=0)
-    {
-        global $objSession, $objPermissions, $objGroups;
-        
-        if($this->Permissions->GroupId != $GroupID)
-        {
-            $this->Permissions->Clear();
-            $this->Permissions->GroupId = $GroupID;
-        }
-
-        if($objSession->HasSystemPermission("GRANT"))
-        {
-            $current = $this->PermissionValue($PermName,$GroupID);
-
-            if($current == NULL)
-            {
-                $this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
-            }
-            else
-            {
-                $p = $this->Permissions->GetPermByName($PermName);
-                if($p->Inherited==FALSE)
-                {
-                    $p->Set("PermissionValue",$Value);
-                    $p->Update();
-                }
-                else
-                   $this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
-            }
-            if($PermName == "CATEGORY.VIEW")
-            {           
-              $Groups = $objGroups->GetAllGroupList();
-              $ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$Groups);
-              $this->SetViewPerms("CATEGORY.VIEW",$ViewList,$Groups);
-              $this->Update();
-            }
-       }
-    }
-
-    function SetViewPerms($PermName,$acl,$allgroups)
-    {
-       global $objPermCache;
-
-       $dacl = array();
-       if(!is_array($allgroups))
-       {
-           global $objGroups;
-           $allgroups = $objGroups->GetAllGroupList();
-       }
-       
-       for($i=0;$i<count($allgroups);$i++)
-       {
-           $g = $allgroups[$i];
-           if(!in_array($g,$acl))
-               $dacl[] = $g;
-       }
-        if(count($acl)<count($dacl))
-        {
-            $aval = implode(",",$acl);
-            $dval = "";
-        }
-        else
-        {            
-            $dval = implode(",",$dacl);
-            $aval = "";
-        }
-        if(strlen($aval)==0 && strlen($dval)==0)
-        {
-         $aval = implode(",",$allgroups);
-        }
-        $PermId = $this->Permissions->GetPermId($PermName);
-        $pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
-        if(is_object($pc))
-        {            
-            $pc->Set("ACL",$aval);
-            $pc->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 "<PRE>";print_r($perms); echo "</PRE>";
-       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 = "<IMG src=\"$url\" $extra_attribs >";
-                   }
-                   else
-                       $ret = "";
-               }
-               else
-                   $ret = $url;
-            break;
-            case "createdby":
-				/*
-				@field:cat.createdby
-				@description:parse a user field of the user that created the category
-  				@attrib:_usertag::User field to return (defaults to login ID)            
-  				*/            
-                $field = $element->GetAttributeByName('_usertag');
-                if(!strlen($field))
-                {
-                    $field = "user_login";
-                }
-                $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 = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
-                }
-                else
-                    $ret = $this->StatusIcon();
-            break;
-            case "subcats":
-            	/*
-            	@field:cat.subcats
-            	@description: Loads category's subcategories into a list and renders using the m_list_cats global tag           	
-            	@attrib:_subcattemplate:tpl:Template used to render subcategory list elements
-  				@attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
-  				@attrib: _maxlistcount:int: Maximum number of categories to list
-  				@attrib: _FirstItemTemplate:tpl: Template used for the first category listed
-  				@attrib: _LastItemTemplate:tpl: Template used for the last category listed  				
-  				@attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
-				*/            	
-                $attr = array();
-                $attr["_catid"] = $this->Get("CategoryId");
-                $attr["_itemtemplate"] = $element->GetAttributeByName('_subcattemplate');
-                if( $element->GetAttributeByName('_notable') )
-                    $attr["_notable"]=1;
-                $ret = m_list_cats($attr);
-            break;
-            case "subcatcount":
-            	/*
-            	@field:cat.subcatcount
-            	@description:returns number of subcategories
-            	*/
-            	$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
-            	$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
-            	$txt .="_CategoryCount=\"1\" _ItemType=\"1\" _GroupOnly=\"$GroupOnly\" />";
-            	$tag = new clsHtmlTag($txt);
-            	$ret = $tag->Execute();	            	
-            break;    
-            case "itemcount":
-               /*
-               @field:cat.itemcount
-               @description:returns the number of items in the category
-               @attrib:_itemtype::name of item type to count, or all items if not set
-               */
-               $typestr = $element->GetAttributeByName('_itemtype');
-               if(strlen($typestr))
-               {
-                 $type = $objItemTypes->GetTypeByName($typestr);
-                 if(is_object($type))
-                 {
-                   $TypeId = $type->Get("ItemType");
-            	   $GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
-            	   $txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
-            	   $txt .=" _ListType=\"category\" _CountCurrent=\"1\" _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<br>
-  				<UL>
-  					<LI>"Numerical": Show the decimal value 
-  				    <LI>"Bar": Show the HTML representing the relevance. Returns two HTML cells &lg;td&lt; with specified background colors
-  				    <LI>"Graphical":Show image representing the relevance
-  				</UL>  
-			@attrib:_onimage::Zero relevance image shown in graphical display mode. Also used as prefix to build other images (i.e. prefix+"_"+percentage+".file_extension"
-			@attrib:_OffBackGroundColor::Off background color of HTML cell in bar display mode
-			@attrib:_OnBackGroundColor::On background color of HTML cell in bar display mode           
-            */  
-            
-            }
-            if( !isset($ret) ) $ret = parent::ParseObject($element);
-            
-        }
-        return $ret;
-    }
-
-
-    function parsetag($tag)
-    { 
-        global $objConfig,$objUsers, $m_var_list, $m_var_list_update;
-        if(is_object($tag))
-        {        
-            $tagname = $tag->name;
-        }
-        else
-            $tagname = $tag;
-
-        switch($tagname)
-        {
-          case "cat_id":
-                return $this->Get("CategoryId");
-                break;        
-          case "cat_parent":
-                return $this->Get("ParentId");
-                break;  
-          case "cat_fullpath":
-                return $this->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..<br>\n";
-          if(strlen($this->Get("ParentPath"))==0)
-          {   
-            $this->UpdateCachedPath();
-          }
-          $cats = explode("|",substr($this->Get("ParentPath"),1,-1));
-          
-          foreach($cats as $catid)
-          { 
-              $cat =& $objCatList->GetCategory($catid);
-              if(is_object($cat))
-              { 
-                  if(strlen($cat->Get("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")."<br>\n";
-    		UpdateCategoryCount(0,$CatId);
-    	}
-    }
-    
-    /**
-    * @return void
-    * @param int $date
-    * @desc Set Modified field for category & all it's parent categories
-    */
-    function SetLastUpdate($date)
-    {
-    	$parents = $this->Get('ParentPath');
-    	$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."<BR>";
-    
-	$rs = $this->adodbConnection->Execute($sql);  
-	if($rs && !$rs->EOF)
-	{
-	   $ret = $rs->fields["CacheVal"];		  
-	}
-	else
-	  $ret = 0;
-	  
-	return $ret;  
-  }         
-    
-  function CurrentCategoryID()
-  {
-      global $m_var_list;      
-      return (int)$m_var_list["cat"];
-  }
-
-  function NumCategories()
-  {
-      return $this->NumItems();
-  }
-
-  function &CurrentCat()
-  {
-      //return $this->GetCategory($this->CurrentCategoryID());
-      return $this->GetItem($this->CurrentCategoryID());
-  }
-
-  function &GetCategory($CatID)
-  {
-      return $this->GetItem($CatID);
-  }
-
-  function GetByResource($ResId)
-  {
-      return $this->GetItemByField("ResourceId",$ResId);
-  }
-
-  function QueryOrderByClause($EditorsPick=FALSE,$Priority=FALSE,$UseTableName=FALSE)  
-  {
-  	global $objSession;
-  	
-    if($UseTableName)
-    {
-      $TableName = $this->SourceTable.".";
-    }
-    else
-      $TableName = "";	
-
-    $Orders = array();
-
-    if($EditorsPick)  
-    {
-    	$Orders[] = $TableName."EditorsPick DESC";
-    }
-    if($Priority)
-    {
-       $Orders[] = $TableName."Priority DESC";  	
-    }
-  
-  	$FieldVar = "Category_Sortfield";
-    $OrderVar = "Category_Sortorder";
-       	 	   
-    if(is_object($objSession))
-    {
-      if(strlen($objSession->GetPersistantVariable($FieldVar))>0)  
-      {  		
-      		$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". 
-          		       $objSession->GetPersistantVariable($OrderVar));            	
-      }
-    }
-
-  	$FieldVar = "Category_Sortfield2";
-    $OrderVar = "Category_Sortorder2";
-       	 	   
-    if(is_object($objSession))
-    {
-      if(strlen($objSession->GetPersistantVariable($FieldVar))>0)  
-      {  		
-      		$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". 
-          		       $objSession->GetPersistantVariable($OrderVar));            	
-      }
-    }
-    
-    
-    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 .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
-      }
-
-
-      for($p=$StartPage;$p<=$EndPage;$p++)
-      {
-          if($p!=$this->Page)
-          {
-              $m_var_list_update["p"]=$p;
-              $href = $page."?env=".BuildEnv();
-              $o .= " <A HREF=\"$href\" >$p</A> ";
-          }
-          else
-          {
-              $o .= "$p";
-          }
-      }
-      if($EndPage<$NumPages && $EndPage>0)
-      {
-        $m_var_list_update["p"]=$this->Page+$PagesToList;
-        $next_url = $page."?env=".BuildEnv();
-        $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
-      }
-      unset($m_var_list_update,$var_list_update["t"] );
-      return $o;
-  }
-	
-  	function GetAdminPageLinkList($url)
-  	{
-      	global $objConfig, $m_var_list_update, $var_list_update, $var_list;
-		
-		$PerPage = $this->GetPerPage();
-      	$NumPages = ceil($this->GetNumPages($PerPage));
-      	$o = "";
-
-      	if($this->Page>1)
-      	{
-        	$m_var_list_update["p"]=$this->Page-1;
-        	$prev_url = $url."?env=".BuildEnv();
-        	unset($m_var_list_update["p"]);
-         	$o .= "<A HREF=\"$prev_url\" class=\"NAV_URL\"><<</A>";
-      	}
-
-      	if($this->Page<$NumPages)
-      	{
-        	$m_var_list_update["p"]=$this->Page+1;
-        	$next_url = $url."?env=".BuildEnv();
-        	unset($m_var_list_update["p"]);
-      	}
-
-      	for($p=1;$p<=$NumPages;$p++)
-      	{
-          	if($p != $this->Page)
-          	{
-              	$m_var_list_update["p"]=$p;
-              	$href = $url."?env=".BuildEnv();
-              	unset($m_var_list_update["p"]);
-              	$o .=  " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
-          	}
-          	else
-              $o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
-      	}
-      	
-      	if($this->Page < $NumPages)
-         	$o .= "<A HREF=\"$next_url\" class=\"NAV_URL\">>></A>";
-
-      	return $o;        
-  	}
-
-  function Search_Category($orderByClause)
-  {
-    global $objSession, $objConfig, $Errors;    
-
-    $PerPage = $this->GetPerPage();
-    $Start = ($this->Page-1) * $PerPage;
-    $objResults = new clsSearchResults("Category","clsCategory");
-    $this->Clear();
-    $this->Categories = $objResults->LoadSearchResults($Start,$PerPage);
-    
-    return $this->Categories;
-  }
-
-
-  function GetSubCats($ParentCat)
-  {   
-      return $this->Query_Category("ParentId=".$ParentCat,"");
-  }
-
-  function AllSubCats($ParentCat)
-  {
-      $c =& $this->GetCategory($ParentCat);
-      $sql = "SELECT * FROM ".$this->SourceTable." WHERE ParentPath LIKE '".$c->Get("ParentPath")."%'";
-      $rs = $this->adodbConnection->Execute($sql);
-      $subcats = array();
-      while($rs && !$rs->EOF)
-      {
-      	  if($rs->fields["CategoryId"]!=$ParentCat)
-      	  {
-            $subcats[] = $rs->fields["CategoryId"];
-      	  }
-          $rs->MoveNext();
-      }
-	  if($ParentCat>0)
-	  {
-        if($c->Get("CachedDescendantCatsQty")!=count($subcats))
-        {
-          $c->Set("CachedDescendantCatsQty",count($subcats));
-        }
-	  }
-      return $subcats;
-  }
-
-  function cat_navbar($admin=0, $cat, $target_template, $separator = " > ", $LinkLeaf = FALSE,
-  					  $root = 0,$RootTemplate="",$modcat=0, $ModTemplate="", $LinkRoot = FALSE)  					 
-  {
-    // draw category navigation bar (at top)
-    global $Errors, $var_list_update, $var_list, $m_var_list_update, $m_var_list, $objConfig;
-
-	$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 = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">$cat_name</a>";	}
-        else
-        	$nav = "<span class=\"NAV_CURRENT_ITEM\">$cat_name</span>";
-    }
-    else
-    {
-      $nav = array();
-      $c =& $this->GetCategory($cat);
-      $nav_unparsed = $c->Get("ParentPath");    
-      if(strlen($nav_unparsed)==0)
-      {  
-        $c->UpdateCachedPath();
-        $nav_unparsed = $c->Get("ParentPath");
-      }
-      //echo " Before $nav_unparsed ";
-      if($root)
-      {      
-        $r =& $this->GetCategory($root);
-        $rpath = $r->Get("ParentPath");
-        $nav_unparsed = substr($nav_unparsed,strlen($rpath),-1);
-        $cat_name = $r->Get("Name");
-        $m_var_list_update["cat"] = $root;
-        if($cat == $catid && !$LinkLeaf)
-        {
-          $nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";         //href=\"browse.php?env=". BuildEnv() ."\"
-        }
-        else
-        {          
-          if ($admin == 1)       
-          {
-            $nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
-          }
-          else
-          {
-            if(strlen($RootTemplate))
-            {
-                $var_list_update["t"] = $RootTemplate;
-            }
-            else
-            {
-              $var_list_update["t"] = $target_template;
-            }
-            $nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
-          }
-        }
-      }
-      else
-      {      
-        $nav_unparsed = substr($nav_unparsed,1,-1);
-        $cat_name = language($objConfig->Get("Root_Name"));
-        $m_var_list_update["cat"] = 0;
-        if($cat == 0)
-        {
-          $nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";         //href=\"browse.php?env=". BuildEnv() ."\"
-        }
-        else
-        {          
-          if ($admin == 1)       
-          {
-            $nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
-          }
-          else
-          {
-            if(strlen($RootTemplate))
-            {
-              $var_list_update["t"] = $RootTemplate;
-            }
-            else
-              $var_list_update["t"] = $target_template;
-            $nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
-          }
-        }
-        
-      }
-      //echo " After $nav_unparsed <br>\n";
-      if(strlen($target_template)==0)
-        $target_template = $var_list["t"];    
-        
-      $cats = explode("|", $nav_unparsed);
-      foreach($cats as $catid)
-      {
-          if($catid)
-          {          
-            $c =& $this->GetCategory($catid);
-            if(is_object($c))
-            {          
-              $cat_name = $c->Get("Name");
-          
-              $m_var_list_update["cat"] = $catid;
-              if($catid==$modcat && strlen($ModTemplate)>0)
-              {
-              	$t = $ModTemplate;
-              }
-              else 
-              	$t = $target_template;
-              if($cat == $catid && !$LinkLeaf)
-              {
-                $nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";
-              }
-              else
-              {          
-                if ($admin == 1)       
-                {
-                  $nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
-                }
-                else
-                {
-                  $var_list_update["t"] = $t;
-                  $nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
-                  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 <br>\n";
-      echo "<PRE>";print_r($ChildList); echo "</PRE>";
-      echo "Old Parent: $oldparent <br>\n";
-      echo "ID: $Id <br>\n";
-      */
-      /* sanity checks */
-      
-      if(!in_array($ParentTo,$ChildList) && $oldparent != $ParentTo && $oldparent != $Id &&
-      	 $Id != $ParentTo)
-      {
-          $d->Set("ParentId", $ParentTo);
-          $d->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<br>";
-		$dest->Set("Name", $Name);    	  
-		$Names = CategoryNameCount($ParentTo,$Name); 
-		//echo "Names Count: ".count($Names)."<br>";
-    	if(count($Names)>0)
-    	{    		
-    		$NameCount = count($Names);
-    		$found = FALSE;
-    		$NewName = "Copy of $Name";
-    		
-    		if(!in_array($NewName,$Names))
-    		{
-    			//echo "Matched on $NewName in:<br>\n";
-    			$found = TRUE;
-    		}
-    		else
-    		{
-    		  for($x=2;$x<$NameCount+2;$x++)
-    		  {
-
-    				$NewName = "Copy ".$x." of ".$Name;
-    				if(!in_array($NewName,$Names))
-    				{
-    					$found = TRUE;
-    					break;
-    				}
-    				
-    			}
-    		}    	
-    		if(!$found)
-    		{
-    			$NameCount++;
-    			$NewName = "Copy $NameCount of $Name";
-    		} 
-    		//echo "New Name: $NewName<br>";
-            $dest->Set("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;$i<count($item_ids);$i++)
-            {   
-                $ItemId = $item_ids[$i];
-                $item = $this->GetItem($item_ids[$i]);
-                if(!$IsCopy)
-                { 
-                    $this->Move_Category($ItemId, $TargetCat);                    
-                    $clip = str_replace("CUT","COPY",$clip);
-                    $objSession->SetVariable("ClipBoard",$clip);
-                }
-                else
-                {              
-                  $this->Copy_CategoryTree($ItemId,$TargetCat);
-                }
-            }
-        }
-      }
-
-
-  function NumChildren($ParentID)
-  {   
-   $cat_filter = "m_cat_filter";
-   global $$cat_filter;
-
-   $filter = $$cat_filter;
-   $adodbConnection = &GetADODBConnection();
-
-   $sql = "SELECT COUNT(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]<br>\n";
-              if($rpath==$p)
-              {              
-                  $itemtype = $Type;
-                  break;
-              }
-          }      
-      }
-      return $itemtype;
-  }
-}
-
-function RunUp($Id, $function, $Param=NULL)
-{     
-    global $objCatList;
-
-   $d =  $objCatList->GetCategory($Id);
-   $ParentId = $d->Get("ParentId");
-   if ($ParentId == 0)
-    {
-        if($Param == NULL)
-        {        
-        	$d->$function();
-        }
-        else
-        {            
-            $d->$function($Param);
-        }
-    }
-   else
-   {
-      	RunUp($ParentId, $function, $Param);
-        if($Param == NULL)
-        {        
-        $d->$function();
-        }
-        else
-        {               
-            $d->$function($Param);
-        }
-
-   }
-   
-}
-
-function RunDown($Id, $function, $Param=NULL)
-{
-    global $objCatList;
-
-   $adodbConnection = &GetADODBConnection(); 
-   $sql = "select CategoryId from ".GetTablePrefix()."Category where ParentId='$Id'";
-   $rs = $adodbConnection->Execute($sql);
-  
-   while($rs && !$rs->EOF) 
-   {  
-      RunDown($rs->fields["CategoryId"], $function, $Param);           
-      $rs->MoveNext();
-   }
-   $d = $objCatList->GetCategory($Id);
-    if($Param == NULL)
-    {        
-      $d->$function();
-    }
-    else
-        $d->$function($Param);
-}
-?>
+<?php
+
+define('TYPE_CATEGORY', 0);
+
+$DownloadId=0;
+
+RegisterPrefix("clsCategory","cat","kernel/include/category.php");
+
+
+
+class clsCategory extends clsItem
+
+{
+
+    var $Permissions;
+
+
+
+    function clsCategory($CategoryId=NULL)
+
+    {
+
+        global $objSession;
+
+
+
+        $this->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 .= "<a class=\"$class_name\" href=\"".GetIndexURL()."?env=" . BuildEnv() . "\">$cat_name</a>";            
+
+		else
+
+			$ret .= "<span=\"$class_name\">$cat_name</span>";       
+
+        
+
+            $rs->MoveNext();
+
+            if(!$rs->EOF)
+
+            {
+
+                $ret.= is_null($separator)? ", " : $separator;
+
+            }
+
+      	}
+
+        if(strlen($ret))
+
+          $ret .= is_null($ending)? " ..." : $ending;
+
+          
+
+      	unset($var_list_update["t"], $m_var_list_update["cat"], $m_var_list_update["p"]);
+
+      	
+
+        return $ret;
+
+   }
+
+
+
+    function Validate()
+
+    {
+
+      global $objSession;
+
+      
+
+        $dataValid = true;             
+
+      if(!isset($this->m_Type))
+
+        {
+
+            $Errors->AddError("error.fieldIsRequired",'Type',"","","clsCategory","Validate");
+
+            $dataValid = false;
+
+        }
+
+        
+
+        if(!isset($this->m_Name))
+
+        {
+
+            $Errors->AddError("error.fieldIsRequired",'Name',"","","clsCategory","Validate");
+
+            $dataValid = false;
+
+        }
+
+        
+
+        if(!isset($this->m_Description))
+
+        {
+
+            $Errors->AddError("error.fieldIsRequired",'Description',"","","clsCategory","Validate");
+
+            $dataValid = false;
+
+        }
+
+        
+
+        if(!isset($this->m_Visible))
+
+        {
+
+            $Errors->AddError("error.fieldIsRequired",'Visible',"","","clsCategory","Validate");
+
+            $dataValid = false;
+
+        }
+
+        
+
+        if(!isset($this->m_CreatedById))
+
+        {
+
+            $Errors->AddError("error.fieldIsRequired",'CreatedBy',"","","clsCategory","Validate");
+
+            $dataValid = false;
+
+        }
+
+        return $dataValid;
+
+    }
+
+    
+
+    function UpdateCachedPath()
+
+   {
+
+   	  if($this->UsingTempTable()==TRUE)
+
+   	    return;
+
+      $Id = $this->Get("CategoryId");
+
+      $Id2 = $Id;
+
+        $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 "<BR>\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")."<br>\n";
+
+        if(!$perm)
+
+        {
+
+            $perm=$objSession->HasSystemPermission("ROOT");
+
+        }
+
+        return ($perm==1);
+
+    }
+
+
+
+    function PermissionValue($PermissionName,$GroupID)
+
+    {
+
+      //$this->LoadPermissions();            
+
+      $ret=NULL;
+
+      //echo "Looping though ".count($this->Permissions)." permissions Looking for $PermissionName of $GroupID<br>\n";
+
+      if($this->Permissions->GroupId != $GroupID)
+
+      {
+
+          $this->Permissions->Clear();
+
+          $this->Permissions->GroupId = $GroupID;
+
+      }
+
+
+
+      $this->Permissions->CatId=$this->Get("CategoryId");
+
+      $ret = $this->Permissions->GetPermissionValue($PermissionName);
+
+      if($ret == NULL)
+
+      {
+
+         $cats = explode("|",substr($this->Get("ParentPath"),1,-1));
+
+
+
+       if(is_array($cats))
+
+        { 
+
+          $cats = array_reverse($cats);          
+
+          $cats[] = 0;
+
+          foreach($cats as $catid)
+
+          {  
+
+            $this->Permissions->LoadCategory($catid);
+
+            $ret = $this->Permissions->GetPermissionValue($PermissionName);
+
+            if(is_numeric($ret))
+
+              break;
+
+          }
+
+        }
+
+      }
+
+      return $ret;
+
+    }
+
+
+
+    function SetPermission($PermName,$GroupID,$Value,$Type=0)
+
+    {
+
+        global $objSession, $objPermissions, $objGroups;
+
+        
+
+        if($this->Permissions->GroupId != $GroupID)
+
+        {
+
+            $this->Permissions->Clear();
+
+            $this->Permissions->GroupId = $GroupID;
+
+        }
+
+
+
+        if($objSession->HasSystemPermission("GRANT"))
+
+        {
+
+            $current = $this->PermissionValue($PermName,$GroupID);
+
+
+
+            if($current == NULL)
+
+            {
+
+                $this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
+
+            }
+
+            else
+
+            {
+
+                $p = $this->Permissions->GetPermByName($PermName);
+
+                if($p->Inherited==FALSE)
+
+                {
+
+                    $p->Set("PermissionValue",$Value);
+
+                    $p->Update();
+
+                }
+
+                else
+
+                   $this->Permissions->Add_Permission($this->Get("CategoryId"),$GroupId,$PermName,$Value,$Type);
+
+            }
+
+            if($PermName == "CATEGORY.VIEW")
+
+            {           
+
+              $Groups = $objGroups->GetAllGroupList();
+
+              $ViewList = $this->Permissions->GetGroupPermList($this,"CATEGORY.VIEW",$Groups);
+
+              $this->SetViewPerms("CATEGORY.VIEW",$ViewList,$Groups);
+
+              $this->Update();
+
+            }
+
+       }
+
+    }
+
+
+
+    function SetViewPerms($PermName,$acl,$allgroups)
+
+    {
+
+       global $objPermCache;
+
+
+
+       $dacl = array();
+
+       if(!is_array($allgroups))
+
+       {
+
+           global $objGroups;
+
+           $allgroups = $objGroups->GetAllGroupList();
+
+       }
+
+       
+
+       for($i=0;$i<count($allgroups);$i++)
+
+       {
+
+           $g = $allgroups[$i];
+
+           if(!in_array($g,$acl))
+
+               $dacl[] = $g;
+
+       }
+
+        if(count($acl)<count($dacl))
+
+        {
+
+            $aval = implode(",",$acl);
+
+            $dval = "";
+
+        }
+
+        else
+
+        {            
+
+            $dval = implode(",",$dacl);
+
+            $aval = "";
+
+        }
+
+        if(strlen($aval)==0 && strlen($dval)==0)
+
+        {
+
+         $aval = implode(",",$allgroups);
+
+        }
+
+        $PermId = $this->Permissions->GetPermId($PermName);
+
+        $pc = $objPermCache->GetPerm($this->Get("CategoryId"),$PermId);
+
+        if(is_object($pc))
+
+        {            
+
+            $pc->Set("ACL",$aval);
+
+            $pc->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 "<PRE>";print_r($perms); echo "</PRE>";
+
+       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 = "<IMG src=\"$url\" $extra_attribs >";
+
+                   }
+
+                   else
+
+                       $ret = "";
+
+               }
+
+               else
+
+                   $ret = $url;
+
+            break;
+
+            case "createdby":
+
+				/*
+
+				@field:cat.createdby
+
+				@description:parse a user field of the user that created the category
+
+  				@attrib:_usertag::User field to return (defaults to login ID)            
+
+  				*/            
+
+                $field = $element->GetAttributeByName('_usertag');
+
+                if(!strlen($field))
+
+                {
+
+                    $field = "user_login";
+
+                }
+
+                $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 = "<IMG $extra_attribs SRC=\"".$this->StatusIcon()."\">";
+
+                }
+
+                else
+
+                    $ret = $this->StatusIcon();
+
+            break;
+
+            case "subcats":
+
+            	/*
+
+            	@field:cat.subcats
+
+            	@description: Loads category's subcategories into a list and renders using the m_list_cats global tag           	
+
+            	@attrib:_subcattemplate:tpl:Template used to render subcategory list elements
+
+  				@attrib: _columns:int: Numver of columns to display the categories in (defaults to 1)
+
+  				@attrib: _maxlistcount:int: Maximum number of categories to list
+
+  				@attrib: _FirstItemTemplate:tpl: Template used for the first category listed
+
+  				@attrib: _LastItemTemplate:tpl: Template used for the last category listed  				
+
+  				@attrib: _NoTable:bool: If set to 1, the categories will not be listed in a table. If a table is used, all HTML attributes are passed to the TABLE tag
+
+				*/            	
+
+                $attr = array();
+
+                $attr["_catid"] = $this->Get("CategoryId");
+
+                $attr["_itemtemplate"] = $element->GetAttributeByName('_subcattemplate');
+
+                if( $element->GetAttributeByName('_notable') )
+
+                    $attr["_notable"]=1;
+
+                $ret = m_list_cats($attr);
+
+            break;
+
+            case "subcatcount":
+
+            	/*
+
+            	@field:cat.subcatcount
+
+            	@description:returns number of subcategories
+
+            	*/
+
+            	$GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
+
+            	$txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
+
+            	$txt .="_CategoryCount=\"1\" _ItemType=\"1\" _GroupOnly=\"$GroupOnly\" />";
+
+            	$tag = new clsHtmlTag($txt);
+
+            	$ret = $tag->Execute();	            	
+
+            break;    
+
+            case "itemcount":
+
+               /*
+
+               @field:cat.itemcount
+
+               @description:returns the number of items in the category
+
+               @attrib:_itemtype::name of item type to count, or all items if not set
+
+               */
+
+               $typestr = $element->GetAttributeByName('_itemtype');
+
+               if(strlen($typestr))
+
+               {
+
+                 $type = $objItemTypes->GetTypeByName($typestr);
+
+                 if(is_object($type))
+
+                 {
+
+                   $TypeId = $type->Get("ItemType");
+
+            	   $GroupOnly = $element->GetAttributeByName('_grouponly') ? 1 : 0;
+
+            	   $txt = "<inp:m_itemcount _CatId=\"".$this->Get("CategoryId")."\" _SubCats=\"1\" ";
+
+            	   $txt .=" _ListType=\"category\" _CountCurrent=\"1\" _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<br>
+
+  				<UL>
+
+  					<LI>"Numerical": Show the decimal value 
+
+  				    <LI>"Bar": Show the HTML representing the relevance. Returns two HTML cells &lg;td&lt; with specified background colors
+
+  				    <LI>"Graphical":Show image representing the relevance
+
+  				</UL>  
+
+			@attrib:_onimage::Zero relevance image shown in graphical display mode. Also used as prefix to build other images (i.e. prefix+"_"+percentage+".file_extension"
+
+			@attrib:_OffBackGroundColor::Off background color of HTML cell in bar display mode
+
+			@attrib:_OnBackGroundColor::On background color of HTML cell in bar display mode           
+
+            */  
+
+            
+
+            }
+
+            if( !isset($ret) ) $ret = parent::ParseObject($element);
+
+            
+
+        }
+
+        return $ret;
+
+    }
+
+
+
+
+
+    function parsetag($tag)
+
+    { 
+
+        global $objConfig,$objUsers, $m_var_list, $m_var_list_update;
+
+        if(is_object($tag))
+
+        {        
+
+            $tagname = $tag->name;
+
+        }
+
+        else
+
+            $tagname = $tag;
+
+
+
+        switch($tagname)
+
+        {
+
+          case "cat_id":
+
+                return $this->Get("CategoryId");
+
+                break;        
+
+          case "cat_parent":
+
+                return $this->Get("ParentId");
+
+                break;  
+
+          case "cat_fullpath":
+
+                return $this->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..<br>\n";
+
+          if(strlen($this->Get("ParentPath"))==0)
+
+          {   
+
+            $this->UpdateCachedPath();
+
+          }
+
+          $cats = explode("|",substr($this->Get("ParentPath"),1,-1));
+
+          
+
+          foreach($cats as $catid)
+
+          { 
+
+              $cat =& $objCatList->GetCategory($catid);
+
+              if(is_object($cat))
+
+              { 
+
+                  if(strlen($cat->Get("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")."<br>\n";
+
+    		UpdateCategoryCount(0,$CatId);
+
+    	}
+
+    }
+
+    
+
+    /**
+
+    * @return void
+
+    * @param int $date
+
+    * @desc Set Modified field for category & all it's parent categories
+
+    */
+
+    function SetLastUpdate($date)
+
+    {
+
+    	$parents = $this->Get('ParentPath');
+
+    	$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."<BR>";
+
+    
+
+	$rs = $this->adodbConnection->Execute($sql);  
+
+	if($rs && !$rs->EOF)
+
+	{
+
+	   $ret = $rs->fields["CacheVal"];		  
+
+	}
+
+	else
+
+	  $ret = 0;
+
+	  
+
+	return $ret;  
+
+  }         
+
+    
+
+  function CurrentCategoryID()
+
+  {
+
+      global $m_var_list;      
+
+      return (int)$m_var_list["cat"];
+
+  }
+
+
+
+  function NumCategories()
+
+  {
+
+      return $this->NumItems();
+
+  }
+
+
+
+  function &CurrentCat()
+
+  {
+
+      //return $this->GetCategory($this->CurrentCategoryID());
+
+      return $this->GetItem($this->CurrentCategoryID());
+
+  }
+
+
+
+  function &GetCategory($CatID)
+
+  {
+
+      return $this->GetItem($CatID);
+
+  }
+
+
+
+  function GetByResource($ResId)
+
+  {
+
+      return $this->GetItemByField("ResourceId",$ResId);
+
+  }
+
+
+
+  function QueryOrderByClause($EditorsPick=FALSE,$Priority=FALSE,$UseTableName=FALSE)  
+
+  {
+
+  	global $objSession;
+
+  	
+
+    if($UseTableName)
+
+    {
+
+      $TableName = $this->SourceTable.".";
+
+    }
+
+    else
+
+      $TableName = "";	
+
+
+
+    $Orders = array();
+
+
+
+    if($EditorsPick)  
+
+    {
+
+    	$Orders[] = $TableName."EditorsPick DESC";
+
+    }
+
+    if($Priority)
+
+    {
+
+       $Orders[] = $TableName."Priority DESC";  	
+
+    }
+
+  
+
+  	$FieldVar = "Category_Sortfield";
+
+    $OrderVar = "Category_Sortorder";
+
+       	 	   
+
+    if(is_object($objSession))
+
+    {
+
+      if(strlen($objSession->GetPersistantVariable($FieldVar))>0)  
+
+      {  		
+
+      		$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". 
+
+          		       $objSession->GetPersistantVariable($OrderVar));            	
+
+      }
+
+    }
+
+
+
+  	$FieldVar = "Category_Sortfield2";
+
+    $OrderVar = "Category_Sortorder2";
+
+       	 	   
+
+    if(is_object($objSession))
+
+    {
+
+      if(strlen($objSession->GetPersistantVariable($FieldVar))>0)  
+
+      {  		
+
+      		$Orders[] = trim($TableName.$objSession->GetPersistantVariable($FieldVar) . " ". 
+
+          		       $objSession->GetPersistantVariable($OrderVar));            	
+
+      }
+
+    }
+
+    
+
+    
+
+    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 .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
+
+      }
+
+
+
+
+
+      for($p=$StartPage;$p<=$EndPage;$p++)
+
+      {
+
+          if($p!=$this->Page)
+
+          {
+
+              $m_var_list_update["p"]=$p;
+
+              $href = $page."?env=".BuildEnv();
+
+              $o .= " <A HREF=\"$href\" >$p</A> ";
+
+          }
+
+          else
+
+          {
+
+              $o .= "$p";
+
+          }
+
+      }
+
+      if($EndPage<$NumPages && $EndPage>0)
+
+      {
+
+        $m_var_list_update["p"]=$this->Page+$PagesToList;
+
+        $next_url = $page."?env=".BuildEnv();
+
+        $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
+
+      }
+
+      unset($m_var_list_update,$var_list_update["t"] );
+
+      return $o;
+
+  }
+
+	
+
+  	function GetAdminPageLinkList($url)
+
+  	{
+
+      	global $objConfig, $m_var_list_update, $var_list_update, $var_list;
+
+		
+
+		$PerPage = $this->GetPerPage();
+
+      	$NumPages = ceil($this->GetNumPages($PerPage));
+
+      	$o = "";
+
+
+
+      	if($this->Page>1)
+
+      	{
+
+        	$m_var_list_update["p"]=$this->Page-1;
+
+        	$prev_url = $url."?env=".BuildEnv();
+
+        	unset($m_var_list_update["p"]);
+
+         	$o .= "<A HREF=\"$prev_url\" class=\"NAV_URL\"><<</A>";
+
+      	}
+
+
+
+      	if($this->Page<$NumPages)
+
+      	{
+
+        	$m_var_list_update["p"]=$this->Page+1;
+
+        	$next_url = $url."?env=".BuildEnv();
+
+        	unset($m_var_list_update["p"]);
+
+      	}
+
+
+
+      	for($p=1;$p<=$NumPages;$p++)
+
+      	{
+
+          	if($p != $this->Page)
+
+          	{
+
+              	$m_var_list_update["p"]=$p;
+
+              	$href = $url."?env=".BuildEnv();
+
+              	unset($m_var_list_update["p"]);
+
+              	$o .=  " <A HREF=\"$href\" class=\"NAV_URL\">$p</A> ";
+
+          	}
+
+          	else
+
+              $o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
+
+      	}
+
+      	
+
+      	if($this->Page < $NumPages)
+
+         	$o .= "<A HREF=\"$next_url\" class=\"NAV_URL\">>></A>";
+
+
+
+      	return $o;        
+
+  	}
+
+
+
+  function Search_Category($orderByClause)
+
+  {
+
+    global $objSession, $objConfig, $Errors;    
+
+
+
+    $PerPage = $this->GetPerPage();
+
+    $Start = ($this->Page-1) * $PerPage;
+
+    $objResults = new clsSearchResults("Category","clsCategory");
+
+    $this->Clear();
+
+    $this->Categories = $objResults->LoadSearchResults($Start,$PerPage);
+
+    
+
+    return $this->Categories;
+
+  }
+
+
+
+
+
+  function GetSubCats($ParentCat)
+
+  {   
+
+      return $this->Query_Category("ParentId=".$ParentCat,"");
+
+  }
+
+
+
+  function AllSubCats($ParentCat)
+
+  {
+
+      $c =& $this->GetCategory($ParentCat);
+
+      $sql = "SELECT * FROM ".$this->SourceTable." WHERE ParentPath LIKE '".$c->Get("ParentPath")."%'";
+
+      $rs = $this->adodbConnection->Execute($sql);
+
+      $subcats = array();
+
+      while($rs && !$rs->EOF)
+
+      {
+
+      	  if($rs->fields["CategoryId"]!=$ParentCat)
+
+      	  {
+
+            $subcats[] = $rs->fields["CategoryId"];
+
+      	  }
+
+          $rs->MoveNext();
+
+      }
+
+	  if($ParentCat>0)
+
+	  {
+
+        if($c->Get("CachedDescendantCatsQty")!=count($subcats))
+
+        {
+
+          $c->Set("CachedDescendantCatsQty",count($subcats));
+
+        }
+
+	  }
+
+      return $subcats;
+
+  }
+
+
+
+  function cat_navbar($admin=0, $cat, $target_template, $separator = " > ", $LinkLeaf = FALSE,
+
+  					  $root = 0,$RootTemplate="",$modcat=0, $ModTemplate="", $LinkRoot = FALSE)  					 
+
+  {
+
+    // draw category navigation bar (at top)
+
+    global $Errors, $var_list_update, $var_list, $m_var_list_update, $m_var_list, $objConfig;
+
+
+
+	$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 = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">$cat_name</a>";	}
+
+        else
+
+        	$nav = "<span class=\"NAV_CURRENT_ITEM\">$cat_name</span>";
+
+    }
+
+    else
+
+    {
+
+      $nav = array();
+
+      $c =& $this->GetCategory($cat);
+
+      $nav_unparsed = $c->Get("ParentPath");    
+
+      if(strlen($nav_unparsed)==0)
+
+      {  
+
+        $c->UpdateCachedPath();
+
+        $nav_unparsed = $c->Get("ParentPath");
+
+      }
+
+      //echo " Before $nav_unparsed ";
+
+      if($root)
+
+      {      
+
+        $r =& $this->GetCategory($root);
+
+        $rpath = $r->Get("ParentPath");
+
+        $nav_unparsed = substr($nav_unparsed,strlen($rpath),-1);
+
+        $cat_name = $r->Get("Name");
+
+        $m_var_list_update["cat"] = $root;
+
+        if($cat == $catid && !$LinkLeaf)
+
+        {
+
+          $nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";         //href=\"browse.php?env=". BuildEnv() ."\"
+
+        }
+
+        else
+
+        {          
+
+          if ($admin == 1)       
+
+          {
+
+            $nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
+
+          }
+
+          else
+
+          {
+
+            if(strlen($RootTemplate))
+
+            {
+
+                $var_list_update["t"] = $RootTemplate;
+
+            }
+
+            else
+
+            {
+
+              $var_list_update["t"] = $target_template;
+
+            }
+
+            $nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
+
+          }
+
+        }
+
+      }
+
+      else
+
+      {      
+
+        $nav_unparsed = substr($nav_unparsed,1,-1);
+
+        $cat_name = language($objConfig->Get("Root_Name"));
+
+        $m_var_list_update["cat"] = 0;
+
+        if($cat == 0)
+
+        {
+
+          $nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";         //href=\"browse.php?env=". BuildEnv() ."\"
+
+        }
+
+        else
+
+        {          
+
+          if ($admin == 1)       
+
+          {
+
+            $nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
+
+          }
+
+          else
+
+          {
+
+            if(strlen($RootTemplate))
+
+            {
+
+              $var_list_update["t"] = $RootTemplate;
+
+            }
+
+            else
+
+              $var_list_update["t"] = $target_template;
+
+            $nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
+
+          }
+
+        }
+
+        
+
+      }
+
+      //echo " After $nav_unparsed <br>\n";
+
+      if(strlen($target_template)==0)
+
+        $target_template = $var_list["t"];    
+
+        
+
+      $cats = explode("|", $nav_unparsed);
+
+      foreach($cats as $catid)
+
+      {
+
+          if($catid)
+
+          {          
+
+            $c =& $this->GetCategory($catid);
+
+            if(is_object($c))
+
+            {          
+
+              $cat_name = $c->Get("Name");
+
+          
+
+              $m_var_list_update["cat"] = $catid;
+
+              if($catid==$modcat && strlen($ModTemplate)>0)
+
+              {
+
+              	$t = $ModTemplate;
+
+              }
+
+              else 
+
+              	$t = $target_template;
+
+              if($cat == $catid && !$LinkLeaf)
+
+              {
+
+                $nav[] = "<span class=\"NAV_CURRENT_ITEM\" >".$cat_name."</span>";
+
+              }
+
+              else
+
+              {          
+
+                if ($admin == 1)       
+
+                {
+
+                  $nav[] = "<a class=\"control_link\" href=\"".$_SERVER["PHP_SELF"]."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
+
+                }
+
+                else
+
+                {
+
+                  $var_list_update["t"] = $t;
+
+                  $nav[] = "<a class=\"navbar\" href=\"".GetIndexURL()."?env=". BuildEnv().$selector.$new."\">".$cat_name."</a>";
+
+                  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 <br>\n";
+
+      echo "<PRE>";print_r($ChildList); echo "</PRE>";
+
+      echo "Old Parent: $oldparent <br>\n";
+
+      echo "ID: $Id <br>\n";
+
+      */
+
+      /* sanity checks */
+
+      
+
+      if(!in_array($ParentTo,$ChildList) && $oldparent != $ParentTo && $oldparent != $Id &&
+
+      	 $Id != $ParentTo)
+
+      {
+
+          $d->Set("ParentId", $ParentTo);
+
+          $d->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<br>";
+
+		$dest->Set("Name", $Name);    	  
+
+		$Names = CategoryNameCount($ParentTo,$Name); 
+
+		//echo "Names Count: ".count($Names)."<br>";
+
+    	if(count($Names)>0)
+
+    	{    		
+
+    		$NameCount = count($Names);
+
+    		$found = FALSE;
+
+    		$NewName = "Copy of $Name";
+
+    		
+
+    		if(!in_array($NewName,$Names))
+
+    		{
+
+    			//echo "Matched on $NewName in:<br>\n";
+
+    			$found = TRUE;
+
+    		}
+
+    		else
+
+    		{
+
+    		  for($x=2;$x<$NameCount+2;$x++)
+
+    		  {
+
+
+
+    				$NewName = "Copy ".$x." of ".$Name;
+
+    				if(!in_array($NewName,$Names))
+
+    				{
+
+    					$found = TRUE;
+
+    					break;
+
+    				}
+
+    				
+
+    			}
+
+    		}    	
+
+    		if(!$found)
+
+    		{
+
+    			$NameCount++;
+
+    			$NewName = "Copy $NameCount of $Name";
+
+    		} 
+
+    		//echo "New Name: $NewName<br>";
+
+            $dest->Set("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;$i<count($item_ids);$i++)
+
+            {   
+
+                $ItemId = $item_ids[$i];
+
+                $item = $this->GetItem($item_ids[$i]);
+
+                if(!$IsCopy)
+
+                { 
+
+                    $this->Move_Category($ItemId, $TargetCat);                    
+
+                    $clip = str_replace("CUT","COPY",$clip);
+
+                    $objSession->SetVariable("ClipBoard",$clip);
+
+                }
+
+                else
+
+                {              
+
+                  $this->Copy_CategoryTree($ItemId,$TargetCat);
+
+                }
+
+            }
+
+        }
+
+      }
+
+
+
+
+
+  function NumChildren($ParentID)
+
+  {   
+
+   $cat_filter = "m_cat_filter";
+
+   global $$cat_filter;
+
+
+
+   $filter = $$cat_filter;
+
+   $adodbConnection = &GetADODBConnection();
+
+
+
+   $sql = "SELECT COUNT(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]<br>\n";
+
+              if($rpath==$p)
+
+              {              
+
+                  $itemtype = $Type;
+
+                  break;
+
+              }
+
+          }      
+
+      }
+
+      return $itemtype;
+
+  }
+
+}
+
+
+
+function RunUp($Id, $function, $Param=NULL)
+
+{     
+
+    global $objCatList;
+
+
+
+   $d =  $objCatList->GetCategory($Id);
+
+   $ParentId = $d->Get("ParentId");
+
+   if ($ParentId == 0)
+
+    {
+
+        if($Param == NULL)
+
+        {        
+
+        	$d->$function();
+
+        }
+
+        else
+
+        {            
+
+            $d->$function($Param);
+
+        }
+
+    }
+
+   else
+
+   {
+
+      	RunUp($ParentId, $function, $Param);
+
+        if($Param == NULL)
+
+        {        
+
+        $d->$function();
+
+        }
+
+        else
+
+        {               
+
+            $d->$function($Param);
+
+        }
+
+
+
+   }
+
+   
+
+}
+
+
+
+function RunDown($Id, $function, $Param=NULL)
+
+{
+
+    global $objCatList;
+
+
+
+   $adodbConnection = &GetADODBConnection(); 
+
+   $sql = "select CategoryId from ".GetTablePrefix()."Category where ParentId='$Id'";
+
+   $rs = $adodbConnection->Execute($sql);
+
+  
+
+   while($rs && !$rs->EOF) 
+
+   {  
+
+      RunDown($rs->fields["CategoryId"], $function, $Param);           
+
+      $rs->MoveNext();
+
+   }
+
+   $d = $objCatList->GetCategory($Id);
+
+    if($Param == NULL)
+
+    {        
+
+      $d->$function();
+
+    }
+
+    else
+
+        $d->$function($Param);
+
+}
+
+?>
\ No newline at end of file

Property changes on: trunk/kernel/include/category.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.10
\ No newline at end of property
+1.11
\ No newline at end of property
Index: trunk/kernel/include/itemreview.php
===================================================================
--- trunk/kernel/include/itemreview.php	(revision 666)
+++ trunk/kernel/include/itemreview.php	(revision 667)
@@ -1,618 +1,1235 @@
-<?php
-
-function ip_exists($ip,$id,$SourceTable)
-{
-        $count = 0;
-        $sql = "SELECT count(*) as DupCount FROM $SourceTable WHERE IPAddress='$ip' and ItemId=$id";
-        $adodbConnection = &GetADODBConnection(); 
-        $rs = $adodbConnection->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."<br>";
-        $result = $this->adodbConnection->Execute($sql);
-        if ($result === false)
-        {
-            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
-            return false;
-        }
-		$data = $result->fields;
-		if(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]<br>";
-        $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<br>";
-        $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 .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
-        }
-
-
-        for($p=$StartPage;$p<=$EndPage;$p++)
-        {
-            if($p!=$this->Page)
-            {
-                $UpdateVar["rp"]=$p;
-                $href = $page."?env=".BuildEnv();
-                $o .= " <A HREF=\"$href\" >$p</A> ";
-            }
-            else
-            {
-                $o .= "$p";
-            }
-        }
-        if($EndPage<$NumPages && $EndPage>0)
-        {
-          $UpdateVar["rp"]=$this->Page+$PagesToList;
-          $next_url = $page."?env=".BuildEnv();
-          $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
-        }                               
-        unset($UpdateVar,$var_list_update["t"] );
-        return $o;       
-    }
-
-
-} /*clsItemReviewList*/
-
-?>
+<?php
+
+
+
+function ip_exists($ip,$id,$SourceTable)
+
+{
+
+        $count = 0;
+
+        $sql = "SELECT count(*) as DupCount FROM $SourceTable WHERE IPAddress='$ip' and ItemId=$id";
+
+        $adodbConnection = &GetADODBConnection(); 
+
+        $rs = $adodbConnection->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."<br>";
+
+        $result = $this->adodbConnection->Execute($sql);
+
+        if ($result === false)
+
+        {
+
+            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
+
+            return false;
+
+        }
+
+		$data = $result->fields;
+
+		if(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]<br>";
+
+        $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<br>";
+
+        $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 .= "<A HREF=\"$prev_url\">&lt;&lt;</A>";
+
+        }
+
+
+
+
+
+        for($p=$StartPage;$p<=$EndPage;$p++)
+
+        {
+
+            if($p!=$this->Page)
+
+            {
+
+                $UpdateVar["rp"]=$p;
+
+                $href = $page."?env=".BuildEnv();
+
+                $o .= " <A HREF=\"$href\" >$p</A> ";
+
+            }
+
+            else
+
+            {
+
+                $o .= "$p";
+
+            }
+
+        }
+
+        if($EndPage<$NumPages && $EndPage>0)
+
+        {
+
+          $UpdateVar["rp"]=$this->Page+$PagesToList;
+
+          $next_url = $page."?env=".BuildEnv();
+
+          $o .= "<A HREF=\"$next_url\"> &gt;&gt;</A>";
+
+        }                               
+
+        unset($UpdateVar,$var_list_update["t"] );
+
+        return $o;       
+
+    }
+
+
+
+
+
+} /*clsItemReviewList*/
+
+
+
+?>
\ No newline at end of file

Property changes on: trunk/kernel/include/itemreview.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.9
\ No newline at end of property
+1.10
\ No newline at end of property
Index: trunk/kernel/include/config.php
===================================================================
--- trunk/kernel/include/config.php	(revision 666)
+++ trunk/kernel/include/config.php	(revision 667)
@@ -1,515 +1,1024 @@
-<?php
-require_once($pathtoroot."kernel/include/adodb/adodb.inc.php");
-
-class clsConfig
-{
-	var $config;
-	var $m_dirty_session;
-	var $m_IsDirty;
-	var $m_DirtyFields;
-	var $m_VarType;
-    var $adodbConnection;
-
-	function clsConfig()
-	{
-	  $this->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."<br>\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:
-                    <option VALUE="[value]">[name]</option>
-                  
-                    To add dynamic data to this list, enclose an SQL statement with <SQL></SQL> tags for example:
-                    <SQL>SELECT FieldLabel as OptionName, FieldName as OptionValue FROM <prefix>CustomField WHERE <prefix>.CustomFieldType=3></SQL>
-                    
-                    note the specific field labels OptionName and OptionValue.  They are required by the parser. 
-                    use the <prefix> 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("<PREFIX>",GetTablePrefix(),$string);      
-      
-      $start = strpos($string,"<SQL>");
-
-      while($start)
-      {
-          $end = strpos($string,"</SQL>");
-          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,"<SQL>"); 
-      }
-      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 .= "<INPUT TYPE=\"TEXT\" tabindex=\"".($TabIndex++)."\" NAME=\"".$this->name."\" ";
-        $o .= "VALUE=\"".$this->default_value."\">";
-      break;
-      case "checkbox":
-        $o .= "<INPUT TYPE=\"checkbox\" NAME=\"".$this->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 .= "<INPUT TYPE=\"PASSWORD\" tabindex=\"".($TabIndex++)."\" NAME=\"".$this->name."\" ";
-        $o .= "VALUE=\"".$this->default_value."\">";
-    break;
-    case "textarea":
-        $o .= "<TEXTAREA  tabindex=\"".($TabIndex++)."\" ".$this->ValueList." name=\"".$this->name."\">".$this->default_value."</TEXTAREA>";
-    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 .= "<input type=\"radio\" tabindex=\"".($localTabIndex)."\"  name=\"".$this->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 .= "<SELECT NAME=\"".$this->name."\" tabindex=\"".($TabIndex++)."\">";
-        $ValList = $this->replace_sql($this->ValueList);
-        $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="";       
-            $selected = "";
-            if($this->default_value==$parts[0])
-                $selected = " SELECTED";
-            if(substr($s,0,1)=="+")
-            {
-               $o .= "<OPTION VALUE=\"".$parts[0]."\" $selected>".substr($s,1)."</OPTION>";
-            }
-            else
-            {
-              if(strlen($s))	
-              	$o .= "<OPTION VALUE=\"".$parts[0]."\" $selected>".admin_language($s)."</OPTION>";
-            }
-          }
-        }
-        $o .= "</SELECT>";
-    }
-    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."<br>\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;
-  }
-}
-
-
-?>
+<?php
+
+require_once($pathtoroot."kernel/include/adodb/adodb.inc.php");
+
+
+
+class clsConfig
+
+{
+
+	var $config;
+
+	var $m_dirty_session;
+
+	var $m_IsDirty;
+
+	var $m_DirtyFields;
+
+	var $m_VarType;
+
+    var $adodbConnection;
+
+
+
+	function clsConfig()
+
+	{
+
+	  $this->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."<br>\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:
+
+                    <option VALUE="[value]">[name]</option>
+
+                  
+
+                    To add dynamic data to this list, enclose an SQL statement with <SQL></SQL> tags for example:
+
+                    <SQL>SELECT FieldLabel as OptionName, FieldName as OptionValue FROM <prefix>CustomField WHERE <prefix>.CustomFieldType=3></SQL>
+
+                    
+
+                    note the specific field labels OptionName and OptionValue.  They are required by the parser. 
+
+                    use the <prefix> 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("<PREFIX>",GetTablePrefix(),$string);      
+
+      
+
+      $start = strpos($string,"<SQL>");
+
+
+
+      while($start)
+
+      {
+
+          $end = strpos($string,"</SQL>");
+
+          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,"<SQL>"); 
+
+      }
+
+      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 .= "<INPUT TYPE=\"TEXT\" tabindex=\"".($TabIndex++)."\" NAME=\"".$this->name."\" ";
+
+        $o .= "VALUE=\"".$this->default_value."\">";
+
+      break;
+
+      case "checkbox":
+
+        $o .= "<INPUT TYPE=\"checkbox\" NAME=\"".$this->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 .= "<INPUT TYPE=\"PASSWORD\" tabindex=\"".($TabIndex++)."\" NAME=\"".$this->name."\" ";
+
+        $o .= "VALUE=\"".$this->default_value."\">";
+
+    break;
+
+    case "textarea":
+
+        $o .= "<TEXTAREA  tabindex=\"".($TabIndex++)."\" ".$this->ValueList." name=\"".$this->name."\">".$this->default_value."</TEXTAREA>";
+
+    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 .= "<input type=\"radio\" tabindex=\"".($localTabIndex)."\"  name=\"".$this->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 .= "<SELECT NAME=\"".$this->name."\" tabindex=\"".($TabIndex++)."\">";
+
+        $ValList = $this->replace_sql($this->ValueList);
+
+        $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="";       
+
+            $selected = "";
+
+            if($this->default_value==$parts[0])
+
+                $selected = " SELECTED";
+
+            if(substr($s,0,1)=="+")
+
+            {
+
+               $o .= "<OPTION VALUE=\"".$parts[0]."\" $selected>".substr($s,1)."</OPTION>";
+
+            }
+
+            else
+
+            {
+
+              if(strlen($s))	
+
+              	$o .= "<OPTION VALUE=\"".$parts[0]."\" $selected>".admin_language($s)."</OPTION>";
+
+            }
+
+          }
+
+        }
+
+        $o .= "</SELECT>";
+
+    }
+
+    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."<br>\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;
+
+  }
+
+}
+?>
\ No newline at end of file

Property changes on: trunk/kernel/include/config.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.9
\ No newline at end of property
+1.10
\ No newline at end of property
Index: trunk/kernel/include/customfield.php
===================================================================
--- trunk/kernel/include/customfield.php	(revision 666)
+++ trunk/kernel/include/customfield.php	(revision 667)
@@ -1,262 +1,262 @@
 <?php
 
 class clsCustomField extends clsItem
 {
     
     function clsCustomField($CustomFieldId=-1)
     {
         $this->clsItem();
         $this->tablename=GetTablePrefix()."CustomField"; 
         $this->type=10;
         $this->BasePermission="";
         $this->id_field = "CustomFieldId";
         $this->NoResourceId=1; //set this to avoid using a resource ID
 		$this->debuglevel=0;
         if($CustomFieldId>-1)
             $this->LoadFromDatabase($CustomFieldId);
     }
 
 
     function GetAdminUI()
     {
     	$a = new clsConfigAdminItem();
-        $a->name = "_".($this->Get("FieldName"));
+        $a->name = "_".$this->Get("FieldName");
         $a->heading = $this->Get("Heading");
         $a->prompt = $this->Get("Prompt");
         $a->ElementType = $this->Get("ElementType");
         $a->ValidationRules="";
         $a->default_value = "";
         $a->ValueList=$this->Get("ValueList");
         if(!strlen($a->ElementType))
           $a->ElementType="text";
         if(!strlen($a->prompt))
           $a->prompt = "lu_fieldcustom__".strtolower($this->Get("FieldName"));
         return $a;  
       }    	
     
     function parsetag($tag)
     {	        
          if(is_object($tag))
          {        
              $tagname = $tag->name;
          }
          else
              $tagname = $tag;
          switch($tagname)
          {	  
              case "fieldlabel":
                  return $this->Get("FieldLabel");
                  break;
          
              case "fieldname":
                  return $this->Get("FieldName");
                  break;
 	
              case "customfieldid":
                 return $this->Get("CustomFieldId");
 
              default:
                  return "Undefined:$tagname";
                 break;
          }
     }
 
  }
 
 class clsCustomFieldList extends clsItemCollection
 {
     var $Type;
 
     function clsCustomFieldList($type=-1,$table="CustomField")
     {
         $this->clsItemCollection();
         $this->Type=$type;
         $this->classname = "clsCustomField";
         if($table=="CustomField")
           $table = GetTablePrefix().$table;
         $this->SourceTable = $table;
         if($this->Type>0)
           $this->LoadFields();
     }
 
     function LoadFields()
     {
         $this->Clear();
         $sql = "SELECT * FROM ".$this->SourceTable." WHERE Type=".$this->Type;
         if($this->debuglevel > 1) 
         	echo $sql."<br>\n";
         $rs = $this->adodbConnection->Execute($sql);
         
         while($rs && !$rs->EOF)
         {
             $data = $rs->fields;
             $this->AddItemFromArray($data);
             $rs->MoveNext();
         }     
     }
 
     function LoadFieldsAndValues($ResourceId)
     {
         $this->Clear();
         $table = $this->SourceTable;
         $DataTable = GetTablePrefix()."CustomMetaData";
         $sql = "SELECT $table.*,$DataTable.Value as Value, $DataTable.CustomDataId as CustomDataId FROM ".$table." LEFT JOIN $DataTable ON ";
         $sql .= "(".$table.".CustomFieldId=$DataTable.CustomFieldId AND $DataTable.ResourceId=$ResourceId) WHERE Type=".$this->Type;
         if( isset($GLOBALS["debuglevel"]) && $GLOBALS["debuglevel"]) echo $sql."<br>\n";
         $rs = $this->adodbConnection->Execute($sql);        
         while($rs && !$rs->EOF)
         {
             $data = $rs->fields;
             $this->AddItemFromArray($data);
             $rs->MoveNext();
         } 
     }
     
     function GetFieldUIList($GeneralTab=FALSE)
     {
       $ret = new clsConfigAdmin();
       
       if($this->NumItems()>0)
       {
         foreach($this->Items as $field)
         {
       	  if($GeneralTab==TRUE && $field->Get("OnGeneralTab")==1 || !$GeneralTab)
       	  {
       	    $ui = $field->GetAdminUI();
       	    array_push($ret->Items,$ui);
       	  }
         }
       }
       return $ret;	
     }
 
     function GetFieldNames()
     {
         $res = array();
         foreach($this->Items as $f)
             $res[] = $f->Get("FieldName");
         return $res;
     }
 
     function SaveFields()
     {
         foreach($this->Items as $i)
         {
           if($i->Get("CustomFieldId"))
           {
               $i->Update();
           }
           else
               $i->Create();
         }
 
     }
 
     function Query_CustomField($where=NULL,$orderby=NULL,$limit=NULL)
     {
       $this->Clear();
       $sql = "SELECT * FROM ".$this->SourceTable;
       if(isset($where))
           $sql = sprintf('%s WHERE %s',$sql,$where);
       if(isset($orderby) && strlen(trim($orderby))>0)
           $sql = sprintf('%s ORDER BY %s',$sql,$orderby);
       if(isset($limit) && strlen(trim($limit)))
          $sql .= " ".$limit;
       // $sql."<br>";
       $this->Query_Item($sql);
       return $this->Items;
     }
 
     function AddField($Type,$FieldName,$FieldLabel,$ShowGeneral=0,$Heading="", $Prompt="",
     				  $ElementType="",$ValueList="")
     {
     	global $objItemTypes,$objSearchConfig,$objLanguages;
     	
     	//if(!is_numeric($Type))
-    //	{
+    //	{    	  
           $f = new clsCustomField();
           $f->tablename = $this->SourceTable;
           $f->Set(array("Type","FieldName","FieldLabel","OnGeneralTab","Heading","Prompt",
           				"ElementType","ValueList"),
                   array($Type,$FieldName,$FieldLabel,$ShowGeneral,$Heading,$Prompt,
                   		$ElementType,$ValueList));
           $f->Create();
           $Item = $objItemTypes->GetItem($Type);
           if(is_object($Item))
           {
           	  //$Table = $Item->Get("SourceTable");
           	  $Table = GetTablePrefix()."CustomField";
           	  $Header = "la_text_".strtolower($Item->Get("ItemName"));
           	  $Module = $Item->Get("Module");
           	  $Desc = $FieldLabel;
           	  
           	  if(!is_object($objSearchConfig))
           	  {
           	  	$objSearchConfig = new clsSearchConfigList();
           	  }
 			  $NextOrder = $objSearchConfig->GetNextDisplayOrder($Module);
 			  $desc = "lu_fieldcustom__".strtolower($FieldName);
 			  if(!strlen($FieldLabel))
 			  {
 			  	$FieldLabel = $FieldName;
 			  }
 			  
 		  	  $l = $objLanguages->GetPrimary();
  		  	  $phrases = new clsPhraseList();
  		  	  $phrases->AddPhrase($desc,$l,$FieldLabel,2);			  	 
  		  	  
 			  $dtable = GetTablePrefix()."CustomMetaData";
 			  $Join = "($dtable.ResourceId={Table}.ResourceId)";
 			  $objSearchConfig->AddSearchField($Table,$FieldName,$Module,0,0,$FieldLabel,$desc,$Header,$NextOrder,0,"text",$Join,$f->Get("CustomFieldId"));
           }  
           return $f;
     	//}
     	//else
     	//  return FALSE;
     }
 
     function EditField($FieldId,$Type,$FieldName,$FieldLabel,$ShowGeneral=0,$Heading="", $Prompt="",
     				  $ElementType="",$ValueList="")
     {
        $f = $this->GetItem($FieldId);
           $f->Set(array("Type","FieldName","FieldLabel","OnGeneralTab","Heading","Prompt",
           				"ElementType","ValueList"),
                   array($Type,$FieldName,$FieldLabel,$ShowGeneral,$Heading,$Prompt,
                   		$ElementType,$ValueList));
        $f->Update();
        return $f;
     }
 
     function DeleteField($FieldId)
     {
     	global $objItemTypes, $objSearchConfig;
     	//echo "<pre>"; print_r($objSearchConfig); echo "</pre>";
         $f = $this->GetItem($FieldId);
         $Type = $f->Get("Type");
         $Item = $objItemTypes->GetItem($Type);
         $Module = $Item->Get("Module");
         if(is_object($Item))
         {
            //$table = $Item->Get("TableName");
            $table = GetTablePrefix()."CustomField";
            if(!is_object($objSearchConfig))
            {
            		$objSearchConfig = new clsSearchConfigList($Module);
            } 	
            
            if (is_object($objSearchConfig)) {
            		$s = $objSearchConfig->GetItemByName($table,$f->Get("FieldName"));
            		//echo "$table ".$f->Get("FieldName")."<pre>"; print_r($s); echo "</pre>";
            	  	if(is_object($s))
            	  	{
            	  		$s->Delete();
            	  	}           
            }
         }
         $f->Delete();
     }     
 
 }/*clsCustomFieldList*/
 
 
 ?>

Property changes on: trunk/kernel/include/customfield.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.4
\ No newline at end of property
+1.5
\ No newline at end of property
Index: trunk/admin/category/addcategory_custom.php
===================================================================
--- trunk/admin/category/addcategory_custom.php	(revision 666)
+++ trunk/admin/category/addcategory_custom.php	(revision 667)
@@ -1,253 +1,516 @@
-<?php 
-##############################################################
-##In-portal													##
-##############################################################
-##					      In-portal							##
-##					Intechnic Corporation					##
-##			   All Rights Reserved, 1998-2002				##
-##															##	
-##	No portion of this code may be copied, reproduced or	##	
-##	   otherwise redistributed without proper written		##
-##	  consent of Intechnic Corporation.  Violation will		##
-##	   result in revocation of the license and support		##
-##	 privileges along maximum prosecution allowed by law.	##
-##############################################################
-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");
-//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"; 
-
-//$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."<br>\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) {
-?>
-<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
-  <tr>
-    <td valign="top">
-      <?php int_hint_red(admin_language("la_Warning_Save_Item")); ?>
-    </td>
-  </tr>
-</table>
-<?php } ?>
-<form id="category" name="category" action="" method=POST>
-<?php
-  
-  $objCustomFields = new clsCustomFieldList(1);  
-  
-  $objCustomDataList->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 = "<input type=\"text\" tabindex=\"".($i+1)."\" VALUE=\"".inp_htmlize($f->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 = "<input type=text tabindex=\"".($i+1)."\" VALUE=\"\" name=\"$fieldname\">";
-        $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;$i<count($objCustomFields->Items);$i++)
-  {   
-    $objListView->RowIcons[] = $imagesURL."/itemicons/icon16_custom.gif";
-  }
-  $objListView->PageLinks = $objListView->PrintPageLinks();
-
-  $objListView->SliceItems();
-  print $objListView->PrintList();
-?>
-  <input type="hidden" name="ItemId" value="<?php echo $c->Get("ResourceId"); ?>">
-  <input type="hidden" name="Action" value="m_edit_custom_data">
-  <input type="hidden" name="CatEditStatus" VALUE="0">
-</FORM>
-
-
-<FORM id="save_edit" method="POST" NAME="save_edit" ID="save_edit">
-   <input type="hidden" name="CatEditStatus" VALUE="0">
-</FORM>
-<!-- CODE FOR VIEW MENU -->
-<form ID="viewmenu" method="post" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar; ?>" name="viewmenu">
-<input type="hidden" name="fieldname" value="">
-<input type="hidden" name="varvalue" value="">
-<input type="hidden" name="varvalue2" value="">
-<input type="hidden" name="Action" value="">
-</form>
-
-<?php int_footer(); ?>
+<?php 
+
+##############################################################
+
+##In-portal													##
+
+##############################################################
+
+##					      In-portal							##
+
+##					Intechnic Corporation					##
+
+##			   All Rights Reserved, 1998-2002				##
+
+##															##	
+
+##	No portion of this code may be copied, reproduced or	##	
+
+##	   otherwise redistributed without proper written		##
+
+##	  consent of Intechnic Corporation.  Violation will		##
+
+##	   result in revocation of the license and support		##
+
+##	 privileges along maximum prosecution allowed by law.	##
+
+##############################################################
+
+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");
+
+//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"; 
+
+
+
+//$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."<br>\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) {
+
+?>
+
+<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
+
+  <tr>
+
+    <td valign="top">
+
+      <?php int_hint_red(admin_language("la_Warning_Save_Item")); ?>
+
+    </td>
+
+  </tr>
+
+</table>
+
+<?php } ?>
+
+<form id="category" name="category" action="" method=POST>
+
+<?php
+
+  
+
+  $objCustomFields = new clsCustomFieldList(1);  
+
+  
+
+  $objCustomDataList->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 = "<input type=\"text\" tabindex=\"".($i+1)."\" VALUE=\"".inp_htmlize($f->Get("Value"))."\" name=\"$fieldname\">";
+
+        $field->Set("Value", $val_field);
+		
+        if ($field->Get('Prompt') != '') {
+        	$field->Set("FieldLabel", admin_language($field->Get('Prompt')));
+        }
+        else {
+        	$field->Set("FieldLabel", admin_language('lu_fieldcustom__'.strtolower($field->Get('FieldName'))));
+        }
+
+        $field->Set("DataId",$f->Get("CustomDataId"));
+
+      }
+
+      else
+
+      {      
+
+        $val_field = "<input type=text tabindex=\"".($i+1)."\" VALUE=\"\" name=\"$fieldname\">";
+
+        $field->Set("Value", $val_field);
+
+        if ($field->Get('Prompt') != '') {
+        	$field->Set("FieldLabel", admin_language($field->Get('Prompt')));
+        }
+        else {
+        	$field->Set("FieldLabel", admin_language('lu_fieldcustom__'.strtolower($field->Get('FieldName'))));
+        }      
+
+        $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;$i<count($objCustomFields->Items);$i++)
+
+  {   
+
+    $objListView->RowIcons[] = $imagesURL."/itemicons/icon16_custom.gif";
+
+  }
+
+  $objListView->PageLinks = $objListView->PrintPageLinks();
+
+
+
+  $objListView->SliceItems();
+
+  print $objListView->PrintList();
+
+?>
+
+  <input type="hidden" name="ItemId" value="<?php echo $c->Get("ResourceId"); ?>">
+
+  <input type="hidden" name="Action" value="m_edit_custom_data">
+
+  <input type="hidden" name="CatEditStatus" VALUE="0">
+
+</FORM>
+
+
+
+
+
+<FORM id="save_edit" method="POST" NAME="save_edit" ID="save_edit">
+
+   <input type="hidden" name="CatEditStatus" VALUE="0">
+
+</FORM>
+
+<!-- CODE FOR VIEW MENU -->
+
+<form ID="viewmenu" method="post" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar; ?>" name="viewmenu">
+
+<input type="hidden" name="fieldname" value="">
+
+<input type="hidden" name="varvalue" value="">
+
+<input type="hidden" name="varvalue2" value="">
+
+<input type="hidden" name="Action" value="">
+
+</form>
+
+
+
+<?php int_footer(); ?>
+

Property changes on: trunk/admin/category/addcategory_custom.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6
\ No newline at end of property
+1.7
\ No newline at end of property
Index: trunk/admin/category/category_maint.php
===================================================================
--- trunk/admin/category/category_maint.php	(revision 666)
+++ trunk/admin/category/category_maint.php	(revision 667)
@@ -1,166 +1,166 @@
 <?php
 ##############################################################
 ##In-portal													##
 ##############################################################
 ##					      In-portal							##
 ##					Intechnic Corporation					##
 ##			   All Rights Reserved, 1998-2002				##
 ##															##
 ##	No portion of this code may be copied, reproduced or	##
 ##	   otherwise redistributed without proper written		##
 ##	  consent of Intechnic Corporation.  Violation will		##
 ##	   result in revocation of the license and support		##
 ##	 privileges along maximum prosecution allowed by law.	##
 ##############################################################
 if(!defined('CACHE_PERM_CHUNK_SIZE'))define('CACHE_PERM_CHUNK_SIZE',30);
 
 if(!strlen($pathtoroot))
 {
   	$path = dirname(realpath(__FILE__));
   	if( strlen($path) )
   	{
     	// determine the OS type for path parsing
     	$pos = strpos($path, ':');
     	$gOS_TYPE = ($pos === false) ? 'unix' : 'win';
     	$pathchar = ($gOS_TYPE == 'unix') ? '/' : "\\";
     	$p = $path.$pathchar;
 
     	// Start looking for the root flag file
     	while( !strlen($pathtoroot) && strlen($p) )
     	{
       		$sub = substr($p, strlen($pathchar) * -1);
       		$filename = $p.( ($sub == $pathchar) ? '' : $pathchar).'root.flg';
       		if( !file_exists($filename) )
       		{
         		$parent = realpath($p.$pathchar."..".$pathchar);
 				$p = ($parent != $p) ? $parent : '';
       		}
       		else
       			$pathtoroot = $p;
     	}
     	if( !strlen($pathtoroot) ) $pathtoroot = '.'.$pathchar;
   	}
   	else
     	$pathtoroot = '.'.$pathchar;
 }
 
 $sub = substr($pathtoroot,strlen($pathchar)*-1);
 if( $sub != $pathchar) $pathtoroot = $pathtoroot.$pathchar;
 
 //echo $pathtoroot;
 //$FrontEnd=2;
 
 require_once($pathtoroot."kernel/startup.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";
 $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");
 $section = "in-portal:category_maint";
 
 
 require_once($pathtoroot.$admin."/category/permcacheupdate.php");
 
 if(!$objSession->GetVariable('PermCache_UpdateRequired'))
 	die(header('Location: '.$adminURL.'/'.$objSession->GetVariable('ReturnScript').'?env='.BuildEnv()));
 
 if(isset($_GET['continue']))
 {
 	$updater =& new clsCacheUpdater(1);
 	if(!intval($_GET['continue']))
 	{
 		$updater->clearData();
 		die(header('Location: '.$adminURL.'/'.$objSession->GetVariable('ReturnScript').'?env='.BuildEnv()));
 	}
 }
 else
 {
 	$updater =& new clsCacheUpdater();
 	$no_url = $_SERVER['PHP_SELF'].'?env='.BuildEnv().'&continue=0';
 	$yes_url = $_SERVER['PHP_SELF'].'?env='.BuildEnv().'&continue=1';
 
 	$title = prompt_language("la_prompt_updating")." ".prompt_language("la_Text_Categories");
 	int_header(NULL,NULL,$title);
 	flush();
 	
 	if(!isset($_GET['force']))
 	if($updater->totalCats > CACHE_PERM_CHUNK_SIZE)
 	{
 		$updater->setData();
 ?>
 <script language="javascript">
 	function goto_url(url)
 	{
 		document.location = url;
 	}
 </script>
 <table cellspacing="0" cellpadding="2" width="100%" border="0" class="tableborder">
     	<tr>
 		<td align="center" colspan="3" bgcolor="#FFFFFF"><?php echo prompt_language('la_confirm_maintenance'); ?></td>
 	</tr>
     	<tr>
 		<td align="center" colspan="3" bgcolor="#FFFFFF"><?php echo prompt_language('la_prompt_perform_now'); ?></td>
 	</tr>
 	<tr>
     		<td align="right" width="50%">
     			<input type="button" name="yes_btn" value="<?php echo admin_language("lu_yes"); ?>" onclick="javascript:goto_url('<?php echo $yes_url; ?>');" class="button">
 	    	</td>
 		<td><img src="<?php echo $imagesURL; ?>/spacer.gif" width="10"></td>
 	    	<td align="left" width="50%">
     			<input type="button" name="yes_btn" value="<?php echo admin_language("lu_no"); ?>" onclick="javascript:goto_url('<?php echo $no_url; ?>');" class="button">
 	    	</td>
 	</tr>
 </table>
 <?php
 		int_footer();
 		die();
 	}
 }
 $title = prompt_language("la_prompt_updating")." ".prompt_language("la_Text_Categories");
 int_header(NULL,NULL,$title);
 flush();
 $percent=$updater->getDonePercent();
 echo '<TABLE cellspacing="0" cellpadding="2" width="100%" border="0" class="tableborder">';
 if ($percent == 0)
 	echo '<TR><TD BGCOLOR="#FFFFFF" width="100%" >'.$percent.'%</td></TR>';
 else if ($percent < 60)
 	echo '<TR><TD BGCOLOR="#4682B2" width="'.$percent.'%"></td><TD BGCOLOR="#FFFFFF" width="'.(100-$percent).'%">'.$percent.'%</td></TR>';
 else if ($percent == 100)
 	echo '<TR><TD BGCOLOR="#4682B2" align="right" width="100%"><FONT COLOR="#FFFFFF">'.$percent.'%</FONT></td>';
 else
 	echo '<TR><TD BGCOLOR="#4682B2" align="right" width="'.$percent.'%"><FONT COLOR="#FFFFFF">'.$percent.'%</FONT></td><TD BGCOLOR="#FFFFFF" width="'.(100-$percent).'%"></td></TR>';
 echo '</TABLE>';
 flush();
 
 $needs_more = TRUE;
 while ($needs_more && $updater->iteration < CACHE_PERM_CHUNK_SIZE) {
 	$needs_more = $updater->DoTheJob();
 }
 
 if ($needs_more)
 {
 	$updater->setData();
 	$url=$adminURL.'/category/category_maint.php?env='.BuildEnv().'&continue=1';
 }
 else
 {
 	$updater->clearData();
 	$url = $adminURL.'/'.$objSession->GetVariable('ReturnScript').'?env='.BuildEnv();
 	$objSession->SetVariable('PermCache_UpdateRequired', 0);
 }
 print "<script language=\"javascript\">" ;
 print "setTimeout(\"document.location='$url';\",40);";
 print "</script>";
 int_footer();
 exit;
-?>
+?>
\ No newline at end of file

Property changes on: trunk/admin/category/category_maint.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.16
\ No newline at end of property
+1.17
\ No newline at end of property
Index: trunk/admin/category/addcategory.php
===================================================================
--- trunk/admin/category/addcategory.php	(revision 666)
+++ trunk/admin/category/addcategory.php	(revision 667)
@@ -1,385 +1,747 @@
-<?php
-##############################################################
-##In-portal													##
-##############################################################
-##					      In-portal							##
-##					Intechnic Corporation					##
-##			   All Rights Reserved, 1998-2002				##
-##															##	
-##	No portion of this code may be copied, reproduced or	##	
-##	   otherwise redistributed without proper written		##
-##	  consent of Intechnic Corporation.  Violation will		##
-##	   result in revocation of the license and support		##
-##	 privileges along maximum prosecution allowed by law.	##
-##############################################################
-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");
-//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"; 
-//$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) {
-?>
-<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
-  <tr>
-    <td valign="top">
-      <?php int_hint_red(admin_language("la_Warning_Save_Item")); ?>
-    </td>
-  </tr>
-</table>
-<?php } ?>
-<table width="100%" border="0" cellspacing="0" cellpadding="4" class="tableborder">
-<form ID="category" name="category" action="" method=POST>
-  <tr <?php int_table_color(1); ?>>
-    <td valign="top" colspan="3"><?php echo prompt_language("la_prompt_Enable_HTML"); ?>
-      <input type="checkbox" name="html_enable" value="1" checked>
-      <br>
-      <?php int_hint(prompt_language("la_Warning_Enable_HTML")); ?>
-    </td>
-  </tr>
-  <?php int_subsection_title(prompt_language("la_Text_Category")); ?>
-  <?php if( $c->Get("CategoryId") > 0 ) { ?>
-  <tr <?php int_table_color(); ?>>
-    <td valign="top"><span class="text"><?php echo prompt_language("la_prompt_CategoryId"); ?></span></td>
-    <td valign="top"><span class="text"><?php echo $c->Get("CategoryId"); ?></span></td>
-    <td><span class="text">&nbsp;</span></td>
-  </tr>
-  <?php } ?>
-  <tr <?php int_table_color(); ?>>
-    <td valign="top"><span ID="prompt_cat_name"  class="text"><?php echo prompt_language("la_prompt_Name"); ?></span></td>
-    <td>
-      <input type="text" name="cat_name" ValidationType="exists" tabindex="1" class="text" size="30" value="<?php echo $c->parsetag("cat_name"); ?>">
-    </td>
-    <td></td>
-  </tr>
-  <tr <?php int_table_color(); ?>>
-    <td valign="top"><span ID="prompt_cat_desc" class="text"><?php echo prompt_language("la_prompt_Description"); ?></span>
-    <br />
-         <a href="#">
-         <img src="<?php echo $rootURL; ?>admin/icons/icon24_link_editor.gif" style="cursor:hand" border="0"
-   ONCLICK="document.forms[0].elements[0].checked=true; OpenEditor('&section=<?php echo $section; ?>','category','cat_desc');">
-         </a>
-    </td>
-    <td>
-      <textarea name="cat_desc" tabindex="2" ValidationType="exists" cols="60" rows="5" class="text"><?php echo inp_textarea_unescape($c->parsetag("cat_desc")); ?></textarea>
-      </td>
-    <td></td>
-  </tr>
-  <?php int_subsection_title(prompt_language("la_tab_Properties")); ?>
-
-  <tr <?php int_table_color(); ?>>
-    <td valign="top"><span id="prompt_status" class="text"><?php echo prompt_language("la_prompt_Status"); ?></span></td>
-    <td>
-      <input type="radio" tabindex="3" name="status" class="text" value="1" <?php if($c->Get("Status") == 1) echo "checked"; ?>><?php echo prompt_language("la_val_Active"); ?>
-      <input type="radio" tabindex="3" name="status" class="text" value="2" <?php if($c->Get("Status") == 2) echo "checked"; ?>><?php echo prompt_language("la_val_Pending"); ?>
-      <input type="radio" tabindex="3" name="status" class="text" value="0" <?php if($c->Get("Status") == 0) echo "checked"; ?>><?php echo prompt_language("la_val_Disabled"); ?>
-     </td>
-    <td class="text">&nbsp;</td>
-  </tr>
-  <tr <?php int_table_color(); ?>>
-    <td valign="top"><span id="prompt_itemnew" class="text"><?php echo prompt_language("la_prompt_New"); ?></span></td>
-    <td>
-       <input type="radio" tabindex="4" name="itemnew" class="text" value="2" <?php if($c->Get("NewItem") == 2) echo "checked"; ?>><?php echo prompt_language("la_val_Auto"); ?>
-       <input type="radio" tabindex="4" name="itemnew" class="text" value="1" <?php if($c->Get("NewItem") == 1) echo "checked"; ?>><?php echo prompt_language("la_val_Always"); ?>
-       <input type="radio" tabindex="4" name="itemnew" class="text" value="0" <?php if($c->Get("NewItem") == 0) echo "checked"; ?>><?php echo prompt_language("la_val_Never"); ?>
-
-      </td>
-    <td class="text">&nbsp;</td>
-  </tr>
-  <tr <?php int_table_color(); ?>>
-   <td valign="top"><span id="prompt_cat_pick" class="text"><?php echo prompt_language("la_prompt_EditorsPick"); ?></span></td>
-    <td>
-      <input type="checkbox" tabindex="5" name="cat_pick" class="text" value="1" <?php if($c->Get("EditorsPick") == 1) echo "checked"; ?>>
-    </td>
-    <td class="text">&nbsp;</td>
-  </tr>
-  <TR <?php int_table_color(); ?> >
-    <TD><span id="prompt_Priority" class="text"><?php echo prompt_language("la_prompt_Priority"); ?></span></TD>
-    <TD><input type=text SIZE="5" tabindex="6" NAME="Priority" VALUE="<?php echo $c->Get("Priority"); ?>"></TD>
-    <TD>&nbsp;</TD>
-  </TR>
-  <tr <?php int_table_color(); ?>>
-    <td valign="top" ID="prompt_cat_date" class="text"> <?php echo prompt_language("la_prompt_CreatedOn"); ?> </td>
-    <td>
-      <input type="text" ValidationType="date,exists" tabindex="7" name="cat_date" id="cat_date_selector" datepickerIcon="../images/ddarrow.gif" class="text" size="20" value="<?php echo $c->parsetag("cat_date"); ?>">
-      <span class="small"><?php echo prompt_language("la_prompt_DateFormat"); ?></span>
-      </td>
-    <td>
-    <?php if( IsDebugMode() ) echo '<b>DBG:</b> '.date('M d. Y H:i:s', $c->get('Modified') ); ?>
-    </td>
-  </tr>
-
-  <?php int_subsection_title(prompt_language("la_Sectionheader_MetaInformation")); ?>
-  <tr <?php int_table_color(); ?>>
-    <td valign="top"><span id="prompt_meta_keywords" class="text"><?php echo prompt_language("la_prompt_MetaKeywords"); ?></span></td>
-    <td>
-      <input type="text" name="meta_keywords" tabindex="8" class="text" size="30" value="<?php echo $c->parsetag("cat_metakeywords"); ?>">
-    </td>
-    <td class="text">&nbsp;</td>
-  </tr>
-  <tr <?php int_table_color(); ?>>
-    <td valign="top"><span id="prompt_meta_desc" class="text"><?php echo prompt_language("la_prompt_MetaDescription"); ?></span></td>
-    <td>
-      <textarea name="meta_desc" tabindex="9" cols="60" rows="2" class="text"><?php echo inp_textarea_unescape($c->parsetag("cat_metadesc")); ?></textarea>
-    </td>
-    <td class="text">&nbsp;</td>
-  </tr>
-<?php  
-$CustomFieldUI = $objCustomFields->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 "<PRE>";print_r($objCustomFields); echo "</PRE>";
-  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 "<tr ".int_table_color_ret().">\n"; 
-            print "  <td valign=\"top\" class=\"text\">".$f->GetPrompt()."</td>\n";
-            print "  <td nowrap>".$f->ItemFormElement()."</TD>";       
-            if(is_object($f->NextItem))
-            {
-                $n = $f->NextItem;
-                print "  <td>".$n->ItemFormElement()."</TD>";       
-            }
-            else
-              print "  <td><span class=\"text\">&nbsp;</span></td>\n";
-            print "</tr>\n";
-        }
-    }
-  }
-}  
-?>
-	<input type="hidden" name="ParentId" value="<?php echo $c->Get("ParentId"); ?>">
-	<input type="hidden" name="CategoryId" value="<?php echo $c->parsetag("cat_id"); ?>">
-    <input type="hidden" name="Action" value="<?php echo $action; ?>">
-    <input type="hidden" name="CatEditStatus" VALUE="0">
-</FORM>
-
-</table>
-<script src="<?php echo $adminURL; ?>/include/calendar.js"></script>
-
-<SCRIPT language="JavaScript">
-    initCalendar("cat_date_selector", CalDateFormat);
-</SCRIPT>  
-<FORM method="POST" NAME="save_edit" ID="save_edit">
-  <input type="hidden" name="CatEditStatus" VALUE="0">
-</FORM>
-
-
-
-<?php 
-	MarkFields('category');
-	int_footer(); 
-?>
+<?php
+
+##############################################################
+
+##In-portal													##
+
+##############################################################
+
+##					      In-portal							##
+
+##					Intechnic Corporation					##
+
+##			   All Rights Reserved, 1998-2002				##
+
+##															##	
+
+##	No portion of this code may be copied, reproduced or	##	
+
+##	   otherwise redistributed without proper written		##
+
+##	  consent of Intechnic Corporation.  Violation will		##
+
+##	   result in revocation of the license and support		##
+
+##	 privileges along maximum prosecution allowed by law.	##
+
+##############################################################
+
+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");
+
+//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"; 
+
+//$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) {
+
+?>
+<table width="100%" border="0" cellspacing="0" cellpadding="0" class="toolbar">
+
+  <tr>
+
+    <td valign="top">
+
+      <?php int_hint_red(admin_language("la_Warning_Save_Item")); ?>
+
+    </td>
+
+  </tr>
+
+</table>
+<?php } ?>
+<table width="100%" border="0" cellspacing="0" cellpadding="4" class="tableborder">
+
+<form ID="category" name="category" action="" method=POST>
+
+  <tr <?php int_table_color(1); ?>>
+
+    <td valign="top" colspan="3"><?php echo prompt_language("la_prompt_Enable_HTML"); ?>
+
+      <input type="checkbox" name="html_enable" value="1" checked>
+
+      <br>
+
+      <?php int_hint(prompt_language("la_Warning_Enable_HTML")); ?>
+
+    </td>
+
+  </tr>
+
+  <?php int_subsection_title(prompt_language("la_Text_Category")); ?>
+
+  <?php if( $c->Get("CategoryId") > 0 ) { ?>
+
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top"><span class="text"><?php echo prompt_language("la_prompt_CategoryId"); ?></span></td>
+
+    <td valign="top"><span class="text"><?php echo $c->Get("CategoryId"); ?></span></td>
+
+    <td><span class="text">&nbsp;</span></td>
+
+  </tr>
+  <?php } ?>
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top"><span ID="prompt_cat_name"  class="text"><?php echo prompt_language("la_prompt_Name"); ?></span></td>
+
+    <td>
+
+      <input type="text" name="cat_name" ValidationType="exists" tabindex="1" class="text" size="30" value="<?php echo $c->parsetag("cat_name"); ?>">
+
+    </td>
+
+    <td></td>
+
+  </tr>
+
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top"><span ID="prompt_cat_desc" class="text"><?php echo prompt_language("la_prompt_Description"); ?></span>
+
+    <br />
+
+         <a href="#">
+
+         <img src="<?php echo $rootURL; ?>admin/icons/icon24_link_editor.gif" style="cursor:hand" border="0"
+
+   ONCLICK="document.forms[0].elements[0].checked=true; OpenEditor('&section=<?php echo $section; ?>','category','cat_desc');">
+
+         </a>
+
+    </td>
+
+    <td>
+
+      <textarea name="cat_desc" tabindex="2" ValidationType="exists" cols="60" rows="5" class="text"><?php echo inp_textarea_unescape($c->parsetag("cat_desc")); ?></textarea>
+
+      </td>
+
+    <td></td>
+
+  </tr>
+  <?php int_subsection_title(prompt_language("la_tab_Properties")); ?>
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top"><span id="prompt_status" class="text"><?php echo prompt_language("la_prompt_Status"); ?></span></td>
+
+    <td>
+
+      <input type="radio" tabindex="3" name="status" class="text" value="1" <?php if($c->Get("Status") == 1) echo "checked"; ?>><?php echo prompt_language("la_val_Active"); ?>
+
+      <input type="radio" tabindex="3" name="status" class="text" value="2" <?php if($c->Get("Status") == 2) echo "checked"; ?>><?php echo prompt_language("la_val_Pending"); ?>
+
+      <input type="radio" tabindex="3" name="status" class="text" value="0" <?php if($c->Get("Status") == 0) echo "checked"; ?>><?php echo prompt_language("la_val_Disabled"); ?>
+
+     </td>
+
+    <td class="text">&nbsp;</td>
+
+  </tr>
+
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top"><span id="prompt_itemnew" class="text"><?php echo prompt_language("la_prompt_New"); ?></span></td>
+
+    <td>
+
+       <input type="radio" tabindex="4" name="itemnew" class="text" value="2" <?php if($c->Get("NewItem") == 2) echo "checked"; ?>><?php echo prompt_language("la_val_Auto"); ?>
+
+       <input type="radio" tabindex="4" name="itemnew" class="text" value="1" <?php if($c->Get("NewItem") == 1) echo "checked"; ?>><?php echo prompt_language("la_val_Always"); ?>
+
+       <input type="radio" tabindex="4" name="itemnew" class="text" value="0" <?php if($c->Get("NewItem") == 0) echo "checked"; ?>><?php echo prompt_language("la_val_Never"); ?>
+
+
+
+      </td>
+
+    <td class="text">&nbsp;</td>
+
+  </tr>
+
+  <tr <?php int_table_color(); ?>>
+
+   <td valign="top"><span id="prompt_cat_pick" class="text"><?php echo prompt_language("la_prompt_EditorsPick"); ?></span></td>
+
+    <td>
+
+      <input type="checkbox" tabindex="5" name="cat_pick" class="text" value="1" <?php if($c->Get("EditorsPick") == 1) echo "checked"; ?>>
+
+    </td>
+
+    <td class="text">&nbsp;</td>
+
+  </tr>
+
+  <TR <?php int_table_color(); ?> >
+
+    <TD><span id="prompt_Priority" class="text"><?php echo prompt_language("la_prompt_Priority"); ?></span></TD>
+
+    <TD><input type=text SIZE="5" tabindex="6" NAME="Priority" VALUE="<?php echo $c->Get("Priority"); ?>"></TD>
+
+    <TD>&nbsp;</TD>
+
+  </TR>
+
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top" ID="prompt_cat_date" class="text"> <?php echo prompt_language("la_prompt_CreatedOn"); ?> </td>
+
+    <td>
+
+      <input type="text" ValidationType="date,exists" tabindex="7" name="cat_date" id="cat_date_selector" datepickerIcon="../images/ddarrow.gif" class="text" size="20" value="<?php echo $c->parsetag("cat_date"); ?>">
+
+      <span class="small"><?php echo prompt_language("la_prompt_DateFormat"); ?></span>
+
+      </td>
+
+    <td>
+
+    <?php if( IsDebugMode() ) echo '<b>DBG:</b> '.date('M d. Y H:i:s', $c->get('Modified') ); ?>
+
+    </td>
+
+  </tr>
+  <?php int_subsection_title(prompt_language("la_Sectionheader_MetaInformation")); ?>
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top"><span id="prompt_meta_keywords" class="text"><?php echo prompt_language("la_prompt_MetaKeywords"); ?></span></td>
+
+    <td>
+
+      <input type="text" name="meta_keywords" tabindex="8" class="text" size="30" value="<?php echo $c->parsetag("cat_metakeywords"); ?>">
+
+    </td>
+
+    <td class="text">&nbsp;</td>
+
+  </tr>
+
+  <tr <?php int_table_color(); ?>>
+
+    <td valign="top"><span id="prompt_meta_desc" class="text"><?php echo prompt_language("la_prompt_MetaDescription"); ?></span></td>
+
+    <td>
+
+      <textarea name="meta_desc" tabindex="9" cols="60" rows="2" class="text"><?php echo inp_textarea_unescape($c->parsetag("cat_metadesc")); ?></textarea>
+
+    </td>
+
+    <td class="text">&nbsp;</td>
+
+  </tr>
+<?php  
+
+$CustomFieldUI = $objCustomFields->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 "<PRE>";print_r($objCustomFields); echo "</PRE>";
+
+  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 "<tr ".int_table_color_ret().">\n"; 
+
+            print "  <td valign=\"top\" class=\"text\">".$f->GetPrompt()."</td>\n";
+
+            print "  <td nowrap>".$f->ItemFormElement()."</TD>";       
+
+            if(is_object($f->NextItem))
+
+            {
+
+                $n = $f->NextItem;
+
+                print "  <td>".$n->ItemFormElement()."</TD>";       
+
+            }
+
+            else
+
+              print "  <td><span class=\"text\">&nbsp;</span></td>\n";
+
+            print "</tr>\n";
+
+        }
+
+    }
+
+  }
+
+} 
+
+?>
+	<input type="hidden" name="ParentId" value="<?php echo $c->Get("ParentId"); ?>">
+
+	<input type="hidden" name="CategoryId" value="<?php echo $c->parsetag("cat_id"); ?>">
+
+    <input type="hidden" name="Action" value="<?php echo $action; ?>">
+
+    <input type="hidden" name="CatEditStatus" VALUE="0">
+
+</FORM>
+
+
+
+</table>
+
+<script src="<?php echo $adminURL; ?>/include/calendar.js"></script>
+
+
+
+<SCRIPT language="JavaScript">
+
+    initCalendar("cat_date_selector", CalDateFormat);
+
+</SCRIPT>  
+
+<FORM method="POST" NAME="save_edit" ID="save_edit">
+
+  <input type="hidden" name="CatEditStatus" VALUE="0">
+
+</FORM>
+<?php 
+
+	MarkFields('category');
+
+	int_footer(); 
+
+?>
\ No newline at end of file

Property changes on: trunk/admin/category/addcategory.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.6
\ No newline at end of property
+1.7
\ No newline at end of property
Index: trunk/admin/config/edit_customfields.php
===================================================================
--- trunk/admin/config/edit_customfields.php	(revision 666)
+++ trunk/admin/config/edit_customfields.php	(revision 667)
@@ -1,212 +1,217 @@
 <?php 
 ##############################################################
 ##In-portal													##
 ##############################################################
 ##					      In-portal							##
 ##					Intechnic Corporation					##
 ##			   All Rights Reserved, 1998-2002				##
 ##															##	
 ##	No portion of this code may be copied, reproduced or	##	
 ##	   otherwise redistributed without proper written		##
 ##	  consent of Intechnic Corporation.  Violation will		##
 ##	   result in revocation of the license and support		##
 ##	 privileges along maximum prosecution allowed by law.	##
 ##############################################################
 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");
 }
 
 //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"; 
 //$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");
 
 $FieldType = $_GET["DataType"];
 $section = $_GET["section"];
 
 $m = GetModuleArray();
 foreach($m as $key=>$value)
 {
     $path = $pathtoroot. $value."admin/include/parser.php";
     if(file_exists($path))
     {    
       include_once($path);
     }
 }
 unset($objEditItems);
 
 $objCustomFields = new clsCustomFieldList($FieldType);  
 
 $envar = "section=$section&DataType=$FieldType&env=".BuildEnv();
 
 $formaction = $_SERVER["PHP_SELF"]."?".$envar;
 
 $sec = $objSections->GetSection($section);
 
 $objListToolBar = new clsToolBar();
 
 $objListToolBar->Set("section",$section);
 $objListToolBar->Set("load_menu_func","");
 $objListToolBar->Set("CheckClass","FieldChecks");
 $objListToolBar->Set("CheckForm","configform");
   
 $listImages = array();
                     //$img, $alt, $link, $onMouseOver, $onMouseOut, $onClick
 
 $objListToolBar->Add("new_field", "la_ToolTip_New_CustomField",$adminURL."/config/addcustomfield.php?$envar&new=1","swap('new_field','toolbar/tool_forum_new_custom_f2.gif');",
                     "swap('new_field', 'toolbar/tool_forum_new_custom.gif');","",$imagesURL."/toolbar/tool_forum_new_custom.gif");
 
 $objListToolBar->Add("field_edit","la_ToolTip_Edit","#", "if (FieldChecks.itemChecked()) swap('field_edit','toolbar/tool_edit_f2.gif');",
                     "if (FieldChecks.itemChecked()) swap('field_edit', 'toolbar/tool_edit.gif');","if (FieldChecks.itemChecked()) FieldChecks.check_submit('addcustomfield', '');",
                     "tool_edit.gif",TRUE,TRUE);
 $listImages[] = "FieldChecks.addImage('field_edit','$imagesURL/toolbar/tool_edit.gif','$imagesURL/toolbar/tool_edit_f3.gif',1); ";
 
 $objListToolBar->Add("field_del","la_ToolTip_Delete","#", "if (FieldChecks.itemChecked()) swap('field_del','toolbar/tool_delete_f2.gif');",
                     "if (FieldChecks.itemChecked()) swap('field_del', 'toolbar/tool_delete.gif');","if (FieldChecks.itemChecked()) FieldChecks.check_submit('edit_customfields', 'm_customfield_delete');",
                     "tool_delete.gif", FALSE, TRUE);
 $listImages[] = "FieldChecks.addImage('field_del','$imagesURL/toolbar/tool_delete.gif','$imagesURL/toolbar/tool_delete_f3.gif',1); ";
 
 $objListToolBar->AddToInitScript($listImages);
 
 //$title = prompt_language("la_Text_Editing")." ".prompt_language("la_Text_CustomFields");
 
 $where = "Type = ".$FieldType;
 $order = trim($objConfig->Get("CustomConfig_LV_Sortfield")." ".$objConfig->Get("CustomConfig_LV_Sortorder"));
 
 $objCustomFields->Query_CustomField($where,$order);
 
 $objListView = new clsListView($objListToolBar,$objCustomFields);
 $objListView->IdField = "CustomFieldId";
 
 $order = $objConfig->Get("CustomConfig_LV_Sortfield");
 $objListView->ColumnHeaders->Add("FieldName",admin_language("la_ColHeader_FieldName"),1,0,$order,"width=\"30%\"","CustomConfig_LV_Sortfield","CustomConfig_LV_Sortorder","FieldName");
 $objListView->ColumnHeaders->Add("FieldLabel",admin_language("la_ColHeader_FieldLabel"),1,0,$order,"width=\"30%\"","CustomConfig_LV_Sortfield","CustomConfig_LV_Sortorder","FieldLabel");
 $objListView->ColumnHeaders->SetSort($objConfig->Get("CustomConfig_LV_Sortfield"), $objConfig->Get("CustomConfig_LV_Sortorder"));
 
 $objListView->PrintToolBar = FALSE;
 $objListView->checkboxes = TRUE;
 
 $objListView->CurrentPageVar = "Page_CustomData";
 $objListView->PerPageVar = "Perpage_CustomData";
 $objListView->CheckboxName = "itemlist[]"; 
 $objListView->extra_env = "section=$section&DataType=$FieldType";
 
 for($i=0;$i<count($objCustomFields->Items);$i++)
 {   
   $objListView->RowIcons[] = $imagesURL."/itemicons/icon16_custom.gif";
   $field =& $objCustomFields->GetItemRefByIndex($i);
-  $field->Set('FieldLabel', admin_language($field->Get('Prompt')) );
+  if ($field->Get('Prompt') != '') {
+	$field->Set("FieldLabel", admin_language($field->Get('Prompt')));
+  }
+  else {
+	$field->Set("FieldLabel", admin_language('lu_fieldcustom__'.strtolower($field->Get('FieldName'))));
+  }
 }
 
 
 $objListView->ConfigureViewMenu($SortFieldVar,$SortOrderVar,$DefaultSortField,"","",0);
 
 $objListToolBar->AddToInitScript("fwLoadMenus();");
 $h = "\n\n<SCRIPT Language=\"JavaScript1.2\">\n".$objListView->GetViewMenu($imagesURL)."\n</SCRIPT>\n";
 
 int_header($objListToolBar,NULL,$title, NULL, $h);
 ?>
 <form name="configform" ID="configform" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar;?>" method=POST>
 <table cellSpacing="0" cellPadding="2" width="100%" class="tableborder">
 <tbody>
 <?php
   $objListView->PageLinks = $objListView->PrintPageLinks(); /* call this before we slice! */
   $objListView->SliceItems();
   print $objListView->PrintList();
   
 ?>
     <input TYPE="hidden" NAME="DataType" VALUE="<?php echo $FieldType; ?>">
     <input type="hidden" NAME="section" VALUE="<?php echo $section; ?>">
     <input type="hidden" name="Action" value="m_config_custom">
 </FORM>
 <!-- CODE FOR VIEW MENU -->
 <form ID="viewmenu" method="post" action="<?php echo $_SERVER["PHP_SELF"]."?".$envar; ?>" name="viewmenu">
 <input type="hidden" name="fieldname" value="">
 <input type="hidden" name="varvalue" value="">
 <input type="hidden" name="varvalue2" value="">
 <input type="hidden" name="Action" value="">
 </form>
 
 <script src="<?php echo $adminURL; ?>/listview/listview.js"></script>
 <script>
 initSelectiorContainers();
 <?php echo $objListToolBar->Get("CheckClass").".setImages();"; ?>
 </script>
 <?php int_footer(); ?>

Property changes on: trunk/admin/config/edit_customfields.php
___________________________________________________________________
Modified: cvs2svn:cvs-rev
## -1 +1 ##
-1.3
\ No newline at end of property
+1.4
\ No newline at end of property