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