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';
63 /** @const int flag for legalSearchChars: includes all chars allowed in a search query */
66 /** @const int flag for legalSearchChars: includes all chars allowed in a search term */
67 const CHARS_NO_SYNTAX
= 2;
70 * Perform a full text search query and return a result set.
71 * If full text searches are not supported or disabled, return null.
73 * As of 1.32 overriding this function is deprecated. It will
74 * be converted to final in 1.34. Override self::doSearchText().
76 * @param string $term Raw search term
77 * @return SearchResultSet|Status|null
79 public function searchText( $term ) {
80 return $this->doSearchText( $term );
84 * Perform a full text search query and return a result set.
86 * @param string $term Raw search term
87 * @return SearchResultSet|Status|null
90 protected function doSearchText( $term ) {
95 * Perform a title search in the article archive.
96 * NOTE: these results still should be filtered by
97 * matching against PageArchive, permissions checks etc
98 * The results returned by this methods are only sugegstions and
99 * may not end up being shown to the user.
101 * As of 1.32 overriding this function is deprecated. It will
102 * be converted to final in 1.34. Override self::doSearchArchiveTitle().
104 * @param string $term Raw search term
105 * @return Status<Title[]>
108 public function searchArchiveTitle( $term ) {
109 return $this->doSearchArchiveTitle( $term );
113 * Perform a title search in the article archive.
115 * @param string $term Raw search term
116 * @return Status<Title[]>
119 protected function doSearchArchiveTitle( $term ) {
120 return Status
::newGood( [] );
124 * Perform a title-only search query and return a result set.
125 * If title searches are not supported or disabled, return null.
128 * As of 1.32 overriding this function is deprecated. It will
129 * be converted to final in 1.34. Override self::doSearchTitle().
131 * @param string $term Raw search term
132 * @return SearchResultSet|null
134 public function searchTitle( $term ) {
135 return $this->doSearchTitle( $term );
139 * Perform a title-only search query and return a result set.
141 * @param string $term Raw search term
142 * @return SearchResultSet|null
145 protected function doSearchTitle( $term ) {
151 * @param string $feature
154 public function supports( $feature ) {
155 switch ( $feature ) {
156 case 'search-update':
158 case 'title-suffix-filter':
165 * Way to pass custom data for engines
167 * @param string $feature
170 public function setFeatureData( $feature, $data ) {
171 $this->features
[$feature] = $data;
175 * Way to retrieve custom data set by setFeatureData
176 * or by the engine itself.
178 * @param string $feature feature name
179 * @return mixed the feature value or null if unset
181 public function getFeatureData( $feature ) {
182 if ( isset( $this->features
[$feature] ) ) {
183 return $this->features
[$feature];
189 * When overridden in derived class, performs database-specific conversions
190 * on text to be used for searching or updating search index.
191 * Default implementation does nothing (simply returns $string).
193 * @param string $string String to process
196 public function normalizeText( $string ) {
199 // Some languages such as Chinese require word segmentation
200 return $wgContLang->segmentByWord( $string );
204 * Transform search term in cases when parts of the query came as different
205 * GET params (when supported), e.g. for prefix queries:
206 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
207 * @param string $term
210 public function transformSearchTerm( $term ) {
215 * Get service class to finding near matches.
216 * @param Config $config Configuration to use for the matcher.
217 * @return SearchNearMatcher
219 public function getNearMatcher( Config
$config ) {
221 return new SearchNearMatcher( $config, $wgContLang );
225 * Get near matcher for default SearchEngine.
226 * @return SearchNearMatcher
228 protected static function defaultNearMatcher() {
229 $config = MediaWikiServices
::getInstance()->getMainConfig();
230 return MediaWikiServices
::getInstance()->newSearchEngine()->getNearMatcher( $config );
234 * If an exact title match can be found, or a very slightly close match,
235 * return the title. If no match, returns NULL.
236 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
237 * @param string $searchterm
240 public static function getNearMatch( $searchterm ) {
241 return static::defaultNearMatcher()->getNearMatch( $searchterm );
245 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
247 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
248 * @param string $searchterm
249 * @return SearchResultSet
251 public static function getNearMatchResultSet( $searchterm ) {
252 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
256 * Get chars legal for search
257 * NOTE: usage as static is deprecated and preserved only as BC measure
258 * @param int $type type of search chars (see self::CHARS_ALL
259 * and self::CHARS_NO_SYNTAX). Defaults to CHARS_ALL
262 public static function legalSearchChars( $type = self
::CHARS_ALL
) {
263 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
267 * Set the maximum number of results to return
268 * and how many to skip before returning the first.
273 function setLimitOffset( $limit, $offset = 0 ) {
274 $this->limit
= intval( $limit );
275 $this->offset
= intval( $offset );
279 * Set which namespaces the search should include.
280 * Give an array of namespace index numbers.
282 * @param int[]|null $namespaces
284 function setNamespaces( $namespaces ) {
286 // Filter namespaces to only keep valid ones
287 $validNs = $this->searchableNamespaces();
288 $namespaces = array_filter( $namespaces, function ( $ns ) use( $validNs ) {
289 return $ns < 0 ||
isset( $validNs[$ns] );
294 $this->namespaces
= $namespaces;
298 * Set whether the searcher should try to build a suggestion. Note: some searchers
299 * don't support building a suggestion in the first place and others don't respect
302 * @param bool $showSuggestion Should the searcher try to build suggestions
304 function setShowSuggestion( $showSuggestion ) {
305 $this->showSuggestion
= $showSuggestion;
309 * Get the valid sort directions. All search engines support 'relevance' but others
310 * might support more. The default in all implementations should be 'relevance.'
313 * @return string[] the valid sort directions for setSort
315 public function getValidSorts() {
316 return [ 'relevance' ];
320 * Set the sort direction of the search results. Must be one returned by
321 * SearchEngine::getValidSorts()
324 * @throws InvalidArgumentException
325 * @param string $sort sort direction for query result
327 public function setSort( $sort ) {
328 if ( !in_array( $sort, $this->getValidSorts() ) ) {
329 throw new InvalidArgumentException( "Invalid sort: $sort. " .
330 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
336 * Get the sort direction of the search results
341 public function getSort() {
346 * Parse some common prefixes: all (search everything)
347 * or namespace names and set the list of namespaces
348 * of this class accordingly.
350 * @param string $query
353 function replacePrefixes( $query ) {
354 $queryAndNs = self
::parseNamespacePrefixes( $query );
355 if ( $queryAndNs === false ) {
358 $this->namespaces
= $queryAndNs[1];
359 return $queryAndNs[0];
363 * Parse some common prefixes: all (search everything)
366 * @param string $query
367 * @return false|array false if no namespace was extracted, an array
368 * with the parsed query at index 0 and an array of namespaces at index
369 * 1 (or null for all namespaces).
371 public static function parseNamespacePrefixes( $query ) {
375 if ( strpos( $query, ':' ) === false ) { // nothing to do
378 $extractedNamespace = null;
381 $allkeywords[] = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
382 // force all: so that we have a common syntax for all the wikis
383 if ( !in_array( 'all:', $allkeywords ) ) {
384 $allkeywords[] = 'all:';
388 foreach ( $allkeywords as $kw ) {
389 if ( strncmp( $query, $kw, strlen( $kw ) ) == 0 ) {
390 $extractedNamespace = null;
391 $parsed = substr( $query, strlen( $kw ) );
397 if ( !$allQuery && strpos( $query, ':' ) !== false ) {
398 // TODO: should we unify with PrefixSearch::extractNamespace ?
399 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
400 $index = $wgContLang->getNsIndex( $prefix );
401 if ( $index !== false ) {
402 $extractedNamespace = [ $index ];
403 $parsed = substr( $query, strlen( $prefix ) +
1 );
409 if ( trim( $parsed ) == '' ) {
410 $parsed = $query; // prefix was the whole query
413 return [ $parsed, $extractedNamespace ];
417 * Find snippet highlight settings for all users
418 * @return array Contextlines, contextchars
420 public static function userHighlightPrefs() {
421 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
422 $contextchars = 75; // same as above.... :P
423 return [ $contextlines, $contextchars ];
427 * Create or update the search index record for the given page.
428 * Title and text should be pre-processed.
432 * @param string $title
433 * @param string $text
435 function update( $id, $title, $text ) {
440 * Update a search index record's title only.
441 * Title should be pre-processed.
445 * @param string $title
447 function updateTitle( $id, $title ) {
452 * Delete an indexed page
453 * Title should be pre-processed.
456 * @param int $id Page id that was deleted
457 * @param string $title Title of page that was deleted
459 function delete( $id, $title ) {
464 * Get the raw text for updating the index from a content object
465 * Nicer search backends could possibly do something cooler than
466 * just returning raw text
468 * @todo This isn't ideal, we'd really like to have content-specific handling here
469 * @param Title $t Title we're indexing
470 * @param Content $c Content of the page to index
473 public function getTextFromContent( Title
$t, Content
$c = null ) {
474 return $c ?
$c->getTextForSearchIndex() : '';
478 * If an implementation of SearchEngine handles all of its own text processing
479 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
480 * rather silly handling, it should return true here instead.
484 public function textAlreadyUpdatedForIndex() {
489 * Makes search simple string if it was namespaced.
490 * Sets namespaces of the search to namespaces extracted from string.
491 * @param string $search
492 * @return string Simplified search string
494 protected function normalizeNamespaces( $search ) {
495 // Find a Title which is not an interwiki and is in NS_MAIN
496 $title = Title
::newFromText( $search );
497 $ns = $this->namespaces
;
498 if ( $title && !$title->isExternal() ) {
499 $ns = [ $title->getNamespace() ];
500 $search = $title->getText();
501 if ( $ns[0] == NS_MAIN
) {
502 $ns = $this->namespaces
; // no explicit prefix, use default namespaces
503 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
506 $title = Title
::newFromText( $search . 'Dummy' );
507 if ( $title && $title->getText() == 'Dummy'
508 && $title->getNamespace() != NS_MAIN
509 && !$title->isExternal()
511 $ns = [ $title->getNamespace() ];
514 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
518 $ns = array_map( function ( $space ) {
519 return $space == NS_MEDIA ? NS_FILE
: $space;
522 $this->setNamespaces( $ns );
527 * Perform a completion search.
528 * Does not resolve namespaces and does not check variants.
529 * Search engine implementations may want to override this function.
530 * @param string $search
531 * @return SearchSuggestionSet
533 protected function completionSearchBackend( $search ) {
536 $search = trim( $search );
538 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
539 !Hooks
::run( 'PrefixSearchBackend',
540 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
542 // False means hook worked.
543 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
545 return SearchSuggestionSet
::fromStrings( $results );
547 // Hook did not do the job, use default simple search
548 $results = $this->simplePrefixSearch( $search );
549 return SearchSuggestionSet
::fromTitles( $results );
554 * Perform a completion search.
555 * @param string $search
556 * @return SearchSuggestionSet
558 public function completionSearch( $search ) {
559 if ( trim( $search ) === '' ) {
560 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
562 $search = $this->normalizeNamespaces( $search );
563 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
567 * Perform a completion search with variants.
568 * @param string $search
569 * @return SearchSuggestionSet
571 public function completionSearchWithVariants( $search ) {
572 if ( trim( $search ) === '' ) {
573 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
575 $search = $this->normalizeNamespaces( $search );
577 $results = $this->completionSearchBackend( $search );
578 $fallbackLimit = $this->limit
- $results->getSize();
579 if ( $fallbackLimit > 0 ) {
582 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
583 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
585 foreach ( $fallbackSearches as $fbs ) {
586 $this->setLimitOffset( $fallbackLimit );
587 $fallbackSearchResult = $this->completionSearch( $fbs );
588 $results->appendAll( $fallbackSearchResult );
589 $fallbackLimit -= $fallbackSearchResult->getSize();
590 if ( $fallbackLimit <= 0 ) {
595 return $this->processCompletionResults( $search, $results );
599 * Extract titles from completion results
600 * @param SearchSuggestionSet $completionResults
603 public function extractTitles( SearchSuggestionSet
$completionResults ) {
604 return $completionResults->map( function ( SearchSuggestion
$sugg ) {
605 return $sugg->getSuggestedTitle();
610 * Process completion search results.
611 * Resolves the titles and rescores.
612 * @param string $search
613 * @param SearchSuggestionSet $suggestions
614 * @return SearchSuggestionSet
616 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
617 $search = trim( $search );
618 // preload the titles with LinkBatch
619 $titles = $suggestions->map( function ( SearchSuggestion
$sugg ) {
620 return $sugg->getSuggestedTitle();
622 $lb = new LinkBatch( $titles );
623 $lb->setCaller( __METHOD__
);
626 $results = $suggestions->map( function ( SearchSuggestion
$sugg ) {
627 return $sugg->getSuggestedTitle()->getPrefixedText();
630 if ( $this->offset
=== 0 ) {
631 // Rescore results with an exact title match
632 // NOTE: in some cases like cross-namespace redirects
633 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
634 // backends like Cirrus will return no results. We should still
635 // try an exact title match to workaround this limitation
636 $rescorer = new SearchExactMatchRescorer();
637 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
639 // No need to rescore if offset is not 0
640 // The exact match must have been returned at position 0
642 $rescoredResults = $results;
645 if ( count( $rescoredResults ) > 0 ) {
646 $found = array_search( $rescoredResults[0], $results );
647 if ( $found === false ) {
648 // If the first result is not in the previous array it
649 // means that we found a new exact match
650 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
651 $suggestions->prepend( $exactMatch );
652 $suggestions->shrink( $this->limit
);
654 // if the first result is not the same we need to rescore
656 $suggestions->rescore( $found );
665 * Simple prefix search for subpages.
666 * @param string $search
669 public function defaultPrefixSearch( $search ) {
670 if ( trim( $search ) === '' ) {
674 $search = $this->normalizeNamespaces( $search );
675 return $this->simplePrefixSearch( $search );
679 * Call out to simple search backend.
680 * Defaults to TitlePrefixSearch.
681 * @param string $search
684 protected function simplePrefixSearch( $search ) {
685 // Use default database prefix search
686 $backend = new TitlePrefixSearch
;
687 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
691 * Make a list of searchable namespaces and their canonical names.
692 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
695 public static function searchableNamespaces() {
696 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
700 * Extract default namespaces to search from the given user's
701 * settings, returning a list of index numbers.
702 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
706 public static function userNamespaces( $user ) {
707 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
711 * An array of namespaces indexes to be searched by default
712 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
715 public static function defaultNamespaces() {
716 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->defaultNamespaces();
720 * Get a list of namespace names useful for showing in tooltips
722 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
723 * @param array $namespaces
726 public static function namespacesAsText( $namespaces ) {
727 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
731 * Load up the appropriate search engine class for the currently
732 * active database backend, and return a configured instance.
733 * @deprecated since 1.27; Use SearchEngineFactory::create
734 * @param string $type Type of search backend, if not the default
735 * @return SearchEngine
737 public static function create( $type = null ) {
738 return MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
742 * Return the search engines we support. If only $wgSearchType
743 * is set, it'll be an array of just that one item.
744 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
747 public static function getSearchTypes() {
748 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->getSearchTypes();
752 * Get a list of supported profiles.
753 * Some search engine implementations may expose specific profiles to fine-tune
755 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
756 * The array returned by this function contains the following keys:
757 * - name: the profile name to use with setFeatureData
758 * - desc-message: the i18n description
759 * - default: set to true if this profile is the default
762 * @param string $profileType the type of profiles
763 * @param User|null $user the user requesting the list of profiles
764 * @return array|null the list of profiles or null if none available
766 public function getProfiles( $profileType, User
$user = null ) {
771 * Create a search field definition.
772 * Specific search engines should override this method to create search fields.
773 * @param string $name
774 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
775 * @return SearchIndexField
778 public function makeSearchFieldMapping( $name, $type ) {
779 return new NullIndexField();
783 * Get fields for search index
785 * @return SearchIndexField[] Index field definitions for all content handlers
787 public function getSearchIndexFields() {
788 $models = ContentHandler
::getContentModels();
790 $seenHandlers = new SplObjectStorage();
791 foreach ( $models as $model ) {
793 $handler = ContentHandler
::getForModelID( $model );
795 catch ( MWUnknownContentModelException
$e ) {
796 // If we can find no handler, ignore it
799 // Several models can have the same handler, so avoid processing it repeatedly
800 if ( $seenHandlers->contains( $handler ) ) {
801 // We already did this one
804 $seenHandlers->attach( $handler );
805 $handlerFields = $handler->getFieldsForSearchIndex( $this );
806 foreach ( $handlerFields as $fieldName => $fieldData ) {
807 if ( empty( $fields[$fieldName] ) ) {
808 $fields[$fieldName] = $fieldData;
810 // TODO: do we allow some clashes with the same type or reject all of them?
811 $mergeDef = $fields[$fieldName]->merge( $fieldData );
813 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
815 $fields[$fieldName] = $mergeDef;
819 // Hook to allow extensions to produce search mapping fields
820 Hooks
::run( 'SearchIndexFields', [ &$fields, $this ] );
825 * Augment search results with extra data.
827 * @param SearchResultSet $resultSet
829 public function augmentSearchResults( SearchResultSet
$resultSet ) {
832 Hooks
::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
834 if ( !$setAugmentors && !$rowAugmentors ) {
839 // Convert row augmentors to set augmentor
840 foreach ( $rowAugmentors as $name => $row ) {
841 if ( isset( $setAugmentors[$name] ) ) {
842 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
844 $setAugmentors[$name] = new PerRowAugmentor( $row );
847 foreach ( $setAugmentors as $name => $augmentor ) {
848 $data = $augmentor->augmentAll( $resultSet );
850 $resultSet->setAugmentedData( $name, $data );
857 * Dummy class to be used when non-supported Database engine is present.
858 * @todo FIXME: Dummy class should probably try something at least mildly useful,
859 * such as a LIKE search through titles.
862 class SearchEngineDummy
extends SearchEngine
{