<?php
/*
+===========================================+
|      ArabPortal V2.1.x Copyright © 2006   |
|   -------------------------------------   |
|                                           |
|            By Rafia AL-Otibi              |
|                    And                    |
|              Arab Portal Team             |
|   -------------------------------------   |
|      Web: http://www.ArabPortal.Net       |
|   -------------------------------------   |
|  Last Updated: 22/10/2006 Time: 10:00 PM  |
+===========================================+
*/

class search
{
    var $db_fields      = '';
    var $db_table       = '';
    var $from_date      = '';
    var $search_word    = '';
    var $search_order   = '';
    var $query          = '';
    var $cquery          = '';
    var $date_time      = 'date_time';
    var $timestamp      = 'timestamp';

 // added by KHR2003
    var $catid      	= 'cat_id';
    var $catno      	= '';
    var $membername	= '';
    var $name		= 'name';
    var $search_orderby  = '';
// END ADD

    var $fileName       = '';
    var $select_array   = '';
    var $count_array    = 0;
    var $fieldID        = 'id';
    var $spell          = 0;

    function search($db_table="",$db_fields=array())
    {
        global $apt,$search_orderby,$search_order,$catsearch,$choosecat;
        $this->db_table  = $db_table;
        $this->db_fields = $db_fields;
        $this->search_order = $search_order;
        $this->search_orderby = $search_orderby;

// Added By khr2003
	if ($membername !== '')$this->membername = $membername;
	if ($catsearch == 'on')$this->catno = $choosecat;
// END ADD

        if (intval($apt->post['search_max']) ==0)
            $this->search_max = '30';
        else
            $this->search_max = $apt->post['search_max'];
	  $from_date = intval($apt->post['from_date']);
        if ($from_date > 0){
            $this->from_date = mktime (0,0,0,date("m"),date("d")-$from_date,  date("Y"));
        }else{
            $this->from_date = '0';
        }

    }

    function search_inday($search_word)
    {
        global $apt;

        $today = mktime (0,0,0,date("m"),date("d")-$apt->conf[search_timeOut],  date("Y"));

	  $search_word =  $apt->spelling_ar_words($this->spell,$search_word);
        
        $result = $apt->query("SELECT id FROM rafia_search_res WHERE
                               search_word ='".$search_word."'
                               and search_in ='".$this->db_table."'
                               and search_date > '".$today."'");
                               
        if($apt->dbnumrows($result) > 0)
        {
            $row = $apt->dbnumrows($result);
            return $row[id];
        }
        else
        return 0;
    }

    function do_search($search_word)
    {
        global $apt;

	  $search_inday = $this->search_inday($search_word);
        if($search_inday > 0)
        {
        	return $search_inday;
        }
        
        $this->search_word = $search_word;
        $this->query  = "SELECT id FROM ".$this->db_table." WHERE ";
        $this->cquery  = "SELECT id FROM rafia_comment WHERE ";
        $this->query .= $this->date_time." >'".$this->from_date."' AND ";
        $this->cquery .= $this->timestamp." >'".$this->from_date."' AND ";
	// ADDED BY KHR2003
        if ($catsearch == on){
			if (! $this->catno == '0'){
            	$this->query .= $this->catid." ='".$this->catno."' AND ";
            	$this->cquery .= $this->catid." ='".$this->catno."' AND ";
			}
        }
	 if (! $membername == ''){
			$this->query .= $this->name." ='".htmlspecialchars($membername)."' AND ";
			$this->cquery .= $this->name." ='".htmlspecialchars($membername)."' AND ";
        }
	// END ADD
        $this->query .= $this->set_fields_sql();
        $this->cquery .= $this->set_Cfields_sql();
        $this->search_word = $search_word;
        $resultid = array();
        $result = $apt->query($this->query);

        if($apt->dbnumrows($result) > 0){
             while($row = $apt->dbarray($result))
            {
                $resultid[] = $row['0'];
            }
        }

	  if($this->db_table == 'rafia_forum')
	   $this->cquery = str_replace('id','thread_id',$this->cquery);
	  elseif($this->db_table == 'rafia_news')
	   $this->cquery = str_replace('id','news_id',$this->cquery);
	  elseif($this->db_table == 'rafia_download')
	   $this->cquery = str_replace('id','down_id',$this->cquery);

        $resultc = $apt->query($this->cquery);
        if($apt->dbnumrows($resultc) > 0)
        {
             while($row = $apt->dbarray($resultc))
            {
                $resultid[] = $row['0'];
            }
        }


        $resultid = array_unique($resultid);
        foreach($resultid as $ids){$resvalue .= $ids.',';}

        $resultid = substr ($resvalue,0,strlen($resvalue)-1);

	  if($resultid==0){
	  return 0;
	  }else{
            $value     =  $resultid;
            $resulti   = $apt->query("insert into rafia_search_res (search_id,
                                                                    search_word,
                                                                    search_in,
                                                                    search_date,
                                                                    from_date,
                                                                    search_order,
											  search_orderby,
                                                                    user_id,
											  cat_id,
                                                                    search_max,
											  name,
                                                                    search_ip)
                                                              values
                                                                   ('".$value."',
                                                                    '".$this->search_word."',
                                                                    '".$this->db_table."',
                                                                    '".$apt->time."',
                                                                    '".$this->from_date."',
                                                                    '".$this->search_order."',
											  '".$this->search_orderby."',
                                                                    '".$apt->cookie['cid']."',
											  '".$this->catno."',
                                                                    '".$this->search_max."',
											  '".$this->membername."',
                                                                    '".$apt->ip."')");

        	if($resulti){
             	return $apt->insertid();
        	}else{
        	return 0;
        	}
	  }
}
    function set_fields_sql()
    {
        global $apt;

        $this->search_word =  $apt->spelling_ar_words($this->spell,$this->search_word);
      
        if(is_array( $this->db_fields ))
        {
            foreach ($this->db_fields as $fields)
            {
				$dbquery .= "".$fields." REGEXP '" . $this->search_word . ".*' OR ";
            }

            $dbquery   = substr ($dbquery,0,strlen($dbquery)-3);

            return  "(".$dbquery.")";
        }
    }

    function set_Cfields_sql()
    {
        global $apt;

        $this->search_word =  $apt->spelling_ar_words($this->spell,$this->search_word);
      
        $array = array('title','comment');
        {
            foreach ($array as $fields)
            {
				$dbquery .= "".$fields." REGEXP '" . $this->search_word . ".*' OR ";
            }

            $dbquery   = substr ($dbquery,0,strlen($dbquery)-3);

            return  "(".$dbquery.")";
        }
    }

    function result_search($select_array = array())
    {
        global $apt,$start;
        $this->search_word = Null;
        $id = $apt->setid('id');
        $this->select_array = $select_array;
        $this->count_array  = count($select_array);
        
        $result = $apt->query("SELECT * FROM rafia_search_res WHERE id ='" . $id . "'");

        if($apt->dbnumrows($result) > 0)
        {
             $row = $apt->dbarray($result);
             
             $this->search_word = $row['search_word'];
             $this->db_table    = $row['search_in'];
             $this->search_max  = $row['search_max'];
                                  
             $this->result_id = sizeof(explode(",",$row['search_id']));
             if($this->db_table =='rafia_links')$tfld = 'date_time'; else $tfld = 'timestamp,c_comment,reader';
             $this->query = "SELECT id,title,name,$tfld FROM ".$this->db_table ." WHERE";

             if($this->result_id > 1)
             {
                 $this->query .= " id in(".$row[search_id].")";
             }
             else
             {
                 $this->query .= " id =".$row[search_id]."";
             }

             if(! $this->db_table =='rafia_links'){
			$this->query .=" ORDER BY ".$row[search_orderby]." ";
			$this->query .= "".$row[search_order]."";
		 }
             if($this->result_id > 1)
             {
                 $this->query .=" LIMIT $start,".$row[search_max]."";
             }
        }else{
             $apt->errmsg(LANG_ERROR_URL);
        }
    }
    
    function SetID($fieldID)
    {
       $this->fieldID = $fieldID;
    }

    function result_outPut($urlK,$date)
    {
        global $apt;
        
        $result = $apt->query($this->query);
        $search_word  = $this->search_word;
        $spell = intval($apt->get['spell']);
        while($rows = $apt->dbarray($result))
        {
            $file = $this->fileName.$this->fieldID."=".$rows[$this->fieldID]."&spell=".$spell."&highlight=".urlencode($search_word);
		
		
		
            $alt = 1;
             $outPut .= '<tr>';
            foreach ($this->select_array as  $k => $v )
            {
                if($alt ==1)
                $alt=2;
                else
                $alt=1;
                if ($date == $k)
                {
                    $rows[$k] = $apt->Hijri($rows[$k]);
                }
                if ($urlK == $k)
                {

                    $outPut .= '<td  class="forum_alt'.$alt.'"><a href='.$file.' target=_blank>'.$rows[$k].'</a></td>';
                }
                else
                $outPut .= '<td class="forum_alt'.$alt.'">'.$rows[$k].'</td>';
                
            }
           $outPut .= ' </tr>';
        }
      return  $this->outPut($outPut);
    }

    function outPut($row)
    {
        global $apt;
        $widths = array(30,20);
        $outPut .="<p><img border=0 src=images/searc.gif> <B>نتائج البحث</B></p>
                             <table border='0' width='90%'><tr><td width='100%'><font class=fontht>
                             <b>عدد المواضيع التي بها كلمة مطابقة  : ".$this->result_id."
                             <br>كلمة البحث ( ".$this->search_word." )</td></tr></table>";
                             
        $outPut .= '<table id="table6" cellSpacing="1" cellPadding="0" width="95%" border="0"><tr>';

       $this->count_array;
        $i =0;
        foreach ($this->select_array as  $v)
        {
            if($i==0)
            $width =  ((100/$this->count_array)*$widths[0]);
            else
            $width =  ((100/$this->count_array)*$widths[1]);
            
            $outPut .= '<td width="$width%" class="forum_header">'.$v.'</td>';
            
            $i++;
        }
        
        $outPut .= '</tr>';
        $outPut .= $row;
        $outPut .= '</table>';
        return $outPut;
    }
    
   function catlist($cattype,$id,$table)
    {
        global $apt;
		$catlist = "<input type=\"checkbox\" name=\"catsearch\" id=\"Delete1\" onclick=\"document.getElementById('$id').disabled=!(this.checked)\">";
		 $catlist .=  "<b>&nbsp;البحث في قسم معين؟</br>";
        $catlist .=  "<select name='choosecat' id='$id' size='5' disabled>\n";
        $result = $apt->query("select * from rafia_$table where catType= $cattype order by id ASC");
        while($row=$apt->dbarray($result))
        {
            $id=$row["id"];
            $title=$row["title"];
            $catlist .=  "<option value='$id'>$title</option>";
        }
        $catlist .=  "</select>\n";
		
         return $catlist;
    }
	
} // end class
?>
