3 * Implements Special:Search
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
23 * @ingroup SpecialPage
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
30 class SpecialSearch
extends SpecialPage
{
32 * Current search profile. Search profile is just a name that identifies
33 * the active search tab on the search page (content, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
41 /** @var SearchEngine Search engine */
42 protected $searchEngine;
44 /** @var string Search engine type, if not default */
45 protected $searchEngineType;
47 /** @var array For links */
48 protected $extraParams = array();
51 * @var string The prefix url parameter. Set on the searcher and the
52 * is expected to treat it as prefix filter on titles.
59 protected $limit, $offset;
64 protected $namespaces;
74 protected $runSuggestion = true;
77 * Names of the wikis, in format: Interwiki prefix -> caption
80 protected $customCaptions;
82 const NAMESPACES_CURRENT
= 'sense';
84 public function __construct() {
85 parent
::__construct( 'Search' );
93 public function execute( $par ) {
95 $this->outputHeader();
96 $out = $this->getOutput();
97 $out->allowClickjacking();
98 $out->addModuleStyles( array(
99 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
100 'mediawiki.ui.input',
103 // Strip underscores from title parameter; most of the time we'll want
104 // text form here. But don't strip underscores from actual text params!
105 $titleParam = str_replace( '_', ' ', $par );
107 $request = $this->getRequest();
109 // Fetch the search term
110 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
113 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
114 $this->saveNamespaces();
115 // Remove the token from the URL to prevent the user from inadvertently
116 // exposing it (e.g. by pasting it into a public wiki page) or undoing
117 // later settings changes (e.g. by reloading the page).
118 $query = $request->getValues();
119 unset( $query['title'], $query['nsRemember'] );
120 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
124 $out->addJsConfigVars( array( 'searchTerm' => $search ) );
125 $this->searchEngineType
= $request->getVal( 'srbackend' );
127 if ( $request->getVal( 'fulltext' )
128 ||
!is_null( $request->getVal( 'offset' ) )
130 $this->showResults( $search );
132 $this->goResult( $search );
137 * Set up basic search parameters from the request and user settings.
139 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
141 public function load() {
142 $request = $this->getRequest();
143 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
144 $this->mPrefix
= $request->getVal( 'prefix', '' );
146 $user = $this->getUser();
148 # Extract manually requested namespaces
149 $nslist = $this->powerSearch( $request );
150 if ( !count( $nslist ) ) {
151 # Fallback to user preference
152 $nslist = SearchEngine
::userNamespaces( $user );
156 if ( !count( $nslist ) ) {
157 $profile = 'default';
160 $profile = $request->getVal( 'profile', $profile );
161 $profiles = $this->getSearchProfiles();
162 if ( $profile === null ) {
163 // BC with old request format
164 $profile = 'advanced';
165 foreach ( $profiles as $key => $data ) {
166 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
170 $this->namespaces
= $nslist;
171 } elseif ( $profile === 'advanced' ) {
172 $this->namespaces
= $nslist;
174 if ( isset( $profiles[$profile]['namespaces'] ) ) {
175 $this->namespaces
= $profiles[$profile]['namespaces'];
177 // Unknown profile requested
178 $profile = 'default';
179 $this->namespaces
= $profiles['default']['namespaces'];
183 $this->fulltext
= $request->getVal( 'fulltext' );
184 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
185 $this->profile
= $profile;
189 * If an exact title match can be found, jump straight ahead to it.
191 * @param string $term
193 public function goResult( $term ) {
194 $this->setupPage( $term );
195 # Try to go to page as entered.
196 $title = Title
::newFromText( $term );
197 # If the string cannot be used to create a title
198 if ( is_null( $title ) ) {
199 $this->showResults( $term );
203 # If there's an exact or very near match, jump right there.
204 $title = SearchEngine
::getNearMatch( $term );
206 if ( !is_null( $title ) ) {
207 $this->getOutput()->redirect( $title->getFullURL() );
211 # No match, generate an edit URL
212 $title = Title
::newFromText( $term );
213 if ( !is_null( $title ) ) {
214 Hooks
::run( 'SpecialSearchNogomatch', array( &$title ) );
216 $this->showResults( $term );
220 * @param string $term
222 public function showResults( $term ) {
225 $search = $this->getSearchEngine();
226 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
227 $search->setLimitOffset( $this->limit
, $this->offset
);
228 $search->setNamespaces( $this->namespaces
);
229 $search->prefix
= $this->mPrefix
;
230 $term = $search->transformSearchTerm( $term );
232 Hooks
::run( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
234 $this->setupPage( $term );
236 $out = $this->getOutput();
238 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
239 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
240 if ( $searchFowardUrl ) {
241 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
242 $out->redirect( $url );
245 Xml
::openElement( 'fieldset' ) .
246 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
249 array( 'class' => 'mw-searchdisabled' ),
250 $this->msg( 'searchdisabled' )->text()
252 $this->msg( 'googlesearch' )->rawParams(
253 htmlspecialchars( $term ),
255 $this->msg( 'searchbutton' )->escaped()
257 Xml
::closeElement( 'fieldset' )
264 $title = Title
::newFromText( $term );
265 $showSuggestion = $title === null ||
!$title->isKnown();
266 $search->setShowSuggestion( $showSuggestion );
268 // fetch search results
269 $rewritten = $search->replacePrefixes( $term );
271 $titleMatches = $search->searchTitle( $rewritten );
272 $textMatches = $search->searchText( $rewritten );
275 if ( $textMatches instanceof Status
) {
276 $textStatus = $textMatches;
280 // did you mean... suggestions
281 $didYouMeanHtml = '';
282 if ( $showSuggestion && $textMatches && !$textStatus ) {
283 if ( $textMatches->hasRewrittenQuery() ) {
284 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
285 } elseif ( $textMatches->hasSuggestion() ) {
286 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
290 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
291 # Hook requested termination
295 // start rendering the page
300 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
302 'action' => wfScript(),
307 // Get number of results
308 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
309 if ( $titleMatches ) {
310 $titleMatchesNum = $titleMatches->numRows();
311 $numTitleMatches = $titleMatches->getTotalHits();
313 if ( $textMatches ) {
314 $textMatchesNum = $textMatches->numRows();
315 $numTextMatches = $textMatches->getTotalHits();
317 $num = $titleMatchesNum +
$textMatchesNum;
318 $totalRes = $numTitleMatches +
$numTextMatches;
321 # This is an awful awful ID name. It's not a table, but we
322 # named it poorly from when this was a table so now we're
324 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
325 $this->shortDialog( $term, $num, $totalRes ) .
326 Xml
::closeElement( 'div' ) .
327 $this->searchProfileTabs( $term ) .
328 $this->searchOptions( $term ) .
329 Xml
::closeElement( 'form' ) .
333 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
334 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
335 // Empty query -- straight view of search form
339 $out->addHtml( "<div class='searchresults'>" );
343 if ( $num ||
$this->offset
) {
344 // Show the create link ahead
345 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
346 if ( $totalRes > $this->limit ||
$this->offset
) {
347 if ( $this->searchEngineType
!== null ) {
348 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
350 $prevnext = $this->getLanguage()->viewPrevNext(
351 $this->getPageTitle(),
354 $this->powerSearchOptions() +
array( 'search' => $term ),
355 $this->limit +
$this->offset
>= $totalRes
359 Hooks
::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
361 $out->parserOptions()->setEditSection( false );
362 if ( $titleMatches ) {
363 if ( $numTitleMatches > 0 ) {
364 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
365 $out->addHTML( $this->showMatches( $titleMatches ) );
367 $titleMatches->free();
369 if ( $textMatches && !$textStatus ) {
370 // output appropriate heading
371 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
372 // if no title matches the heading is redundant
373 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
377 if ( $numTextMatches > 0 ) {
378 $out->addHTML( $this->showMatches( $textMatches ) );
381 // show secondary interwiki results if any
382 if ( $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
383 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
384 SearchResultSet
::SECONDARY_RESULTS
), $term ) );
387 $textMatches->free();
390 $hasOtherResults = $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
394 $out->addHTML( '<div class="error">' .
395 $textStatus->getMessage( 'search-error' ) . '</div>' );
397 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
398 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
399 array( $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
400 wfEscapeWikiText( $term )
405 if ( $hasOtherResults ) {
406 foreach ( $textMatches->getInterwikiResults( SearchResultSet
::INLINE_RESULTS
)
407 as $interwiki => $interwikiResult ) {
408 if ( $interwikiResult instanceof Status ||
$interwikiResult->numRows() == 0 ) {
409 // ignore bad interwikis for now
413 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
417 $out->addHTML( '<div class="visualClear"></div>' );
420 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
423 $out->addHtml( "</div>" );
425 Hooks
::run( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
430 * Produce wiki header for interwiki results
431 * @param string $interwiki Interwiki name
432 * @param SearchResultSet $interwikiResult The result set
434 protected function interwikiHeader( $interwiki, $interwikiResult ) {
435 // TODO: we need to figure out how to name wikis correctly
436 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
437 return "<p class=\"mw-search-interwiki-header\">\n$wikiMsg</p>";
441 * Decide if the suggested query should be run, and it's results returned
442 * instead of the provided $textMatches
444 * @param SearchResultSet $textMatches The results of a users query
447 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
448 if ( !$this->runSuggestion ||
449 !$textMatches->hasSuggestion() ||
450 $textMatches->numRows() > 0 ||
451 $textMatches->searchContainedSyntax()
456 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
460 * Generates HTML shown to the user when we have a suggestion about a query
461 * that might give more results than their current query.
463 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
464 # mirror Go/Search behavior of original request ..
465 $params = array( 'search' => $textMatches->getSuggestionQuery() );
466 if ( $this->fulltext
!= null ) {
467 $params['fulltext'] = $this->fulltext
;
469 $stParams = array_merge( $params, $this->powerSearchOptions() );
471 $suggest = Linker
::linkKnown(
472 $this->getPageTitle(),
473 $textMatches->getSuggestionSnippet() ?
: null,
474 array( 'id' => 'mw-search-DYM-suggestion' ),
478 # HTML of did you mean... search suggestion link
479 return Html
::rawElement(
481 array( 'class' => 'searchdidyoumean' ),
482 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
487 * Generates HTML shown to user when their query has been internally rewritten,
488 * and the results of the rewritten query are being returned.
490 * @param string $term The users search input
491 * @param SearchResultSet $textMatches The response to the users initial search request
492 * @return string HTML linking the user to their original $term query, and the one
493 * suggested by $textMatches.
495 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
496 // Showing results for '$rewritten'
497 // Search instead for '$orig'
499 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
500 if ( $this->fulltext
!= null ) {
501 $params['fulltext'] = $this->fulltext
;
503 $stParams = array_merge( $params, $this->powerSearchOptions() );
505 $rewritten = Linker
::linkKnown(
506 $this->getPageTitle(),
507 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
508 array( 'id' => 'mw-search-DYM-rewritten' ),
512 $stParams['search'] = $term;
513 $stParams['runsuggestion'] = 0;
514 $original = Linker
::linkKnown(
515 $this->getPageTitle(),
516 htmlspecialchars( $term ),
517 array( 'id' => 'mw-search-DYM-original' ),
521 return Html
::rawElement(
523 array( 'class' => 'searchdidyoumean' ),
524 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
529 * @param Title $title
530 * @param int $num The number of search results found
531 * @param null|SearchResultSet $titleMatches Results from title search
532 * @param null|SearchResultSet $textMatches Results from text search
534 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
535 // show direct page/create link if applicable
537 // Check DBkey !== '' in case of fragment link only.
538 if ( is_null( $title ) ||
$title->getDBkey() === ''
539 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
540 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
543 // preserve the paragraph for margins etc...
544 $this->getOutput()->addHtml( '<p></p>' );
549 $messageName = 'searchmenu-new-nocreate';
550 $linkClass = 'mw-search-createlink';
552 if ( !$title->isExternal() ) {
553 if ( $title->isKnown() ) {
554 $messageName = 'searchmenu-exists';
555 $linkClass = 'mw-search-exists';
556 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
557 $messageName = 'searchmenu-new';
563 wfEscapeWikiText( $title->getPrefixedText() ),
564 Message
::numParam( $num )
566 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
568 // Extensions using the hook might still return an empty $messageName
569 if ( $messageName ) {
570 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
572 // preserve the paragraph for margins etc...
573 $this->getOutput()->addHtml( '<p></p>' );
578 * @param string $term
580 protected function setupPage( $term ) {
581 $out = $this->getOutput();
582 if ( strval( $term ) !== '' ) {
583 $out->setPageTitle( $this->msg( 'searchresults' ) );
584 $out->setHTMLTitle( $this->msg( 'pagetitle' )
585 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
586 ->inContentLanguage()->text()
589 // add javascript specific to special:search
590 $out->addModules( 'mediawiki.special.search' );
594 * Return true if current search is a power (advanced) search
598 protected function isPowerSearch() {
599 return $this->profile
=== 'advanced';
603 * Extract "power search" namespace settings from the request object,
604 * returning a list of index numbers to search.
606 * @param WebRequest $request
609 protected function powerSearch( &$request ) {
611 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
612 if ( $request->getCheck( 'ns' . $ns ) ) {
621 * Reconstruct the 'power search' options for links
625 protected function powerSearchOptions() {
627 if ( !$this->isPowerSearch() ) {
628 $opt['profile'] = $this->profile
;
630 foreach ( $this->namespaces
as $n ) {
635 return $opt +
$this->extraParams
;
639 * Save namespace preferences when we're supposed to
641 * @return bool Whether we wrote something
643 protected function saveNamespaces() {
644 $user = $this->getUser();
645 $request = $this->getRequest();
647 if ( $user->isLoggedIn() &&
648 $user->matchEditToken(
649 $request->getVal( 'nsRemember' ),
654 // Reset namespace preferences: namespaces are not searched
655 // when they're not mentioned in the URL parameters.
656 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
657 $user->setOption( 'searchNs' . $n, false );
659 // The request parameters include all the namespaces to be searched.
660 // Even if they're the same as an existing profile, they're not eaten.
661 foreach ( $this->namespaces
as $n ) {
662 $user->setOption( 'searchNs' . $n, true );
665 $user->saveSettings();
673 * Show whole set of results
675 * @param SearchResultSet $matches
676 * @param string $interwiki Interwiki name
680 protected function showMatches( &$matches, $interwiki = null ) {
683 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
685 $result = $matches->next();
686 $pos = $this->offset
;
688 if ( $result && $interwiki ) {
689 $out .= $this->interwikiHeader( $interwiki, $result );
692 $out .= "<ul class='mw-search-results'>\n";
694 $out .= $this->showHit( $result, $terms, ++
$pos );
695 $result = $matches->next();
699 // convert the whole thing to desired language variant
700 $out = $wgContLang->convert( $out );
706 * Format a single hit result
708 * @param SearchResult $result
709 * @param array $terms Terms to highlight
710 * @param int $position Position within the search results, including offset.
714 protected function showHit( $result, $terms, $position ) {
716 if ( $result->isBrokenTitle() ) {
720 $title = $result->getTitle();
722 $titleSnippet = $result->getTitleSnippet();
724 if ( $titleSnippet == '' ) {
725 $titleSnippet = null;
728 $link_t = clone $title;
731 Hooks
::run( 'ShowSearchHitTitle',
732 array( &$link_t, &$titleSnippet, $result, $terms, $this, &$query ) );
734 $link = Linker
::linkKnown(
737 array( 'data-serp-pos' => $position ), // HTML attributes
741 // If page content is not readable, just return the title.
742 // This is not quite safe, but better than showing excerpts from non-readable pages
743 // Note that hiding the entry entirely would screw up paging.
744 if ( !$title->userCan( 'read', $this->getUser() ) ) {
745 return "<li>{$link}</li>\n";
748 // If the page doesn't *exist*... our search index is out of date.
749 // The least confusing at this point is to drop the result.
750 // You may get less results, but... oh well. :P
751 if ( $result->isMissingRevision() ) {
755 // format redirects / relevant sections
756 $redirectTitle = $result->getRedirectTitle();
757 $redirectText = $result->getRedirectSnippet();
758 $sectionTitle = $result->getSectionTitle();
759 $sectionText = $result->getSectionSnippet();
760 $categorySnippet = $result->getCategorySnippet();
763 if ( !is_null( $redirectTitle ) ) {
764 if ( $redirectText == '' ) {
765 $redirectText = null;
768 $redirect = "<span class='searchalttitle'>" .
769 $this->msg( 'search-redirect' )->rawParams(
770 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
775 if ( !is_null( $sectionTitle ) ) {
776 if ( $sectionText == '' ) {
780 $section = "<span class='searchalttitle'>" .
781 $this->msg( 'search-section' )->rawParams(
782 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
787 if ( $categorySnippet ) {
788 $category = "<span class='searchalttitle'>" .
789 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
793 // format text extract
794 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
796 $lang = $this->getLanguage();
798 // format description
799 $byteSize = $result->getByteSize();
800 $wordCount = $result->getWordCount();
801 $timestamp = $result->getTimestamp();
802 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
803 ->numParams( $wordCount )->escaped();
805 if ( $title->getNamespace() == NS_CATEGORY
) {
806 $cat = Category
::newFromTitle( $title );
807 $size = $this->msg( 'search-result-category-size' )
808 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
812 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
815 // Include a thumbnail for media files...
816 if ( $title->getNamespace() == NS_FILE
) {
817 $img = $result->getFile();
818 $img = $img ?
: wfFindFile( $title );
819 if ( $result->isFileMatch() ) {
820 $fileMatch = "<span class='searchalttitle'>" .
821 $this->msg( 'search-file-match' )->escaped() . "</span>";
824 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
826 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
827 // Float doesn't seem to interact well with the bullets.
828 // Table messes up vertical alignment of the bullets.
829 // Bullets are therefore disabled (didn't look great anyway).
831 '<table class="searchResultImage">' .
833 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
834 $thumb->toHtml( array( 'desc-link' => true ) ) .
836 '<td style="vertical-align: top;">' .
837 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
839 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
851 if ( Hooks
::run( 'ShowSearchHit', array(
852 $this, $result, $terms,
853 &$link, &$redirect, &$section, &$extract,
854 &$score, &$size, &$date, &$related,
857 $html = "<li><div class='mw-search-result-heading'>" .
858 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
859 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
867 * Extract custom captions from search-interwiki-custom message
869 protected function getCustomCaptions() {
870 if ( is_null( $this->customCaptions
) ) {
871 $this->customCaptions
= array();
872 // format per line <iwprefix>:<caption>
873 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
874 foreach ( $customLines as $line ) {
875 $parts = explode( ":", $line, 2 );
876 if ( count( $parts ) == 2 ) { // validate line
877 $this->customCaptions
[$parts[0]] = $parts[1];
884 * Show results from other wikis
886 * @param SearchResultSet|array $matches
887 * @param string $query
891 protected function showInterwiki( $matches, $query ) {
894 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
895 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
896 $out .= "<ul class='mw-search-iwresults'>\n";
898 // work out custom project captions
899 $this->getCustomCaptions();
901 if ( !is_array( $matches ) ) {
902 $matches = array( $matches );
905 foreach ( $matches as $set ) {
907 $result = $set->next();
909 $out .= $this->showInterwikiHit( $result, $prev, $query );
910 $prev = $result->getInterwikiPrefix();
911 $result = $set->next();
915 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
916 $out .= "</ul></div>\n";
918 // convert the whole thing to desired language variant
919 $out = $wgContLang->convert( $out );
925 * Show single interwiki link
927 * @param SearchResult $result
928 * @param string $lastInterwiki
929 * @param string $query
933 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
935 if ( $result->isBrokenTitle() ) {
939 $title = $result->getTitle();
941 $titleSnippet = $result->getTitleSnippet();
943 if ( $titleSnippet == '' ) {
944 $titleSnippet = null;
947 $link = Linker
::linkKnown(
952 // format redirect if any
953 $redirectTitle = $result->getRedirectTitle();
954 $redirectText = $result->getRedirectSnippet();
956 if ( !is_null( $redirectTitle ) ) {
957 if ( $redirectText == '' ) {
958 $redirectText = null;
961 $redirect = "<span class='searchalttitle'>" .
962 $this->msg( 'search-redirect' )->rawParams(
963 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
968 // display project name
969 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
970 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions
) ) {
971 // captions from 'search-interwiki-custom'
972 $caption = $this->customCaptions
[$title->getInterwiki()];
974 // default is to show the hostname of the other wiki which might suck
975 // if there are many wikis on one hostname
976 $parsed = wfParseUrl( $title->getFullURL() );
977 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
979 // "more results" link (special page stuff could be localized, but we might not know target lang)
980 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
981 $searchLink = Linker
::linkKnown(
983 $this->msg( 'search-interwiki-more' )->text(),
987 'fulltext' => 'Search'
990 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
991 {$searchLink}</span>{$caption}</div>\n<ul>";
994 $out .= "<li>{$link} {$redirect}</li>\n";
1000 * Generates the power search box at [[Special:Search]]
1002 * @param string $term Search term
1003 * @param array $opts
1004 * @return string HTML form
1006 protected function powerSearchBox( $term, $opts ) {
1009 // Groups namespaces into rows according to subject
1011 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
1012 $subject = MWNamespace
::getSubject( $namespace );
1013 if ( !array_key_exists( $subject, $rows ) ) {
1014 $rows[$subject] = "";
1017 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1018 if ( $name == '' ) {
1019 $name = $this->msg( 'blanknamespace' )->text();
1023 Xml
::openElement( 'td' ) .
1027 "mw-search-ns{$namespace}",
1028 in_array( $namespace, $this->namespaces
)
1030 Xml
::closeElement( 'td' );
1033 $rows = array_values( $rows );
1034 $numRows = count( $rows );
1036 // Lays out namespaces in multiple floating two-column tables so they'll
1037 // be arranged nicely while still accommodating different screen widths
1038 $namespaceTables = '';
1039 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
1040 $namespaceTables .= Xml
::openElement( 'table' );
1042 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
1043 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
1046 $namespaceTables .= Xml
::closeElement( 'table' );
1049 $showSections = array( 'namespaceTables' => $namespaceTables );
1051 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1054 foreach ( $opts as $key => $value ) {
1055 $hidden .= Html
::hidden( $key, $value );
1058 # Stuff to feed saveNamespaces()
1060 $user = $this->getUser();
1061 if ( $user->isLoggedIn() ) {
1062 $remember .= Xml
::checkLabel(
1063 $this->msg( 'powersearch-remember' )->text(),
1065 'mw-search-powersearch-remember',
1067 // The token goes here rather than in a hidden field so it
1068 // is only sent when necessary (not every form submission).
1069 array( 'value' => $user->getEditToken(
1076 // Return final output
1077 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1078 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1079 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1080 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1081 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1082 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1084 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1086 Xml
::closeElement( 'fieldset' );
1092 protected function getSearchProfiles() {
1093 // Builds list of Search Types (profiles)
1094 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1098 'message' => 'searchprofile-articles',
1099 'tooltip' => 'searchprofile-articles-tooltip',
1100 'namespaces' => SearchEngine
::defaultNamespaces(),
1101 'namespace-messages' => SearchEngine
::namespacesAsText(
1102 SearchEngine
::defaultNamespaces()
1106 'message' => 'searchprofile-images',
1107 'tooltip' => 'searchprofile-images-tooltip',
1108 'namespaces' => array( NS_FILE
),
1111 'message' => 'searchprofile-everything',
1112 'tooltip' => 'searchprofile-everything-tooltip',
1113 'namespaces' => $nsAllSet,
1115 'advanced' => array(
1116 'message' => 'searchprofile-advanced',
1117 'tooltip' => 'searchprofile-advanced-tooltip',
1118 'namespaces' => self
::NAMESPACES_CURRENT
,
1122 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
1124 foreach ( $profiles as &$data ) {
1125 if ( !is_array( $data['namespaces'] ) ) {
1128 sort( $data['namespaces'] );
1135 * @param string $term
1138 protected function searchProfileTabs( $term ) {
1139 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1142 if ( $this->startsWithImage( $term ) ) {
1144 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1147 $profiles = $this->getSearchProfiles();
1148 $lang = $this->getLanguage();
1150 // Outputs XML for Search Types
1151 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1152 $out .= Xml
::openElement( 'ul' );
1153 foreach ( $profiles as $id => $profile ) {
1154 if ( !isset( $profile['parameters'] ) ) {
1155 $profile['parameters'] = array();
1157 $profile['parameters']['profile'] = $id;
1159 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1160 $lang->commaList( $profile['namespace-messages'] ) : null;
1164 'class' => $this->profile
=== $id ?
'current' : 'normal'
1166 $this->makeSearchLink(
1169 $this->msg( $profile['message'] )->text(),
1170 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1171 $profile['parameters']
1175 $out .= Xml
::closeElement( 'ul' );
1176 $out .= Xml
::closeElement( 'div' );
1177 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1178 $out .= Xml
::closeElement( 'div' );
1184 * @param string $term Search term
1187 protected function searchOptions( $term ) {
1190 $opts['profile'] = $this->profile
;
1192 if ( $this->isPowerSearch() ) {
1193 $out .= $this->powerSearchBox( $term, $opts );
1196 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1204 * @param string $term
1205 * @param int $resultsShown
1206 * @param int $totalNum
1209 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1210 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1211 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1213 $out .= Html
::input( 'search', $term, 'search', array(
1214 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1216 'autofocus' => trim( $term ) === '',
1217 'class' => 'mw-ui-input mw-ui-input-inline',
1219 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1220 $out .= Html
::submitButton(
1221 $this->msg( 'searchbutton' )->text(),
1222 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1223 array( 'mw-ui-progressive' )
1227 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1228 $top = $this->msg( 'search-showingresults' )
1229 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1230 ->numParams( $resultsShown )
1232 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1233 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1240 * Make a search link with some target namespaces
1242 * @param string $term
1243 * @param array $namespaces Ignored
1244 * @param string $label Link's text
1245 * @param string $tooltip Link's tooltip
1246 * @param array $params Query string parameters
1247 * @return string HTML fragment
1249 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1251 foreach ( $namespaces as $n ) {
1252 $opt['ns' . $n] = 1;
1255 $stParams = array_merge(
1258 'fulltext' => $this->msg( 'search' )->text()
1263 return Xml
::element(
1266 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1274 * Check if query starts with image: prefix
1276 * @param string $term The string to check
1279 protected function startsWithImage( $term ) {
1282 $parts = explode( ':', $term );
1283 if ( count( $parts ) > 1 ) {
1284 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1291 * Check if query starts with all: prefix
1293 * @param string $term The string to check
1296 protected function startsWithAll( $term ) {
1298 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1300 $parts = explode( ':', $term );
1301 if ( count( $parts ) > 1 ) {
1302 return $parts[0] == $allkeyword;
1311 * @return SearchEngine
1313 public function getSearchEngine() {
1314 if ( $this->searchEngine
=== null ) {
1315 $this->searchEngine
= $this->searchEngineType ?
1316 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1319 return $this->searchEngine
;
1323 * Current search profile.
1324 * @return null|string
1326 function getProfile() {
1327 return $this->profile
;
1331 * Current namespaces.
1334 function getNamespaces() {
1335 return $this->namespaces
;
1339 * Users of hook SpecialSearchSetupEngine can use this to
1340 * add more params to links to not lose selection when
1341 * user navigates search results.
1344 * @param string $key
1345 * @param mixed $value
1347 public function setExtraParam( $key, $value ) {
1348 $this->extraParams
[$key] = $value;
1351 protected function getGroupName() {