<?
/*   search.php3 v.2.1.2 for UdmSearch 2.1
 *   by UdmSearch Developers Team
 */

$configdir="/usr/local/UdmSearch/etc";

//$DEBUG=1;
/* Please set the following mysql variables in template (etc/search.htm) */
$mysqldb='udmsearch';
$mysqlhost='localhost';
$mysqluser='foo';
$mysqlpass='bar';

$self='search.php3';
$template_file='udmsearch.htm';

/* You should'n change anything below
 */

$tag=$t;
$tagstr=($tag=="")?"":"AND url.tag=$tag";
if($ps=="") $ps=20;
if($np=="") $np=0;
// All by default
$mode=(strtolower($m)=="all")?"all":"any";
srand(mktime()); 
$Randoms[$i]=array();

// array of templates
$templates=array();

function read_template(){
    global $Randoms;
    global $template_file;
    global $configdir;
    global $templates;
    $names=array('top', 'bottom', 'restop', 'resbot',
		'res', 'notfound', 'error', 'variables', 'clone');

    $where='';
    
    if (!($fp=fopen($configdir.'/'.$template_file, 'r'))){
	echo "Can't open template file $configdir/$template_file";
	exit;
    }    
    do {
	$str=fgets($fp, 1024);
	reset($names);
	while ($name=current($names)){
	    if (strstr($str, "<!--$name")){
		$where=$name;
		$templates["$where"]='';
		break;
	    }
	    else
	    if (strstr($str, "/$name-->")){
		$where='';
		break;
	    }
	    next($names);
	}
	if ($where=='variables'){
	    // find and assign vars
	    if ($var=strtok($str, '=')){
		    $value=strtok(" \n\r");
		    $var=strtolower($var);
		    if($var[0]=='r'){
				$rand=0+substr($var,1);
				$frand=rand();
				$frand=$frand/getrandmax()*$value;
				$Randoms[$rand]=floor($frand);
		    } else
			$GLOBALS["$var"]="$value";
	    }
	}
	else
	if ($where!=''){
	    $templates["$where"]=$templates["$where"]."\n".$str;
	}
    } while (!feof($fp));

    fclose($fp);
}

/* Variables used in templates
 */

$from1;	// $f - num of first doc on page
$to;	// $l - num of last doc on page
$found; // $t - total docs found

$query; // $Q - query
$error;	// $E - error
$nav;	// $V - naVigator
$wordsinfo; // $W - words info

/* don't uncomment this
$self;  // $A - form Action
*/

// some about Document found
$url;		// $DU - Document URL
$title;		// $DT - Document Title
$rating;	// $DR - Document Rating
$contype;	// $DC - Document Content-type
$lastmod;	// $DM - Document last Modified
$docsize;	// $DS - Document Size
$ndoc;		// $DN - Document No
$desc;		// $DD - Document Description
$keyw;		// $DK - Document Keywords
$text;		// $DX - Document teXt

function print_template($t,$echo=1){
    global $templates;
    global $from1, $to, $found, $query, $error, $self;
    global $nav, $wordsinfo;
    global $url, $title, $rating, $desc, $contype, $lastmod, $docsize, $ndoc;
    global $keyw, $text;
    global $crc, $Randoms, $rec_id, $mysqldb, $DEBUG;
    
    $str=$templates["$t"];

    $str=ereg_replace('\$f', "$from1", $str);
    $str=ereg_replace('\$l', "$to", $str);
    $str=ereg_replace('\$t', "$found", $str);
    $str=ereg_replace('\$A', $self, $str);

    $str=ereg_replace('\$Q', $query, $str);
    $str=ereg_replace('\$E', $error, $str);
    $str=ereg_replace('\$V', $nav, $str);
    $str=ereg_replace('\$W', $wordsinfo, $str);

    $str=ereg_replace('\$DU', $url, $str);
    $str=ereg_replace('\$DT', $title, $str);
    $str=ereg_replace('\$DR', "$rating", $str);
    $str=ereg_replace('\$DX', $text, $str);
    $str=ereg_replace('\$DC', $contype, $str);
    $str=ereg_replace('\$DM', $lastmod, $str);
    $str=ereg_replace('\$DS', "$docsize", $str);
    $str=ereg_replace('\$DN', "$ndoc", $str);
    $str=ereg_replace('\$DD', $desc, $str);
    $str=ereg_replace('\$DK', $keyw, $str);
    
	$sub=$str;
    while($sub=strstr($sub,'$r')){
		$sub=substr($sub,2);
		$pos=0;
		$num='';
		while(($sub[$pos]>='0')&&($sub[$pos]<='9')){
			$num.=$sub[$pos++];
		}
		$str=ereg_replace('\$r'.$num, ''.$Randoms[$num], $str);
    }
    
    if(strstr($str,'$CL')&&($t=='res')){
	if($crc<>''){
		$myurl=$url;$myct=$contype;$mylm=$lastmod;
		$query="SELECT url,content_type,last_modified FROM url WHERE crc='$crc' AND rec_id<>'$rec_id'";
		if($DEBUG) echo $query,"<BR><HR>";
		if(!($res=mysql($mysqldb,$query))) print_error('Query error:'.$query."\n<BR>".mysql_error());
		while($row=mysql_fetch_row($res)){
		    $url=$row[0];
		    $contype=$row[1];
		    $lastmod=$row[2];
		    $clon.=print_template('clone',0);
		}
		mysql_free_result($res);
		$url=$myurl;$contype=$myct;$lastmod=$mylm;
	}
	$str=ereg_replace('\$CL', $clon, $str);
    }
    
    // ....
    
    if($echo) echo $str; else return $str;
}

function print_error($str){
    global $error;
    
    $error=$str;
    print_template('error');
    print_template('bottom');
    exit;
}

if (isset($q)){
    $query=htmlspecialchars($q);
}
else{
    $query='';
}
read_template();
if(isset($resultsperpage)) $ps=$resultsperpage;

print_template('top');

function ParseStr($qwe){
  $qwe=ereg_replace("[^ &|~()ءآ×اؤإ£ضعةتثجحخدذزسشصئبأقغفكظطـہر0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]{1,}","&",$qwe);
  $qwe=ereg_replace("^ {0,}","",$qwe);
  $qwe=ereg_replace(" {0,}\| {0,}","|",$qwe);
  $qwe=ereg_replace(" {0,}\& {0,}","&",$qwe);
  $qwe=ereg_replace(" {0,}\( {0,}","(",$qwe);
  $qwe=ereg_replace(" {0,}\) {0,}",")",$qwe);
  $qwe=ereg_replace(" {0,}\~ {0,}","~",$qwe);
  $qwe=ereg_replace(" {1,}","|",$qwe);
  $qwe=ereg_replace("\|{1,}","|",$qwe);
  $qwe=ereg_replace("&{1,}","&",$qwe);  
  $qwe=ereg_replace("\|\&\|","&",$qwe);
  $qwe=ereg_replace("[\|\&]{1,}$","",$qwe);
  $qwe=ereg_replace("^[\|\&]{1,}","",$qwe);
  return($qwe);
}

if (ereg_replace(" ","",$q)==''){
    print_template('bottom');
    exit;
}

$query_orig=$q;

$q=ParseStr($q);

$q=ereg_replace("\&"," && ",$q);
$q=ereg_replace("\|"," || ",$q);
$q=ereg_replace("\~"," ! ",$q);
$q=ereg_replace("\("," ( ",$q);
$q=ereg_replace("\)"," ) ",$q);
$q="( $q )"; 
$q=ereg_replace(" {1,}"," ",$q);
$qu="";
$w=""; 
$state=0; 
$n=0;

$t=strtok($q," ");

if (!mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass))
    print_error('Connection Error');

$stopwords=array();
$query="SELECT word FROM stopword";
if($DEBUG) echo $query,"<BR><HR>";
if(!($res=mysql($mysqldb,$query))) print_error('Query Error');
while($row=mysql_fetch_row($res)){
    $stopwords[$row[0]]=1;
}

while(($t!="")&&($error=="")){
  if(isset($stopwords[$t])) {
       if(isset($wordsinfo)) $wordsinfo.=', ';
       $wordsinfo.="$t: stopword";
       $t='';
  }
  switch($state){
    case 0;  
    if(($t=="||")||($t=="&&")||($t==")"))
      $error="at '$t'";
    else if($t=="!"){
      $state=0;
      $qu="$qu ! ";
    }
    else if($t=="("){
      $n++;
      $state=0;
      $qu="$qu(";
    }
    else {
      $qu="$qu sum(dict.word='$t')";
      if($w=="")
	$w="'$t'";
      else
	$w="$w,'$t'";
      $state=1;
    }
    break;
    
    case 1;  
    if(($t=="||")||($t=="&&")){
      $state=0;
      $qu="$qu $t";
    }
    else if($t==")"){
      $n--;
      $state=1;
      $qu="$qu)";
    }
    else
      $error=" at '$t'";
    break;
  }
  $t=strtok(" ");
}

if(isset($wordsinfo)) $wordsinfo.='; ';

if($error==""&&$n!=0)
  $error='Unmatched brackets';

if($error!="")
    print_error($error);

if($ul||$tagstr)
    $query="SELECT word,count(*) as c FROM dict,url WHERE word IN 
    ($w) AND url.rec_id=dict.url_id AND url.url LIKE '%$ul%' $tagstr
    GROUP BY word ORDER BY word";
else
    $query="SELECT word,count(*) as c FROM dict WHERE word IN
    ($w) GROUP BY word ORDER BY word";
if($DEBUG) echo $query,"<BR><HR>";

if(!($res=mysql($mysqldb,$query))) print_error('Query Error');
$rows=mysql_num_rows($res);
for($i=0;$i<$rows;$i++){
    $row=mysql_fetch_row($res);
    $wordsinfo.=$row[0].': '.$row[1];
    if($i+1<$rows) $wordsinfo.=', ';
    else $wordsinfo.='  &nbsp; &nbsp; ';
}
mysql_free_result($res);

$query="SELECT ($qu)as qu, dict.url_id
     FROM dict,url WHERE url.rec_id=dict.url_id
     AND url.url LIKE '%$ul%' $tagstr
     AND dict.word in ($w)
     GROUP BY dict.url_id HAVING qu>0";
if($DEBUG) echo $query,"<BR><HR>";
if (!($res=@mysql($mysqldb,$query)))
    print_error('Query error: '.$query."\n<BR>".mysql_error());

$found=mysql_numrows($res);
mysql_FreeResult($res);

$from=IntVal($np)*IntVal($ps); 
$from1=IntVal($from)+1;
$to=IntVal($np+1)*IntVal($ps); 
$ps1=IntVal($ps)+1;
if($to>$found)
  $to=IntVal($found);

$ps_next=$found-$to;
if (($ps_next>$ps) || ($ps_next<0))
    $ps_next=$ps;

if($found>0){
    print_template('restop');
}
else{
    print_template('notfound');
    print_template('bottom');
    exit;
}

if($ul||$tagstr)
    $query="SELECT dict.url_id,sum(dict.word in ($w))as r,($qu)as qu
	    FROM url,dict
	    WHERE url.rec_id=dict.url_id
	    AND url.url LIKE '%$ul%' $tagstr
	    AND dict.word in ($w)
	    GROUP BY url_id
	    HAVING qu>0
	    ORDER BY r DESC LIMIT $from,$ps1";
else
    $query="SELECT dict.url_id,sum(dict.word in ($w))as r,($qu)as qu
	    FROM dict
	    WHERE dict.word in ($w)
	    GROUP BY url_id
	    HAVING qu>0
	    ORDER BY r DESC LIMIT $from,$ps1";
if($DEBUG) echo $query,"<BR><HR>";

if (!($res=@mysql($mysqldb,$query)))
    print_error('Query error: '.$query."\n<BR>".mysql_error());

$rows=mysql_numrows($res); 
$i=0;
if($rows>$ps){
 $rows=$ps;
 $isnext=1;
}

while($i++<$rows){
  $row=mysql_fetch_row($res);
  $url_id = $row[0];
  if($url_in=="")
    $url_in="$url_id";
  else	
    $url_in.=",$url_id";
}
mysql_FreeResult($res);

if($url_in!=""){
  $query="SELECT url.url,url.title,url.text,url.content_type,url.size,url.last_modified,url.keywords,url.description,url.crc,dict.url_id,sum(dict.word in ($w))as r,($qu)as qu FROM dict,url WHERE dict.word in ($w) AND dict.url_id in ($url_in) AND dict.url_id=url.rec_id GROUP BY url_id HAVING qu>0 ORDER BY r DESC";
  if($DEBUG) echo $query,"<BR><HR>";
  if (!($res=@mysql($mysqldb,$query)))
      print_error('Query error: '.$query."\n<BR>".mysql_error());

  $ndoc=$from+1;
  while($data=mysql_fetch_array($res)){
    $title=$data[title];
    $title=($title) ? htmlspecialChars($title):'No title';
    $text=htmlspecialChars($data[text]);
    $url=$data[url]; $rec_id=0+$data[url_id];
    $contype=$data[content_type];
    $docsize=$data[size];
    $lastmod=$data[last_modified];
    $rating=$data[r];
    $keyw=$data[keywords];
    $desc=$data[description];
	$crc=$data[crc];
    print_template('res');
    $ndoc++;
  }
  mysql_FreeResult($res);
}
$q=ereg_replace(" ","+",$query_orig);
$q=ereg_replace("&","%26",$q);
if($np>0){
  $prevp=$np-1;
  $nav="<A HREF=\"$self?q=$q&np=$prevp&ps=$ps&m=$mode&t=$tag&ul=$ul\">[&lt; &lt; Prev $ps]</A> &nbsp; ";
}
if($isnext==1){
  $nextp=$np+1;
  $nav=$nav."<A HREF=\"$self?q=$q&np=$nextp&ps=$ps&m=$mode&t=$tag&ul=$ul\">[Next $ps_next &gt; &gt;]</A>";
}

  print_template('resbot');    
  print_template('bottom');
?>