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 function parseQuery( $filteredText, $fulltext ) {
49 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
51 $this->searchTerms
= array();
53 # FIXME: This doesn't handle parenthetical expressions.
55 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
56 $filteredText, $m, PREG_SET_ORDER
) ) {
57 foreach( $m as $bits ) {
58 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
60 if( $nonQuoted != '' ) {
64 $term = str_replace( '"', '', $term );
68 if( $searchon !== '' ) $searchon .= ' ';
69 if( $this->strictMatching
&& ($modifier == '') ) {
70 // If we leave this out, boolean op defaults to OR which is rarely helpful.
74 // Some languages such as Serbian store the input form in the search index,
75 // so we may need to search for matches in multiple writing system variants.
76 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
77 if( is_array( $convertedVariants ) ) {
78 $variants = array_unique( array_values( $convertedVariants ) );
80 $variants = array( $term );
83 // The low-level search index does some processing on input to work
84 // around problems with minimum lengths and encoding in MySQL's
86 // For Chinese this also inserts spaces between adjacent Han characters.
87 $strippedVariants = array_map(
88 array( $wgContLang, 'normalizeForSearch' ),
91 // Some languages such as Chinese force all variants to a canonical
92 // form when stripping to the low-level search index, so to be sure
93 // let's check our variants list for unique items after stripping.
94 $strippedVariants = array_unique( $strippedVariants );
96 $searchon .= $modifier;
97 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 )
112 // Match individual terms or quoted phrase in result highlighting...
113 // Note that variants will be introduced in a later stage for highlighting!
114 $regexp = $this->regexTerm( $term, $wildcard );
115 $this->searchTerms
[] = $regexp;
117 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
118 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
120 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
123 $searchon = $this->db
->strencode( $searchon );
124 $field = $this->getIndexField( $fulltext );
125 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
128 function regexTerm( $string, $wildcard ) {
131 $regex = preg_quote( $string, '/' );
132 if( $wgContLang->hasWordBreaks() ) {
134 // Don't cut off the final bit!
137 $regex = "\b$regex\b";
140 // For Chinese, words may legitimately abut other words in the text literal.
141 // Don't add \b boundary checks... note this could cause false positives
147 public static function legalSearchChars() {
148 return "\"*" . parent
::legalSearchChars();
152 * Perform a full text search query and return a result set.
154 * @param $term String: raw search term
155 * @return MySQLSearchResultSet
157 function searchText( $term ) {
158 return $this->searchInternal( $term, true );
162 * Perform a title-only search query and return a result set.
164 * @param $term String: raw search term
165 * @return MySQLSearchResultSet
167 function searchTitle( $term ) {
168 return $this->searchInternal( $term, false );
171 protected function searchInternal( $term, $fulltext ) {
172 global $wgCountTotalSearchHits;
174 // This seems of place, why is this called with empty term?
175 if ( trim( $term ) === '' ) return null;
177 $filteredTerm = $this->filter( $term );
178 $query = $this->getQuery( $filteredTerm, $fulltext );
179 $resultSet = $this->db
->select(
180 $query['tables'], $query['fields'], $query['conds'],
181 __METHOD__
, $query['options'], $query['joins']
185 if( $wgCountTotalSearchHits ) {
186 $query = $this->getCountQuery( $filteredTerm, $fulltext );
187 $totalResult = $this->db
->select(
188 $query['tables'], $query['fields'], $query['conds'],
189 __METHOD__
, $query['options'], $query['joins']
192 $row = $totalResult->fetchObject();
194 $total = intval( $row->c
);
196 $totalResult->free();
199 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
, $total );
204 * Add redirect conditions
205 * @param $query Array
206 * @since 1.18 (changed)
208 function queryRedirect( &$query ) {
209 if( !$this->showRedirects
) {
210 $query['conds']['page_is_redirect'] = 0;
215 * Add namespace conditions
216 * @param $query Array
217 * @since 1.18 (changed)
219 function queryNamespaces( &$query ) {
220 if ( is_array( $this->namespaces
) ) {
221 if ( count( $this->namespaces
) === 0 ) {
222 $this->namespaces
[] = '0';
224 $query['conds']['page_namespace'] = $this->namespaces
;
230 * @param $query Array
233 protected function limitResult( &$query ) {
234 $query['options']['LIMIT'] = $this->limit
;
235 $query['options']['OFFSET'] = $this->offset
;
239 * Construct the SQL query to do the search.
240 * The guts shoulds be constructed in queryMain()
241 * @param $filteredTerm String
242 * @param $fulltext Boolean
244 * @since 1.18 (changed)
246 function getQuery( $filteredTerm, $fulltext ) {
251 'options' => array(),
255 $this->queryMain( $query, $filteredTerm, $fulltext );
256 $this->queryRedirect( $query );
257 $this->queryNamespaces( $query );
258 $this->limitResult( $query );
264 * Picks which field to index on, depending on what type of query.
265 * @param $fulltext Boolean
268 function getIndexField( $fulltext ) {
269 return $fulltext ?
'si_text' : 'si_title';
273 * Get the base part of the search query.
275 * @param $filteredTerm String
276 * @param $fulltext Boolean
277 * @since 1.18 (changed)
279 function queryMain( &$query, $filteredTerm, $fulltext ) {
280 $match = $this->parseQuery( $filteredTerm, $fulltext );
281 $query['tables'][] = 'page';
282 $query['tables'][] = 'searchindex';
283 $query['fields'][] = 'page_id';
284 $query['fields'][] = 'page_namespace';
285 $query['fields'][] = 'page_title';
286 $query['conds'][] = 'page_id=si_page';
287 $query['conds'][] = $match;
291 * @since 1.18 (changed)
293 function getCountQuery( $filteredTerm, $fulltext ) {
294 $match = $this->parseQuery( $filteredTerm, $fulltext );
297 'tables' => array( 'page', 'searchindex' ),
298 'fields' => array( 'COUNT(*) as c' ),
299 'conds' => array( 'page_id=si_page', $match ),
300 'options' => array(),
304 $this->queryRedirect( $query );
305 $this->queryNamespaces( $query );
311 * Create or update the search index record for the given page.
312 * Title and text should be pre-processed.
315 * @param $title String
316 * @param $text String
318 function update( $id, $title, $text ) {
319 $dbw = wfGetDB( DB_MASTER
);
320 $dbw->replace( 'searchindex',
324 'si_title' => $this->normalizeText( $title ),
325 'si_text' => $this->normalizeText( $text )
330 * Update a search index record's title only.
331 * Title should be pre-processed.
334 * @param $title String
336 function updateTitle( $id, $title ) {
337 $dbw = wfGetDB( DB_MASTER
);
339 $dbw->update( 'searchindex',
340 array( 'si_title' => $this->normalizeText( $title ) ),
341 array( 'si_page' => $id ),
343 array( $dbw->lowPriorityOption() ) );
347 * Converts some characters for MySQL's indexing to grok it correctly,
348 * and pads short words to overcome limitations.
350 function normalizeText( $string ) {
353 wfProfileIn( __METHOD__
);
355 $out = parent
::normalizeText( $string );
357 // MySQL fulltext index doesn't grok utf-8, so we
358 // need to fold cases and convert to hex
359 $out = preg_replace_callback(
360 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
361 array( $this, 'stripForSearchCallback' ),
362 $wgContLang->lc( $out ) );
364 // And to add insult to injury, the default indexing
365 // ignores short words... Pad them so we can pass them
366 // through without reconfiguring the server...
367 $minLength = $this->minSearchLength();
368 if( $minLength > 1 ) {
376 // Periods within things like hostnames and IP addresses
377 // are also important -- we want a search for "example.com"
378 // or "192.168.1.1" to work sanely.
380 // MySQL's search seems to ignore them, so you'd match on
381 // "example.wikipedia.com" and "192.168.83.1" as well.
387 wfProfileOut( __METHOD__
);
393 * Armor a case-folded UTF-8 string to get through MySQL's
394 * fulltext search without being mucked up by funny charset
395 * settings or anything else of the sort.
397 protected function stripForSearchCallback( $matches ) {
398 return 'u8' . bin2hex( $matches[1] );
402 * Check MySQL server's ft_min_word_len setting so we know
403 * if we need to pad short words...
407 protected function minSearchLength() {
408 if( is_null( self
::$mMinSearchLength ) ) {
409 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
411 $dbr = wfGetDB( DB_SLAVE
);
412 $result = $dbr->query( $sql );
413 $row = $result->fetchObject();
416 if( $row && $row->Variable_name
== 'ft_min_word_len' ) {
417 self
::$mMinSearchLength = intval( $row->Value
);
419 self
::$mMinSearchLength = 0;
422 return self
::$mMinSearchLength;
429 class MySQLSearchResultSet
extends SqlSearchResultSet
{
430 function __construct( $resultSet, $terms, $totalHits=null ) {
431 parent
::__construct( $resultSet, $terms );
432 $this->mTotalHits
= $totalHits;
435 function getTotalHits() {
436 return $this->mTotalHits
;