<?php

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~ E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################
define('THIS_SCRIPT', 'ajaxlivesearch');
define('CSRF_PROTECTION', true);
define('LOCATION_BYPASS', 1);
define('NOPMPOPUP', 1);

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// get special data templates from the datastore
$specialtemplates = array();

// pre-cache templates used by all actions
$globaltemplates = array('lsa_bit', 'lsa_box');

// ######################### REQUIRE BACK-END ############################
require_once('./global.php');
require_once(DIR . '/includes/functions_misc.php');
require_once(DIR . '/includes/functions_livesearch.php');
require_once(DIR . '/includes/class_xml.php');

if ($vbulletin->options['lsa_global'])
{
	$xml = new vB_AJAX_XML_Builder($vbulletin, 'text/xml');
	$xml->add_group('lsagroup');
	if ($_POST['do'] == 'lsawin')
	{
		$tpl = vB_Template::create('lsa_main');
		$tpl->register('findzone', showForumOptions());
		$lsawin = $tpl->render();
		$xml->add_tag('lsagetwin', process_replacement_vars($lsawin));
	}
	if ($_POST['do'] == 'search')
	{
		$vbulletin->input->clean_array_gpc('p', array(
			'lsazone' => TYPE_NOHTML, 
			'lsasort' => TYPE_NOHTML,
			'lsasorttype' => TYPE_NOHTML, 
			'lsawithword' => TYPE_BOOL, 
			'lsatype' => TYPE_BOOL, 
			'childforums' => TYPE_BOOL,
			'keyword' => TYPE_STR
		));

		$searchstart = microtime();

		$minstr = $vbulletin->options['lsa_minsym'];
		$maxstr = $vbulletin->options['lsa_maxsym'];
		$lsanresults = intval($vbulletin->options['lsa_nresults']);
		$trimtitle = $vbulletin->options['lsa_trimt'];
		$trimftitle = $vbulletin->options['lsa_trimf'];

		$lsasearchin = convert_urlencoded_unicode(htmlspecialchars_uni($vbulletin->GPC['lsazone']));
		if ($vbulletin->GPC['childforums'])
		{
			foreach (explode(",", $lsasearchin) AS $forumid)
			{
				$children = fetch_child_forums($forumid, 'ARRAY');
				if (!empty($children))
				{
					foreach ($children AS $childid)
					{
						$lsasearchin .= ',' . $childid;
					}
				}
				unset($children);
			}
		}
		if (empty($lsasearchin))
		{
			$lsasearchin = 'allforum';
		}
		$lsasorttype = $vbulletin->GPC['lsasorttype'];
		$lsatype = $vbulletin->GPC['lsatype'];
		$lsaut = $lsatype ? $vbphrase['lsa_users'] : $vbphrase['lsa_threads'];

		switch ($vbulletin->GPC['lsasort'])
		{
			case 'dateline':
				$lsasortby .= 'thread.dateline';
				break;

			case 'title':
				$lsasortby .= 'thread.title';
				break;

			case 'replycount':
				$lsasortby .= 'thread.replycount';
				break;

			case 'views':
				$lsasortby .= 'thread.views';
				break;

			case 'forum':
				$lsasortby .= 'forum.title';
				break;

			case 'lastpost':
				$lsasortby .= 'thread.lastpost';
				break;
			default:
				$lsasortby .= 'thread.lastpost';
		}

		$vbulletin->GPC['keyword'] = convert_urlencoded_unicode($vbulletin->GPC['keyword']);
		$query = htmlspecialchars_uni($vbulletin->GPC['keyword']);
		$query = $db->escape_string($query);

		$lsaword = str_replace(" ", ", ", $query);
		$wordlist = explode(" ", $query);
		$sl = sizeof($wordlist);
		$lsaresult = 0;

		$lsww = $vbulletin->GPC['lsawithword'] ? ' AND ' : ' OR ';

		$iword = array();

		foreach ($wordlist AS $word)
		{
			if (strlen($word) >= $minstr OR strlen($wordlist[0]) < $minstr)
			{
				$esword = $vbulletin->db->escape_string($word);
				$eslword = $vbulletin->db->escape_string_like($word);
				if ($lsatype)
				{
					$iword[] = "username LIKE('%" . $eslword . "%')";
				} else
				{
					if ($vbulletin->options['lsa_fulltext'])
					{
						$qword .= $vbulletin->GPC['lsawithword'] ? " +$esword" : " $esword";
					}
					else
					{
						$iword[] = "thread.title LIKE('%" . $eslword . "%')";
					}
				}
			}
		}

		foreach($vbulletin->forumcache AS $forum)
		{
			if (!($vbulletin->userinfo['forumpermissions']["$forum[forumid]"] & $vbulletin->bf_ugp_forumpermissions['canview']) AND ($forum["$forum[forumid]"]['showprivate'] == 1 OR (!$forum["$forum[forumid]"]['showprivate'] AND !$vbulletin->options['showprivateforums'])))
			{
				$excludelist .= ',' . $forum['forumid'];
			}
		}

		if ($lsatype)
		{
			$results = $vbulletin->db->query_read("
				SELECT userid, username, usertitle, usergroupid, displaygroupid
				FROM " . TABLE_PREFIX . "user AS user
				WHERE " . implode($lsww, $iword) . "
				ORDER BY username ASC
				LIMIT $lsanresults
			");
		} else
		{
			$results = $vbulletin->db->query_read("
				SELECT thread.threadid, thread.lastpostid, thread.forumid AS tforumid, thread.title AS ttitle, forum.title AS ftitle
				FROM " . TABLE_PREFIX . "thread AS thread
				LEFT JOIN " . TABLE_PREFIX . "forum AS forum ON(thread.forumid = forum.forumid)
				WHERE " . iif($vbulletin->options['lsa_fulltext'], "MATCH(thread.title) AGAINST ('" . $qword . "' IN BOOLEAN MODE)", implode($lsww, $iword)) . "
				" . iif(substr($lsasearchin, 0, 8) != 'allforum', "AND thread.forumid IN (" . $vbulletin->db->escape_string($lsasearchin) . ")") . "
				AND thread.forumid NOT IN (0$excludelist)
				AND thread.lastpostid > 0
				ORDER BY " . $vbulletin->db->escape_string($lsasortby) . " " . $vbulletin->db->escape_string($lsasorttype) . "
				LIMIT $lsanresults
			");
		}

		if (strlen($wordlist[0]) >= $minstr AND $vbulletin->db->num_rows($results) > 0)
		{
			while ($result = $vbulletin->db->fetch_array($results))
			{
				$lsfid = $result['tforumid'];
				$lsttitle = $result['ttitle'];
				$lsforumname = $result[ftitle];
				$lstid = $result['threadid'];
				$lsunamealt = $result['username'];
				$lsuname = $result['username'];
				$lsuname = fetch_musername($result);
				$lsuid = $result['userid'];

				// triming thread title
				$lstalt = $lsttitle;
				$lsttitle = ($trimtitle > 0) ? fetch_trimmed_title($lsttitle, $trimtitle) : $lsttitle;

				// triming forum title
				$lsfalt = $lsforumname;
				$lsfname = ($trimftitle > 0) ? fetch_trimmed_title($lsfalt, $trimftitle) : $lsfname;

				// words to highlight from the search engine
				foreach ($wordlist AS $hiword)
				{
					$lsttitle = preg_replace('#(' . strtolower($hiword) . ')(?![^<]*>)#is', '<span class="highlight">\\1</span>', $lsttitle);
				}

				$bit = vB_Template::create('lsa_bit');
				$bit->quickRegister(array(
					'lsatype' => $lsatype,
					'lsuid' => $lsuid,
					'lsunamealt' => $lsunamealt,
					'lsuname' => $lsuname,
					'usertitle' => $result['usertitle'],
					'lstid' => $lstid,
					'lstalt' => $lstalt,
					'lsttitle' => $lsttitle,
					'lsfid' => $lsfid,
					'lsfalt' => $lsfalt,
					'lsfname' => $lsfname,
				));
				$lsa_bits .= $bit->render();
				$lsaresult++;
			}
			$searchtime = number_format(fetch_microtime_difference($searchstart), 5, '.', '');
			$lsaphr = construct_phrase($vbphrase['lsa_result'], $lsaresult, $lsaword, $lsaut, $searchtime);
			$box = vB_Template::create('lsa_box');
			$box->register('lsaphr', $lsaphr);
			$box->register('lsa_bits', $lsa_bits);
			$lsaout = $box->render();

		} else if ($vbulletin->db->num_rows($results) == 0)
		{
			$lsaout = $vbphrase['lsa_no_results'] . (($checkps = check_ps($wordlist)) ? construct_phrase($vbphrase['lsa_no_results_but'], $checkps) : "");
		}
		$xml->add_tag('ajaxlivesearch', process_replacement_vars($lsaout));
	}
	$xml->close_group();
	$xml->print_xml();
}

?>