PageRenderTime 77ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/search/SearchMySQL.php

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