Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / search / SearchMySQL.php
blobf63931dc44835532acd646d5e82a453f779887ac
1 <?php
2 /**
3 * MySQL search engine
5 * Copyright (C) 2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
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.
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.
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
23 * @file
24 * @ingroup Search
27 /**
28 * Search engine hook for MySQL 4+
29 * @ingroup Search
31 class SearchMySQL extends SearchEngine {
32 var $strictMatching = true;
33 static $mMinSearchLength;
35 /**
36 * Creates an instance of this class
37 * @param $db DatabaseMysql: database object
39 function __construct( $db ) {
40 parent::__construct( $db );
43 /**
44 * Parse the user's query and transform it into an SQL fragment which will
45 * become part of a WHERE clause
47 * @param $filteredText string
48 * @param $fulltext string
50 * @return string
52 function parseQuery( $filteredText, $fulltext ) {
53 global $wgContLang;
54 $lc = SearchEngine::legalSearchChars(); // Minus format chars
55 $searchon = '';
56 $this->searchTerms = array();
58 # @todo FIXME: This doesn't handle parenthetical expressions.
59 $m = array();
60 if ( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
61 $filteredText, $m, PREG_SET_ORDER ) ) {
62 foreach ( $m as $bits ) {
63 @list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
65 if ( $nonQuoted != '' ) {
66 $term = $nonQuoted;
67 $quote = '';
68 } else {
69 $term = str_replace( '"', '', $term );
70 $quote = '"';
73 if ( $searchon !== '' ) {
74 $searchon .= ' ';
76 if ( $this->strictMatching && ( $modifier == '' ) ) {
77 // If we leave this out, boolean op defaults to OR which is rarely helpful.
78 $modifier = '+';
81 // Some languages such as Serbian store the input form in the search index,
82 // so we may need to search for matches in multiple writing system variants.
83 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
84 if ( is_array( $convertedVariants ) ) {
85 $variants = array_unique( array_values( $convertedVariants ) );
86 } else {
87 $variants = array( $term );
90 // The low-level search index does some processing on input to work
91 // around problems with minimum lengths and encoding in MySQL's
92 // fulltext engine.
93 // For Chinese this also inserts spaces between adjacent Han characters.
94 $strippedVariants = array_map(
95 array( $wgContLang, 'normalizeForSearch' ),
96 $variants );
98 // Some languages such as Chinese force all variants to a canonical
99 // form when stripping to the low-level search index, so to be sure
100 // let's check our variants list for unique items after stripping.
101 $strippedVariants = array_unique( $strippedVariants );
103 $searchon .= $modifier;
104 if ( count( $strippedVariants ) > 1 ) {
105 $searchon .= '(';
107 foreach ( $strippedVariants as $stripped ) {
108 $stripped = $this->normalizeText( $stripped );
109 if ( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
110 // Hack for Chinese: we need to toss in quotes for
111 // multiple-character phrases since normalizeForSearch()
112 // added spaces between them to make word breaks.
113 $stripped = '"' . trim( $stripped ) . '"';
115 $searchon .= "$quote$stripped$quote$wildcard ";
117 if ( count( $strippedVariants ) > 1 ) {
118 $searchon .= ')';
121 // Match individual terms or quoted phrase in result highlighting...
122 // Note that variants will be introduced in a later stage for highlighting!
123 $regexp = $this->regexTerm( $term, $wildcard );
124 $this->searchTerms[] = $regexp;
126 wfDebug( __METHOD__ . ": Would search with '$searchon'\n" );
127 wfDebug( __METHOD__ . ': Match with /' . implode( '|', $this->searchTerms ) . "/\n" );
128 } else {
129 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
132 $searchon = $this->db->strencode( $searchon );
133 $field = $this->getIndexField( $fulltext );
134 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
137 function regexTerm( $string, $wildcard ) {
138 global $wgContLang;
140 $regex = preg_quote( $string, '/' );
141 if ( $wgContLang->hasWordBreaks() ) {
142 if ( $wildcard ) {
143 // Don't cut off the final bit!
144 $regex = "\b$regex";
145 } else {
146 $regex = "\b$regex\b";
148 } else {
149 // For Chinese, words may legitimately abut other words in the text literal.
150 // Don't add \b boundary checks... note this could cause false positives
151 // for latin chars.
153 return $regex;
156 public static function legalSearchChars() {
157 return "\"*" . parent::legalSearchChars();
161 * Perform a full text search query and return a result set.
163 * @param string $term raw search term
164 * @return MySQLSearchResultSet
166 function searchText( $term ) {
167 return $this->searchInternal( $term, true );
171 * Perform a title-only search query and return a result set.
173 * @param string $term raw search term
174 * @return MySQLSearchResultSet
176 function searchTitle( $term ) {
177 return $this->searchInternal( $term, false );
180 protected function searchInternal( $term, $fulltext ) {
181 global $wgCountTotalSearchHits;
183 // This seems out of place, why is this called with empty term?
184 if ( trim( $term ) === '' ) {
185 return null;
188 $filteredTerm = $this->filter( $term );
189 $query = $this->getQuery( $filteredTerm, $fulltext );
190 $resultSet = $this->db->select(
191 $query['tables'], $query['fields'], $query['conds'],
192 __METHOD__, $query['options'], $query['joins']
195 $total = null;
196 if ( $wgCountTotalSearchHits ) {
197 $query = $this->getCountQuery( $filteredTerm, $fulltext );
198 $totalResult = $this->db->select(
199 $query['tables'], $query['fields'], $query['conds'],
200 __METHOD__, $query['options'], $query['joins']
203 $row = $totalResult->fetchObject();
204 if ( $row ) {
205 $total = intval( $row->c );
207 $totalResult->free();
210 return new MySQLSearchResultSet( $resultSet, $this->searchTerms, $total );
213 public function supports( $feature ) {
214 switch( $feature ) {
215 case 'list-redirects':
216 case 'title-suffix-filter':
217 return true;
218 default:
219 return false;
224 * Add special conditions
225 * @param $query Array
226 * @since 1.18
228 protected function queryFeatures( &$query ) {
229 foreach ( $this->features as $feature => $value ) {
230 if ( $feature === 'list-redirects' && !$value ) {
231 $query['conds']['page_is_redirect'] = 0;
232 } elseif ( $feature === 'title-suffix-filter' && $value ) {
233 $query['conds'][] = 'page_title' . $this->db->buildLike( $this->db->anyString(), $value );
239 * Add namespace conditions
240 * @param $query Array
241 * @since 1.18 (changed)
243 function queryNamespaces( &$query ) {
244 if ( is_array( $this->namespaces ) ) {
245 if ( count( $this->namespaces ) === 0 ) {
246 $this->namespaces[] = '0';
248 $query['conds']['page_namespace'] = $this->namespaces;
253 * Add limit options
254 * @param $query Array
255 * @since 1.18
257 protected function limitResult( &$query ) {
258 $query['options']['LIMIT'] = $this->limit;
259 $query['options']['OFFSET'] = $this->offset;
263 * Construct the SQL query to do the search.
264 * The guts shoulds be constructed in queryMain()
265 * @param $filteredTerm String
266 * @param $fulltext Boolean
267 * @return Array
268 * @since 1.18 (changed)
270 function getQuery( $filteredTerm, $fulltext ) {
271 $query = array(
272 'tables' => array(),
273 'fields' => array(),
274 'conds' => array(),
275 'options' => array(),
276 'joins' => array(),
279 $this->queryMain( $query, $filteredTerm, $fulltext );
280 $this->queryFeatures( $query );
281 $this->queryNamespaces( $query );
282 $this->limitResult( $query );
284 return $query;
288 * Picks which field to index on, depending on what type of query.
289 * @param $fulltext Boolean
290 * @return String
292 function getIndexField( $fulltext ) {
293 return $fulltext ? 'si_text' : 'si_title';
297 * Get the base part of the search query.
299 * @param &$query array Search query array
300 * @param $filteredTerm String
301 * @param $fulltext Boolean
302 * @since 1.18 (changed)
304 function queryMain( &$query, $filteredTerm, $fulltext ) {
305 $match = $this->parseQuery( $filteredTerm, $fulltext );
306 $query['tables'][] = 'page';
307 $query['tables'][] = 'searchindex';
308 $query['fields'][] = 'page_id';
309 $query['fields'][] = 'page_namespace';
310 $query['fields'][] = 'page_title';
311 $query['conds'][] = 'page_id=si_page';
312 $query['conds'][] = $match;
316 * @since 1.18 (changed)
317 * @return array
319 function getCountQuery( $filteredTerm, $fulltext ) {
320 $match = $this->parseQuery( $filteredTerm, $fulltext );
322 $query = array(
323 'tables' => array( 'page', 'searchindex' ),
324 'fields' => array( 'COUNT(*) as c' ),
325 'conds' => array( 'page_id=si_page', $match ),
326 'options' => array(),
327 'joins' => array(),
330 $this->queryFeatures( $query );
331 $this->queryNamespaces( $query );
333 return $query;
337 * Create or update the search index record for the given page.
338 * Title and text should be pre-processed.
340 * @param $id Integer
341 * @param $title String
342 * @param $text String
344 function update( $id, $title, $text ) {
345 $dbw = wfGetDB( DB_MASTER );
346 $dbw->replace( 'searchindex',
347 array( 'si_page' ),
348 array(
349 'si_page' => $id,
350 'si_title' => $this->normalizeText( $title ),
351 'si_text' => $this->normalizeText( $text )
352 ), __METHOD__ );
356 * Update a search index record's title only.
357 * Title should be pre-processed.
359 * @param $id Integer
360 * @param $title String
362 function updateTitle( $id, $title ) {
363 $dbw = wfGetDB( DB_MASTER );
365 $dbw->update( 'searchindex',
366 array( 'si_title' => $this->normalizeText( $title ) ),
367 array( 'si_page' => $id ),
368 __METHOD__,
369 array( $dbw->lowPriorityOption() ) );
373 * Converts some characters for MySQL's indexing to grok it correctly,
374 * and pads short words to overcome limitations.
375 * @return mixed|string
377 function normalizeText( $string ) {
378 global $wgContLang;
380 wfProfileIn( __METHOD__ );
382 $out = parent::normalizeText( $string );
384 // MySQL fulltext index doesn't grok utf-8, so we
385 // need to fold cases and convert to hex
386 $out = preg_replace_callback(
387 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
388 array( $this, 'stripForSearchCallback' ),
389 $wgContLang->lc( $out ) );
391 // And to add insult to injury, the default indexing
392 // ignores short words... Pad them so we can pass them
393 // through without reconfiguring the server...
394 $minLength = $this->minSearchLength();
395 if ( $minLength > 1 ) {
396 $n = $minLength - 1;
397 $out = preg_replace(
398 "/\b(\w{1,$n})\b/",
399 "$1u800",
400 $out );
403 // Periods within things like hostnames and IP addresses
404 // are also important -- we want a search for "example.com"
405 // or "192.168.1.1" to work sanely.
407 // MySQL's search seems to ignore them, so you'd match on
408 // "example.wikipedia.com" and "192.168.83.1" as well.
409 $out = preg_replace(
410 "/(\w)\.(\w|\*)/u",
411 "$1u82e$2",
412 $out );
414 wfProfileOut( __METHOD__ );
416 return $out;
420 * Armor a case-folded UTF-8 string to get through MySQL's
421 * fulltext search without being mucked up by funny charset
422 * settings or anything else of the sort.
423 * @return string
425 protected function stripForSearchCallback( $matches ) {
426 return 'u8' . bin2hex( $matches[1] );
430 * Check MySQL server's ft_min_word_len setting so we know
431 * if we need to pad short words...
433 * @return int
435 protected function minSearchLength() {
436 if ( is_null( self::$mMinSearchLength ) ) {
437 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
439 $dbr = wfGetDB( DB_SLAVE );
440 $result = $dbr->query( $sql );
441 $row = $result->fetchObject();
442 $result->free();
444 if ( $row && $row->Variable_name == 'ft_min_word_len' ) {
445 self::$mMinSearchLength = intval( $row->Value );
446 } else {
447 self::$mMinSearchLength = 0;
450 return self::$mMinSearchLength;
455 * @ingroup Search
457 class MySQLSearchResultSet extends SqlSearchResultSet {
458 function __construct( $resultSet, $terms, $totalHits = null ) {
459 parent::__construct( $resultSet, $terms );
460 $this->mTotalHits = $totalHits;
463 function getTotalHits() {
464 return $this->mTotalHits;