<?php

RegisterPrefix("clsSearchConfig","searchfield","kernel/include/searchconfig.php");

class clsSearchConfig extends clsParsedItem 
{

    function clsSearchConfig($id=NULL)
    {        
        $this->clsParsedItem();
        $this->tablename = GetTablePrefix()."SearchConfig";
        $this->id_field = "SearchConfigId";
        $this->NoResourceId=1;
        $this->TagPrefix="searchfield";
        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;
    }

    function GetWhereClause($verb,$value)
    {
    	//$value = $this->adodbConnection->qstr(stripslashes($value));
    	$where = "";
    	if(strlen($this->Get("ForeignField"))>0)
    	{
    		$field = $this->Get("ForeignField");
    	}
    	else
    	  $field = $this->Get("FieldName");
    	  
    	switch($verb)
    	{
    		case "is":
    			if(strlen($this->Get("IsWhere")))
    			{
    				$where = str_replace("{Value}",$value,$this->Get("IsWhere"));
    			}
    			else
    			  $where = $field." = '".$value."'";
    		break;
    		case "isnot":
    			if(strlen($this->Get("IsNotWhere")))
    			{
    				$where = str_replace("{Value}",$value,$this->Get("IsNotWhere"));
    			}
    			else
    			  $where = $field." != '".$value."'";
    		break; 
    		case "contains":
    			if(strlen($this->Get("ContainsWhere")))
    			{
    				$where = str_replace("{Value}",$value,$this->Get("ContainsWhere"));
    			}
    			else
    			  $where = $field." LIKE '%".$value."%'";
    		break; 
    		case "notcontains":
    			if(strlen($this->Get("NotContainsWhere")))
    			{
    				$where = str_replace("{Value}",$value,$this->Get("NotContainsWhere"));
    			}
    			else
    			  $where = $field." NOT LIKE '%".$value."%'";
    		break; 
    	}
    	return $where;	
    }

    function ParseObject($element)
    {
        global $objConfig, $objSession, $objUsers, $objCatList, $var_list_update, $var_list, 
               $bb_var_list_update, $m_var_list_update,$FormValues;
       
        $extra_attribs = ExtraAttributes($element->attributes);
        if(strtolower($element->name)==$this->TagPrefix)
        {          
            $field = strtolower($element->attributes["_field"]);          
            switch($field)
            {  
            case "name":
                $ret = $this->Get("FieldName");
                break;
            case "lang_name":
                $ret = language($this->Get("DisplayName"));
                break;
            case "id":
                $ret = $this->Get("SearchConfigId");
                break;
            case "header":
                $hdr = $this->Get("ConfigHeader");
                if(strlen($hdr))
                    $ret = language($hdr);
                break;
            case "table":
                $ret = $this->Get("TableName");
                break;
            case "simple":
                $ret = (int)$this->Get("SimpleSearch");
                if($ret)
                {                
                  if(strlen($element->attributes["_text"]))
                      $ret = language($element->attributes["_text"]);
                  if(strlen($element->attributes["_plaintext"]))
                      $ret = $element->attributes["_plaintext"];
                }
                break;
            case "advanced":
                $ret = (int)$this->Get("AdvancedSearch");
                if($ret)
                {                
                  if(strlen($element->attributes["_text"]))
                      $ret = language($element->attributes["_text"]);
                  if(strlen($element->attributes["_plaintext"]))
                      $ret = $element->attributes["_plaintext"];
                }

            break;
            case "verb_select":
              $datatype = $this->Get("FieldType");
              switch($datatype)
              {
              	case "text":              
              	  $fieldname = "verb[".$this->Get("FieldName")."]";
              	  $ret = "<SELECT name=\"$fieldname\">";
              	 
              	  $selected="";
              	  if($FormValues[$fieldname]=="any")
              	    $selected = " selected";              	 
              	  $ret .= "<OPTION value=\"any\" $selected>".language("lu_advsearch_any")."</OPTION>";              	 
              	 
              	  $selected="";
              	  if($FormValues[$fieldname]=="is")
              	    $selected = " selected";              	 
              	  $ret .= "<OPTION value=\"is\" $selected>".language("lu_advsearch_is")."</OPTION>";
              	 
              	  $selected="";
              	  if($FormValues[$fieldname]=="isnot")
              	    $selected = " selected";              	               	
              	  $ret .= "<OPTION value=\"isnot\" $selected>".language("lu_advsearch_isnot")."</OPTION>";
              	 
              	  $selected="";
              	  if($FormValues[$fieldname]=="contains")
              	    $selected = " selected";              	 
              	  $ret .= "<OPTION value=\"contains\" $selected>".language("lu_advsearch_contains")."</OPTION>";

              	  $selected="";
              	  if($FormValues[$fieldname]=="notcontains")
              	    $selected = " selected";              	 
              	  $ret .= "<OPTION value=\"notcontains\" $selected>".language("lu_advsearch_notcontains")."</OPTION>";
              	  $ret .= "</SELECT>";
                 break;
                 case "boolean":
					$ret = "";            	             	                
                 break;              
              } 
            break;  
            case "form_input":
              $datatype = $this->Get("FieldType");
              $name = $this->Get("FieldName");
              switch($datatype)
              {
              	case "text":              	
              	  $ret = "<INPUT TYPE=TEXT maxlength=50 name=\"value[$name]\" VALUE=\"".$FormValues[$name]."\">";
              	break;
              	case "boolean":              	
              	  $ret = "<INPUT TYPE=RADIO name=\"value[$name]\" VALUE=\"-1\" ";
              	  if(!is_numeric($FormValues[$name]) || ($FormValues[$name] != 1 && $FormValues[$name]!= 0))
              	    $ret .= " CHECKED";
              	  $ret .=">".language("lu_advsearch_any");
              	  $ret .= "<INPUT TYPE=RADIO name=\"value[$name]\" VALUE=\"1\" ";
              	  if($FormValues[$name]==1)
              	    $ret .= " CHECKED";
              	  $ret .= ">".language("lu_true");
              	  $ret .= " <INPUT TYPE=RADIO name=\"value[$name]\" VALUE=\"0\" ";   
              	  if(is_numeric($FormValues[$name]) && $FormValues[$name]==0)
              	    $ret .= " CHECKED";
              	  $ret .= ">".language("lu_false");
              	break;    
              }
              break;
              case "andor_radio":
                $name = $this->Get("FieldName");
                $Field = "andor[$name]";
                $checked = Array(1 => '', 2 => '');
                $checked[ $FormValues[$Field] ] = ' checked';
                if(!$FormValues[$Field]) $checked[1] = ' checked';
                
                $ret = "<INPUT TYPE=RADIO NAME=\"$Field\" VALUE=\"1\" ".$checked[1].">".language("lu_and");				
                $ret .= "<INPUT TYPE=RADIO NAME=\"$Field\" VALUE=\"2\" ".$checked[2].">".language("lu_or");
                return $ret;
            }
            
        }
        return $ret;
    }
}

class clsSearchConfigList
{
    var $Module;
    var $Items;
    var $SourceTable;
    var $classname;
    var $adodbConnection;

    function clsSearchConfigList($module=NULL)
    {        
        $this->SourceTable = GetTablePrefix()."SearchConfig";
        $this->classname = "clsSearchConfig";
        $this->adodbConnection = &GetADODBConnection();
        $this->Items = array();
        if($module)
            $this->LoadModule($module);
    }

    function Clear()
    {
      unset($this->Items);
      $this->Items = array();
    }


    function ResetModule()
    {
        $this->Clear();
        $sql = "UPDATE ".$this->SourceTable." SET SimpleSearch=0, AdvancedSearch=0 WHERE ModuleName='".$this->module."'";
        $this->adodbConnection->Execute($sql);
    }

    function LoadModule($mod)
    {
        $this->Clear();
        $this->Module = $mod;
        $sql = "SELECT * FROM ".$this->SourceTable." WHERE ModuleName ='$mod' ORDER BY DisplayOrder";
        
        return $this->Query_Item($sql);
    }
        
    function GetNextDisplayOrder($mod)
    {
    	$ret = 0;
    	$sql = "SELECT max(DisplayOrder) as do FROM ".$this->SourceTable." WHERE ModuleName='$mod'";
    	$rs = $this->adodbConnection->Execute($sql);
    	if($rs && !$rs->EOF)
    	  $ret = $rs->fields["do"]+1;
    	return $ret;
    }  

    function AddItemFromArray($data)
    {    
        $class = new $this->classname;
        $class->SetFromArray($data);
        //foreach($data as $prop => $value)
        //    $class->Set($prop,$value);
        array_push($this->Items,$class);
        return $class;
    }

    
    function Query_Item($sql, $limit=NULL)
    {
        global $Errors;

        if(isset($limit))
            $result = $this->adodbConnection->SelectLimit($sql, $limit);
        else
            $result = $this->adodbConnection->Execute($sql);
    
        if ($result === false)
        {
            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"Query_Item");
            return false;
        }
        $this->Clear();
        while ($result && !$result->EOF)
        {
            $data = $result->fields;
            $this->AddItemFromArray($data);
            $result->MoveNext();
        }
        return $this->Items;
    }
    
    function GetItem($ID)
    {
        $found=FALSE;

        if(is_array($this->Items))
        {
          foreach($this->Items as $i)
          {
            if($i->UniqueID()==$ID)
            {
                $found=TRUE;
                break;
            }
          }
        }
        if(!$found)
        {
            $i = NULL;
            $i = new $this->classname();
            //$i->idfield = $i->IdField(); //set the id field before we change tables
            $i->tablename = $this->SourceTable;
            $i->LoadFromDatabase($ID);
            array_push($this->Items, $i);
        }
        return $i;
    }

    function GetItemByName($Table,$Name)
    {
        $found=FALSE;

        if(is_array($this->Items))
        {
          foreach($this->Items as $i)
          {
            if($i->Get("TableName")==$Table && $i->Get("FieldName")==$Name)
            {
                $found=TRUE;
                break;
            }
          }
        }
        if(!$found)
        {
            $i = NULL;

            $rs = $this->adodbConnection->Execute("SELECT * FROM ".$this->SourceTable." WHERE Tablename='$Table' AND FieldName='$Name'");
            if($rs && !$rs->EOF)
            {
            	$i = new $this->classname();
            	//$i->idfield = $i->IdField(); //set the id field before we change tables
            	$i->tablename = $this->SourceTable;            	
            	$i->SetFromArray($rs->fields);
            }            
            array_push($this->Items, $i);
        }
        return $i;      	
    }

    function EditFieldSettings($FieldId,$SimpleSearch,$AdvancedSearch,$Priority)
    {
        $f = $this->GetItem($FieldId);
        //echo "<PRE>"; print_r($f); echo "</PRE>";
        $f->Set("SimpleSearch",(int)$SimpleSearch);
        $f->Set("AdvancedSearch",(int)$AdvancedSearch);
        $f->Set("Priority",(int)$Priority);
        $f->Update();
        return $f;
    }  
    
    function &AddSearchField($Table,$FieldName,$Module,$Simple,$Adv,$Description,$DisplayName,$ConfigHeader,$DisplayOrder=0,
    			 			 $Priority=0,$FieldType="text",$JoinClause=NULL,$IsWhere=NULL,$IsNotWhere=NULL,$ContainsWhere=NULL,$NotContainsWhere=NULL,$CustomId=0)
    {
    	$f = new clsSearchConfig();
    	if($DisplayOrder==0)
    	  $DisplayOrder = $this->GetNextDisplayOrder($Module);
    	$f->Set(Array("TableName","ModuleName","SimpleSearch","AdvancedSearch","Description","DisplayName","ConfigHeader",
    				   "DisplayOrder","Priority","FieldType","FieldName"),
    			Array($Table,$Module,$Simple,$Adv,$Description,$DisplayName,$ConfigHeader,$DisplayOrder,$Priority,$FieldType,$FieldName));
    	$f->Set("CustomFieldId",$CustomId);
		if(strlen($JoinClause))
			$f->Set("JoinClause",$JoinClause);    			
		if(strlen($IsWhere))
			$f->Set("IsWhere",$IsWhere);
		if(strlen($IsNotWhere))
			$f->Set("IsNotWhere",$IsNotWhere);
		if(strlen($ContainsWhere))
			$f->Set("ContainsWhere",$ContainsWhere);
		if(strlen($NotContainsWhere))
			$f->Set("NotContainsWhere",$NotContainsWhere);
	    $f->Create();
	    return $f; 		    			
    }

    function GetHeadingList()
    {
        $res = array();
        foreach($this->Items as $i)
        {
            $header = $i->Get("ConfigHeader");
            $res[$header]=1;
        }
        reset($res);
        return array_keys($res);
    }
    
    function GetHeadingItems($heading)
    {
        $res = array();
        foreach($this->Items as $i)
        {
            if($i->Get("ConfigHeader")==$heading)
                array_push($res,$i);
        }
        return $res;
    }
}
?>