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