PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / search / SearchEngine.php
blob81b850a27b731fed5b2c163f009c830200d5a55c
1 <?php
2 /**
3 * Basic search engine
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
20 * @file
21 * @ingroup Search
24 /**
25 * @defgroup Search Search
28 /**
29 * Contain a class for special pages
30 * @ingroup Search
32 class SearchEngine {
33 /** @var string */
34 public $prefix = '';
36 /** @var int[]|null */
37 public $namespaces = array( NS_MAIN );
39 /** @var int */
40 protected $limit = 10;
42 /** @var int */
43 protected $offset = 0;
45 /** @var array|string */
46 protected $searchTerms = array();
48 /** @var bool */
49 protected $showSuggestion = true;
50 private $sort = 'relevance';
52 /** @var array Feature values */
53 protected $features = array();
55 /**
56 * Perform a full text search query and return a result set.
57 * If title searches are not supported or disabled, return null.
58 * STUB
60 * @param string $term Raw search term
61 * @return SearchResultSet|Status|null
63 function searchText( $term ) {
64 return null;
67 /**
68 * Perform a title-only search query and return a result set.
69 * If title searches are not supported or disabled, return null.
70 * STUB
72 * @param string $term Raw search term
73 * @return SearchResultSet|null
75 function searchTitle( $term ) {
76 return null;
79 /**
80 * @since 1.18
81 * @param string $feature
82 * @return bool
84 public function supports( $feature ) {
85 switch ( $feature ) {
86 case 'search-update':
87 return true;
88 case 'title-suffix-filter':
89 default:
90 return false;
94 /**
95 * Way to pass custom data for engines
96 * @since 1.18
97 * @param string $feature
98 * @param mixed $data
99 * @return bool
101 public function setFeatureData( $feature, $data ) {
102 $this->features[$feature] = $data;
106 * When overridden in derived class, performs database-specific conversions
107 * on text to be used for searching or updating search index.
108 * Default implementation does nothing (simply returns $string).
110 * @param string $string String to process
111 * @return string
113 public function normalizeText( $string ) {
114 global $wgContLang;
116 // Some languages such as Chinese require word segmentation
117 return $wgContLang->segmentByWord( $string );
121 * Transform search term in cases when parts of the query came as different
122 * GET params (when supported), e.g. for prefix queries:
123 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
124 * @param string $term
125 * @return string
127 function transformSearchTerm( $term ) {
128 return $term;
132 * If an exact title match can be found, or a very slightly close match,
133 * return the title. If no match, returns NULL.
135 * @param string $searchterm
136 * @return Title
138 public static function getNearMatch( $searchterm ) {
139 $title = self::getNearMatchInternal( $searchterm );
141 Hooks::run( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
142 return $title;
146 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
147 * SearchResultSet.
149 * @param string $searchterm
150 * @return SearchResultSet
152 public static function getNearMatchResultSet( $searchterm ) {
153 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
157 * Really find the title match.
158 * @param string $searchterm
159 * @return null|Title
161 private static function getNearMatchInternal( $searchterm ) {
162 global $wgContLang, $wgEnableSearchContributorsByIP;
164 $allSearchTerms = array( $searchterm );
166 if ( $wgContLang->hasVariants() ) {
167 $allSearchTerms = array_unique( array_merge(
168 $allSearchTerms,
169 $wgContLang->autoConvertToAllVariants( $searchterm )
170 ) );
173 $titleResult = null;
174 if ( !Hooks::run( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
175 return $titleResult;
178 foreach ( $allSearchTerms as $term ) {
180 # Exact match? No need to look further.
181 $title = Title::newFromText( $term );
182 if ( is_null( $title ) ) {
183 return null;
186 # Try files if searching in the Media: namespace
187 if ( $title->getNamespace() == NS_MEDIA ) {
188 $title = Title::makeTitle( NS_FILE, $title->getText() );
191 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
192 return $title;
195 # See if it still otherwise has content is some sane sense
196 $page = WikiPage::factory( $title );
197 if ( $page->hasViewableContent() ) {
198 return $title;
201 if ( !Hooks::run( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
202 return $title;
205 # Now try all lower case (i.e. first letter capitalized)
206 $title = Title::newFromText( $wgContLang->lc( $term ) );
207 if ( $title && $title->exists() ) {
208 return $title;
211 # Now try capitalized string
212 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
213 if ( $title && $title->exists() ) {
214 return $title;
217 # Now try all upper case
218 $title = Title::newFromText( $wgContLang->uc( $term ) );
219 if ( $title && $title->exists() ) {
220 return $title;
223 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
224 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
225 if ( $title && $title->exists() ) {
226 return $title;
229 // Give hooks a chance at better match variants
230 $title = null;
231 if ( !Hooks::run( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
232 return $title;
236 $title = Title::newFromText( $searchterm );
238 # Entering an IP address goes to the contributions page
239 if ( $wgEnableSearchContributorsByIP ) {
240 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
241 || User::isIP( trim( $searchterm ) ) ) {
242 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
246 # Entering a user goes to the user page whether it's there or not
247 if ( $title->getNamespace() == NS_USER ) {
248 return $title;
251 # Go to images that exist even if there's no local page.
252 # There may have been a funny upload, or it may be on a shared
253 # file repository such as Wikimedia Commons.
254 if ( $title->getNamespace() == NS_FILE ) {
255 $image = wfFindFile( $title );
256 if ( $image ) {
257 return $title;
261 # MediaWiki namespace? Page may be "implied" if not customized.
262 # Just return it, with caps forced as the message system likes it.
263 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
264 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
267 # Quoted term? Try without the quotes...
268 $matches = array();
269 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
270 return SearchEngine::getNearMatch( $matches[1] );
273 return null;
276 public static function legalSearchChars() {
277 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
281 * Set the maximum number of results to return
282 * and how many to skip before returning the first.
284 * @param int $limit
285 * @param int $offset
287 function setLimitOffset( $limit, $offset = 0 ) {
288 $this->limit = intval( $limit );
289 $this->offset = intval( $offset );
293 * Set which namespaces the search should include.
294 * Give an array of namespace index numbers.
296 * @param int[]|null $namespaces
298 function setNamespaces( $namespaces ) {
299 if ( $namespaces ) {
300 // Filter namespaces to only keep valid ones
301 $validNs = $this->searchableNamespaces();
302 $namespaces = array_filter( $namespaces, function( $ns ) use( $validNs ) {
303 return $ns < 0 || isset( $validNs[$ns] );
304 } );
305 } else {
306 $namespaces = array();
308 $this->namespaces = $namespaces;
312 * Set whether the searcher should try to build a suggestion. Note: some searchers
313 * don't support building a suggestion in the first place and others don't respect
314 * this flag.
316 * @param bool $showSuggestion Should the searcher try to build suggestions
318 function setShowSuggestion( $showSuggestion ) {
319 $this->showSuggestion = $showSuggestion;
323 * Get the valid sort directions. All search engines support 'relevance' but others
324 * might support more. The default in all implementations should be 'relevance.'
326 * @since 1.25
327 * @return array(string) the valid sort directions for setSort
329 public function getValidSorts() {
330 return array( 'relevance' );
334 * Set the sort direction of the search results. Must be one returned by
335 * SearchEngine::getValidSorts()
337 * @since 1.25
338 * @throws InvalidArgumentException
339 * @param string $sort sort direction for query result
341 public function setSort( $sort ) {
342 if ( !in_array( $sort, $this->getValidSorts() ) ) {
343 throw new InvalidArgumentException( "Invalid sort: $sort. " .
344 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
346 $this->sort = $sort;
350 * Get the sort direction of the search results
352 * @since 1.25
353 * @return string
355 public function getSort() {
356 return $this->sort;
360 * Parse some common prefixes: all (search everything)
361 * or namespace names
363 * @param string $query
364 * @return string
366 function replacePrefixes( $query ) {
367 global $wgContLang;
369 $parsed = $query;
370 if ( strpos( $query, ':' ) === false ) { // nothing to do
371 return $parsed;
374 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
375 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
376 $this->namespaces = null;
377 $parsed = substr( $query, strlen( $allkeyword ) );
378 } elseif ( strpos( $query, ':' ) !== false ) {
379 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
380 $index = $wgContLang->getNsIndex( $prefix );
381 if ( $index !== false ) {
382 $this->namespaces = array( $index );
383 $parsed = substr( $query, strlen( $prefix ) + 1 );
386 if ( trim( $parsed ) == '' ) {
387 $parsed = $query; // prefix was the whole query
390 return $parsed;
394 * Make a list of searchable namespaces and their canonical names.
395 * @return array
397 public static function searchableNamespaces() {
398 global $wgContLang;
399 $arr = array();
400 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
401 if ( $ns >= NS_MAIN ) {
402 $arr[$ns] = $name;
406 Hooks::run( 'SearchableNamespaces', array( &$arr ) );
407 return $arr;
411 * Extract default namespaces to search from the given user's
412 * settings, returning a list of index numbers.
414 * @param user $user
415 * @return array
417 public static function userNamespaces( $user ) {
418 $arr = array();
419 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
420 if ( $user->getOption( 'searchNs' . $ns ) ) {
421 $arr[] = $ns;
425 return $arr;
429 * Find snippet highlight settings for all users
431 * @return array Contextlines, contextchars
433 public static function userHighlightPrefs() {
434 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
435 $contextchars = 75; // same as above.... :P
436 return array( $contextlines, $contextchars );
440 * An array of namespaces indexes to be searched by default
442 * @return array
444 public static function defaultNamespaces() {
445 global $wgNamespacesToBeSearchedDefault;
447 return array_keys( $wgNamespacesToBeSearchedDefault, true );
451 * Get a list of namespace names useful for showing in tooltips
452 * and preferences
454 * @param array $namespaces
455 * @return array
457 public static function namespacesAsText( $namespaces ) {
458 global $wgContLang;
460 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
461 foreach ( $formatted as $key => $ns ) {
462 if ( empty( $ns ) ) {
463 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
466 return $formatted;
470 * Load up the appropriate search engine class for the currently
471 * active database backend, and return a configured instance.
473 * @param string $type Type of search backend, if not the default
474 * @return SearchEngine
476 public static function create( $type = null ) {
477 global $wgSearchType;
478 $dbr = null;
480 $alternatives = self::getSearchTypes();
482 if ( $type && in_array( $type, $alternatives ) ) {
483 $class = $type;
484 } elseif ( $wgSearchType !== null ) {
485 $class = $wgSearchType;
486 } else {
487 $dbr = wfGetDB( DB_SLAVE );
488 $class = $dbr->getSearchEngine();
491 $search = new $class( $dbr );
492 return $search;
496 * Return the search engines we support. If only $wgSearchType
497 * is set, it'll be an array of just that one item.
499 * @return array
501 public static function getSearchTypes() {
502 global $wgSearchType, $wgSearchTypeAlternatives;
504 $alternatives = $wgSearchTypeAlternatives ?: array();
505 array_unshift( $alternatives, $wgSearchType );
507 return $alternatives;
511 * Create or update the search index record for the given page.
512 * Title and text should be pre-processed.
513 * STUB
515 * @param int $id
516 * @param string $title
517 * @param string $text
519 function update( $id, $title, $text ) {
520 // no-op
524 * Update a search index record's title only.
525 * Title should be pre-processed.
526 * STUB
528 * @param int $id
529 * @param string $title
531 function updateTitle( $id, $title ) {
532 // no-op
536 * Delete an indexed page
537 * Title should be pre-processed.
538 * STUB
540 * @param int $id Page id that was deleted
541 * @param string $title Title of page that was deleted
543 function delete( $id, $title ) {
544 // no-op
548 * Get OpenSearch suggestion template
550 * @deprecated since 1.25
551 * @return string
553 public static function getOpenSearchTemplate() {
554 wfDeprecated( __METHOD__, '1.25' );
555 return ApiOpenSearch::getOpenSearchTemplate( 'application/x-suggestions+json' );
559 * Get the raw text for updating the index from a content object
560 * Nicer search backends could possibly do something cooler than
561 * just returning raw text
563 * @todo This isn't ideal, we'd really like to have content-specific handling here
564 * @param Title $t Title we're indexing
565 * @param Content $c Content of the page to index
566 * @return string
568 public function getTextFromContent( Title $t, Content $c = null ) {
569 return $c ? $c->getTextForSearchIndex() : '';
573 * If an implementation of SearchEngine handles all of its own text processing
574 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
575 * rather silly handling, it should return true here instead.
577 * @return bool
579 public function textAlreadyUpdatedForIndex() {
580 return false;
584 * Makes search simple string if it was namespaced.
585 * Sets namespaces of the search to namespaces extracted from string.
586 * @param string $search
587 * @return $string Simplified search string
589 protected function normalizeNamespaces( $search ) {
590 // Find a Title which is not an interwiki and is in NS_MAIN
591 $title = Title::newFromText( $search );
592 $ns = $this->namespaces;
593 if ( $title && !$title->isExternal() ) {
594 $ns = array( $title->getNamespace() );
595 $search = $title->getText();
596 if ( $ns[0] == NS_MAIN ) {
597 $ns = $this->namespaces; // no explicit prefix, use default namespaces
598 Hooks::run( 'PrefixSearchExtractNamespace', array( &$ns, &$search ) );
600 } else {
601 $title = Title::newFromText( $search . 'Dummy' );
602 if ( $title && $title->getText() == 'Dummy'
603 && $title->getNamespace() != NS_MAIN
604 && !$title->isExternal() )
606 $ns = array( $title->getNamespace() );
607 $search = '';
608 } else {
609 Hooks::run( 'PrefixSearchExtractNamespace', array( &$ns, &$search ) );
613 $ns = array_map( function( $space ) {
614 return $space == NS_MEDIA ? NS_FILE : $space;
615 }, $ns );
617 $this->setNamespaces( $ns );
618 return $search;
622 * Perform a completion search.
623 * Does not resolve namespaces and does not check variants.
624 * Search engine implementations may want to override this function.
625 * @param string $search
626 * @return SearchSuggestionSet
628 protected function completionSearchBackend( $search ) {
629 $results = array();
631 $search = trim( $search );
633 if ( !in_array( NS_SPECIAL, $this->namespaces ) && // We do not run hook on Special: search
634 !Hooks::run( 'PrefixSearchBackend',
635 array( $this->namespaces, $search, $this->limit, &$results, $this->offset )
636 ) ) {
637 // False means hook worked.
638 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
640 return SearchSuggestionSet::fromStrings( $results );
641 } else {
642 // Hook did not do the job, use default simple search
643 $results = $this->simplePrefixSearch( $search );
644 return SearchSuggestionSet::fromTitles( $results );
649 * Perform a completion search.
650 * @param string $search
651 * @return SearchSuggestionSet
653 public function completionSearch( $search ) {
654 if ( trim( $search ) === '' ) {
655 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
657 $search = $this->normalizeNamespaces( $search );
658 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
662 * Perform a completion search with variants.
663 * @param string $search
664 * @return SearchSuggestionSet
666 public function completionSearchWithVariants( $search ) {
667 if ( trim( $search ) === '' ) {
668 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
670 $search = $this->normalizeNamespaces( $search );
672 $results = $this->completionSearchBackend( $search );
673 $fallbackLimit = $this->limit - $results->getSize();
674 if ( $fallbackLimit > 0 ) {
675 global $wgContLang;
677 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
678 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), array( $search ) );
680 foreach ( $fallbackSearches as $fbs ) {
681 $this->setLimitOffset( $fallbackLimit );
682 $fallbackSearchResult = $this->completionSearch( $fbs );
683 $results->appendAll( $fallbackSearchResult );
684 $fallbackLimit -= count( $fallbackSearchResult );
685 if ( $fallbackLimit <= 0 ) {
686 break;
690 return $this->processCompletionResults( $search, $results );
694 * Extract titles from completion results
695 * @param SearchSuggestionSet $completionResults
696 * @return Title[]
698 public function extractTitles( SearchSuggestionSet $completionResults ) {
699 return $completionResults->map( function( SearchSuggestion $sugg ) {
700 return $sugg->getSuggestedTitle();
701 } );
705 * Process completion search results.
706 * Resolves the titles and rescores.
707 * @param SearchSuggestionSet $suggestions
708 * @return SearchSuggestionSet
710 protected function processCompletionResults( $search, SearchSuggestionSet $suggestions ) {
711 if ( $suggestions->getSize() == 0 ) {
712 // If we don't have anything, don't bother
713 return $suggestions;
715 $search = trim( $search );
716 // preload the titles with LinkBatch
717 $titles = $suggestions->map( function( SearchSuggestion $sugg ) {
718 return $sugg->getSuggestedTitle();
719 } );
720 $lb = new LinkBatch( $titles );
721 $lb->setCaller( __METHOD__ );
722 $lb->execute();
724 $results = $suggestions->map( function( SearchSuggestion $sugg ) {
725 return $sugg->getSuggestedTitle()->getPrefixedText();
726 } );
728 // Rescore results with an exact title match
729 $rescorer = new SearchExactMatchRescorer();
730 $rescoredResults = $rescorer->rescore( $search, $this->namespaces, $results, $this->limit );
732 if ( count( $rescoredResults ) > 0 ) {
733 $found = array_search( $rescoredResults[0], $results );
734 if ( $found === false ) {
735 // If the first result is not in the previous array it
736 // means that we found a new exact match
737 $exactMatch = SearchSuggestion::fromTitle( 0, Title::newFromText( $rescoredResults[0] ) );
738 $suggestions->prepend( $exactMatch );
739 $suggestions->shrink( $this->limit );
740 } else {
741 // if the first result is not the same we need to rescore
742 if ( $found > 0 ) {
743 $suggestions->rescore( $found );
748 return $suggestions;
752 * Simple prefix search for subpages.
753 * @param string $search
754 * @return Title[]
756 public function defaultPrefixSearch( $search ) {
757 if ( trim( $search ) === '' ) {
758 return array();
761 $search = $this->normalizeNamespaces( $search );
762 return $this->simplePrefixSearch( $search );
766 * Call out to simple search backend.
767 * Defaults to TitlePrefixSearch.
768 * @param string $search
769 * @return Title[]
771 protected function simplePrefixSearch( $search ) {
772 // Use default database prefix search
773 $backend = new TitlePrefixSearch;
774 return $backend->defaultSearchBackend( $this->namespaces, $search, $this->limit, $this->offset );
780 * Dummy class to be used when non-supported Database engine is present.
781 * @todo FIXME: Dummy class should probably try something at least mildly useful,
782 * such as a LIKE search through titles.
783 * @ingroup Search
785 class SearchEngineDummy extends SearchEngine {
786 // no-op