Move wgContLang from config to injectable
[lhc/web/wiklou.git] / includes / search / SearchEngine.php
1 <?php
2 /**
3 * Basic search engine
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Search
22 */
23
24 /**
25 * @defgroup Search Search
26 */
27
28 use MediaWiki\MediaWikiServices;
29
30 /**
31 * Contain a class for special pages
32 * @ingroup Search
33 */
34 abstract class SearchEngine {
35 /** @var string */
36 public $prefix = '';
37
38 /** @var int[]|null */
39 public $namespaces = [ NS_MAIN ];
40
41 /** @var int */
42 protected $limit = 10;
43
44 /** @var int */
45 protected $offset = 0;
46
47 /** @var array|string */
48 protected $searchTerms = [];
49
50 /** @var bool */
51 protected $showSuggestion = true;
52 private $sort = 'relevance';
53
54 /** @var array Feature values */
55 protected $features = [];
56
57 /**
58 * Perform a full text search query and return a result set.
59 * If full text searches are not supported or disabled, return null.
60 * STUB
61 *
62 * @param string $term Raw search term
63 * @return SearchResultSet|Status|null
64 */
65 function searchText( $term ) {
66 return null;
67 }
68
69 /**
70 * Perform a title-only search query and return a result set.
71 * If title searches are not supported or disabled, return null.
72 * STUB
73 *
74 * @param string $term Raw search term
75 * @return SearchResultSet|null
76 */
77 function searchTitle( $term ) {
78 return null;
79 }
80
81 /**
82 * @since 1.18
83 * @param string $feature
84 * @return bool
85 */
86 public function supports( $feature ) {
87 switch ( $feature ) {
88 case 'search-update':
89 return true;
90 case 'title-suffix-filter':
91 default:
92 return false;
93 }
94 }
95
96 /**
97 * Way to pass custom data for engines
98 * @since 1.18
99 * @param string $feature
100 * @param mixed $data
101 * @return bool
102 */
103 public function setFeatureData( $feature, $data ) {
104 $this->features[$feature] = $data;
105 }
106
107 /**
108 * When overridden in derived class, performs database-specific conversions
109 * on text to be used for searching or updating search index.
110 * Default implementation does nothing (simply returns $string).
111 *
112 * @param string $string String to process
113 * @return string
114 */
115 public function normalizeText( $string ) {
116 global $wgContLang;
117
118 // Some languages such as Chinese require word segmentation
119 return $wgContLang->segmentByWord( $string );
120 }
121
122 /**
123 * Transform search term in cases when parts of the query came as different
124 * GET params (when supported), e.g. for prefix queries:
125 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
126 * @param string $term
127 * @return string
128 */
129 public function transformSearchTerm( $term ) {
130 return $term;
131 }
132
133 /**
134 * Get service class to finding near matches.
135 * @param Config $config Configuration to use for the matcher.
136 * @return SearchNearMatcher
137 */
138 public function getNearMatcher( Config $config ) {
139 global $wgContLang;
140 return new SearchNearMatcher( $config, $wgContLang );
141 }
142
143 /**
144 * Get near matcher for default SearchEngine.
145 * @return SearchNearMatcher
146 */
147 protected static function defaultNearMatcher() {
148 $config = MediaWikiServices::getInstance()->getMainConfig();
149 return MediaWikiServices::getInstance()->newSearchEngine()->getNearMatcher( $config );
150 }
151
152 /**
153 * If an exact title match can be found, or a very slightly close match,
154 * return the title. If no match, returns NULL.
155 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
156 * @param string $searchterm
157 * @return Title
158 */
159 public static function getNearMatch( $searchterm ) {
160 return static::defaultNearMatcher()->getNearMatch( $searchterm );
161 }
162
163 /**
164 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
165 * SearchResultSet.
166 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
167 * @param string $searchterm
168 * @return SearchResultSet
169 */
170 public static function getNearMatchResultSet( $searchterm ) {
171 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
172 }
173
174 /**
175 * Get chars legal for search.
176 * NOTE: usage as static is deprecated and preserved only as BC measure
177 * @return string
178 */
179 public static function legalSearchChars() {
180 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
181 }
182
183 /**
184 * Set the maximum number of results to return
185 * and how many to skip before returning the first.
186 *
187 * @param int $limit
188 * @param int $offset
189 */
190 function setLimitOffset( $limit, $offset = 0 ) {
191 $this->limit = intval( $limit );
192 $this->offset = intval( $offset );
193 }
194
195 /**
196 * Set which namespaces the search should include.
197 * Give an array of namespace index numbers.
198 *
199 * @param int[]|null $namespaces
200 */
201 function setNamespaces( $namespaces ) {
202 if ( $namespaces ) {
203 // Filter namespaces to only keep valid ones
204 $validNs = $this->searchableNamespaces();
205 $namespaces = array_filter( $namespaces, function( $ns ) use( $validNs ) {
206 return $ns < 0 || isset( $validNs[$ns] );
207 } );
208 } else {
209 $namespaces = [];
210 }
211 $this->namespaces = $namespaces;
212 }
213
214 /**
215 * Set whether the searcher should try to build a suggestion. Note: some searchers
216 * don't support building a suggestion in the first place and others don't respect
217 * this flag.
218 *
219 * @param bool $showSuggestion Should the searcher try to build suggestions
220 */
221 function setShowSuggestion( $showSuggestion ) {
222 $this->showSuggestion = $showSuggestion;
223 }
224
225 /**
226 * Get the valid sort directions. All search engines support 'relevance' but others
227 * might support more. The default in all implementations should be 'relevance.'
228 *
229 * @since 1.25
230 * @return array(string) the valid sort directions for setSort
231 */
232 public function getValidSorts() {
233 return [ 'relevance' ];
234 }
235
236 /**
237 * Set the sort direction of the search results. Must be one returned by
238 * SearchEngine::getValidSorts()
239 *
240 * @since 1.25
241 * @throws InvalidArgumentException
242 * @param string $sort sort direction for query result
243 */
244 public function setSort( $sort ) {
245 if ( !in_array( $sort, $this->getValidSorts() ) ) {
246 throw new InvalidArgumentException( "Invalid sort: $sort. " .
247 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
248 }
249 $this->sort = $sort;
250 }
251
252 /**
253 * Get the sort direction of the search results
254 *
255 * @since 1.25
256 * @return string
257 */
258 public function getSort() {
259 return $this->sort;
260 }
261
262 /**
263 * Parse some common prefixes: all (search everything)
264 * or namespace names
265 *
266 * @param string $query
267 * @return string
268 */
269 function replacePrefixes( $query ) {
270 global $wgContLang;
271
272 $parsed = $query;
273 if ( strpos( $query, ':' ) === false ) { // nothing to do
274 return $parsed;
275 }
276
277 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
278 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
279 $this->namespaces = null;
280 $parsed = substr( $query, strlen( $allkeyword ) );
281 } elseif ( strpos( $query, ':' ) !== false ) {
282 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
283 $index = $wgContLang->getNsIndex( $prefix );
284 if ( $index !== false ) {
285 $this->namespaces = [ $index ];
286 $parsed = substr( $query, strlen( $prefix ) + 1 );
287 }
288 }
289 if ( trim( $parsed ) == '' ) {
290 $parsed = $query; // prefix was the whole query
291 }
292
293 return $parsed;
294 }
295
296 /**
297 * Find snippet highlight settings for all users
298 * @return array Contextlines, contextchars
299 */
300 public static function userHighlightPrefs() {
301 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
302 $contextchars = 75; // same as above.... :P
303 return [ $contextlines, $contextchars ];
304 }
305
306 /**
307 * Create or update the search index record for the given page.
308 * Title and text should be pre-processed.
309 * STUB
310 *
311 * @param int $id
312 * @param string $title
313 * @param string $text
314 */
315 function update( $id, $title, $text ) {
316 // no-op
317 }
318
319 /**
320 * Update a search index record's title only.
321 * Title should be pre-processed.
322 * STUB
323 *
324 * @param int $id
325 * @param string $title
326 */
327 function updateTitle( $id, $title ) {
328 // no-op
329 }
330
331 /**
332 * Delete an indexed page
333 * Title should be pre-processed.
334 * STUB
335 *
336 * @param int $id Page id that was deleted
337 * @param string $title Title of page that was deleted
338 */
339 function delete( $id, $title ) {
340 // no-op
341 }
342
343 /**
344 * Get OpenSearch suggestion template
345 *
346 * @deprecated since 1.25
347 * @return string
348 */
349 public static function getOpenSearchTemplate() {
350 wfDeprecated( __METHOD__, '1.25' );
351 return ApiOpenSearch::getOpenSearchTemplate( 'application/x-suggestions+json' );
352 }
353
354 /**
355 * Get the raw text for updating the index from a content object
356 * Nicer search backends could possibly do something cooler than
357 * just returning raw text
358 *
359 * @todo This isn't ideal, we'd really like to have content-specific handling here
360 * @param Title $t Title we're indexing
361 * @param Content $c Content of the page to index
362 * @return string
363 */
364 public function getTextFromContent( Title $t, Content $c = null ) {
365 return $c ? $c->getTextForSearchIndex() : '';
366 }
367
368 /**
369 * If an implementation of SearchEngine handles all of its own text processing
370 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
371 * rather silly handling, it should return true here instead.
372 *
373 * @return bool
374 */
375 public function textAlreadyUpdatedForIndex() {
376 return false;
377 }
378
379 /**
380 * Makes search simple string if it was namespaced.
381 * Sets namespaces of the search to namespaces extracted from string.
382 * @param string $search
383 * @return $string Simplified search string
384 */
385 protected function normalizeNamespaces( $search ) {
386 // Find a Title which is not an interwiki and is in NS_MAIN
387 $title = Title::newFromText( $search );
388 $ns = $this->namespaces;
389 if ( $title && !$title->isExternal() ) {
390 $ns = [ $title->getNamespace() ];
391 $search = $title->getText();
392 if ( $ns[0] == NS_MAIN ) {
393 $ns = $this->namespaces; // no explicit prefix, use default namespaces
394 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
395 }
396 } else {
397 $title = Title::newFromText( $search . 'Dummy' );
398 if ( $title && $title->getText() == 'Dummy'
399 && $title->getNamespace() != NS_MAIN
400 && !$title->isExternal() )
401 {
402 $ns = [ $title->getNamespace() ];
403 $search = '';
404 } else {
405 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
406 }
407 }
408
409 $ns = array_map( function( $space ) {
410 return $space == NS_MEDIA ? NS_FILE : $space;
411 }, $ns );
412
413 $this->setNamespaces( $ns );
414 return $search;
415 }
416
417 /**
418 * Perform a completion search.
419 * Does not resolve namespaces and does not check variants.
420 * Search engine implementations may want to override this function.
421 * @param string $search
422 * @return SearchSuggestionSet
423 */
424 protected function completionSearchBackend( $search ) {
425 $results = [];
426
427 $search = trim( $search );
428
429 if ( !in_array( NS_SPECIAL, $this->namespaces ) && // We do not run hook on Special: search
430 !Hooks::run( 'PrefixSearchBackend',
431 [ $this->namespaces, $search, $this->limit, &$results, $this->offset ]
432 ) ) {
433 // False means hook worked.
434 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
435
436 return SearchSuggestionSet::fromStrings( $results );
437 } else {
438 // Hook did not do the job, use default simple search
439 $results = $this->simplePrefixSearch( $search );
440 return SearchSuggestionSet::fromTitles( $results );
441 }
442 }
443
444 /**
445 * Perform a completion search.
446 * @param string $search
447 * @return SearchSuggestionSet
448 */
449 public function completionSearch( $search ) {
450 if ( trim( $search ) === '' ) {
451 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
452 }
453 $search = $this->normalizeNamespaces( $search );
454 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
455 }
456
457 /**
458 * Perform a completion search with variants.
459 * @param string $search
460 * @return SearchSuggestionSet
461 */
462 public function completionSearchWithVariants( $search ) {
463 if ( trim( $search ) === '' ) {
464 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
465 }
466 $search = $this->normalizeNamespaces( $search );
467
468 $results = $this->completionSearchBackend( $search );
469 $fallbackLimit = $this->limit - $results->getSize();
470 if ( $fallbackLimit > 0 ) {
471 global $wgContLang;
472
473 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
474 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
475
476 foreach ( $fallbackSearches as $fbs ) {
477 $this->setLimitOffset( $fallbackLimit );
478 $fallbackSearchResult = $this->completionSearch( $fbs );
479 $results->appendAll( $fallbackSearchResult );
480 $fallbackLimit -= count( $fallbackSearchResult );
481 if ( $fallbackLimit <= 0 ) {
482 break;
483 }
484 }
485 }
486 return $this->processCompletionResults( $search, $results );
487 }
488
489 /**
490 * Extract titles from completion results
491 * @param SearchSuggestionSet $completionResults
492 * @return Title[]
493 */
494 public function extractTitles( SearchSuggestionSet $completionResults ) {
495 return $completionResults->map( function( SearchSuggestion $sugg ) {
496 return $sugg->getSuggestedTitle();
497 } );
498 }
499
500 /**
501 * Process completion search results.
502 * Resolves the titles and rescores.
503 * @param SearchSuggestionSet $suggestions
504 * @return SearchSuggestionSet
505 */
506 protected function processCompletionResults( $search, SearchSuggestionSet $suggestions ) {
507 $search = trim( $search );
508 // preload the titles with LinkBatch
509 $titles = $suggestions->map( function( SearchSuggestion $sugg ) {
510 return $sugg->getSuggestedTitle();
511 } );
512 $lb = new LinkBatch( $titles );
513 $lb->setCaller( __METHOD__ );
514 $lb->execute();
515
516 $results = $suggestions->map( function( SearchSuggestion $sugg ) {
517 return $sugg->getSuggestedTitle()->getPrefixedText();
518 } );
519
520 // Rescore results with an exact title match
521 // NOTE: in some cases like cross-namespace redirects
522 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
523 // backends like Cirrus will return no results. We should still
524 // try an exact title match to workaround this limitation
525 $rescorer = new SearchExactMatchRescorer();
526 $rescoredResults = $rescorer->rescore( $search, $this->namespaces, $results, $this->limit );
527
528 if ( count( $rescoredResults ) > 0 ) {
529 $found = array_search( $rescoredResults[0], $results );
530 if ( $found === false ) {
531 // If the first result is not in the previous array it
532 // means that we found a new exact match
533 $exactMatch = SearchSuggestion::fromTitle( 0, Title::newFromText( $rescoredResults[0] ) );
534 $suggestions->prepend( $exactMatch );
535 $suggestions->shrink( $this->limit );
536 } else {
537 // if the first result is not the same we need to rescore
538 if ( $found > 0 ) {
539 $suggestions->rescore( $found );
540 }
541 }
542 }
543
544 return $suggestions;
545 }
546
547 /**
548 * Simple prefix search for subpages.
549 * @param string $search
550 * @return Title[]
551 */
552 public function defaultPrefixSearch( $search ) {
553 if ( trim( $search ) === '' ) {
554 return [];
555 }
556
557 $search = $this->normalizeNamespaces( $search );
558 return $this->simplePrefixSearch( $search );
559 }
560
561 /**
562 * Call out to simple search backend.
563 * Defaults to TitlePrefixSearch.
564 * @param string $search
565 * @return Title[]
566 */
567 protected function simplePrefixSearch( $search ) {
568 // Use default database prefix search
569 $backend = new TitlePrefixSearch;
570 return $backend->defaultSearchBackend( $this->namespaces, $search, $this->limit, $this->offset );
571 }
572
573 /**
574 * Make a list of searchable namespaces and their canonical names.
575 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
576 * @return array
577 */
578 public static function searchableNamespaces() {
579 return MediaWikiServices::getInstance()->getSearchEngineConfig()->searchableNamespaces();
580 }
581
582 /**
583 * Extract default namespaces to search from the given user's
584 * settings, returning a list of index numbers.
585 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
586 * @param user $user
587 * @return array
588 */
589 public static function userNamespaces( $user ) {
590 return MediaWikiServices::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
591 }
592
593 /**
594 * An array of namespaces indexes to be searched by default
595 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
596 * @return array
597 */
598 public static function defaultNamespaces() {
599 return MediaWikiServices::getInstance()->getSearchEngineConfig()->defaultNamespaces();
600 }
601
602 /**
603 * Get a list of namespace names useful for showing in tooltips
604 * and preferences
605 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
606 * @param array $namespaces
607 * @return array
608 */
609 public static function namespacesAsText( $namespaces ) {
610 return MediaWikiServices::getInstance()->getSearchEngineConfig()->namespacesAsText();
611 }
612
613 /**
614 * Load up the appropriate search engine class for the currently
615 * active database backend, and return a configured instance.
616 * @deprecated since 1.27; Use SearchEngineFactory::create
617 * @param string $type Type of search backend, if not the default
618 * @return SearchEngine
619 */
620 public static function create( $type = null ) {
621 return MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $type );
622 }
623
624 /**
625 * Return the search engines we support. If only $wgSearchType
626 * is set, it'll be an array of just that one item.
627 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
628 * @return array
629 */
630 public static function getSearchTypes() {
631 return MediaWikiServices::getInstance()->getSearchEngineConfig()->getSearchTypes();
632 }
633
634 }
635
636 /**
637 * Dummy class to be used when non-supported Database engine is present.
638 * @todo FIXME: Dummy class should probably try something at least mildly useful,
639 * such as a LIKE search through titles.
640 * @ingroup Search
641 */
642 class SearchEngineDummy extends SearchEngine {
643 // no-op
644 }