Remove "include redirects" option from search
[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 === '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 &$query array Search query array
289 * @param $filteredTerm String
290 * @param $fulltext Boolean
291 * @since 1.18 (changed)
292 */
293 function queryMain( &$query, $filteredTerm, $fulltext ) {
294 $match = $this->parseQuery( $filteredTerm, $fulltext );
295 $query['tables'][] = 'page';
296 $query['tables'][] = 'searchindex';
297 $query['fields'][] = 'page_id';
298 $query['fields'][] = 'page_namespace';
299 $query['fields'][] = 'page_title';
300 $query['conds'][] = 'page_id=si_page';
301 $query['conds'][] = $match;
302 }
303
304 /**
305 * @since 1.18 (changed)
306 * @return array
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 * Delete an indexed page
363 * Title should be pre-processed.
364 *
365 * @param Integer $id Page id that was deleted
366 * @param String $title Title of page that was deleted
367 */
368 function delete( $id, $title ) {
369 $dbw = wfGetDB( DB_MASTER );
370
371 $dbw->delete( 'searchindex', array( 'si_page' => $id ), __METHOD__ );
372 }
373
374 /**
375 * Converts some characters for MySQL's indexing to grok it correctly,
376 * and pads short words to overcome limitations.
377 * @return mixed|string
378 */
379 function normalizeText( $string ) {
380 global $wgContLang;
381
382 wfProfileIn( __METHOD__ );
383
384 $out = parent::normalizeText( $string );
385
386 // MySQL fulltext index doesn't grok utf-8, so we
387 // need to fold cases and convert to hex
388 $out = preg_replace_callback(
389 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
390 array( $this, 'stripForSearchCallback' ),
391 $wgContLang->lc( $out ) );
392
393 // And to add insult to injury, the default indexing
394 // ignores short words... Pad them so we can pass them
395 // through without reconfiguring the server...
396 $minLength = $this->minSearchLength();
397 if ( $minLength > 1 ) {
398 $n = $minLength - 1;
399 $out = preg_replace(
400 "/\b(\w{1,$n})\b/",
401 "$1u800",
402 $out );
403 }
404
405 // Periods within things like hostnames and IP addresses
406 // are also important -- we want a search for "example.com"
407 // or "192.168.1.1" to work sanely.
408 //
409 // MySQL's search seems to ignore them, so you'd match on
410 // "example.wikipedia.com" and "192.168.83.1" as well.
411 $out = preg_replace(
412 "/(\w)\.(\w|\*)/u",
413 "$1u82e$2",
414 $out );
415
416 wfProfileOut( __METHOD__ );
417
418 return $out;
419 }
420
421 /**
422 * Armor a case-folded UTF-8 string to get through MySQL's
423 * fulltext search without being mucked up by funny charset
424 * settings or anything else of the sort.
425 * @return string
426 */
427 protected function stripForSearchCallback( $matches ) {
428 return 'u8' . bin2hex( $matches[1] );
429 }
430
431 /**
432 * Check MySQL server's ft_min_word_len setting so we know
433 * if we need to pad short words...
434 *
435 * @return int
436 */
437 protected function minSearchLength() {
438 if ( is_null( self::$mMinSearchLength ) ) {
439 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
440
441 $dbr = wfGetDB( DB_SLAVE );
442 $result = $dbr->query( $sql );
443 $row = $result->fetchObject();
444 $result->free();
445
446 if ( $row && $row->Variable_name == 'ft_min_word_len' ) {
447 self::$mMinSearchLength = intval( $row->Value );
448 } else {
449 self::$mMinSearchLength = 0;
450 }
451 }
452 return self::$mMinSearchLength;
453 }
454 }
455
456 /**
457 * @ingroup Search
458 */
459 class MySQLSearchResultSet extends SqlSearchResultSet {
460 function __construct( $resultSet, $terms, $totalHits = null ) {
461 parent::__construct( $resultSet, $terms );
462 $this->mTotalHits = $totalHits;
463 }
464
465 function getTotalHits() {
466 return $this->mTotalHits;
467 }
468 }