Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / search / SearchEngine.php
blob5770276ac6a4766bcca380d3f1503505468181c8
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[] */
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_merge(
168 $allSearchTerms,
169 $wgContLang->autoConvertToAllVariants( $searchterm )
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 array $namespaces
298 function setNamespaces( $namespaces ) {
299 $this->namespaces = $namespaces;
303 * Set whether the searcher should try to build a suggestion. Note: some searchers
304 * don't support building a suggestion in the first place and others don't respect
305 * this flag.
307 * @param bool $showSuggestion Should the searcher try to build suggestions
309 function setShowSuggestion( $showSuggestion ) {
310 $this->showSuggestion = $showSuggestion;
314 * Get the valid sort directions. All search engines support 'relevance' but others
315 * might support more. The default in all implementations should be 'relevance.'
317 * @since 1.25
318 * @return array(string) the valid sort directions for setSort
320 public function getValidSorts() {
321 return array( 'relevance' );
325 * Set the sort direction of the search results. Must be one returned by
326 * SearchEngine::getValidSorts()
328 * @since 1.25
329 * @throws InvalidArgumentException
330 * @param string $sort sort direction for query result
332 public function setSort( $sort ) {
333 if ( !in_array( $sort, $this->getValidSorts() ) ) {
334 throw new InvalidArgumentException( "Invalid sort: $sort. " .
335 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
337 $this->sort = $sort;
341 * Get the sort direction of the search results
343 * @since 1.25
344 * @return string
346 public function getSort() {
347 return $this->sort;
351 * Parse some common prefixes: all (search everything)
352 * or namespace names
354 * @param string $query
355 * @return string
357 function replacePrefixes( $query ) {
358 global $wgContLang;
360 $parsed = $query;
361 if ( strpos( $query, ':' ) === false ) { // nothing to do
362 return $parsed;
365 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
366 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
367 $this->namespaces = null;
368 $parsed = substr( $query, strlen( $allkeyword ) );
369 } elseif ( strpos( $query, ':' ) !== false ) {
370 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
371 $index = $wgContLang->getNsIndex( $prefix );
372 if ( $index !== false ) {
373 $this->namespaces = array( $index );
374 $parsed = substr( $query, strlen( $prefix ) + 1 );
377 if ( trim( $parsed ) == '' ) {
378 $parsed = $query; // prefix was the whole query
381 return $parsed;
385 * Make a list of searchable namespaces and their canonical names.
386 * @return array
388 public static function searchableNamespaces() {
389 global $wgContLang;
390 $arr = array();
391 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
392 if ( $ns >= NS_MAIN ) {
393 $arr[$ns] = $name;
397 Hooks::run( 'SearchableNamespaces', array( &$arr ) );
398 return $arr;
402 * Extract default namespaces to search from the given user's
403 * settings, returning a list of index numbers.
405 * @param user $user
406 * @return array
408 public static function userNamespaces( $user ) {
409 $arr = array();
410 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
411 if ( $user->getOption( 'searchNs' . $ns ) ) {
412 $arr[] = $ns;
416 return $arr;
420 * Find snippet highlight settings for all users
422 * @return array Contextlines, contextchars
424 public static function userHighlightPrefs() {
425 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
426 $contextchars = 75; // same as above.... :P
427 return array( $contextlines, $contextchars );
431 * An array of namespaces indexes to be searched by default
433 * @return array
435 public static function defaultNamespaces() {
436 global $wgNamespacesToBeSearchedDefault;
438 return array_keys( $wgNamespacesToBeSearchedDefault, true );
442 * Get a list of namespace names useful for showing in tooltips
443 * and preferences
445 * @param array $namespaces
446 * @return array
448 public static function namespacesAsText( $namespaces ) {
449 global $wgContLang;
451 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
452 foreach ( $formatted as $key => $ns ) {
453 if ( empty( $ns ) ) {
454 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
457 return $formatted;
461 * Load up the appropriate search engine class for the currently
462 * active database backend, and return a configured instance.
464 * @param string $type Type of search backend, if not the default
465 * @return SearchEngine
467 public static function create( $type = null ) {
468 global $wgSearchType;
469 $dbr = null;
471 $alternatives = self::getSearchTypes();
473 if ( $type && in_array( $type, $alternatives ) ) {
474 $class = $type;
475 } elseif ( $wgSearchType !== null ) {
476 $class = $wgSearchType;
477 } else {
478 $dbr = wfGetDB( DB_SLAVE );
479 $class = $dbr->getSearchEngine();
482 $search = new $class( $dbr );
483 return $search;
487 * Return the search engines we support. If only $wgSearchType
488 * is set, it'll be an array of just that one item.
490 * @return array
492 public static function getSearchTypes() {
493 global $wgSearchType, $wgSearchTypeAlternatives;
495 $alternatives = $wgSearchTypeAlternatives ?: array();
496 array_unshift( $alternatives, $wgSearchType );
498 return $alternatives;
502 * Create or update the search index record for the given page.
503 * Title and text should be pre-processed.
504 * STUB
506 * @param int $id
507 * @param string $title
508 * @param string $text
510 function update( $id, $title, $text ) {
511 // no-op
515 * Update a search index record's title only.
516 * Title should be pre-processed.
517 * STUB
519 * @param int $id
520 * @param string $title
522 function updateTitle( $id, $title ) {
523 // no-op
527 * Delete an indexed page
528 * Title should be pre-processed.
529 * STUB
531 * @param int $id Page id that was deleted
532 * @param string $title Title of page that was deleted
534 function delete( $id, $title ) {
535 // no-op
539 * Get OpenSearch suggestion template
541 * @deprecated since 1.25
542 * @return string
544 public static function getOpenSearchTemplate() {
545 wfDeprecated( __METHOD__, '1.25' );
546 return ApiOpenSearch::getOpenSearchTemplate( 'application/x-suggestions+json' );
550 * Get the raw text for updating the index from a content object
551 * Nicer search backends could possibly do something cooler than
552 * just returning raw text
554 * @todo This isn't ideal, we'd really like to have content-specific handling here
555 * @param Title $t Title we're indexing
556 * @param Content $c Content of the page to index
557 * @return string
559 public function getTextFromContent( Title $t, Content $c = null ) {
560 return $c ? $c->getTextForSearchIndex() : '';
564 * If an implementation of SearchEngine handles all of its own text processing
565 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
566 * rather silly handling, it should return true here instead.
568 * @return bool
570 public function textAlreadyUpdatedForIndex() {
571 return false;
576 * Dummy class to be used when non-supported Database engine is present.
577 * @todo FIXME: Dummy class should probably try something at least mildly useful,
578 * such as a LIKE search through titles.
579 * @ingroup Search
581 class SearchEngineDummy extends SearchEngine {
582 // no-op