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 = [];
58 * Perform a full text search query and return a result set.
59 * If full text searches are not supported or disabled, return null.
62 * @param string $term Raw search term
63 * @return SearchResultSet|Status|null
65 function searchText( $term ) {
70 * Perform a title-only search query and return a result set.
71 * If title searches are not supported or disabled, return null.
74 * @param string $term Raw search term
75 * @return SearchResultSet|null
77 function searchTitle( $term ) {
83 * @param string $feature
86 public function supports( $feature ) {
90 case 'title-suffix-filter':
97 * Way to pass custom data for engines
99 * @param string $feature
103 public function setFeatureData( $feature, $data ) {
104 $this->features
[$feature] = $data;
108 * When overridden in derived class, performs database-specific conversions
109 * on text to be used for searching or updating search index.
110 * Default implementation does nothing (simply returns $string).
112 * @param string $string String to process
115 public function normalizeText( $string ) {
118 // Some languages such as Chinese require word segmentation
119 return $wgContLang->segmentByWord( $string );
123 * Transform search term in cases when parts of the query came as different
124 * GET params (when supported), e.g. for prefix queries:
125 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
126 * @param string $term
129 public function transformSearchTerm( $term ) {
134 * Get service class to finding near matches.
135 * @param Config $config Configuration to use for the matcher.
136 * @return SearchNearMatcher
138 public function getNearMatcher( Config
$config ) {
139 return new SearchNearMatcher( $config );
143 * Get near matcher for default SearchEngine.
144 * @return SearchNearMatcher
146 protected static function defaultNearMatcher() {
147 $config = MediaWikiServices
::getInstance()->getMainConfig();
148 return MediaWikiServices
::getInstance()->newSearchEngine()->getNearMatcher( $config );
152 * If an exact title match can be found, or a very slightly close match,
153 * return the title. If no match, returns NULL.
154 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
155 * @param string $searchterm
158 public static function getNearMatch( $searchterm ) {
159 return static::defaultNearMatcher()->getNearMatch( $searchterm );
163 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
165 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
166 * @param string $searchterm
167 * @return SearchResultSet
169 public static function getNearMatchResultSet( $searchterm ) {
170 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
174 * Get chars legal for search.
175 * NOTE: usage as static is deprecated and preserved only as BC measure
178 public static function legalSearchChars() {
179 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
183 * Set the maximum number of results to return
184 * and how many to skip before returning the first.
189 function setLimitOffset( $limit, $offset = 0 ) {
190 $this->limit
= intval( $limit );
191 $this->offset
= intval( $offset );
195 * Set which namespaces the search should include.
196 * Give an array of namespace index numbers.
198 * @param int[]|null $namespaces
200 function setNamespaces( $namespaces ) {
202 // Filter namespaces to only keep valid ones
203 $validNs = $this->searchableNamespaces();
204 $namespaces = array_filter( $namespaces, function( $ns ) use( $validNs ) {
205 return $ns < 0 ||
isset( $validNs[$ns] );
210 $this->namespaces
= $namespaces;
214 * Set whether the searcher should try to build a suggestion. Note: some searchers
215 * don't support building a suggestion in the first place and others don't respect
218 * @param bool $showSuggestion Should the searcher try to build suggestions
220 function setShowSuggestion( $showSuggestion ) {
221 $this->showSuggestion
= $showSuggestion;
225 * Get the valid sort directions. All search engines support 'relevance' but others
226 * might support more. The default in all implementations should be 'relevance.'
229 * @return array(string) the valid sort directions for setSort
231 public function getValidSorts() {
232 return [ 'relevance' ];
236 * Set the sort direction of the search results. Must be one returned by
237 * SearchEngine::getValidSorts()
240 * @throws InvalidArgumentException
241 * @param string $sort sort direction for query result
243 public function setSort( $sort ) {
244 if ( !in_array( $sort, $this->getValidSorts() ) ) {
245 throw new InvalidArgumentException( "Invalid sort: $sort. " .
246 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
252 * Get the sort direction of the search results
257 public function getSort() {
262 * Parse some common prefixes: all (search everything)
265 * @param string $query
268 function replacePrefixes( $query ) {
272 if ( strpos( $query, ':' ) === false ) { // nothing to do
276 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
277 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
278 $this->namespaces
= null;
279 $parsed = substr( $query, strlen( $allkeyword ) );
280 } elseif ( strpos( $query, ':' ) !== false ) {
281 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
282 $index = $wgContLang->getNsIndex( $prefix );
283 if ( $index !== false ) {
284 $this->namespaces
= [ $index ];
285 $parsed = substr( $query, strlen( $prefix ) +
1 );
288 if ( trim( $parsed ) == '' ) {
289 $parsed = $query; // prefix was the whole query
296 * Find snippet highlight settings for all users
297 * @return array Contextlines, contextchars
299 public static function userHighlightPrefs() {
300 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
301 $contextchars = 75; // same as above.... :P
302 return [ $contextlines, $contextchars ];
306 * Create or update the search index record for the given page.
307 * Title and text should be pre-processed.
311 * @param string $title
312 * @param string $text
314 function update( $id, $title, $text ) {
319 * Update a search index record's title only.
320 * Title should be pre-processed.
324 * @param string $title
326 function updateTitle( $id, $title ) {
331 * Delete an indexed page
332 * Title should be pre-processed.
335 * @param int $id Page id that was deleted
336 * @param string $title Title of page that was deleted
338 function delete( $id, $title ) {
343 * Get OpenSearch suggestion template
345 * @deprecated since 1.25
348 public static function getOpenSearchTemplate() {
349 wfDeprecated( __METHOD__
, '1.25' );
350 return ApiOpenSearch
::getOpenSearchTemplate( 'application/x-suggestions+json' );
354 * Get the raw text for updating the index from a content object
355 * Nicer search backends could possibly do something cooler than
356 * just returning raw text
358 * @todo This isn't ideal, we'd really like to have content-specific handling here
359 * @param Title $t Title we're indexing
360 * @param Content $c Content of the page to index
363 public function getTextFromContent( Title
$t, Content
$c = null ) {
364 return $c ?
$c->getTextForSearchIndex() : '';
368 * If an implementation of SearchEngine handles all of its own text processing
369 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
370 * rather silly handling, it should return true here instead.
374 public function textAlreadyUpdatedForIndex() {
379 * Makes search simple string if it was namespaced.
380 * Sets namespaces of the search to namespaces extracted from string.
381 * @param string $search
382 * @return $string Simplified search string
384 protected function normalizeNamespaces( $search ) {
385 // Find a Title which is not an interwiki and is in NS_MAIN
386 $title = Title
::newFromText( $search );
387 $ns = $this->namespaces
;
388 if ( $title && !$title->isExternal() ) {
389 $ns = [ $title->getNamespace() ];
390 $search = $title->getText();
391 if ( $ns[0] == NS_MAIN
) {
392 $ns = $this->namespaces
; // no explicit prefix, use default namespaces
393 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
396 $title = Title
::newFromText( $search . 'Dummy' );
397 if ( $title && $title->getText() == 'Dummy'
398 && $title->getNamespace() != NS_MAIN
399 && !$title->isExternal() )
401 $ns = [ $title->getNamespace() ];
404 Hooks
::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
408 $ns = array_map( function( $space ) {
409 return $space == NS_MEDIA ? NS_FILE
: $space;
412 $this->setNamespaces( $ns );
417 * Perform a completion search.
418 * Does not resolve namespaces and does not check variants.
419 * Search engine implementations may want to override this function.
420 * @param string $search
421 * @return SearchSuggestionSet
423 protected function completionSearchBackend( $search ) {
426 $search = trim( $search );
428 if ( !in_array( NS_SPECIAL
, $this->namespaces
) && // We do not run hook on Special: search
429 !Hooks
::run( 'PrefixSearchBackend',
430 [ $this->namespaces
, $search, $this->limit
, &$results, $this->offset
]
432 // False means hook worked.
433 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
435 return SearchSuggestionSet
::fromStrings( $results );
437 // Hook did not do the job, use default simple search
438 $results = $this->simplePrefixSearch( $search );
439 return SearchSuggestionSet
::fromTitles( $results );
444 * Perform a completion search.
445 * @param string $search
446 * @return SearchSuggestionSet
448 public function completionSearch( $search ) {
449 if ( trim( $search ) === '' ) {
450 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
452 $search = $this->normalizeNamespaces( $search );
453 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
457 * Perform a completion search with variants.
458 * @param string $search
459 * @return SearchSuggestionSet
461 public function completionSearchWithVariants( $search ) {
462 if ( trim( $search ) === '' ) {
463 return SearchSuggestionSet
::emptySuggestionSet(); // Return empty result
465 $search = $this->normalizeNamespaces( $search );
467 $results = $this->completionSearchBackend( $search );
468 $fallbackLimit = $this->limit
- $results->getSize();
469 if ( $fallbackLimit > 0 ) {
472 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
473 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
475 foreach ( $fallbackSearches as $fbs ) {
476 $this->setLimitOffset( $fallbackLimit );
477 $fallbackSearchResult = $this->completionSearch( $fbs );
478 $results->appendAll( $fallbackSearchResult );
479 $fallbackLimit -= count( $fallbackSearchResult );
480 if ( $fallbackLimit <= 0 ) {
485 return $this->processCompletionResults( $search, $results );
489 * Extract titles from completion results
490 * @param SearchSuggestionSet $completionResults
493 public function extractTitles( SearchSuggestionSet
$completionResults ) {
494 return $completionResults->map( function( SearchSuggestion
$sugg ) {
495 return $sugg->getSuggestedTitle();
500 * Process completion search results.
501 * Resolves the titles and rescores.
502 * @param SearchSuggestionSet $suggestions
503 * @return SearchSuggestionSet
505 protected function processCompletionResults( $search, SearchSuggestionSet
$suggestions ) {
506 $search = trim( $search );
507 // preload the titles with LinkBatch
508 $titles = $suggestions->map( function( SearchSuggestion
$sugg ) {
509 return $sugg->getSuggestedTitle();
511 $lb = new LinkBatch( $titles );
512 $lb->setCaller( __METHOD__
);
515 $results = $suggestions->map( function( SearchSuggestion
$sugg ) {
516 return $sugg->getSuggestedTitle()->getPrefixedText();
519 // Rescore results with an exact title match
520 // NOTE: in some cases like cross-namespace redirects
521 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
522 // backends like Cirrus will return no results. We should still
523 // try an exact title match to workaround this limitation
524 $rescorer = new SearchExactMatchRescorer();
525 $rescoredResults = $rescorer->rescore( $search, $this->namespaces
, $results, $this->limit
);
527 if ( count( $rescoredResults ) > 0 ) {
528 $found = array_search( $rescoredResults[0], $results );
529 if ( $found === false ) {
530 // If the first result is not in the previous array it
531 // means that we found a new exact match
532 $exactMatch = SearchSuggestion
::fromTitle( 0, Title
::newFromText( $rescoredResults[0] ) );
533 $suggestions->prepend( $exactMatch );
534 $suggestions->shrink( $this->limit
);
536 // if the first result is not the same we need to rescore
538 $suggestions->rescore( $found );
547 * Simple prefix search for subpages.
548 * @param string $search
551 public function defaultPrefixSearch( $search ) {
552 if ( trim( $search ) === '' ) {
556 $search = $this->normalizeNamespaces( $search );
557 return $this->simplePrefixSearch( $search );
561 * Call out to simple search backend.
562 * Defaults to TitlePrefixSearch.
563 * @param string $search
566 protected function simplePrefixSearch( $search ) {
567 // Use default database prefix search
568 $backend = new TitlePrefixSearch
;
569 return $backend->defaultSearchBackend( $this->namespaces
, $search, $this->limit
, $this->offset
);
573 * Make a list of searchable namespaces and their canonical names.
574 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
577 public static function searchableNamespaces() {
578 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->searchableNamespaces();
582 * Extract default namespaces to search from the given user's
583 * settings, returning a list of index numbers.
584 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
588 public static function userNamespaces( $user ) {
589 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
593 * An array of namespaces indexes to be searched by default
594 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
597 public static function defaultNamespaces() {
598 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->defaultNamespaces();
602 * Get a list of namespace names useful for showing in tooltips
604 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
605 * @param array $namespaces
608 public static function namespacesAsText( $namespaces ) {
609 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->namespacesAsText();
613 * Load up the appropriate search engine class for the currently
614 * active database backend, and return a configured instance.
615 * @deprecated since 1.27; Use SearchEngineFactory::create
616 * @param string $type Type of search backend, if not the default
617 * @return SearchEngine
619 public static function create( $type = null ) {
620 return MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
624 * Return the search engines we support. If only $wgSearchType
625 * is set, it'll be an array of just that one item.
626 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
629 public static function getSearchTypes() {
630 return MediaWikiServices
::getInstance()->getSearchEngineConfig()->getSearchTypes();
636 * Dummy class to be used when non-supported Database engine is present.
637 * @todo FIXME: Dummy class should probably try something at least mildly useful,
638 * such as a LIKE search through titles.
641 class SearchEngineDummy
extends SearchEngine
{