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 * When overridden in derived class, performs database-specific conversions
114 * on text to be used for searching or updating search index.
115 * Default implementation does nothing (simply returns $string).
117 * @param string $string String to process
120 public function normalizeText( $string ) {
123 // Some languages such as Chinese require word segmentation
124 return $wgContLang->segmentByWord( $string );
128 * Transform search term in cases when parts of the query came as different
129 * GET params (when supported), e.g. for prefix queries:
130 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
131 * @param string $term
134 public function transformSearchTerm( $term ) {
139 * Get service class to finding near matches.
140 * @param Config $config Configuration to use for the matcher.
141 * @return SearchNearMatcher
143 public function getNearMatcher( Config
$config ) {
145 return new SearchNearMatcher( $config, $wgContLang );
149 * Get near matcher for default SearchEngine.
150 * @return SearchNearMatcher
152 protected static function defaultNearMatcher() {
153 $config = MediaWikiServices
::getInstance()->getMainConfig();
154 return MediaWikiServices
::getInstance()->newSearchEngine()->getNearMatcher( $config );
158 * If an exact title match can be found, or a very slightly close match,
159 * return the title. If no match, returns NULL.
160 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
161 * @param string $searchterm
164 public static function getNearMatch( $searchterm ) {
165 return static::defaultNearMatcher()->getNearMatch( $searchterm );
169 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
171 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
172 * @param string $searchterm
173 * @return SearchResultSet
175 public static function getNearMatchResultSet( $searchterm ) {
176 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
180 * Get chars legal for search.
181 * NOTE: usage as static is deprecated and preserved only as BC measure
184 public static function legalSearchChars() {
185 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
189 * Set the maximum number of results to return
190 * and how many to skip before returning the first.
195 function setLimitOffset( $limit, $offset = 0 ) {
196 $this->limit
= intval( $limit );
197 $this->offset
= intval( $offset );
201 * Set which namespaces the search should include.
202 * Give an array of namespace index numbers.
204 * @param int[]|null $namespaces
206 function setNamespaces( $namespaces ) {
208 // Filter namespaces to only keep valid ones
209 $validNs = $this->searchableNamespaces();
210 $namespaces = array_filter( $namespaces, function( $ns ) use( $validNs ) {
211 return $ns < 0 ||
isset( $validNs[$ns] );
216 $this->namespaces
= $namespaces;
220 * Set whether the searcher should try to build a suggestion. Note: some searchers
221 * don't support building a suggestion in the first place and others don't respect
224 * @param bool $showSuggestion Should the searcher try to build suggestions
226 function setShowSuggestion( $showSuggestion ) {
227 $this->showSuggestion
= $showSuggestion;
231 * Get the valid sort directions. All search engines support 'relevance' but others
232 * might support more. The default in all implementations should be 'relevance.'
235 * @return array(string) the valid sort directions for setSort
237 public function getValidSorts() {
238 return [ 'relevance' ];
242 * Set the sort direction of the search results. Must be one returned by
243 * SearchEngine::getValidSorts()
246 * @throws InvalidArgumentException
247 * @param string $sort sort direction for query result
249 public function setSort( $sort ) {
250 if ( !in_array( $sort, $this->getValidSorts() ) ) {
251 throw new InvalidArgumentException( "Invalid sort: $sort. " .
252 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
258 * Get the sort direction of the search results
263 public function getSort() {
268 * Parse some common prefixes: all (search everything)
269 * or namespace names and set the list of namespaces
270 * of this class accordingly.
272 * @param string $query
275 function replacePrefixes( $query ) {
276 $queryAndNs = self
::parseNamespacePrefixes( $query );
277 if ( $queryAndNs === false ) {
280 $this->namespaces
= $queryAndNs[1];
281 return $queryAndNs[0];
285 * Parse some common prefixes: all (search everything)
288 * @param string $query
289 * @return false|array false if no namespace was extracted, an array
290 * with the parsed query at index 0 and an array of namespaces at index
291 * 1 (or null for all namespaces).
293 public static function parseNamespacePrefixes( $query ) {
297 if ( strpos( $query, ':' ) === false ) { // nothing to do
300 $extractedNamespace = null;
302 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
303 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
304 $extractedNamespace = null;
305 $parsed = substr( $query, strlen( $allkeyword ) );
306 } elseif ( strpos( $query, ':' ) !== false ) {
307 // TODO: should we unify with PrefixSearch::extractNamespace ?
308 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
309 $index = $wgContLang->getNsIndex( $prefix );
310 if ( $index !== false ) {
311 $extractedNamespace = [ $index ];
312 $parsed = substr( $query, strlen( $prefix ) +
1 );
318 if ( trim( $parsed ) == '' ) {
319 $parsed = $query; // prefix was the whole query
322 return [ $parsed, $extractedNamespace ];
326 * Find snippet highlight settings for all users
327 * @return array Contextlines, contextchars
329 public static function userHighlightPrefs() {
330 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
331 $contextchars = 75; // same as above.... :P
332 return [ $contextlines, $contextchars ];
336 * Create or update the search index record for the given page.
337 * Title and text should be pre-processed.
341 * @param string $title
342 * @param string $text
344 function update( $id, $title, $text ) {
349 * Update a search index record's title only.
350 * Title should be pre-processed.
354 * @param string $title
356 function updateTitle( $id, $title ) {
361 * Delete an indexed page
362 * Title should be pre-processed.
365 * @param int $id Page id that was deleted
366 * @param string $title Title of page that was deleted
368 function delete( $id, $title ) {
373 * Get OpenSearch suggestion template
375 * @deprecated since 1.25
378 public static function getOpenSearchTemplate() {
379 wfDeprecated( __METHOD__
, '1.25' );
380 return ApiOpenSearch
::getOpenSearchTemplate( 'application/x-suggestions+json' );
384 * Get the raw text for updating the index from a content object
385 * Nicer search backends could possibly do something cooler than
386 * just returning raw text
388 * @todo This isn't ideal, we'd really like to have content-specific handling here
389 * @param Title $t Title we're indexing
390 * @param Content $c Content of the page to index
393 public function getTextFromContent( Title
$t, Content
$c = null ) {
394 return $c ?
$c->getTextForSearchIndex() : '';
398 * If an implementation of SearchEngine handles all of its own text processing
399 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
400 * rather silly handling, it should return true here instead.
404 public function textAlreadyUpdatedForIndex() {
409 * Makes search simple string if it was namespaced.
410 * Sets namespaces of the search to namespaces extracted from string.
411 * @param string $search
412 * @return string Simplified search string
414 protected function normalizeNamespaces( $search ) {
415 // Find a Title which is not an interwiki and is in NS_MAIN
416 $title = Title
::newFromText( $search );
417 $ns = $this->namespaces
;
418 if ( $title && !$title->isExternal() ) {
419 $ns = [ $title->getNamespace() ];
420 $search = $title->getText();
421 if ( $ns[0] == NS_MAIN
) {
422 $ns = $this->namespaces
; // no explicit prefix, use default namespaces
423 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
426 $title = Title
::newFromText( $search . 'Dummy' );
427 if ( $title && $title->getText() == 'Dummy'
428 && $title->getNamespace() != NS_MAIN
429 && !$title->isExternal() )
431 $ns = [ $title->getNamespace() ];
434 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
438 $ns = array_map( function( $space ) {
439 return $space == NS_MEDIA ? NS_FILE
: $space;
442 $this->setNamespaces( $ns );
447 * Perform a completion search.
448 * Does not resolve namespaces and does not check variants.
449 * Search engine implementations may want to override this function.
450 * @param string $search
451 * @return SearchSuggestionSet
453 protected function completionSearchBackend( $search ) {
456 $search = trim( $search );
458 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
459 !Hooks
::run( 'PrefixSearchBackend',
460 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
462 // False means hook worked.
463 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
465 return SearchSuggestionSet
::fromStrings( $results );
467 // Hook did not do the job, use default simple search
468 $results = $this->simplePrefixSearch( $search );
469 return SearchSuggestionSet
::fromTitles( $results );
474 * Perform a completion search.
475 * @param string $search
476 * @return SearchSuggestionSet
478 public function completionSearch( $search ) {
479 if ( trim( $search ) === '' ) {
480 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
482 $search = $this->normalizeNamespaces( $search );
483 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
487 * Perform a completion search with variants.
488 * @param string $search
489 * @return SearchSuggestionSet
491 public function completionSearchWithVariants( $search ) {
492 if ( trim( $search ) === '' ) {
493 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
495 $search = $this->normalizeNamespaces( $search );
497 $results = $this->completionSearchBackend( $search );
498 $fallbackLimit = $this->limit
- $results->getSize();
499 if ( $fallbackLimit > 0 ) {
502 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
503 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
505 foreach ( $fallbackSearches as $fbs ) {
506 $this->setLimitOffset( $fallbackLimit );
507 $fallbackSearchResult = $this->completionSearch( $fbs );
508 $results->appendAll( $fallbackSearchResult );
509 $fallbackLimit -= count( $fallbackSearchResult );
510 if ( $fallbackLimit <= 0 ) {
515 return $this->processCompletionResults( $search, $results );
519 * Extract titles from completion results
520 * @param SearchSuggestionSet $completionResults
523 public function extractTitles( SearchSuggestionSet
$completionResults ) {
524 return $completionResults->map( function( SearchSuggestion
$sugg ) {
525 return $sugg->getSuggestedTitle();
530 * Process completion search results.
531 * Resolves the titles and rescores.
532 * @param SearchSuggestionSet $suggestions
533 * @return SearchSuggestionSet
535 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
536 $search = trim( $search );
537 // preload the titles with LinkBatch
538 $titles = $suggestions->map( function( SearchSuggestion
$sugg ) {
539 return $sugg->getSuggestedTitle();
541 $lb = new LinkBatch( $titles );
542 $lb->setCaller( __METHOD__
);
545 $results = $suggestions->map( function( SearchSuggestion
$sugg ) {
546 return $sugg->getSuggestedTitle()->getPrefixedText();
549 if ( $this->offset
=== 0 ) {
550 // Rescore results with an exact title match
551 // NOTE: in some cases like cross-namespace redirects
552 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
553 // backends like Cirrus will return no results. We should still
554 // try an exact title match to workaround this limitation
555 $rescorer = new SearchExactMatchRescorer();
556 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
558 // No need to rescore if offset is not 0
559 // The exact match must have been returned at position 0
561 $rescoredResults = $results;
564 if ( count( $rescoredResults ) > 0 ) {
565 $found = array_search( $rescoredResults[0], $results );
566 if ( $found === false ) {
567 // If the first result is not in the previous array it
568 // means that we found a new exact match
569 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
570 $suggestions->prepend( $exactMatch );
571 $suggestions->shrink( $this->limit
);
573 // if the first result is not the same we need to rescore
575 $suggestions->rescore( $found );
584 * Simple prefix search for subpages.
585 * @param string $search
588 public function defaultPrefixSearch( $search ) {
589 if ( trim( $search ) === '' ) {
593 $search = $this->normalizeNamespaces( $search );
594 return $this->simplePrefixSearch( $search );
598 * Call out to simple search backend.
599 * Defaults to TitlePrefixSearch.
600 * @param string $search
603 protected function simplePrefixSearch( $search ) {
604 // Use default database prefix search
605 $backend = new TitlePrefixSearch
;
606 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
610 * Make a list of searchable namespaces and their canonical names.
611 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
614 public static function searchableNamespaces() {
615 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
619 * Extract default namespaces to search from the given user's
620 * settings, returning a list of index numbers.
621 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
625 public static function userNamespaces( $user ) {
626 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
630 * An array of namespaces indexes to be searched by default
631 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
634 public static function defaultNamespaces() {
635 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->defaultNamespaces();
639 * Get a list of namespace names useful for showing in tooltips
641 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
642 * @param array $namespaces
645 public static function namespacesAsText( $namespaces ) {
646 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
650 * Load up the appropriate search engine class for the currently
651 * active database backend, and return a configured instance.
652 * @deprecated since 1.27; Use SearchEngineFactory::create
653 * @param string $type Type of search backend, if not the default
654 * @return SearchEngine
656 public static function create( $type = null ) {
657 return MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
661 * Return the search engines we support. If only $wgSearchType
662 * is set, it'll be an array of just that one item.
663 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
666 public static function getSearchTypes() {
667 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->getSearchTypes();
671 * Get a list of supported profiles.
672 * Some search engine implementations may expose specific profiles to fine-tune
674 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
675 * The array returned by this function contains the following keys:
676 * - name: the profile name to use with setFeatureData
677 * - desc-message: the i18n description
678 * - default: set to true if this profile is the default
681 * @param string $profileType the type of profiles
682 * @param User|null $user the user requesting the list of profiles
683 * @return array|null the list of profiles or null if none available
685 public function getProfiles( $profileType, User
$user = null ) {
690 * Create a search field definition.
691 * Specific search engines should override this method to create search fields.
692 * @param string $name
693 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
694 * @return SearchIndexField
697 public function makeSearchFieldMapping( $name, $type ) {
698 return new NullIndexField();
702 * Get fields for search index
704 * @return SearchIndexField[] Index field definitions for all content handlers
706 public function getSearchIndexFields() {
707 $models = ContentHandler
::getContentModels();
709 foreach ( $models as $model ) {
710 $handler = ContentHandler
::getForModelID( $model );
711 $handlerFields = $handler->getFieldsForSearchIndex( $this );
712 foreach ( $handlerFields as $fieldName => $fieldData ) {
713 if ( empty( $fields[$fieldName] ) ) {
714 $fields[$fieldName] = $fieldData;
716 // TODO: do we allow some clashes with the same type or reject all of them?
717 $mergeDef = $fields[$fieldName]->merge( $fieldData );
719 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
721 $fields[$fieldName] = $mergeDef;
725 // Hook to allow extensions to produce search mapping fields
726 Hooks
::run( 'SearchIndexFields', [ &$fields, $this ] );
731 * Augment search results with extra data.
733 * @param SearchResultSet $resultSet
735 public function augmentSearchResults( SearchResultSet
$resultSet ) {
738 Hooks
::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
740 if ( !$setAugmentors && !$rowAugmentors ) {
745 // Convert row augmentors to set augmentor
746 foreach ( $rowAugmentors as $name => $row ) {
747 if ( isset( $setAugmentors[$name] ) ) {
748 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
750 $setAugmentors[$name] = new PerRowAugmentor( $row );
753 foreach ( $setAugmentors as $name => $augmentor ) {
754 $data = $augmentor->augmentAll( $resultSet );
756 $resultSet->setAugmentedData( $name, $data );
763 * Dummy class to be used when non-supported Database engine is present.
764 * @todo FIXME: Dummy class should probably try something at least mildly useful,
765 * such as a LIKE search through titles.
768 class SearchEngineDummy
extends SearchEngine
{