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
29 * Contain a class for special pages
36 /** @var int[]|null */
37 public $namespaces = array( NS_MAIN
);
40 protected $limit = 10;
43 protected $offset = 0;
45 /** @var array|string */
46 protected $searchTerms = array();
49 protected $showSuggestion = true;
50 private $sort = 'relevance';
52 /** @var array Feature values */
53 protected $features = array();
56 * Perform a full text search query and return a result set.
57 * If title searches are not supported or disabled, return null.
60 * @param string $term Raw search term
61 * @return SearchResultSet|Status|null
63 function searchText( $term ) {
68 * Perform a title-only search query and return a result set.
69 * If title searches are not supported or disabled, return null.
72 * @param string $term Raw search term
73 * @return SearchResultSet|null
75 function searchTitle( $term ) {
81 * @param string $feature
84 public function supports( $feature ) {
88 case 'title-suffix-filter':
95 * Way to pass custom data for engines
97 * @param string $feature
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
113 public function normalizeText( $string ) {
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
127 function transformSearchTerm( $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
138 public static function getNearMatch( $searchterm ) {
139 $title = self
::getNearMatchInternal( $searchterm );
141 Hooks
::run( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
146 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
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
161 private static function getNearMatchInternal( $searchterm ) {
162 global $wgContLang, $wgEnableSearchContributorsByIP;
164 $allSearchTerms = array( $searchterm );
166 if ( $wgContLang->hasVariants() ) {
167 $allSearchTerms = array_merge(
169 $wgContLang->autoConvertToAllVariants( $searchterm )
174 if ( !Hooks
::run( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
178 foreach ( $allSearchTerms as $term ) {
180 # Exact match? No need to look further.
181 $title = Title
::newFromText( $term );
182 if ( is_null( $title ) ) {
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() ) {
195 # See if it still otherwise has content is some sane sense
196 $page = WikiPage
::factory( $title );
197 if ( $page->hasViewableContent() ) {
201 if ( !Hooks
::run( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
205 # Now try all lower case (i.e. first letter capitalized)
206 $title = Title
::newFromText( $wgContLang->lc( $term ) );
207 if ( $title && $title->exists() ) {
211 # Now try capitalized string
212 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
213 if ( $title && $title->exists() ) {
217 # Now try all upper case
218 $title = Title
::newFromText( $wgContLang->uc( $term ) );
219 if ( $title && $title->exists() ) {
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() ) {
229 // Give hooks a chance at better match variants
231 if ( !Hooks
::run( 'SearchGetNearMatch', array( $term, &$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
) {
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 );
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...
269 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
270 return SearchEngine
::getNearMatch( $matches[1] );
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.
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 $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
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.'
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()
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() ) );
341 * Get the sort direction of the search results
346 public function getSort() {
351 * Parse some common prefixes: all (search everything)
354 * @param string $query
357 function replacePrefixes( $query ) {
361 if ( strpos( $query, ':' ) === false ) { // nothing to do
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
385 * Make a list of searchable namespaces and their canonical names.
388 public static function searchableNamespaces() {
391 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
392 if ( $ns >= NS_MAIN
) {
397 Hooks
::run( 'SearchableNamespaces', array( &$arr ) );
402 * Extract default namespaces to search from the given user's
403 * settings, returning a list of index numbers.
408 public static function userNamespaces( $user ) {
410 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
411 if ( $user->getOption( 'searchNs' . $ns ) ) {
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
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
445 * @param array $namespaces
448 public static function namespacesAsText( $namespaces ) {
451 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
452 foreach ( $formatted as $key => $ns ) {
453 if ( empty( $ns ) ) {
454 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
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;
471 $alternatives = self
::getSearchTypes();
473 if ( $type && in_array( $type, $alternatives ) ) {
475 } elseif ( $wgSearchType !== null ) {
476 $class = $wgSearchType;
478 $dbr = wfGetDB( DB_SLAVE
);
479 $class = $dbr->getSearchEngine();
482 $search = new $class( $dbr );
487 * Return the search engines we support. If only $wgSearchType
488 * is set, it'll be an array of just that one item.
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.
507 * @param string $title
508 * @param string $text
510 function update( $id, $title, $text ) {
515 * Update a search index record's title only.
516 * Title should be pre-processed.
520 * @param string $title
522 function updateTitle( $id, $title ) {
527 * Delete an indexed page
528 * Title should be pre-processed.
531 * @param int $id Page id that was deleted
532 * @param string $title Title of page that was deleted
534 function delete( $id, $title ) {
539 * Get OpenSearch suggestion template
541 * @deprecated since 1.25
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
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.
570 public function textAlreadyUpdatedForIndex() {
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.
581 class SearchEngineDummy
extends SearchEngine
{