SearchAPI-Fulltext.php 8.9 KB

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