<?php
define('IN_SMT',true);
define('CURSCRIPT','search');
define('IN_MYMPS', true);

require_once dirname(__FILE__)."/include/global.php";
require_once dirname(__FILE__)."/data/config.php";
if($keywords != '' && strlen($keywords) < 2) write_msg('您输入的关键字太短了！关键字不能少于2个字节！');

$mymps_global['SiteStat'] = htmlspecialchars_decode($mymps_global['SiteStat']);
$mymps_global['SiteStat'] = str_replace('type=\'/javascript\'','type=\'text/javascript\'',$mymps_global['SiteStat']);

ifsiteopen();
require_once MYMPS_SMARTY."/include.php";
require_once MYMPS_DATA."/config.db.php";
require_once MYMPS_INC."/db.class.php";

$catid    = isset($catid) 	 ? intval($catid) 	 	 : '';
$areaid   = isset($areaid) 	 ? intval($areaid) 	 	 : '';
$posttime = isset($posttime) ? intval($posttime) 	 : '';
$tel	  = isset($tel)		 ? mhtmlspecialchars($tel)	 : '';

$keywords = trim(mhtmlspecialchars($_GET[keywords]));
$keywords = str_replace('?','',$keywords);
$keywords = isset($keywords) ? trim(preg_replace("/(\s+)/",' ',$keywords)) : '';
$mod = isset($mod)	 ? mhtmlspecialchars($mod) : '';

if($keywords == '请输入关键词或分类名') $keywords = $_GET['keywords'] = '';

!in_array($mod,array('information','store','news','group','coupon','goods')) && $mod = 'information';

@include MYMPS_DATA.'/caches/plugin.php';
$pluginsettings = $data;
unset($data);

$allowplugin = array();
if(is_array($pluginsettings)){
	foreach($pluginsettings as $k => $v){
		if($v['disable'] != 1){
			$allowplugin[$k]['flag'] = $v['flag'];
			$allowplugin[$k]['name'] = $v['name'];
		}
	}
}

$smarty->assign('allowplugin',$allowplugin);

$sql = $search = $where = $allow_identifier = '';
switch($mod){
	case 'information':
		$search['page_title'] = ($keywords != '' ? $keywords.' - ' : '').'信息搜索 - '.$mymps_global['SiteName'];
		if($keywords != '' || $tel != ''){
			require MYMPS_DATA."/info_posttime.php";
			
				if($catid != ''){
					$modid = $db -> getOne("SELECT modid FROM `{$db_mymps}category` WHERE catid = '$catid'");
					$allow_identifier = allow_identifier();
					if(is_array($allow_identifier = $allow_identifier[$modid]['identifier'])){
						$extra_in  = '';
						$extra_num = 0;
						$extra_uri = '';
						$extra_arg = array();
						$sql = "SELECT infoid,count(*) AS num FROM `{$db_mymps}info_extra` WHERE 0";
						foreach ($$_request as $key => $val){
							if(in_array($key,$allow_identifier) && !empty($$key)){
								//$val = intval($val);
								$extra_num++;
								$sql .= " OR (1 ";
								if(is_array($val)){
									$sql .= "AND name = '$key'";
									if(!empty($val['min'])){
										$val['min'] = intval($val['min']);
										$sql .= " AND value >= '" .$val['min']."'";
									}
									if(!empty($val['max'])){
										$val['max'] = intval($val['max']);
										$sql .= " AND value <= '" .$val['max']."'" ;
									}
								}else{
									$val = intval($val);
									$sql .= empty($val) ? "AND name = '$key'" : " AND name = '$key' AND value = '$val' ";
								}
								//$extra_uri .= "&amp;$key=$val";
								$extra_arg["$key"] = $val;
								$sql .= ')';
							}
						}
						
						if ($extra_num > 0){
							$sql .= " GROUP BY infoid HAVING num = '$extra_num'";
							$row = $db->getCol($sql);
							if (count($row)){
								$extra_in = " AND " . create_in($row, 'i.id');
							}else{
								$extra_in = " AND 0 ";
							}
						} else {
							$sql = '';
						}
					}
					$mymps_extra_model = mod_identifier();
					$smarty -> assign('extra_model',$mymps_extra_model[$modid]);
				}
				if(is_array($keyword = explode(' ',$keywords))){
					$or = '';
					$sqlkeywords = '';
					foreach($keyword as $k => $v){
						$sqlkeywords .= " $or i.title LIKE '%".$v."%' OR i.content LIKE '%".$v."%' OR c.catname LIKE '%".$v."%'";
						$or = 'OR';
					}
					$where .= " AND ($sqlkeywords)";
				}
				$where .= $areaid != ''  ? " AND i.areaid = '$areaid'" : "";
				$where .= $tel != ''  ? " AND i.tel LIKE '%".$tel."%'" : "";
				$where .= $catid != ''  ? " AND ".get_children($catid,'i.catid') : "";
				$where .= $posttime != '' ? " AND i.begintime >= (".$timestamp."-".$posttime."*3600*24)" : "";
				$where .= " AND i.info_level > '0'";
				
				$search['rows_num'] = $rows_num = $db -> getOne("SELECT COUNT(i.id) FROM `{$db_mymps}information` AS i LEFT JOIN `{$db_mymps}category` AS c ON i.catid = c.catid WHERE 1 {$where} {$extra_in}");
				$param = $catid != '' && is_array($allow_identifier) ? setParam(array_merge(array('mod','keywords','catid','areaid','posttime','tel'),$allow_identifier)) : setParam(array('mod','keywords','catid','areaid','posttime','tel'));
	
				$searchresult = page1("SELECT i.id,i.html_path,i.begintime,i.title,i.content,i.ismember,i.contact_who,i.begintime,i.catid,c.catname,i.catid,c.dir_typename,c.html_dir FROM `{$db_mymps}information` AS i LEFT JOIN `{$db_mymps}category` AS c ON i.catid = c.catid WHERE 1 {$where} {$extra_in} ORDER BY i.id DESC");
				foreach($searchresult as $k => $val){
					$result['id']			= $val['id'];
					$result['uri'] 			= Rewrite('info',array('id'=>$val['id'],'catid'=>$val['catid'],'html_path'=>$val['html_path']));
					$result['begintime']	= $val['begintime'];
					$result['title']		= HighLight($val['title'],$keywords);
					$result['content']		= HighLight(substring(clear_html($val['content']),0,220),$keywords);
					$result['poster']		= $val['ismember'] == 1 ? '<a target="black" href='.Rewrite('space',array("userid"=>$val["userid"])).$val["userid"].'</a>' : $val['contact_who'] ? $val['contact_who'] : '游客';
					$result['catname']		= HighLight($val['catname'],$keywords);
					$result['caturi']		= Rewrite('category',array('catid'=>$val['catid'],'dir_typename'=>$val['dir_typename'],'html_dir'=>$val['html_dir']));
					$search['result'][$val['id']] = $result;
				}
				$search['pagination'] = page2();
				if($search['result'] && $catid != '' && is_array($allow_identifier)){
					$ids = NULL;
					foreach($search['result'] as $info){
						$ids .= $info['id'].',';
					}
					$infoid = substr($ids,0,-1);
					$sql = "select c.infoid,c.name,c.value,d.optionid,d.title,d.type,d.rules from {$db_mymps}info_extra as c left join {$db_mymps}info_typeoptions as d on d.identifier = c.name WHERE c.infoid IN ($infoid) AND d.search = 'on' AND d.available = 'on'";
					$res = $db->query($sql);
					while($row=$db->fetchrow($res)){
						$optionarray = get_extraoption_value(array('type'=>$row['type'],'rules'=>$row['rules']),$row['value']);
						$arr[$row['infoid']][$row['optionid']]['title'] = $row['title'];
						$arr[$row['infoid']][$row['optionid']]['value'] = $optionarray['value'];
					}
					foreach($search['result'] as $key => $info){
						$search['result'][$key]['extra'] = is_array($arr[$key]) ? $arr[$key] : array();
					}
				}
	
			$smarty -> assign('posttime_select',GetInfoPostTime($posttime));
			$smarty -> assign('catoption',get_categories_tree(0,'category'));
			$smarty -> assign('area_list',cat_list('area',0,0,false,1));
		}
	break;
	case 'store':
		$search['page_title'] = ($keywords != '' ? $keywords.' - ' : '').'商家搜索 - '.$mymps_global['SiteName'];
		if($keywords != ''){
			if(is_array($keyword = explode(' ',$keywords))){
				$or = '';
				$sqlkeywords = '';
				foreach($keyword as $k => $v){
					$sqlkeywords .= " $or a.tname LIKE '%".$v."%' OR a.introduce LIKE '%".$v."%' OR a.userid LIKE '%".$v."%'";
					$or = 'OR';
				}
				$where .= " AND ($sqlkeywords)";
			}
			$where 	.= !empty($catid) 	? " AND b.catid IN(".get_corp_children($catid).") "  : "";
			$where 	.= !empty($areaid) 	? " AND a.areaid = '$areaid' "	: "";
			$where 	.= " AND a.levelid > '1' AND a.if_corp = '1'";
			$sql = empty($catid) ? "SELECT a.* FROM `{$db_mymps}member` AS a WHERE 1 {$where} ORDER BY a.jointime DESC" : "SELECT a.* FROM `{$db_mymps}member` AS a LEFT JOIN `{$db_mymps}member_category` AS b ON a.userid = b.userid WHERE 1 {$where} ORDER BY a.jointime DESC";
			$count_sql	= empty($catid) ? "SELECT COUNT(a.id) FROM `{$db_mymps}member` AS a WHERE 1 {$where}" : "SELECT COUNT(b.id) FROM `{$db_mymps}member` AS a LEFT JOIN {$db_mymps}member_category AS b ON a.userid = b.userid WHERE 1 $where";
			$search['rows_num']	=	$rows_num 	= $db -> getOne($count_sql);
			$param = setParam(array('mod','catid','areaid','keywords'));
			if(is_array($res = page1($sql))){
				foreach($res as $key => $val){
					$arr['userid']		= $val['userid'];
					$arr['tel']			= $val['tel'] ? $val['tel'] : '尚未填写电话信息';
					$arr['address']		= $val['address'] ? $val['address'] : '尚未填写地址信息';
					$arr['tname']		= $val['tname'] ? $val['tname'] : $val['userid'];
					$arr['prelogo']		= $val['prelogo'] ? $val['prelogo'] : '/images/nophoto.jpg';
					$arr['tname']		= HighLight($val['tname'] ? $val['tname'] : $val['userid'],$keyword ? $keyword : $keywords);
					$arr['uri'] 		= Rewrite('store',array('uid'=>$val['id']));
					$arr['uri_aboutus'] = Rewrite('store',array('uid'=>$val['id'],'part'=>'about'));
					$arr['uri_comment'] = Rewrite('store',array('uid'=>$val['id'],'part'=>'comment'));
					$arr['uri_album'] 	= Rewrite('store',array('uid'=>$val['id'],'part'=>'album'));
					$search['result'][]	= $arr;
				}
			}
			$search['pagination']	= page2();
		}
		
		$smarty -> assign('search',$search);
		$smarty -> assign('catoption',get_corp_tree(0,'corp'));
		$smarty -> assign('area_list',cat_list('area',0,0,false,1));
	break;
	
	case 'news':
		!ifplugin('news') && exit('管理员已禁用或未安装新闻插件...');
	
		$smarty -> assign('catoption',cat_list('channel',0,0,false,1));
		if($keywords != ''){
			if(is_array($keyword = explode(' ',$keywords))){
				$or = '';
				$sqlkeywords = '';
				foreach($keyword as $k => $v){
					$sqlkeywords .= " $or n.title LIKE '%".$v."%' OR n.content LIKE '%".$v."%'";
					$or = 'OR';
				}
				$where .= " AND ($sqlkeywords)";
			}
			$where .= !empty($catid)  ? " AND ".get_cat_children($catid,'channel','n.catid') : "";
			$sql = "SELECT n.*,c.catname,c.html_dir FROM `{$db_mymps}news` AS n LEFT JOIN `{$db_mymps}channel` AS c ON n.catid = c.catid WHERE 1 $where";
			$search['rows_num'] = $rows_num = $db -> getOne("SELECT COUNT(n.id) FROM `{$db_mymps}news` AS n WHERE 1 $where");
			$param = setParam(array('mod','catid','keywords'));
			$searchresult = page1($sql);
			foreach($searchresult as $k => $val){
				$result['id']			= $val['id'];
				$result['hit']			= $val['hit'];
				$result['uri'] 			= Rewrite('news',array('id'=>$val['id'],'html_path'=>$val['html_path']));
				$result['begintime']	= $val['begintime'];
				$result['title']		= HighLight($val['title'],$keyword ? $keyword : $keywords);
				$result['content']		= HighLight(substring(clear_html($val['content']),0,300),$keyword ? $keyword : $keywords);
				$result['catname']		= $val['catname'];
				$result['caturi']		= Rewrite('news',array('catid'=>$val['catid'],'html_dir'=>$val['html_dir']));
				$search['result'][] 	= $result;
			}
			$search['pagination'] = page2();
		}
		$search['page_title'] = ($keywords != '' ? $keywords.' - ' : '').'网站新闻搜索 - '.$mymps_global['SiteName'];
	break;
	
	case 'group':
		require_once MYMPS_ROOT.'/plugin/group/include/functions.php';
		
		$group_class = get_group_class();
		$area_class = cat_list('area',0,0,false,1);
		$smarty -> assign('catoption',$group_class);
		$smarty -> assign('area_list',$area_class);
		
		require_once MYMPS_DATA.'/grouplevel.inc.php';
		$smarty -> assign('glevel',$glevel);
		unset($area_class,$glevel);
		
		if($keywords != ''){
		
			$where = "WHERE glevel > '0'";
			
			if(is_array($keyword = explode(' ',$keywords))){
				$or = '';
				$sqlkeywords = '';
				foreach($keyword as $k => $v){
					$sqlkeywords .= " $or gname LIKE '%".$v."%'";
					$or = 'OR';
				}
				$where .= " AND ($sqlkeywords)";
			}		
		
			if($cate_id) $where .= " AND cate_id = '$cate_id'";
			if($areaid) $where .= " AND areaid = '$areaid'";
			
			$search['rows_num']	= $rows_num = $db -> getOne("SELECT COUNT(groupid) FROM `{$db_mymps}group` $where");
			$param = setParam(array('mod','cate_id','areaid','keywords'));
			$group = page1("SELECT * FROM `{$db_mymps}group` $where ORDER BY displayorder DESC");
			foreach($group as $k => $v){
				$result['groupid'] = $v['groupid'];
				$result['gname'] = $v['gname'];
				$result['des'] = clear_html($v['des']);
				$result['enddate'] = $v['enddate'];
				$result['meetdate'] = $v['meetdate'];
				$result['gaddress'] = $v['gaddress'];
				$result['glevel'] = $v['glevel'];
				$result['signintotal'] = $v['signintotal'];
				$result['commenturl'] = $v['commenturl'];
				$result['pre_picture'] = $v['pre_picture'];
				$result['uri'] = plugin_url('group',array('id'=>$v['groupid']));
				$search['result'][] 	= $result;
			}
			$search['pagination'] = page2();
		}
			
		$search['page_title'] = ($keywords != '' ? $keywords.' - ' : '').'团购活动搜索 - '.$mymps_global['SiteName'];
	
	break;
	
	case 'coupon':
		require_once MYMPS_ROOT.'/plugin/coupon/include/functions.php';
		
		$coupon_class = get_coupon_class();
		$area_class = cat_list('area',0,0,false,1);
		$smarty -> assign('catoption',$coupon_class);
		$smarty -> assign('area_list',$area_class);
		
		if($keywords != ''){
				
			$where = "WHERE status = '1' AND grade > '0'";
			
			if(is_array($keyword = explode(' ',$keywords))){
				$or = '';
				$sqlkeywords = '';
				foreach($keyword as $k => $v){
					$sqlkeywords .= " $or title LIKE '%".$v."%'";
					$or = 'OR';
				}
				$where .= " AND ($sqlkeywords)";
			}		
		
			if($cate_id) $where .= " AND cate_id = '$cate_id'";
			if($areaid) $where .= " AND areaid = '$areaid'";
			
			$search['rows_num']	= $rows_num = $db->getOne("SELECT count(id) FROM {$db_mymps}coupon $where");
			$param = setParam(array('mod','cate_id','areaid'));
			$coupon = page1("SELECT * FROM `{$db_mymps}coupon` $where ORDER BY begindate DESC");
			foreach($coupon as $k => $v){
				$result['id'] = $v['id'];
				$result['title'] = $v['title'];
				$result['des'] = $v['des'];
				$result['enddate'] = $v['enddate'];
				$result['begindate'] = $v['begindate'];
				$result['prints'] = $v['prints'];
				$result['pre_picture'] = $v['pre_picture'];
				$result['sup'] = $v['sup'];
				$result['uri'] = plugin_url('coupon',array('id'=>$v['id']));
				$search['result'][] 	= $result;
			}
			$search['pagination'] = page2();
		}
		
		$search['page_title'] = ($keywords != '' ? $keywords.' - ' : '').'优惠券搜索 - '.$mymps_global['SiteName'];
		
	break;
	
	case 'goods':
		require_once MYMPS_ROOT.'/plugin/goods/include/functions.php';
		
		$goods_class = goods_category_tree(0);
		$smarty -> assign('catoption',$goods_class);
		
		if($keywords != ''){
				
			$where = "WHERE onsale = '1'";
			
			if(is_array($keyword = explode(' ',$keywords))){
				$or = '';
				$sqlkeywords = '';
				foreach($keyword as $k => $v){
					$sqlkeywords .= " $or goodsname LIKE '%".$v."%'";
					$or = 'OR';
				}
				$where .= " AND ($sqlkeywords)";
			}		
		
			if($catid) $where .= " AND catid IN (".get_goods_children($catid).")";
			
			$search['rows_num'] = $rows_num = $db -> getOne("SELECT COUNT(goodsid) FROM `{$db_mymps}goods` $where");
			$param = setParam(array('mod','cate_id'));
			$goods = page1("SELECT * FROM `{$db_mymps}goods` $where ORDER BY dateline DESC",16);
			foreach($goods as $k => $v){
				$result['goodsid'] = $v['goodsid'];
				$result['goodsname'] = $v['goodsname'];
				$result['nowprice'] = $v['nowprice'];
				$result['pre_picture'] = $v['pre_picture'] ? $v['pre_picture'] : $mymps_global['SiteUrl'].'/images/nophoto.gif';
				$result['uri'] = plugin_url('goods',array('id'=>$v['goodsid']));
				$search['result'][] = $result;
			}
			$search['pagination'] = page2();
		}
		
		$search['page_title'] = ($keywords != '' ? $keywords.' - ' : '').'商品搜索 - '.$mymps_global['SiteName'];
		
	break;
}
$about = array();
$about['aboutus_uri']	= Rewrite('about',array('part'=>'aboutus','html_path'=>'/aboutus/'));
$about['faq_uri']		= Rewrite('about',array('part'=>'faq','html_path'=>'/faq/'));
$about['friendlink_uri']= Rewrite('about',array('part'=>'friendlink','html_path'=>'/friendlink/'));
$about['announce_uri']	= Rewrite('about',array('part'=>'announce','html_path'=>'/announce/'));
$about['sitemap_uri']	= Rewrite('about',array('part'=>'sitemap','html_path'=>'/sitemap.html'));

$mtime = explode(' ', microtime());
$totaltime = number_format(($mtime[1] + $mtime[0] - $mymps_starttime), 6);
$sitedebug = 'Processed in '.$totaltime.' second(s) , '.$db->query_num.' queries';
$search['keywords'] = $keywords;

$smarty -> assign('about',$about);
$smarty -> assign("MPS_VERSION",MPS_VERSION);
$smarty -> assign("MPS_SOFTNAME",MPS_SOFTNAME);
$smarty -> assign("config",$mymps_global);
$smarty -> assign('search',$search);
$smarty -> assign('sitedebug',$sitedebug);
$smarty -> assign('mod',$mod);
$smarty -> display(($keywords || $tel) ? MYMPS_ROOT.'/template/search/'.CURSCRIPT.'_'.$mod.'.html' : MYMPS_ROOT.'/template/search/search_index.html');
is_object($db) && $db -> Close();
unset($db,$mymps_global,$search,$about,$searchresult,$result,$rows_num,$allow_identifier,$keywords,$param,$sqlkeywords,$or,$smarty,$totaltime,$sitedebug,$mtime);
?>