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
{
35 const DEFAULT_SORT
= 'relevance';
40 /** @var int[]|null */
41 public $namespaces = [ NS_MAIN
];
44 protected $limit = 10;
47 protected $offset = 0;
49 /** @var array|string */
50 protected $searchTerms = [];
53 protected $showSuggestion = true;
54 private $sort = self
::DEFAULT_SORT
;
56 /** @var array Feature values */
57 protected $features = [];
59 /** Profile type for completionSearch */
60 const COMPLETION_PROFILE_TYPE
= 'completionSearchProfile';
62 /** Profile type for query independent ranking features */
63 const FT_QUERY_INDEP_PROFILE_TYPE
= 'fulltextQueryIndepProfile';
65 /** Integer flag for legalSearchChars: includes all chars allowed in a search query */
68 /** Integer flag for legalSearchChars: includes all chars allowed in a search term */
69 const CHARS_NO_SYNTAX
= 2;
72 * Perform a full text search query and return a result set.
73 * If full text searches are not supported or disabled, return null.
75 * As of 1.32 overriding this function is deprecated. It will
76 * be converted to final in 1.34. Override self::doSearchText().
78 * @param string $term Raw search term
79 * @return SearchResultSet|Status|null
81 public function searchText( $term ) {
82 return $this->maybePaginate( function () use ( $term ) {
83 return $this->doSearchText( $term );
88 * Perform a full text search query and return a result set.
90 * @param string $term Raw search term
91 * @return SearchResultSet|Status|null
94 protected function doSearchText( $term ) {
99 * Perform a title search in the article archive.
100 * NOTE: these results still should be filtered by
101 * matching against PageArchive, permissions checks etc
102 * The results returned by this methods are only sugegstions and
103 * may not end up being shown to the user.
105 * As of 1.32 overriding this function is deprecated. It will
106 * be converted to final in 1.34. Override self::doSearchArchiveTitle().
108 * @param string $term Raw search term
109 * @return Status<Title[]>
112 public function searchArchiveTitle( $term ) {
113 return $this->doSearchArchiveTitle( $term );
117 * Perform a title search in the article archive.
119 * @param string $term Raw search term
120 * @return Status<Title[]>
123 protected function doSearchArchiveTitle( $term ) {
124 return Status
::newGood( [] );
128 * Perform a title-only search query and return a result set.
129 * If title searches are not supported or disabled, return null.
132 * As of 1.32 overriding this function is deprecated. It will
133 * be converted to final in 1.34. Override self::doSearchTitle().
135 * @param string $term Raw search term
136 * @return SearchResultSet|null
138 public function searchTitle( $term ) {
139 return $this->maybePaginate( function () use ( $term ) {
140 return $this->doSearchTitle( $term );
145 * Perform a title-only search query and return a result set.
147 * @param string $term Raw search term
148 * @return SearchResultSet|null
151 protected function doSearchTitle( $term ) {
156 * Performs an overfetch and shrink operation to determine if
157 * the next page is available for search engines that do not
158 * explicitly implement their own pagination.
160 * @param Closure $fn Takes no arguments
161 * @return SearchResultSet|Status<SearchResultSet>|null Result of calling $fn
163 private function maybePaginate( Closure
$fn ) {
164 if ( $this instanceof PaginatingSearchEngine
) {
169 $resultSetOrStatus = $fn();
175 if ( $resultSetOrStatus instanceof SearchResultSet
) {
176 $resultSet = $resultSetOrStatus;
177 } elseif ( $resultSetOrStatus instanceof Status
&&
178 $resultSetOrStatus->getValue() instanceof SearchResultSet
180 $resultSet = $resultSetOrStatus->getValue();
183 $resultSet->shrink( $this->limit
);
186 return $resultSetOrStatus;
191 * @param string $feature
194 public function supports( $feature ) {
195 switch ( $feature ) {
196 case 'search-update':
198 case 'title-suffix-filter':
205 * Way to pass custom data for engines
207 * @param string $feature
210 public function setFeatureData( $feature, $data ) {
211 $this->features
[$feature] = $data;
215 * Way to retrieve custom data set by setFeatureData
216 * or by the engine itself.
218 * @param string $feature feature name
219 * @return mixed the feature value or null if unset
221 public function getFeatureData( $feature ) {
222 return $this->features
[$feature] ??
null;
226 * When overridden in derived class, performs database-specific conversions
227 * on text to be used for searching or updating search index.
228 * Default implementation does nothing (simply returns $string).
230 * @param string $string String to process
233 public function normalizeText( $string ) {
234 // Some languages such as Chinese require word segmentation
235 return MediaWikiServices
::getInstance()->getContentLanguage()->segmentByWord( $string );
239 * Transform search term in cases when parts of the query came as different
240 * GET params (when supported), e.g. for prefix queries:
241 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
242 * @param string $term
244 * @deprecated since 1.32 this should now be handled internally by the
247 public function transformSearchTerm( $term ) {
252 * Get service class to finding near matches.
253 * @param Config $config Configuration to use for the matcher.
254 * @return SearchNearMatcher
256 public function getNearMatcher( Config
$config ) {
257 return new SearchNearMatcher( $config,
258 MediaWikiServices
::getInstance()->getContentLanguage() );
262 * Get near matcher for default SearchEngine.
263 * @return SearchNearMatcher
265 protected static function defaultNearMatcher() {
266 $services = MediaWikiServices
::getInstance();
267 $config = $services->getMainConfig();
268 return $services->newSearchEngine()->getNearMatcher( $config );
272 * Get chars legal for search
273 * @param int $type type of search chars (see self::CHARS_ALL
274 * and self::CHARS_NO_SYNTAX). Defaults to CHARS_ALL
277 public function legalSearchChars( $type = self
::CHARS_ALL
) {
278 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
282 * Set the maximum number of results to return
283 * and how many to skip before returning the first.
288 function setLimitOffset( $limit, $offset = 0 ) {
289 $this->limit
= intval( $limit );
290 $this->offset
= intval( $offset );
294 * Set which namespaces the search should include.
295 * Give an array of namespace index numbers.
297 * @param int[]|null $namespaces
299 function setNamespaces( $namespaces ) {
301 // Filter namespaces to only keep valid ones
302 $validNs = MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
303 $namespaces = array_filter( $namespaces, function ( $ns ) use( $validNs ) {
304 return $ns < 0 ||
isset( $validNs[$ns] );
309 $this->namespaces
= $namespaces;
313 * Set whether the searcher should try to build a suggestion. Note: some searchers
314 * don't support building a suggestion in the first place and others don't respect
317 * @param bool $showSuggestion Should the searcher try to build suggestions
319 function setShowSuggestion( $showSuggestion ) {
320 $this->showSuggestion
= $showSuggestion;
324 * Get the valid sort directions. All search engines support 'relevance' but others
325 * might support more. The default in all implementations must be 'relevance.'
328 * @return string[] the valid sort directions for setSort
330 public function getValidSorts() {
331 return [ self
::DEFAULT_SORT
];
335 * Set the sort direction of the search results. Must be one returned by
336 * SearchEngine::getValidSorts()
339 * @throws InvalidArgumentException
340 * @param string $sort sort direction for query result
342 public function setSort( $sort ) {
343 if ( !in_array( $sort, $this->getValidSorts() ) ) {
344 throw new InvalidArgumentException( "Invalid sort: $sort. " .
345 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
351 * Get the sort direction of the search results
356 public function getSort() {
361 * Parse some common prefixes: all (search everything)
362 * or namespace names and set the list of namespaces
363 * of this class accordingly.
365 * @deprecated since 1.32; should be handled internally by the search engine
366 * @param string $query
369 function replacePrefixes( $query ) {
374 * Parse some common prefixes: all (search everything)
377 * @param string $query
378 * @param bool $withAllKeyword activate support of the "all:" keyword and its
379 * translations to activate searching on all namespaces.
380 * @param bool $withPrefixSearchExtractNamespaceHook call the PrefixSearchExtractNamespace hook
381 * if classic namespace identification did not match.
382 * @return false|array false if no namespace was extracted, an array
383 * with the parsed query at index 0 and an array of namespaces at index
384 * 1 (or null for all namespaces).
386 * @throws MWException
388 public static function parseNamespacePrefixes(
390 $withAllKeyword = true,
391 $withPrefixSearchExtractNamespaceHook = false
394 if ( strpos( $query, ':' ) === false ) { // nothing to do
397 $extractedNamespace = null;
400 if ( $withAllKeyword ) {
403 $allkeywords[] = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
404 // force all: so that we have a common syntax for all the wikis
405 if ( !in_array( 'all:', $allkeywords ) ) {
406 $allkeywords[] = 'all:';
409 foreach ( $allkeywords as $kw ) {
410 if ( strncmp( $query, $kw, strlen( $kw ) ) == 0 ) {
411 $extractedNamespace = null;
412 $parsed = substr( $query, strlen( $kw ) );
419 if ( !$allQuery && strpos( $query, ':' ) !== false ) {
420 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
421 $index = MediaWikiServices
::getInstance()->getContentLanguage()->getNsIndex( $prefix );
422 if ( $index !== false ) {
423 $extractedNamespace = [ $index ];
424 $parsed = substr( $query, strlen( $prefix ) +
1 );
425 } elseif ( $withPrefixSearchExtractNamespaceHook ) {
426 $hookNamespaces = [ NS_MAIN
];
428 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$hookNamespaces, &$hookQuery ] );
429 if ( $hookQuery !== $query ) {
430 $parsed = $hookQuery;
431 $extractedNamespace = $hookNamespaces;
440 return [ $parsed, $extractedNamespace ];
444 * Find snippet highlight settings for all users
445 * @return array Contextlines, contextchars
447 public static function userHighlightPrefs() {
448 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
449 $contextchars = 75; // same as above.... :P
450 return [ $contextlines, $contextchars ];
454 * Create or update the search index record for the given page.
455 * Title and text should be pre-processed.
459 * @param string $title
460 * @param string $text
462 function update( $id, $title, $text ) {
467 * Update a search index record's title only.
468 * Title should be pre-processed.
472 * @param string $title
474 function updateTitle( $id, $title ) {
479 * Delete an indexed page
480 * Title should be pre-processed.
483 * @param int $id Page id that was deleted
484 * @param string $title Title of page that was deleted
486 function delete( $id, $title ) {
491 * Get the raw text for updating the index from a content object
492 * Nicer search backends could possibly do something cooler than
493 * just returning raw text
495 * @todo This isn't ideal, we'd really like to have content-specific handling here
496 * @param Title $t Title we're indexing
497 * @param Content|null $c Content of the page to index
500 public function getTextFromContent( Title
$t, Content
$c = null ) {
501 return $c ?
$c->getTextForSearchIndex() : '';
505 * If an implementation of SearchEngine handles all of its own text processing
506 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
507 * rather silly handling, it should return true here instead.
511 public function textAlreadyUpdatedForIndex() {
516 * Makes search simple string if it was namespaced.
517 * Sets namespaces of the search to namespaces extracted from string.
518 * @param string $search
519 * @return string Simplified search string
521 protected function normalizeNamespaces( $search ) {
522 $queryAndNs = self
::parseNamespacePrefixes( $search, false, true );
523 if ( $queryAndNs !== false ) {
524 $this->setNamespaces( $queryAndNs[1] );
525 return $queryAndNs[0];
531 * Perform an overfetch of completion search results. This allows
532 * determining if another page of results is available.
534 * @param string $search
535 * @return SearchSuggestionSet
537 protected function completionSearchBackendOverfetch( $search ) {
540 return $this->completionSearchBackend( $search );
547 * Perform a completion search.
548 * Does not resolve namespaces and does not check variants.
549 * Search engine implementations may want to override this function.
550 * @param string $search
551 * @return SearchSuggestionSet
553 protected function completionSearchBackend( $search ) {
556 $search = trim( $search );
558 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
559 !Hooks
::run( 'PrefixSearchBackend',
560 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
562 // False means hook worked.
563 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
565 return SearchSuggestionSet
::fromStrings( $results );
567 // Hook did not do the job, use default simple search
568 $results = $this->simplePrefixSearch( $search );
569 return SearchSuggestionSet
::fromTitles( $results );
574 * Perform a completion search.
575 * @param string $search
576 * @return SearchSuggestionSet
578 public function completionSearch( $search ) {
579 if ( trim( $search ) === '' ) {
580 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
582 $search = $this->normalizeNamespaces( $search );
583 $suggestions = $this->completionSearchBackendOverfetch( $search );
584 return $this->processCompletionResults( $search, $suggestions );
588 * Perform a completion search with variants.
589 * @param string $search
590 * @return SearchSuggestionSet
592 public function completionSearchWithVariants( $search ) {
593 if ( trim( $search ) === '' ) {
594 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
596 $search = $this->normalizeNamespaces( $search );
598 $results = $this->completionSearchBackendOverfetch( $search );
599 $fallbackLimit = 1 +
$this->limit
- $results->getSize();
600 if ( $fallbackLimit > 0 ) {
601 $fallbackSearches = MediaWikiServices
::getInstance()->getContentLanguage()->
602 autoConvertToAllVariants( $search );
603 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
605 foreach ( $fallbackSearches as $fbs ) {
606 $this->setLimitOffset( $fallbackLimit );
607 $fallbackSearchResult = $this->completionSearch( $fbs );
608 $results->appendAll( $fallbackSearchResult );
609 $fallbackLimit -= $fallbackSearchResult->getSize();
610 if ( $fallbackLimit <= 0 ) {
615 return $this->processCompletionResults( $search, $results );
619 * Extract titles from completion results
620 * @param SearchSuggestionSet $completionResults
623 public function extractTitles( SearchSuggestionSet
$completionResults ) {
624 return $completionResults->map( function ( SearchSuggestion
$sugg ) {
625 return $sugg->getSuggestedTitle();
630 * Process completion search results.
631 * Resolves the titles and rescores.
632 * @param string $search
633 * @param SearchSuggestionSet $suggestions
634 * @return SearchSuggestionSet
636 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
637 // We over-fetched to determine pagination. Shrink back down if we have extra results
638 // and mark if pagination is possible
639 $suggestions->shrink( $this->limit
);
641 $search = trim( $search );
642 // preload the titles with LinkBatch
643 $lb = new LinkBatch( $suggestions->map( function ( SearchSuggestion
$sugg ) {
644 return $sugg->getSuggestedTitle();
646 $lb->setCaller( __METHOD__
);
649 $diff = $suggestions->filter( function ( SearchSuggestion
$sugg ) {
650 return $sugg->getSuggestedTitle()->isKnown();
653 MediaWikiServices
::getInstance()->getStatsdDataFactory()
654 ->updateCount( 'search.completion.missing', $diff );
657 $results = $suggestions->map( function ( SearchSuggestion
$sugg ) {
658 return $sugg->getSuggestedTitle()->getPrefixedText();
661 if ( $this->offset
=== 0 ) {
662 // Rescore results with an exact title match
663 // NOTE: in some cases like cross-namespace redirects
664 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
665 // backends like Cirrus will return no results. We should still
666 // try an exact title match to workaround this limitation
667 $rescorer = new SearchExactMatchRescorer();
668 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
670 // No need to rescore if offset is not 0
671 // The exact match must have been returned at position 0
673 $rescoredResults = $results;
676 if ( count( $rescoredResults ) > 0 ) {
677 $found = array_search( $rescoredResults[0], $results );
678 if ( $found === false ) {
679 // If the first result is not in the previous array it
680 // means that we found a new exact match
681 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
682 $suggestions->prepend( $exactMatch );
683 $suggestions->shrink( $this->limit
);
685 // if the first result is not the same we need to rescore
687 $suggestions->rescore( $found );
696 * Simple prefix search for subpages.
697 * @param string $search
700 public function defaultPrefixSearch( $search ) {
701 if ( trim( $search ) === '' ) {
705 $search = $this->normalizeNamespaces( $search );
706 return $this->simplePrefixSearch( $search );
710 * Call out to simple search backend.
711 * Defaults to TitlePrefixSearch.
712 * @param string $search
715 protected function simplePrefixSearch( $search ) {
716 // Use default database prefix search
717 $backend = new TitlePrefixSearch
;
718 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
722 * Get a list of supported profiles.
723 * Some search engine implementations may expose specific profiles to fine-tune
725 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
726 * The array returned by this function contains the following keys:
727 * - name: the profile name to use with setFeatureData
728 * - desc-message: the i18n description
729 * - default: set to true if this profile is the default
732 * @param string $profileType the type of profiles
733 * @param User|null $user the user requesting the list of profiles
734 * @return array|null the list of profiles or null if none available
736 public function getProfiles( $profileType, User
$user = null ) {
741 * Create a search field definition.
742 * Specific search engines should override this method to create search fields.
743 * @param string $name
744 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
745 * @return SearchIndexField
748 public function makeSearchFieldMapping( $name, $type ) {
749 return new NullIndexField();
753 * Get fields for search index
755 * @return SearchIndexField[] Index field definitions for all content handlers
757 public function getSearchIndexFields() {
758 $models = ContentHandler
::getContentModels();
760 $seenHandlers = new SplObjectStorage();
761 foreach ( $models as $model ) {
763 $handler = ContentHandler
::getForModelID( $model );
765 catch ( MWUnknownContentModelException
$e ) {
766 // If we can find no handler, ignore it
769 // Several models can have the same handler, so avoid processing it repeatedly
770 if ( $seenHandlers->contains( $handler ) ) {
771 // We already did this one
774 $seenHandlers->attach( $handler );
775 $handlerFields = $handler->getFieldsForSearchIndex( $this );
776 foreach ( $handlerFields as $fieldName => $fieldData ) {
777 if ( empty( $fields[$fieldName] ) ) {
778 $fields[$fieldName] = $fieldData;
780 // TODO: do we allow some clashes with the same type or reject all of them?
781 $mergeDef = $fields[$fieldName]->merge( $fieldData );
783 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
785 $fields[$fieldName] = $mergeDef;
789 // Hook to allow extensions to produce search mapping fields
790 Hooks
::run( 'SearchIndexFields', [ &$fields, $this ] );
795 * Augment search results with extra data.
797 * @param SearchResultSet $resultSet
799 public function augmentSearchResults( SearchResultSet
$resultSet ) {
802 Hooks
::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
803 if ( !$setAugmentors && !$rowAugmentors ) {
808 // Convert row augmentors to set augmentor
809 foreach ( $rowAugmentors as $name => $row ) {
810 if ( isset( $setAugmentors[$name] ) ) {
811 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
813 $setAugmentors[$name] = new PerRowAugmentor( $row );
816 foreach ( $setAugmentors as $name => $augmentor ) {
817 $data = $augmentor->augmentAll( $resultSet );
819 $resultSet->setAugmentedData( $name, $data );