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.
74 * @param string $term Raw search term
75 * @return SearchResultSet|Status|null
77 function searchText( $term ) {
82 * Perform a title search in the article archive.
83 * NOTE: these results still should be filtered by
84 * matching against PageArchive, permissions checks etc
85 * The results returned by this methods are only sugegstions and
86 * may not end up being shown to the user.
88 * @param string $term Raw search term
89 * @return Status<Title[]>
92 function searchArchiveTitle( $term ) {
93 return Status
::newGood( [] );
97 * Perform a title-only search query and return a result set.
98 * If title searches are not supported or disabled, return null.
101 * @param string $term Raw search term
102 * @return SearchResultSet|null
104 function searchTitle( $term ) {
110 * @param string $feature
113 public function supports( $feature ) {
114 switch ( $feature ) {
115 case 'search-update':
117 case 'title-suffix-filter':
124 * Way to pass custom data for engines
126 * @param string $feature
129 public function setFeatureData( $feature, $data ) {
130 $this->features
[$feature] = $data;
134 * Way to retrieve custom data set by setFeatureData
135 * or by the engine itself.
137 * @param string $feature feature name
138 * @return mixed the feature value or null if unset
140 public function getFeatureData( $feature ) {
141 if ( isset ( $this->features
[$feature] ) ) {
142 return $this->features
[$feature];
148 * When overridden in derived class, performs database-specific conversions
149 * on text to be used for searching or updating search index.
150 * Default implementation does nothing (simply returns $string).
152 * @param string $string String to process
155 public function normalizeText( $string ) {
158 // Some languages such as Chinese require word segmentation
159 return $wgContLang->segmentByWord( $string );
163 * Transform search term in cases when parts of the query came as different
164 * GET params (when supported), e.g. for prefix queries:
165 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
166 * @param string $term
169 public function transformSearchTerm( $term ) {
174 * Get service class to finding near matches.
175 * @param Config $config Configuration to use for the matcher.
176 * @return SearchNearMatcher
178 public function getNearMatcher( Config
$config ) {
180 return new SearchNearMatcher( $config, $wgContLang );
184 * Get near matcher for default SearchEngine.
185 * @return SearchNearMatcher
187 protected static function defaultNearMatcher() {
188 $config = MediaWikiServices
::getInstance()->getMainConfig();
189 return MediaWikiServices
::getInstance()->newSearchEngine()->getNearMatcher( $config );
193 * If an exact title match can be found, or a very slightly close match,
194 * return the title. If no match, returns NULL.
195 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
196 * @param string $searchterm
199 public static function getNearMatch( $searchterm ) {
200 return static::defaultNearMatcher()->getNearMatch( $searchterm );
204 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
206 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
207 * @param string $searchterm
208 * @return SearchResultSet
210 public static function getNearMatchResultSet( $searchterm ) {
211 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
215 * Get chars legal for search
216 * NOTE: usage as static is deprecated and preserved only as BC measure
217 * @param int $type type of search chars (see self::CHARS_ALL
218 * and self::CHARS_NO_SYNTAX). Defaults to CHARS_ALL
221 public static function legalSearchChars( $type = self
::CHARS_ALL
) {
222 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
226 * Set the maximum number of results to return
227 * and how many to skip before returning the first.
232 function setLimitOffset( $limit, $offset = 0 ) {
233 $this->limit
= intval( $limit );
234 $this->offset
= intval( $offset );
238 * Set which namespaces the search should include.
239 * Give an array of namespace index numbers.
241 * @param int[]|null $namespaces
243 function setNamespaces( $namespaces ) {
245 // Filter namespaces to only keep valid ones
246 $validNs = $this->searchableNamespaces();
247 $namespaces = array_filter( $namespaces, function ( $ns ) use( $validNs ) {
248 return $ns < 0 ||
isset( $validNs[$ns] );
253 $this->namespaces
= $namespaces;
257 * Set whether the searcher should try to build a suggestion. Note: some searchers
258 * don't support building a suggestion in the first place and others don't respect
261 * @param bool $showSuggestion Should the searcher try to build suggestions
263 function setShowSuggestion( $showSuggestion ) {
264 $this->showSuggestion
= $showSuggestion;
268 * Get the valid sort directions. All search engines support 'relevance' but others
269 * might support more. The default in all implementations should be 'relevance.'
272 * @return array(string) the valid sort directions for setSort
274 public function getValidSorts() {
275 return [ 'relevance' ];
279 * Set the sort direction of the search results. Must be one returned by
280 * SearchEngine::getValidSorts()
283 * @throws InvalidArgumentException
284 * @param string $sort sort direction for query result
286 public function setSort( $sort ) {
287 if ( !in_array( $sort, $this->getValidSorts() ) ) {
288 throw new InvalidArgumentException( "Invalid sort: $sort. " .
289 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
295 * Get the sort direction of the search results
300 public function getSort() {
305 * Parse some common prefixes: all (search everything)
306 * or namespace names and set the list of namespaces
307 * of this class accordingly.
309 * @param string $query
312 function replacePrefixes( $query ) {
313 $queryAndNs = self
::parseNamespacePrefixes( $query );
314 if ( $queryAndNs === false ) {
317 $this->namespaces
= $queryAndNs[1];
318 return $queryAndNs[0];
322 * Parse some common prefixes: all (search everything)
325 * @param string $query
326 * @return false|array false if no namespace was extracted, an array
327 * with the parsed query at index 0 and an array of namespaces at index
328 * 1 (or null for all namespaces).
330 public static function parseNamespacePrefixes( $query ) {
334 if ( strpos( $query, ':' ) === false ) { // nothing to do
337 $extractedNamespace = null;
339 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
340 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
341 $extractedNamespace = null;
342 $parsed = substr( $query, strlen( $allkeyword ) );
343 } elseif ( strpos( $query, ':' ) !== false ) {
344 // TODO: should we unify with PrefixSearch::extractNamespace ?
345 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
346 $index = $wgContLang->getNsIndex( $prefix );
347 if ( $index !== false ) {
348 $extractedNamespace = [ $index ];
349 $parsed = substr( $query, strlen( $prefix ) +
1 );
355 if ( trim( $parsed ) == '' ) {
356 $parsed = $query; // prefix was the whole query
359 return [ $parsed, $extractedNamespace ];
363 * Find snippet highlight settings for all users
364 * @return array Contextlines, contextchars
366 public static function userHighlightPrefs() {
367 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
368 $contextchars = 75; // same as above.... :P
369 return [ $contextlines, $contextchars ];
373 * Create or update the search index record for the given page.
374 * Title and text should be pre-processed.
378 * @param string $title
379 * @param string $text
381 function update( $id, $title, $text ) {
386 * Update a search index record's title only.
387 * Title should be pre-processed.
391 * @param string $title
393 function updateTitle( $id, $title ) {
398 * Delete an indexed page
399 * Title should be pre-processed.
402 * @param int $id Page id that was deleted
403 * @param string $title Title of page that was deleted
405 function delete( $id, $title ) {
410 * Get OpenSearch suggestion template
412 * @deprecated since 1.25
415 public static function getOpenSearchTemplate() {
416 wfDeprecated( __METHOD__
, '1.25' );
417 return ApiOpenSearch
::getOpenSearchTemplate( 'application/x-suggestions+json' );
421 * Get the raw text for updating the index from a content object
422 * Nicer search backends could possibly do something cooler than
423 * just returning raw text
425 * @todo This isn't ideal, we'd really like to have content-specific handling here
426 * @param Title $t Title we're indexing
427 * @param Content $c Content of the page to index
430 public function getTextFromContent( Title
$t, Content
$c = null ) {
431 return $c ?
$c->getTextForSearchIndex() : '';
435 * If an implementation of SearchEngine handles all of its own text processing
436 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
437 * rather silly handling, it should return true here instead.
441 public function textAlreadyUpdatedForIndex() {
446 * Makes search simple string if it was namespaced.
447 * Sets namespaces of the search to namespaces extracted from string.
448 * @param string $search
449 * @return string Simplified search string
451 protected function normalizeNamespaces( $search ) {
452 // Find a Title which is not an interwiki and is in NS_MAIN
453 $title = Title
::newFromText( $search );
454 $ns = $this->namespaces
;
455 if ( $title && !$title->isExternal() ) {
456 $ns = [ $title->getNamespace() ];
457 $search = $title->getText();
458 if ( $ns[0] == NS_MAIN
) {
459 $ns = $this->namespaces
; // no explicit prefix, use default namespaces
460 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
463 $title = Title
::newFromText( $search . 'Dummy' );
464 if ( $title && $title->getText() == 'Dummy'
465 && $title->getNamespace() != NS_MAIN
466 && !$title->isExternal()
468 $ns = [ $title->getNamespace() ];
471 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
475 $ns = array_map( function ( $space ) {
476 return $space == NS_MEDIA ? NS_FILE
: $space;
479 $this->setNamespaces( $ns );
484 * Perform a completion search.
485 * Does not resolve namespaces and does not check variants.
486 * Search engine implementations may want to override this function.
487 * @param string $search
488 * @return SearchSuggestionSet
490 protected function completionSearchBackend( $search ) {
493 $search = trim( $search );
495 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
496 !Hooks
::run( 'PrefixSearchBackend',
497 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
499 // False means hook worked.
500 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
502 return SearchSuggestionSet
::fromStrings( $results );
504 // Hook did not do the job, use default simple search
505 $results = $this->simplePrefixSearch( $search );
506 return SearchSuggestionSet
::fromTitles( $results );
511 * Perform a completion search.
512 * @param string $search
513 * @return SearchSuggestionSet
515 public function completionSearch( $search ) {
516 if ( trim( $search ) === '' ) {
517 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
519 $search = $this->normalizeNamespaces( $search );
520 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
524 * Perform a completion search with variants.
525 * @param string $search
526 * @return SearchSuggestionSet
528 public function completionSearchWithVariants( $search ) {
529 if ( trim( $search ) === '' ) {
530 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
532 $search = $this->normalizeNamespaces( $search );
534 $results = $this->completionSearchBackend( $search );
535 $fallbackLimit = $this->limit
- $results->getSize();
536 if ( $fallbackLimit > 0 ) {
539 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
540 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
542 foreach ( $fallbackSearches as $fbs ) {
543 $this->setLimitOffset( $fallbackLimit );
544 $fallbackSearchResult = $this->completionSearch( $fbs );
545 $results->appendAll( $fallbackSearchResult );
546 $fallbackLimit -= count( $fallbackSearchResult );
547 if ( $fallbackLimit <= 0 ) {
552 return $this->processCompletionResults( $search, $results );
556 * Extract titles from completion results
557 * @param SearchSuggestionSet $completionResults
560 public function extractTitles( SearchSuggestionSet
$completionResults ) {
561 return $completionResults->map( function ( SearchSuggestion
$sugg ) {
562 return $sugg->getSuggestedTitle();
567 * Process completion search results.
568 * Resolves the titles and rescores.
569 * @param SearchSuggestionSet $suggestions
570 * @return SearchSuggestionSet
572 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
573 $search = trim( $search );
574 // preload the titles with LinkBatch
575 $titles = $suggestions->map( function ( SearchSuggestion
$sugg ) {
576 return $sugg->getSuggestedTitle();
578 $lb = new LinkBatch( $titles );
579 $lb->setCaller( __METHOD__
);
582 $results = $suggestions->map( function ( SearchSuggestion
$sugg ) {
583 return $sugg->getSuggestedTitle()->getPrefixedText();
586 if ( $this->offset
=== 0 ) {
587 // Rescore results with an exact title match
588 // NOTE: in some cases like cross-namespace redirects
589 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
590 // backends like Cirrus will return no results. We should still
591 // try an exact title match to workaround this limitation
592 $rescorer = new SearchExactMatchRescorer();
593 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
595 // No need to rescore if offset is not 0
596 // The exact match must have been returned at position 0
598 $rescoredResults = $results;
601 if ( count( $rescoredResults ) > 0 ) {
602 $found = array_search( $rescoredResults[0], $results );
603 if ( $found === false ) {
604 // If the first result is not in the previous array it
605 // means that we found a new exact match
606 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
607 $suggestions->prepend( $exactMatch );
608 $suggestions->shrink( $this->limit
);
610 // if the first result is not the same we need to rescore
612 $suggestions->rescore( $found );
621 * Simple prefix search for subpages.
622 * @param string $search
625 public function defaultPrefixSearch( $search ) {
626 if ( trim( $search ) === '' ) {
630 $search = $this->normalizeNamespaces( $search );
631 return $this->simplePrefixSearch( $search );
635 * Call out to simple search backend.
636 * Defaults to TitlePrefixSearch.
637 * @param string $search
640 protected function simplePrefixSearch( $search ) {
641 // Use default database prefix search
642 $backend = new TitlePrefixSearch
;
643 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
647 * Make a list of searchable namespaces and their canonical names.
648 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
651 public static function searchableNamespaces() {
652 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
656 * Extract default namespaces to search from the given user's
657 * settings, returning a list of index numbers.
658 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
662 public static function userNamespaces( $user ) {
663 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
667 * An array of namespaces indexes to be searched by default
668 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
671 public static function defaultNamespaces() {
672 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->defaultNamespaces();
676 * Get a list of namespace names useful for showing in tooltips
678 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
679 * @param array $namespaces
682 public static function namespacesAsText( $namespaces ) {
683 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
687 * Load up the appropriate search engine class for the currently
688 * active database backend, and return a configured instance.
689 * @deprecated since 1.27; Use SearchEngineFactory::create
690 * @param string $type Type of search backend, if not the default
691 * @return SearchEngine
693 public static function create( $type = null ) {
694 return MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
698 * Return the search engines we support. If only $wgSearchType
699 * is set, it'll be an array of just that one item.
700 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
703 public static function getSearchTypes() {
704 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->getSearchTypes();
708 * Get a list of supported profiles.
709 * Some search engine implementations may expose specific profiles to fine-tune
711 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
712 * The array returned by this function contains the following keys:
713 * - name: the profile name to use with setFeatureData
714 * - desc-message: the i18n description
715 * - default: set to true if this profile is the default
718 * @param string $profileType the type of profiles
719 * @param User|null $user the user requesting the list of profiles
720 * @return array|null the list of profiles or null if none available
722 public function getProfiles( $profileType, User
$user = null ) {
727 * Create a search field definition.
728 * Specific search engines should override this method to create search fields.
729 * @param string $name
730 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
731 * @return SearchIndexField
734 public function makeSearchFieldMapping( $name, $type ) {
735 return new NullIndexField();
739 * Get fields for search index
741 * @return SearchIndexField[] Index field definitions for all content handlers
743 public function getSearchIndexFields() {
744 $models = ContentHandler
::getContentModels();
746 $seenHandlers = new SplObjectStorage();
747 foreach ( $models as $model ) {
749 $handler = ContentHandler
::getForModelID( $model );
751 catch ( MWUnknownContentModelException
$e ) {
752 // If we can find no handler, ignore it
755 // Several models can have the same handler, so avoid processing it repeatedly
756 if ( $seenHandlers->contains( $handler ) ) {
757 // We already did this one
760 $seenHandlers->attach( $handler );
761 $handlerFields = $handler->getFieldsForSearchIndex( $this );
762 foreach ( $handlerFields as $fieldName => $fieldData ) {
763 if ( empty( $fields[$fieldName] ) ) {
764 $fields[$fieldName] = $fieldData;
766 // TODO: do we allow some clashes with the same type or reject all of them?
767 $mergeDef = $fields[$fieldName]->merge( $fieldData );
769 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
771 $fields[$fieldName] = $mergeDef;
775 // Hook to allow extensions to produce search mapping fields
776 Hooks
::run( 'SearchIndexFields', [ &$fields, $this ] );
781 * Augment search results with extra data.
783 * @param SearchResultSet $resultSet
785 public function augmentSearchResults( SearchResultSet
$resultSet ) {
788 Hooks
::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
790 if ( !$setAugmentors && !$rowAugmentors ) {
795 // Convert row augmentors to set augmentor
796 foreach ( $rowAugmentors as $name => $row ) {
797 if ( isset( $setAugmentors[$name] ) ) {
798 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
800 $setAugmentors[$name] = new PerRowAugmentor( $row );
803 foreach ( $setAugmentors as $name => $augmentor ) {
804 $data = $augmentor->augmentAll( $resultSet );
806 $resultSet->setAugmentedData( $name, $data );
813 * Dummy class to be used when non-supported Database engine is present.
814 * @todo FIXME: Dummy class should probably try something at least mildly useful,
815 * such as a LIKE search through titles.
818 class SearchEngineDummy
extends SearchEngine
{