<?php
/**
 * @version $Id: search.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

define('PB_CSCRIPT', 'search');
require_once('include/common.inc.php');

$rhost = parse_url($_SERVER['HTTP_REFERER']);
$rhost['host'] .= $rhost['port'] ? (':'.$rhost['port']) : '';
if($rhost['host'] != $_SERVER['HTTP_HOST']) exit('Access Denied');

if (!$allowbsearch && !$allowasearch)
{
	showMsg($u_message['search_nopermission']);
}
if (!$pb_s && !is_numeric($searchid))
{
	showMsg($u_message['parameter_error']);
}
$sql = $rs = $searchresult = $totalRecords = $khash = '';

$pagesize = (int)$pb_aperpage;
$page = !is_Page($page) ? 1 : $page;
$start_limit = ($page -1) * $pagesize;

if ($pb_s)
{
	if (strlen($pb_s) < 2)
	{
		showMsg('关键字长度不能小于 2 个字符。');
	}
	$pb_s = trim($_POST['pb_s']);
	$seo['pagetitle'] = $seo['keywords'] = $seo['description'] = htmlspecialchars($pb_s);
	$pb_s = str_replace(array("_","\\","&","'","\"","/","*",",","<",">","\r","\t","\n","#","\$","(",")","%","@","+","?",";","^"), '', $pb_s);
	$khash = md5($pb_s);
	if(preg_match("/(\s)/i", $pb_s) && !preg_match("/(\|)/i", $pb_s))
	{
		$andor = ' AND ';
		$cut = -5;
		$pb_s = preg_replace("/( )/is", "+", $pb_s);
	}
	else
	{
		$andor = ' OR ';
		$cut = -4;
		$pb_s = preg_replace("/(\|)/is", "+", $pb_s);
	}
	$keywords = array_filter(explode('+', $pb_s));
	foreach ($keywords as $t)
	{
		$t = trim($t);
		if($t)
		{
			$sql .= "(subject LIKE '%".$t."%' OR keywords LIKE '%".$t."%'";
			$sql .= $allowasearch ? " OR content LIKE '%".$t."%')" : ')';
			$sql .= $andor;
		}
	}
	$sql = substr($sql, 0 , $cut);
}

$content_replacement = array('[emote]','[/emote]','[strike]','[/strike]','[br]','[pre]','[/pre]','[acronym]','[/acronym]','[address]','[/address]','[ul]','[ol]','[li]','[/ul]','[/ol]','[/li]','[div]','[/div]','[p]','[/p]','[span]','[/span]','[tr]','[/tr]','[/td]','[/table]','[code]','[/code]','[b]','[/b]','[i]','[/i]','[u]','[/u]','[img]','[/img]','[/font]','[/size]','[/color]','[/align]','[/url]','[/quote]','[/media]','[/flash]','[/email]');
$content_preg_replacement = '#\[(font|table|td|size|color|align|url|quote|media|flash|email)(.*?)\]#is';

if (isset($searchid))
{
	$searchid = intval($searchid);
	$rs = $DB->db_fetch_one_array("SELECT keywords, tnum, tids FROM {$db_prefix}scaches WHERE searchid = $searchid");
	if ($rs && $rs['tids'])
	{
		$totalRecords = $rs['tnum'];
		$seo['pagetitle'] = $seo['keywords'] = $seo['description'] = htmlspecialchars($rs['keywords']);
		$DB->db_query("SELECT tid, author, uid, subject, content, postdate FROM {$db_prefix}threads t WHERE tid IN (".$rs['tids'].") ORDER BY postdate DESC LIMIT $start_limit, $pagesize");
		if ($DB->db_num())
		{
			while ($rs = $DB->db_fetch_array())
			{
				$rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i');
				$rs['content'] = str_replace($content_replacement, '', preg_replace($content_preg_replacement, '', $rs['content']));
				$rs['content'] = PBSubstr($rs['content'], $pb_indexcontent);
				$searchresult[] = $rs;
			}
			$pageurl = 'search.php?searchid='.$searchid.'&amp;';
		}
	}
	else
	{
		showMsg($u_message['search_nocontent']);
	}
}
elseif ($pb_s)
{
	$rs = $DB->db_fetch_one_array("SELECT searchid, tids, tnum FROM {$db_prefix}scaches WHERE khash = '$khash' AND exptime >= $timestamp");
	if ($DB->db_num())
	{
		$totalRecords = $rs['tnum'];
		$searchid = $rs['searchid'];
		$DB->db_query("SELECT tid, author, uid, subject, content, postdate FROM {$db_prefix}threads t WHERE tid IN (".addslashes($rs['tids']).") AND ifcheck = 1 ORDER BY postdate DESC LIMIT $start_limit, $pagesize");
		if ($DB->db_num())
		{
			while ($rs = $DB->db_fetch_array())
			{
				$rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i');
				$rs['content'] = str_replace($content_replacement, '', preg_replace($content_preg_replacement, '', $rs['content']));
				$rs['content'] = PBSubstr($rs['content'], $pb_indexcontent);
				$searchresult[] = $rs;
			}
			$pageurl = 'search.php?searchid='.$searchid.'&amp;';
		}
	}
	else
	{
		$DB->db_query("SELECT tid FROM {$db_prefix}threads WHERE ".$sql." LIMIT ".intval($pb_maxresult));
		$totalRecords = $DB->db_num();
		if (!$totalRecords)
		{
			showMsg($u_message['search_nocontent']);
		}
		else
		{
			$tids = '';
			while ($rs = $DB->db_fetch_array())
			{
				$tids .= $rs['tid'].',';
			}
			if (substr($tids, -1) == ',')
			{
				$tids = substr($tids, 0, -1);
			}
			$tids = addslashes($tids);
			$DB->db_query("INSERT INTO {$db_prefix}scaches (keywords, khash, tnum, tids, searchip, searchtime, exptime) VALUES ('$pb_s', '$khash', $totalRecords, '".$tids."', '".$_PBDEV['PB_IP']."', '$timestamp', ".($timestamp + 3600).")");
			$autoid = $DB->db_insertID();
			$DB->db_query("DELETE FROM {$db_prefix}scaches WHERE exptime < $timestamp");
			$DB->db_query("SELECT tid, author, uid, subject, content, postdate FROM {$db_prefix}threads t WHERE tid IN (".$tids.") ORDER BY postdate DESC LIMIT $start_limit, $pagesize");
			if ($DB->db_num())
			{
				while ($rs = $DB->db_fetch_array())
				{
					$rs['postdate'] = gdate($rs['postdate'], 'Y-m-d H:i');
					$rs['content'] = str_replace($content_replacement, '', preg_replace($content_preg_replacement, '', $rs['content']));
					$rs['content'] = PBSubstr($rs['content'], $pb_indexcontent);
					$searchresult[] = $rs;
				}
				$pageurl = 'search.php?searchid='.$autoid.'&amp;';
			}
			else
			{
				showMsg($u_message['search_nocontent']);
			}
		}
	}
}
else
{
	showMsg($u_message['search_nocontent']);
}

$mult = multLink($page, $totalRecords, $pageurl, $pagesize);

$TPL->assign('seo', $seo);
$TPL->assign('searchresult', $searchresult);
$TPL->assign('mult_page', $mult);
$TPL->assign('searchnum', sprintf($ui_message['search_result'], $totalRecords));
PBOutPut('search.html');
?>
