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 !== '' ) {
76 if ( $this->strictMatching
&& ( $modifier == '' ) ) {
77 // If we leave this out, boolean op defaults to OR which is rarely helpful.
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 ) );
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
93 // For Chinese this also inserts spaces between adjacent Han characters.
94 $strippedVariants = array_map(
95 array( $wgContLang, 'normalizeForSearch' ),
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 ) {
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 ) {
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" );
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 ) {
140 $regex = preg_quote( $string, '/' );
141 if ( $wgContLang->hasWordBreaks() ) {
143 // Don't cut off the final bit!
146 $regex = "\b$regex\b";
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
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 ) === '' ) {
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']
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();
205 $total = intval( $row->c
);
207 $totalResult->free();
210 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
, $total );
213 public function supports( $feature ) {
215 case 'list-redirects':
216 case 'title-suffix-filter':
224 * Add special conditions
225 * @param $query Array
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
;
254 * @param $query Array
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
268 * @since 1.18 (changed)
270 function getQuery( $filteredTerm, $fulltext ) {
275 'options' => array(),
279 $this->queryMain( $query, $filteredTerm, $fulltext );
280 $this->queryFeatures( $query );
281 $this->queryNamespaces( $query );
282 $this->limitResult( $query );
288 * Picks which field to index on, depending on what type of query.
289 * @param $fulltext Boolean
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)
319 function getCountQuery( $filteredTerm, $fulltext ) {
320 $match = $this->parseQuery( $filteredTerm, $fulltext );
323 'tables' => array( 'page', 'searchindex' ),
324 'fields' => array( 'COUNT(*) as c' ),
325 'conds' => array( 'page_id=si_page', $match ),
326 'options' => array(),
330 $this->queryFeatures( $query );
331 $this->queryNamespaces( $query );
337 * Create or update the search index record for the given page.
338 * Title and text should be pre-processed.
341 * @param $title String
342 * @param $text String
344 function update( $id, $title, $text ) {
345 $dbw = wfGetDB( DB_MASTER
);
346 $dbw->replace( 'searchindex',
350 'si_title' => $this->normalizeText( $title ),
351 'si_text' => $this->normalizeText( $text )
356 * Update a search index record's title only.
357 * Title should be pre-processed.
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 ),
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 ) {
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 ) {
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.
414 wfProfileOut( __METHOD__
);
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.
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...
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();
444 if ( $row && $row->Variable_name
== 'ft_min_word_len' ) {
445 self
::$mMinSearchLength = intval( $row->Value
);
447 self
::$mMinSearchLength = 0;
450 return self
::$mMinSearchLength;
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
;