Use consistent notation for "@todo FIXME". Should update http://svn.wikimedia.org...
[lhc/web/wiklou.git] / includes / search / SearchMySQL.php
1 <?php
2 /**
3 * MySQL search engine
4 *
5 * Copyright (C) 2004 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @ingroup Search
25 */
26
27 /**
28 * Search engine hook for MySQL 4+
29 * @ingroup Search
30 */
31 class SearchMySQL extends SearchEngine {
32 var $strictMatching = true;
33 static $mMinSearchLength;
34
35 /**
36 * Creates an instance of this class
37 * @param $db DatabaseMysql: database object
38 */
39 function __construct( $db ) {
40 parent::__construct( $db );
41 }
42
43 /**
44 * Parse the user's query and transform it into an SQL fragment which will
45 * become part of a WHERE clause
46 */
47 function parseQuery( $filteredText, $fulltext ) {
48 global $wgContLang;
49 $lc = SearchEngine::legalSearchChars(); // Minus format chars
50 $searchon = '';
51 $this->searchTerms = array();
52
53 # @todo FIXME: This doesn't handle parenthetical expressions.
54 $m = array();
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;
59
60 if( $nonQuoted != '' ) {
61 $term = $nonQuoted;
62 $quote = '';
63 } else {
64 $term = str_replace( '"', '', $term );
65 $quote = '"';
66 }
67
68 if( $searchon !== '' ) $searchon .= ' ';
69 if( $this->strictMatching && ($modifier == '') ) {
70 // If we leave this out, boolean op defaults to OR which is rarely helpful.
71 $modifier = '+';
72 }
73
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 ) );
79 } else {
80 $variants = array( $term );
81 }
82
83 // The low-level search index does some processing on input to work
84 // around problems with minimum lengths and encoding in MySQL's
85 // fulltext engine.
86 // For Chinese this also inserts spaces between adjacent Han characters.
87 $strippedVariants = array_map(
88 array( $wgContLang, 'normalizeForSearch' ),
89 $variants );
90
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 );
95
96 $searchon .= $modifier;
97 if( count( $strippedVariants) > 1 )
98 $searchon .= '(';
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 ) . '"';
106 }
107 $searchon .= "$quote$stripped$quote$wildcard ";
108 }
109 if( count( $strippedVariants) > 1 )
110 $searchon .= ')';
111
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;
116 }
117 wfDebug( __METHOD__ . ": Would search with '$searchon'\n" );
118 wfDebug( __METHOD__ . ': Match with /' . implode( '|', $this->searchTerms ) . "/\n" );
119 } else {
120 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
121 }
122
123 $searchon = $this->db->strencode( $searchon );
124 $field = $this->getIndexField( $fulltext );
125 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
126 }
127
128 function regexTerm( $string, $wildcard ) {
129 global $wgContLang;
130
131 $regex = preg_quote( $string, '/' );
132 if( $wgContLang->hasWordBreaks() ) {
133 if( $wildcard ) {
134 // Don't cut off the final bit!
135 $regex = "\b$regex";
136 } else {
137 $regex = "\b$regex\b";
138 }
139 } else {
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
142 // for latin chars.
143 }
144 return $regex;
145 }
146
147 public static function legalSearchChars() {
148 return "\"*" . parent::legalSearchChars();
149 }
150
151 /**
152 * Perform a full text search query and return a result set.
153 *
154 * @param $term String: raw search term
155 * @return MySQLSearchResultSet
156 */
157 function searchText( $term ) {
158 return $this->searchInternal( $term, true );
159 }
160
161 /**
162 * Perform a title-only search query and return a result set.
163 *
164 * @param $term String: raw search term
165 * @return MySQLSearchResultSet
166 */
167 function searchTitle( $term ) {
168 return $this->searchInternal( $term, false );
169 }
170
171 protected function searchInternal( $term, $fulltext ) {
172 global $wgCountTotalSearchHits;
173
174 // This seems out of place, why is this called with empty term?
175 if ( trim( $term ) === '' ) return null;
176
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']
182 );
183
184 $total = null;
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']
190 );
191
192 $row = $totalResult->fetchObject();
193 if( $row ) {
194 $total = intval( $row->c );
195 }
196 $totalResult->free();
197 }
198
199 return new MySQLSearchResultSet( $resultSet, $this->searchTerms, $total );
200 }
201
202 public function supports( $feature ) {
203 switch( $feature ) {
204 case 'list-redirects':
205 case 'title-suffix-filter':
206 return true;
207 default:
208 return false;
209 }
210 }
211
212 /**
213 * Add special conditions
214 * @param $query Array
215 * @since 1.18
216 */
217 protected function queryFeatures( &$query ) {
218 foreach ( $this->features as $feature => $value ) {
219 if ( $feature === 'list-redirects' && !$value ) {
220 $query['conds']['page_is_redirect'] = 0;
221 } elseif( $feature === 'title-suffix-filter' && $value ) {
222 $query['conds'][] = 'page_title' . $this->db->buildLike( $this->db->anyString(), $value );
223 }
224 }
225 }
226
227 /**
228 * Add namespace conditions
229 * @param $query Array
230 * @since 1.18 (changed)
231 */
232 function queryNamespaces( &$query ) {
233 if ( is_array( $this->namespaces ) ) {
234 if ( count( $this->namespaces ) === 0 ) {
235 $this->namespaces[] = '0';
236 }
237 $query['conds']['page_namespace'] = $this->namespaces;
238 }
239 }
240
241 /**
242 * Add limit options
243 * @param $query Array
244 * @since 1.18
245 */
246 protected function limitResult( &$query ) {
247 $query['options']['LIMIT'] = $this->limit;
248 $query['options']['OFFSET'] = $this->offset;
249 }
250
251 /**
252 * Construct the SQL query to do the search.
253 * The guts shoulds be constructed in queryMain()
254 * @param $filteredTerm String
255 * @param $fulltext Boolean
256 * @return Array
257 * @since 1.18 (changed)
258 */
259 function getQuery( $filteredTerm, $fulltext ) {
260 $query = array(
261 'tables' => array(),
262 'fields' => array(),
263 'conds' => array(),
264 'options' => array(),
265 'joins' => array(),
266 );
267
268 $this->queryMain( $query, $filteredTerm, $fulltext );
269 $this->queryFeatures( $query );
270 $this->queryNamespaces( $query );
271 $this->limitResult( $query );
272
273 return $query;
274 }
275
276 /**
277 * Picks which field to index on, depending on what type of query.
278 * @param $fulltext Boolean
279 * @return String
280 */
281 function getIndexField( $fulltext ) {
282 return $fulltext ? 'si_text' : 'si_title';
283 }
284
285 /**
286 * Get the base part of the search query.
287 *
288 * @param $filteredTerm String
289 * @param $fulltext Boolean
290 * @since 1.18 (changed)
291 */
292 function queryMain( &$query, $filteredTerm, $fulltext ) {
293 $match = $this->parseQuery( $filteredTerm, $fulltext );
294 $query['tables'][] = 'page';
295 $query['tables'][] = 'searchindex';
296 $query['fields'][] = 'page_id';
297 $query['fields'][] = 'page_namespace';
298 $query['fields'][] = 'page_title';
299 $query['conds'][] = 'page_id=si_page';
300 $query['conds'][] = $match;
301 }
302
303 /**
304 * @since 1.18 (changed)
305 */
306 function getCountQuery( $filteredTerm, $fulltext ) {
307 $match = $this->parseQuery( $filteredTerm, $fulltext );
308
309 $query = array(
310 'tables' => array( 'page', 'searchindex' ),
311 'fields' => array( 'COUNT(*) as c' ),
312 'conds' => array( 'page_id=si_page', $match ),
313 'options' => array(),
314 'joins' => array(),
315 );
316
317 $this->queryFeatures( $query );
318 $this->queryNamespaces( $query );
319
320 return $query;
321 }
322
323 /**
324 * Create or update the search index record for the given page.
325 * Title and text should be pre-processed.
326 *
327 * @param $id Integer
328 * @param $title String
329 * @param $text String
330 */
331 function update( $id, $title, $text ) {
332 $dbw = wfGetDB( DB_MASTER );
333 $dbw->replace( 'searchindex',
334 array( 'si_page' ),
335 array(
336 'si_page' => $id,
337 'si_title' => $this->normalizeText( $title ),
338 'si_text' => $this->normalizeText( $text )
339 ), __METHOD__ );
340 }
341
342 /**
343 * Update a search index record's title only.
344 * Title should be pre-processed.
345 *
346 * @param $id Integer
347 * @param $title String
348 */
349 function updateTitle( $id, $title ) {
350 $dbw = wfGetDB( DB_MASTER );
351
352 $dbw->update( 'searchindex',
353 array( 'si_title' => $this->normalizeText( $title ) ),
354 array( 'si_page' => $id ),
355 __METHOD__,
356 array( $dbw->lowPriorityOption() ) );
357 }
358
359 /**
360 * Converts some characters for MySQL's indexing to grok it correctly,
361 * and pads short words to overcome limitations.
362 */
363 function normalizeText( $string ) {
364 global $wgContLang;
365
366 wfProfileIn( __METHOD__ );
367
368 $out = parent::normalizeText( $string );
369
370 // MySQL fulltext index doesn't grok utf-8, so we
371 // need to fold cases and convert to hex
372 $out = preg_replace_callback(
373 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
374 array( $this, 'stripForSearchCallback' ),
375 $wgContLang->lc( $out ) );
376
377 // And to add insult to injury, the default indexing
378 // ignores short words... Pad them so we can pass them
379 // through without reconfiguring the server...
380 $minLength = $this->minSearchLength();
381 if( $minLength > 1 ) {
382 $n = $minLength - 1;
383 $out = preg_replace(
384 "/\b(\w{1,$n})\b/",
385 "$1u800",
386 $out );
387 }
388
389 // Periods within things like hostnames and IP addresses
390 // are also important -- we want a search for "example.com"
391 // or "192.168.1.1" to work sanely.
392 //
393 // MySQL's search seems to ignore them, so you'd match on
394 // "example.wikipedia.com" and "192.168.83.1" as well.
395 $out = preg_replace(
396 "/(\w)\.(\w|\*)/u",
397 "$1u82e$2",
398 $out );
399
400 wfProfileOut( __METHOD__ );
401
402 return $out;
403 }
404
405 /**
406 * Armor a case-folded UTF-8 string to get through MySQL's
407 * fulltext search without being mucked up by funny charset
408 * settings or anything else of the sort.
409 */
410 protected function stripForSearchCallback( $matches ) {
411 return 'u8' . bin2hex( $matches[1] );
412 }
413
414 /**
415 * Check MySQL server's ft_min_word_len setting so we know
416 * if we need to pad short words...
417 *
418 * @return int
419 */
420 protected function minSearchLength() {
421 if( is_null( self::$mMinSearchLength ) ) {
422 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
423
424 $dbr = wfGetDB( DB_SLAVE );
425 $result = $dbr->query( $sql );
426 $row = $result->fetchObject();
427 $result->free();
428
429 if( $row && $row->Variable_name == 'ft_min_word_len' ) {
430 self::$mMinSearchLength = intval( $row->Value );
431 } else {
432 self::$mMinSearchLength = 0;
433 }
434 }
435 return self::$mMinSearchLength;
436 }
437 }
438
439 /**
440 * @ingroup Search
441 */
442 class MySQLSearchResultSet extends SqlSearchResultSet {
443 function __construct( $resultSet, $terms, $totalHits=null ) {
444 parent::__construct( $resultSet, $terms );
445 $this->mTotalHits = $totalHits;
446 }
447
448 function getTotalHits() {
449 return $this->mTotalHits;
450 }
451 }