MediaWiki REL1_39
SearchMySQL.php
Go to the documentation of this file.
1<?php
28use Wikimedia\AtEase\AtEase;
29
35 protected $strictMatching = true;
36
37 private static $mMinSearchLength;
38
48 private function parseQuery( $filteredText, $fulltext ) {
49 $lc = $this->legalSearchChars( self::CHARS_NO_SYNTAX ); // Minus syntax chars (" and *)
50 $searchon = '';
51 $this->searchTerms = [];
52
53 # @todo FIXME: This doesn't handle parenthetical expressions.
54 $m = [];
55 if ( preg_match_all( '/([-+<>~]?)(([' . $lc . ']+)(\*?)|"[^"]*")/',
56 $filteredText, $m, PREG_SET_ORDER )
57 ) {
58 $services = MediaWikiServices::getInstance();
59 $contLang = $services->getContentLanguage();
60 $langConverter = $services->getLanguageConverterFactory()->getLanguageConverter( $contLang );
61 foreach ( $m as $bits ) {
62 AtEase::suppressWarnings();
63 list( /* all */, $modifier, $term, $nonQuoted, $wildcard ) = $bits;
64 AtEase::restoreWarnings();
65
66 if ( $nonQuoted != '' ) {
67 $term = $nonQuoted;
68 $quote = '';
69 } else {
70 $term = str_replace( '"', '', $term );
71 $quote = '"';
72 }
73
74 if ( $searchon !== '' ) {
75 $searchon .= ' ';
76 }
77 if ( $this->strictMatching && ( $modifier == '' ) ) {
78 // If we leave this out, boolean op defaults to OR which is rarely helpful.
79 $modifier = '+';
80 }
81
82 // Some languages such as Serbian store the input form in the search index,
83 // so we may need to search for matches in multiple writing system variants.
84 $convertedVariants = $langConverter->autoConvertToAllVariants( $term );
85 if ( is_array( $convertedVariants ) ) {
86 $variants = array_unique( array_values( $convertedVariants ) );
87 } else {
88 $variants = [ $term ];
89 }
90
91 // The low-level search index does some processing on input to work
92 // around problems with minimum lengths and encoding in MySQL's
93 // fulltext engine.
94 // For Chinese this also inserts spaces between adjacent Han characters.
95 $strippedVariants = array_map( [ $contLang, 'normalizeForSearch' ], $variants );
96
97 // Some languages such as Chinese force all variants to a canonical
98 // form when stripping to the low-level search index, so to be sure
99 // let's check our variants list for unique items after stripping.
100 $strippedVariants = array_unique( $strippedVariants );
101
102 $searchon .= $modifier;
103 if ( count( $strippedVariants ) > 1 ) {
104 $searchon .= '(';
105 }
106 foreach ( $strippedVariants as $stripped ) {
107 $stripped = $this->normalizeText( $stripped );
108 if ( $nonQuoted && strpos( $stripped, ' ' ) !== false ) {
109 // Hack for Chinese: we need to toss in quotes for
110 // multiple-character phrases since normalizeForSearch()
111 // added spaces between them to make word breaks.
112 $stripped = '"' . trim( $stripped ) . '"';
113 }
114 $searchon .= "$quote$stripped$quote$wildcard ";
115 }
116 if ( count( $strippedVariants ) > 1 ) {
117 $searchon .= ')';
118 }
119
120 // Match individual terms or quoted phrase in result highlighting...
121 // Note that variants will be introduced in a later stage for highlighting!
122 $regexp = $this->regexTerm( $term, $wildcard );
123 $this->searchTerms[] = $regexp;
124 }
125 wfDebug( __METHOD__ . ": Would search with '$searchon'" );
126 wfDebug( __METHOD__ . ': Match with /' . implode( '|', $this->searchTerms ) . "/" );
127 } else {
128 wfDebug( __METHOD__ . ": Can't understand search query '{$filteredText}'" );
129 }
130
131 $dbr = $this->lb->getConnectionRef( DB_REPLICA );
132 $searchon = $dbr->addQuotes( $searchon );
133 $field = $this->getIndexField( $fulltext );
134 return [
135 " MATCH($field) AGAINST($searchon IN BOOLEAN MODE) ",
136 " MATCH($field) AGAINST($searchon IN NATURAL LANGUAGE MODE) DESC "
137 ];
138 }
139
140 private function regexTerm( $string, $wildcard ) {
141 $regex = preg_quote( $string, '/' );
142 if ( MediaWikiServices::getInstance()->getContentLanguage()->hasWordBreaks() ) {
143 if ( $wildcard ) {
144 // Don't cut off the final bit!
145 $regex = "\b$regex";
146 } else {
147 $regex = "\b$regex\b";
148 }
149 } else {
150 // For Chinese, words may legitimately abut other words in the text literal.
151 // Don't add \b boundary checks... note this could cause false positives
152 // for Latin chars.
153 }
154 return $regex;
155 }
156
157 public function legalSearchChars( $type = self::CHARS_ALL ) {
158 $searchChars = parent::legalSearchChars( $type );
159
160 // In the MediaWiki UI, search strings containing (just) a hyphen are translated into
161 // MATCH(si_title) AGAINST('+- ' IN BOOLEAN MODE)
162 // which is not valid.
163
164 // From <https://dev.mysql.com/doc/refman/8.0/en/fulltext-boolean.html>:
165 // "InnoDB full-text search does not support... a plus and minus sign combination ('+-')"
166
167 // See also https://phabricator.wikimedia.org/T221560
168 $searchChars = preg_replace( '/\\\\-/', '', $searchChars );
169
170 if ( $type === self::CHARS_ALL ) {
171 // " for phrase, * for wildcard
172 $searchChars = "\"*" . $searchChars;
173 }
174 return $searchChars;
175 }
176
183 protected function doSearchTextInDB( $term ) {
184 return $this->searchInternal( $term, true );
185 }
186
193 protected function doSearchTitleInDB( $term ) {
194 return $this->searchInternal( $term, false );
195 }
196
197 protected function searchInternal( $term, $fulltext ) {
198 // This seems out of place, why is this called with empty term?
199 if ( trim( $term ) === '' ) {
200 return null;
201 }
202
203 $filteredTerm = $this->filter( $term );
204 $query = $this->getQuery( $filteredTerm, $fulltext );
205 $dbr = $this->lb->getConnectionRef( DB_REPLICA );
206 $resultSet = $dbr->select(
207 $query['tables'], $query['fields'], $query['conds'],
208 __METHOD__, $query['options'], $query['joins']
209 );
210
211 $total = null;
212 $query = $this->getCountQuery( $filteredTerm, $fulltext );
213 $totalResult = $dbr->select(
214 $query['tables'], $query['fields'], $query['conds'],
215 __METHOD__, $query['options'], $query['joins']
216 );
217
218 $row = $totalResult->fetchObject();
219 if ( $row ) {
220 $total = intval( $row->c );
221 }
222 $totalResult->free();
223
224 return new SqlSearchResultSet( $resultSet, $this->searchTerms, $total );
225 }
226
227 public function supports( $feature ) {
228 switch ( $feature ) {
229 case 'title-suffix-filter':
230 return true;
231 default:
232 return parent::supports( $feature );
233 }
234 }
235
241 protected function queryFeatures( &$query ) {
242 foreach ( $this->features as $feature => $value ) {
243 if ( $feature === 'title-suffix-filter' && $value ) {
244 $dbr = $this->lb->getConnectionRef( DB_REPLICA );
245 $query['conds'][] = 'page_title' . $dbr->buildLike( $dbr->anyString(), $value );
246 }
247 }
248 }
249
255 private function queryNamespaces( &$query ) {
256 if ( is_array( $this->namespaces ) ) {
257 if ( count( $this->namespaces ) === 0 ) {
258 $this->namespaces[] = NS_MAIN;
259 }
260 $query['conds']['page_namespace'] = $this->namespaces;
261 }
262 }
263
269 protected function limitResult( &$query ) {
270 $query['options']['LIMIT'] = $this->limit;
271 $query['options']['OFFSET'] = $this->offset;
272 }
273
282 private function getQuery( $filteredTerm, $fulltext ) {
283 $query = [
284 'tables' => [],
285 'fields' => [],
286 'conds' => [],
287 'options' => [],
288 'joins' => [],
289 ];
290
291 $this->queryMain( $query, $filteredTerm, $fulltext );
292 $this->queryFeatures( $query );
293 $this->queryNamespaces( $query );
294 $this->limitResult( $query );
295
296 return $query;
297 }
298
304 private function getIndexField( $fulltext ) {
305 return $fulltext ? 'si_text' : 'si_title';
306 }
307
316 private function queryMain( &$query, $filteredTerm, $fulltext ) {
317 $match = $this->parseQuery( $filteredTerm, $fulltext );
318 $query['tables'][] = 'page';
319 $query['tables'][] = 'searchindex';
320 $query['fields'][] = 'page_id';
321 $query['fields'][] = 'page_namespace';
322 $query['fields'][] = 'page_title';
323 $query['conds'][] = 'page_id=si_page';
324 $query['conds'][] = $match[0];
325 $query['options']['ORDER BY'] = $match[1];
326 }
327
334 private function getCountQuery( $filteredTerm, $fulltext ) {
335 $match = $this->parseQuery( $filteredTerm, $fulltext );
336
337 $query = [
338 'tables' => [ 'page', 'searchindex' ],
339 'fields' => [ 'COUNT(*) as c' ],
340 'conds' => [ 'page_id=si_page', $match[0] ],
341 'options' => [],
342 'joins' => [],
343 ];
344
345 $this->queryFeatures( $query );
346 $this->queryNamespaces( $query );
347
348 return $query;
349 }
350
359 public function update( $id, $title, $text ) {
360 $dbw = $this->lb->getConnectionRef( DB_PRIMARY );
361 $dbw->replace(
362 'searchindex',
363 'si_page',
364 [
365 'si_page' => $id,
366 'si_title' => $this->normalizeText( $title ),
367 'si_text' => $this->normalizeText( $text )
368 ],
369 __METHOD__
370 );
371 }
372
380 public function updateTitle( $id, $title ) {
381 $dbw = $this->lb->getConnectionRef( DB_PRIMARY );
382 $dbw->update( 'searchindex',
383 [ 'si_title' => $this->normalizeText( $title ) ],
384 [ 'si_page' => $id ],
385 __METHOD__
386 );
387 }
388
396 public function delete( $id, $title ) {
397 $dbw = $this->lb->getConnectionRef( DB_PRIMARY );
398 $dbw->delete( 'searchindex', [ 'si_page' => $id ], __METHOD__ );
399 }
400
407 public function normalizeText( $string ) {
408 $out = parent::normalizeText( $string );
409
410 // MySQL fulltext index doesn't grok utf-8, so we
411 // need to fold cases and convert to hex
412 $out = preg_replace_callback(
413 "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
414 [ $this, 'stripForSearchCallback' ],
415 MediaWikiServices::getInstance()->getContentLanguage()->lc( $out ) );
416
417 // And to add insult to injury, the default indexing
418 // ignores short words... Pad them so we can pass them
419 // through without reconfiguring the server...
420 $minLength = $this->minSearchLength();
421 if ( $minLength > 1 ) {
422 $n = $minLength - 1;
423 $out = preg_replace(
424 "/\b(\w{1,$n})\b/",
425 "$1u800",
426 $out );
427 }
428
429 // Periods within things like hostnames and IP addresses
430 // are also important -- we want a search for "example.com"
431 // or "192.168.1.1" to work sensibly.
432 // MySQL's search seems to ignore them, so you'd match on
433 // "example.wikipedia.com" and "192.168.83.1" as well.
434 return preg_replace(
435 "/(\w)\.(\w|\*)/u",
436 "$1u82e$2",
437 $out
438 );
439 }
440
448 protected function stripForSearchCallback( $matches ) {
449 return 'u8' . bin2hex( $matches[1] );
450 }
451
458 protected function minSearchLength() {
459 if ( self::$mMinSearchLength === null ) {
460 $sql = "SHOW GLOBAL VARIABLES LIKE 'ft\\_min\\_word\\_len'";
461
462 $dbr = $this->lb->getConnectionRef( DB_REPLICA );
463 $result = $dbr->query( $sql, __METHOD__ );
464 $row = $result->fetchObject();
465 $result->free();
466
467 if ( $row && $row->Variable_name == 'ft_min_word_len' ) {
468 self::$mMinSearchLength = intval( $row->Value );
469 } else {
470 self::$mMinSearchLength = 0;
471 }
472 }
473 return self::$mMinSearchLength;
474 }
475}
const NS_MAIN
Definition Defines.php:64
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Service locator for MediaWiki core services.
Base search engine base class for database-backed searches.
filter( $text)
Return a 'cleaned up' search string.
int[] null $namespaces
Search engine hook for MySQL.
updateTitle( $id, $title)
Update a search index record's title only.
doSearchTitleInDB( $term)
Perform a title-only search query and return a result set.
stripForSearchCallback( $matches)
Armor a case-folded UTF-8 string to get through MySQL's fulltext search without being mucked up by fu...
queryFeatures(&$query)
Add special conditions.
update( $id, $title, $text)
Create or update the search index record for the given page.
supports( $feature)
searchInternal( $term, $fulltext)
limitResult(&$query)
Add limit options.
legalSearchChars( $type=self::CHARS_ALL)
Get chars legal for search.
normalizeText( $string)
Converts some characters for MySQL's indexing to grok it correctly, and pads short words to overcome ...
minSearchLength()
Check MySQL server's ft_min_word_len setting so we know if we need to pad short words....
doSearchTextInDB( $term)
Perform a full text search query and return a result set.
This class is used for different SQL-based search engines shipped with MediaWiki.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28