SearchMySQL.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <?php
  2. /**
  3. * MySQL search engine
  4. *
  5. * Copyright (C) 2004 Brion Vibber <brion@pobox.com>
  6. * https://www.mediawiki.org/
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. * http://www.gnu.org/copyleft/gpl.html
  22. *
  23. * @file
  24. * @ingroup Search
  25. */
  26. use MediaWiki\MediaWikiServices;
  27. /**
  28. * Search engine hook for MySQL 4+
  29. * @ingroup Search
  30. */
  31. class SearchMySQL extends SearchDatabase {
  32. protected $strictMatching = true;
  33. private static $mMinSearchLength;
  34. /**
  35. * Parse the user's query and transform it into two SQL fragments:
  36. * a WHERE condition and an ORDER BY expression
  37. *
  38. * @param string $filteredText
  39. * @param string $fulltext
  40. *
  41. * @return array
  42. */
  43. private function parseQuery( $filteredText, $fulltext ) {
  44. $lc = $this->legalSearchChars( self::CHARS_NO_SYNTAX ); // Minus syntax chars (" and *)
  45. $searchon = '';
  46. $this->searchTerms = [];
  47. # @todo FIXME: This doesn't handle parenthetical expressions.
  48. $m = [];
  49. if ( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
  50. $filteredText, $m, PREG_SET_ORDER ) ) {
  51. foreach ( $m as $bits ) {
  52. Wikimedia\suppressWarnings();
  53. list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
  54. Wikimedia\restoreWarnings();
  55. if ( $nonQuoted != '' ) {
  56. $term = $nonQuoted;
  57. $quote = '';
  58. } else {
  59. $term = str_replace( '"', '', $term );
  60. $quote = '"';
  61. }
  62. if ( $searchon !== '' ) {
  63. $searchon .= ' ';
  64. }
  65. if ( $this->strictMatching && ( $modifier == '' ) ) {
  66. // If we leave this out, boolean op defaults to OR which is rarely helpful.
  67. $modifier = '+';
  68. }
  69. // Some languages such as Serbian store the input form in the search index,
  70. // so we may need to search for matches in multiple writing system variants.
  71. $contLang = MediaWikiServices::getInstance()->getContentLanguage();
  72. $convertedVariants = $contLang->autoConvertToAllVariants( $term );
  73. if ( is_array( $convertedVariants ) ) {
  74. $variants = array_unique( array_values( $convertedVariants ) );
  75. } else {
  76. $variants = [ $term ];
  77. }
  78. // The low-level search index does some processing on input to work
  79. // around problems with minimum lengths and encoding in MySQL's
  80. // fulltext engine.
  81. // For Chinese this also inserts spaces between adjacent Han characters.
  82. $strippedVariants = array_map( [ $contLang, 'normalizeForSearch' ], $variants );
  83. // Some languages such as Chinese force all variants to a canonical
  84. // form when stripping to the low-level search index, so to be sure
  85. // let's check our variants list for unique items after stripping.
  86. $strippedVariants = array_unique( $strippedVariants );
  87. $searchon .= $modifier;
  88. if ( count( $strippedVariants ) > 1 ) {
  89. $searchon .= '(';
  90. }
  91. foreach ( $strippedVariants as $stripped ) {
  92. $stripped = $this->normalizeText( $stripped );
  93. if ( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
  94. // Hack for Chinese: we need to toss in quotes for
  95. // multiple-character phrases since normalizeForSearch()
  96. // added spaces between them to make word breaks.
  97. $stripped = '"' . trim( $stripped ) . '"';
  98. }
  99. $searchon .= "$quote$stripped$quote$wildcard ";
  100. }
  101. if ( count( $strippedVariants ) > 1 ) {
  102. $searchon .= ')';
  103. }
  104. // Match individual terms or quoted phrase in result highlighting...
  105. // Note that variants will be introduced in a later stage for highlighting!
  106. $regexp = $this->regexTerm( $term, $wildcard );
  107. $this->searchTerms[] = $regexp;
  108. }
  109. wfDebug( __METHOD__ . ": Would search with '$searchon'\n" );
  110. wfDebug( __METHOD__ . ': Match with /' . implode( '|', $this->searchTerms ) . "/\n" );
  111. } else {
  112. wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
  113. }
  114. $dbr = $this->lb->getConnectionRef( DB_REPLICA );
  115. $searchon = $dbr->addQuotes( $searchon );
  116. $field = $this->getIndexField( $fulltext );
  117. return [
  118. " MATCH($field) AGAINST($searchon IN BOOLEAN MODE) ",
  119. " MATCH($field) AGAINST($searchon IN NATURAL LANGUAGE MODE) DESC "
  120. ];
  121. }
  122. private function regexTerm( $string, $wildcard ) {
  123. $regex = preg_quote( $string, '/' );
  124. if ( MediaWikiServices::getInstance()->getContentLanguage()->hasWordBreaks() ) {
  125. if ( $wildcard ) {
  126. // Don't cut off the final bit!
  127. $regex = "\b$regex";
  128. } else {
  129. $regex = "\b$regex\b";
  130. }
  131. } else {
  132. // For Chinese, words may legitimately abut other words in the text literal.
  133. // Don't add \b boundary checks... note this could cause false positives
  134. // for Latin chars.
  135. }
  136. return $regex;
  137. }
  138. public function legalSearchChars( $type = self::CHARS_ALL ) {
  139. $searchChars = parent::legalSearchChars( $type );
  140. if ( $type === self::CHARS_ALL ) {
  141. // " for phrase, * for wildcard
  142. $searchChars = "\"*" . $searchChars;
  143. }
  144. return $searchChars;
  145. }
  146. /**
  147. * Perform a full text search query and return a result set.
  148. *
  149. * @param string $term Raw search term
  150. * @return SqlSearchResultSet|null
  151. */
  152. protected function doSearchTextInDB( $term ) {
  153. return $this->searchInternal( $term, true );
  154. }
  155. /**
  156. * Perform a title-only search query and return a result set.
  157. *
  158. * @param string $term Raw search term
  159. * @return SqlSearchResultSet|null
  160. */
  161. protected function doSearchTitleInDB( $term ) {
  162. return $this->searchInternal( $term, false );
  163. }
  164. protected function searchInternal( $term, $fulltext ) {
  165. // This seems out of place, why is this called with empty term?
  166. if ( trim( $term ) === '' ) {
  167. return null;
  168. }
  169. $filteredTerm = $this->filter( $term );
  170. $query = $this->getQuery( $filteredTerm, $fulltext );
  171. $dbr = $this->lb->getConnectionRef( DB_REPLICA );
  172. $resultSet = $dbr->select(
  173. $query['tables'], $query['fields'], $query['conds'],
  174. __METHOD__, $query['options'], $query['joins']
  175. );
  176. $total = null;
  177. $query = $this->getCountQuery( $filteredTerm, $fulltext );
  178. $totalResult = $dbr->select(
  179. $query['tables'], $query['fields'], $query['conds'],
  180. __METHOD__, $query['options'], $query['joins']
  181. );
  182. $row = $totalResult->fetchObject();
  183. if ( $row ) {
  184. $total = intval( $row->c );
  185. }
  186. $totalResult->free();
  187. return new SqlSearchResultSet( $resultSet, $this->searchTerms, $total );
  188. }
  189. public function supports( $feature ) {
  190. switch ( $feature ) {
  191. case 'title-suffix-filter':
  192. return true;
  193. default:
  194. return parent::supports( $feature );
  195. }
  196. }
  197. /**
  198. * Add special conditions
  199. * @param array &$query
  200. * @since 1.18
  201. */
  202. protected function queryFeatures( &$query ) {
  203. foreach ( $this->features as $feature => $value ) {
  204. if ( $feature === 'title-suffix-filter' && $value ) {
  205. $dbr = $this->lb->getConnectionRef( DB_REPLICA );
  206. $query['conds'][] = 'page_title' . $dbr->buildLike( $dbr->anyString(), $value );
  207. }
  208. }
  209. }
  210. /**
  211. * Add namespace conditions
  212. * @param array &$query
  213. * @since 1.18 (changed)
  214. */
  215. function queryNamespaces( &$query ) {
  216. if ( is_array( $this->namespaces ) ) {
  217. if ( count( $this->namespaces ) === 0 ) {
  218. $this->namespaces[] = '0';
  219. }
  220. $query['conds']['page_namespace'] = $this->namespaces;
  221. }
  222. }
  223. /**
  224. * Add limit options
  225. * @param array &$query
  226. * @since 1.18
  227. */
  228. protected function limitResult( &$query ) {
  229. $query['options']['LIMIT'] = $this->limit;
  230. $query['options']['OFFSET'] = $this->offset;
  231. }
  232. /**
  233. * Construct the SQL query to do the search.
  234. * The guts shoulds be constructed in queryMain()
  235. * @param string $filteredTerm
  236. * @param bool $fulltext
  237. * @return array
  238. * @since 1.18 (changed)
  239. */
  240. private function getQuery( $filteredTerm, $fulltext ) {
  241. $query = [
  242. 'tables' => [],
  243. 'fields' => [],
  244. 'conds' => [],
  245. 'options' => [],
  246. 'joins' => [],
  247. ];
  248. $this->queryMain( $query, $filteredTerm, $fulltext );
  249. $this->queryFeatures( $query );
  250. $this->queryNamespaces( $query );
  251. $this->limitResult( $query );
  252. return $query;
  253. }
  254. /**
  255. * Picks which field to index on, depending on what type of query.
  256. * @param bool $fulltext
  257. * @return string
  258. */
  259. private function getIndexField( $fulltext ) {
  260. return $fulltext ? 'si_text' : 'si_title';
  261. }
  262. /**
  263. * Get the base part of the search query.
  264. *
  265. * @param array &$query Search query array
  266. * @param string $filteredTerm
  267. * @param bool $fulltext
  268. * @since 1.18 (changed)
  269. */
  270. private function queryMain( &$query, $filteredTerm, $fulltext ) {
  271. $match = $this->parseQuery( $filteredTerm, $fulltext );
  272. $query['tables'][] = 'page';
  273. $query['tables'][] = 'searchindex';
  274. $query['fields'][] = 'page_id';
  275. $query['fields'][] = 'page_namespace';
  276. $query['fields'][] = 'page_title';
  277. $query['conds'][] = 'page_id=si_page';
  278. $query['conds'][] = $match[0];
  279. $query['options']['ORDER BY'] = $match[1];
  280. }
  281. /**
  282. * @since 1.18 (changed)
  283. * @param string $filteredTerm
  284. * @param bool $fulltext
  285. * @return array
  286. */
  287. private function getCountQuery( $filteredTerm, $fulltext ) {
  288. $match = $this->parseQuery( $filteredTerm, $fulltext );
  289. $query = [
  290. 'tables' => [ 'page', 'searchindex' ],
  291. 'fields' => [ 'COUNT(*) as c' ],
  292. 'conds' => [ 'page_id=si_page', $match[0] ],
  293. 'options' => [],
  294. 'joins' => [],
  295. ];
  296. $this->queryFeatures( $query );
  297. $this->queryNamespaces( $query );
  298. return $query;
  299. }
  300. /**
  301. * Create or update the search index record for the given page.
  302. * Title and text should be pre-processed.
  303. *
  304. * @param int $id
  305. * @param string $title
  306. * @param string $text
  307. */
  308. function update( $id, $title, $text ) {
  309. $dbw = $this->lb->getConnectionRef( DB_MASTER );
  310. $dbw->replace( 'searchindex',
  311. [ 'si_page' ],
  312. [
  313. 'si_page' => $id,
  314. 'si_title' => $this->normalizeText( $title ),
  315. 'si_text' => $this->normalizeText( $text )
  316. ], __METHOD__ );
  317. }
  318. /**
  319. * Update a search index record's title only.
  320. * Title should be pre-processed.
  321. *
  322. * @param int $id
  323. * @param string $title
  324. */
  325. function updateTitle( $id, $title ) {
  326. $dbw = $this->lb->getConnectionRef( DB_MASTER );
  327. $dbw->update( 'searchindex',
  328. [ 'si_title' => $this->normalizeText( $title ) ],
  329. [ 'si_page' => $id ],
  330. __METHOD__
  331. );
  332. }
  333. /**
  334. * Delete an indexed page
  335. * Title should be pre-processed.
  336. *
  337. * @param int $id Page id that was deleted
  338. * @param string $title Title of page that was deleted
  339. */
  340. function delete( $id, $title ) {
  341. $dbw = $this->lb->getConnectionRef( DB_MASTER );
  342. $dbw->delete( 'searchindex', [ 'si_page' => $id ], __METHOD__ );
  343. }
  344. /**
  345. * Converts some characters for MySQL's indexing to grok it correctly,
  346. * and pads short words to overcome limitations.
  347. * @param string $string
  348. * @return mixed|string
  349. */
  350. function normalizeText( $string ) {
  351. $out = parent::normalizeText( $string );
  352. // MySQL fulltext index doesn't grok utf-8, so we
  353. // need to fold cases and convert to hex
  354. $out = preg_replace_callback(
  355. "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
  356. [ $this, 'stripForSearchCallback' ],
  357. MediaWikiServices::getInstance()->getContentLanguage()->lc( $out ) );
  358. // And to add insult to injury, the default indexing
  359. // ignores short words... Pad them so we can pass them
  360. // through without reconfiguring the server...
  361. $minLength = $this->minSearchLength();
  362. if ( $minLength > 1 ) {
  363. $n = $minLength - 1;
  364. $out = preg_replace(
  365. "/\b(\w{1,$n})\b/",
  366. "$1u800",
  367. $out );
  368. }
  369. // Periods within things like hostnames and IP addresses
  370. // are also important -- we want a search for "example.com"
  371. // or "192.168.1.1" to work sanely.
  372. // MySQL's search seems to ignore them, so you'd match on
  373. // "example.wikipedia.com" and "192.168.83.1" as well.
  374. $out = preg_replace(
  375. "/(\w)\.(\w|\*)/u",
  376. "$1u82e$2",
  377. $out );
  378. return $out;
  379. }
  380. /**
  381. * Armor a case-folded UTF-8 string to get through MySQL's
  382. * fulltext search without being mucked up by funny charset
  383. * settings or anything else of the sort.
  384. * @param array $matches
  385. * @return string
  386. */
  387. protected function stripForSearchCallback( $matches ) {
  388. return 'u8' . bin2hex( $matches[1] );
  389. }
  390. /**
  391. * Check MySQL server's ft_min_word_len setting so we know
  392. * if we need to pad short words...
  393. *
  394. * @return int
  395. */
  396. protected function minSearchLength() {
  397. if ( is_null( self::$mMinSearchLength ) ) {
  398. $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
  399. $dbr = $this->lb->getConnectionRef( DB_REPLICA );
  400. $result = $dbr->query( $sql, __METHOD__ );
  401. $row = $result->fetchObject();
  402. $result->free();
  403. if ( $row && $row->Variable_name == 'ft_min_word_len' ) {
  404. self::$mMinSearchLength = intval( $row->Value );
  405. } else {
  406. self::$mMinSearchLength = 0;
  407. }
  408. }
  409. return self::$mMinSearchLength;
  410. }
  411. }