<?php

/**
* 搜索
* 2007-11-9
* bailing
*
*/

//---------------------------------------------------------------------------------
//require_once("softInc/timer.php");$t = new timer(0);$t->b("开始");
//require_once( "softInc/sysFunc.php" );
//$REQUEST_TIME = time()."\t".rand(10000,99999);
include_once( "config.inc.php" );
function checkReferer()
{
	//if($_GET['oldso']!='')return true;
	$ref = $_SERVER['HTTP_REFERER'];
    if( strpos($ref,"wanyx.com") )
	{
		if($_GET['oldso']!='')return true;
	}
	return false;
}

function SearchCount($sword,$state)
{
	//state  搜到为1 未0
	global $DB;
	$time = time();
	$addTime = date('Y-m-d',$time);
	$month = substr($addTime,0,strlen($addTime)-3);
	$month = str_replace('-','',$month);

	$sql="insert into tab_seac_tmp ( sword,`addTime` , month , state )values('".$sword."','".$addTime."','$month','$state')";
	$DB->query($sql);
	return;
}
function checkDDOS()
{
	$noCheck = checkReferer();
	if($noCheck)return;

	global $DB;
	$time = time();
	//header("Time: $time");
	$ip = $_SERVER['REMOTE_ADDR'];
	$php_self = $_SERVER['PHP_SELF'];
	$sql="select `accessTime` from tab_accessIp WHERE ip='$ip' AND url='".$php_self."'";
	$lastTime = $DB->loadResult($sql);
	//header("lastTime: $lastTime");
	//echo $sql;
	//header("q: $sql");
	//die;
	if(!$lastTime)
	{
		$sql="insert into tab_accessIp( `accessTime` , ip , url )values('$time','$ip','$php_self')";
		$DB->query($sql);
		$ok = mysql_affected_rows();
		return;
	}

	if( $lastTime+2>$time )
	{
		//die;
		$DB->close();
		die("<script>function r(){location.reload(true)}setTimeout(r,2000);</script>正在搜索中,请等待2秒<!-- $lastTime $time-->");
	}
	else
	{
		$sql="Update tab_accessIp set `accessTime` = '$time' where ip='$ip' AND url='".$php_self."'";
		$DB->query($sql);
	}
	//die;
}
unset($_GET['x']);
unset($_GET['y']);
$force = $_GET['f'];
unset($_GET['f']);

//ａｂｃｄｅｆｇｈｉｊｋｌｍｎｏｐｑｒｓｔｕｖｗｘｙｚ１２３４５６７８９０／＼＇；．，ＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ

$_GET['so'] =  str_replace("请输入游戏关键字","",$_GET['so']);
$searchType = $_GET['searchType'];
$sojieque = $_GET['so'] ;
$_GET['so'] = strtolower( $_GET['so'] );
$trim = " \t\n\r\0\x0B*&^%$#@!~`)(-.=[]{},/\\'\"<>";
$so = trim($_GET['so'] , $trim );
$oldso = trim($_GET['oldso'] , $trim );
$sid = intval( $_GET['sid'] );
$ob = $_GET['ob'];
$ow = $_GET['ow'];

$smarty->assign( "ob" , $ob );
$smarty->assign( "ow" , $ow );

if ($ob == '')
{
    $ob ='hit';
}
if ($ow == 'pj')
{
    $ow == 'pj';
}
elseif ($ow == 'xiazai') {
    $ow1 = ' AND zgssid = 0 AND bdid = 0 ';
}
elseif ($ow == 'zixun') {
    $ow1 = ' AND zgssid = 1 ';
}
elseif ($ow == 'gl') {
    $ow1 = ' AND zgssid = 3 ';
}
elseif ($ow == 'pic') {
    $ow1 = ' AND zgssid in (4,5,6) ';
}
elseif ($ow == 'bd') {
    $ow1 = ' AND bdid !=0 ';
}

$so = str_replace("("," ",$so);
$so = str_replace(")"," ",$so);

if(substr($so,-4)=="下载" && strlen($so)>4 )
{
    $so =  str_replace("下载","",$so);
}


if(strlen($so)<1 )
	sysErrorShow("您要搜索的关键字不为空或长度不能小于1个字节\\n如下字符将被过滤\\n\'.*&^%$#@!~`)(-+.=[]{}\\\<>,.\\\"" ,$_SERVER['HTTP_REFERER']);

//初始化页面参数
if(isset($_GET['p']) and is_numeric($_GET['p']))$p = $_GET['p'];
else $p = 1;

$cacheNow = true;
$nowTime = time();

if (!get_magic_quotes_gpc())
{
	if($_GET)
	{
		foreach( $_GET as $getkey=>$getvalue)
		{
			$_GET[$getkey] = addslashes($getvalue);
		}
	}
}

//搜索关键词分词
$so = trim(preg_replace("/[ ]{1,}/"," ",$so));
$keyArray = explode(" ",strtolower($so));	//关键词数组
$keyNum = count($keyArray);
$sField = "*";
$sql = "SELECT ".$sField." FROM `tab_search` ";
$mainWord = $keyArray[0];


//普通搜索
if($keyNum>1)
{
	//require_once("softInc/sysFunc.php");
	$where .=" WHERE published = 1 AND (title like '%".$mainWord."%' or dict like '%".$mainWord."%' )".$ow1;
}
else
{
	$where .=" WHERE published = 1 AND (title like '%".$mainWord."%' or dict like '%".$mainWord."%' )".$ow1;
}
//include_once( "search_advanced_inc.php" );
//$where = " WHERE ( MATCH (`content`) AGAINST ('$so') ";

define("MASTER_ONLY",0);
include_once($_INC_PATH."connectDb.inc.php");
//-----------------------------------------------------------------------
$pageNum = 20676524;	//每页记录数20676524
$needSearchNum = 2; //小于此记录数，则需搜介绍.
$limitstart = ($p-1)*$pageNum;
$sql .= $where . "  order by zgssid ASC ,".$ob.",tDown DESC Limit $limitstart , $pageNum";//	echo '<!--'.$sql.'-->';
$sql2 .= $where2 . " Limit $limitstart , ".($pageNum-$needSearchNum)." ";	//echo $sql2;
$totalSql = "SELECT count(*) from `tab_search` $where"; //echo $totalSql;

$tsql = "SELECT zgssid,bdid from `tab_search` WHERE published = 1 AND title like '%".$mainWord."%' or dict like '%".$mainWord."%'";
$DB->setQuery($tsql);
$trows = $DB->loadList( "" , "assoc" );
$alltotal =  count ($trows);
foreach( $trows as $trow)
{
	if ($trow['zgssid'] == 0 && $trow['bdid'] == 0)
	{
	    $xz[]=$trow;
	}
	if ($trow['zgssid'] == 1)
	{
	    $zx[]=$trow;
	}
	if ($trow['zgssid'] == 3)
	{
	    $gl[]=$trow;
	}
	if ($trow['zgssid'] == 4 ||$trow['zgssid'] == 5 ||$trow['zgssid'] == 6 )
	{
	    $pic[]=$trow;
	}
	if ($trow['bdid'] != 0)
	{
	    $bd[]=$trow;
	}
}
$alltotal =  count ($trows);
$xztotal = count ($xz);
$zxtotal = count ($zx);
$gltotal = count ($gl);
$pictotal = count ($pic);
$bdtotal = count ($bd);
$smarty->assign("page",'search');
$smarty->assign( "alltotal" , $alltotal );
$smarty->assign( "xztotal" , $xztotal );
$smarty->assign( "zxtotal" , $zxtotal );
$smarty->assign( "gltotal" , $gltotal );
$smarty->assign( "pictotal" , $pictotal );
$smarty->assign( "bdtotal" , $bdtotal );

//echo "<!--". $sql . "-->";
//$t->b("开始链接数据库并执行统计");

//记录搜索数据
if ($_GET['seacount'] == 'seacount')
{

	if (strlen($so)>2)
	{
		$total = $alltotal > 0 ? 1:0;
		//SearchCount($so,$total);
	}
}

//检察缓存文件结构
$caeTime = 286400;
$caePage = 2;
$fileMd5 = md5( implode( ";" , $_GET ) );
$caePath = "./cache/search/".$p."/".substr($fileMd5,0,1);
$caeFile = $caePath."/".$fileMd5.".dt";
if($p<=$caePage )
{
	if($force!=1)
	{
		if(@filemtime($caeFile)>($nowTime-$caeTime))
		{
			echo file_get_contents($caeFile);
			echo "<!-- cache... -->";
			die;
		}
	}
}
else
{
	$cacheNow = false;
}

//checkDDOS();
$total = $DB->loadResult($totalSql);
//$t->b("sql执行开始");
if($total<=0)
{
	//智能纠错
	unset($info);
	$dsql = "SELECT debugKey FROM `tab_debuglist` WHERE sKey = '".$so."'";
	$debugKey = $DB->loadResult($dsql); //echo $dsql;die;
	if($debugKey)
	{
		header("location: /search.php?so=".$debugKey."&oldso=".$so."&ob=".$ob."&ow=".$ow );
		die;
	}
	else
	{
		//errorCorrect($so);
		$oldso	= $_GET['oldso'];
		if($oldso)
			$debugKey = $oldso;
		else
			$debugKey = $so;
		$vArray = array(
		"debugKey" => $debugKey ,
		"addTime" => $nowTime ,
		"month" => date("ym",$nowTime),
		);
		$DB->insert( $vArray , $db_SeaKeydebug );
		$cacheNow = true;
	}
}
elseif ( $total<$needSearchNum )
{//判断是否要搜介绍
	$DB->setQuery($sql);
	$rows = $DB->loadList( "" , "assoc" );
	if( $where2 )
	{
		$DB->setQuery($sql2);
		$rows2 = $DB->loadList( "" , "assoc" );	//echo $sql2;
		if( $rows2 && $rows )
			$rows = array_merge( $rows , $rows2 );
		elseif( $rows2 )
			$rows = $rows2;
		//$t->b("sql2执行完毕");
	}
	$total = count($rows);
}
else
{
	$DB->setQuery($sql);
	$rows = $DB->loadList( "" , "assoc" );
}
$DB->close();
//$t->b("sql执行完毕");$t->p();

if( $total>0 )
{
	require_once( GA_ROOT."/softInc/listPage.php");
	@include_once($_CAE_PATH."subSort1.cae.php");
	//--------------------分页---------------------------------------------------
	$link = "search.php?so=".urlencode($so);
	$pageNav = new listPage(  $p  , $pageNum , $total) ;
	if ($p>$pageNav->totalPages)
	{
	    errorCode404();
	}
	$pageNav->pageLink = $link . "&p={{page}}&ob=".$ob."&ow=".$ow;
	$pageNav->selectPageLink = "'".$link . "&p='+this.value";;
//	$pageLinks   = $pageNav->getPagesLinks();
//	$pageCounter = $pageNav->getPagesCounter( true );
	$pageString = $pageNav->getPage1 ();
	//-------------------------------------------------------------------------
	$smarty->assign( "p" , $p );
	$smarty->assign( "total" , $total );
	$smarty->assign( "totalPages" , $pageNav->totalPages );
	$smarty->assign( "pageLinks" , $pageLinks);
	$smarty->assign( "pageString" , $pageString);
	//-------------------------------------------------------------------------
	$start = "[[<<{{";
	$end = "}}>>]]";

	$n=count($rows);
	arsortByLen( $keyArray , "DESC" );
	$k = 1;
	for ($i=0;$i<$n ;$i++ )
	{
	    $row = &$rows[$i];
		if ($row['zgssid'] == 0 && $row['bdid'] == 0)
		{
		    $row['link'] = "/game/".$row['softid'].".html";
		}
		elseif ($row['zgssid'] == 1) {
		    $row['link'] = "/news/".$row['zgid']."_1.html";
		}
		elseif ($row['zgssid'] == 3) {
		    $row['link'] = "/gl/".$row['zgid']."_1.html";
		}
		elseif ($row['zgssid'] == 4||$row['zgssid'] == 5||$row['zgssid'] == 6) {
			$row['conf'] = $zg_conf[$row['zgssid']];
		    $row['link'] = "/picnews/".$row['zgid'].".html";
		}
		elseif ($row['bdid'] != 0) {
		    $row['link'] = "/buding/".$row['bdid'].".html";
		}
		//软件介绍
		$row['content'] = trim( str_replace( "　","", $row['content'] ) );
		//加色
		$row['content'] = str_sub( preg_replace("#</?[^>]+>#", "" , $row['content']),296);
		//$row['content'] = substr2( $row['content'] , $keyArray[0] , "140" , "150" , $encoding='gbk' , $mode='' );
		$row['title1'] = $row['title'];
		highlightString( $row['content'] , $keyArray );
		highlightString( $row['title'] , $keyArray );
		highlightString( $row['sEdition'] , $keyArray );

		//子类别
		$row['typeName'] = $allName[$row['ssid']];
		$row['typeLink'] = "/list/".$row['ssid']."_1.html";
		//大小
		if($row['size']>1024)
			$row['size'] = round($row['size']/1024 , 2)." MB";
		else
			$row['size'] = $row['size']."KB";

		//运行环境
		$row['sysIng'] = substr($row['sysIng'],0,-1);
		//图片信息
		if($row['softImg']=="")
		{
			$row['softImg'] = "无";
			$row['thumbImg'] = "/images/empty.jpg";
		}
		else
		{
			$imgArray = explode("||",$row['softImg']);
			$row['softImg'] = '<a href="/gamePic.php?img='.$imgArray[0].'" target="_blank">安装预览</a>';
			$row['thumbImg'] = $imgArray[1];
		}
		//更新时间
		$row['stamp'] = $row['addTime'];
		$row['addtime'] = date("Y/m/d",$row['addtime'] );
		//语言，类型
		$row['sLang'] = $lang_conf[$row['sLang']]; //sLang

		$row['zpj'] = $row['pj'] + $row['pj2'] + $row['pj3'];
		if ($row['zpj'] == '0')
		{
			$row['pjb'] = '100%';
		}
		else
		{
			 $row['pjb'] = ceil(100*($row['pj']/$row['zpj'])).'%';
		}

		//img
		if ($row['zgssid'] > 3)
		{
			$row['img'] = '/thumbid/'.$row['zgid'].'.jpg';
		}


		//下载次数
		$row['tDown'] = intval( $row['tDown'] )*6;
		$row['commentNum'] = intval( $row['commentNum'] );
		$row['commentLink'] = getCommentListLink( $row['id'] );

	}//end while
	if($ow == 'zixun' || $ow == 'gl' || $ow == 'bd')
	{
		$rows = array_chunk($rows,5);
		if($ow == 'zixun')$nn = ceil($zxtotal/5);
		if($ow == 'gl')$nn = ceil($gltotal/5);
		if($ow == 'bd')$nn = ceil($bdtotal/5);
		for($i=0;$i<$nn;$i++)
		{
			$zxc[$i]=$i;
		}
		$smarty->assign("nn",$zxc);
	}

	$smarty->assign("rows",$rows);
}

$tpl = "search.tpl.html";

$smarty->assign("so",$so);
$htmlTitle = $so . " - 搜索结果 - 单机游戏站";
$smarty -> assign('htmlTitle',$htmlTitle);
$smarty->assign("search","search");
$pageMain=$smarty->Fetch( $tpl );

//$t->b("结束"); $t->p();

echo $pageMain;
//echo $caeFile;

//写入缓存
if($p<=$caePage and $cacheNow)
{
	//@mkdir($caePath);
	//getWriteFile($pageMain,$caeFile);
	f_put( $caeFile, $pageMain , 'wb' , true );
}

function mkdirp($target)
{
  if (file_exists($target)) {
   if (!is_dir($target)) return false;
   else return true;
  }
  if ( @mkdir($target) ) return true;
  if ( mkdirp(dirname($target)) ) return mkdirp($target);
  return false;
}

function f_put( $file , $data , $mode="wb" , $autoMkDir=false )
{
	$fp = @fopen($file,$mode);
	if(!$fp && $autoMkDir )
	{
		mkdirp(dirname($file));
		$fp = fopen($file,$mode);
	}
	fwrite($fp,$data);
	fclose($fp);
}

function arsortByLen(&$arr , $mode="ASC" )
{
    foreach( $arr as $k=>$v)
    {
        $len[$k] = strlen($v);
    }
    if( $mode=="ASC" )
        asort($len);
    elseif( $mode=="DESC" )
        arsort($len);

    foreach( $len as $k=>$v)
    {
        $newarr[] = $arr[$k];
    }
    $arr = $newarr;
}

//高亮关键字
//作者 异域苍穹(gudai)
//版权所有，如需使用，必须注明作者来源。
function highlightString(&$string , $findKeyArr ,$highlightTagStart="<font color=red>", $highlightTagEnd="</font>" )
{

    $start = "[[<<{{";
    $end = "}}>>]]";
	//pr($_GET);
	//pr($findKeyArr);die;
    //替换key
    foreach( $findKeyArr as $k=>$key)
    {
		if ($key=="")
			return;

		$key = preg_quote( $key , "#" );
        $reg = "#".$key."#i";
        $string = preg_replace( $reg, $start."\$0".$end,$string);
    }
    $string = str_replace($start,$highlightTagStart,$string);
    $string = str_replace($end,$highlightTagEnd,$string);
}

function pr($arr)
{
    echo "<pre>";
	print_R( $arr );
}
function filter($var)
{
        if($var == '')
        {
                return false;
        }

        return true;
}
?>