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;
76 const NAMESPACES_CURRENT
= 'sense';
78 public function __construct() {
79 parent
::__construct( 'Search' );
87 public function execute( $par ) {
89 $this->outputHeader();
90 $out = $this->getOutput();
91 $out->allowClickjacking();
92 $out->addModuleStyles( array(
93 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
96 $this->addHelpLink( 'Help:Searching' );
98 // Strip underscores from title parameter; most of the time we'll want
99 // text form here. But don't strip underscores from actual text params!
100 $titleParam = str_replace( '_', ' ', $par );
102 $request = $this->getRequest();
104 // Fetch the search term
105 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
108 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
109 $this->saveNamespaces();
110 // Remove the token from the URL to prevent the user from inadvertently
111 // exposing it (e.g. by pasting it into a public wiki page) or undoing
112 // later settings changes (e.g. by reloading the page).
113 $query = $request->getValues();
114 unset( $query['title'], $query['nsRemember'] );
115 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
119 $out->addJsConfigVars( array( 'searchTerm' => $search ) );
120 $this->searchEngineType
= $request->getVal( 'srbackend' );
122 if ( $request->getVal( 'fulltext' )
123 ||
!is_null( $request->getVal( 'offset' ) )
125 $this->showResults( $search );
127 $this->goResult( $search );
132 * Set up basic search parameters from the request and user settings.
134 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
136 public function load() {
137 $request = $this->getRequest();
138 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
139 $this->mPrefix
= $request->getVal( 'prefix', '' );
141 $user = $this->getUser();
143 # Extract manually requested namespaces
144 $nslist = $this->powerSearch( $request );
145 if ( !count( $nslist ) ) {
146 # Fallback to user preference
147 $nslist = SearchEngine
::userNamespaces( $user );
151 if ( !count( $nslist ) ) {
152 $profile = 'default';
155 $profile = $request->getVal( 'profile', $profile );
156 $profiles = $this->getSearchProfiles();
157 if ( $profile === null ) {
158 // BC with old request format
159 $profile = 'advanced';
160 foreach ( $profiles as $key => $data ) {
161 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
165 $this->namespaces
= $nslist;
166 } elseif ( $profile === 'advanced' ) {
167 $this->namespaces
= $nslist;
169 if ( isset( $profiles[$profile]['namespaces'] ) ) {
170 $this->namespaces
= $profiles[$profile]['namespaces'];
172 // Unknown profile requested
173 $profile = 'default';
174 $this->namespaces
= $profiles['default']['namespaces'];
178 $this->fulltext
= $request->getVal( 'fulltext' );
179 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
180 $this->profile
= $profile;
184 * If an exact title match can be found, jump straight ahead to it.
186 * @param string $term
188 public function goResult( $term ) {
189 $this->setupPage( $term );
190 # Try to go to page as entered.
191 $title = Title
::newFromText( $term );
192 # If the string cannot be used to create a title
193 if ( is_null( $title ) ) {
194 $this->showResults( $term );
198 # If there's an exact or very near match, jump right there.
199 $title = SearchEngine
::getNearMatch( $term );
201 if ( !is_null( $title ) ) {
202 $this->getOutput()->redirect( $title->getFullURL() );
206 # No match, generate an edit URL
207 $title = Title
::newFromText( $term );
208 if ( !is_null( $title ) ) {
209 Hooks
::run( 'SpecialSearchNogomatch', array( &$title ) );
211 $this->showResults( $term );
215 * @param string $term
217 public function showResults( $term ) {
220 $search = $this->getSearchEngine();
221 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
222 $search->setLimitOffset( $this->limit
, $this->offset
);
223 $search->setNamespaces( $this->namespaces
);
224 $search->prefix
= $this->mPrefix
;
225 $term = $search->transformSearchTerm( $term );
227 Hooks
::run( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
229 $this->setupPage( $term );
231 $out = $this->getOutput();
233 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
234 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
235 if ( $searchFowardUrl ) {
236 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
237 $out->redirect( $url );
240 Xml
::openElement( 'fieldset' ) .
241 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
244 array( 'class' => 'mw-searchdisabled' ),
245 $this->msg( 'searchdisabled' )->text()
247 $this->msg( 'googlesearch' )->rawParams(
248 htmlspecialchars( $term ),
250 $this->msg( 'searchbutton' )->escaped()
252 Xml
::closeElement( 'fieldset' )
259 $title = Title
::newFromText( $term );
260 $showSuggestion = $title === null ||
!$title->isKnown();
261 $search->setShowSuggestion( $showSuggestion );
263 // fetch search results
264 $rewritten = $search->replacePrefixes( $term );
266 $titleMatches = $search->searchTitle( $rewritten );
267 $textMatches = $search->searchText( $rewritten );
270 if ( $textMatches instanceof Status
) {
271 $textStatus = $textMatches;
275 // did you mean... suggestions
276 $didYouMeanHtml = '';
277 if ( $showSuggestion && $textMatches && !$textStatus ) {
278 if ( $textMatches->hasRewrittenQuery() ) {
279 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
280 } elseif ( $textMatches->hasSuggestion() ) {
281 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
285 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
286 # Hook requested termination
290 // start rendering the page
295 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
297 'action' => wfScript(),
302 // Get number of results
303 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
304 if ( $titleMatches ) {
305 $titleMatchesNum = $titleMatches->numRows();
306 $numTitleMatches = $titleMatches->getTotalHits();
308 if ( $textMatches ) {
309 $textMatchesNum = $textMatches->numRows();
310 $numTextMatches = $textMatches->getTotalHits();
312 $num = $titleMatchesNum +
$textMatchesNum;
313 $totalRes = $numTitleMatches +
$numTextMatches;
316 # This is an awful awful ID name. It's not a table, but we
317 # named it poorly from when this was a table so now we're
319 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
320 $this->shortDialog( $term, $num, $totalRes ) .
321 Xml
::closeElement( 'div' ) .
322 $this->searchProfileTabs( $term ) .
323 $this->searchOptions( $term ) .
324 Xml
::closeElement( 'form' ) .
328 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
329 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
330 // Empty query -- straight view of search form
334 $out->addHtml( "<div class='searchresults'>" );
338 if ( $num ||
$this->offset
) {
339 // Show the create link ahead
340 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
341 if ( $totalRes > $this->limit ||
$this->offset
) {
342 if ( $this->searchEngineType
!== null ) {
343 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
345 $prevnext = $this->getLanguage()->viewPrevNext(
346 $this->getPageTitle(),
349 $this->powerSearchOptions() +
array( 'search' => $term ),
350 $this->limit +
$this->offset
>= $totalRes
354 Hooks
::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
356 $out->parserOptions()->setEditSection( false );
357 if ( $titleMatches ) {
358 if ( $numTitleMatches > 0 ) {
359 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
360 $out->addHTML( $this->showMatches( $titleMatches ) );
362 $titleMatches->free();
364 if ( $textMatches && !$textStatus ) {
365 // output appropriate heading
366 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
367 // if no title matches the heading is redundant
368 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
372 if ( $numTextMatches > 0 ) {
373 $out->addHTML( $this->showMatches( $textMatches ) );
375 // show interwiki results if any
376 if ( $textMatches->hasInterwikiResults() ) {
377 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
380 $textMatches->free();
384 $out->addHTML( '<div class="error">' .
385 $textStatus->getMessage( 'search-error' ) . '</div>' );
387 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
388 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
389 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
393 $out->addHTML( '<div class="visualClear"></div>' );
395 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
398 $out->addHtml( "</div>" );
400 Hooks
::run( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
405 * Decide if the suggested query should be run, and it's results returned
406 * instead of the provided $textMatches
408 * @param SearchResultSet $textMatches The results of a users query
411 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
412 if ( !$this->runSuggestion ||
413 !$textMatches->hasSuggestion() ||
414 $textMatches->numRows() > 0 ||
415 $textMatches->searchContainedSyntax()
420 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
424 * Generates HTML shown to the user when we have a suggestion about a query
425 * that might give more results than their current query.
427 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
428 # mirror Go/Search behavior of original request ..
429 $params = array( 'search' => $textMatches->getSuggestionQuery() );
430 if ( $this->fulltext
!= null ) {
431 $params['fulltext'] = $this->fulltext
;
433 $stParams = array_merge( $params, $this->powerSearchOptions() );
435 $suggest = Linker
::linkKnown(
436 $this->getPageTitle(),
437 $textMatches->getSuggestionSnippet() ?
: null,
438 array( 'id' => 'mw-search-DYM-suggestion' ),
442 # HTML of did you mean... search suggestion link
443 return Html
::rawElement(
445 array( 'class' => 'searchdidyoumean' ),
446 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
451 * Generates HTML shown to user when their query has been internally rewritten,
452 * and the results of the rewritten query are being returned.
454 * @param string $term The users search input
455 * @param SearchResultSet $textMatches The response to the users initial search request
456 * @return string HTML linking the user to their original $term query, and the one
457 * suggested by $textMatches.
459 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
460 // Showing results for '$rewritten'
461 // Search instead for '$orig'
463 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
464 if ( $this->fulltext
!= null ) {
465 $params['fulltext'] = $this->fulltext
;
467 $stParams = array_merge( $params, $this->powerSearchOptions() );
469 $rewritten = Linker
::linkKnown(
470 $this->getPageTitle(),
471 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
472 array( 'id' => 'mw-search-DYM-rewritten' ),
476 $stParams['search'] = $term;
477 $stParams['runsuggestion'] = 0;
478 $original = Linker
::linkKnown(
479 $this->getPageTitle(),
480 htmlspecialchars( $term ),
481 array( 'id' => 'mw-search-DYM-original' ),
485 return Html
::rawElement(
487 array( 'class' => 'searchdidyoumean' ),
488 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
493 * @param Title $title
494 * @param int $num The number of search results found
495 * @param null|SearchResultSet $titleMatches Results from title search
496 * @param null|SearchResultSet $textMatches Results from text search
498 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
499 // show direct page/create link if applicable
501 // Check DBkey !== '' in case of fragment link only.
502 if ( is_null( $title ) ||
$title->getDBkey() === ''
503 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
504 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
507 // preserve the paragraph for margins etc...
508 $this->getOutput()->addHtml( '<p></p>' );
513 $messageName = 'searchmenu-new-nocreate';
514 $linkClass = 'mw-search-createlink';
516 if ( !$title->isExternal() ) {
517 if ( $title->isKnown() ) {
518 $messageName = 'searchmenu-exists';
519 $linkClass = 'mw-search-exists';
520 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
521 $messageName = 'searchmenu-new';
527 wfEscapeWikiText( $title->getPrefixedText() ),
528 Message
::numParam( $num )
530 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
532 // Extensions using the hook might still return an empty $messageName
533 if ( $messageName ) {
534 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
536 // preserve the paragraph for margins etc...
537 $this->getOutput()->addHtml( '<p></p>' );
542 * @param string $term
544 protected function setupPage( $term ) {
545 $out = $this->getOutput();
546 if ( strval( $term ) !== '' ) {
547 $out->setPageTitle( $this->msg( 'searchresults' ) );
548 $out->setHTMLTitle( $this->msg( 'pagetitle' )
549 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
550 ->inContentLanguage()->text()
553 // add javascript specific to special:search
554 $out->addModules( 'mediawiki.special.search' );
558 * Return true if current search is a power (advanced) search
562 protected function isPowerSearch() {
563 return $this->profile
=== 'advanced';
567 * Extract "power search" namespace settings from the request object,
568 * returning a list of index numbers to search.
570 * @param WebRequest $request
573 protected function powerSearch( &$request ) {
575 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
576 if ( $request->getCheck( 'ns' . $ns ) ) {
585 * Reconstruct the 'power search' options for links
589 protected function powerSearchOptions() {
591 if ( !$this->isPowerSearch() ) {
592 $opt['profile'] = $this->profile
;
594 foreach ( $this->namespaces
as $n ) {
599 return $opt +
$this->extraParams
;
603 * Save namespace preferences when we're supposed to
605 * @return bool Whether we wrote something
607 protected function saveNamespaces() {
608 $user = $this->getUser();
609 $request = $this->getRequest();
611 if ( $user->isLoggedIn() &&
612 $user->matchEditToken(
613 $request->getVal( 'nsRemember' ),
618 // Reset namespace preferences: namespaces are not searched
619 // when they're not mentioned in the URL parameters.
620 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
621 $user->setOption( 'searchNs' . $n, false );
623 // The request parameters include all the namespaces to be searched.
624 // Even if they're the same as an existing profile, they're not eaten.
625 foreach ( $this->namespaces
as $n ) {
626 $user->setOption( 'searchNs' . $n, true );
629 $user->saveSettings();
637 * Show whole set of results
639 * @param SearchResultSet $matches
643 protected function showMatches( &$matches ) {
646 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
648 $out = "<ul class='mw-search-results'>\n";
649 $result = $matches->next();
650 $pos = $this->offset
;
652 $out .= $this->showHit( $result, $terms, ++
$pos );
653 $result = $matches->next();
657 // convert the whole thing to desired language variant
658 $out = $wgContLang->convert( $out );
664 * Format a single hit result
666 * @param SearchResult $result
667 * @param array $terms Terms to highlight
668 * @param int $position Position within the search results, including offset.
672 protected function showHit( $result, $terms, $position ) {
674 if ( $result->isBrokenTitle() ) {
678 $title = $result->getTitle();
680 $titleSnippet = $result->getTitleSnippet();
682 if ( $titleSnippet == '' ) {
683 $titleSnippet = null;
686 $link_t = clone $title;
688 Hooks
::run( 'ShowSearchHitTitle',
689 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
691 $link = Linker
::linkKnown(
694 array( 'data-serp-pos' => $position ) // HTML attributes
697 // If page content is not readable, just return the title.
698 // This is not quite safe, but better than showing excerpts from non-readable pages
699 // Note that hiding the entry entirely would screw up paging.
700 if ( !$title->userCan( 'read', $this->getUser() ) ) {
701 return "<li>{$link}</li>\n";
704 // If the page doesn't *exist*... our search index is out of date.
705 // The least confusing at this point is to drop the result.
706 // You may get less results, but... oh well. :P
707 if ( $result->isMissingRevision() ) {
711 // format redirects / relevant sections
712 $redirectTitle = $result->getRedirectTitle();
713 $redirectText = $result->getRedirectSnippet();
714 $sectionTitle = $result->getSectionTitle();
715 $sectionText = $result->getSectionSnippet();
716 $categorySnippet = $result->getCategorySnippet();
719 if ( !is_null( $redirectTitle ) ) {
720 if ( $redirectText == '' ) {
721 $redirectText = null;
724 $redirect = "<span class='searchalttitle'>" .
725 $this->msg( 'search-redirect' )->rawParams(
726 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
731 if ( !is_null( $sectionTitle ) ) {
732 if ( $sectionText == '' ) {
736 $section = "<span class='searchalttitle'>" .
737 $this->msg( 'search-section' )->rawParams(
738 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
743 if ( $categorySnippet ) {
744 $category = "<span class='searchalttitle'>" .
745 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
749 // format text extract
750 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
752 $lang = $this->getLanguage();
754 // format description
755 $byteSize = $result->getByteSize();
756 $wordCount = $result->getWordCount();
757 $timestamp = $result->getTimestamp();
758 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
759 ->numParams( $wordCount )->escaped();
761 if ( $title->getNamespace() == NS_CATEGORY
) {
762 $cat = Category
::newFromTitle( $title );
763 $size = $this->msg( 'search-result-category-size' )
764 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
768 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
771 // Include a thumbnail for media files...
772 if ( $title->getNamespace() == NS_FILE
) {
773 $img = $result->getFile();
774 $img = $img ?
: wfFindFile( $title );
775 if ( $result->isFileMatch() ) {
776 $fileMatch = "<span class='searchalttitle'>" .
777 $this->msg( 'search-file-match' )->escaped() . "</span>";
780 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
782 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
783 // Float doesn't seem to interact well with the bullets.
784 // Table messes up vertical alignment of the bullets.
785 // Bullets are therefore disabled (didn't look great anyway).
787 '<table class="searchResultImage">' .
789 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
790 $thumb->toHtml( array( 'desc-link' => true ) ) .
792 '<td style="vertical-align: top;">' .
793 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
795 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
807 if ( Hooks
::run( 'ShowSearchHit', array(
808 $this, $result, $terms,
809 &$link, &$redirect, &$section, &$extract,
810 &$score, &$size, &$date, &$related,
813 $html = "<li><div class='mw-search-result-heading'>" .
814 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
815 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
823 * Show results from other wikis
825 * @param SearchResultSet|array $matches
826 * @param string $query
830 protected function showInterwiki( $matches, $query ) {
833 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
834 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
835 $out .= "<ul class='mw-search-iwresults'>\n";
837 // work out custom project captions
838 $customCaptions = array();
839 // format per line <iwprefix>:<caption>
840 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
841 foreach ( $customLines as $line ) {
842 $parts = explode( ":", $line, 2 );
843 if ( count( $parts ) == 2 ) { // validate line
844 $customCaptions[$parts[0]] = $parts[1];
848 if ( !is_array( $matches ) ) {
849 $matches = array( $matches );
852 foreach ( $matches as $set ) {
854 $result = $set->next();
856 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
857 $prev = $result->getInterwikiPrefix();
858 $result = $set->next();
862 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
863 $out .= "</ul></div>\n";
865 // convert the whole thing to desired language variant
866 $out = $wgContLang->convert( $out );
872 * Show single interwiki link
874 * @param SearchResult $result
875 * @param string $lastInterwiki
876 * @param string $query
877 * @param array $customCaptions Interwiki prefix -> caption
881 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
883 if ( $result->isBrokenTitle() ) {
887 $title = $result->getTitle();
889 $titleSnippet = $result->getTitleSnippet();
891 if ( $titleSnippet == '' ) {
892 $titleSnippet = null;
895 $link = Linker
::linkKnown(
900 // format redirect if any
901 $redirectTitle = $result->getRedirectTitle();
902 $redirectText = $result->getRedirectSnippet();
904 if ( !is_null( $redirectTitle ) ) {
905 if ( $redirectText == '' ) {
906 $redirectText = null;
909 $redirect = "<span class='searchalttitle'>" .
910 $this->msg( 'search-redirect' )->rawParams(
911 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
916 // display project name
917 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
918 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
919 // captions from 'search-interwiki-custom'
920 $caption = $customCaptions[$title->getInterwiki()];
922 // default is to show the hostname of the other wiki which might suck
923 // if there are many wikis on one hostname
924 $parsed = wfParseUrl( $title->getFullURL() );
925 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
927 // "more results" link (special page stuff could be localized, but we might not know target lang)
928 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
929 $searchLink = Linker
::linkKnown(
931 $this->msg( 'search-interwiki-more' )->text(),
935 'fulltext' => 'Search'
938 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
939 {$searchLink}</span>{$caption}</div>\n<ul>";
942 $out .= "<li>{$link} {$redirect}</li>\n";
948 * Generates the power search box at [[Special:Search]]
950 * @param string $term Search term
952 * @return string HTML form
954 protected function powerSearchBox( $term, $opts ) {
957 // Groups namespaces into rows according to subject
959 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
960 $subject = MWNamespace
::getSubject( $namespace );
961 if ( !array_key_exists( $subject, $rows ) ) {
962 $rows[$subject] = "";
965 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
967 $name = $this->msg( 'blanknamespace' )->text();
971 Xml
::openElement( 'td' ) .
975 "mw-search-ns{$namespace}",
976 in_array( $namespace, $this->namespaces
)
978 Xml
::closeElement( 'td' );
981 $rows = array_values( $rows );
982 $numRows = count( $rows );
984 // Lays out namespaces in multiple floating two-column tables so they'll
985 // be arranged nicely while still accommodating different screen widths
986 $namespaceTables = '';
987 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
988 $namespaceTables .= Xml
::openElement( 'table' );
990 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
991 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
994 $namespaceTables .= Xml
::closeElement( 'table' );
997 $showSections = array( 'namespaceTables' => $namespaceTables );
999 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1002 foreach ( $opts as $key => $value ) {
1003 $hidden .= Html
::hidden( $key, $value );
1006 # Stuff to feed saveNamespaces()
1008 $user = $this->getUser();
1009 if ( $user->isLoggedIn() ) {
1010 $remember .= Xml
::checkLabel(
1011 $this->msg( 'powersearch-remember' )->text(),
1013 'mw-search-powersearch-remember',
1015 // The token goes here rather than in a hidden field so it
1016 // is only sent when necessary (not every form submission).
1017 array( 'value' => $user->getEditToken(
1024 // Return final output
1025 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1026 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1027 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1028 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1029 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1030 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1032 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1034 Xml
::closeElement( 'fieldset' );
1040 protected function getSearchProfiles() {
1041 // Builds list of Search Types (profiles)
1042 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1046 'message' => 'searchprofile-articles',
1047 'tooltip' => 'searchprofile-articles-tooltip',
1048 'namespaces' => SearchEngine
::defaultNamespaces(),
1049 'namespace-messages' => SearchEngine
::namespacesAsText(
1050 SearchEngine
::defaultNamespaces()
1054 'message' => 'searchprofile-images',
1055 'tooltip' => 'searchprofile-images-tooltip',
1056 'namespaces' => array( NS_FILE
),
1059 'message' => 'searchprofile-everything',
1060 'tooltip' => 'searchprofile-everything-tooltip',
1061 'namespaces' => $nsAllSet,
1063 'advanced' => array(
1064 'message' => 'searchprofile-advanced',
1065 'tooltip' => 'searchprofile-advanced-tooltip',
1066 'namespaces' => self
::NAMESPACES_CURRENT
,
1070 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
1072 foreach ( $profiles as &$data ) {
1073 if ( !is_array( $data['namespaces'] ) ) {
1076 sort( $data['namespaces'] );
1083 * @param string $term
1086 protected function searchProfileTabs( $term ) {
1087 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1090 if ( $this->startsWithImage( $term ) ) {
1092 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1095 $profiles = $this->getSearchProfiles();
1096 $lang = $this->getLanguage();
1098 // Outputs XML for Search Types
1099 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1100 $out .= Xml
::openElement( 'ul' );
1101 foreach ( $profiles as $id => $profile ) {
1102 if ( !isset( $profile['parameters'] ) ) {
1103 $profile['parameters'] = array();
1105 $profile['parameters']['profile'] = $id;
1107 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1108 $lang->commaList( $profile['namespace-messages'] ) : null;
1112 'class' => $this->profile
=== $id ?
'current' : 'normal'
1114 $this->makeSearchLink(
1117 $this->msg( $profile['message'] )->text(),
1118 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1119 $profile['parameters']
1123 $out .= Xml
::closeElement( 'ul' );
1124 $out .= Xml
::closeElement( 'div' );
1125 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1126 $out .= Xml
::closeElement( 'div' );
1132 * @param string $term Search term
1135 protected function searchOptions( $term ) {
1138 $opts['profile'] = $this->profile
;
1140 if ( $this->isPowerSearch() ) {
1141 $out .= $this->powerSearchBox( $term, $opts );
1144 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1152 * @param string $term
1153 * @param int $resultsShown
1154 * @param int $totalNum
1157 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1158 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1159 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1161 $out .= Html
::input( 'search', $term, 'search', array(
1162 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1164 'autofocus' => trim( $term ) === '',
1165 'class' => 'mw-ui-input mw-ui-input-inline',
1167 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1168 $out .= Html
::submitButton(
1169 $this->msg( 'searchbutton' )->text(),
1170 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1171 array( 'mw-ui-progressive' )
1175 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1176 $top = $this->msg( 'search-showingresults' )
1177 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1178 ->numParams( $resultsShown )
1180 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1181 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1188 * Make a search link with some target namespaces
1190 * @param string $term
1191 * @param array $namespaces Ignored
1192 * @param string $label Link's text
1193 * @param string $tooltip Link's tooltip
1194 * @param array $params Query string parameters
1195 * @return string HTML fragment
1197 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1199 foreach ( $namespaces as $n ) {
1200 $opt['ns' . $n] = 1;
1203 $stParams = array_merge(
1206 'fulltext' => $this->msg( 'search' )->text()
1211 return Xml
::element(
1214 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1222 * Check if query starts with image: prefix
1224 * @param string $term The string to check
1227 protected function startsWithImage( $term ) {
1230 $parts = explode( ':', $term );
1231 if ( count( $parts ) > 1 ) {
1232 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1239 * Check if query starts with all: prefix
1241 * @param string $term The string to check
1244 protected function startsWithAll( $term ) {
1246 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1248 $parts = explode( ':', $term );
1249 if ( count( $parts ) > 1 ) {
1250 return $parts[0] == $allkeyword;
1259 * @return SearchEngine
1261 public function getSearchEngine() {
1262 if ( $this->searchEngine
=== null ) {
1263 $this->searchEngine
= $this->searchEngineType ?
1264 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1267 return $this->searchEngine
;
1271 * Current search profile.
1272 * @return null|string
1274 function getProfile() {
1275 return $this->profile
;
1279 * Current namespaces.
1282 function getNamespaces() {
1283 return $this->namespaces
;
1287 * Users of hook SpecialSearchSetupEngine can use this to
1288 * add more params to links to not lose selection when
1289 * user navigates search results.
1292 * @param string $key
1293 * @param mixed $value
1295 public function setExtraParam( $key, $value ) {
1296 $this->extraParams
[$key] = $value;
1299 protected function getGroupName() {