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