Merge "mw.loader: Improve error logging"
[mediawiki.git] / includes / search / SearchEngine.php
blob827d8c31d7ccf30983cf3f630b4c25736ed398b8
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 $limit = 10;
34 var $offset = 0;
35 var $prefix = '';
36 var $searchTerms = array();
37 var $namespaces = array( NS_MAIN );
38 protected $showSuggestion = true;
40 /** @var array Feature values */
41 protected $features = array();
43 /**
44 * Perform a full text search query and return a result set.
45 * If title searches are not supported or disabled, return null.
46 * STUB
48 * @param string $term Raw search term
49 * @return SearchResultSet|Status|null
51 function searchText( $term ) {
52 return null;
55 /**
56 * Perform a title-only 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|null
63 function searchTitle( $term ) {
64 return null;
67 /**
68 * @since 1.18
69 * @param string $feature
70 * @return bool
72 public function supports( $feature ) {
73 switch ( $feature ) {
74 case 'search-update':
75 return true;
76 case 'title-suffix-filter':
77 default:
78 return false;
82 /**
83 * Way to pass custom data for engines
84 * @since 1.18
85 * @param string $feature
86 * @param mixed $data
87 * @return bool
89 public function setFeatureData( $feature, $data ) {
90 $this->features[$feature] = $data;
93 /**
94 * When overridden in derived class, performs database-specific conversions
95 * on text to be used for searching or updating search index.
96 * Default implementation does nothing (simply returns $string).
98 * @param string $string String to process
99 * @return string
101 public function normalizeText( $string ) {
102 global $wgContLang;
104 // Some languages such as Chinese require word segmentation
105 return $wgContLang->segmentByWord( $string );
109 * Transform search term in cases when parts of the query came as different GET params (when supported)
110 * e.g. for prefix queries: search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
112 function transformSearchTerm( $term ) {
113 return $term;
117 * If an exact title match can be found, or a very slightly close match,
118 * return the title. If no match, returns NULL.
120 * @param string $searchterm
121 * @return Title
123 public static function getNearMatch( $searchterm ) {
124 $title = self::getNearMatchInternal( $searchterm );
126 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
127 return $title;
131 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
132 * SearchResultSet.
134 * @param string $searchterm
135 * @return SearchResultSet
137 public static function getNearMatchResultSet( $searchterm ) {
138 return new SearchNearMatchResultSet( self::getNearMatch( $searchterm ) );
142 * Really find the title match.
143 * @return null|Title
145 private static function getNearMatchInternal( $searchterm ) {
146 global $wgContLang, $wgEnableSearchContributorsByIP;
148 $allSearchTerms = array( $searchterm );
150 if ( $wgContLang->hasVariants() ) {
151 $allSearchTerms = array_merge( $allSearchTerms, $wgContLang->autoConvertToAllVariants( $searchterm ) );
154 $titleResult = null;
155 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
156 return $titleResult;
159 foreach ( $allSearchTerms as $term ) {
161 # Exact match? No need to look further.
162 $title = Title::newFromText( $term );
163 if ( is_null( $title ) ) {
164 return null;
167 # Try files if searching in the Media: namespace
168 if ( $title->getNamespace() == NS_MEDIA ) {
169 $title = Title::makeTitle( NS_FILE, $title->getText() );
172 if ( $title->isSpecialPage() || $title->isExternal() || $title->exists() ) {
173 return $title;
176 # See if it still otherwise has content is some sane sense
177 $page = WikiPage::factory( $title );
178 if ( $page->hasViewableContent() ) {
179 return $title;
182 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
183 return $title;
186 # Now try all lower case (i.e. first letter capitalized)
187 $title = Title::newFromText( $wgContLang->lc( $term ) );
188 if ( $title && $title->exists() ) {
189 return $title;
192 # Now try capitalized string
193 $title = Title::newFromText( $wgContLang->ucwords( $term ) );
194 if ( $title && $title->exists() ) {
195 return $title;
198 # Now try all upper case
199 $title = Title::newFromText( $wgContLang->uc( $term ) );
200 if ( $title && $title->exists() ) {
201 return $title;
204 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
205 $title = Title::newFromText( $wgContLang->ucwordbreaks( $term ) );
206 if ( $title && $title->exists() ) {
207 return $title;
210 // Give hooks a chance at better match variants
211 $title = null;
212 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
213 return $title;
217 $title = Title::newFromText( $searchterm );
219 # Entering an IP address goes to the contributions page
220 if ( $wgEnableSearchContributorsByIP ) {
221 if ( ( $title->getNamespace() == NS_USER && User::isIP( $title->getText() ) )
222 || User::isIP( trim( $searchterm ) ) ) {
223 return SpecialPage::getTitleFor( 'Contributions', $title->getDBkey() );
227 # Entering a user goes to the user page whether it's there or not
228 if ( $title->getNamespace() == NS_USER ) {
229 return $title;
232 # Go to images that exist even if there's no local page.
233 # There may have been a funny upload, or it may be on a shared
234 # file repository such as Wikimedia Commons.
235 if ( $title->getNamespace() == NS_FILE ) {
236 $image = wfFindFile( $title );
237 if ( $image ) {
238 return $title;
242 # MediaWiki namespace? Page may be "implied" if not customized.
243 # Just return it, with caps forced as the message system likes it.
244 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
245 return Title::makeTitle( NS_MEDIAWIKI, $wgContLang->ucfirst( $title->getText() ) );
248 # Quoted term? Try without the quotes...
249 $matches = array();
250 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
251 return SearchEngine::getNearMatch( $matches[1] );
254 return null;
257 public static function legalSearchChars() {
258 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
262 * Set the maximum number of results to return
263 * and how many to skip before returning the first.
265 * @param int $limit
266 * @param int $offset
268 function setLimitOffset( $limit, $offset = 0 ) {
269 $this->limit = intval( $limit );
270 $this->offset = intval( $offset );
274 * Set which namespaces the search should include.
275 * Give an array of namespace index numbers.
277 * @param array $namespaces
279 function setNamespaces( $namespaces ) {
280 $this->namespaces = $namespaces;
284 * Set whether the searcher should try to build a suggestion. Note: some searchers
285 * don't support building a suggestion in the first place and others don't respect
286 * this flag.
288 * @param bool $showSuggestion Should the searcher try to build suggestions
290 function setShowSuggestion( $showSuggestion ) {
291 $this->showSuggestion = $showSuggestion;
295 * Parse some common prefixes: all (search everything)
296 * or namespace names
298 * @param string $query
299 * @return string
301 function replacePrefixes( $query ) {
302 global $wgContLang;
304 $parsed = $query;
305 if ( strpos( $query, ':' ) === false ) { // nothing to do
306 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
307 return $parsed;
310 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
311 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
312 $this->namespaces = null;
313 $parsed = substr( $query, strlen( $allkeyword ) );
314 } elseif ( strpos( $query, ':' ) !== false ) {
315 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
316 $index = $wgContLang->getNsIndex( $prefix );
317 if ( $index !== false ) {
318 $this->namespaces = array( $index );
319 $parsed = substr( $query, strlen( $prefix ) + 1 );
322 if ( trim( $parsed ) == '' ) {
323 $parsed = $query; // prefix was the whole query
326 wfRunHooks( 'SearchEngineReplacePrefixesComplete', array( $this, $query, &$parsed ) );
328 return $parsed;
332 * Make a list of searchable namespaces and their canonical names.
333 * @return array
335 public static function searchableNamespaces() {
336 global $wgContLang;
337 $arr = array();
338 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
339 if ( $ns >= NS_MAIN ) {
340 $arr[$ns] = $name;
344 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
345 return $arr;
349 * Extract default namespaces to search from the given user's
350 * settings, returning a list of index numbers.
352 * @param user $user
353 * @return array
355 public static function userNamespaces( $user ) {
356 global $wgSearchEverythingOnlyLoggedIn;
358 $searchableNamespaces = SearchEngine::searchableNamespaces();
360 // get search everything preference, that can be set to be read for logged-in users
361 // it overrides other options
362 if ( !$wgSearchEverythingOnlyLoggedIn || $user->isLoggedIn() ) {
363 if ( $user->getOption( 'searcheverything' ) ) {
364 return array_keys( $searchableNamespaces );
368 $arr = array();
369 foreach ( $searchableNamespaces as $ns => $name ) {
370 if ( $user->getOption( 'searchNs' . $ns ) ) {
371 $arr[] = $ns;
375 return $arr;
379 * Find snippet highlight settings for all users
381 * @return array Contextlines, contextchars
383 public static function userHighlightPrefs() {
384 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
385 $contextchars = 75; // same as above.... :P
386 return array( $contextlines, $contextchars );
390 * An array of namespaces indexes to be searched by default
392 * @return array
394 public static function defaultNamespaces() {
395 global $wgNamespacesToBeSearchedDefault;
397 return array_keys( $wgNamespacesToBeSearchedDefault, true );
401 * Get a list of namespace names useful for showing in tooltips
402 * and preferences
404 * @param array $namespaces
405 * @return array
407 public static function namespacesAsText( $namespaces ) {
408 global $wgContLang;
410 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
411 foreach ( $formatted as $key => $ns ) {
412 if ( empty( $ns ) ) {
413 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
416 return $formatted;
420 * Return the help namespaces to be shown on Special:Search
422 * @return array
424 public static function helpNamespaces() {
425 global $wgNamespacesToBeSearchedHelp;
427 return array_keys( $wgNamespacesToBeSearchedHelp, true );
431 * Return a 'cleaned up' search string
433 * @param string $text
434 * @return string
436 function filter( $text ) {
437 $lc = $this->legalSearchChars();
438 return trim( preg_replace( "/[^{$lc}]/", " ", $text ) );
442 * Load up the appropriate search engine class for the currently
443 * active database backend, and return a configured instance.
445 * @param string $type Type of search backend, if not the default
446 * @return SearchEngine
448 public static function create( $type = null ) {
449 global $wgSearchType;
450 $dbr = null;
452 $alternatives = self::getSearchTypes();
454 if ( $type && in_array( $type, $alternatives ) ) {
455 $class = $type;
456 } elseif ( $wgSearchType !== null ) {
457 $class = $wgSearchType;
458 } else {
459 $dbr = wfGetDB( DB_SLAVE );
460 $class = $dbr->getSearchEngine();
463 $search = new $class( $dbr );
464 return $search;
468 * Return the search engines we support. If only $wgSearchType
469 * is set, it'll be an array of just that one item.
471 * @return array
473 public static function getSearchTypes() {
474 global $wgSearchType, $wgSearchTypeAlternatives;
476 $alternatives = $wgSearchTypeAlternatives ?: array();
477 array_unshift( $alternatives, $wgSearchType );
479 return $alternatives;
483 * Create or update the search index record for the given page.
484 * Title and text should be pre-processed.
485 * STUB
487 * @param int $id
488 * @param string $title
489 * @param string $text
491 function update( $id, $title, $text ) {
492 // no-op
496 * Update a search index record's title only.
497 * Title should be pre-processed.
498 * STUB
500 * @param int $id
501 * @param string $title
503 function updateTitle( $id, $title ) {
504 // no-op
508 * Delete an indexed page
509 * Title should be pre-processed.
510 * STUB
512 * @param int $id Page id that was deleted
513 * @param string $title Title of page that was deleted
515 function delete( $id, $title ) {
516 // no-op
520 * Get OpenSearch suggestion template
522 * @return string
524 public static function getOpenSearchTemplate() {
525 global $wgOpenSearchTemplate, $wgCanonicalServer;
526 if ( $wgOpenSearchTemplate ) {
527 return $wgOpenSearchTemplate;
528 } else {
529 $ns = implode( '|', SearchEngine::defaultNamespaces() );
530 if ( !$ns ) {
531 $ns = "0";
533 return $wgCanonicalServer . wfScript( 'api' ) . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
538 * Get the raw text for updating the index from a content object
539 * Nicer search backends could possibly do something cooler than
540 * just returning raw text
542 * @todo This isn't ideal, we'd really like to have content-specific handling here
543 * @param Title $t Title we're indexing
544 * @param Content $c Content of the page to index
545 * @return string
547 public function getTextFromContent( Title $t, Content $c = null ) {
548 return $c ? $c->getTextForSearchIndex() : '';
552 * If an implementation of SearchEngine handles all of its own text processing
553 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
554 * rather silly handling, it should return true here instead.
556 * @return bool
558 public function textAlreadyUpdatedForIndex() {
559 return false;
564 * @ingroup Search
566 class SearchResultTooMany {
567 # # Some search engines may bail out if too many matches are found
571 * Dummy class to be used when non-supported Database engine is present.
572 * @todo FIXME: Dummy class should probably try something at least mildly useful,
573 * such as a LIKE search through titles.
574 * @ingroup Search
576 class SearchEngineDummy extends SearchEngine {
577 // no-op