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',
102 $this->addHelpLink( 'Help:Searching' );
104 // Strip underscores from title parameter; most of the time we'll want
105 // text form here. But don't strip underscores from actual text params!
106 $titleParam = str_replace( '_', ' ', $par );
108 $request = $this->getRequest();
110 // Fetch the search term
111 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
114 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
115 $this->saveNamespaces();
116 // Remove the token from the URL to prevent the user from inadvertently
117 // exposing it (e.g. by pasting it into a public wiki page) or undoing
118 // later settings changes (e.g. by reloading the page).
119 $query = $request->getValues();
120 unset( $query['title'], $query['nsRemember'] );
121 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
125 $out->addJsConfigVars( array( 'searchTerm' => $search ) );
126 $this->searchEngineType
= $request->getVal( 'srbackend' );
128 if ( $request->getVal( 'fulltext' )
129 ||
!is_null( $request->getVal( 'offset' ) )
131 $this->showResults( $search );
133 $this->goResult( $search );
138 * Set up basic search parameters from the request and user settings.
140 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
142 public function load() {
143 $request = $this->getRequest();
144 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
145 $this->mPrefix
= $request->getVal( 'prefix', '' );
147 $user = $this->getUser();
149 # Extract manually requested namespaces
150 $nslist = $this->powerSearch( $request );
151 if ( !count( $nslist ) ) {
152 # Fallback to user preference
153 $nslist = SearchEngine
::userNamespaces( $user );
157 if ( !count( $nslist ) ) {
158 $profile = 'default';
161 $profile = $request->getVal( 'profile', $profile );
162 $profiles = $this->getSearchProfiles();
163 if ( $profile === null ) {
164 // BC with old request format
165 $profile = 'advanced';
166 foreach ( $profiles as $key => $data ) {
167 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
171 $this->namespaces
= $nslist;
172 } elseif ( $profile === 'advanced' ) {
173 $this->namespaces
= $nslist;
175 if ( isset( $profiles[$profile]['namespaces'] ) ) {
176 $this->namespaces
= $profiles[$profile]['namespaces'];
178 // Unknown profile requested
179 $profile = 'default';
180 $this->namespaces
= $profiles['default']['namespaces'];
184 $this->fulltext
= $request->getVal( 'fulltext' );
185 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
186 $this->profile
= $profile;
190 * If an exact title match can be found, jump straight ahead to it.
192 * @param string $term
194 public function goResult( $term ) {
195 $this->setupPage( $term );
196 # Try to go to page as entered.
197 $title = Title
::newFromText( $term );
198 # If the string cannot be used to create a title
199 if ( is_null( $title ) ) {
200 $this->showResults( $term );
204 # If there's an exact or very near match, jump right there.
205 $title = SearchEngine
::getNearMatch( $term );
207 if ( !is_null( $title ) ) {
208 $this->getOutput()->redirect( $title->getFullURL() );
212 # No match, generate an edit URL
213 $title = Title
::newFromText( $term );
214 if ( !is_null( $title ) ) {
215 Hooks
::run( 'SpecialSearchNogomatch', array( &$title ) );
217 $this->showResults( $term );
221 * @param string $term
223 public function showResults( $term ) {
226 $search = $this->getSearchEngine();
227 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
228 $search->setLimitOffset( $this->limit
, $this->offset
);
229 $search->setNamespaces( $this->namespaces
);
230 $search->prefix
= $this->mPrefix
;
231 $term = $search->transformSearchTerm( $term );
233 Hooks
::run( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
235 $this->setupPage( $term );
237 $out = $this->getOutput();
239 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
240 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
241 if ( $searchFowardUrl ) {
242 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
243 $out->redirect( $url );
246 Xml
::openElement( 'fieldset' ) .
247 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
250 array( 'class' => 'mw-searchdisabled' ),
251 $this->msg( 'searchdisabled' )->text()
253 $this->msg( 'googlesearch' )->rawParams(
254 htmlspecialchars( $term ),
256 $this->msg( 'searchbutton' )->escaped()
258 Xml
::closeElement( 'fieldset' )
265 $title = Title
::newFromText( $term );
266 $showSuggestion = $title === null ||
!$title->isKnown();
267 $search->setShowSuggestion( $showSuggestion );
269 // fetch search results
270 $rewritten = $search->replacePrefixes( $term );
272 $titleMatches = $search->searchTitle( $rewritten );
273 $textMatches = $search->searchText( $rewritten );
276 if ( $textMatches instanceof Status
) {
277 $textStatus = $textMatches;
281 // did you mean... suggestions
282 $didYouMeanHtml = '';
283 if ( $showSuggestion && $textMatches && !$textStatus ) {
284 if ( $textMatches->hasRewrittenQuery() ) {
285 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
286 } elseif ( $textMatches->hasSuggestion() ) {
287 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
291 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
292 # Hook requested termination
296 // start rendering the page
301 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
303 'action' => wfScript(),
308 // Get number of results
309 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
310 if ( $titleMatches ) {
311 $titleMatchesNum = $titleMatches->numRows();
312 $numTitleMatches = $titleMatches->getTotalHits();
314 if ( $textMatches ) {
315 $textMatchesNum = $textMatches->numRows();
316 $numTextMatches = $textMatches->getTotalHits();
318 $num = $titleMatchesNum +
$textMatchesNum;
319 $totalRes = $numTitleMatches +
$numTextMatches;
322 # This is an awful awful ID name. It's not a table, but we
323 # named it poorly from when this was a table so now we're
325 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
326 $this->shortDialog( $term, $num, $totalRes ) .
327 Xml
::closeElement( 'div' ) .
328 $this->searchProfileTabs( $term ) .
329 $this->searchOptions( $term ) .
330 Xml
::closeElement( 'form' ) .
334 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
335 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
336 // Empty query -- straight view of search form
340 $out->addHtml( "<div class='searchresults'>" );
344 if ( $num ||
$this->offset
) {
345 // Show the create link ahead
346 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
347 if ( $totalRes > $this->limit ||
$this->offset
) {
348 if ( $this->searchEngineType
!== null ) {
349 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
351 $prevnext = $this->getLanguage()->viewPrevNext(
352 $this->getPageTitle(),
355 $this->powerSearchOptions() +
array( 'search' => $term ),
356 $this->limit +
$this->offset
>= $totalRes
360 Hooks
::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
362 $out->parserOptions()->setEditSection( false );
363 if ( $titleMatches ) {
364 if ( $numTitleMatches > 0 ) {
365 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
366 $out->addHTML( $this->showMatches( $titleMatches ) );
368 $titleMatches->free();
370 if ( $textMatches && !$textStatus ) {
371 // output appropriate heading
372 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
373 // if no title matches the heading is redundant
374 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
378 if ( $numTextMatches > 0 ) {
379 $out->addHTML( $this->showMatches( $textMatches ) );
382 // show secondary interwiki results if any
383 if ( $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
384 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
385 SearchResultSet
::SECONDARY_RESULTS
), $term ) );
388 $textMatches->free();
391 $hasOtherResults = $textMatches &&
392 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
396 $out->addHTML( '<div class="error">' .
397 $textStatus->getMessage( 'search-error' ) . '</div>' );
399 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
400 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
401 array( $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
402 wfEscapeWikiText( $term )
407 if ( $hasOtherResults ) {
408 foreach ( $textMatches->getInterwikiResults( SearchResultSet
::INLINE_RESULTS
)
409 as $interwiki => $interwikiResult ) {
410 if ( $interwikiResult instanceof Status ||
$interwikiResult->numRows() == 0 ) {
411 // ignore bad interwikis for now
415 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
419 $out->addHTML( '<div class="visualClear"></div>' );
422 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
425 $out->addHtml( "</div>" );
427 Hooks
::run( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
432 * Produce wiki header for interwiki results
433 * @param string $interwiki Interwiki name
434 * @param SearchResultSet $interwikiResult The result set
436 protected function interwikiHeader( $interwiki, $interwikiResult ) {
437 // TODO: we need to figure out how to name wikis correctly
438 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
439 return "<p class=\"mw-search-interwiki-header\">\n$wikiMsg</p>";
443 * Decide if the suggested query should be run, and it's results returned
444 * instead of the provided $textMatches
446 * @param SearchResultSet $textMatches The results of a users query
449 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
450 if ( !$this->runSuggestion ||
451 !$textMatches->hasSuggestion() ||
452 $textMatches->numRows() > 0 ||
453 $textMatches->searchContainedSyntax()
458 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
462 * Generates HTML shown to the user when we have a suggestion about a query
463 * that might give more results than their current query.
465 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
466 # mirror Go/Search behavior of original request ..
467 $params = array( 'search' => $textMatches->getSuggestionQuery() );
468 if ( $this->fulltext
!= null ) {
469 $params['fulltext'] = $this->fulltext
;
471 $stParams = array_merge( $params, $this->powerSearchOptions() );
473 $suggest = Linker
::linkKnown(
474 $this->getPageTitle(),
475 $textMatches->getSuggestionSnippet() ?
: null,
476 array( 'id' => 'mw-search-DYM-suggestion' ),
480 # HTML of did you mean... search suggestion link
481 return Html
::rawElement(
483 array( 'class' => 'searchdidyoumean' ),
484 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
489 * Generates HTML shown to user when their query has been internally rewritten,
490 * and the results of the rewritten query are being returned.
492 * @param string $term The users search input
493 * @param SearchResultSet $textMatches The response to the users initial search request
494 * @return string HTML linking the user to their original $term query, and the one
495 * suggested by $textMatches.
497 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
498 // Showing results for '$rewritten'
499 // Search instead for '$orig'
501 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
502 if ( $this->fulltext
!= null ) {
503 $params['fulltext'] = $this->fulltext
;
505 $stParams = array_merge( $params, $this->powerSearchOptions() );
507 $rewritten = Linker
::linkKnown(
508 $this->getPageTitle(),
509 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
510 array( 'id' => 'mw-search-DYM-rewritten' ),
514 $stParams['search'] = $term;
515 $stParams['runsuggestion'] = 0;
516 $original = Linker
::linkKnown(
517 $this->getPageTitle(),
518 htmlspecialchars( $term ),
519 array( 'id' => 'mw-search-DYM-original' ),
523 return Html
::rawElement(
525 array( 'class' => 'searchdidyoumean' ),
526 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
531 * @param Title $title
532 * @param int $num The number of search results found
533 * @param null|SearchResultSet $titleMatches Results from title search
534 * @param null|SearchResultSet $textMatches Results from text search
536 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
537 // show direct page/create link if applicable
539 // Check DBkey !== '' in case of fragment link only.
540 if ( is_null( $title ) ||
$title->getDBkey() === ''
541 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
542 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
545 // preserve the paragraph for margins etc...
546 $this->getOutput()->addHtml( '<p></p>' );
551 $messageName = 'searchmenu-new-nocreate';
552 $linkClass = 'mw-search-createlink';
554 if ( !$title->isExternal() ) {
555 if ( $title->isKnown() ) {
556 $messageName = 'searchmenu-exists';
557 $linkClass = 'mw-search-exists';
558 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
559 $messageName = 'searchmenu-new';
565 wfEscapeWikiText( $title->getPrefixedText() ),
566 Message
::numParam( $num )
568 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
570 // Extensions using the hook might still return an empty $messageName
571 if ( $messageName ) {
572 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
574 // preserve the paragraph for margins etc...
575 $this->getOutput()->addHtml( '<p></p>' );
580 * @param string $term
582 protected function setupPage( $term ) {
583 $out = $this->getOutput();
584 if ( strval( $term ) !== '' ) {
585 $out->setPageTitle( $this->msg( 'searchresults' ) );
586 $out->setHTMLTitle( $this->msg( 'pagetitle' )
587 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
588 ->inContentLanguage()->text()
591 // add javascript specific to special:search
592 $out->addModules( 'mediawiki.special.search' );
596 * Return true if current search is a power (advanced) search
600 protected function isPowerSearch() {
601 return $this->profile
=== 'advanced';
605 * Extract "power search" namespace settings from the request object,
606 * returning a list of index numbers to search.
608 * @param WebRequest $request
611 protected function powerSearch( &$request ) {
613 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
614 if ( $request->getCheck( 'ns' . $ns ) ) {
623 * Reconstruct the 'power search' options for links
627 protected function powerSearchOptions() {
629 if ( !$this->isPowerSearch() ) {
630 $opt['profile'] = $this->profile
;
632 foreach ( $this->namespaces
as $n ) {
637 return $opt +
$this->extraParams
;
641 * Save namespace preferences when we're supposed to
643 * @return bool Whether we wrote something
645 protected function saveNamespaces() {
646 $user = $this->getUser();
647 $request = $this->getRequest();
649 if ( $user->isLoggedIn() &&
650 $user->matchEditToken(
651 $request->getVal( 'nsRemember' ),
656 // Reset namespace preferences: namespaces are not searched
657 // when they're not mentioned in the URL parameters.
658 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
659 $user->setOption( 'searchNs' . $n, false );
661 // The request parameters include all the namespaces to be searched.
662 // Even if they're the same as an existing profile, they're not eaten.
663 foreach ( $this->namespaces
as $n ) {
664 $user->setOption( 'searchNs' . $n, true );
667 $user->saveSettings();
675 * Show whole set of results
677 * @param SearchResultSet $matches
678 * @param string $interwiki Interwiki name
682 protected function showMatches( &$matches, $interwiki = null ) {
685 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
687 $result = $matches->next();
688 $pos = $this->offset
;
690 if ( $result && $interwiki ) {
691 $out .= $this->interwikiHeader( $interwiki, $result );
694 $out .= "<ul class='mw-search-results'>\n";
696 $out .= $this->showHit( $result, $terms, ++
$pos );
697 $result = $matches->next();
701 // convert the whole thing to desired language variant
702 $out = $wgContLang->convert( $out );
708 * Format a single hit result
710 * @param SearchResult $result
711 * @param array $terms Terms to highlight
712 * @param int $position Position within the search results, including offset.
716 protected function showHit( $result, $terms, $position ) {
718 if ( $result->isBrokenTitle() ) {
722 $title = $result->getTitle();
724 $titleSnippet = $result->getTitleSnippet();
726 if ( $titleSnippet == '' ) {
727 $titleSnippet = null;
730 $link_t = clone $title;
733 Hooks
::run( 'ShowSearchHitTitle',
734 array( &$link_t, &$titleSnippet, $result, $terms, $this, &$query ) );
736 $link = Linker
::linkKnown(
739 array( 'data-serp-pos' => $position ), // HTML attributes
743 // If page content is not readable, just return the title.
744 // This is not quite safe, but better than showing excerpts from non-readable pages
745 // Note that hiding the entry entirely would screw up paging.
746 if ( !$title->userCan( 'read', $this->getUser() ) ) {
747 return "<li>{$link}</li>\n";
750 // If the page doesn't *exist*... our search index is out of date.
751 // The least confusing at this point is to drop the result.
752 // You may get less results, but... oh well. :P
753 if ( $result->isMissingRevision() ) {
757 // format redirects / relevant sections
758 $redirectTitle = $result->getRedirectTitle();
759 $redirectText = $result->getRedirectSnippet();
760 $sectionTitle = $result->getSectionTitle();
761 $sectionText = $result->getSectionSnippet();
762 $categorySnippet = $result->getCategorySnippet();
765 if ( !is_null( $redirectTitle ) ) {
766 if ( $redirectText == '' ) {
767 $redirectText = null;
770 $redirect = "<span class='searchalttitle'>" .
771 $this->msg( 'search-redirect' )->rawParams(
772 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
777 if ( !is_null( $sectionTitle ) ) {
778 if ( $sectionText == '' ) {
782 $section = "<span class='searchalttitle'>" .
783 $this->msg( 'search-section' )->rawParams(
784 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
789 if ( $categorySnippet ) {
790 $category = "<span class='searchalttitle'>" .
791 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
795 // format text extract
796 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
798 $lang = $this->getLanguage();
800 // format description
801 $byteSize = $result->getByteSize();
802 $wordCount = $result->getWordCount();
803 $timestamp = $result->getTimestamp();
804 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
805 ->numParams( $wordCount )->escaped();
807 if ( $title->getNamespace() == NS_CATEGORY
) {
808 $cat = Category
::newFromTitle( $title );
809 $size = $this->msg( 'search-result-category-size' )
810 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
814 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
817 // Include a thumbnail for media files...
818 if ( $title->getNamespace() == NS_FILE
) {
819 $img = $result->getFile();
820 $img = $img ?
: wfFindFile( $title );
821 if ( $result->isFileMatch() ) {
822 $fileMatch = "<span class='searchalttitle'>" .
823 $this->msg( 'search-file-match' )->escaped() . "</span>";
826 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
828 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
829 // Float doesn't seem to interact well with the bullets.
830 // Table messes up vertical alignment of the bullets.
831 // Bullets are therefore disabled (didn't look great anyway).
833 '<table class="searchResultImage">' .
835 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
836 $thumb->toHtml( array( 'desc-link' => true ) ) .
838 '<td style="vertical-align: top;">' .
839 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
841 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
853 if ( Hooks
::run( 'ShowSearchHit', array(
854 $this, $result, $terms,
855 &$link, &$redirect, &$section, &$extract,
856 &$score, &$size, &$date, &$related,
859 $html = "<li><div class='mw-search-result-heading'>" .
860 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
861 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
869 * Extract custom captions from search-interwiki-custom message
871 protected function getCustomCaptions() {
872 if ( is_null( $this->customCaptions
) ) {
873 $this->customCaptions
= array();
874 // format per line <iwprefix>:<caption>
875 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
876 foreach ( $customLines as $line ) {
877 $parts = explode( ":", $line, 2 );
878 if ( count( $parts ) == 2 ) { // validate line
879 $this->customCaptions
[$parts[0]] = $parts[1];
886 * Show results from other wikis
888 * @param SearchResultSet|array $matches
889 * @param string $query
893 protected function showInterwiki( $matches, $query ) {
896 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
897 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
898 $out .= "<ul class='mw-search-iwresults'>\n";
900 // work out custom project captions
901 $this->getCustomCaptions();
903 if ( !is_array( $matches ) ) {
904 $matches = array( $matches );
907 foreach ( $matches as $set ) {
909 $result = $set->next();
911 $out .= $this->showInterwikiHit( $result, $prev, $query );
912 $prev = $result->getInterwikiPrefix();
913 $result = $set->next();
917 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
918 $out .= "</ul></div>\n";
920 // convert the whole thing to desired language variant
921 $out = $wgContLang->convert( $out );
927 * Show single interwiki link
929 * @param SearchResult $result
930 * @param string $lastInterwiki
931 * @param string $query
935 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
937 if ( $result->isBrokenTitle() ) {
941 $title = $result->getTitle();
943 $titleSnippet = $result->getTitleSnippet();
945 if ( $titleSnippet == '' ) {
946 $titleSnippet = null;
949 $link = Linker
::linkKnown(
954 // format redirect if any
955 $redirectTitle = $result->getRedirectTitle();
956 $redirectText = $result->getRedirectSnippet();
958 if ( !is_null( $redirectTitle ) ) {
959 if ( $redirectText == '' ) {
960 $redirectText = null;
963 $redirect = "<span class='searchalttitle'>" .
964 $this->msg( 'search-redirect' )->rawParams(
965 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
970 // display project name
971 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
972 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions
) ) {
973 // captions from 'search-interwiki-custom'
974 $caption = $this->customCaptions
[$title->getInterwiki()];
976 // default is to show the hostname of the other wiki which might suck
977 // if there are many wikis on one hostname
978 $parsed = wfParseUrl( $title->getFullURL() );
979 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
981 // "more results" link (special page stuff could be localized, but we might not know target lang)
982 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
983 $searchLink = Linker
::linkKnown(
985 $this->msg( 'search-interwiki-more' )->text(),
989 'fulltext' => 'Search'
992 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
993 {$searchLink}</span>{$caption}</div>\n<ul>";
996 $out .= "<li>{$link} {$redirect}</li>\n";
1002 * Generates the power search box at [[Special:Search]]
1004 * @param string $term Search term
1005 * @param array $opts
1006 * @return string HTML form
1008 protected function powerSearchBox( $term, $opts ) {
1011 // Groups namespaces into rows according to subject
1013 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
1014 $subject = MWNamespace
::getSubject( $namespace );
1015 if ( !array_key_exists( $subject, $rows ) ) {
1016 $rows[$subject] = "";
1019 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1020 if ( $name == '' ) {
1021 $name = $this->msg( 'blanknamespace' )->text();
1025 Xml
::openElement( 'td' ) .
1029 "mw-search-ns{$namespace}",
1030 in_array( $namespace, $this->namespaces
)
1032 Xml
::closeElement( 'td' );
1035 $rows = array_values( $rows );
1036 $numRows = count( $rows );
1038 // Lays out namespaces in multiple floating two-column tables so they'll
1039 // be arranged nicely while still accommodating different screen widths
1040 $namespaceTables = '';
1041 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
1042 $namespaceTables .= Xml
::openElement( 'table' );
1044 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
1045 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
1048 $namespaceTables .= Xml
::closeElement( 'table' );
1051 $showSections = array( 'namespaceTables' => $namespaceTables );
1053 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1056 foreach ( $opts as $key => $value ) {
1057 $hidden .= Html
::hidden( $key, $value );
1060 # Stuff to feed saveNamespaces()
1062 $user = $this->getUser();
1063 if ( $user->isLoggedIn() ) {
1064 $remember .= Xml
::checkLabel(
1065 $this->msg( 'powersearch-remember' )->text(),
1067 'mw-search-powersearch-remember',
1069 // The token goes here rather than in a hidden field so it
1070 // is only sent when necessary (not every form submission).
1071 array( 'value' => $user->getEditToken(
1078 // Return final output
1079 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1080 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1081 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1082 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1083 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1084 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1086 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1088 Xml
::closeElement( 'fieldset' );
1094 protected function getSearchProfiles() {
1095 // Builds list of Search Types (profiles)
1096 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1100 'message' => 'searchprofile-articles',
1101 'tooltip' => 'searchprofile-articles-tooltip',
1102 'namespaces' => SearchEngine
::defaultNamespaces(),
1103 'namespace-messages' => SearchEngine
::namespacesAsText(
1104 SearchEngine
::defaultNamespaces()
1108 'message' => 'searchprofile-images',
1109 'tooltip' => 'searchprofile-images-tooltip',
1110 'namespaces' => array( NS_FILE
),
1113 'message' => 'searchprofile-everything',
1114 'tooltip' => 'searchprofile-everything-tooltip',
1115 'namespaces' => $nsAllSet,
1117 'advanced' => array(
1118 'message' => 'searchprofile-advanced',
1119 'tooltip' => 'searchprofile-advanced-tooltip',
1120 'namespaces' => self
::NAMESPACES_CURRENT
,
1124 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
1126 foreach ( $profiles as &$data ) {
1127 if ( !is_array( $data['namespaces'] ) ) {
1130 sort( $data['namespaces'] );
1137 * @param string $term
1140 protected function searchProfileTabs( $term ) {
1141 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1144 if ( $this->startsWithImage( $term ) ) {
1146 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1149 $profiles = $this->getSearchProfiles();
1150 $lang = $this->getLanguage();
1152 // Outputs XML for Search Types
1153 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1154 $out .= Xml
::openElement( 'ul' );
1155 foreach ( $profiles as $id => $profile ) {
1156 if ( !isset( $profile['parameters'] ) ) {
1157 $profile['parameters'] = array();
1159 $profile['parameters']['profile'] = $id;
1161 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1162 $lang->commaList( $profile['namespace-messages'] ) : null;
1166 'class' => $this->profile
=== $id ?
'current' : 'normal'
1168 $this->makeSearchLink(
1171 $this->msg( $profile['message'] )->text(),
1172 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1173 $profile['parameters']
1177 $out .= Xml
::closeElement( 'ul' );
1178 $out .= Xml
::closeElement( 'div' );
1179 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1180 $out .= Xml
::closeElement( 'div' );
1186 * @param string $term Search term
1189 protected function searchOptions( $term ) {
1192 $opts['profile'] = $this->profile
;
1194 if ( $this->isPowerSearch() ) {
1195 $out .= $this->powerSearchBox( $term, $opts );
1198 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1206 * @param string $term
1207 * @param int $resultsShown
1208 * @param int $totalNum
1211 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1212 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1213 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1215 $out .= Html
::input( 'search', $term, 'search', array(
1216 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1218 'autofocus' => trim( $term ) === '',
1219 'class' => 'mw-ui-input mw-ui-input-inline',
1221 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1222 $out .= Html
::submitButton(
1223 $this->msg( 'searchbutton' )->text(),
1224 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1225 array( 'mw-ui-progressive' )
1229 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1230 $top = $this->msg( 'search-showingresults' )
1231 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1232 ->numParams( $resultsShown )
1234 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1235 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1242 * Make a search link with some target namespaces
1244 * @param string $term
1245 * @param array $namespaces Ignored
1246 * @param string $label Link's text
1247 * @param string $tooltip Link's tooltip
1248 * @param array $params Query string parameters
1249 * @return string HTML fragment
1251 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1253 foreach ( $namespaces as $n ) {
1254 $opt['ns' . $n] = 1;
1257 $stParams = array_merge(
1260 'fulltext' => $this->msg( 'search' )->text()
1265 return Xml
::element(
1268 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1276 * Check if query starts with image: prefix
1278 * @param string $term The string to check
1281 protected function startsWithImage( $term ) {
1284 $parts = explode( ':', $term );
1285 if ( count( $parts ) > 1 ) {
1286 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1293 * Check if query starts with all: prefix
1295 * @param string $term The string to check
1298 protected function startsWithAll( $term ) {
1300 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1302 $parts = explode( ':', $term );
1303 if ( count( $parts ) > 1 ) {
1304 return $parts[0] == $allkeyword;
1313 * @return SearchEngine
1315 public function getSearchEngine() {
1316 if ( $this->searchEngine
=== null ) {
1317 $this->searchEngine
= $this->searchEngineType ?
1318 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1321 return $this->searchEngine
;
1325 * Current search profile.
1326 * @return null|string
1328 function getProfile() {
1329 return $this->profile
;
1333 * Current namespaces.
1336 function getNamespaces() {
1337 return $this->namespaces
;
1341 * Users of hook SpecialSearchSetupEngine can use this to
1342 * add more params to links to not lose selection when
1343 * user navigates search results.
1346 * @param string $key
1347 * @param mixed $value
1349 public function setExtraParam( $key, $value ) {
1350 $this->extraParams
[$key] = $value;
1353 protected function getGroupName() {