2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
26 * Search engine hook for MySQL 4+
29 class SearchMySQL
extends SearchEngine
{
30 var $strictMatching = true;
31 static $mMinSearchLength;
34 function __construct( $db ) {
39 * Parse the user's query and transform it into an SQL fragment which will
40 * become part of a WHERE clause
42 function parseQuery( $filteredText, $fulltext ) {
44 $lc = SearchEngine
::legalSearchChars(); // Minus format chars
46 $this->searchTerms
= array();
48 # FIXME: This doesn't handle parenthetical expressions.
50 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
51 $filteredText, $m, PREG_SET_ORDER
) ) {
52 foreach( $m as $bits ) {
53 @list
( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
55 if( $nonQuoted != '' ) {
59 $term = str_replace( '"', '', $term );
63 if( $searchon !== '' ) $searchon .= ' ';
64 if( $this->strictMatching
&& ($modifier == '') ) {
65 // If we leave this out, boolean op defaults to OR which is rarely helpful.
69 // Some languages such as Serbian store the input form in the search index,
70 // so we may need to search for matches in multiple writing system variants.
71 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
72 if( is_array( $convertedVariants ) ) {
73 $variants = array_unique( array_values( $convertedVariants ) );
75 $variants = array( $term );
78 // The low-level search index does some processing on input to work
79 // around problems with minimum lengths and encoding in MySQL's
81 // For Chinese this also inserts spaces between adjacent Han characters.
82 $strippedVariants = array_map(
83 array( $wgContLang, 'stripForSearch' ),
86 // Some languages such as Chinese force all variants to a canonical
87 // form when stripping to the low-level search index, so to be sure
88 // let's check our variants list for unique items after stripping.
89 $strippedVariants = array_unique( $strippedVariants );
91 $searchon .= $modifier;
92 if( count( $strippedVariants) > 1 )
94 foreach( $strippedVariants as $stripped ) {
95 $stripped = $this->normalizeText( $stripped );
96 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
97 // Hack for Chinese: we need to toss in quotes for
98 // multiple-character phrases since stripForSearch()
99 // added spaces between them to make word breaks.
100 $stripped = '"' . trim( $stripped ) . '"';
102 $searchon .= "$quote$stripped$quote$wildcard ";
104 if( count( $strippedVariants) > 1 )
107 // Match individual terms or quoted phrase in result highlighting...
108 // Note that variants will be introduced in a later stage for highlighting!
109 $regexp = $this->regexTerm( $term, $wildcard );
110 $this->searchTerms
[] = $regexp;
112 wfDebug( __METHOD__
. ": Would search with '$searchon'\n" );
113 wfDebug( __METHOD__
. ': Match with /' . implode( '|', $this->searchTerms
) . "/\n" );
115 wfDebug( __METHOD__
. ": Can't understand search query '{$filteredText}'\n" );
118 $searchon = $this->db
->strencode( $searchon );
119 $field = $this->getIndexField( $fulltext );
120 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
123 function regexTerm( $string, $wildcard ) {
126 $regex = preg_quote( $string, '/' );
127 if( $wgContLang->hasWordBreaks() ) {
129 // Don't cut off the final bit!
132 $regex = "\b$regex\b";
135 // For Chinese, words may legitimately abut other words in the text literal.
136 // Don't add \b boundary checks... note this could cause false positives
142 public static function legalSearchChars() {
143 return "\"*" . parent
::legalSearchChars();
147 * Perform a full text search query and return a result set.
149 * @param $term String: raw search term
150 * @return MySQLSearchResultSet
152 function searchText( $term ) {
153 return $this->searchInternal( $term, true );
157 * Perform a title-only search query and return a result set.
159 * @param $term String: raw search term
160 * @return MySQLSearchResultSet
162 function searchTitle( $term ) {
163 return $this->searchInternal( $term, false );
166 protected function searchInternal( $term, $fulltext ) {
167 global $wgCountTotalSearchHits;
169 $filteredTerm = $this->filter( $term );
170 $resultSet = $this->db
->query( $this->getQuery( $filteredTerm, $fulltext ) );
173 if( $wgCountTotalSearchHits ) {
174 $totalResult = $this->db
->query( $this->getCountQuery( $filteredTerm, $fulltext ) );
175 $row = $totalResult->fetchObject();
177 $total = intval( $row->c
);
179 $totalResult->free();
182 return new MySQLSearchResultSet( $resultSet, $this->searchTerms
, $total );
187 * Return a partial WHERE clause to exclude redirects, if so set
190 function queryRedirect() {
191 if( $this->showRedirects
) {
194 return 'AND page_is_redirect=0';
199 * Return a partial WHERE clause to limit the search to the given namespaces
202 function queryNamespaces() {
203 if( is_null($this->namespaces
) )
204 return ''; # search all
205 if ( !count( $this->namespaces
) ) {
208 $namespaces = $this->db
->makeList( $this->namespaces
);
210 return 'AND page_namespace IN (' . $namespaces . ')';
214 * Return a LIMIT clause to limit results on the query.
217 function queryLimit() {
218 return $this->db
->limitResult( '', $this->limit
, $this->offset
);
222 * Does not do anything for generic search engine
223 * subclasses may define this though
226 function queryRanking( $filteredTerm, $fulltext ) {
231 * Construct the full SQL query to do the search.
232 * The guts shoulds be constructed in queryMain()
233 * @param $filteredTerm String
234 * @param $fulltext Boolean
236 function getQuery( $filteredTerm, $fulltext ) {
237 return $this->queryMain( $filteredTerm, $fulltext ) . ' ' .
238 $this->queryRedirect() . ' ' .
239 $this->queryNamespaces() . ' ' .
240 $this->queryRanking( $filteredTerm, $fulltext ) . ' ' .
245 * Picks which field to index on, depending on what type of query.
246 * @param $fulltext Boolean
249 function getIndexField( $fulltext ) {
250 return $fulltext ?
'si_text' : 'si_title';
254 * Get the base part of the search query.
255 * The actual match syntax will depend on the server
256 * version; MySQL 3 and MySQL 4 have different capabilities
257 * in their fulltext search indexes.
259 * @param $filteredTerm String
260 * @param $fulltext Boolean
263 function queryMain( $filteredTerm, $fulltext ) {
264 $match = $this->parseQuery( $filteredTerm, $fulltext );
265 $page = $this->db
->tableName( 'page' );
266 $searchindex = $this->db
->tableName( 'searchindex' );
267 return 'SELECT page_id, page_namespace, page_title ' .
268 "FROM $page,$searchindex " .
269 'WHERE page_id=si_page AND ' . $match;
272 function getCountQuery( $filteredTerm, $fulltext ) {
273 $match = $this->parseQuery( $filteredTerm, $fulltext );
274 $page = $this->db
->tableName( 'page' );
275 $searchindex = $this->db
->tableName( 'searchindex' );
276 return "SELECT COUNT(*) AS c " .
277 "FROM $page,$searchindex " .
278 'WHERE page_id=si_page AND ' . $match .
279 $this->queryRedirect() . ' ' .
280 $this->queryNamespaces();
284 * Create or update the search index record for the given page.
285 * Title and text should be pre-processed.
288 * @param $title String
289 * @param $text String
291 function update( $id, $title, $text ) {
292 $dbw = wfGetDB( DB_MASTER
);
293 $dbw->replace( 'searchindex',
297 'si_title' => $this->normalizeText( $title ),
298 'si_text' => $this->normalizeText( $text )
303 * Update a search index record's title only.
304 * Title should be pre-processed.
307 * @param $title String
309 function updateTitle( $id, $title ) {
310 $dbw = wfGetDB( DB_MASTER
);
312 $dbw->update( 'searchindex',
313 array( 'si_title' => $this->normalizeText( $title ) ),
314 array( 'si_page' => $id ),
316 array( $dbw->lowPriorityOption() ) );
320 * Converts some characters for MySQL's indexing to grok it correctly,
321 * and pads short words to overcome limitations.
323 function normalizeText( $string ) {
326 wfProfileIn( __METHOD__
);
328 // MySQL fulltext index doesn't grok utf-8, so we
329 // need to fold cases and convert to hex
330 $out = preg_replace_callback(
331 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
332 array( $this, 'stripForSearchCallback' ),
333 $wgContLang->lc( $string ) );
335 // And to add insult to injury, the default indexing
336 // ignores short words... Pad them so we can pass them
337 // through without reconfiguring the server...
338 $minLength = $this->minSearchLength();
339 if( $minLength > 1 ) {
347 // Periods within things like hostnames and IP addresses
348 // are also important -- we want a search for "example.com"
349 // or "192.168.1.1" to work sanely.
351 // MySQL's search seems to ignore them, so you'd match on
352 // "example.wikipedia.com" and "192.168.83.1" as well.
358 wfProfileOut( __METHOD__
);
364 * Armor a case-folded UTF-8 string to get through MySQL's
365 * fulltext search without being mucked up by funny charset
366 * settings or anything else of the sort.
368 protected function stripForSearchCallback( $matches ) {
369 return 'u8' . bin2hex( $matches[1] );
373 * Check MySQL server's ft_min_word_len setting so we know
374 * if we need to pad short words...
378 protected function minSearchLength() {
379 if( is_null( self
::$mMinSearchLength ) ) {
380 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
382 $dbr = wfGetDB( DB_SLAVE
);
383 $result = $dbr->query( $sql );
384 $row = $result->fetchObject();
387 if( $row && $row->Variable_name
== 'ft_min_word_len' ) {
388 self
::$mMinSearchLength = intval( $row->Value
);
390 self
::$mMinSearchLength = 0;
393 return self
::$mMinSearchLength;
400 class MySQLSearchResultSet
extends SqlSearchResultSet
{
401 function MySQLSearchResultSet( $resultSet, $terms, $totalHits=null ) {
402 parent
::__construct( $resultSet, $terms );
403 $this->mTotalHits
= $totalHits;
406 function getTotalHits() {
407 return $this->mTotalHits
;