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
47 * @param $filteredText string
48 * @param $fulltext string
52 function parseQuery( $filteredText, $fulltext ) {
54 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
56 $this->searchTerms
= array();
58 # @todo FIXME: This doesn't handle parenthetical expressions.
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 != '' ) {
69 $term = str_replace( '"', '', $term );
73 if( $searchon !== '' ) $searchon .= ' ';
74 if( $this->strictMatching
&& ($modifier == '') ) {
75 // If we leave this out, boolean op defaults to OR which is rarely helpful.
79 // Some languages such as Serbian store the input form in the search index,
80 // so we may need to search for matches in multiple writing system variants.
81 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
82 if( is_array( $convertedVariants ) ) {
83 $variants = array_unique( array_values( $convertedVariants ) );
85 $variants = array( $term );
88 // The low-level search index does some processing on input to work
89 // around problems with minimum lengths and encoding in MySQL's
91 // For Chinese this also inserts spaces between adjacent Han characters.
92 $strippedVariants = array_map(
93 array( $wgContLang, 'normalizeForSearch' ),
96 // Some languages such as Chinese force all variants to a canonical
97 // form when stripping to the low-level search index, so to be sure
98 // let's check our variants list for unique items after stripping.
99 $strippedVariants = array_unique( $strippedVariants );
101 $searchon .= $modifier;
102 if( count( $strippedVariants) > 1 )
104 foreach( $strippedVariants as $stripped ) {
105 $stripped = $this->normalizeText( $stripped );
106 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
107 // Hack for Chinese: we need to toss in quotes for
108 // multiple-character phrases since normalizeForSearch()
109 // added spaces between them to make word breaks.
110 $stripped = '"' . trim( $stripped ) . '"';
112 $searchon .= "$quote$stripped$quote$wildcard ";
114 if( count( $strippedVariants) > 1 )
117 // Match individual terms or quoted phrase in result highlighting...
118 // Note that variants will be introduced in a later stage for highlighting!
119 $regexp = $this->regexTerm( $term, $wildcard );
120 $this->searchTerms
[] = $regexp;
122 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
123 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
125 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
128 $searchon = $this->db
->strencode( $searchon );
129 $field = $this->getIndexField( $fulltext );
130 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
133 function regexTerm( $string, $wildcard ) {
136 $regex = preg_quote( $string, '/' );
137 if( $wgContLang->hasWordBreaks() ) {
139 // Don't cut off the final bit!
142 $regex = "\b$regex\b";
145 // For Chinese, words may legitimately abut other words in the text literal.
146 // Don't add \b boundary checks... note this could cause false positives
152 public static function legalSearchChars() {
153 return "\"*" . parent
::legalSearchChars();
157 * Perform a full text search query and return a result set.
159 * @param $term String: raw search term
160 * @return MySQLSearchResultSet
162 function searchText( $term ) {
163 return $this->searchInternal( $term, true );
167 * Perform a title-only search query and return a result set.
169 * @param $term String: raw search term
170 * @return MySQLSearchResultSet
172 function searchTitle( $term ) {
173 return $this->searchInternal( $term, false );
176 protected function searchInternal( $term, $fulltext ) {
177 global $wgCountTotalSearchHits;
179 // This seems out of place, why is this called with empty term?
180 if ( trim( $term ) === '' ) return null;
182 $filteredTerm = $this->filter( $term );
183 $query = $this->getQuery( $filteredTerm, $fulltext );
184 $resultSet = $this->db
->select(
185 $query['tables'], $query['fields'], $query['conds'],
186 __METHOD__
, $query['options'], $query['joins']
190 if( $wgCountTotalSearchHits ) {
191 $query = $this->getCountQuery( $filteredTerm, $fulltext );
192 $totalResult = $this->db
->select(
193 $query['tables'], $query['fields'], $query['conds'],
194 __METHOD__
, $query['options'], $query['joins']
197 $row = $totalResult->fetchObject();
199 $total = intval( $row->c
);
201 $totalResult->free();
204 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
, $total );
207 public function supports( $feature ) {
209 case 'list-redirects':
210 case 'title-suffix-filter':
218 * Add special conditions
219 * @param $query Array
222 protected function queryFeatures( &$query ) {
223 foreach ( $this->features
as $feature => $value ) {
224 if ( $feature === 'list-redirects' && !$value ) {
225 $query['conds']['page_is_redirect'] = 0;
226 } elseif( $feature === 'title-suffix-filter' && $value ) {
227 $query['conds'][] = 'page_title' . $this->db
->buildLike( $this->db
->anyString(), $value );
233 * Add namespace conditions
234 * @param $query Array
235 * @since 1.18 (changed)
237 function queryNamespaces( &$query ) {
238 if ( is_array( $this->namespaces
) ) {
239 if ( count( $this->namespaces
) === 0 ) {
240 $this->namespaces
[] = '0';
242 $query['conds']['page_namespace'] = $this->namespaces
;
248 * @param $query Array
251 protected function limitResult( &$query ) {
252 $query['options']['LIMIT'] = $this->limit
;
253 $query['options']['OFFSET'] = $this->offset
;
257 * Construct the SQL query to do the search.
258 * The guts shoulds be constructed in queryMain()
259 * @param $filteredTerm String
260 * @param $fulltext Boolean
262 * @since 1.18 (changed)
264 function getQuery( $filteredTerm, $fulltext ) {
269 'options' => array(),
273 $this->queryMain( $query, $filteredTerm, $fulltext );
274 $this->queryFeatures( $query );
275 $this->queryNamespaces( $query );
276 $this->limitResult( $query );
282 * Picks which field to index on, depending on what type of query.
283 * @param $fulltext Boolean
286 function getIndexField( $fulltext ) {
287 return $fulltext ?
'si_text' : 'si_title';
291 * Get the base part of the search query.
293 * @param &$query array Search query array
294 * @param $filteredTerm String
295 * @param $fulltext Boolean
296 * @since 1.18 (changed)
298 function queryMain( &$query, $filteredTerm, $fulltext ) {
299 $match = $this->parseQuery( $filteredTerm, $fulltext );
300 $query['tables'][] = 'page';
301 $query['tables'][] = 'searchindex';
302 $query['fields'][] = 'page_id';
303 $query['fields'][] = 'page_namespace';
304 $query['fields'][] = 'page_title';
305 $query['conds'][] = 'page_id=si_page';
306 $query['conds'][] = $match;
310 * @since 1.18 (changed)
313 function getCountQuery( $filteredTerm, $fulltext ) {
314 $match = $this->parseQuery( $filteredTerm, $fulltext );
317 'tables' => array( 'page', 'searchindex' ),
318 'fields' => array( 'COUNT(*) as c' ),
319 'conds' => array( 'page_id=si_page', $match ),
320 'options' => array(),
324 $this->queryFeatures( $query );
325 $this->queryNamespaces( $query );
331 * Create or update the search index record for the given page.
332 * Title and text should be pre-processed.
335 * @param $title String
336 * @param $text String
338 function update( $id, $title, $text ) {
339 $dbw = wfGetDB( DB_MASTER
);
340 $dbw->replace( 'searchindex',
344 'si_title' => $this->normalizeText( $title ),
345 'si_text' => $this->normalizeText( $text )
350 * Update a search index record's title only.
351 * Title should be pre-processed.
354 * @param $title String
356 function updateTitle( $id, $title ) {
357 $dbw = wfGetDB( DB_MASTER
);
359 $dbw->update( 'searchindex',
360 array( 'si_title' => $this->normalizeText( $title ) ),
361 array( 'si_page' => $id ),
363 array( $dbw->lowPriorityOption() ) );
367 * Converts some characters for MySQL's indexing to grok it correctly,
368 * and pads short words to overcome limitations.
369 * @return mixed|string
371 function normalizeText( $string ) {
374 wfProfileIn( __METHOD__
);
376 $out = parent
::normalizeText( $string );
378 // MySQL fulltext index doesn't grok utf-8, so we
379 // need to fold cases and convert to hex
380 $out = preg_replace_callback(
381 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
382 array( $this, 'stripForSearchCallback' ),
383 $wgContLang->lc( $out ) );
385 // And to add insult to injury, the default indexing
386 // ignores short words... Pad them so we can pass them
387 // through without reconfiguring the server...
388 $minLength = $this->minSearchLength();
389 if( $minLength > 1 ) {
397 // Periods within things like hostnames and IP addresses
398 // are also important -- we want a search for "example.com"
399 // or "192.168.1.1" to work sanely.
401 // MySQL's search seems to ignore them, so you'd match on
402 // "example.wikipedia.com" and "192.168.83.1" as well.
408 wfProfileOut( __METHOD__
);
414 * Armor a case-folded UTF-8 string to get through MySQL's
415 * fulltext search without being mucked up by funny charset
416 * settings or anything else of the sort.
419 protected function stripForSearchCallback( $matches ) {
420 return 'u8' . bin2hex( $matches[1] );
424 * Check MySQL server's ft_min_word_len setting so we know
425 * if we need to pad short words...
429 protected function minSearchLength() {
430 if( is_null( self
::$mMinSearchLength ) ) {
431 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
433 $dbr = wfGetDB( DB_SLAVE
);
434 $result = $dbr->query( $sql );
435 $row = $result->fetchObject();
438 if( $row && $row->Variable_name
== 'ft_min_word_len' ) {
439 self
::$mMinSearchLength = intval( $row->Value
);
441 self
::$mMinSearchLength = 0;
444 return self
::$mMinSearchLength;
451 class MySQLSearchResultSet
extends SqlSearchResultSet
{
452 function __construct( $resultSet, $terms, $totalHits=null ) {
453 parent
::__construct( $resultSet, $terms );
454 $this->mTotalHits
= $totalHits;
457 function getTotalHits() {
458 return $this->mTotalHits
;