<?php
	define('T_ROOT', str_replace("\\", '/',substr(dirname(__FILE__),0,-6)));
	include T_ROOT.'include/common.inc.php';
	$cururl=getcururl();
	$starttime=getMicrotime();
	if(file_exists(DIRCMS_ROOT.'data/cache_page/'.md5($cururl).'.php') && SEARCHTTL && (TIME-@filemtime(DIRCMS_ROOT.'data/cache_page/'.md5($cururl).'.php')<SEARCHTTL))
	{
		include(DIRCMS_ROOT.'data/cache_page/'.md5($cururl).'.php');
		exit();
	}
	$dir_catid=0;
	require_once(DIRCMS_ROOT.'include/list.class.php');
	include DIRCMS_ROOT.'include/wordsplit.class.php';
	$k=htmlspecialchars(stripslashes(trim($k)));
	$type=trim($type);
	if($k || in_array($type,array('content','member')))
	{	
		$type=in_array($type,array('content','member'))?$type:'content';
		switch($type)
		{
			case 'content':
				$datafirst=$searchfields=array();
				$skey=array();
				$where=1;
				$template='search_result';
				if(isset($catid) && intval($catid))
				{
					$dir_catid=$catid=intval($catid);
					$dir_search=$searchoption=searchoption($catid);
					$dir_postion=$position=get_pos($catid);
					$dir_catname=getCategoryname($dir_catid,0);
					$r=cache_read('category'.$catid.'.cache.php',DIRCMS_ROOT.'data/cache_category/');
					if(!$r)showmsg('搜索参数不足!',$DIRCMS['site_url']);
					$modelid=$r['modelid'];
					$r=cache_read('cache_model'.$modelid.'.fields.cache.php',DIRCMS_ROOT.'data/cache_model/');
					if(!$r)showmsg('搜索参数不足!',$DIRCMS['site_url']);
					if($r)foreach($r as $_r)
					{
						if($_r['issearch'])
						{
							$searchfields[$_r['searchbyvalue']]=$_r;
							$skey[$_r['searchbyvalue']]=$_r['name'];
						}
					}

					$r=cache_read('cache_model'.$modelid.'.cache.php',DIRCMS_ROOT.'data/cache_model/');
					$template=$r['stemplate'];

					$datafirst=array();
				}
				//echo 'here';
				if($searchfields)
				{
					foreach($searchfields as $key => $value)
					{
						if(!strpos($key,'-'))
						{
							if(isset(${$key}) && ${$key})
							{
								$safestr=mysql_escape_string(${$key});
								if($safestr)
								{
									switch($value['searchby'])
									{
										case 'eq':
											$where.=' AND '.$skey[$key].' =\''.$safestr.'\'';
											break;
										case 'lt':
											if(!is_numeric($safestr))showmsg($value['fieldname'].'必须为数字!');
											$where.=' AND '.$skey[$key].' <'.intval($safestr);
											break;
										case 'le':
											if(!is_numeric($safestr))showmsg($value['fieldname'].'必须为数字!');
											$where.=' AND '.$skey[$key].' <='.intval($safestr);
											break;
										case 'gt':
											if(!is_numeric($safestr))showmsg($value['fieldname'].'必须为数字!');
											$where.=' AND '.$skey[$key].' >'.intval($safestr);
											break;
										case 'ge':	
											if(!is_numeric($safestr))showmsg($value['fieldname'].'必须为数字!');
											$where.=' AND '.$skey[$key].' >='.intval($safestr);
											break;
										case 'like':
											$where.=' AND '.$skey[$key].' like \'%'.$safestr.'%\'';
											break;	
									}
								}
							}
						}
						else
						{
							$key=explode('-',$key);
							if(isset(${$key[0]}) && (${$key[0]} || ${$key[0]}==0))
							{
								if(!is_numeric(${$key[0]}) || !is_numeric(${$key[1]}) || (intval(${$key[1]})<intval(${$key[0]})))showmsg('请输入正确区间的'.$value['fieldname'].'值!');	
								$where.=' AND '.$value['name'].'<='.intval(${$key[1]}).' AND '.$value['name'].'>='.intval(${$key[0]});
							}
						}
					}
				}
			//	echo $where;
				if($r['name'])$datafirst=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE.$r['name']." WHERE ".$where." ORDER BY contentid DESC",'contentid');

				if($k)
				{
					if(strlen($k)<2)showmsg('搜索关键字不能少于2个字符!',$DIRCMS['site_url']);	
					if(strlen($k)>90)showmsg('搜索关键字中文不能大于30个字符!',$DIRCMS['site_url']);
					$splitwords=new wordsplit(DIRCMS_ROOT.'include/DirCMSChineseDictionary.txt');
					$k=iconv("GBK", "UTF-8", $k);
					$tkey=$splitwords->splitWords($k);
					$k=iconv("UTF-8", "GBK", $k);
					$_tkey=array();
					foreach($tkey as $_k => $_v)
					{
						$_tkey[$_k]=iconv("UTF-8", "GBK", $_v);;
					}
					$keywords=implode(' ',$_tkey);
					$tkey=strtoZoneCode($keywords);
					$r=cache_read('finalcatid.cache.php',DIRCMS_ROOT.'data/cache_category/');
					
					if(isset($catid) && intval($catid))
					{
						if(in_array($catid,$r))
						{
							$data=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE."content WHERE catid={$catid} AND MATCH(tags) AGAINST ('".$tkey."' IN BOOLEAN MODE) ORDER BY id DESC");
						}
						else
						{
							
							$t_catid[]=implode(',',get_childrencatid($catid));
							$catid=array_unique(explode(',',implode(',',$t_catid)));
							$catid=$catid?$catid:array(0);
							$data=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE."content WHERE catid IN('".implode(',',$catid)."') AND MATCH(tags) AGAINST ('".$tkey."' IN BOOLEAN MODE) ORDER BY id DESC");
						}
					}
					else
					{
						$data=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE."content WHERE MATCH(tags) AGAINST ('".$tkey."' IN BOOLEAN MODE) ORDER BY id DESC");
					}
					$data=$where!==1?array_intersect_assoc($data,$datafirst):$data;					
				}
				else
				{
					$r=cache_read('finalcatid.cache.php',DIRCMS_ROOT.'data/cache_category/');
					if(in_array($catid,$r))
					{
						if(isset($areaid)&& intval($areaid))
						{
							$data=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE."content WHERE areaid={$areaid} AND catid={$catid} ORDER BY id DESC");
						}
						else
						{
							$data=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE."content WHERE catid={$catid} ORDER BY id DESC");
						}
					}
					else
					{
						$t_catid[]=implode(',',get_childrencatid($catid));
						$_catid=array_unique(explode(',',implode(',',$t_catid)));
						$_catid=array_intersect($_catid,$r);
						$_catid=$_catid?$_catid:array(0);

						if(isset($areaid)&& intval($areaid))
						{
							$data=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE."content WHERE areaid={$areaid} AND catid IN(".implode(',',$_catid).") ORDER BY id DESC");
						}
						else
						{
							$data=$db->fetch_all_withkey("SELECT * FROM ".DB_PRE."content WHERE catid IN(".implode(',',$_catid).") ORDER BY id DESC");
						}
					}	
					//print_r($data);
					$t=array();
					foreach($data as $_k=>$_v)
					{
						foreach($datafirst as $k=>$v)
						{
							if($k==$_k)$t[$k]=array_merge($_v,$v);
						}
					}
					$data=$t;
				}
				break;
			case 'member':
				$modelid=intval($modelid)?intval($modelid):2;

				$r=cache_read('cache_membermodel'.$modelid.'.cache.php',DIRCMS_ROOT.'data/cache_model/');
				if(!$r)showmsg('搜索参数不足!',$DIRCMS['site_url']);
				$template=$r['stemplate'];
				$where='a.iscompmayed=1';
				$where.=isset($typeid)&& intval($typeid)?' AND a.typeid='.intval($typeid):'';
				$where.=isset($areaid)&& intval($areaid)?' AND a.areaid='.intval($areaid):'';
				$data=$db->fetch_all_withkey("SELECT a.*,b.* FROM ".DB_PRE."member a LEFT JOIN ".DB_PRE.$r['name']." b ON a.id=b.userid WHERE ".$where." AND b.companyname LIKE '%{$k}%'");
				$dir_postion=$position='<a href="'.$DIRCMS['site_url'].'">首页</a> > <a href="'.$DIRCMS['site_url'].'company/index.php">商家黄页</a> > 商家搜索结果';
				break;
		}
	}
	else
	{
		$template='search_index';
		$head['title']='搜索首页-'.$DIRCMS['site_name'];		
	}
	$page=intval($page);
	$runtime=round((getMicrotime()-$starttime)/10,6);
	$count=sizeof($data);
	$pagecount=max(ceil($count/PAGESIZE),1);
	$page=max(min($page,$pagecount),1);
	$data=array_slice($data,($page-1)*PAGESIZE,PAGESIZE);
	$_url=parse_url($cururl);
	$_query=preg_replace('/&page=[0-9]+/i','',$_url['query']);
	$firstpage=$_url['path'].'?'.$_query.'&page=1';
	$frontpage=$_url['path'].'?'.$_query.'&page='.max($page-1,1);
	$nextpage=$_url['path'].'?'.$_query.'&page='.min($page+1,$pagecount);
	$lastpage=$_url['path'].'?'.$_query.'&page='.$pagecount;
	$sdir_page=$pagestring='当前'.$page.'/'.$pagecount.'页 <a href="'.$firstpage.'">首页</a> <a href="'.$frontpage.'">上一页</a> <a href="'.$nextpage.'">下一页</a> <a href="'.$lastpage.'">尾页</a>';
	$head['title']=$head['title']?$head['title']:'搜索结果';
	$head['keywords']=$DIRCMS['keywords'];
	$head['description']=$DIRCMS['description'];
	if(SEARCHTTL)ob_start();

	$keywords_rep=array();
	$colorreg=explode(" ",$keywords);
	foreach($colorreg as $v)
	{
		$keywords_rep[]='<font color="#ff0000">'.trim($v).'</font>';
	}
	
	include template($template);
	if(SEARCHTTL && (TIME-@filemtime(DIRCMS_ROOT.'data/cache_page/'.md5($cururl).'.php')>SEARCHTTL))
	{
		$pagecache=ob_get_contents();
		ob_end_clean();
		file_put_contents(DIRCMS_ROOT.'data/cache_page/'.md5($cururl).'.php',$pagecache);
		exit($pagecache);
	}
?>