Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / search / SearchEngine.php
blob0bcb07a5a67fb759e5665bd685a07e21a274153c
1 <?php
2 /**
3 * Basic search engine
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.
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.
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
20 * @file
21 * @ingroup Search
24 /**
25 * @defgroup Search Search
28 use MediaWiki\MediaWikiServices;
30 /**
31 * Contain a class for special pages
32 * @ingroup Search
34 abstract class SearchEngine {
35 /** @var string */
36 public $prefix = '';
38 /** @var int[]|null */
39 public $namespaces = [ NS_MAIN ];
41 /** @var int */
42 protected $limit = 10;
44 /** @var int */
45 protected $offset = 0;
47 /** @var array|string */
48 protected $searchTerms = [];
50 /** @var bool */
51 protected $showSuggestion = true;
52 private $sort = 'relevance';
54 /** @var array Feature values */
55 protected $features = [];
57 /** @const string profile type for completionSearch */
58 const COMPLETION_PROFILE_TYPE = 'completionSearchProfile';
60 /** @const string profile type for query independent ranking features */
61 const FT_QUERY_INDEP_PROFILE_TYPE = 'fulltextQueryIndepProfile';
63 /**
64 * Perform a full text search query and return a result set.
65 * If full text searches are not supported or disabled, return null.
66 * STUB
68 * @param string $term Raw search term
69 * @return SearchResultSet|Status|null
71 function searchText( $term ) {
72 return null;
75 /**
76 * Perform a title-only search query and return a result set.
77 * If title searches are not supported or disabled, return null.
78 * STUB
80 * @param string $term Raw search term
81 * @return SearchResultSet|null
83 function searchTitle( $term ) {
84 return null;
87 /**
88 * @since 1.18
89 * @param string $feature
90 * @return bool
92 public function supports( $feature ) {
93 switch ( $feature ) {
94 case 'search-update':
95 return true;
96 case 'title-suffix-filter':
97 default:
98 return false;
103 * Way to pass custom data for engines
104 * @since 1.18
105 * @param string $feature
106 * @param mixed $data
108 public function setFeatureData( $feature, $data ) {
109 $this->features[$feature] = $data;
113 * When overridden in derived class, performs database-specific conversions
114 * on text to be used for searching or updating search index.
115 * Default implementation does nothing (simply returns $string).
117 * @param string $string String to process
118 * @return string
120 public function normalizeText( $string ) {
121 global $wgContLang;
123 // Some languages such as Chinese require word segmentation
124 return $wgContLang->segmentByWord( $string );
128 * Transform search term in cases when parts of the query came as different
129 * GET params (when supported), e.g. for prefix queries:
130 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
131 * @param string $term
132 * @return string
134 public function transformSearchTerm( $term ) {
135 return $term;
139 * Get service class to finding near matches.
140 * @param Config $config Configuration to use for the matcher.
141 * @return SearchNearMatcher
143 public function getNearMatcher( Config $config ) {
144 global $wgContLang;
145 return new SearchNearMatcher( $config, $wgContLang );
149 * Get near matcher for default SearchEngine.
150 * @return SearchNearMatcher
152 protected static function defaultNearMatcher() {
153 $config = MediaWikiServices::getInstance()->getMainConfig();
154 return MediaWikiServices::getInstance()->newSearchEngine()->getNearMatcher( $config );
158 * If an exact title match can be found, or a very slightly close match,
159 * return the title. If no match, returns NULL.
160 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
161 * @param string $searchterm
162 * @return Title
164 public static function getNearMatch( $searchterm ) {
165 return static::defaultNearMatcher()->getNearMatch( $searchterm );
169 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
170 * SearchResultSet.
171 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
172 * @param string $searchterm
173 * @return SearchResultSet
175 public static function getNearMatchResultSet( $searchterm ) {
176 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
180 * Get chars legal for search.
181 * NOTE: usage as static is deprecated and preserved only as BC measure
182 * @return string
184 public static function legalSearchChars() {
185 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
189 * Set the maximum number of results to return
190 * and how many to skip before returning the first.
192 * @param int $limit
193 * @param int $offset
195 function setLimitOffset( $limit, $offset = 0 ) {
196 $this->limit = intval( $limit );
197 $this->offset = intval( $offset );
201 * Set which namespaces the search should include.
202 * Give an array of namespace index numbers.
204 * @param int[]|null $namespaces
206 function setNamespaces( $namespaces ) {
207 if ( $namespaces ) {
208 // Filter namespaces to only keep valid ones
209 $validNs = $this->searchableNamespaces();
210 $namespaces = array_filter( $namespaces, function( $ns ) use( $validNs ) {
211 return $ns < 0 || isset( $validNs[$ns] );
212 } );
213 } else {
214 $namespaces = [];
216 $this->namespaces = $namespaces;
220 * Set whether the searcher should try to build a suggestion. Note: some searchers
221 * don't support building a suggestion in the first place and others don't respect
222 * this flag.
224 * @param bool $showSuggestion Should the searcher try to build suggestions
226 function setShowSuggestion( $showSuggestion ) {
227 $this->showSuggestion = $showSuggestion;
231 * Get the valid sort directions. All search engines support 'relevance' but others
232 * might support more. The default in all implementations should be 'relevance.'
234 * @since 1.25
235 * @return array(string) the valid sort directions for setSort
237 public function getValidSorts() {
238 return [ 'relevance' ];
242 * Set the sort direction of the search results. Must be one returned by
243 * SearchEngine::getValidSorts()
245 * @since 1.25
246 * @throws InvalidArgumentException
247 * @param string $sort sort direction for query result
249 public function setSort( $sort ) {
250 if ( !in_array( $sort, $this->getValidSorts() ) ) {
251 throw new InvalidArgumentException( "Invalid sort: $sort. " .
252 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
254 $this->sort = $sort;
258 * Get the sort direction of the search results
260 * @since 1.25
261 * @return string
263 public function getSort() {
264 return $this->sort;
268 * Parse some common prefixes: all (search everything)
269 * or namespace names and set the list of namespaces
270 * of this class accordingly.
272 * @param string $query
273 * @return string
275 function replacePrefixes( $query ) {
276 $queryAndNs = self::parseNamespacePrefixes( $query );
277 if ( $queryAndNs === false ) {
278 return $query;
280 $this->namespaces = $queryAndNs[1];
281 return $queryAndNs[0];
285 * Parse some common prefixes: all (search everything)
286 * or namespace names
288 * @param string $query
289 * @return false|array false if no namespace was extracted, an array
290 * with the parsed query at index 0 and an array of namespaces at index
291 * 1 (or null for all namespaces).
293 public static function parseNamespacePrefixes( $query ) {
294 global $wgContLang;
296 $parsed = $query;
297 if ( strpos( $query, ':' ) === false ) { // nothing to do
298 return false;
300 $extractedNamespace = null;
302 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
303 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
304 $extractedNamespace = null;
305 $parsed = substr( $query, strlen( $allkeyword ) );
306 } elseif ( strpos( $query, ':' ) !== false ) {
307 // TODO: should we unify with PrefixSearch::extractNamespace ?
308 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
309 $index = $wgContLang->getNsIndex( $prefix );
310 if ( $index !== false ) {
311 $extractedNamespace = [ $index ];
312 $parsed = substr( $query, strlen( $prefix ) + 1 );
313 } else {
314 return false;
318 if ( trim( $parsed ) == '' ) {
319 $parsed = $query; // prefix was the whole query
322 return [ $parsed, $extractedNamespace ];
326 * Find snippet highlight settings for all users
327 * @return array Contextlines, contextchars
329 public static function userHighlightPrefs() {
330 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
331 $contextchars = 75; // same as above.... :P
332 return [ $contextlines, $contextchars ];
336 * Create or update the search index record for the given page.
337 * Title and text should be pre-processed.
338 * STUB
340 * @param int $id
341 * @param string $title
342 * @param string $text
344 function update( $id, $title, $text ) {
345 // no-op
349 * Update a search index record's title only.
350 * Title should be pre-processed.
351 * STUB
353 * @param int $id
354 * @param string $title
356 function updateTitle( $id, $title ) {
357 // no-op
361 * Delete an indexed page
362 * Title should be pre-processed.
363 * STUB
365 * @param int $id Page id that was deleted
366 * @param string $title Title of page that was deleted
368 function delete( $id, $title ) {
369 // no-op
373 * Get OpenSearch suggestion template
375 * @deprecated since 1.25
376 * @return string
378 public static function getOpenSearchTemplate() {
379 wfDeprecated( __METHOD__, '1.25' );
380 return ApiOpenSearch::getOpenSearchTemplate( 'application/x-suggestions+json' );
384 * Get the raw text for updating the index from a content object
385 * Nicer search backends could possibly do something cooler than
386 * just returning raw text
388 * @todo This isn't ideal, we'd really like to have content-specific handling here
389 * @param Title $t Title we're indexing
390 * @param Content $c Content of the page to index
391 * @return string
393 public function getTextFromContent( Title $t, Content $c = null ) {
394 return $c ? $c->getTextForSearchIndex() : '';
398 * If an implementation of SearchEngine handles all of its own text processing
399 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
400 * rather silly handling, it should return true here instead.
402 * @return bool
404 public function textAlreadyUpdatedForIndex() {
405 return false;
409 * Makes search simple string if it was namespaced.
410 * Sets namespaces of the search to namespaces extracted from string.
411 * @param string $search
412 * @return string Simplified search string
414 protected function normalizeNamespaces( $search ) {
415 // Find a Title which is not an interwiki and is in NS_MAIN
416 $title = Title::newFromText( $search );
417 $ns = $this->namespaces;
418 if ( $title && !$title->isExternal() ) {
419 $ns = [ $title->getNamespace() ];
420 $search = $title->getText();
421 if ( $ns[0] == NS_MAIN ) {
422 $ns = $this->namespaces; // no explicit prefix, use default namespaces
423 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
425 } else {
426 $title = Title::newFromText( $search . 'Dummy' );
427 if ( $title && $title->getText() == 'Dummy'
428 && $title->getNamespace() != NS_MAIN
429 && !$title->isExternal() )
431 $ns = [ $title->getNamespace() ];
432 $search = '';
433 } else {
434 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
438 $ns = array_map( function( $space ) {
439 return $space == NS_MEDIA ? NS_FILE : $space;
440 }, $ns );
442 $this->setNamespaces( $ns );
443 return $search;
447 * Perform a completion search.
448 * Does not resolve namespaces and does not check variants.
449 * Search engine implementations may want to override this function.
450 * @param string $search
451 * @return SearchSuggestionSet
453 protected function completionSearchBackend( $search ) {
454 $results = [];
456 $search = trim( $search );
458 if ( !in_array( NS_SPECIAL, $this->namespaces ) && // We do not run hook on Special: search
459 !Hooks::run( 'PrefixSearchBackend',
460 [ $this->namespaces, $search, $this->limit, &$results, $this->offset ]
461 ) ) {
462 // False means hook worked.
463 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
465 return SearchSuggestionSet::fromStrings( $results );
466 } else {
467 // Hook did not do the job, use default simple search
468 $results = $this->simplePrefixSearch( $search );
469 return SearchSuggestionSet::fromTitles( $results );
474 * Perform a completion search.
475 * @param string $search
476 * @return SearchSuggestionSet
478 public function completionSearch( $search ) {
479 if ( trim( $search ) === '' ) {
480 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
482 $search = $this->normalizeNamespaces( $search );
483 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
487 * Perform a completion search with variants.
488 * @param string $search
489 * @return SearchSuggestionSet
491 public function completionSearchWithVariants( $search ) {
492 if ( trim( $search ) === '' ) {
493 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
495 $search = $this->normalizeNamespaces( $search );
497 $results = $this->completionSearchBackend( $search );
498 $fallbackLimit = $this->limit - $results->getSize();
499 if ( $fallbackLimit > 0 ) {
500 global $wgContLang;
502 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
503 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
505 foreach ( $fallbackSearches as $fbs ) {
506 $this->setLimitOffset( $fallbackLimit );
507 $fallbackSearchResult = $this->completionSearch( $fbs );
508 $results->appendAll( $fallbackSearchResult );
509 $fallbackLimit -= count( $fallbackSearchResult );
510 if ( $fallbackLimit <= 0 ) {
511 break;
515 return $this->processCompletionResults( $search, $results );
519 * Extract titles from completion results
520 * @param SearchSuggestionSet $completionResults
521 * @return Title[]
523 public function extractTitles( SearchSuggestionSet $completionResults ) {
524 return $completionResults->map( function( SearchSuggestion $sugg ) {
525 return $sugg->getSuggestedTitle();
526 } );
530 * Process completion search results.
531 * Resolves the titles and rescores.
532 * @param SearchSuggestionSet $suggestions
533 * @return SearchSuggestionSet
535 protected function processCompletionResults( $search, SearchSuggestionSet $suggestions ) {
536 $search = trim( $search );
537 // preload the titles with LinkBatch
538 $titles = $suggestions->map( function( SearchSuggestion $sugg ) {
539 return $sugg->getSuggestedTitle();
540 } );
541 $lb = new LinkBatch( $titles );
542 $lb->setCaller( __METHOD__ );
543 $lb->execute();
545 $results = $suggestions->map( function( SearchSuggestion $sugg ) {
546 return $sugg->getSuggestedTitle()->getPrefixedText();
547 } );
549 if ( $this->offset === 0 ) {
550 // Rescore results with an exact title match
551 // NOTE: in some cases like cross-namespace redirects
552 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
553 // backends like Cirrus will return no results. We should still
554 // try an exact title match to workaround this limitation
555 $rescorer = new SearchExactMatchRescorer();
556 $rescoredResults = $rescorer->rescore( $search, $this->namespaces, $results, $this->limit );
557 } else {
558 // No need to rescore if offset is not 0
559 // The exact match must have been returned at position 0
560 // if it existed.
561 $rescoredResults = $results;
564 if ( count( $rescoredResults ) > 0 ) {
565 $found = array_search( $rescoredResults[0], $results );
566 if ( $found === false ) {
567 // If the first result is not in the previous array it
568 // means that we found a new exact match
569 $exactMatch = SearchSuggestion::fromTitle( 0, Title::newFromText( $rescoredResults[0] ) );
570 $suggestions->prepend( $exactMatch );
571 $suggestions->shrink( $this->limit );
572 } else {
573 // if the first result is not the same we need to rescore
574 if ( $found > 0 ) {
575 $suggestions->rescore( $found );
580 return $suggestions;
584 * Simple prefix search for subpages.
585 * @param string $search
586 * @return Title[]
588 public function defaultPrefixSearch( $search ) {
589 if ( trim( $search ) === '' ) {
590 return [];
593 $search = $this->normalizeNamespaces( $search );
594 return $this->simplePrefixSearch( $search );
598 * Call out to simple search backend.
599 * Defaults to TitlePrefixSearch.
600 * @param string $search
601 * @return Title[]
603 protected function simplePrefixSearch( $search ) {
604 // Use default database prefix search
605 $backend = new TitlePrefixSearch;
606 return $backend->defaultSearchBackend( $this->namespaces, $search, $this->limit, $this->offset );
610 * Make a list of searchable namespaces and their canonical names.
611 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
612 * @return array
614 public static function searchableNamespaces() {
615 return MediaWikiServices::getInstance()->getSearchEngineConfig()->searchableNamespaces();
619 * Extract default namespaces to search from the given user's
620 * settings, returning a list of index numbers.
621 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
622 * @param user $user
623 * @return array
625 public static function userNamespaces( $user ) {
626 return MediaWikiServices::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
630 * An array of namespaces indexes to be searched by default
631 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
632 * @return array
634 public static function defaultNamespaces() {
635 return MediaWikiServices::getInstance()->getSearchEngineConfig()->defaultNamespaces();
639 * Get a list of namespace names useful for showing in tooltips
640 * and preferences
641 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
642 * @param array $namespaces
643 * @return array
645 public static function namespacesAsText( $namespaces ) {
646 return MediaWikiServices::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
650 * Load up the appropriate search engine class for the currently
651 * active database backend, and return a configured instance.
652 * @deprecated since 1.27; Use SearchEngineFactory::create
653 * @param string $type Type of search backend, if not the default
654 * @return SearchEngine
656 public static function create( $type = null ) {
657 return MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $type );
661 * Return the search engines we support. If only $wgSearchType
662 * is set, it'll be an array of just that one item.
663 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
664 * @return array
666 public static function getSearchTypes() {
667 return MediaWikiServices::getInstance()->getSearchEngineConfig()->getSearchTypes();
671 * Get a list of supported profiles.
672 * Some search engine implementations may expose specific profiles to fine-tune
673 * its behaviors.
674 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
675 * The array returned by this function contains the following keys:
676 * - name: the profile name to use with setFeatureData
677 * - desc-message: the i18n description
678 * - default: set to true if this profile is the default
680 * @since 1.28
681 * @param string $profileType the type of profiles
682 * @param User|null $user the user requesting the list of profiles
683 * @return array|null the list of profiles or null if none available
685 public function getProfiles( $profileType, User $user = null ) {
686 return null;
690 * Create a search field definition.
691 * Specific search engines should override this method to create search fields.
692 * @param string $name
693 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
694 * @return SearchIndexField
695 * @since 1.28
697 public function makeSearchFieldMapping( $name, $type ) {
698 return new NullIndexField();
702 * Get fields for search index
703 * @since 1.28
704 * @return SearchIndexField[] Index field definitions for all content handlers
706 public function getSearchIndexFields() {
707 $models = ContentHandler::getContentModels();
708 $fields = [];
709 foreach ( $models as $model ) {
710 $handler = ContentHandler::getForModelID( $model );
711 $handlerFields = $handler->getFieldsForSearchIndex( $this );
712 foreach ( $handlerFields as $fieldName => $fieldData ) {
713 if ( empty( $fields[$fieldName] ) ) {
714 $fields[$fieldName] = $fieldData;
715 } else {
716 // TODO: do we allow some clashes with the same type or reject all of them?
717 $mergeDef = $fields[$fieldName]->merge( $fieldData );
718 if ( !$mergeDef ) {
719 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
721 $fields[$fieldName] = $mergeDef;
725 // Hook to allow extensions to produce search mapping fields
726 Hooks::run( 'SearchIndexFields', [ &$fields, $this ] );
727 return $fields;
731 * Augment search results with extra data.
733 * @param SearchResultSet $resultSet
735 public function augmentSearchResults( SearchResultSet $resultSet ) {
736 $setAugmentors = [];
737 $rowAugmentors = [];
738 Hooks::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
740 if ( !$setAugmentors && !$rowAugmentors ) {
741 // We're done here
742 return;
745 // Convert row augmentors to set augmentor
746 foreach ( $rowAugmentors as $name => $row ) {
747 if ( isset( $setAugmentors[$name] ) ) {
748 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
750 $setAugmentors[$name] = new PerRowAugmentor( $row );
753 foreach ( $setAugmentors as $name => $augmentor ) {
754 $data = $augmentor->augmentAll( $resultSet );
755 if ( $data ) {
756 $resultSet->setAugmentedData( $name, $data );
763 * Dummy class to be used when non-supported Database engine is present.
764 * @todo FIXME: Dummy class should probably try something at least mildly useful,
765 * such as a LIKE search through titles.
766 * @ingroup Search
768 class SearchEngineDummy extends SearchEngine {
769 // no-op