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 SearchDatabase
{
32 var $strictMatching = true;
33 static $mMinSearchLength;
36 * Parse the user's query and transform it into an SQL fragment which will
37 * become part of a WHERE clause
39 * @param $filteredText string
40 * @param $fulltext string
44 function parseQuery( $filteredText, $fulltext ) {
46 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
48 $this->searchTerms
= array();
50 # @todo FIXME: This doesn't handle parenthetical expressions.
52 if ( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
53 $filteredText, $m, PREG_SET_ORDER
) ) {
54 foreach ( $m as $bits ) {
55 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
57 if ( $nonQuoted != '' ) {
61 $term = str_replace( '"', '', $term );
65 if ( $searchon !== '' ) {
68 if ( $this->strictMatching
&& ( $modifier == '' ) ) {
69 // If we leave this out, boolean op defaults to OR which is rarely helpful.
73 // Some languages such as Serbian store the input form in the search index,
74 // so we may need to search for matches in multiple writing system variants.
75 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
76 if ( is_array( $convertedVariants ) ) {
77 $variants = array_unique( array_values( $convertedVariants ) );
79 $variants = array( $term );
82 // The low-level search index does some processing on input to work
83 // around problems with minimum lengths and encoding in MySQL's
85 // For Chinese this also inserts spaces between adjacent Han characters.
86 $strippedVariants = array_map(
87 array( $wgContLang, 'normalizeForSearch' ),
90 // Some languages such as Chinese force all variants to a canonical
91 // form when stripping to the low-level search index, so to be sure
92 // let's check our variants list for unique items after stripping.
93 $strippedVariants = array_unique( $strippedVariants );
95 $searchon .= $modifier;
96 if ( count( $strippedVariants ) > 1 ) {
99 foreach ( $strippedVariants as $stripped ) {
100 $stripped = $this->normalizeText( $stripped );
101 if ( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
102 // Hack for Chinese: we need to toss in quotes for
103 // multiple-character phrases since normalizeForSearch()
104 // added spaces between them to make word breaks.
105 $stripped = '"' . trim( $stripped ) . '"';
107 $searchon .= "$quote$stripped$quote$wildcard ";
109 if ( count( $strippedVariants ) > 1 ) {
113 // Match individual terms or quoted phrase in result highlighting...
114 // Note that variants will be introduced in a later stage for highlighting!
115 $regexp = $this->regexTerm( $term, $wildcard );
116 $this->searchTerms
[] = $regexp;
118 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
119 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
121 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
124 $searchon = $this->db
->strencode( $searchon );
125 $field = $this->getIndexField( $fulltext );
126 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
129 function regexTerm( $string, $wildcard ) {
132 $regex = preg_quote( $string, '/' );
133 if ( $wgContLang->hasWordBreaks() ) {
135 // Don't cut off the final bit!
138 $regex = "\b$regex\b";
141 // For Chinese, words may legitimately abut other words in the text literal.
142 // Don't add \b boundary checks... note this could cause false positives
148 public static function legalSearchChars() {
149 return "\"*" . parent
::legalSearchChars();
153 * Perform a full text search query and return a result set.
155 * @param string $term raw search term
156 * @return MySQLSearchResultSet
158 function searchText( $term ) {
159 return $this->searchInternal( $term, true );
163 * Perform a title-only search query and return a result set.
165 * @param string $term raw search term
166 * @return MySQLSearchResultSet
168 function searchTitle( $term ) {
169 return $this->searchInternal( $term, false );
172 protected function searchInternal( $term, $fulltext ) {
173 global $wgCountTotalSearchHits;
175 // This seems out of place, why is this called with empty term?
176 if ( trim( $term ) === '' ) {
180 $filteredTerm = $this->filter( $term );
181 $query = $this->getQuery( $filteredTerm, $fulltext );
182 $resultSet = $this->db
->select(
183 $query['tables'], $query['fields'], $query['conds'],
184 __METHOD__
, $query['options'], $query['joins']
188 if ( $wgCountTotalSearchHits ) {
189 $query = $this->getCountQuery( $filteredTerm, $fulltext );
190 $totalResult = $this->db
->select(
191 $query['tables'], $query['fields'], $query['conds'],
192 __METHOD__
, $query['options'], $query['joins']
195 $row = $totalResult->fetchObject();
197 $total = intval( $row->c
);
199 $totalResult->free();
202 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
, $total );
205 public function supports( $feature ) {
206 switch ( $feature ) {
207 case 'title-suffix-filter':
210 return parent
::supports( $feature );
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 &$query array Search query array
291 * @param $filteredTerm String
292 * @param $fulltext Boolean
293 * @since 1.18 (changed)
295 function queryMain( &$query, $filteredTerm, $fulltext ) {
296 $match = $this->parseQuery( $filteredTerm, $fulltext );
297 $query['tables'][] = 'page';
298 $query['tables'][] = 'searchindex';
299 $query['fields'][] = 'page_id';
300 $query['fields'][] = 'page_namespace';
301 $query['fields'][] = 'page_title';
302 $query['conds'][] = 'page_id=si_page';
303 $query['conds'][] = $match;
307 * @since 1.18 (changed)
310 function getCountQuery( $filteredTerm, $fulltext ) {
311 $match = $this->parseQuery( $filteredTerm, $fulltext );
314 'tables' => array( 'page', 'searchindex' ),
315 'fields' => array( 'COUNT(*) as c' ),
316 'conds' => array( 'page_id=si_page', $match ),
317 'options' => array(),
321 $this->queryFeatures( $query );
322 $this->queryNamespaces( $query );
328 * Create or update the search index record for the given page.
329 * Title and text should be pre-processed.
332 * @param $title String
333 * @param $text String
335 function update( $id, $title, $text ) {
336 $dbw = wfGetDB( DB_MASTER
);
337 $dbw->replace( 'searchindex',
341 'si_title' => $this->normalizeText( $title ),
342 'si_text' => $this->normalizeText( $text )
347 * Update a search index record's title only.
348 * Title should be pre-processed.
351 * @param $title String
353 function updateTitle( $id, $title ) {
354 $dbw = wfGetDB( DB_MASTER
);
356 $dbw->update( 'searchindex',
357 array( 'si_title' => $this->normalizeText( $title ) ),
358 array( 'si_page' => $id ),
360 array( $dbw->lowPriorityOption() ) );
364 * Delete an indexed page
365 * Title should be pre-processed.
367 * @param Integer $id Page id that was deleted
368 * @param String $title Title of page that was deleted
370 function delete( $id, $title ) {
371 $dbw = wfGetDB( DB_MASTER
);
373 $dbw->delete( 'searchindex', array( 'si_page' => $id ), __METHOD__
);
377 * Converts some characters for MySQL's indexing to grok it correctly,
378 * and pads short words to overcome limitations.
379 * @return mixed|string
381 function normalizeText( $string ) {
384 wfProfileIn( __METHOD__
);
386 $out = parent
::normalizeText( $string );
388 // MySQL fulltext index doesn't grok utf-8, so we
389 // need to fold cases and convert to hex
390 $out = preg_replace_callback(
391 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
392 array( $this, 'stripForSearchCallback' ),
393 $wgContLang->lc( $out ) );
395 // And to add insult to injury, the default indexing
396 // ignores short words... Pad them so we can pass them
397 // through without reconfiguring the server...
398 $minLength = $this->minSearchLength();
399 if ( $minLength > 1 ) {
407 // Periods within things like hostnames and IP addresses
408 // are also important -- we want a search for "example.com"
409 // or "192.168.1.1" to work sanely.
411 // MySQL's search seems to ignore them, so you'd match on
412 // "example.wikipedia.com" and "192.168.83.1" as well.
418 wfProfileOut( __METHOD__
);
424 * Armor a case-folded UTF-8 string to get through MySQL's
425 * fulltext search without being mucked up by funny charset
426 * settings or anything else of the sort.
429 protected function stripForSearchCallback( $matches ) {
430 return 'u8' . bin2hex( $matches[1] );
434 * Check MySQL server's ft_min_word_len setting so we know
435 * if we need to pad short words...
439 protected function minSearchLength() {
440 if ( is_null( self
::$mMinSearchLength ) ) {
441 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
443 $dbr = wfGetDB( DB_SLAVE
);
444 $result = $dbr->query( $sql );
445 $row = $result->fetchObject();
448 if ( $row && $row->Variable_name
== 'ft_min_word_len' ) {
449 self
::$mMinSearchLength = intval( $row->Value
);
451 self
::$mMinSearchLength = 0;
454 return self
::$mMinSearchLength;
461 class MySQLSearchResultSet
extends SqlSearchResultSet
{
462 function __construct( $resultSet, $terms, $totalHits = null ) {
463 parent
::__construct( $resultSet, $terms );
464 $this->mTotalHits
= $totalHits;
467 function getTotalHits() {
468 return $this->mTotalHits
;