<?php

/*
	[DISCUZ!] search.php - board search
	This is NOT a freeware, use is subject to license terms

	Version: 4.0.0
	Web: http://www.comsenz.com
	Copyright: 2001-2005 Comsenz Technology Ltd.
	Last Modified: 2004/12/7 05:13
*/

require_once './include/common.inc.php';
require_once DISCUZ_ROOT.'./include/forum.func.php';
require_once DISCUZ_ROOT.'./forumdata/cache/cache_forums.php';

$discuz_action = 111;

$cachelife_time = 300;		// Life span for cache of searching in specified range of time
$cachelife_text = 3600;		// Life span for cache of searching in specified range of full text

if(!submitcheck('searchsubmit', 1) && empty($page)) {

	$forumselect = forumselect();
	$checktype = array(($qihoostatus == 2 || ($qihoostatus == 1 && !$allowsearch) ? 'qihoo' : 'title') => 'checked');

	$disabled = array();
	$disabled['title'] = $disabled['blog'] = !$allowsearch ? 'disabled' : '';
	$disabled['fulltext'] = $allowsearch != 2 ? 'disabled' : '';

	include template('search');

} else {

	if($srchtype == 'qihoo') {

		if(!$srchtxt && !$srchuname) {
			showmessage('search_invalid');
		}

		$url = 'http://search.discuz.net/qihoo.php?host='.rawurlencode($_SERVER['HTTP_HOST']).
			'&srchtxt='.rawurlencode($srchtxt).
			'&srchuname='.rawurlencode($srchuname).
			'&orderby='.rawurlencode($orderby).
			($srchfid ? '&srchforum='.rawurlencode($_DCACHE['forums'][$srchfid]['name']) : '').
			'&srchfrom='.intval($srchfrom).
			'&before='.rawurlencode($before);

		header("Location: $url");
		dexit();

	}

	if(!$allowsearch) {
		showmessage('group_nopermission', NULL, 'NOPERM');
	}

	$orderby = in_array($orderby, array('dateline', 'replies', 'views')) ? $orderby : 'lastpost';
	$ascdesc = isset($ascdesc) && $ascdesc == 'asc' ? 'asc' : 'desc';

	if(isset($searchid)) {

		require_once DISCUZ_ROOT.'./include/misc.func.php';

		$page = !ispage($page) ? 1 : $page;
		$start_limit = ($page - 1) * $tpp;

		$query = $db->query("SELECT searchstring, keywords, threads, tids FROM {$tablepre}searchindex WHERE searchid='$searchid'");
		if(!$index = $db->fetch_array($query)) {
			showmessage('search_id_invalid');
		}
		$index['keywords'] = rawurlencode($index['keywords']);
		$index['searchtype'] = preg_replace("/^([a-z]+)\|.*/", "\\1", $index['searchstring']);

		$threadlist = array();
		$query = $db->query("SELECT * FROM {$tablepre}threads WHERE tid IN ($index[tids]) AND displayorder>='0' ORDER BY $orderby $ascdesc LIMIT $start_limit, $tpp");
		while($thread = $db->fetch_array($query)) {
			$threadlist[] = procthread($thread);
		}

		$multipage = multi($index['threads'], $tpp, $page, "search.php?searchid=$searchid&orderby=$orderby&ascdesc=$ascdesc&searchsubmit=yes");

		include template($index['searchtype'] != 'blog' ? 'search_threads' : 'search_blog');

	} else {

		checklowerlimit($creditspolicy['search'], -1);

		$srchtxt = isset($srchtxt) ? trim($srchtxt) : '';
		$srchuname = isset($srchuname) ? trim($srchuname) : '';

		if($allowsearch == 2 && $srchtype == 'fulltext') {
			periodscheck('searchbanperiods');
		} elseif(!in_array($srchtype, array('title', 'blog'))) {
			$srchtype = 'title';
		}

		$searchstring = $srchtype.'|'.addslashes($srchtxt).'|'.intval($srchuid).'|'.trim($srchuname).'|'.intval($srchfid).'|'.intval($srchfrom).'|'.intval($before);

		$searchindex = array('id' => 0, 'dateline' => '0');
		$query = $db->query("SELECT searchid, dateline, ('$searchctrl'<>'0' AND ".(empty($uid) ? "useip='$onlineip'" : "uid='$uid'")." AND $timestamp-dateline<$searchctrl) AS flood, (searchstring='$searchstring' AND expiration>'$timestamp') AS indexvalid FROM {$tablepre}searchindex WHERE ('$searchctrl'<>'0' AND ".(empty($uid) ? "useip='$onlineip'" : "uid='$uid'")." AND $timestamp-dateline<$searchctrl) OR (searchstring='$searchstring' AND expiration>'$timestamp') ORDER BY flood");
		while($index = $db->fetch_array($query)) {
			if($index['indexvalid'] && $index['dateline'] > $searchindex['dateline']) {
				if(substr($timestamp, -1) == '0') {
					$db->query("DELETE FROM {$tablepre}searchindex WHERE expiration<'$timestamp'", 'UNBUFFERED');
				}
				$searchindex = array('id' => $index['searchid'], 'dateline' => $index['dateline']);
				break;
			} elseif($index['flood']) {
				showmessage('search_ctrl');
			}
		}

		if($searchindex['id']) {

			$searchid = $searchindex['id'];

		} else {

			if(!isset($srchfid)) {
				$srchfid = 'all';
			}

			$fids = $comma = '';
			foreach($_DCACHE['forums'] as $fid => $forum) {
				if($forum['type'] != 'group' && (!$forum['viewperm'] && $readaccess) || ($forum['viewperm'] && forumperm($forum['viewperm']))) {
					$fids .= "$comma'$fid'";
					$comma = ',';
				}
			}

			if(!$srchtxt && !$srchuid && !$srchuname && !$srchfrom) {
				showmessage('search_invalid');
			} elseif(empty($srchfid)) {
				showmessage('search_forum_invalid');
			} elseif(!$fids) {
				showmessage('group_nopermission', NULL, 'NOPERM');
			}

			if(!empty($srchfrom) && empty($srchtxt) && empty($srchuid) && empty($srchuname)) {
	
				$searchfrom = $before ? '<=' : '>=';
				$searchfrom .= $timestamp - $srchfrom;
				$sqlsrch = "FROM {$tablepre}threads t WHERE t.fid IN ($fids) AND t.displayorder>='0' AND t.lastpost$searchfrom";
				if($srchfid != "all" && $srchfid) {
					$sqlsrch .= " AND t.fid='$srchfid'";
				}
				$expiration = $timestamp + $cachelife_time;
				$keywords = '';

			} else {

				if(!empty($mytopics) && $srchuid) {
					if($fullmytopics) {
						$srchtype = 'fulltext';
					}
					$srchfrom = 2592000;
					$srchuname = $srchtxt = $before = '';
				}

				$sqlsrch = $srchtype == 'fulltext' ?
					"FROM {$tablepre}posts p, {$tablepre}threads t WHERE t.fid IN ($fids) AND p.tid=t.tid AND p.invisible='0'" :
					"FROM {$tablepre}threads t WHERE t.fid IN ($fids) AND t.displayorder>='0'".($srchtype == 'blog' ? ' AND t.blog=\'1\'' : '');

				if($srchuname) {
					$srchuid = $comma = '';
					$srchuname = str_replace('*', '%', addcslashes($srchuname, '%_'));
					$query = $db->query("SELECT uid FROM {$tablepre}members WHERE username LIKE '".str_replace('_', '\_', $srchuname)."' LIMIT 50");
					while($member = $db->fetch_array($query)) {
						$srchuid .= "$comma'$member[uid]'";
						$comma = ', ';
					}
					if(!$srchuid) {
						$sqlsrch .= ' AND 0';
					}
				} elseif($srchuid) {
					$srchuid = "'$srchuid'";
				}

				if($srchtxt) {
					if(preg_match("(AND|\+|&|\s)", $srchtxt) && !preg_match("(OR|\|)", $srchtxt)) {
						$andor = ' AND ';
						$sqltxtsrch = '1';
						$srchtxt = preg_replace("/( AND |&| )/is", "+", $srchtxt);
					} else {
						$andor = ' OR ';
						$sqltxtsrch = '0';
						$srchtxt = preg_replace("/( OR |\|)/is", "+", $srchtxt);
					}
					$srchtxt = str_replace('*', '%', addcslashes($srchtxt, '%_'));
					foreach(explode('+', $srchtxt) as $text) {
						$text = trim($text);
						if($text) {
							$sqltxtsrch .= $andor;
							$sqltxtsrch .= $srchtype == 'fulltext' ? "(p.message LIKE '%".str_replace('_', '\_', $text)."%' OR p.subject LIKE '%$text%')" : "t.subject LIKE '%$text%'";
						}
					}
					$sqlsrch .= " AND ($sqltxtsrch)";
				}

				if($srchuid) {
					$sqlsrch .= ' AND '.($srchtype == 'fulltext' ? 'p' : 't').".authorid IN ($srchuid)";
				}

				if($srchfid != 'all' && $srchfid) {
					$sqlsrch .= ' AND '.($srchtype == 'fulltext' ? 'p' : 't').".fid='$srchfid'";
				}

				if(!empty($srchfrom)) {
					$searchfrom = $before ? '<=' : '>=';
					$searchfrom .= $timestamp - $srchfrom;
					$sqlsrch .= " AND t.lastpost$searchfrom";
				}

				$keywords = str_replace('%', '+', $srchtxt).(trim($srchuname) ? '+'.str_replace('%', '+', $srchuname) : NULL);
				$expiration = $timestamp + $cachelife_text;

			}

			$threads = $tids = 0;
			$query = $db->query("SELECT DISTINCT t.tid, t.closed $sqlsrch ORDER BY tid DESC LIMIT $maxsearchresults");
			while($thread = $db->fetch_array($query)) {
				if($thread['closed'] <= 1) {
					$tids .= ','.$thread['tid'];
					$threads++;
				}
			}
			$db->free_result($query);

			$db->query("INSERT INTO {$tablepre}searchindex (keywords, searchstring, useip, uid, dateline, expiration, threads, tids)
					VALUES ('$keywords', '$searchstring', '$onlineip', '$discuz_uid', '$timestamp', '$expiration', '$threads', '$tids')");
			$searchid = $db->insert_id();

			updatecredits($discuz_uid, $creditspolicy['search'], -1);

		}

		showmessage('search_redirect', "search.php?searchid=$searchid&orderby=$orderby&ascdesc=$ascdesc&searchsubmit=yes");

	}

}

?>