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
28 * Search engine hook for MySQL 4+
31 class SearchMySQL
extends SearchEngine
{
32 var $strictMatching = true;
33 static $mMinSearchLength;
36 * Creates an instance of this class
37 * @param $db DatabaseMysql: database object
39 function __construct( $db ) {
40 parent
::__construct( $db );
44 * Parse the user's query and transform it into an SQL fragment which will
45 * become part of a WHERE clause
49 function parseQuery( $filteredText, $fulltext ) {
51 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
53 $this->searchTerms
= array();
55 # @todo FIXME: This doesn't handle parenthetical expressions.
57 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
58 $filteredText, $m, PREG_SET_ORDER
) ) {
59 foreach( $m as $bits ) {
60 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
62 if( $nonQuoted != '' ) {
66 $term = str_replace( '"', '', $term );
70 if( $searchon !== '' ) $searchon .= ' ';
71 if( $this->strictMatching
&& ($modifier == '') ) {
72 // If we leave this out, boolean op defaults to OR which is rarely helpful.
76 // Some languages such as Serbian store the input form in the search index,
77 // so we may need to search for matches in multiple writing system variants.
78 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
79 if( is_array( $convertedVariants ) ) {
80 $variants = array_unique( array_values( $convertedVariants ) );
82 $variants = array( $term );
85 // The low-level search index does some processing on input to work
86 // around problems with minimum lengths and encoding in MySQL's
88 // For Chinese this also inserts spaces between adjacent Han characters.
89 $strippedVariants = array_map(
90 array( $wgContLang, 'normalizeForSearch' ),
93 // Some languages such as Chinese force all variants to a canonical
94 // form when stripping to the low-level search index, so to be sure
95 // let's check our variants list for unique items after stripping.
96 $strippedVariants = array_unique( $strippedVariants );
98 $searchon .= $modifier;
99 if( count( $strippedVariants) > 1 )
101 foreach( $strippedVariants as $stripped ) {
102 $stripped = $this->normalizeText( $stripped );
103 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
104 // Hack for Chinese: we need to toss in quotes for
105 // multiple-character phrases since normalizeForSearch()
106 // added spaces between them to make word breaks.
107 $stripped = '"' . trim( $stripped ) . '"';
109 $searchon .= "$quote$stripped$quote$wildcard ";
111 if( count( $strippedVariants) > 1 )
114 // Match individual terms or quoted phrase in result highlighting...
115 // Note that variants will be introduced in a later stage for highlighting!
116 $regexp = $this->regexTerm( $term, $wildcard );
117 $this->searchTerms
[] = $regexp;
119 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
120 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
122 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
125 $searchon = $this->db
->strencode( $searchon );
126 $field = $this->getIndexField( $fulltext );
127 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
130 function regexTerm( $string, $wildcard ) {
133 $regex = preg_quote( $string, '/' );
134 if( $wgContLang->hasWordBreaks() ) {
136 // Don't cut off the final bit!
139 $regex = "\b$regex\b";
142 // For Chinese, words may legitimately abut other words in the text literal.
143 // Don't add \b boundary checks... note this could cause false positives
149 public static function legalSearchChars() {
150 return "\"*" . parent
::legalSearchChars();
154 * Perform a full text search query and return a result set.
156 * @param $term String: raw search term
157 * @return MySQLSearchResultSet
159 function searchText( $term ) {
160 return $this->searchInternal( $term, true );
164 * Perform a title-only search query and return a result set.
166 * @param $term String: raw search term
167 * @return MySQLSearchResultSet
169 function searchTitle( $term ) {
170 return $this->searchInternal( $term, false );
173 protected function searchInternal( $term, $fulltext ) {
174 global $wgCountTotalSearchHits;
176 // This seems out of place, why is this called with empty term?
177 if ( trim( $term ) === '' ) return null;
179 $filteredTerm = $this->filter( $term );
180 $query = $this->getQuery( $filteredTerm, $fulltext );
181 $resultSet = $this->db
->select(
182 $query['tables'], $query['fields'], $query['conds'],
183 __METHOD__
, $query['options'], $query['joins']
187 if( $wgCountTotalSearchHits ) {
188 $query = $this->getCountQuery( $filteredTerm, $fulltext );
189 $totalResult = $this->db
->select(
190 $query['tables'], $query['fields'], $query['conds'],
191 __METHOD__
, $query['options'], $query['joins']
194 $row = $totalResult->fetchObject();
196 $total = intval( $row->c
);
198 $totalResult->free();
201 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
, $total );
204 public function supports( $feature ) {
206 case 'list-redirects':
207 case 'title-suffix-filter':
215 * Add special conditions
216 * @param $query Array
219 protected function queryFeatures( &$query ) {
220 foreach ( $this->features
as $feature => $value ) {
221 if ( $feature === 'list-redirects' && !$value ) {
222 $query['conds']['page_is_redirect'] = 0;
223 } elseif( $feature === 'title-suffix-filter' && $value ) {
224 $query['conds'][] = 'page_title' . $this->db
->buildLike( $this->db
->anyString(), $value );
230 * Add namespace conditions
231 * @param $query Array
232 * @since 1.18 (changed)
234 function queryNamespaces( &$query ) {
235 if ( is_array( $this->namespaces
) ) {
236 if ( count( $this->namespaces
) === 0 ) {
237 $this->namespaces
[] = '0';
239 $query['conds']['page_namespace'] = $this->namespaces
;
245 * @param $query Array
248 protected function limitResult( &$query ) {
249 $query['options']['LIMIT'] = $this->limit
;
250 $query['options']['OFFSET'] = $this->offset
;
254 * Construct the SQL query to do the search.
255 * The guts shoulds be constructed in queryMain()
256 * @param $filteredTerm String
257 * @param $fulltext Boolean
259 * @since 1.18 (changed)
261 function getQuery( $filteredTerm, $fulltext ) {
266 'options' => array(),
270 $this->queryMain( $query, $filteredTerm, $fulltext );
271 $this->queryFeatures( $query );
272 $this->queryNamespaces( $query );
273 $this->limitResult( $query );
279 * Picks which field to index on, depending on what type of query.
280 * @param $fulltext Boolean
283 function getIndexField( $fulltext ) {
284 return $fulltext ?
'si_text' : 'si_title';
288 * Get the base part of the search query.
290 * @param $filteredTerm String
291 * @param $fulltext Boolean
292 * @since 1.18 (changed)
294 function queryMain( &$query, $filteredTerm, $fulltext ) {
295 $match = $this->parseQuery( $filteredTerm, $fulltext );
296 $query['tables'][] = 'page';
297 $query['tables'][] = 'searchindex';
298 $query['fields'][] = 'page_id';
299 $query['fields'][] = 'page_namespace';
300 $query['fields'][] = 'page_title';
301 $query['conds'][] = 'page_id=si_page';
302 $query['conds'][] = $match;
306 * @since 1.18 (changed)
308 function getCountQuery( $filteredTerm, $fulltext ) {
309 $match = $this->parseQuery( $filteredTerm, $fulltext );
312 'tables' => array( 'page', 'searchindex' ),
313 'fields' => array( 'COUNT(*) as c' ),
314 'conds' => array( 'page_id=si_page', $match ),
315 'options' => array(),
319 $this->queryFeatures( $query );
320 $this->queryNamespaces( $query );
326 * Create or update the search index record for the given page.
327 * Title and text should be pre-processed.
330 * @param $title String
331 * @param $text String
333 function update( $id, $title, $text ) {
334 $dbw = wfGetDB( DB_MASTER
);
335 $dbw->replace( 'searchindex',
339 'si_title' => $this->normalizeText( $title ),
340 'si_text' => $this->normalizeText( $text )
345 * Update a search index record's title only.
346 * Title should be pre-processed.
349 * @param $title String
351 function updateTitle( $id, $title ) {
352 $dbw = wfGetDB( DB_MASTER
);
354 $dbw->update( 'searchindex',
355 array( 'si_title' => $this->normalizeText( $title ) ),
356 array( 'si_page' => $id ),
358 array( $dbw->lowPriorityOption() ) );
362 * Converts some characters for MySQL's indexing to grok it correctly,
363 * and pads short words to overcome limitations.
365 function normalizeText( $string ) {
368 wfProfileIn( __METHOD__
);
370 $out = parent
::normalizeText( $string );
372 // MySQL fulltext index doesn't grok utf-8, so we
373 // need to fold cases and convert to hex
374 $out = preg_replace_callback(
375 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
376 array( $this, 'stripForSearchCallback' ),
377 $wgContLang->lc( $out ) );
379 // And to add insult to injury, the default indexing
380 // ignores short words... Pad them so we can pass them
381 // through without reconfiguring the server...
382 $minLength = $this->minSearchLength();
383 if( $minLength > 1 ) {
391 // Periods within things like hostnames and IP addresses
392 // are also important -- we want a search for "example.com"
393 // or "192.168.1.1" to work sanely.
395 // MySQL's search seems to ignore them, so you'd match on
396 // "example.wikipedia.com" and "192.168.83.1" as well.
402 wfProfileOut( __METHOD__
);
408 * Armor a case-folded UTF-8 string to get through MySQL's
409 * fulltext search without being mucked up by funny charset
410 * settings or anything else of the sort.
412 protected function stripForSearchCallback( $matches ) {
413 return 'u8' . bin2hex( $matches[1] );
417 * Check MySQL server's ft_min_word_len setting so we know
418 * if we need to pad short words...
422 protected function minSearchLength() {
423 if( is_null( self
::$mMinSearchLength ) ) {
424 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
426 $dbr = wfGetDB( DB_SLAVE
);
427 $result = $dbr->query( $sql );
428 $row = $result->fetchObject();
431 if( $row && $row->Variable_name
== 'ft_min_word_len' ) {
432 self
::$mMinSearchLength = intval( $row->Value
);
434 self
::$mMinSearchLength = 0;
437 return self
::$mMinSearchLength;
444 class MySQLSearchResultSet
extends SqlSearchResultSet
{
445 function __construct( $resultSet, $terms, $totalHits=null ) {
446 parent
::__construct( $resultSet, $terms );
447 $this->mTotalHits
= $totalHits;
450 function getTotalHits() {
451 return $this->mTotalHits
;