Blame Identity/Webenv/phpBB/3.0.4/includes/search/fulltext_mysql.php

ef5584
ef5584
/**
ef5584
*
ef5584
* @package search
ef5584
* @version $Id: fulltext_mysql.php 8814 2008-09-04 12:01:47Z acydburn $
ef5584
* @copyright (c) 2005 phpBB Group
ef5584
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
ef5584
*
ef5584
*/
ef5584
ef5584
/**
ef5584
* @ignore
ef5584
*/
ef5584
if (!defined('IN_PHPBB'))
ef5584
{
ef5584
	exit;
ef5584
}
ef5584
ef5584
/**
ef5584
* @ignore
ef5584
*/
ef5584
include_once($phpbb_root_path . 'includes/search/search.' . $phpEx);
ef5584
ef5584
/**
ef5584
* fulltext_mysql
ef5584
* Fulltext search for MySQL
ef5584
* @package search
ef5584
*/
ef5584
class fulltext_mysql extends search_backend
ef5584
{
ef5584
	var $stats = array();
ef5584
	var $word_length = array();
ef5584
	var $split_words = array();
ef5584
	var $search_query;
ef5584
	var $common_words = array();
ef5584
	var $pcre_properties = false;
ef5584
	var $mbstring_regex = false;
ef5584
ef5584
	function fulltext_mysql(&$error)
ef5584
	{
ef5584
		global $config;
ef5584
ef5584
		$this->word_length = array('min' => $config['fulltext_mysql_min_word_len'], 'max' => $config['fulltext_mysql_max_word_len']);
ef5584
ef5584
		if (version_compare(PHP_VERSION, '5.1.0', '>=') || (version_compare(PHP_VERSION, '5.0.0-dev', '<=') && version_compare(PHP_VERSION, '4.4.0', '>=')))
ef5584
		{
ef5584
			// While this is the proper range of PHP versions, PHP may not be linked with the bundled PCRE lib and instead with an older version
ef5584
			if (@preg_match('/\p{L}/u', 'a') !== false)
ef5584
			{
ef5584
				$this->pcre_properties = true;
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (function_exists('mb_ereg'))
ef5584
		{
ef5584
			$this->mbstring_regex = true;
ef5584
			mb_regex_encoding('UTF-8');
ef5584
		}
ef5584
ef5584
		$error = false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Checks for correct MySQL version and stores min/max word length in the config
ef5584
	*/
ef5584
	function init()
ef5584
	{
ef5584
		global $db, $user;
ef5584
ef5584
		if ($db->sql_layer != 'mysql4' && $db->sql_layer != 'mysqli')
ef5584
		{
ef5584
			return $user->lang['FULLTEXT_MYSQL_INCOMPATIBLE_VERSION'];
ef5584
		}
ef5584
ef5584
		$result = $db->sql_query('SHOW TABLE STATUS LIKE \'' . POSTS_TABLE . '\'');
ef5584
		$info = $db->sql_fetchrow($result);
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$engine = '';
ef5584
		if (isset($info['Engine']))
ef5584
		{
ef5584
			$engine = $info['Engine'];
ef5584
		}
ef5584
		else if (isset($info['Type']))
ef5584
		{
ef5584
			$engine = $info['Type'];
ef5584
		}
ef5584
ef5584
		if ($engine != 'MyISAM')
ef5584
		{
ef5584
			return $user->lang['FULLTEXT_MYSQL_NOT_MYISAM'];
ef5584
		}
ef5584
ef5584
		$sql = 'SHOW VARIABLES
ef5584
			LIKE \'ft\_%\'';
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		$mysql_info = array();
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$mysql_info[$row['Variable_name']] = $row['Value'];
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		set_config('fulltext_mysql_max_word_len', $mysql_info['ft_max_word_len']);
ef5584
		set_config('fulltext_mysql_min_word_len', $mysql_info['ft_min_word_len']);
ef5584
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Splits keywords entered by a user into an array of words stored in $this->split_words
ef5584
	* Stores the tidied search query in $this->search_query
ef5584
	*
ef5584
	* @param string &$keywords Contains the keyword as entered by the user
ef5584
	* @param string $terms is either 'all' or 'any'
ef5584
	* @return bool false if no valid keywords were found and otherwise true
ef5584
	*/
ef5584
	function split_keywords(&$keywords, $terms)
ef5584
	{
ef5584
		global $config;
ef5584
ef5584
		if ($terms == 'all')
ef5584
		{
ef5584
			$match		= array('#\sand\s#iu', '#\sor\s#iu', '#\snot\s#iu', '#\+#', '#-#', '#\|#');
ef5584
			$replace	= array(' +', ' |', ' -', ' +', ' -', ' |');
ef5584
ef5584
			$keywords = preg_replace($match, $replace, $keywords);
ef5584
		}
ef5584
ef5584
		// Filter out as above
ef5584
		$split_keywords = preg_replace("#[\n\r\t]+#", ' ', trim(htmlspecialchars_decode($keywords)));
ef5584
ef5584
		// Split words
ef5584
		if ($this->pcre_properties)
ef5584
		{
ef5584
			$split_keywords = preg_replace('#([^\p{L}\p{N}\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords)));
ef5584
		}
ef5584
		else if ($this->mbstring_regex)
ef5584
		{
ef5584
			$split_keywords = mb_ereg_replace('([^\w\'*"()])', '\\1\\1', str_replace('\'\'', '\' \'', trim($split_keywords)));
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$split_keywords = preg_replace('#([^\w\'*"()])#u', '$1$1', str_replace('\'\'', '\' \'', trim($split_keywords)));
ef5584
		}
ef5584
ef5584
		if ($this->pcre_properties)
ef5584
		{
ef5584
			$matches = array();
ef5584
			preg_match_all('#(?:[^\p{L}\p{N}*"()]|^)([+\-|]?(?:[\p{L}\p{N}*"()]+\'?)*[\p{L}\p{N}*"()])(?:[^\p{L}\p{N}*"()]|$)#u', $split_keywords, $matches);
ef5584
			$this->split_words = $matches[1];
ef5584
		}
ef5584
		else if ($this->mbstring_regex)
ef5584
		{
ef5584
			mb_ereg_search_init($split_keywords, '(?:[^\w*"()]|^)([+\-|]?(?:[\w*"()]+\'?)*[\w*"()])(?:[^\w*"()]|$)');
ef5584
ef5584
			while (($word = mb_ereg_search_regs()))
ef5584
			{
ef5584
				$this->split_words[] = $word[1];
ef5584
			}
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$matches = array();
ef5584
			preg_match_all('#(?:[^\w*"()]|^)([+\-|]?(?:[\w*"()]+\'?)*[\w*"()])(?:[^\w*"()]|$)#u', $split_keywords, $matches);
ef5584
			$this->split_words = $matches[1];
ef5584
		}
ef5584
ef5584
		// to allow phrase search, we need to concatenate quoted words
ef5584
		$tmp_split_words = array();
ef5584
		$phrase = '';
ef5584
		foreach ($this->split_words as $word)
ef5584
		{
ef5584
			if ($phrase)
ef5584
			{
ef5584
				$phrase .= ' ' . $word;
ef5584
				if (strpos($word, '"') !== false && substr_count($word, '"') % 2 == 1)
ef5584
				{
ef5584
					$tmp_split_words[] = $phrase;
ef5584
					$phrase = '';
ef5584
				}
ef5584
			}
ef5584
			else if (strpos($word, '"') !== false && substr_count($word, '"') % 2 == 1)
ef5584
			{
ef5584
				$phrase = $word;
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$tmp_split_words[] = $word . ' ';
ef5584
			}
ef5584
		}
ef5584
		if ($phrase)
ef5584
		{
ef5584
			$tmp_split_words[] = $phrase;
ef5584
		}
ef5584
ef5584
		$this->split_words = $tmp_split_words;
ef5584
ef5584
		unset($tmp_split_words);
ef5584
		unset($phrase);
ef5584
ef5584
		foreach ($this->split_words as $i => $word)
ef5584
		{
ef5584
			$clean_word = preg_replace('#^[+\-|"]#', '', $word);
ef5584
ef5584
			// check word length
ef5584
			$clean_len = utf8_strlen(str_replace('*', '', $clean_word));
ef5584
			if (($clean_len < $config['fulltext_mysql_min_word_len']) || ($clean_len > $config['fulltext_mysql_max_word_len']))
ef5584
			{
ef5584
				$this->common_words[] = $word;
ef5584
				unset($this->split_words[$i]);
ef5584
			}
ef5584
		}
ef5584
ef5584
		if ($terms == 'any')
ef5584
		{
ef5584
			$this->search_query = '';
ef5584
			foreach ($this->split_words as $word)
ef5584
			{
ef5584
				if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0) || (strpos($word, '|') === 0))
ef5584
				{
ef5584
					$word = substr($word, 1);
ef5584
				}
ef5584
				$this->search_query .= $word . ' ';
ef5584
			}
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->search_query = '';
ef5584
			foreach ($this->split_words as $word)
ef5584
			{
ef5584
				if ((strpos($word, '+') === 0) || (strpos($word, '-') === 0))
ef5584
				{
ef5584
					$this->search_query .= $word . ' ';
ef5584
				}
ef5584
				else if (strpos($word, '|') === 0)
ef5584
				{
ef5584
					$this->search_query .= substr($word, 1) . ' ';
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$this->search_query .= '+' . $word . ' ';
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		$this->search_query = utf8_htmlspecialchars($this->search_query);
ef5584
ef5584
		if ($this->search_query)
ef5584
		{
ef5584
			$this->split_words = array_values($this->split_words);
ef5584
			sort($this->split_words);
ef5584
			return true;
ef5584
		}
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Turns text into an array of words
ef5584
	*/
ef5584
	function split_message($text)
ef5584
	{
ef5584
		global $config;
ef5584
ef5584
		// Split words
ef5584
		if ($this->pcre_properties)
ef5584
		{
ef5584
			$text = preg_replace('#([^\p{L}\p{N}\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text)));
ef5584
		}
ef5584
		else if ($this->mbstring_regex)
ef5584
		{
ef5584
			$text = mb_ereg_replace('([^\w\'*])', '\\1\\1', str_replace('\'\'', '\' \'', trim($text)));
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$text = preg_replace('#([^\w\'*])#u', '$1$1', str_replace('\'\'', '\' \'', trim($text)));
ef5584
		}
ef5584
ef5584
		if ($this->pcre_properties)
ef5584
		{
ef5584
			$matches = array();
ef5584
			preg_match_all('#(?:[^\p{L}\p{N}*]|^)([+\-|]?(?:[\p{L}\p{N}*]+\'?)*[\p{L}\p{N}*])(?:[^\p{L}\p{N}*]|$)#u', $text, $matches);
ef5584
			$text = $matches[1];
ef5584
		}
ef5584
		else if ($this->mbstring_regex)
ef5584
		{
ef5584
			mb_ereg_search_init($text, '(?:[^\w*]|^)([+\-|]?(?:[\w*]+\'?)*[\w*])(?:[^\w*]|$)');
ef5584
ef5584
			$text = array();
ef5584
			while (($word = mb_ereg_search_regs()))
ef5584
			{
ef5584
				$text[] = $word[1];
ef5584
			}
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$matches = array();
ef5584
			preg_match_all('#(?:[^\w*]|^)([+\-|]?(?:[\w*]+\'?)*[\w*])(?:[^\w*]|$)#u', $text, $matches);
ef5584
			$text = $matches[1];
ef5584
		}
ef5584
ef5584
		// remove too short or too long words
ef5584
		$text = array_values($text);
ef5584
		for ($i = 0, $n = sizeof($text); $i < $n; $i++)
ef5584
		{
ef5584
			$text[$i] = trim($text[$i]);
ef5584
			if (utf8_strlen($text[$i]) < $config['fulltext_mysql_min_word_len'] || utf8_strlen($text[$i]) > $config['fulltext_mysql_max_word_len'])
ef5584
			{
ef5584
				unset($text[$i]);
ef5584
			}
ef5584
		}
ef5584
ef5584
		return array_values($text);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Performs a search on keywords depending on display specific params. You have to run split_keywords() first.
ef5584
	*
ef5584
	* @param	string		$type				contains either posts or topics depending on what should be searched for
ef5584
	* @param	string		&$fields			contains either titleonly (topic titles should be searched), msgonly (only message bodies should be searched), firstpost (only subject and body of the first post should be searched) or all (all post bodies and subjects should be searched)
ef5584
	* @param	string		&$terms				is either 'all' (use query as entered, words without prefix should default to "have to be in field") or 'any' (ignore search query parts and just return all posts that contain any of the specified words)
ef5584
	* @param	array		&$sort_by_sql		contains SQL code for the ORDER BY part of a query
ef5584
	* @param	string		&$sort_key			is the key of $sort_by_sql for the selected sorting
ef5584
	* @param	string		&$sort_dir			is either a or d representing ASC and DESC
ef5584
	* @param	string		&$sort_days			specifies the maximum amount of days a post may be old
ef5584
	* @param	array		&$ex_fid_ary		specifies an array of forum ids which should not be searched
ef5584
	* @param	array		&$m_approve_fid_ary	specifies an array of forum ids in which the searcher is allowed to view unapproved posts
ef5584
	* @param	int			&$topic_id			is set to 0 or a topic id, if it is not 0 then only posts in this topic should be searched
ef5584
	* @param	array		&$author_ary		an array of author ids if the author should be ignored during the search the array is empty
ef5584
	* @param	array		&$id_ary			passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
ef5584
	* @param	int			$start				indicates the first index of the page
ef5584
	* @param	int			$per_page			number of ids each page is supposed to contain
ef5584
	* @return	boolean|int						total number of results
ef5584
	*
ef5584
	* @access	public
ef5584
	*/
ef5584
	function keyword_search($type, &$fields, &$terms, &$sort_by_sql, &$sort_key, &$sort_dir, &$sort_days, &$ex_fid_ary, &$m_approve_fid_ary, &$topic_id, &$author_ary, &$id_ary, $start, $per_page)
ef5584
	{
ef5584
		global $config, $db;
ef5584
ef5584
		// No keywords? No posts.
ef5584
		if (!$this->search_query)
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
ef5584
		// generate a search_key from all the options to identify the results
ef5584
		$search_key = md5(implode('#', array(
ef5584
			implode(', ', $this->split_words),
ef5584
			$type,
ef5584
			$fields,
ef5584
			$terms,
ef5584
			$sort_days,
ef5584
			$sort_key,
ef5584
			$topic_id,
ef5584
			implode(',', $ex_fid_ary),
ef5584
			implode(',', $m_approve_fid_ary),
ef5584
			implode(',', $author_ary)
ef5584
		)));
ef5584
ef5584
		// try reading the results from cache
ef5584
		$result_count = 0;
ef5584
		if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
ef5584
		{
ef5584
			return $result_count;
ef5584
		}
ef5584
ef5584
		$id_ary = array();
ef5584
ef5584
		$join_topic = ($type == 'posts') ? false : true;
ef5584
ef5584
		// Build sql strings for sorting
ef5584
		$sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
ef5584
		$sql_sort_table = $sql_sort_join = '';
ef5584
ef5584
		switch ($sql_sort[0])
ef5584
		{
ef5584
			case 'u':
ef5584
				$sql_sort_table	= USERS_TABLE . ' u, ';
ef5584
				$sql_sort_join	= ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
ef5584
			break;
ef5584
ef5584
			case 't':
ef5584
				$join_topic = true;
ef5584
			break;
ef5584
ef5584
			case 'f':
ef5584
				$sql_sort_table	= FORUMS_TABLE . ' f, ';
ef5584
				$sql_sort_join	= ' AND f.forum_id = p.forum_id ';
ef5584
			break;
ef5584
		}
ef5584
ef5584
		// Build some display specific sql strings
ef5584
		switch ($fields)
ef5584
		{
ef5584
			case 'titleonly':
ef5584
				$sql_match = 'p.post_subject';
ef5584
				$sql_match_where = ' AND p.post_id = t.topic_first_post_id';
ef5584
				$join_topic = true;
ef5584
			break;
ef5584
ef5584
			case 'msgonly':
ef5584
				$sql_match = 'p.post_text';
ef5584
				$sql_match_where = '';
ef5584
			break;
ef5584
ef5584
			case 'firstpost':
ef5584
				$sql_match = 'p.post_subject, p.post_text';
ef5584
				$sql_match_where = ' AND p.post_id = t.topic_first_post_id';
ef5584
				$join_topic = true;
ef5584
			break;
ef5584
ef5584
			default:
ef5584
				$sql_match = 'p.post_subject, p.post_text';
ef5584
				$sql_match_where = '';
ef5584
			break;
ef5584
		}
ef5584
ef5584
		if (!sizeof($m_approve_fid_ary))
ef5584
		{
ef5584
			$m_approve_fid_sql = ' AND p.post_approved = 1';
ef5584
		}
ef5584
		else if ($m_approve_fid_ary === array(-1))
ef5584
		{
ef5584
			$m_approve_fid_sql = '';
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$m_approve_fid_sql = ' AND (p.post_approved = 1 OR ' . $db->sql_in_set('p.forum_id', $m_approve_fid_ary, true) . ')';
ef5584
		}
ef5584
ef5584
		$sql_select			= (!$result_count) ? 'SQL_CALC_FOUND_ROWS ' : '';
ef5584
		$sql_select			= ($type == 'posts') ? $sql_select . 'p.post_id' : 'DISTINCT ' . $sql_select . 't.topic_id';
ef5584
		$sql_from			= ($join_topic) ? TOPICS_TABLE . ' t, ' : '';
ef5584
		$field				= ($type == 'posts') ? 'post_id' : 'topic_id';
ef5584
		$sql_author			= (sizeof($author_ary) == 1) ? ' = ' . $author_ary[0] : 'IN (' . implode(', ', $author_ary) . ')';
ef5584
ef5584
		$sql_where_options = $sql_sort_join;
ef5584
		$sql_where_options .= ($topic_id) ? ' AND p.topic_id = ' . $topic_id : '';
ef5584
		$sql_where_options .= ($join_topic) ? ' AND t.topic_id = p.topic_id' : '';
ef5584
		$sql_where_options .= (sizeof($ex_fid_ary)) ? ' AND ' . $db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
ef5584
		$sql_where_options .= $m_approve_fid_sql;
ef5584
		$sql_where_options .= (sizeof($author_ary)) ? ' AND p.poster_id ' . $sql_author : '';
ef5584
		$sql_where_options .= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
ef5584
		$sql_where_options .= $sql_match_where;
ef5584
ef5584
		$sql = "SELECT $sql_select
ef5584
			FROM $sql_from$sql_sort_table" . POSTS_TABLE . " p
ef5584
			WHERE MATCH ($sql_match) AGAINST ('" . $db->sql_escape(htmlspecialchars_decode($this->search_query)) . "' IN BOOLEAN MODE)
ef5584
				$sql_where_options
ef5584
			ORDER BY $sql_sort";
ef5584
		$result = $db->sql_query_limit($sql, $config['search_block_size'], $start);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$id_ary[] = $row[$field];
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$id_ary = array_unique($id_ary);
ef5584
ef5584
		if (!sizeof($id_ary))
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
ef5584
		// if the total result count is not cached yet, retrieve it from the db
ef5584
		if (!$result_count)
ef5584
		{
ef5584
			$sql = 'SELECT FOUND_ROWS() as result_count';
ef5584
			$result = $db->sql_query($sql);
ef5584
			$result_count = (int) $db->sql_fetchfield('result_count');
ef5584
			$db->sql_freeresult($result);
ef5584
ef5584
			if (!$result_count)
ef5584
			{
ef5584
				return false;
ef5584
			}
ef5584
		}
ef5584
ef5584
		// store the ids, from start on then delete anything that isn't on the current page because we only need ids for one page
ef5584
		$this->save_ids($search_key, implode(' ', $this->split_words), $author_ary, $result_count, $id_ary, $start, $sort_dir);
ef5584
		$id_ary = array_slice($id_ary, 0, (int) $per_page);
ef5584
ef5584
		return $result_count;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Performs a search on an author's posts without caring about message contents. Depends on display specific params
ef5584
	*
ef5584
	* @param array &$id_ary passed by reference, to be filled with ids for the page specified by $start and $per_page, should be ordered
ef5584
	* @param int $start indicates the first index of the page
ef5584
	* @param int $per_page number of ids each page is supposed to contain
ef5584
	* @return total number of results
ef5584
	*/
ef5584
	function author_search($type, $firstpost_only, &$sort_by_sql, &$sort_key, &$sort_dir, &$sort_days, &$ex_fid_ary, &$m_approve_fid_ary, &$topic_id, &$author_ary, &$id_ary, $start, $per_page)
ef5584
	{
ef5584
		global $config, $db;
ef5584
ef5584
		// No author? No posts.
ef5584
		if (!sizeof($author_ary))
ef5584
		{
ef5584
			return 0;
ef5584
		}
ef5584
ef5584
		// generate a search_key from all the options to identify the results
ef5584
		$search_key = md5(implode('#', array(
ef5584
			'',
ef5584
			$type,
ef5584
			($firstpost_only) ? 'firstpost' : '',
ef5584
			'',
ef5584
			'',
ef5584
			$sort_days,
ef5584
			$sort_key,
ef5584
			$topic_id,
ef5584
			implode(',', $ex_fid_ary),
ef5584
			implode(',', $m_approve_fid_ary),
ef5584
			implode(',', $author_ary)
ef5584
		)));
ef5584
ef5584
		// try reading the results from cache
ef5584
		$result_count = 0;
ef5584
		if ($this->obtain_ids($search_key, $result_count, $id_ary, $start, $per_page, $sort_dir) == SEARCH_RESULT_IN_CACHE)
ef5584
		{
ef5584
			return $result_count;
ef5584
		}
ef5584
ef5584
		$id_ary = array();
ef5584
ef5584
		// Create some display specific sql strings
ef5584
		$sql_author		= $db->sql_in_set('p.poster_id', $author_ary);
ef5584
		$sql_fora		= (sizeof($ex_fid_ary)) ? ' AND ' . $db->sql_in_set('p.forum_id', $ex_fid_ary, true) : '';
ef5584
		$sql_topic_id	= ($topic_id) ? ' AND p.topic_id = ' . (int) $topic_id : '';
ef5584
		$sql_time		= ($sort_days) ? ' AND p.post_time >= ' . (time() - ($sort_days * 86400)) : '';
ef5584
		$sql_firstpost = ($firstpost_only) ? ' AND p.post_id = t.topic_first_post_id' : '';
ef5584
ef5584
		// Build sql strings for sorting
ef5584
		$sql_sort = $sort_by_sql[$sort_key] . (($sort_dir == 'a') ? ' ASC' : ' DESC');
ef5584
		$sql_sort_table = $sql_sort_join = '';
ef5584
		switch ($sql_sort[0])
ef5584
		{
ef5584
			case 'u':
ef5584
				$sql_sort_table	= USERS_TABLE . ' u, ';
ef5584
				$sql_sort_join	= ($type == 'posts') ? ' AND u.user_id = p.poster_id ' : ' AND u.user_id = t.topic_poster ';
ef5584
			break;
ef5584
ef5584
			case 't':
ef5584
				$sql_sort_table	= ($type == 'posts' && !$firstpost_only) ? TOPICS_TABLE . ' t, ' : '';
ef5584
				$sql_sort_join	= ($type == 'posts' && !$firstpost_only) ? ' AND t.topic_id = p.topic_id ' : '';
ef5584
			break;
ef5584
ef5584
			case 'f':
ef5584
				$sql_sort_table	= FORUMS_TABLE . ' f, ';
ef5584
				$sql_sort_join	= ' AND f.forum_id = p.forum_id ';
ef5584
			break;
ef5584
		}
ef5584
ef5584
		if (!sizeof($m_approve_fid_ary))
ef5584
		{
ef5584
			$m_approve_fid_sql = ' AND p.post_approved = 1';
ef5584
		}
ef5584
		else if ($m_approve_fid_ary == array(-1))
ef5584
		{
ef5584
			$m_approve_fid_sql = '';
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$m_approve_fid_sql = ' AND (p.post_approved = 1 OR ' . $db->sql_in_set('p.forum_id', $m_approve_fid_ary, true) . ')';
ef5584
		}
ef5584
ef5584
		// If the cache was completely empty count the results
ef5584
		$calc_results = ($result_count) ? '' : 'SQL_CALC_FOUND_ROWS ';
ef5584
ef5584
		// Build the query for really selecting the post_ids
ef5584
		if ($type == 'posts')
ef5584
		{
ef5584
			$sql = "SELECT {$calc_results}p.post_id
ef5584
				FROM " . $sql_sort_table . POSTS_TABLE . ' p' . (($firstpost_only) ? ', ' . TOPICS_TABLE . ' t ' : ' ') . "
ef5584
				WHERE $sql_author
ef5584
					$sql_topic_id
ef5584
					$sql_firstpost
ef5584
					$m_approve_fid_sql
ef5584
					$sql_fora
ef5584
					$sql_sort_join
ef5584
					$sql_time
ef5584
				ORDER BY $sql_sort";
ef5584
			$field = 'post_id';
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$sql = "SELECT {$calc_results}t.topic_id
ef5584
				FROM " . $sql_sort_table . TOPICS_TABLE . ' t, ' . POSTS_TABLE . " p
ef5584
				WHERE $sql_author
ef5584
					$sql_topic_id
ef5584
					$sql_firstpost
ef5584
					$m_approve_fid_sql
ef5584
					$sql_fora
ef5584
					AND t.topic_id = p.topic_id
ef5584
					$sql_sort_join
ef5584
					$sql_time
ef5584
				GROUP BY t.topic_id
ef5584
				ORDER BY $sql_sort";
ef5584
			$field = 'topic_id';
ef5584
		}
ef5584
ef5584
		// Only read one block of posts from the db and then cache it
ef5584
		$result = $db->sql_query_limit($sql, $config['search_block_size'], $start);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			$id_ary[] = $row[$field];
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		// retrieve the total result count if needed
ef5584
		if (!$result_count)
ef5584
		{
ef5584
			$sql = 'SELECT FOUND_ROWS() as result_count';
ef5584
			$result = $db->sql_query($sql);
ef5584
			$result_count = (int) $db->sql_fetchfield('result_count');
ef5584
			$db->sql_freeresult($result);
ef5584
ef5584
			if (!$result_count)
ef5584
			{
ef5584
				return false;
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (sizeof($id_ary))
ef5584
		{
ef5584
			$this->save_ids($search_key, '', $author_ary, $result_count, $id_ary, $start, $sort_dir);
ef5584
			$id_ary = array_slice($id_ary, 0, $per_page);
ef5584
ef5584
			return $result_count;
ef5584
		}
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Destroys cached search results, that contained one of the new words in a post so the results won't be outdated.
ef5584
	*
ef5584
	* @param string $mode contains the post mode: edit, post, reply, quote ...
ef5584
	*/
ef5584
	function index($mode, $post_id, &$message, &$subject, $poster_id, $forum_id)
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		// Split old and new post/subject to obtain array of words
ef5584
		$split_text = $this->split_message($message);
ef5584
		$split_title = ($subject) ? $this->split_message($subject) : array();
ef5584
ef5584
		$words = array_unique(array_merge($split_text, $split_title));
ef5584
ef5584
		unset($split_text);
ef5584
		unset($split_title);
ef5584
ef5584
		// destroy cached search results containing any of the words removed or added
ef5584
		$this->destroy_cache($words, array($poster_id));
ef5584
ef5584
		unset($words);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Destroy cached results, that might be outdated after deleting a post
ef5584
	*/
ef5584
	function index_remove($post_ids, $author_ids, $forum_ids)
ef5584
	{
ef5584
		$this->destroy_cache(array(), $author_ids);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Destroy old cache entries
ef5584
	*/
ef5584
	function tidy()
ef5584
	{
ef5584
		global $db, $config;
ef5584
ef5584
		// destroy too old cached search results
ef5584
		$this->destroy_cache(array());
ef5584
ef5584
		set_config('search_last_gc', time(), true);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Create fulltext index
ef5584
	*/
ef5584
	function create_index($acp_module, $u_action)
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		// Make sure we can actually use MySQL with fulltext indexes
ef5584
		if ($error = $this->init())
ef5584
		{
ef5584
			return $error;
ef5584
		}
ef5584
ef5584
		if (empty($this->stats))
ef5584
		{
ef5584
			$this->get_stats();
ef5584
		}
ef5584
ef5584
		$alter = array();
ef5584
ef5584
		if (!isset($this->stats['post_subject']))
ef5584
		{
ef5584
			if ($db->sql_layer == 'mysqli' || version_compare($db->sql_server_info(true), '4.1.3', '>='))
ef5584
			{
ef5584
				//$alter[] = 'MODIFY post_subject varchar(100) COLLATE utf8_unicode_ci DEFAULT \'\' NOT NULL';
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$alter[] = 'MODIFY post_subject text NOT NULL';
ef5584
			}
ef5584
			$alter[] = 'ADD FULLTEXT (post_subject)';
ef5584
		}
ef5584
ef5584
		if (!isset($this->stats['post_text']))
ef5584
		{
ef5584
			if ($db->sql_layer == 'mysqli' || version_compare($db->sql_server_info(true), '4.1.3', '>='))
ef5584
			{
ef5584
				$alter[] = 'MODIFY post_text mediumtext COLLATE utf8_unicode_ci NOT NULL';
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$alter[] = 'MODIFY post_text mediumtext NOT NULL';
ef5584
			}
ef5584
			$alter[] = 'ADD FULLTEXT (post_text)';
ef5584
		}
ef5584
ef5584
		if (!isset($this->stats['post_content']))
ef5584
		{
ef5584
			$alter[] = 'ADD FULLTEXT post_content (post_subject, post_text)';
ef5584
		}
ef5584
ef5584
		if (sizeof($alter))
ef5584
		{
ef5584
			$db->sql_query('ALTER TABLE ' . POSTS_TABLE . ' ' . implode(', ', $alter));
ef5584
		}
ef5584
ef5584
		$db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
ef5584
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Drop fulltext index
ef5584
	*/
ef5584
	function delete_index($acp_module, $u_action)
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		// Make sure we can actually use MySQL with fulltext indexes
ef5584
		if ($error = $this->init())
ef5584
		{
ef5584
			return $error;
ef5584
		}
ef5584
ef5584
		if (empty($this->stats))
ef5584
		{
ef5584
			$this->get_stats();
ef5584
		}
ef5584
ef5584
		$alter = array();
ef5584
ef5584
		if (isset($this->stats['post_subject']))
ef5584
		{
ef5584
			$alter[] = 'DROP INDEX post_subject';
ef5584
		}
ef5584
ef5584
		if (isset($this->stats['post_text']))
ef5584
		{
ef5584
			$alter[] = 'DROP INDEX post_text';
ef5584
		}
ef5584
ef5584
		if (isset($this->stats['post_content']))
ef5584
		{
ef5584
			$alter[] = 'DROP INDEX post_content';
ef5584
		}
ef5584
ef5584
		if (sizeof($alter))
ef5584
		{
ef5584
			$db->sql_query('ALTER TABLE ' . POSTS_TABLE . ' ' . implode(', ', $alter));
ef5584
		}
ef5584
ef5584
		$db->sql_query('TRUNCATE TABLE ' . SEARCH_RESULTS_TABLE);
ef5584
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Returns true if both FULLTEXT indexes exist
ef5584
	*/
ef5584
	function index_created()
ef5584
	{
ef5584
		if (empty($this->stats))
ef5584
		{
ef5584
			$this->get_stats();
ef5584
		}
ef5584
ef5584
		return (isset($this->stats['post_text']) && isset($this->stats['post_subject']) && isset($this->stats['post_content'])) ? true : false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Returns an associative array containing information about the indexes
ef5584
	*/
ef5584
	function index_stats()
ef5584
	{
ef5584
		global $user;
ef5584
ef5584
		if (empty($this->stats))
ef5584
		{
ef5584
			$this->get_stats();
ef5584
		}
ef5584
ef5584
		return array(
ef5584
			$user->lang['FULLTEXT_MYSQL_TOTAL_POSTS']			=> ($this->index_created()) ? $this->stats['total_posts'] : 0,
ef5584
		);
ef5584
	}
ef5584
ef5584
	function get_stats()
ef5584
	{
ef5584
		global $db;
ef5584
ef5584
		if (strpos($db->sql_layer, 'mysql') === false)
ef5584
		{
ef5584
			$this->stats = array();
ef5584
			return;
ef5584
		}
ef5584
ef5584
		$sql = 'SHOW INDEX
ef5584
			FROM ' . POSTS_TABLE;
ef5584
		$result = $db->sql_query($sql);
ef5584
ef5584
		while ($row = $db->sql_fetchrow($result))
ef5584
		{
ef5584
			// deal with older MySQL versions which didn't use Index_type
ef5584
			$index_type = (isset($row['Index_type'])) ? $row['Index_type'] : $row['Comment'];
ef5584
ef5584
			if ($index_type == 'FULLTEXT')
ef5584
			{
ef5584
				if ($row['Key_name'] == 'post_text')
ef5584
				{
ef5584
					$this->stats['post_text'] = $row;
ef5584
				}
ef5584
				else if ($row['Key_name'] == 'post_subject')
ef5584
				{
ef5584
					$this->stats['post_subject'] = $row;
ef5584
				}
ef5584
				else if ($row['Key_name'] == 'post_content')
ef5584
				{
ef5584
					$this->stats['post_content'] = $row;
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
		$db->sql_freeresult($result);
ef5584
ef5584
		$sql = 'SELECT COUNT(post_id) as total_posts
ef5584
			FROM ' . POSTS_TABLE;
ef5584
		$result = $db->sql_query($sql);
ef5584
		$this->stats['total_posts'] = (int) $db->sql_fetchfield('total_posts');
ef5584
		$db->sql_freeresult($result);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Display a note, that UTF-8 support is not available with certain versions of PHP
ef5584
	*/
ef5584
	function acp()
ef5584
	{
ef5584
		global $user, $config;
ef5584
ef5584
		$tpl = '
ef5584
		
ef5584
			
<label>' . $user->lang['FULLTEXT_MYSQL_PCRE'] . '</label>
' . $user->lang['FULLTEXT_MYSQL_PCRE_EXPLAIN'] . '
ef5584
			
' . (($this->pcre_properties) ? $user->lang['YES'] : $user->lang['NO']) . ' (PHP ' . PHP_VERSION . ')
ef5584
		
ef5584
		
ef5584
			
<label>' . $user->lang['FULLTEXT_MYSQL_MBSTRING'] . '</label>
' . $user->lang['FULLTEXT_MYSQL_MBSTRING_EXPLAIN'] . '
ef5584
			
' . (($this->mbstring_regex) ? $user->lang['YES'] : $user->lang['NO']). '
ef5584
		
ef5584
		';
ef5584
ef5584
		// These are fields required in the config table
ef5584
		return array(
ef5584
			'tpl'		=> $tpl,
ef5584
			'config'	=> array()
ef5584
		);
ef5584
	}
ef5584
}
ef5584
ef5584
?>