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
25 * @defgroup Search Search
28 use MediaWiki\MediaWikiServices
;
31 * Contain a class for special pages
34 abstract class SearchEngine
{
38 /** @var int[]|null */
39 public $namespaces = [ NS_MAIN
];
42 protected $limit = 10;
45 protected $offset = 0;
47 /** @var array|string */
48 protected $searchTerms = [];
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';
64 * Perform a full text search query and return a result set.
65 * If full text searches are not supported or disabled, return null.
68 * @param string $term Raw search term
69 * @return SearchResultSet|Status|null
71 function searchText( $term ) {
76 * Perform a title search in the article archive.
77 * NOTE: these results still should be filtered by
78 * matching against PageArchive, permissions checks etc
79 * The results returned by this methods are only sugegstions and
80 * may not end up being shown to the user.
82 * @param string $term Raw search term
83 * @return Status<Title[]>
86 function searchArchiveTitle( $term ) {
87 return Status
::newGood( [] );
91 * Perform a title-only search query and return a result set.
92 * If title searches are not supported or disabled, return null.
95 * @param string $term Raw search term
96 * @return SearchResultSet|null
98 function searchTitle( $term ) {
104 * @param string $feature
107 public function supports( $feature ) {
108 switch ( $feature ) {
109 case 'search-update':
111 case 'title-suffix-filter':
118 * Way to pass custom data for engines
120 * @param string $feature
123 public function setFeatureData( $feature, $data ) {
124 $this->features
[$feature] = $data;
128 * Way to retrieve custom data set by setFeatureData
129 * or by the engine itself.
131 * @param string $feature feature name
132 * @return mixed the feature value or null if unset
134 public function getFeatureData( $feature ) {
135 if ( isset ( $this->features
[$feature] ) ) {
136 return $this->features
[$feature];
142 * When overridden in derived class, performs database-specific conversions
143 * on text to be used for searching or updating search index.
144 * Default implementation does nothing (simply returns $string).
146 * @param string $string String to process
149 public function normalizeText( $string ) {
152 // Some languages such as Chinese require word segmentation
153 return $wgContLang->segmentByWord( $string );
157 * Transform search term in cases when parts of the query came as different
158 * GET params (when supported), e.g. for prefix queries:
159 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
160 * @param string $term
163 public function transformSearchTerm( $term ) {
168 * Get service class to finding near matches.
169 * @param Config $config Configuration to use for the matcher.
170 * @return SearchNearMatcher
172 public function getNearMatcher( Config
$config ) {
174 return new SearchNearMatcher( $config, $wgContLang );
178 * Get near matcher for default SearchEngine.
179 * @return SearchNearMatcher
181 protected static function defaultNearMatcher() {
182 $config = MediaWikiServices
::getInstance()->getMainConfig();
183 return MediaWikiServices
::getInstance()->newSearchEngine()->getNearMatcher( $config );
187 * If an exact title match can be found, or a very slightly close match,
188 * return the title. If no match, returns NULL.
189 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
190 * @param string $searchterm
193 public static function getNearMatch( $searchterm ) {
194 return static::defaultNearMatcher()->getNearMatch( $searchterm );
198 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
200 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
201 * @param string $searchterm
202 * @return SearchResultSet
204 public static function getNearMatchResultSet( $searchterm ) {
205 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
209 * Get chars legal for search.
210 * NOTE: usage as static is deprecated and preserved only as BC measure
213 public static function legalSearchChars() {
214 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
218 * Set the maximum number of results to return
219 * and how many to skip before returning the first.
224 function setLimitOffset( $limit, $offset = 0 ) {
225 $this->limit
= intval( $limit );
226 $this->offset
= intval( $offset );
230 * Set which namespaces the search should include.
231 * Give an array of namespace index numbers.
233 * @param int[]|null $namespaces
235 function setNamespaces( $namespaces ) {
237 // Filter namespaces to only keep valid ones
238 $validNs = $this->searchableNamespaces();
239 $namespaces = array_filter( $namespaces, function ( $ns ) use( $validNs ) {
240 return $ns < 0 ||
isset( $validNs[$ns] );
245 $this->namespaces
= $namespaces;
249 * Set whether the searcher should try to build a suggestion. Note: some searchers
250 * don't support building a suggestion in the first place and others don't respect
253 * @param bool $showSuggestion Should the searcher try to build suggestions
255 function setShowSuggestion( $showSuggestion ) {
256 $this->showSuggestion
= $showSuggestion;
260 * Get the valid sort directions. All search engines support 'relevance' but others
261 * might support more. The default in all implementations should be 'relevance.'
264 * @return array(string) the valid sort directions for setSort
266 public function getValidSorts() {
267 return [ 'relevance' ];
271 * Set the sort direction of the search results. Must be one returned by
272 * SearchEngine::getValidSorts()
275 * @throws InvalidArgumentException
276 * @param string $sort sort direction for query result
278 public function setSort( $sort ) {
279 if ( !in_array( $sort, $this->getValidSorts() ) ) {
280 throw new InvalidArgumentException( "Invalid sort: $sort. " .
281 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
287 * Get the sort direction of the search results
292 public function getSort() {
297 * Parse some common prefixes: all (search everything)
298 * or namespace names and set the list of namespaces
299 * of this class accordingly.
301 * @param string $query
304 function replacePrefixes( $query ) {
305 $queryAndNs = self
::parseNamespacePrefixes( $query );
306 if ( $queryAndNs === false ) {
309 $this->namespaces
= $queryAndNs[1];
310 return $queryAndNs[0];
314 * Parse some common prefixes: all (search everything)
317 * @param string $query
318 * @return false|array false if no namespace was extracted, an array
319 * with the parsed query at index 0 and an array of namespaces at index
320 * 1 (or null for all namespaces).
322 public static function parseNamespacePrefixes( $query ) {
326 if ( strpos( $query, ':' ) === false ) { // nothing to do
329 $extractedNamespace = null;
331 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
332 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
333 $extractedNamespace = null;
334 $parsed = substr( $query, strlen( $allkeyword ) );
335 } elseif ( strpos( $query, ':' ) !== false ) {
336 // TODO: should we unify with PrefixSearch::extractNamespace ?
337 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
338 $index = $wgContLang->getNsIndex( $prefix );
339 if ( $index !== false ) {
340 $extractedNamespace = [ $index ];
341 $parsed = substr( $query, strlen( $prefix ) +
1 );
347 if ( trim( $parsed ) == '' ) {
348 $parsed = $query; // prefix was the whole query
351 return [ $parsed, $extractedNamespace ];
355 * Find snippet highlight settings for all users
356 * @return array Contextlines, contextchars
358 public static function userHighlightPrefs() {
359 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
360 $contextchars = 75; // same as above.... :P
361 return [ $contextlines, $contextchars ];
365 * Create or update the search index record for the given page.
366 * Title and text should be pre-processed.
370 * @param string $title
371 * @param string $text
373 function update( $id, $title, $text ) {
378 * Update a search index record's title only.
379 * Title should be pre-processed.
383 * @param string $title
385 function updateTitle( $id, $title ) {
390 * Delete an indexed page
391 * Title should be pre-processed.
394 * @param int $id Page id that was deleted
395 * @param string $title Title of page that was deleted
397 function delete( $id, $title ) {
402 * Get OpenSearch suggestion template
404 * @deprecated since 1.25
407 public static function getOpenSearchTemplate() {
408 wfDeprecated( __METHOD__
, '1.25' );
409 return ApiOpenSearch
::getOpenSearchTemplate( 'application/x-suggestions+json' );
413 * Get the raw text for updating the index from a content object
414 * Nicer search backends could possibly do something cooler than
415 * just returning raw text
417 * @todo This isn't ideal, we'd really like to have content-specific handling here
418 * @param Title $t Title we're indexing
419 * @param Content $c Content of the page to index
422 public function getTextFromContent( Title
$t, Content
$c = null ) {
423 return $c ?
$c->getTextForSearchIndex() : '';
427 * If an implementation of SearchEngine handles all of its own text processing
428 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
429 * rather silly handling, it should return true here instead.
433 public function textAlreadyUpdatedForIndex() {
438 * Makes search simple string if it was namespaced.
439 * Sets namespaces of the search to namespaces extracted from string.
440 * @param string $search
441 * @return string Simplified search string
443 protected function normalizeNamespaces( $search ) {
444 // Find a Title which is not an interwiki and is in NS_MAIN
445 $title = Title
::newFromText( $search );
446 $ns = $this->namespaces
;
447 if ( $title && !$title->isExternal() ) {
448 $ns = [ $title->getNamespace() ];
449 $search = $title->getText();
450 if ( $ns[0] == NS_MAIN
) {
451 $ns = $this->namespaces
; // no explicit prefix, use default namespaces
452 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
455 $title = Title
::newFromText( $search . 'Dummy' );
456 if ( $title && $title->getText() == 'Dummy'
457 && $title->getNamespace() != NS_MAIN
458 && !$title->isExternal()
460 $ns = [ $title->getNamespace() ];
463 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
467 $ns = array_map( function ( $space ) {
468 return $space == NS_MEDIA ? NS_FILE
: $space;
471 $this->setNamespaces( $ns );
476 * Perform a completion search.
477 * Does not resolve namespaces and does not check variants.
478 * Search engine implementations may want to override this function.
479 * @param string $search
480 * @return SearchSuggestionSet
482 protected function completionSearchBackend( $search ) {
485 $search = trim( $search );
487 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
488 !Hooks
::run( 'PrefixSearchBackend',
489 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
491 // False means hook worked.
492 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
494 return SearchSuggestionSet
::fromStrings( $results );
496 // Hook did not do the job, use default simple search
497 $results = $this->simplePrefixSearch( $search );
498 return SearchSuggestionSet
::fromTitles( $results );
503 * Perform a completion search.
504 * @param string $search
505 * @return SearchSuggestionSet
507 public function completionSearch( $search ) {
508 if ( trim( $search ) === '' ) {
509 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
511 $search = $this->normalizeNamespaces( $search );
512 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
516 * Perform a completion search with variants.
517 * @param string $search
518 * @return SearchSuggestionSet
520 public function completionSearchWithVariants( $search ) {
521 if ( trim( $search ) === '' ) {
522 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
524 $search = $this->normalizeNamespaces( $search );
526 $results = $this->completionSearchBackend( $search );
527 $fallbackLimit = $this->limit
- $results->getSize();
528 if ( $fallbackLimit > 0 ) {
531 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
532 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
534 foreach ( $fallbackSearches as $fbs ) {
535 $this->setLimitOffset( $fallbackLimit );
536 $fallbackSearchResult = $this->completionSearch( $fbs );
537 $results->appendAll( $fallbackSearchResult );
538 $fallbackLimit -= count( $fallbackSearchResult );
539 if ( $fallbackLimit <= 0 ) {
544 return $this->processCompletionResults( $search, $results );
548 * Extract titles from completion results
549 * @param SearchSuggestionSet $completionResults
552 public function extractTitles( SearchSuggestionSet
$completionResults ) {
553 return $completionResults->map( function ( SearchSuggestion
$sugg ) {
554 return $sugg->getSuggestedTitle();
559 * Process completion search results.
560 * Resolves the titles and rescores.
561 * @param SearchSuggestionSet $suggestions
562 * @return SearchSuggestionSet
564 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
565 $search = trim( $search );
566 // preload the titles with LinkBatch
567 $titles = $suggestions->map( function ( SearchSuggestion
$sugg ) {
568 return $sugg->getSuggestedTitle();
570 $lb = new LinkBatch( $titles );
571 $lb->setCaller( __METHOD__
);
574 $results = $suggestions->map( function ( SearchSuggestion
$sugg ) {
575 return $sugg->getSuggestedTitle()->getPrefixedText();
578 if ( $this->offset
=== 0 ) {
579 // Rescore results with an exact title match
580 // NOTE: in some cases like cross-namespace redirects
581 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
582 // backends like Cirrus will return no results. We should still
583 // try an exact title match to workaround this limitation
584 $rescorer = new SearchExactMatchRescorer();
585 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
587 // No need to rescore if offset is not 0
588 // The exact match must have been returned at position 0
590 $rescoredResults = $results;
593 if ( count( $rescoredResults ) > 0 ) {
594 $found = array_search( $rescoredResults[0], $results );
595 if ( $found === false ) {
596 // If the first result is not in the previous array it
597 // means that we found a new exact match
598 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
599 $suggestions->prepend( $exactMatch );
600 $suggestions->shrink( $this->limit
);
602 // if the first result is not the same we need to rescore
604 $suggestions->rescore( $found );
613 * Simple prefix search for subpages.
614 * @param string $search
617 public function defaultPrefixSearch( $search ) {
618 if ( trim( $search ) === '' ) {
622 $search = $this->normalizeNamespaces( $search );
623 return $this->simplePrefixSearch( $search );
627 * Call out to simple search backend.
628 * Defaults to TitlePrefixSearch.
629 * @param string $search
632 protected function simplePrefixSearch( $search ) {
633 // Use default database prefix search
634 $backend = new TitlePrefixSearch
;
635 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
639 * Make a list of searchable namespaces and their canonical names.
640 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
643 public static function searchableNamespaces() {
644 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
648 * Extract default namespaces to search from the given user's
649 * settings, returning a list of index numbers.
650 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
654 public static function userNamespaces( $user ) {
655 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
659 * An array of namespaces indexes to be searched by default
660 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
663 public static function defaultNamespaces() {
664 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->defaultNamespaces();
668 * Get a list of namespace names useful for showing in tooltips
670 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
671 * @param array $namespaces
674 public static function namespacesAsText( $namespaces ) {
675 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
679 * Load up the appropriate search engine class for the currently
680 * active database backend, and return a configured instance.
681 * @deprecated since 1.27; Use SearchEngineFactory::create
682 * @param string $type Type of search backend, if not the default
683 * @return SearchEngine
685 public static function create( $type = null ) {
686 return MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
690 * Return the search engines we support. If only $wgSearchType
691 * is set, it'll be an array of just that one item.
692 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
695 public static function getSearchTypes() {
696 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->getSearchTypes();
700 * Get a list of supported profiles.
701 * Some search engine implementations may expose specific profiles to fine-tune
703 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
704 * The array returned by this function contains the following keys:
705 * - name: the profile name to use with setFeatureData
706 * - desc-message: the i18n description
707 * - default: set to true if this profile is the default
710 * @param string $profileType the type of profiles
711 * @param User|null $user the user requesting the list of profiles
712 * @return array|null the list of profiles or null if none available
714 public function getProfiles( $profileType, User
$user = null ) {
719 * Create a search field definition.
720 * Specific search engines should override this method to create search fields.
721 * @param string $name
722 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
723 * @return SearchIndexField
726 public function makeSearchFieldMapping( $name, $type ) {
727 return new NullIndexField();
731 * Get fields for search index
733 * @return SearchIndexField[] Index field definitions for all content handlers
735 public function getSearchIndexFields() {
736 $models = ContentHandler
::getContentModels();
738 $seenHandlers = new SplObjectStorage();
739 foreach ( $models as $model ) {
741 $handler = ContentHandler
::getForModelID( $model );
743 catch ( MWUnknownContentModelException
$e ) {
744 // If we can find no handler, ignore it
747 // Several models can have the same handler, so avoid processing it repeatedly
748 if ( $seenHandlers->contains( $handler ) ) {
749 // We already did this one
752 $seenHandlers->attach( $handler );
753 $handlerFields = $handler->getFieldsForSearchIndex( $this );
754 foreach ( $handlerFields as $fieldName => $fieldData ) {
755 if ( empty( $fields[$fieldName] ) ) {
756 $fields[$fieldName] = $fieldData;
758 // TODO: do we allow some clashes with the same type or reject all of them?
759 $mergeDef = $fields[$fieldName]->merge( $fieldData );
761 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
763 $fields[$fieldName] = $mergeDef;
767 // Hook to allow extensions to produce search mapping fields
768 Hooks
::run( 'SearchIndexFields', [ &$fields, $this ] );
773 * Augment search results with extra data.
775 * @param SearchResultSet $resultSet
777 public function augmentSearchResults( SearchResultSet
$resultSet ) {
780 Hooks
::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
782 if ( !$setAugmentors && !$rowAugmentors ) {
787 // Convert row augmentors to set augmentor
788 foreach ( $rowAugmentors as $name => $row ) {
789 if ( isset( $setAugmentors[$name] ) ) {
790 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
792 $setAugmentors[$name] = new PerRowAugmentor( $row );
795 foreach ( $setAugmentors as $name => $augmentor ) {
796 $data = $augmentor->augmentAll( $resultSet );
798 $resultSet->setAugmentedData( $name, $data );
805 * Dummy class to be used when non-supported Database engine is present.
806 * @todo FIXME: Dummy class should probably try something at least mildly useful,
807 * such as a LIKE search through titles.
810 class SearchEngineDummy
extends SearchEngine
{