Merge "DifferenceEngine: Remove broken comment"
[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 'list-redirects':
216 case 'title-suffix-filter':
217 return true;
218 default:
219 return false;
220 }
221 }
222
223 /**
224 * Add special conditions
225 * @param $query Array
226 * @since 1.18
227 */
228 protected function queryFeatures( &$query ) {
229 foreach ( $this->features as $feature => $value ) {
230 if ( $feature === 'list-redirects' && !$value ) {
231 $query['conds']['page_is_redirect'] = 0;
232 } elseif ( $feature === 'title-suffix-filter' && $value ) {
233 $query['conds'][] = 'page_title' . $this->db->buildLike( $this->db->anyString(), $value );
234 }
235 }
236 }
237
238 /**
239 * Add namespace conditions
240 * @param $query Array
241 * @since 1.18 (changed)
242 */
243 function queryNamespaces( &$query ) {
244 if ( is_array( $this->namespaces ) ) {
245 if ( count( $this->namespaces ) === 0 ) {
246 $this->namespaces[] = '0';
247 }
248 $query['conds']['page_namespace'] = $this->namespaces;
249 }
250 }
251
252 /**
253 * Add limit options
254 * @param $query Array
255 * @since 1.18
256 */
257 protected function limitResult( &$query ) {
258 $query['options']['LIMIT'] = $this->limit;
259 $query['options']['OFFSET'] = $this->offset;
260 }
261
262 /**
263 * Construct the SQL query to do the search.
264 * The guts shoulds be constructed in queryMain()
265 * @param $filteredTerm String
266 * @param $fulltext Boolean
267 * @return Array
268 * @since 1.18 (changed)
269 */
270 function getQuery( $filteredTerm, $fulltext ) {
271 $query = array(
272 'tables' => array(),
273 'fields' => array(),
274 'conds' => array(),
275 'options' => array(),
276 'joins' => array(),
277 );
278
279 $this->queryMain( $query, $filteredTerm, $fulltext );
280 $this->queryFeatures( $query );
281 $this->queryNamespaces( $query );
282 $this->limitResult( $query );
283
284 return $query;
285 }
286
287 /**
288 * Picks which field to index on, depending on what type of query.
289 * @param $fulltext Boolean
290 * @return String
291 */
292 function getIndexField( $fulltext ) {
293 return $fulltext ? 'si_text' : 'si_title';
294 }
295
296 /**
297 * Get the base part of the search query.
298 *
299 * @param &$query array Search query array
300 * @param $filteredTerm String
301 * @param $fulltext Boolean
302 * @since 1.18 (changed)
303 */
304 function queryMain( &$query, $filteredTerm, $fulltext ) {
305 $match = $this->parseQuery( $filteredTerm, $fulltext );
306 $query['tables'][] = 'page';
307 $query['tables'][] = 'searchindex';
308 $query['fields'][] = 'page_id';
309 $query['fields'][] = 'page_namespace';
310 $query['fields'][] = 'page_title';
311 $query['conds'][] = 'page_id=si_page';
312 $query['conds'][] = $match;
313 }
314
315 /**
316 * @since 1.18 (changed)
317 * @return array
318 */
319 function getCountQuery( $filteredTerm, $fulltext ) {
320 $match = $this->parseQuery( $filteredTerm, $fulltext );
321
322 $query = array(
323 'tables' => array( 'page', 'searchindex' ),
324 'fields' => array( 'COUNT(*) as c' ),
325 'conds' => array( 'page_id=si_page', $match ),
326 'options' => array(),
327 'joins' => array(),
328 );
329
330 $this->queryFeatures( $query );
331 $this->queryNamespaces( $query );
332
333 return $query;
334 }
335
336 /**
337 * Create or update the search index record for the given page.
338 * Title and text should be pre-processed.
339 *
340 * @param $id Integer
341 * @param $title String
342 * @param $text String
343 */
344 function update( $id, $title, $text ) {
345 $dbw = wfGetDB( DB_MASTER );
346 $dbw->replace( 'searchindex',
347 array( 'si_page' ),
348 array(
349 'si_page' => $id,
350 'si_title' => $this->normalizeText( $title ),
351 'si_text' => $this->normalizeText( $text )
352 ), __METHOD__ );
353 }
354
355 /**
356 * Update a search index record's title only.
357 * Title should be pre-processed.
358 *
359 * @param $id Integer
360 * @param $title String
361 */
362 function updateTitle( $id, $title ) {
363 $dbw = wfGetDB( DB_MASTER );
364
365 $dbw->update( 'searchindex',
366 array( 'si_title' => $this->normalizeText( $title ) ),
367 array( 'si_page' => $id ),
368 __METHOD__,
369 array( $dbw->lowPriorityOption() ) );
370 }
371
372 /**
373 * Delete an indexed page
374 * Title should be pre-processed.
375 *
376 * @param Integer $id Page id that was deleted
377 * @param String $title Title of page that was deleted
378 */
379 function delete( $id, $title ) {
380 $dbw = wfGetDB( DB_MASTER );
381
382 $dbw->delete( 'searchindex', array( 'si_page' => $id ), __METHOD__ );
383 }
384
385 /**
386 * Converts some characters for MySQL's indexing to grok it correctly,
387 * and pads short words to overcome limitations.
388 * @return mixed|string
389 */
390 function normalizeText( $string ) {
391 global $wgContLang;
392
393 wfProfileIn( __METHOD__ );
394
395 $out = parent::normalizeText( $string );
396
397 // MySQL fulltext index doesn't grok utf-8, so we
398 // need to fold cases and convert to hex
399 $out = preg_replace_callback(
400 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
401 array( $this, 'stripForSearchCallback' ),
402 $wgContLang->lc( $out ) );
403
404 // And to add insult to injury, the default indexing
405 // ignores short words... Pad them so we can pass them
406 // through without reconfiguring the server...
407 $minLength = $this->minSearchLength();
408 if ( $minLength > 1 ) {
409 $n = $minLength - 1;
410 $out = preg_replace(
411 "/\b(\w{1,$n})\b/",
412 "$1u800",
413 $out );
414 }
415
416 // Periods within things like hostnames and IP addresses
417 // are also important -- we want a search for "example.com"
418 // or "192.168.1.1" to work sanely.
419 //
420 // MySQL's search seems to ignore them, so you'd match on
421 // "example.wikipedia.com" and "192.168.83.1" as well.
422 $out = preg_replace(
423 "/(\w)\.(\w|\*)/u",
424 "$1u82e$2",
425 $out );
426
427 wfProfileOut( __METHOD__ );
428
429 return $out;
430 }
431
432 /**
433 * Armor a case-folded UTF-8 string to get through MySQL's
434 * fulltext search without being mucked up by funny charset
435 * settings or anything else of the sort.
436 * @return string
437 */
438 protected function stripForSearchCallback( $matches ) {
439 return 'u8' . bin2hex( $matches[1] );
440 }
441
442 /**
443 * Check MySQL server's ft_min_word_len setting so we know
444 * if we need to pad short words...
445 *
446 * @return int
447 */
448 protected function minSearchLength() {
449 if ( is_null( self::$mMinSearchLength ) ) {
450 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
451
452 $dbr = wfGetDB( DB_SLAVE );
453 $result = $dbr->query( $sql );
454 $row = $result->fetchObject();
455 $result->free();
456
457 if ( $row && $row->Variable_name == 'ft_min_word_len' ) {
458 self::$mMinSearchLength = intval( $row->Value );
459 } else {
460 self::$mMinSearchLength = 0;
461 }
462 }
463 return self::$mMinSearchLength;
464 }
465 }
466
467 /**
468 * @ingroup Search
469 */
470 class MySQLSearchResultSet extends SqlSearchResultSet {
471 function __construct( $resultSet, $terms, $totalHits = null ) {
472 parent::__construct( $resultSet, $terms );
473 $this->mTotalHits = $totalHits;
474 }
475
476 function getTotalHits() {
477 return $this->mTotalHits;
478 }
479 }