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-only search query and return a result set.
77 * If title searches are not supported or disabled, return null.
80 * @param string $term Raw search term
81 * @return SearchResultSet|null
83 function searchTitle( $term ) {
89 * @param string $feature
92 public function supports( $feature ) {
96 case 'title-suffix-filter':
103 * Way to pass custom data for engines
105 * @param string $feature
108 public function setFeatureData( $feature, $data ) {
109 $this->features
[$feature] = $data;
113 * Way to retrieve custom data set by setFeatureData
114 * or by the engine itself.
116 * @param string $feature feature name
117 * @return mixed the feature value or null if unset
119 public function getFeatureData( $feature ) {
120 if ( isset ( $this->features
[$feature] ) ) {
121 return $this->features
[$feature];
127 * When overridden in derived class, performs database-specific conversions
128 * on text to be used for searching or updating search index.
129 * Default implementation does nothing (simply returns $string).
131 * @param string $string String to process
134 public function normalizeText( $string ) {
137 // Some languages such as Chinese require word segmentation
138 return $wgContLang->segmentByWord( $string );
142 * Transform search term in cases when parts of the query came as different
143 * GET params (when supported), e.g. for prefix queries:
144 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
145 * @param string $term
148 public function transformSearchTerm( $term ) {
153 * Get service class to finding near matches.
154 * @param Config $config Configuration to use for the matcher.
155 * @return SearchNearMatcher
157 public function getNearMatcher( Config
$config ) {
159 return new SearchNearMatcher( $config, $wgContLang );
163 * Get near matcher for default SearchEngine.
164 * @return SearchNearMatcher
166 protected static function defaultNearMatcher() {
167 $config = MediaWikiServices
::getInstance()->getMainConfig();
168 return MediaWikiServices
::getInstance()->newSearchEngine()->getNearMatcher( $config );
172 * If an exact title match can be found, or a very slightly close match,
173 * return the title. If no match, returns NULL.
174 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
175 * @param string $searchterm
178 public static function getNearMatch( $searchterm ) {
179 return static::defaultNearMatcher()->getNearMatch( $searchterm );
183 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
185 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
186 * @param string $searchterm
187 * @return SearchResultSet
189 public static function getNearMatchResultSet( $searchterm ) {
190 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
194 * Get chars legal for search.
195 * NOTE: usage as static is deprecated and preserved only as BC measure
198 public static function legalSearchChars() {
199 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
203 * Set the maximum number of results to return
204 * and how many to skip before returning the first.
209 function setLimitOffset( $limit, $offset = 0 ) {
210 $this->limit
= intval( $limit );
211 $this->offset
= intval( $offset );
215 * Set which namespaces the search should include.
216 * Give an array of namespace index numbers.
218 * @param int[]|null $namespaces
220 function setNamespaces( $namespaces ) {
222 // Filter namespaces to only keep valid ones
223 $validNs = $this->searchableNamespaces();
224 $namespaces = array_filter( $namespaces, function( $ns ) use( $validNs ) {
225 return $ns < 0 ||
isset( $validNs[$ns] );
230 $this->namespaces
= $namespaces;
234 * Set whether the searcher should try to build a suggestion. Note: some searchers
235 * don't support building a suggestion in the first place and others don't respect
238 * @param bool $showSuggestion Should the searcher try to build suggestions
240 function setShowSuggestion( $showSuggestion ) {
241 $this->showSuggestion
= $showSuggestion;
245 * Get the valid sort directions. All search engines support 'relevance' but others
246 * might support more. The default in all implementations should be 'relevance.'
249 * @return array(string) the valid sort directions for setSort
251 public function getValidSorts() {
252 return [ 'relevance' ];
256 * Set the sort direction of the search results. Must be one returned by
257 * SearchEngine::getValidSorts()
260 * @throws InvalidArgumentException
261 * @param string $sort sort direction for query result
263 public function setSort( $sort ) {
264 if ( !in_array( $sort, $this->getValidSorts() ) ) {
265 throw new InvalidArgumentException( "Invalid sort: $sort. " .
266 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
272 * Get the sort direction of the search results
277 public function getSort() {
282 * Parse some common prefixes: all (search everything)
283 * or namespace names and set the list of namespaces
284 * of this class accordingly.
286 * @param string $query
289 function replacePrefixes( $query ) {
290 $queryAndNs = self
::parseNamespacePrefixes( $query );
291 if ( $queryAndNs === false ) {
294 $this->namespaces
= $queryAndNs[1];
295 return $queryAndNs[0];
299 * Parse some common prefixes: all (search everything)
302 * @param string $query
303 * @return false|array false if no namespace was extracted, an array
304 * with the parsed query at index 0 and an array of namespaces at index
305 * 1 (or null for all namespaces).
307 public static function parseNamespacePrefixes( $query ) {
311 if ( strpos( $query, ':' ) === false ) { // nothing to do
314 $extractedNamespace = null;
316 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
317 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
318 $extractedNamespace = null;
319 $parsed = substr( $query, strlen( $allkeyword ) );
320 } elseif ( strpos( $query, ':' ) !== false ) {
321 // TODO: should we unify with PrefixSearch::extractNamespace ?
322 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
323 $index = $wgContLang->getNsIndex( $prefix );
324 if ( $index !== false ) {
325 $extractedNamespace = [ $index ];
326 $parsed = substr( $query, strlen( $prefix ) +
1 );
332 if ( trim( $parsed ) == '' ) {
333 $parsed = $query; // prefix was the whole query
336 return [ $parsed, $extractedNamespace ];
340 * Find snippet highlight settings for all users
341 * @return array Contextlines, contextchars
343 public static function userHighlightPrefs() {
344 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
345 $contextchars = 75; // same as above.... :P
346 return [ $contextlines, $contextchars ];
350 * Create or update the search index record for the given page.
351 * Title and text should be pre-processed.
355 * @param string $title
356 * @param string $text
358 function update( $id, $title, $text ) {
363 * Update a search index record's title only.
364 * Title should be pre-processed.
368 * @param string $title
370 function updateTitle( $id, $title ) {
375 * Delete an indexed page
376 * Title should be pre-processed.
379 * @param int $id Page id that was deleted
380 * @param string $title Title of page that was deleted
382 function delete( $id, $title ) {
387 * Get OpenSearch suggestion template
389 * @deprecated since 1.25
392 public static function getOpenSearchTemplate() {
393 wfDeprecated( __METHOD__
, '1.25' );
394 return ApiOpenSearch
::getOpenSearchTemplate( 'application/x-suggestions+json' );
398 * Get the raw text for updating the index from a content object
399 * Nicer search backends could possibly do something cooler than
400 * just returning raw text
402 * @todo This isn't ideal, we'd really like to have content-specific handling here
403 * @param Title $t Title we're indexing
404 * @param Content $c Content of the page to index
407 public function getTextFromContent( Title
$t, Content
$c = null ) {
408 return $c ?
$c->getTextForSearchIndex() : '';
412 * If an implementation of SearchEngine handles all of its own text processing
413 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
414 * rather silly handling, it should return true here instead.
418 public function textAlreadyUpdatedForIndex() {
423 * Makes search simple string if it was namespaced.
424 * Sets namespaces of the search to namespaces extracted from string.
425 * @param string $search
426 * @return string Simplified search string
428 protected function normalizeNamespaces( $search ) {
429 // Find a Title which is not an interwiki and is in NS_MAIN
430 $title = Title
::newFromText( $search );
431 $ns = $this->namespaces
;
432 if ( $title && !$title->isExternal() ) {
433 $ns = [ $title->getNamespace() ];
434 $search = $title->getText();
435 if ( $ns[0] == NS_MAIN
) {
436 $ns = $this->namespaces
; // no explicit prefix, use default namespaces
437 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
440 $title = Title
::newFromText( $search . 'Dummy' );
441 if ( $title && $title->getText() == 'Dummy'
442 && $title->getNamespace() != NS_MAIN
443 && !$title->isExternal() )
445 $ns = [ $title->getNamespace() ];
448 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
452 $ns = array_map( function( $space ) {
453 return $space == NS_MEDIA ? NS_FILE
: $space;
456 $this->setNamespaces( $ns );
461 * Perform a completion search.
462 * Does not resolve namespaces and does not check variants.
463 * Search engine implementations may want to override this function.
464 * @param string $search
465 * @return SearchSuggestionSet
467 protected function completionSearchBackend( $search ) {
470 $search = trim( $search );
472 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
473 !Hooks
::run( 'PrefixSearchBackend',
474 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
476 // False means hook worked.
477 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
479 return SearchSuggestionSet
::fromStrings( $results );
481 // Hook did not do the job, use default simple search
482 $results = $this->simplePrefixSearch( $search );
483 return SearchSuggestionSet
::fromTitles( $results );
488 * Perform a completion search.
489 * @param string $search
490 * @return SearchSuggestionSet
492 public function completionSearch( $search ) {
493 if ( trim( $search ) === '' ) {
494 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
496 $search = $this->normalizeNamespaces( $search );
497 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
501 * Perform a completion search with variants.
502 * @param string $search
503 * @return SearchSuggestionSet
505 public function completionSearchWithVariants( $search ) {
506 if ( trim( $search ) === '' ) {
507 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
509 $search = $this->normalizeNamespaces( $search );
511 $results = $this->completionSearchBackend( $search );
512 $fallbackLimit = $this->limit
- $results->getSize();
513 if ( $fallbackLimit > 0 ) {
516 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
517 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
519 foreach ( $fallbackSearches as $fbs ) {
520 $this->setLimitOffset( $fallbackLimit );
521 $fallbackSearchResult = $this->completionSearch( $fbs );
522 $results->appendAll( $fallbackSearchResult );
523 $fallbackLimit -= count( $fallbackSearchResult );
524 if ( $fallbackLimit <= 0 ) {
529 return $this->processCompletionResults( $search, $results );
533 * Extract titles from completion results
534 * @param SearchSuggestionSet $completionResults
537 public function extractTitles( SearchSuggestionSet
$completionResults ) {
538 return $completionResults->map( function( SearchSuggestion
$sugg ) {
539 return $sugg->getSuggestedTitle();
544 * Process completion search results.
545 * Resolves the titles and rescores.
546 * @param SearchSuggestionSet $suggestions
547 * @return SearchSuggestionSet
549 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
550 $search = trim( $search );
551 // preload the titles with LinkBatch
552 $titles = $suggestions->map( function( SearchSuggestion
$sugg ) {
553 return $sugg->getSuggestedTitle();
555 $lb = new LinkBatch( $titles );
556 $lb->setCaller( __METHOD__
);
559 $results = $suggestions->map( function( SearchSuggestion
$sugg ) {
560 return $sugg->getSuggestedTitle()->getPrefixedText();
563 if ( $this->offset
=== 0 ) {
564 // Rescore results with an exact title match
565 // NOTE: in some cases like cross-namespace redirects
566 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
567 // backends like Cirrus will return no results. We should still
568 // try an exact title match to workaround this limitation
569 $rescorer = new SearchExactMatchRescorer();
570 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
572 // No need to rescore if offset is not 0
573 // The exact match must have been returned at position 0
575 $rescoredResults = $results;
578 if ( count( $rescoredResults ) > 0 ) {
579 $found = array_search( $rescoredResults[0], $results );
580 if ( $found === false ) {
581 // If the first result is not in the previous array it
582 // means that we found a new exact match
583 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
584 $suggestions->prepend( $exactMatch );
585 $suggestions->shrink( $this->limit
);
587 // if the first result is not the same we need to rescore
589 $suggestions->rescore( $found );
598 * Simple prefix search for subpages.
599 * @param string $search
602 public function defaultPrefixSearch( $search ) {
603 if ( trim( $search ) === '' ) {
607 $search = $this->normalizeNamespaces( $search );
608 return $this->simplePrefixSearch( $search );
612 * Call out to simple search backend.
613 * Defaults to TitlePrefixSearch.
614 * @param string $search
617 protected function simplePrefixSearch( $search ) {
618 // Use default database prefix search
619 $backend = new TitlePrefixSearch
;
620 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
624 * Make a list of searchable namespaces and their canonical names.
625 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
628 public static function searchableNamespaces() {
629 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
633 * Extract default namespaces to search from the given user's
634 * settings, returning a list of index numbers.
635 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
639 public static function userNamespaces( $user ) {
640 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
644 * An array of namespaces indexes to be searched by default
645 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
648 public static function defaultNamespaces() {
649 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->defaultNamespaces();
653 * Get a list of namespace names useful for showing in tooltips
655 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
656 * @param array $namespaces
659 public static function namespacesAsText( $namespaces ) {
660 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
664 * Load up the appropriate search engine class for the currently
665 * active database backend, and return a configured instance.
666 * @deprecated since 1.27; Use SearchEngineFactory::create
667 * @param string $type Type of search backend, if not the default
668 * @return SearchEngine
670 public static function create( $type = null ) {
671 return MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
675 * Return the search engines we support. If only $wgSearchType
676 * is set, it'll be an array of just that one item.
677 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
680 public static function getSearchTypes() {
681 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->getSearchTypes();
685 * Get a list of supported profiles.
686 * Some search engine implementations may expose specific profiles to fine-tune
688 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
689 * The array returned by this function contains the following keys:
690 * - name: the profile name to use with setFeatureData
691 * - desc-message: the i18n description
692 * - default: set to true if this profile is the default
695 * @param string $profileType the type of profiles
696 * @param User|null $user the user requesting the list of profiles
697 * @return array|null the list of profiles or null if none available
699 public function getProfiles( $profileType, User
$user = null ) {
704 * Create a search field definition.
705 * Specific search engines should override this method to create search fields.
706 * @param string $name
707 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
708 * @return SearchIndexField
711 public function makeSearchFieldMapping( $name, $type ) {
712 return new NullIndexField();
716 * Get fields for search index
718 * @return SearchIndexField[] Index field definitions for all content handlers
720 public function getSearchIndexFields() {
721 $models = ContentHandler
::getContentModels();
723 $seenHandlers = new SplObjectStorage();
724 foreach ( $models as $model ) {
726 $handler = ContentHandler
::getForModelID( $model );
728 catch ( MWUnknownContentModelException
$e ) {
729 // If we can find no handler, ignore it
732 // Several models can have the same handler, so avoid processing it repeatedly
733 if ( $seenHandlers->contains( $handler ) ) {
734 // We already did this one
737 $seenHandlers->attach( $handler );
738 $handlerFields = $handler->getFieldsForSearchIndex( $this );
739 foreach ( $handlerFields as $fieldName => $fieldData ) {
740 if ( empty( $fields[$fieldName] ) ) {
741 $fields[$fieldName] = $fieldData;
743 // TODO: do we allow some clashes with the same type or reject all of them?
744 $mergeDef = $fields[$fieldName]->merge( $fieldData );
746 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
748 $fields[$fieldName] = $mergeDef;
752 // Hook to allow extensions to produce search mapping fields
753 Hooks
::run( 'SearchIndexFields', [ &$fields, $this ] );
758 * Augment search results with extra data.
760 * @param SearchResultSet $resultSet
762 public function augmentSearchResults( SearchResultSet
$resultSet ) {
765 Hooks
::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
767 if ( !$setAugmentors && !$rowAugmentors ) {
772 // Convert row augmentors to set augmentor
773 foreach ( $rowAugmentors as $name => $row ) {
774 if ( isset( $setAugmentors[$name] ) ) {
775 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
777 $setAugmentors[$name] = new PerRowAugmentor( $row );
780 foreach ( $setAugmentors as $name => $augmentor ) {
781 $data = $augmentor->augmentAll( $resultSet );
783 $resultSet->setAugmentedData( $name, $data );
790 * Dummy class to be used when non-supported Database engine is present.
791 * @todo FIXME: Dummy class should probably try something at least mildly useful,
792 * such as a LIKE search through titles.
795 class SearchEngineDummy
extends SearchEngine
{