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
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;
51 /** @var array Feature values */
52 protected $features = array();
55 * Perform a full text search query and return a result set.
56 * If title searches are not supported or disabled, return null.
59 * @param string $term Raw search term
60 * @return SearchResultSet|Status|null
62 function searchText( $term ) {
67 * Perform a title-only search query and return a result set.
68 * If title searches are not supported or disabled, return null.
71 * @param string $term Raw search term
72 * @return SearchResultSet|null
74 function searchTitle( $term ) {
80 * @param string $feature
83 public function supports( $feature ) {
87 case 'title-suffix-filter':
94 * Way to pass custom data for engines
96 * @param string $feature
100 public function setFeatureData( $feature, $data ) {
101 $this->features
[$feature] = $data;
105 * When overridden in derived class, performs database-specific conversions
106 * on text to be used for searching or updating search index.
107 * Default implementation does nothing (simply returns $string).
109 * @param string $string String to process
112 public function normalizeText( $string ) {
115 // Some languages such as Chinese require word segmentation
116 return $wgContLang->segmentByWord( $string );
120 * Transform search term in cases when parts of the query came as different
121 * GET params (when supported), e.g. for prefix queries:
122 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
124 function transformSearchTerm( $term ) {
129 * If an exact title match can be found, or a very slightly close match,
130 * return the title. If no match, returns NULL.
132 * @param string $searchterm
135 public static function getNearMatch( $searchterm ) {
136 $title = self
::getNearMatchInternal( $searchterm );
138 wfRunHooks( 'SearchGetNearMatchComplete', array( $searchterm, &$title ) );
143 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
146 * @param string $searchterm
147 * @return SearchResultSet
149 public static function getNearMatchResultSet( $searchterm ) {
150 return new SearchNearMatchResultSet( self
::getNearMatch( $searchterm ) );
154 * Really find the title match.
157 private static function getNearMatchInternal( $searchterm ) {
158 global $wgContLang, $wgEnableSearchContributorsByIP;
160 $allSearchTerms = array( $searchterm );
162 if ( $wgContLang->hasVariants() ) {
163 $allSearchTerms = array_merge(
165 $wgContLang->autoConvertToAllVariants( $searchterm )
170 if ( !wfRunHooks( 'SearchGetNearMatchBefore', array( $allSearchTerms, &$titleResult ) ) ) {
174 foreach ( $allSearchTerms as $term ) {
176 # Exact match? No need to look further.
177 $title = Title
::newFromText( $term );
178 if ( is_null( $title ) ) {
182 # Try files if searching in the Media: namespace
183 if ( $title->getNamespace() == NS_MEDIA
) {
184 $title = Title
::makeTitle( NS_FILE
, $title->getText() );
187 if ( $title->isSpecialPage() ||
$title->isExternal() ||
$title->exists() ) {
191 # See if it still otherwise has content is some sane sense
192 $page = WikiPage
::factory( $title );
193 if ( $page->hasViewableContent() ) {
197 if ( !wfRunHooks( 'SearchAfterNoDirectMatch', array( $term, &$title ) ) ) {
201 # Now try all lower case (i.e. first letter capitalized)
202 $title = Title
::newFromText( $wgContLang->lc( $term ) );
203 if ( $title && $title->exists() ) {
207 # Now try capitalized string
208 $title = Title
::newFromText( $wgContLang->ucwords( $term ) );
209 if ( $title && $title->exists() ) {
213 # Now try all upper case
214 $title = Title
::newFromText( $wgContLang->uc( $term ) );
215 if ( $title && $title->exists() ) {
219 # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
220 $title = Title
::newFromText( $wgContLang->ucwordbreaks( $term ) );
221 if ( $title && $title->exists() ) {
225 // Give hooks a chance at better match variants
227 if ( !wfRunHooks( 'SearchGetNearMatch', array( $term, &$title ) ) ) {
232 $title = Title
::newFromText( $searchterm );
234 # Entering an IP address goes to the contributions page
235 if ( $wgEnableSearchContributorsByIP ) {
236 if ( ( $title->getNamespace() == NS_USER
&& User
::isIP( $title->getText() ) )
237 || User
::isIP( trim( $searchterm ) ) ) {
238 return SpecialPage
::getTitleFor( 'Contributions', $title->getDBkey() );
242 # Entering a user goes to the user page whether it's there or not
243 if ( $title->getNamespace() == NS_USER
) {
247 # Go to images that exist even if there's no local page.
248 # There may have been a funny upload, or it may be on a shared
249 # file repository such as Wikimedia Commons.
250 if ( $title->getNamespace() == NS_FILE
) {
251 $image = wfFindFile( $title );
257 # MediaWiki namespace? Page may be "implied" if not customized.
258 # Just return it, with caps forced as the message system likes it.
259 if ( $title->getNamespace() == NS_MEDIAWIKI
) {
260 return Title
::makeTitle( NS_MEDIAWIKI
, $wgContLang->ucfirst( $title->getText() ) );
263 # Quoted term? Try without the quotes...
265 if ( preg_match( '/^"([^"]+)"$/', $searchterm, $matches ) ) {
266 return SearchEngine
::getNearMatch( $matches[1] );
272 public static function legalSearchChars() {
273 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
277 * Set the maximum number of results to return
278 * and how many to skip before returning the first.
283 function setLimitOffset( $limit, $offset = 0 ) {
284 $this->limit
= intval( $limit );
285 $this->offset
= intval( $offset );
289 * Set which namespaces the search should include.
290 * Give an array of namespace index numbers.
292 * @param array $namespaces
294 function setNamespaces( $namespaces ) {
295 $this->namespaces
= $namespaces;
299 * Set whether the searcher should try to build a suggestion. Note: some searchers
300 * don't support building a suggestion in the first place and others don't respect
303 * @param bool $showSuggestion Should the searcher try to build suggestions
305 function setShowSuggestion( $showSuggestion ) {
306 $this->showSuggestion
= $showSuggestion;
310 * Parse some common prefixes: all (search everything)
313 * @param string $query
316 function replacePrefixes( $query ) {
320 if ( strpos( $query, ':' ) === false ) { // nothing to do
324 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
325 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
326 $this->namespaces
= null;
327 $parsed = substr( $query, strlen( $allkeyword ) );
328 } elseif ( strpos( $query, ':' ) !== false ) {
329 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
330 $index = $wgContLang->getNsIndex( $prefix );
331 if ( $index !== false ) {
332 $this->namespaces
= array( $index );
333 $parsed = substr( $query, strlen( $prefix ) +
1 );
336 if ( trim( $parsed ) == '' ) {
337 $parsed = $query; // prefix was the whole query
344 * Make a list of searchable namespaces and their canonical names.
347 public static function searchableNamespaces() {
350 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
351 if ( $ns >= NS_MAIN
) {
356 wfRunHooks( 'SearchableNamespaces', array( &$arr ) );
361 * Extract default namespaces to search from the given user's
362 * settings, returning a list of index numbers.
367 public static function userNamespaces( $user ) {
369 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
370 if ( $user->getOption( 'searchNs' . $ns ) ) {
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
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
404 * @param array $namespaces
407 public static function namespacesAsText( $namespaces ) {
410 $formatted = array_map( array( $wgContLang, 'getFormattedNsText' ), $namespaces );
411 foreach ( $formatted as $key => $ns ) {
412 if ( empty( $ns ) ) {
413 $formatted[$key] = wfMessage( 'blanknamespace' )->text();
420 * Load up the appropriate search engine class for the currently
421 * active database backend, and return a configured instance.
423 * @param string $type Type of search backend, if not the default
424 * @return SearchEngine
426 public static function create( $type = null ) {
427 global $wgSearchType;
430 $alternatives = self
::getSearchTypes();
432 if ( $type && in_array( $type, $alternatives ) ) {
434 } elseif ( $wgSearchType !== null ) {
435 $class = $wgSearchType;
437 $dbr = wfGetDB( DB_SLAVE
);
438 $class = $dbr->getSearchEngine();
441 $search = new $class( $dbr );
446 * Return the search engines we support. If only $wgSearchType
447 * is set, it'll be an array of just that one item.
451 public static function getSearchTypes() {
452 global $wgSearchType, $wgSearchTypeAlternatives;
454 $alternatives = $wgSearchTypeAlternatives ?
: array();
455 array_unshift( $alternatives, $wgSearchType );
457 return $alternatives;
461 * Create or update the search index record for the given page.
462 * Title and text should be pre-processed.
466 * @param string $title
467 * @param string $text
469 function update( $id, $title, $text ) {
474 * Update a search index record's title only.
475 * Title should be pre-processed.
479 * @param string $title
481 function updateTitle( $id, $title ) {
486 * Delete an indexed page
487 * Title should be pre-processed.
490 * @param int $id Page id that was deleted
491 * @param string $title Title of page that was deleted
493 function delete( $id, $title ) {
498 * Get OpenSearch suggestion template
502 public static function getOpenSearchTemplate() {
503 global $wgOpenSearchTemplate, $wgCanonicalServer;
505 if ( $wgOpenSearchTemplate ) {
506 return $wgOpenSearchTemplate;
508 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
513 return $wgCanonicalServer . wfScript( 'api' )
514 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
519 * Get the raw text for updating the index from a content object
520 * Nicer search backends could possibly do something cooler than
521 * just returning raw text
523 * @todo This isn't ideal, we'd really like to have content-specific handling here
524 * @param Title $t Title we're indexing
525 * @param Content $c Content of the page to index
528 public function getTextFromContent( Title
$t, Content
$c = null ) {
529 return $c ?
$c->getTextForSearchIndex() : '';
533 * If an implementation of SearchEngine handles all of its own text processing
534 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
535 * rather silly handling, it should return true here instead.
539 public function textAlreadyUpdatedForIndex() {
545 * Dummy class to be used when non-supported Database engine is present.
546 * @todo FIXME: Dummy class should probably try something at least mildly useful,
547 * such as a LIKE search through titles.
550 class SearchEngineDummy
extends SearchEngine
{