And even more documentation, the last of this batch
[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 * @return string
48 */
49 function parseQuery( $filteredText, $fulltext ) {
50 global $wgContLang;
51 $lc = SearchEngine::legalSearchChars(); // Minus format chars
52 $searchon = '';
53 $this->searchTerms = array();
54
55 # @todo FIXME: This doesn't handle parenthetical expressions.
56 $m = array();
57 if( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
58 $filteredText, $m, PREG_SET_ORDER ) ) {
59 foreach( $m as $bits ) {
60 @list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
61
62 if( $nonQuoted != '' ) {
63 $term = $nonQuoted;
64 $quote = '';
65 } else {
66 $term = str_replace( '"', '', $term );
67 $quote = '"';
68 }
69
70 if( $searchon !== '' ) $searchon .= ' ';
71 if( $this->strictMatching && ($modifier == '') ) {
72 // If we leave this out, boolean op defaults to OR which is rarely helpful.
73 $modifier = '+';
74 }
75
76 // Some languages such as Serbian store the input form in the search index,
77 // so we may need to search for matches in multiple writing system variants.
78 $convertedVariants = $wgContLang->autoConvertToAllVariants( $term );
79 if( is_array( $convertedVariants ) ) {
80 $variants = array_unique( array_values( $convertedVariants ) );
81 } else {
82 $variants = array( $term );
83 }
84
85 // The low-level search index does some processing on input to work
86 // around problems with minimum lengths and encoding in MySQL's
87 // fulltext engine.
88 // For Chinese this also inserts spaces between adjacent Han characters.
89 $strippedVariants = array_map(
90 array( $wgContLang, 'normalizeForSearch' ),
91 $variants );
92
93 // Some languages such as Chinese force all variants to a canonical
94 // form when stripping to the low-level search index, so to be sure
95 // let's check our variants list for unique items after stripping.
96 $strippedVariants = array_unique( $strippedVariants );
97
98 $searchon .= $modifier;
99 if( count( $strippedVariants) > 1 )
100 $searchon .= '(';
101 foreach( $strippedVariants as $stripped ) {
102 $stripped = $this->normalizeText( $stripped );
103 if( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
104 // Hack for Chinese: we need to toss in quotes for
105 // multiple-character phrases since normalizeForSearch()
106 // added spaces between them to make word breaks.
107 $stripped = '"' . trim( $stripped ) . '"';
108 }
109 $searchon .= "$quote$stripped$quote$wildcard ";
110 }
111 if( count( $strippedVariants) > 1 )
112 $searchon .= ')';
113
114 // Match individual terms or quoted phrase in result highlighting...
115 // Note that variants will be introduced in a later stage for highlighting!
116 $regexp = $this->regexTerm( $term, $wildcard );
117 $this->searchTerms[] = $regexp;
118 }
119 wfDebug( __METHOD__ . ": Would search with '$searchon'\n" );
120 wfDebug( __METHOD__ . ': Match with /' . implode( '|', $this->searchTerms ) . "/\n" );
121 } else {
122 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'\n" );
123 }
124
125 $searchon = $this->db->strencode( $searchon );
126 $field = $this->getIndexField( $fulltext );
127 return " MATCH($field) AGAINST('$searchon' IN BOOLEAN MODE) ";
128 }
129
130 function regexTerm( $string, $wildcard ) {
131 global $wgContLang;
132
133 $regex = preg_quote( $string, '/' );
134 if( $wgContLang->hasWordBreaks() ) {
135 if( $wildcard ) {
136 // Don't cut off the final bit!
137 $regex = "\b$regex";
138 } else {
139 $regex = "\b$regex\b";
140 }
141 } else {
142 // For Chinese, words may legitimately abut other words in the text literal.
143 // Don't add \b boundary checks... note this could cause false positives
144 // for latin chars.
145 }
146 return $regex;
147 }
148
149 public static function legalSearchChars() {
150 return "\"*" . parent::legalSearchChars();
151 }
152
153 /**
154 * Perform a full text search query and return a result set.
155 *
156 * @param $term String: raw search term
157 * @return MySQLSearchResultSet
158 */
159 function searchText( $term ) {
160 return $this->searchInternal( $term, true );
161 }
162
163 /**
164 * Perform a title-only search query and return a result set.
165 *
166 * @param $term String: raw search term
167 * @return MySQLSearchResultSet
168 */
169 function searchTitle( $term ) {
170 return $this->searchInternal( $term, false );
171 }
172
173 protected function searchInternal( $term, $fulltext ) {
174 global $wgCountTotalSearchHits;
175
176 // This seems out of place, why is this called with empty term?
177 if ( trim( $term ) === '' ) return null;
178
179 $filteredTerm = $this->filter( $term );
180 $query = $this->getQuery( $filteredTerm, $fulltext );
181 $resultSet = $this->db->select(
182 $query['tables'], $query['fields'], $query['conds'],
183 __METHOD__, $query['options'], $query['joins']
184 );
185
186 $total = null;
187 if( $wgCountTotalSearchHits ) {
188 $query = $this->getCountQuery( $filteredTerm, $fulltext );
189 $totalResult = $this->db->select(
190 $query['tables'], $query['fields'], $query['conds'],
191 __METHOD__, $query['options'], $query['joins']
192 );
193
194 $row = $totalResult->fetchObject();
195 if( $row ) {
196 $total = intval( $row->c );
197 }
198 $totalResult->free();
199 }
200
201 return new MySQLSearchResultSet( $resultSet, $this->searchTerms, $total );
202 }
203
204 public function supports( $feature ) {
205 switch( $feature ) {
206 case 'list-redirects':
207 case 'title-suffix-filter':
208 return true;
209 default:
210 return false;
211 }
212 }
213
214 /**
215 * Add special conditions
216 * @param $query Array
217 * @since 1.18
218 */
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 );
225 }
226 }
227 }
228
229 /**
230 * Add namespace conditions
231 * @param $query Array
232 * @since 1.18 (changed)
233 */
234 function queryNamespaces( &$query ) {
235 if ( is_array( $this->namespaces ) ) {
236 if ( count( $this->namespaces ) === 0 ) {
237 $this->namespaces[] = '0';
238 }
239 $query['conds']['page_namespace'] = $this->namespaces;
240 }
241 }
242
243 /**
244 * Add limit options
245 * @param $query Array
246 * @since 1.18
247 */
248 protected function limitResult( &$query ) {
249 $query['options']['LIMIT'] = $this->limit;
250 $query['options']['OFFSET'] = $this->offset;
251 }
252
253 /**
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
258 * @return Array
259 * @since 1.18 (changed)
260 */
261 function getQuery( $filteredTerm, $fulltext ) {
262 $query = array(
263 'tables' => array(),
264 'fields' => array(),
265 'conds' => array(),
266 'options' => array(),
267 'joins' => array(),
268 );
269
270 $this->queryMain( $query, $filteredTerm, $fulltext );
271 $this->queryFeatures( $query );
272 $this->queryNamespaces( $query );
273 $this->limitResult( $query );
274
275 return $query;
276 }
277
278 /**
279 * Picks which field to index on, depending on what type of query.
280 * @param $fulltext Boolean
281 * @return String
282 */
283 function getIndexField( $fulltext ) {
284 return $fulltext ? 'si_text' : 'si_title';
285 }
286
287 /**
288 * Get the base part of the search query.
289 *
290 * @param $filteredTerm String
291 * @param $fulltext Boolean
292 * @since 1.18 (changed)
293 */
294 function queryMain( &$query, $filteredTerm, $fulltext ) {
295 $match = $this->parseQuery( $filteredTerm, $fulltext );
296 $query['tables'][] = 'page';
297 $query['tables'][] = 'searchindex';
298 $query['fields'][] = 'page_id';
299 $query['fields'][] = 'page_namespace';
300 $query['fields'][] = 'page_title';
301 $query['conds'][] = 'page_id=si_page';
302 $query['conds'][] = $match;
303 }
304
305 /**
306 * @since 1.18 (changed)
307 */
308 function getCountQuery( $filteredTerm, $fulltext ) {
309 $match = $this->parseQuery( $filteredTerm, $fulltext );
310
311 $query = array(
312 'tables' => array( 'page', 'searchindex' ),
313 'fields' => array( 'COUNT(*) as c' ),
314 'conds' => array( 'page_id=si_page', $match ),
315 'options' => array(),
316 'joins' => array(),
317 );
318
319 $this->queryFeatures( $query );
320 $this->queryNamespaces( $query );
321
322 return $query;
323 }
324
325 /**
326 * Create or update the search index record for the given page.
327 * Title and text should be pre-processed.
328 *
329 * @param $id Integer
330 * @param $title String
331 * @param $text String
332 */
333 function update( $id, $title, $text ) {
334 $dbw = wfGetDB( DB_MASTER );
335 $dbw->replace( 'searchindex',
336 array( 'si_page' ),
337 array(
338 'si_page' => $id,
339 'si_title' => $this->normalizeText( $title ),
340 'si_text' => $this->normalizeText( $text )
341 ), __METHOD__ );
342 }
343
344 /**
345 * Update a search index record's title only.
346 * Title should be pre-processed.
347 *
348 * @param $id Integer
349 * @param $title String
350 */
351 function updateTitle( $id, $title ) {
352 $dbw = wfGetDB( DB_MASTER );
353
354 $dbw->update( 'searchindex',
355 array( 'si_title' => $this->normalizeText( $title ) ),
356 array( 'si_page' => $id ),
357 __METHOD__,
358 array( $dbw->lowPriorityOption() ) );
359 }
360
361 /**
362 * Converts some characters for MySQL's indexing to grok it correctly,
363 * and pads short words to overcome limitations.
364 */
365 function normalizeText( $string ) {
366 global $wgContLang;
367
368 wfProfileIn( __METHOD__ );
369
370 $out = parent::normalizeText( $string );
371
372 // MySQL fulltext index doesn't grok utf-8, so we
373 // need to fold cases and convert to hex
374 $out = preg_replace_callback(
375 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
376 array( $this, 'stripForSearchCallback' ),
377 $wgContLang->lc( $out ) );
378
379 // And to add insult to injury, the default indexing
380 // ignores short words... Pad them so we can pass them
381 // through without reconfiguring the server...
382 $minLength = $this->minSearchLength();
383 if( $minLength > 1 ) {
384 $n = $minLength - 1;
385 $out = preg_replace(
386 "/\b(\w{1,$n})\b/",
387 "$1u800",
388 $out );
389 }
390
391 // Periods within things like hostnames and IP addresses
392 // are also important -- we want a search for "example.com"
393 // or "192.168.1.1" to work sanely.
394 //
395 // MySQL's search seems to ignore them, so you'd match on
396 // "example.wikipedia.com" and "192.168.83.1" as well.
397 $out = preg_replace(
398 "/(\w)\.(\w|\*)/u",
399 "$1u82e$2",
400 $out );
401
402 wfProfileOut( __METHOD__ );
403
404 return $out;
405 }
406
407 /**
408 * Armor a case-folded UTF-8 string to get through MySQL's
409 * fulltext search without being mucked up by funny charset
410 * settings or anything else of the sort.
411 */
412 protected function stripForSearchCallback( $matches ) {
413 return 'u8' . bin2hex( $matches[1] );
414 }
415
416 /**
417 * Check MySQL server's ft_min_word_len setting so we know
418 * if we need to pad short words...
419 *
420 * @return int
421 */
422 protected function minSearchLength() {
423 if( is_null( self::$mMinSearchLength ) ) {
424 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
425
426 $dbr = wfGetDB( DB_SLAVE );
427 $result = $dbr->query( $sql );
428 $row = $result->fetchObject();
429 $result->free();
430
431 if( $row && $row->Variable_name == 'ft_min_word_len' ) {
432 self::$mMinSearchLength = intval( $row->Value );
433 } else {
434 self::$mMinSearchLength = 0;
435 }
436 }
437 return self::$mMinSearchLength;
438 }
439 }
440
441 /**
442 * @ingroup Search
443 */
444 class MySQLSearchResultSet extends SqlSearchResultSet {
445 function __construct( $resultSet, $terms, $totalHits=null ) {
446 parent::__construct( $resultSet, $terms );
447 $this->mTotalHits = $totalHits;
448 }
449
450 function getTotalHits() {
451 return $this->mTotalHits;
452 }
453 }