54 protected $limit = 10;
57 protected $offset = 0;
63 protected $searchTerms = [];
66 protected $showSuggestion =
true;
68 private $sort = self::DEFAULT_SORT;
71 protected $features = [];
74 private $hookContainer;
102 return $this->maybePaginate(
function () use ( $term ) {
148 return Status::newGood( [] );
163 return $this->maybePaginate(
function () use ( $term ) {
189 private function maybePaginate( Closure $fn ) {
195 $resultSetOrStatus = $fn();
202 $resultSet = $resultSetOrStatus;
203 } elseif ( $resultSetOrStatus instanceof
Status &&
206 $resultSet = $resultSetOrStatus->getValue();
209 $resultSet->shrink( $this->limit );
212 return $resultSetOrStatus;
223 switch ( $feature ) {
224 case 'search-update':
226 case 'title-suffix-filter':
239 $this->features[$feature] = $data;
250 return $this->features[$feature] ??
null;
263 return MediaWikiServices::getInstance()->getContentLanguage()->segmentByWord( $string );
273 return MediaWikiServices::getInstance()->getTitleMatcher();
284 return MediaWikiServices::getInstance()->getTitleMatcher();
294 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
305 $this->limit = intval( $limit );
306 $this->offset = intval( $offset );
318 $validNs = MediaWikiServices::getInstance()->getSearchEngineConfig()->searchableNamespaces();
320 return $ns < 0 || isset( $validNs[$ns] );
336 $this->showSuggestion = $showSuggestion;
349 return [ self::DEFAULT_SORT ];
361 throw new InvalidArgumentException(
"Invalid sort: $sort. " .
362 "Must be one of: " . implode(
', ', $this->
getValidSorts() ) );
405 $withAllKeyword =
true,
406 $withPrefixSearchExtractNamespaceHook =
false
409 if ( strpos( $query,
':' ) ===
false ) {
412 $extractedNamespace =
null;
415 if ( $withAllKeyword ) {
418 $allkeywords[] =
wfMessage(
'searchall' )->inContentLanguage()->text() .
":";
420 if ( !in_array(
'all:', $allkeywords ) ) {
421 $allkeywords[] =
'all:';
424 foreach ( $allkeywords as $kw ) {
425 if ( str_starts_with( $query, $kw ) ) {
426 $parsed = substr( $query, strlen( $kw ) );
433 if ( !$allQuery && strpos( $query,
':' ) !==
false ) {
434 $prefix = str_replace(
' ',
'_', substr( $query, 0, strpos( $query,
':' ) ) );
435 $services = MediaWikiServices::getInstance();
436 $index = $services->getContentLanguage()->getNsIndex( $prefix );
437 if ( $index !==
false ) {
438 $extractedNamespace = [ $index ];
439 $parsed = substr( $query, strlen( $prefix ) + 1 );
440 } elseif ( $withPrefixSearchExtractNamespaceHook ) {
443 (
new HookRunner( $services->getHookContainer() ) )
444 ->onPrefixSearchExtractNamespace( $hookNamespaces, $hookQuery );
445 if ( $hookQuery !== $query ) {
446 $parsed = $hookQuery;
447 $extractedNamespace = $hookNamespaces;
456 return [ $parsed, $extractedNamespace ];
469 return [ $contextlines, $contextchars ];
481 public function update( $id, $title, $text ) {
505 public function delete( $id, $title ) {
521 return $c ? $c->getTextForSearchIndex() :
'';
543 $queryAndNs = self::parseNamespacePrefixes( $search,
false,
true );
544 if ( $queryAndNs !==
false ) {
546 return $queryAndNs[0];
580 $search = trim( $search );
582 if ( !in_array(
NS_SPECIAL, $this->namespaces ) &&
584 $this->namespaces, $search, $this->limit, $results, $this->offset )
603 if ( trim( $search ) ===
'' ) {
619 if ( trim( $search ) ===
'' ) {
625 $fallbackLimit = 1 + $this->limit - $results->getSize();
626 if ( $fallbackLimit > 0 ) {
627 $services = MediaWikiServices::getInstance();
628 $fallbackSearches = $services->getLanguageConverterFactory()
629 ->getLanguageConverter( $services->getContentLanguage() )
630 ->autoConvertToAllVariants( $search );
631 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
633 $origLimit = $this->limit;
634 $origOffset = $this->offset;
635 foreach ( $fallbackSearches as $fbs ) {
639 $results->appendAll( $fallbackSearchResult );
640 $fallbackLimit -= $fallbackSearchResult->getSize();
644 if ( $fallbackLimit <= 0 ) {
673 $suggestions->
shrink( $this->limit );
675 $search = trim( $search );
680 $linkBatchFactory = MediaWikiServices::getInstance()->getLinkBatchFactory();
681 $linkBatchFactory->newLinkBatch( $suggestedTitles )
682 ->setCaller( __METHOD__ )
689 MediaWikiServices::getInstance()->getStatsdDataFactory()
690 ->updateCount(
'search.completion.missing', $diff );
701 if ( $this->offset === 0 ) {
707 $rescoredResults = $rescorer->rescore( $search, $this->namespaces, $results, $this->limit );
712 $rescoredResults = $results;
715 if ( count( $rescoredResults ) > 0 ) {
716 $found = array_search( $rescoredResults[0], $results );
717 if ( $found ===
false ) {
720 $exactMatch = SearchSuggestion::fromTitle( 0, Title::newFromText( $rescoredResults[0] ) );
721 $suggestions->
prepend( $exactMatch );
722 if ( $rescorer->getReplacedRedirect() !==
null ) {
725 $suggestions->
remove( SearchSuggestion::fromTitle( 0,
726 Title::newFromText( $rescorer->getReplacedRedirect() ) ) );
728 $suggestions->
shrink( $this->limit );
732 $suggestions->
rescore( $found );
746 if ( trim( $search ) ===
'' ) {
763 return $backend->
defaultSearchBackend( $this->namespaces, $search, $this->limit, $this->offset );
808 $models = MediaWikiServices::getInstance()->getContentHandlerFactory()->getContentModels();
810 $seenHandlers =
new SplObjectStorage();
811 foreach ( $models as $model ) {
813 $handler = MediaWikiServices::getInstance()
814 ->getContentHandlerFactory()
815 ->getContentHandler( $model );
821 if ( $seenHandlers->contains( $handler ) ) {
825 $seenHandlers->attach( $handler );
826 $handlerFields = $handler->getFieldsForSearchIndex( $this );
827 foreach ( $handlerFields as $fieldName => $fieldData ) {
828 if ( empty( $fields[$fieldName] ) ) {
829 $fields[$fieldName] = $fieldData;
832 $mergeDef = $fields[$fieldName]->merge( $fieldData );
834 throw new InvalidArgumentException(
"Duplicate field $fieldName for model $model" );
836 $fields[$fieldName] = $mergeDef;
841 $this->
getHookRunner()->onSearchIndexFields( $fields, $this );
851 $this->
getHookRunner()->onSearchResultsAugment( $setAugmentors, $rowAugmentors );
852 if ( !$setAugmentors && !$rowAugmentors ) {
858 foreach ( $rowAugmentors as $name => $row ) {
859 if ( isset( $setAugmentors[$name] ) ) {
860 throw new InvalidArgumentException(
"Both row and set augmentors are defined for $name" );
869 foreach ( $setAugmentors as $name => $augmentor ) {
870 $data = $augmentor->augmentAll( $resultSet );
883 $this->hookContainer = $hookContainer;
884 $this->hookRunner =
new HookRunner( $hookContainer );
894 if ( !$this->hookContainer ) {
898 $this->hookContainer = MediaWikiServices::getInstance()->getHookContainer();
900 return $this->hookContainer;
912 if ( !$this->hookRunner ) {
913 $this->hookRunner =
new HookRunner( $this->getHookContainer() );
915 return $this->hookRunner;
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined('MW_SETUP_CALLBACK'))
Exception thrown when an unregistered content model is requested.
Null index field - means search engine does not implement this field.
Perform augmentation of each row and return composite result, indexed by ID.
defaultSearchBackend( $namespaces, $search, $limit, $offset)
Unless overridden by PrefixSearchBackend hook... This is case-sensitive (First character may be autom...
Contain a class for special pages.
completionSearchBackendOverfetch( $search)
Perform an overfetch of completion search results.
makeSearchFieldMapping( $name, $type)
Create a search field definition.
getNearMatcher(Config $config)
Get service class to finding near matches.
getHookRunner()
Get a HookRunner for running core hooks.
searchTitle( $term)
Perform a title-only search query and return a result set.
processCompletionResults( $search, SearchSuggestionSet $suggestions)
Process completion search results.
getFeatureData( $feature)
Way to retrieve custom data set by setFeatureData or by the engine itself.
update( $id, $title, $text)
Create or update the search index record for the given page.
setNamespaces( $namespaces)
Set which namespaces the search should include.
static parseNamespacePrefixes( $query, $withAllKeyword=true, $withPrefixSearchExtractNamespaceHook=false)
Parse some common prefixes: all (search everything) or namespace names.
doSearchArchiveTitle( $term)
Perform a title search in the article archive.
getTextFromContent(Title $t, ?Content $c=null)
Get the raw text for updating the index from a content object Nicer search backends could possibly do...
array $features
Feature values.
replacePrefixes( $query)
Parse some common prefixes: all (search everything) or namespace names and set the list of namespaces...
textAlreadyUpdatedForIndex()
If an implementation of SearchEngine handles all of its own text processing in getTextFromContent() a...
defaultPrefixSearch( $search)
Simple prefix search for subpages.
augmentSearchResults(ISearchResultSet $resultSet)
Augment search results with extra data.
searchArchiveTitle( $term)
Perform a title search in the article archive.
normalizeText( $string)
When overridden in derived class, performs database-specific conversions on text to be used for searc...
setFeatureData( $feature, $data)
Way to pass custom data for engines.
completionSearchBackend( $search)
Perform a completion search.
getSort()
Get the sort direction of the search results.
static defaultNearMatcher()
Get near matcher for default SearchEngine.
getSearchIndexFields()
Get fields for search index.
getValidSorts()
Get the valid sort directions.
static userHighlightPrefs()
Find snippet highlight settings for all users.
updateTitle( $id, $title)
Update a search index record's title only.
completionSearchWithVariants( $search)
Perform a completion search with variants.
doSearchText( $term)
Perform a full text search query and return a result set.
normalizeNamespaces( $search)
Makes search simple string if it was namespaced.
const CHARS_ALL
Integer flag for legalSearchChars: includes all chars allowed in a search query.
getHookContainer()
Get a HookContainer, for running extension hooks or for hook metadata.
completionSearch( $search)
Perform a completion search.
setLimitOffset( $limit, $offset=0)
Set the maximum number of results to return and how many to skip before returning the first.
const CHARS_NO_SYNTAX
Integer flag for legalSearchChars: includes all chars allowed in a search term.
setShowSuggestion( $showSuggestion)
Set whether the searcher should try to build a suggestion.
getProfiles( $profileType, ?User $user=null)
Get a list of supported profiles.
simplePrefixSearch( $search)
Call out to simple search backend.
setSort( $sort)
Set the sort direction of the search results.
const FT_QUERY_INDEP_PROFILE_TYPE
Profile type for query independent ranking features.
setHookContainer(HookContainer $hookContainer)
searchText( $term)
Perform a full text search query and return a result set.
legalSearchChars( $type=self::CHARS_ALL)
Get chars legal for search.
extractTitles(SearchSuggestionSet $completionResults)
Extract titles from completion results.
const COMPLETION_PROFILE_TYPE
Profile type for completionSearch.
doSearchTitle( $term)
Perform a title-only search query and return a result set.
An utility class to rescore search results by looking for an exact match in the db and add the page f...
const DEFAULT_CONTEXT_LINES
const DEFAULT_CONTEXT_CHARS
A set of search suggestions.
filter( $callback)
Filter the suggestions array.
rescore( $key)
Move the suggestion at index $key to the first position.
shrink( $limit)
Remove any extra elements in the suggestions set.
static fromStrings(array $titles, $hasMoreResults=false)
Builds a new set of suggestion based on a string array.
static fromTitles(array $titles, $hasMoreResults=false)
Builds a new set of suggestion based on a title array.
static emptySuggestionSet()
map( $callback)
Call array_map on the suggestions array.
prepend(SearchSuggestion $suggestion)
Add a new suggestion at the top.
remove(SearchSuggestion $suggestion)
Remove a suggestion from the set.
getSuggestedTitle()
Title object in the case this suggestion is based on a title.
Performs prefix search, returning Title objects.
A set of SearchEngine results.
setAugmentedData( $name, $data)
Sets augmented data for result set.
Content objects represent page content, e.g.
Marker class for search engines that can handle their own pagination, by reporting in their ISearchRe...