SearchAPI-Custom.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. /*
  15. int searchSort(string $wordA, string $wordB)
  16. - callback function for usort used to sort the fulltext results.
  17. - the order of sorting is: large words, small words, large words that
  18. are excluded from the search, small words that are excluded.
  19. */
  20. class custom_search
  21. {
  22. // This is the last version of SMF that this was tested on, to protect against API changes.
  23. public $version_compatible = 'SMF 2.1 Alpha 1';
  24. // This won't work with versions of SMF less than this.
  25. public $min_smf_version = 'SMF 2.1 Alpha 1';
  26. // Is it supported?
  27. public $is_supported = true;
  28. protected $indexSettings = array();
  29. // What words are banned?
  30. protected $bannedWords = array();
  31. // What is the minimum word length?
  32. protected $min_word_length = null;
  33. // What databases support the custom index?
  34. protected $supported_databases = array('mysql', 'postgresql', 'sqlite');
  35. public function __construct()
  36. {
  37. global $modSettings, $db_type;
  38. // Is this database supported?
  39. if (!in_array($db_type, $this->supported_databases))
  40. {
  41. $this->is_supported = false;
  42. return;
  43. }
  44. if (empty($modSettings['search_custom_index_config']))
  45. return;
  46. $this->indexSettings = unserialize($modSettings['search_custom_index_config']);
  47. $this->bannedWords = empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']);
  48. $this->min_word_length = $this->indexSettings['bytes_per_word'];
  49. }
  50. // Check whether the search can be performed by this API.
  51. public function supportsMethod($methodName, $query_params = null)
  52. {
  53. switch ($methodName)
  54. {
  55. case 'isValid':
  56. case 'searchSort':
  57. case 'prepareIndexes':
  58. case 'indexedWordQuery':
  59. case 'postCreated':
  60. case 'postModified':
  61. return true;
  62. break;
  63. // All other methods, too bad dunno you.
  64. default:
  65. return false;
  66. return;
  67. }
  68. }
  69. // If the settings don't exist we can't continue.
  70. public function isValid()
  71. {
  72. global $modSettings;
  73. return !empty($modSettings['search_custom_index_config']);
  74. }
  75. // This function compares the length of two strings plus a little.
  76. public function searchSort($a, $b)
  77. {
  78. global $modSettings, $excludedWords;
  79. $x = strlen($a) - (in_array($a, $excludedWords) ? 1000 : 0);
  80. $y = strlen($b) - (in_array($b, $excludedWords) ? 1000 : 0);
  81. return $y < $x ? 1 : ($y > $x ? -1 : 0);
  82. }
  83. // Do we have to do some work with the words we are searching for to prepare them?
  84. public function prepareIndexes($word, &$wordsSearch, &$wordsExclude, $isExcluded)
  85. {
  86. global $modSettings, $smcFunc;
  87. $subwords = text2words($word, $this->min_word_length, true);
  88. if (empty($modSettings['search_force_index']))
  89. $wordsSearch['words'][] = $word;
  90. // Excluded phrases don't benefit from being split into subwords.
  91. if (count($subwords) > 1 && $isExcluded)
  92. continue;
  93. else
  94. {
  95. foreach ($subwords as $subword)
  96. {
  97. if ($smcFunc['strlen']($subword) >= $this->min_word_length && !in_array($subword, $this->bannedWords))
  98. {
  99. $wordsSearch['indexed_words'][] = $subword;
  100. if ($isExcluded)
  101. $wordsExclude[] = $subword;
  102. }
  103. }
  104. }
  105. }
  106. // Search for indexed words.
  107. public function indexedWordQuery($words, $search_data)
  108. {
  109. global $modSettings, $smcFunc;
  110. $query_select = array(
  111. 'id_msg' => 'm.id_msg',
  112. );
  113. $query_inner_join = array();
  114. $query_left_join = array();
  115. $query_where = array();
  116. $query_params = $search_data['params'];
  117. if ($query_params['id_search'])
  118. $query_select['id_search'] = '{int:id_search}';
  119. $count = 0;
  120. foreach ($words['words'] as $regularWord)
  121. {
  122. $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 . '}';
  123. $query_params['complex_body_' . $count++] = empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? '%' . strtr($regularWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $regularWord), '\\\'') . '[[:>:]]';
  124. }
  125. if ($query_params['user_query'])
  126. $query_where[] = '{raw:user_query}';
  127. if ($query_params['board_query'])
  128. $query_where[] = 'm.id_board {raw:board_query}';
  129. if ($query_params['topic'])
  130. $query_where[] = 'm.id_topic = {int:topic}';
  131. if ($query_params['min_msg_id'])
  132. $query_where[] = 'm.id_msg >= {int:min_msg_id}';
  133. if ($query_params['max_msg_id'])
  134. $query_where[] = 'm.id_msg <= {int:max_msg_id}';
  135. $count = 0;
  136. if (!empty($query_params['excluded_phrases']) && empty($modSettings['search_force_index']))
  137. foreach ($query_params['excluded_phrases'] as $phrase)
  138. {
  139. $query_where[] = 'subject NOT ' . (empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? ' LIKE ' : ' RLIKE ') . '{string:exclude_subject_phrase_' . $count . '}';
  140. $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), '\\\'') . '[[:>:]]';
  141. }
  142. $count = 0;
  143. if (!empty($query_params['excluded_subject_words']) && empty($modSettings['search_force_index']))
  144. foreach ($query_params['excluded_subject_words'] as $excludedWord)
  145. {
  146. $query_where[] = 'subject NOT ' . (empty($modSettings['search_match_words']) || $search_data['no_regexp'] ? ' LIKE ' : ' RLIKE ') . '{string:exclude_subject_words_' . $count . '}';
  147. $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), '\\\'') . '[[:>:]]';
  148. }
  149. $numTables = 0;
  150. $prev_join = 0;
  151. foreach ($words['indexed_words'] as $indexedWord)
  152. {
  153. $numTables++;
  154. if (in_array($indexedWord, $query_params['excluded_index_words']))
  155. {
  156. $query_left_join[] = '{db_prefix}log_search_words AS lsw' . $numTables . ' ON (lsw' . $numTables . '.id_word = ' . $indexedWord . ' AND lsw' . $numTables . '.id_msg = m.id_msg)';
  157. $query_where[] = '(lsw' . $numTables . '.id_word IS NULL)';
  158. }
  159. else
  160. {
  161. $query_inner_join[] = '{db_prefix}log_search_words AS lsw' . $numTables . ' ON (lsw' . $numTables . '.id_msg = ' . ($prev_join === 0 ? 'm' : 'lsw' . $prev_join) . '.id_msg)';
  162. $query_where[] = 'lsw' . $numTables . '.id_word = ' . $indexedWord;
  163. $prev_join = $numTables;
  164. }
  165. }
  166. $ignoreRequest = $smcFunc['db_search_query']('insert_into_log_messages_fulltext', ($smcFunc['db_support_ignore'] ? ( '
  167. INSERT IGNORE INTO {db_prefix}' . $search_data['insert_into'] . '
  168. (' . implode(', ', array_keys($query_select)) . ')') : '') . '
  169. SELECT ' . implode(', ', $query_select) . '
  170. FROM {db_prefix}messages AS m' . (empty($query_inner_join) ? '' : '
  171. INNER JOIN ' . implode('
  172. INNER JOIN ', $query_inner_join)) . (empty($query_left_join) ? '' : '
  173. LEFT JOIN ' . implode('
  174. LEFT JOIN ', $query_left_join)) . '
  175. WHERE ' . implode('
  176. AND ', $query_where) . (empty($search_data['max_results']) ? '' : '
  177. LIMIT ' . ($search_data['max_results'] - $search_data['indexed_results'])),
  178. $query_params
  179. );
  180. return $ignoreRequest;
  181. }
  182. /*
  183. * After a post is made, we update the database.
  184. */
  185. public function postCreated($msgOptions, $topicOptions, $posterOptions)
  186. {
  187. global $modSettings, $smcFunc;
  188. $customIndexSettings = unserialize($modSettings['search_custom_index_config']);
  189. $inserts = array();
  190. foreach (text2words($msgOptions['body'], $customIndexSettings['bytes_per_word'], true) as $word)
  191. $inserts[] = array($word, $msgOptions['id']);
  192. if (!empty($inserts))
  193. $smcFunc['db_insert']('ignore',
  194. '{db_prefix}log_search_words',
  195. array('id_word' => 'int', 'id_msg' => 'int'),
  196. $inserts,
  197. array('id_word', 'id_msg')
  198. );
  199. }
  200. /*
  201. * After a post is modified, we update the database.
  202. */
  203. public function postModified($msgOptions, $topicOptions, $posterOptions)
  204. {
  205. global $modSettings, $smcFunc;
  206. $customIndexSettings = unserialize($modSettings['search_custom_index_config']);
  207. $stopwords = empty($modSettings['search_stopwords']) ? array() : explode(',', $modSettings['search_stopwords']);
  208. $old_index = text2words($old_body, $customIndexSettings['bytes_per_word'], true);
  209. $new_index = text2words($msgOptions['body'], $customIndexSettings['bytes_per_word'], true);
  210. // Calculate the words to be added and removed from the index.
  211. $removed_words = array_diff(array_diff($old_index, $new_index), $stopwords);
  212. $inserted_words = array_diff(array_diff($new_index, $old_index), $stopwords);
  213. // Delete the removed words AND the added ones to avoid key constraints.
  214. if (!empty($removed_words))
  215. {
  216. $removed_words = array_merge($removed_words, $inserted_words);
  217. $smcFunc['db_query']('', '
  218. DELETE FROM {db_prefix}log_search_words
  219. WHERE id_msg = {int:id_msg}
  220. AND id_word IN ({array_int:removed_words})',
  221. array(
  222. 'removed_words' => $removed_words,
  223. 'id_msg' => $msgOptions['id'],
  224. )
  225. );
  226. }
  227. // Add the new words to be indexed.
  228. if (!empty($inserted_words))
  229. {
  230. $inserts = array();
  231. foreach ($inserted_words as $word)
  232. $inserts[] = array($word, $msgOptions['id']);
  233. $smcFunc['db_insert']('insert',
  234. '{db_prefix}log_search_words',
  235. array('id_word' => 'string', 'id_msg' => 'int'),
  236. $inserts,
  237. array('id_word', 'id_msg')
  238. );
  239. }
  240. }
  241. }