<?
extract($_REQUEST);
$script_path = dirname(__FILE__);
chdir($script_path);
chdir('..');
chdir('..');
$root_path = getcwd();
$admin_path = $root_path.'/admin';
chdir($script_path); 

require($admin_path.'/functions.php');
require($admin_path.'/config.inc.php');
require($admin_path.'/mysql.class.php');
require($admin_path.'/time.class.php');
//require($admin_path.'/_site.class.php');
include($admin_path.'/types.class.php');
$types = new Types();
include($admin_path.'/libchapters.class.php');
$libchapter = new LibChapters();

if(empty($lang)) $lang = 1;
$alang_dir = array('/rus','/www','/eng');
$lang_dir = $alang_dir[$lang];

	$page = empty($page)?1:(int)$page;
	$limit = empty($limit)?10:(int)$limit;

$_txt = array(
	'rus' => array('res'=>'Результат поиска','nocrit'=>'Не задан критерий поиска!','search'=>'ПОИСК','inbase'=>'в информационной базе','fas'=>'искать','innews'=>'в новостях'),
	'ukr' => array('res'=>'Результат пошуку','nocrit'=>'Не заданий критерій пошуку!','search'=>'ПОШУК','inbase'=>'в інформаційній базі','fas'=>'шукати','innews'=>'в новинах'),
	'eng' => array('res'=>'Search results','nocrit'=>'Need criteria of search!','search'=>'SEARCH','inbase'=>'in base','fas'=>'find','innews'=>'in news'),
);

echo replInc(str_replace('%DATE%',gmdate("D, d M Y H:i:s")." GMT",_geTempl('head','tpl',$lang_dir)));

if(!count($section)) $section = array(1);

if(!$start_date){
	$start_time=new real_time;
//	if($start_year)$start_time->year=$start_year; else $start_time->year = date('Y')-1;
	if($start_year)$start_time->year=$start_year; else $start_time->year = '2008';
	if($start_month)$start_time->month=$start_month; else $start_time->month = date('m');
	if($start_day)$start_time->day=$start_day; else $start_time->day = date('d');
	$start_time->correct_time();
	$start_date=$start_time->year."-".$start_time->month."-".$start_time->day." 00:00:00";
}
if(!$end_date){
	$end_time=new real_time;
	if($end_year)$end_time->year=$end_year;
	if($end_month)$end_time->month=$end_month;
	if($end_day)$end_time->day=$end_day;
	$end_time->correct_time();
	$end_date=$end_time->year."-".$end_time->month."-".$end_time->day." 23:59:59";
}
$search = strip_tags($_REQUEST['search']);	//XSS patch
$search = str_replace("%","/%",$search);  //  add all needed slashe
$search = str_replace("'","’",$search); //ukraine apostrophe 

//$_SERVER["REMOTE_ADDR"] = $_SERVER["HTTP_X_REAL_IP"];	//patch for Saddam perversion

if(!empty($search)||!empty($let)||!empty($aut)) {	
	list($html,$skoka,$navig) = _Site_search($search,$area,$let,$aut,$page,$limit);

	$my = new MySQL;
	$rem = (empty($_SERVER["REMOTE_ADDR"]))?"":$_SERVER["REMOTE_ADDR"];
	$ref = (empty($_SERVER["HTTP_REFERER"]))?"":$_SERVER["HTTP_REFERER"];
	$my->ExecQuery('INSERT INTO search_stat (data,mova,stroka,razdel,nachalo,konec,ip,referer) VALUES(now(),'.$lang.',"'.mysql_real_escape_string($search).'","'.@implode(',',$section).'","'.$start_date.'","'.$end_date.'","'.$rem.'","'.mysql_real_escape_string($ref).'")');
}else {
	$html .= "<br><font color=red>".$_txt[$lang]['nocrit']."</font><br><br>";
}

echo 
	replInc(
		str_replace('<?=SEARCH?>',$search?$search:($let?$let:$aut),
		str_replace('<?=SKOKA?>',(int)$skoka,
		str_replace('<?=START?>',(($page-1)*$limit)+1,
		str_replace('<?=ITEMS?>',$html,
		str_replace('<?=NAVIGATE?>',$navig,
		str_replace('матеріал',($aut?'автор':'матеріал'),
		str_replace('<?=KONCHALO?>',endec($skoka),
		_geTempl('searchlib','htm',$lang_dir)))))))));

echo replInc(_geTempl('foot','tpl',$lang_dir));

function _Site_search($search,$area,$let,$aut,$page,$limit){
   global $pak_text,$admin,$PHP_SELF,$lang,$total,$libchapter,$root_path,$lang_dir;

//$search = preg_replace("/\\$/sim","",$search);	//remove trailing slashes
$search=str_replace("_","\_",str_replace("%","\%",mysql_real_escape_string($search)));
	$page = empty($page)?1:(int)$page;
	$limit = empty($limit)?10:(int)$limit;

	$_tpl = _geTempl('searchlib','tpl',$lang_dir);

	$MySQL = new MySQL;
	$my = new MySQL;
	$amount = 0;
	//$search = stripslashes($search);	//what was this for?
	$aarea = array('title','author','content');
	if(!empty($let)) {
		$let = substr($let,0,1);
		$res = $MySQL->FetchObject("SELECT count(*) as skoka FROM library WHERE title LIKE '$let%'"); 
		$skoka = $res->skoka;
		$qu = "SELECT * FROM library WHERE title LIKE '$let%' ORDER BY title LIMIT ".(($page-1)*$limit).','.$limit;
	}elseif(!empty($aut)) {
		$aut = substr($aut,0,1);
		$res = $MySQL->FetchObject("SELECT count(*) as skoka FROM library WHERE author LIKE '% $aut%' GROUP BY author"); 
		//$skoka = $res->skoka;
		$skoka = $MySQL->NumRows();
		$qu = "SELECT * FROM library WHERE author LIKE '% $aut%' GROUP BY author ORDER BY author LIMIT ".(($page-1)*$limit).','.$limit;
	}elseif($area&&in_array($area,$aarea)) {
		$res = $MySQL->FetchObject("SELECT count(*) as skoka FROM library WHERE $area LIKE '%$search%'"); 
		$skoka = $res->skoka;
		$qu = "SELECT * FROM library WHERE $area LIKE '%$search%' ORDER BY title LIMIT ".(($page-1)*$limit).','.$limit;
	}else {
		$res = $MySQL->FetchObject("SELECT count(*) as skoka FROM library WHERE MATCH (title,anons,content,author) AGAINST ('$search'$inbool) $where AND date<NOW()"); 
//	echo $MySQL->Error();
		$skoka = $res->skoka;
		$qu = "SELECT m.*,ch.*,MATCH (title,anons,content,author) AGAINST ('$search'$inbool) as score FROM library m LEFT JOIN libchapters ch ON ch.id=m.chapter WHERE MATCH (title,anons,content,author) AGAINST ('$search'$inbool) $where AND date<NOW() ORDER BY title DESC LIMIT ".(($page-1)*$limit).','.$limit;
	}
		//echo "<!-- $qu -->";
	$MySQL->ExecQuery($qu); 
//	echo $MySQL->Error();
	if(!$MySQL->NumRows()) return false;

	while($res=$MySQL->FetchObject()){
			if($res->img) {
				if(file_exists($admin_path.'/library/imgthumb/'.$res->img)) {
					//$size = getimagesize($admin_path.$ipath);
					$_img = 
						str_replace('<?=IMAGE_NAME?>','/library/imgthumb/'.$res->img,
						str_replace('<?=IMAGE_SIZE?>','width="68"',
						str_replace('<?=IMAGE_ALT?>',strip_tags($res->foto_alt),
						str_replace('<?=IMAGE_CLASS?>','img',
						$_itpl))));
				}else {
					$_img = '';
				}
			}else {
				$_img = '';
			}
		if(empty($aut)) {
			$Search_result .= 
				str_replace('<?=ITEM_LINK?>','/library/'.strtolower(translIt($res->author)).'/'.strtolower(translIt($res->title)).'/',
				str_replace('<?=ITEM_TITLE?>',strip_tags($res->title)."<!-- $res->score -->",
				str_replace('<?=ITEM_ANONS?>',hiLi(strip_tags($res->anons.' '.$res->content),$search),
				str_replace('<?=ITEM_AUTHOR?>',$res->author,
				str_replace('<?=ITEM_AUTHOR_LINK?>','/library/'.strtolower(translIt($res->author)).'/',
				str_replace("<?=TYPE_DIR?>",$types->typetree[$res->type]->dir,
				str_replace("<?=TYPE_NAME?>",$types->typetree[$res->type]->name,
				$_tpl)))))));
		}else {
			$Search_result .= 
				str_replace('<?=ITEM_LINK?>','/library/'.strtolower(translIt($res->author)).'/',
				str_replace('<?=ITEM_TITLE?>',$res->author,
				str_replace('<?=ITEM_ANONS?>','',
				str_replace('<?=ITEM_AUTHOR?>','',
				str_replace('<?=ITEM_AUTHOR_LINK?>','',
				str_replace("<?=TYPE_DIR?>",'',
				str_replace("<?=TYPE_NAME?>",'',
				$_tpl)))))));
		}
	}
	if($skoka>$limit)	{
		$navig = navigate($skoka,$limit,$page,"/library/search/?search=".htmlspecialchars(stripslashes($search),ENT_QUOTES,'cp1251')."&area=$area&let=$let&aut=$aut&");
	}else $navig = '';
	return array($debug.$Search_result,$skoka,$navig);
}
function hiLi($where,$what) {
	if(!empty($what)&&strpos($where,$what)!==false) {
		$pp = strpos($where,$what);
		$start = $pp-150>0 ? $pp-150 : 0;
		$out = substr($where,$start,350);
		$out = truncate(strrev($out),300);
		$out = truncate(strrev($out),250);
		return str_replace($what,'<b style="color:#CC0066;">'.$what.'</b>',$out);
	}else return truncate(strip_tags($where),300);
}
?>