SearchAPI-Fulltext.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.1 Alpha 1
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. class fulltext_search
  15. {
  16. // This is the last version of SMF that this was tested on, to protect against API changes.
  17. public $version_compatible = 'SMF 2.1 Alpha 1';
  18. // This won't work with versions of SMF less than this.
  19. public $min_smf_version = 'SMF 2.1 Alpha 1';
  20. // Is it supported?
  21. public $is_supported = true;
  22. // Can we do a boolean search - tested on construct.
  23. protected $canDoBooleanSearch = false;
  24. // What words are banned?
  25. protected $bannedWords = array();
  26. // What is the minimum word length?
  27. protected $min_word_length = 4;
  28. // What databases support the fulltext index?
  29. protected $supported_databases = array('mysql');
  30. public function __construct()
  31. {
  32. global $smcFunc, $db_connection, $modSettings, $db_type;
  33. // Is this database supported?
  34. if (!in_array($db_type, $this->supported_databases))
  35. {
  36. $this->is_supported = false;
  37. return;
  38. }
  39. // Some MySQL versions are superior to others :P.
  40. $this->canDoBooleanSearch = version_compare($smcFunc['db_server_info']($db_connection), '4.0.1', '>=');
  41. $this->bannedWords = empty($modSettings['search_banned_words']) ? array() : explode(',', $modSettings['search_banned_words']);
  42. $this->min_word_length = $this->_getMinWordLength();
  43. }
  44. // Check whether the method can be performed by this API.
  45. public function supportsMethod($methodName, $query_params = null)
  46. {
  47. switch ($methodName)
  48. {
  49. case 'searchSort':
  50. case 'prepareIndexes':
  51. case 'indexedWordQuery':
  52. return true;
  53. break;
  54. // All other methods, too bad dunno you.
  55. default:
  56. return false;
  57. break;
  58. }
  59. }
  60. // What is the minimum word length full text supports?
  61. protected function _getMinWordLength()
  62. {
  63. global $smcFunc;
  64. // Try to determine the minimum number of letters for a fulltext search.
  65. $request = $smcFunc['db_search_query']('max_fulltext_length', '
  66. SHOW VARIABLES
  67. LIKE {string:fulltext_minimum_word_length}',
  68. array(
  69. 'fulltext_minimum_word_length' => 'ft_min_word_len',
  70. )
  71. );
  72. if ($request !== false && $smcFunc['db_num_rows']($request) == 1)
  73. {
  74. list (, $min_word_length) = $smcFunc['db_fetch_row']($request);
  75. $smcFunc['db_free_result']($request);
  76. }
  77. // 4 is the MySQL default...
  78. else
  79. $min_word_length = 4;
  80. return $min_word_length;
  81. }
  82. /**
  83. * callback function for usort used to sort the fulltext results.
  84. * the order of sorting is: large words, small words, large words that
  85. * are excluded from the search, small words that are excluded.
  86. * @param string $a Word A
  87. * @param string $b Word B
  88. * @return int
  89. */
  90. public function searchSort($a, $b)
  91. {
  92. global $modSettings, $excludedWords;
  93. $x = strlen($a) - (in_array($a, $excludedWords) ? 1000 : 0);
  94. $y = strlen($b) - (in_array($b, $excludedWords) ? 1000 : 0);
  95. return $x < $y ? 1 : ($x > $y ? -1 : 0);
  96. }
  97. // Do we have to do some work with the words we are searching for to prepare them?
  98. public function prepareIndexes($word, &$wordsSearch, &$wordsExclude, $isExcluded)
  99. {
  100. global $modSettings, $smcFunc;
  101. $subwords = text2words($word, null, false);
  102. if (!$this->canDoBooleanSearch && count($subwords) > 1 && empty($modSettings['search_force_index']))
  103. $wordsSearch['words'][] = $word;
  104. elseif (empty($modSettings['search_force_index']) && $this->canDoBooleanSearch)
  105. {
  106. // A boolean capable search engine and not forced to only use an index, we may use a non index search
  107. // this is harder on the server so we are restrictive here
  108. if (count($subwords) > 1 && preg_match('~[.:@$]~', $word))
  109. {
  110. // using special characters that a full index would ignore and the remaining words are short which would also be ignored
  111. if (($smcFunc['strlen'](current($subwords)) < $this->min_word_length) && ($smcFunc['strlen'](next($subwords)) < $this->min_word_length))
  112. {
  113. $wordsSearch['words'][] = trim($word, "/*- ");
  114. $wordsSearch['complex_words'][] = count($subwords) === 1 ? $word : '"' . $word . '"';
  115. }
  116. }
  117. elseif ($smcFunc['strlen'](trim($word, "/*- ")) < $this->min_word_length)
  118. {
  119. // short words have feelings too
  120. $wordsSearch['words'][] = trim($word, "/*- ");
  121. $wordsSearch['complex_words'][] = count($subwords) === 1 ? $word : '"' . $word . '"';
  122. }
  123. }
  124. if ($this->canDoBooleanSearch)
  125. {
  126. $fulltextWord = count($subwords) === 1 ? $word : '"' . $word . '"';
  127. $wordsSearch['indexed_words'][] = $fulltextWord;
  128. if ($isExcluded)
  129. $wordsExclude[] = $fulltextWord;
  130. }
  131. // Excluded phrases don't benefit from being split into subwords.
  132. elseif (count($subwords) > 1 && $isExcluded)
  133. return;
  134. else
  135. {
  136. $relyOnIndex = true;
  137. foreach ($subwords as $subword)
  138. {
  139. if (($smcFunc['strlen']($subword) >= $this->min_word_length) && !in_array($subword, $this->bannedWords))
  140. {
  141. $wordsSearch['indexed_words'][] = $subword;
  142. if ($isExcluded)
  143. $wordsExclude[] = $subword;
  144. }
  145. elseif (!in_array($subword, $this->bannedWords))
  146. $relyOnIndex = false;
  147. }
  148. if ($this->canDoBooleanSearch && !$relyOnIndex && empty($modSettings['search_force_index']))
  149. $wordsSearch['words'][] = $word;
  150. }
  151. }
  152. // Search for indexed words.
  153. public function indexedWordQuery($words, $search_data)
  154. {
  155. global $modSettings, $smcFunc;
  156. $query_select = array(
  157. 'id_msg' => 'm.id_msg',
  158. );
  159. $query_where = array();
  160. $query_params = $search_data['params'];
  161. if ($query_params['id_search'])
  162. $query_select['id_search'] = '{int:id_search}';
  163. $count = 0;
  164. if (empty($modSettings['search_simple_fulltext']))
  165. foreach ($words['words'] as $regularWord)
  166. {
  167. $query_where[] = 'm.body' . (in_array($regularWord, $query_params['excluded_words']) ? ' NOT' : '') . (empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? ' LIKE ' : 'RLIKE') . '{string:complex_body_' . $count . '}';
  168. $query_params['complex_body_' . $count++] = empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? '%' . strtr($regularWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $regularWord), '\\\'') . '[[:>:]]';
  169. }
  170. if ($query_params['user_query'])
  171. $query_where[] = '{raw:user_query}';
  172. if ($query_params['board_query'])
  173. $query_where[] = 'm.id_board {raw:board_query}';
  174. if ($query_params['topic'])
  175. $query_where[] = 'm.id_topic = {int:topic}';
  176. if ($query_params['min_msg_id'])
  177. $query_where[] = 'm.id_msg >= {int:min_msg_id}';
  178. if ($query_params['max_msg_id'])
  179. $query_where[] = 'm.id_msg <= {int:max_msg_id}';
  180. $count = 0;
  181. if (!empty($query_params['excluded_phrases']) && empty($modSettings['search_force_index']))
  182. foreach ($query_params['excluded_phrases'] as $phrase)
  183. {
  184. $query_where[] = 'subject NOT ' . (empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? ' LIKE ' : 'RLIKE') . '{string:exclude_subject_phrase_' . $count . '}';
  185. $query_params['exclude_subject_phrase_' . $count++] = empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? '%' . strtr($phrase, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $phrase), '\\\'') . '[[:>:]]';
  186. }
  187. $count = 0;
  188. if (!empty($query_params['excluded_subject_words']) && empty($modSettings['search_force_index']))
  189. foreach ($query_params['excluded_subject_words'] as $excludedWord)
  190. {
  191. $query_where[] = 'subject NOT ' . (empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? ' LIKE ' : 'RLIKE') . '{string:exclude_subject_words_' . $count . '}';
  192. $query_params['exclude_subject_words_' . $count++] = empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? '%' . strtr($excludedWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $excludedWord), '\\\'') . '[[:>:]]';
  193. }
  194. if (!empty($modSettings['search_simple_fulltext']))
  195. {
  196. $query_where[] = 'MATCH (body) AGAINST ({string:body_match})';
  197. $query_params['body_match'] = implode(' ', array_diff($words['indexed_words'], $query_params['excluded_index_words']));
  198. }
  199. elseif ($this->canDoBooleanSearch)
  200. {
  201. $query_params['boolean_match'] = '';
  202. // remove any indexed words that are used in the complex body search terms
  203. $words['indexed_words'] = array_diff($words['indexed_words'], $words['complex_words']);
  204. foreach ($words['indexed_words'] as $fulltextWord)
  205. $query_params['boolean_match'] .= (in_array($fulltextWord, $query_params['excluded_index_words']) ? '-' : '+') . $fulltextWord . ' ';
  206. $query_params['boolean_match'] = substr($query_params['boolean_match'], 0, -1);
  207. // if we have bool terms to search, add them in
  208. if ($query_params['boolean_match'])
  209. $query_where[] = 'MATCH (body) AGAINST ({string:boolean_match} IN BOOLEAN MODE)';
  210. }
  211. else
  212. {
  213. $count = 0;
  214. foreach ($words['indexed_words'] as $fulltextWord)
  215. {
  216. $query_where[] = (in_array($fulltextWord, $query_params['excluded_index_words']) ? 'NOT ' : '') . 'MATCH (body) AGAINST ({string:fulltext_match_' . $count . '})';
  217. $query_params['fulltext_match_' . $count++] = $fulltextWord;
  218. }
  219. }
  220. $ignoreRequest = $smcFunc['db_search_query']('insert_into_log_messages_fulltext', ($smcFunc['db_support_ignore'] ? ( '
  221. INSERT IGNORE INTO {db_prefix}' . $search_data['insert_into'] . '
  222. (' . implode(', ', array_keys($query_select)) . ')') : '') . '
  223. SELECT ' . implode(', ', $query_select) . '
  224. FROM {db_prefix}messages AS m
  225. WHERE ' . implode('
  226. AND ', $query_where) . (empty($search_data['max_results']) ? '' : '
  227. LIMIT ' . ($search_data['max_results'] - $search_data['indexed_results'])),
  228. $query_params
  229. );
  230. return $ignoreRequest;
  231. }
  232. }
  233. ?>