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 (at query time).
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 * Get chars legal for search (at index time).
223 public function legalSearchCharsForUpdate() {
224 return static::legalSearchChars();
228 * Set the maximum number of results to return
229 * and how many to skip before returning the first.
234 function setLimitOffset( $limit, $offset = 0 ) {
235 $this->limit
= intval( $limit );
236 $this->offset
= intval( $offset );
240 * Set which namespaces the search should include.
241 * Give an array of namespace index numbers.
243 * @param int[]|null $namespaces
245 function setNamespaces( $namespaces ) {
247 // Filter namespaces to only keep valid ones
248 $validNs = $this->searchableNamespaces();
249 $namespaces = array_filter( $namespaces, function ( $ns ) use( $validNs ) {
250 return $ns < 0 ||
isset( $validNs[$ns] );
255 $this->namespaces
= $namespaces;
259 * Set whether the searcher should try to build a suggestion. Note: some searchers
260 * don't support building a suggestion in the first place and others don't respect
263 * @param bool $showSuggestion Should the searcher try to build suggestions
265 function setShowSuggestion( $showSuggestion ) {
266 $this->showSuggestion
= $showSuggestion;
270 * Get the valid sort directions. All search engines support 'relevance' but others
271 * might support more. The default in all implementations should be 'relevance.'
274 * @return array(string) the valid sort directions for setSort
276 public function getValidSorts() {
277 return [ 'relevance' ];
281 * Set the sort direction of the search results. Must be one returned by
282 * SearchEngine::getValidSorts()
285 * @throws InvalidArgumentException
286 * @param string $sort sort direction for query result
288 public function setSort( $sort ) {
289 if ( !in_array( $sort, $this->getValidSorts() ) ) {
290 throw new InvalidArgumentException( "Invalid sort: $sort. " .
291 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
297 * Get the sort direction of the search results
302 public function getSort() {
307 * Parse some common prefixes: all (search everything)
308 * or namespace names and set the list of namespaces
309 * of this class accordingly.
311 * @param string $query
314 function replacePrefixes( $query ) {
315 $queryAndNs = self
::parseNamespacePrefixes( $query );
316 if ( $queryAndNs === false ) {
319 $this->namespaces
= $queryAndNs[1];
320 return $queryAndNs[0];
324 * Parse some common prefixes: all (search everything)
327 * @param string $query
328 * @return false|array false if no namespace was extracted, an array
329 * with the parsed query at index 0 and an array of namespaces at index
330 * 1 (or null for all namespaces).
332 public static function parseNamespacePrefixes( $query ) {
336 if ( strpos( $query, ':' ) === false ) { // nothing to do
339 $extractedNamespace = null;
341 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
342 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
343 $extractedNamespace = null;
344 $parsed = substr( $query, strlen( $allkeyword ) );
345 } elseif ( strpos( $query, ':' ) !== false ) {
346 // TODO: should we unify with PrefixSearch::extractNamespace ?
347 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
348 $index = $wgContLang->getNsIndex( $prefix );
349 if ( $index !== false ) {
350 $extractedNamespace = [ $index ];
351 $parsed = substr( $query, strlen( $prefix ) +
1 );
357 if ( trim( $parsed ) == '' ) {
358 $parsed = $query; // prefix was the whole query
361 return [ $parsed, $extractedNamespace ];
365 * Find snippet highlight settings for all users
366 * @return array Contextlines, contextchars
368 public static function userHighlightPrefs() {
369 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
370 $contextchars = 75; // same as above.... :P
371 return [ $contextlines, $contextchars ];
375 * Create or update the search index record for the given page.
376 * Title and text should be pre-processed.
380 * @param string $title
381 * @param string $text
383 function update( $id, $title, $text ) {
388 * Update a search index record's title only.
389 * Title should be pre-processed.
393 * @param string $title
395 function updateTitle( $id, $title ) {
400 * Delete an indexed page
401 * Title should be pre-processed.
404 * @param int $id Page id that was deleted
405 * @param string $title Title of page that was deleted
407 function delete( $id, $title ) {
412 * Get OpenSearch suggestion template
414 * @deprecated since 1.25
417 public static function getOpenSearchTemplate() {
418 wfDeprecated( __METHOD__
, '1.25' );
419 return ApiOpenSearch
::getOpenSearchTemplate( 'application/x-suggestions+json' );
423 * Get the raw text for updating the index from a content object
424 * Nicer search backends could possibly do something cooler than
425 * just returning raw text
427 * @todo This isn't ideal, we'd really like to have content-specific handling here
428 * @param Title $t Title we're indexing
429 * @param Content $c Content of the page to index
432 public function getTextFromContent( Title
$t, Content
$c = null ) {
433 return $c ?
$c->getTextForSearchIndex() : '';
437 * If an implementation of SearchEngine handles all of its own text processing
438 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
439 * rather silly handling, it should return true here instead.
443 public function textAlreadyUpdatedForIndex() {
448 * Makes search simple string if it was namespaced.
449 * Sets namespaces of the search to namespaces extracted from string.
450 * @param string $search
451 * @return string Simplified search string
453 protected function normalizeNamespaces( $search ) {
454 // Find a Title which is not an interwiki and is in NS_MAIN
455 $title = Title
::newFromText( $search );
456 $ns = $this->namespaces
;
457 if ( $title && !$title->isExternal() ) {
458 $ns = [ $title->getNamespace() ];
459 $search = $title->getText();
460 if ( $ns[0] == NS_MAIN
) {
461 $ns = $this->namespaces
; // no explicit prefix, use default namespaces
462 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
465 $title = Title
::newFromText( $search . 'Dummy' );
466 if ( $title && $title->getText() == 'Dummy'
467 && $title->getNamespace() != NS_MAIN
468 && !$title->isExternal()
470 $ns = [ $title->getNamespace() ];
473 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
477 $ns = array_map( function ( $space ) {
478 return $space == NS_MEDIA ? NS_FILE
: $space;
481 $this->setNamespaces( $ns );
486 * Perform a completion search.
487 * Does not resolve namespaces and does not check variants.
488 * Search engine implementations may want to override this function.
489 * @param string $search
490 * @return SearchSuggestionSet
492 protected function completionSearchBackend( $search ) {
495 $search = trim( $search );
497 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
498 !Hooks
::run( 'PrefixSearchBackend',
499 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
501 // False means hook worked.
502 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
504 return SearchSuggestionSet
::fromStrings( $results );
506 // Hook did not do the job, use default simple search
507 $results = $this->simplePrefixSearch( $search );
508 return SearchSuggestionSet
::fromTitles( $results );
513 * Perform a completion search.
514 * @param string $search
515 * @return SearchSuggestionSet
517 public function completionSearch( $search ) {
518 if ( trim( $search ) === '' ) {
519 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
521 $search = $this->normalizeNamespaces( $search );
522 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
526 * Perform a completion search with variants.
527 * @param string $search
528 * @return SearchSuggestionSet
530 public function completionSearchWithVariants( $search ) {
531 if ( trim( $search ) === '' ) {
532 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
534 $search = $this->normalizeNamespaces( $search );
536 $results = $this->completionSearchBackend( $search );
537 $fallbackLimit = $this->limit
- $results->getSize();
538 if ( $fallbackLimit > 0 ) {
541 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
542 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
544 foreach ( $fallbackSearches as $fbs ) {
545 $this->setLimitOffset( $fallbackLimit );
546 $fallbackSearchResult = $this->completionSearch( $fbs );
547 $results->appendAll( $fallbackSearchResult );
548 $fallbackLimit -= count( $fallbackSearchResult );
549 if ( $fallbackLimit <= 0 ) {
554 return $this->processCompletionResults( $search, $results );
558 * Extract titles from completion results
559 * @param SearchSuggestionSet $completionResults
562 public function extractTitles( SearchSuggestionSet
$completionResults ) {
563 return $completionResults->map( function ( SearchSuggestion
$sugg ) {
564 return $sugg->getSuggestedTitle();
569 * Process completion search results.
570 * Resolves the titles and rescores.
571 * @param SearchSuggestionSet $suggestions
572 * @return SearchSuggestionSet
574 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
575 $search = trim( $search );
576 // preload the titles with LinkBatch
577 $titles = $suggestions->map( function ( SearchSuggestion
$sugg ) {
578 return $sugg->getSuggestedTitle();
580 $lb = new LinkBatch( $titles );
581 $lb->setCaller( __METHOD__
);
584 $results = $suggestions->map( function ( SearchSuggestion
$sugg ) {
585 return $sugg->getSuggestedTitle()->getPrefixedText();
588 if ( $this->offset
=== 0 ) {
589 // Rescore results with an exact title match
590 // NOTE: in some cases like cross-namespace redirects
591 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
592 // backends like Cirrus will return no results. We should still
593 // try an exact title match to workaround this limitation
594 $rescorer = new SearchExactMatchRescorer();
595 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
597 // No need to rescore if offset is not 0
598 // The exact match must have been returned at position 0
600 $rescoredResults = $results;
603 if ( count( $rescoredResults ) > 0 ) {
604 $found = array_search( $rescoredResults[0], $results );
605 if ( $found === false ) {
606 // If the first result is not in the previous array it
607 // means that we found a new exact match
608 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
609 $suggestions->prepend( $exactMatch );
610 $suggestions->shrink( $this->limit
);
612 // if the first result is not the same we need to rescore
614 $suggestions->rescore( $found );
623 * Simple prefix search for subpages.
624 * @param string $search
627 public function defaultPrefixSearch( $search ) {
628 if ( trim( $search ) === '' ) {
632 $search = $this->normalizeNamespaces( $search );
633 return $this->simplePrefixSearch( $search );
637 * Call out to simple search backend.
638 * Defaults to TitlePrefixSearch.
639 * @param string $search
642 protected function simplePrefixSearch( $search ) {
643 // Use default database prefix search
644 $backend = new TitlePrefixSearch
;
645 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
649 * Make a list of searchable namespaces and their canonical names.
650 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
653 public static function searchableNamespaces() {
654 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
658 * Extract default namespaces to search from the given user's
659 * settings, returning a list of index numbers.
660 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
664 public static function userNamespaces( $user ) {
665 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
669 * An array of namespaces indexes to be searched by default
670 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
673 public static function defaultNamespaces() {
674 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->defaultNamespaces();
678 * Get a list of namespace names useful for showing in tooltips
680 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
681 * @param array $namespaces
684 public static function namespacesAsText( $namespaces ) {
685 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
689 * Load up the appropriate search engine class for the currently
690 * active database backend, and return a configured instance.
691 * @deprecated since 1.27; Use SearchEngineFactory::create
692 * @param string $type Type of search backend, if not the default
693 * @return SearchEngine
695 public static function create( $type = null ) {
696 return MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
700 * Return the search engines we support. If only $wgSearchType
701 * is set, it'll be an array of just that one item.
702 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
705 public static function getSearchTypes() {
706 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->getSearchTypes();
710 * Get a list of supported profiles.
711 * Some search engine implementations may expose specific profiles to fine-tune
713 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
714 * The array returned by this function contains the following keys:
715 * - name: the profile name to use with setFeatureData
716 * - desc-message: the i18n description
717 * - default: set to true if this profile is the default
720 * @param string $profileType the type of profiles
721 * @param User|null $user the user requesting the list of profiles
722 * @return array|null the list of profiles or null if none available
724 public function getProfiles( $profileType, User
$user = null ) {
729 * Create a search field definition.
730 * Specific search engines should override this method to create search fields.
731 * @param string $name
732 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
733 * @return SearchIndexField
736 public function makeSearchFieldMapping( $name, $type ) {
737 return new NullIndexField();
741 * Get fields for search index
743 * @return SearchIndexField[] Index field definitions for all content handlers
745 public function getSearchIndexFields() {
746 $models = ContentHandler
::getContentModels();
748 $seenHandlers = new SplObjectStorage();
749 foreach ( $models as $model ) {
751 $handler = ContentHandler
::getForModelID( $model );
753 catch ( MWUnknownContentModelException
$e ) {
754 // If we can find no handler, ignore it
757 // Several models can have the same handler, so avoid processing it repeatedly
758 if ( $seenHandlers->contains( $handler ) ) {
759 // We already did this one
762 $seenHandlers->attach( $handler );
763 $handlerFields = $handler->getFieldsForSearchIndex( $this );
764 foreach ( $handlerFields as $fieldName => $fieldData ) {
765 if ( empty( $fields[$fieldName] ) ) {
766 $fields[$fieldName] = $fieldData;
768 // TODO: do we allow some clashes with the same type or reject all of them?
769 $mergeDef = $fields[$fieldName]->merge( $fieldData );
771 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
773 $fields[$fieldName] = $mergeDef;
777 // Hook to allow extensions to produce search mapping fields
778 Hooks
::run( 'SearchIndexFields', [ &$fields, $this ] );
783 * Augment search results with extra data.
785 * @param SearchResultSet $resultSet
787 public function augmentSearchResults( SearchResultSet
$resultSet ) {
790 Hooks
::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
792 if ( !$setAugmentors && !$rowAugmentors ) {
797 // Convert row augmentors to set augmentor
798 foreach ( $rowAugmentors as $name => $row ) {
799 if ( isset( $setAugmentors[$name] ) ) {
800 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
802 $setAugmentors[$name] = new PerRowAugmentor( $row );
805 foreach ( $setAugmentors as $name => $augmentor ) {
806 $data = $augmentor->augmentAll( $resultSet );
808 $resultSet->setAugmentedData( $name, $data );
815 * Dummy class to be used when non-supported Database engine is present.
816 * @todo FIXME: Dummy class should probably try something at least mildly useful,
817 * such as a LIKE search through titles.
820 class SearchEngineDummy
extends SearchEngine
{