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',
97 // Strip underscores from title parameter; most of the time we'll want
98 // text form here. But don't strip underscores from actual text params!
99 $titleParam = str_replace( '_', ' ', $par );
101 $request = $this->getRequest();
103 // Fetch the search term
104 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
107 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
108 $this->saveNamespaces();
109 // Remove the token from the URL to prevent the user from inadvertently
110 // exposing it (e.g. by pasting it into a public wiki page) or undoing
111 // later settings changes (e.g. by reloading the page).
112 $query = $request->getValues();
113 unset( $query['title'], $query['nsRemember'] );
114 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
118 $this->searchEngineType
= $request->getVal( 'srbackend' );
120 if ( $request->getVal( 'fulltext' )
121 ||
!is_null( $request->getVal( 'offset' ) )
123 $this->showResults( $search );
125 $this->goResult( $search );
130 * Set up basic search parameters from the request and user settings.
132 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
134 public function load() {
135 $request = $this->getRequest();
136 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
137 $this->mPrefix
= $request->getVal( 'prefix', '' );
139 $user = $this->getUser();
141 # Extract manually requested namespaces
142 $nslist = $this->powerSearch( $request );
143 if ( !count( $nslist ) ) {
144 # Fallback to user preference
145 $nslist = SearchEngine
::userNamespaces( $user );
149 if ( !count( $nslist ) ) {
150 $profile = 'default';
153 $profile = $request->getVal( 'profile', $profile );
154 $profiles = $this->getSearchProfiles();
155 if ( $profile === null ) {
156 // BC with old request format
157 $profile = 'advanced';
158 foreach ( $profiles as $key => $data ) {
159 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
163 $this->namespaces
= $nslist;
164 } elseif ( $profile === 'advanced' ) {
165 $this->namespaces
= $nslist;
167 if ( isset( $profiles[$profile]['namespaces'] ) ) {
168 $this->namespaces
= $profiles[$profile]['namespaces'];
170 // Unknown profile requested
171 $profile = 'default';
172 $this->namespaces
= $profiles['default']['namespaces'];
176 $this->fulltext
= $request->getVal( 'fulltext' );
177 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
178 $this->profile
= $profile;
182 * If an exact title match can be found, jump straight ahead to it.
184 * @param string $term
186 public function goResult( $term ) {
187 $this->setupPage( $term );
188 # Try to go to page as entered.
189 $title = Title
::newFromText( $term );
190 # If the string cannot be used to create a title
191 if ( is_null( $title ) ) {
192 $this->showResults( $term );
196 # If there's an exact or very near match, jump right there.
197 $title = SearchEngine
::getNearMatch( $term );
199 if ( !is_null( $title ) ) {
200 $this->getOutput()->redirect( $title->getFullURL() );
204 # No match, generate an edit URL
205 $title = Title
::newFromText( $term );
206 if ( !is_null( $title ) ) {
207 Hooks
::run( 'SpecialSearchNogomatch', array( &$title ) );
209 $this->showResults( $term );
213 * @param string $term
215 public function showResults( $term ) {
218 $search = $this->getSearchEngine();
219 $search->setLimitOffset( $this->limit
, $this->offset
);
220 $search->setNamespaces( $this->namespaces
);
221 $search->prefix
= $this->mPrefix
;
222 $term = $search->transformSearchTerm( $term );
224 Hooks
::run( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
226 $this->setupPage( $term );
228 $out = $this->getOutput();
230 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
231 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
232 if ( $searchFowardUrl ) {
233 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
234 $out->redirect( $url );
237 Xml
::openElement( 'fieldset' ) .
238 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
241 array( 'class' => 'mw-searchdisabled' ),
242 $this->msg( 'searchdisabled' )->text()
244 $this->msg( 'googlesearch' )->rawParams(
245 htmlspecialchars( $term ),
247 $this->msg( 'searchbutton' )->escaped()
249 Xml
::closeElement( 'fieldset' )
256 $title = Title
::newFromText( $term );
257 $showSuggestion = $title === null ||
!$title->isKnown();
258 $search->setShowSuggestion( $showSuggestion );
260 // fetch search results
261 $rewritten = $search->replacePrefixes( $term );
263 $titleMatches = $search->searchTitle( $rewritten );
264 $textMatches = $search->searchText( $rewritten );
267 if ( $textMatches instanceof Status
) {
268 $textStatus = $textMatches;
272 // did you mean... suggestions
273 $didYouMeanHtml = '';
274 if ( $showSuggestion && $textMatches && !$textStatus ) {
275 if ( $this->shouldRunSuggestedQuery( $textMatches ) ) {
276 $newMatches = $search->searchText( $textMatches->getSuggestionQuery() );
277 if ( $newMatches instanceof SearchResultSet
&& $newMatches->numRows() > 0 ) {
278 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
279 $textMatches = $newMatches;
281 } elseif ( $textMatches->hasSuggestion() ) {
282 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
286 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
287 # Hook requested termination
291 // start rendering the page
296 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
298 'action' => wfScript(),
303 // Get number of results
304 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
305 if ( $titleMatches ) {
306 $titleMatchesNum = $titleMatches->numRows();
307 $numTitleMatches = $titleMatches->getTotalHits();
309 if ( $textMatches ) {
310 $textMatchesNum = $textMatches->numRows();
311 $numTextMatches = $textMatches->getTotalHits();
313 $num = $titleMatchesNum +
$textMatchesNum;
314 $totalRes = $numTitleMatches +
$numTextMatches;
317 # This is an awful awful ID name. It's not a table, but we
318 # named it poorly from when this was a table so now we're
320 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
321 $this->shortDialog( $term, $num, $totalRes ) .
322 Xml
::closeElement( 'div' ) .
323 $this->searchProfileTabs( $term ) .
324 $this->searchOptions( $term ) .
325 Xml
::closeElement( 'form' ) .
329 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
330 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
331 // Empty query -- straight view of search form
335 $out->addHtml( "<div class='searchresults'>" );
339 if ( $num ||
$this->offset
) {
340 // Show the create link ahead
341 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
342 if ( $totalRes > $this->limit ||
$this->offset
) {
343 if ( $this->searchEngineType
!== null ) {
344 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
346 $prevnext = $this->getLanguage()->viewPrevNext(
347 $this->getPageTitle(),
350 $this->powerSearchOptions() +
array( 'search' => $term ),
351 $this->limit +
$this->offset
>= $totalRes
355 Hooks
::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
357 $out->parserOptions()->setEditSection( false );
358 if ( $titleMatches ) {
359 if ( $numTitleMatches > 0 ) {
360 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
361 $out->addHTML( $this->showMatches( $titleMatches ) );
363 $titleMatches->free();
365 if ( $textMatches && !$textStatus ) {
366 // output appropriate heading
367 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
368 // if no title matches the heading is redundant
369 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
373 if ( $numTextMatches > 0 ) {
374 $out->addHTML( $this->showMatches( $textMatches ) );
376 // show interwiki results if any
377 if ( $textMatches->hasInterwikiResults() ) {
378 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
381 $textMatches->free();
385 $out->addHTML( '<div class="error">' .
386 $textStatus->getMessage( 'search-error' ) . '</div>' );
388 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
389 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
390 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
394 $out->addHTML( '<div class="visualClear"></div>\n' );
396 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
399 $out->addHtml( "</div>" );
401 Hooks
::run( 'SpecialSearchResultsAppend', array( $this, $out ) );
406 * Decide if the suggested query should be run, and it's results returned
407 * instead of the provided $textMatches
409 * @param SearchResultSet $textMatches The results of a users query
412 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
413 if ( !$this->runSuggestion ||
414 !$textMatches->hasSuggestion() ||
415 $textMatches->numRows() > 0 ||
416 $textMatches->searchContainedSyntax()
421 // Generate a random number between 0 and 1. If the
422 // number is less than the desired percentages run it.
423 $rand = rand( 0, getrandmax() ) / getrandmax();
424 return $this->getConfig()->get( 'SearchRunSuggestedQueryPercent' ) > $rand;
428 * Generates HTML shown to the user when we have a suggestion about a query
429 * that might give more results than their current query.
431 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
432 # mirror Go/Search behavior of original request ..
433 $params = array( 'search' => $textMatches->getSuggestionQuery() );
434 if ( $this->fulltext
!= null ) {
435 $params['fulltext'] = $this->fulltext
;
437 $stParams = array_merge( $params, $this->powerSearchOptions() );
439 $suggest = Linker
::linkKnown(
440 $this->getPageTitle(),
441 $textMatches->getSuggestionSnippet() ?
: null,
446 # html of did you mean... search suggestion link
447 return Html
::rawElement(
449 array( 'class' => 'searchdidyoumean' ),
450 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
455 * Generates HTML shown to user when their query has been internally rewritten,
456 * and the results of the rewritten query are being returned.
458 * @param string $term The users search input
459 * @param SearchResultSet $textMatches The response to the users initial search request
460 * @return string HTML linking the user to their original $term query, and the one
461 * suggested by $textMatches.
463 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
464 // Showing results for '$rewritten'
465 // Search instead for '$orig'
467 $params = array( 'search' => $textMatches->getSuggestionQuery() );
468 if ( $this->fulltext
!= null ) {
469 $params['fulltext'] = $this->fulltext
;
471 $stParams = array_merge( $params, $this->powerSearchOptions() );
473 $rewritten = Linker
::linkKnown(
474 $this->getPageTitle(),
475 $textMatches->getSuggestionSnippet() ?
: null,
480 $stParams['search'] = $term;
481 $stParams['runsuggestion'] = 0;
482 $original = Linker
::linkKnown(
483 $this->getPageTitle(),
484 htmlspecialchars( $term ),
489 return Html
::rawElement(
491 array( 'class' => 'searchdidyoumean' ),
492 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
497 * @param Title $title
498 * @param int $num The number of search results found
499 * @param null|SearchResultSet $titleMatches Results from title search
500 * @param null|SearchResultSet $textMatches Results from text search
502 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
503 // show direct page/create link if applicable
505 // Check DBkey !== '' in case of fragment link only.
506 if ( is_null( $title ) ||
$title->getDBkey() === ''
507 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
508 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
511 // preserve the paragraph for margins etc...
512 $this->getOutput()->addHtml( '<p></p>' );
517 $messageName = 'searchmenu-new-nocreate';
518 $linkClass = 'mw-search-createlink';
520 if ( !$title->isExternal() ) {
521 if ( $title->isKnown() ) {
522 $messageName = 'searchmenu-exists';
523 $linkClass = 'mw-search-exists';
524 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
525 $messageName = 'searchmenu-new';
531 wfEscapeWikiText( $title->getPrefixedText() ),
532 Message
::numParam( $num )
534 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
536 // Extensions using the hook might still return an empty $messageName
537 if ( $messageName ) {
538 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
540 // preserve the paragraph for margins etc...
541 $this->getOutput()->addHtml( '<p></p>' );
546 * @param string $term
548 protected function setupPage( $term ) {
549 $out = $this->getOutput();
550 if ( strval( $term ) !== '' ) {
551 $out->setPageTitle( $this->msg( 'searchresults' ) );
552 $out->setHTMLTitle( $this->msg( 'pagetitle' )
553 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
554 ->inContentLanguage()->text()
557 // add javascript specific to special:search
558 $out->addModules( 'mediawiki.special.search' );
562 * Return true if current search is a power (advanced) search
566 protected function isPowerSearch() {
567 return $this->profile
=== 'advanced';
571 * Extract "power search" namespace settings from the request object,
572 * returning a list of index numbers to search.
574 * @param WebRequest $request
577 protected function powerSearch( &$request ) {
579 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
580 if ( $request->getCheck( 'ns' . $ns ) ) {
589 * Reconstruct the 'power search' options for links
593 protected function powerSearchOptions() {
595 if ( !$this->isPowerSearch() ) {
596 $opt['profile'] = $this->profile
;
598 foreach ( $this->namespaces
as $n ) {
603 return $opt +
$this->extraParams
;
607 * Save namespace preferences when we're supposed to
609 * @return bool Whether we wrote something
611 protected function saveNamespaces() {
612 $user = $this->getUser();
613 $request = $this->getRequest();
615 if ( $user->isLoggedIn() &&
616 $user->matchEditToken(
617 $request->getVal( 'nsRemember' ),
622 // Reset namespace preferences: namespaces are not searched
623 // when they're not mentioned in the URL parameters.
624 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
625 $user->setOption( 'searchNs' . $n, false );
627 // The request parameters include all the namespaces to be searched.
628 // Even if they're the same as an existing profile, they're not eaten.
629 foreach ( $this->namespaces
as $n ) {
630 $user->setOption( 'searchNs' . $n, true );
633 $user->saveSettings();
641 * Show whole set of results
643 * @param SearchResultSet $matches
647 protected function showMatches( &$matches ) {
650 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
652 $out = "<ul class='mw-search-results'>\n";
653 $result = $matches->next();
655 $out .= $this->showHit( $result, $terms );
656 $result = $matches->next();
660 // convert the whole thing to desired language variant
661 $out = $wgContLang->convert( $out );
667 * Format a single hit result
669 * @param SearchResult $result
670 * @param array $terms Terms to highlight
674 protected function showHit( $result, $terms ) {
676 if ( $result->isBrokenTitle() ) {
680 $title = $result->getTitle();
682 $titleSnippet = $result->getTitleSnippet();
684 if ( $titleSnippet == '' ) {
685 $titleSnippet = null;
688 $link_t = clone $title;
690 Hooks
::run( 'ShowSearchHitTitle',
691 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
693 $link = Linker
::linkKnown(
698 //If page content is not readable, just return the title.
699 //This is not quite safe, but better than showing excerpts from non-readable pages
700 //Note that hiding the entry entirely would screw up paging.
701 if ( !$title->userCan( 'read', $this->getUser() ) ) {
702 return "<li>{$link}</li>\n";
705 // If the page doesn't *exist*... our search index is out of date.
706 // The least confusing at this point is to drop the result.
707 // You may get less results, but... oh well. :P
708 if ( $result->isMissingRevision() ) {
712 // format redirects / relevant sections
713 $redirectTitle = $result->getRedirectTitle();
714 $redirectText = $result->getRedirectSnippet();
715 $sectionTitle = $result->getSectionTitle();
716 $sectionText = $result->getSectionSnippet();
717 $categorySnippet = $result->getCategorySnippet();
720 if ( !is_null( $redirectTitle ) ) {
721 if ( $redirectText == '' ) {
722 $redirectText = null;
725 $redirect = "<span class='searchalttitle'>" .
726 $this->msg( 'search-redirect' )->rawParams(
727 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
732 if ( !is_null( $sectionTitle ) ) {
733 if ( $sectionText == '' ) {
737 $section = "<span class='searchalttitle'>" .
738 $this->msg( 'search-section' )->rawParams(
739 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
744 if ( $categorySnippet ) {
745 $category = "<span class='searchalttitle'>" .
746 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
750 // format text extract
751 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
753 $lang = $this->getLanguage();
755 // format description
756 $byteSize = $result->getByteSize();
757 $wordCount = $result->getWordCount();
758 $timestamp = $result->getTimestamp();
759 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
760 ->numParams( $wordCount )->escaped();
762 if ( $title->getNamespace() == NS_CATEGORY
) {
763 $cat = Category
::newFromTitle( $title );
764 $size = $this->msg( 'search-result-category-size' )
765 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
769 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
772 // Include a thumbnail for media files...
773 if ( $title->getNamespace() == NS_FILE
) {
774 $img = $result->getFile();
775 $img = $img ?
: wfFindFile( $title );
776 if ( $result->isFileMatch() ) {
777 $fileMatch = "<span class='searchalttitle'>" .
778 $this->msg( 'search-file-match' )->escaped() . "</span>";
781 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
783 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
784 // Float doesn't seem to interact well with the bullets.
785 // Table messes up vertical alignment of the bullets.
786 // Bullets are therefore disabled (didn't look great anyway).
788 '<table class="searchResultImage">' .
790 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
791 $thumb->toHtml( array( 'desc-link' => true ) ) .
793 '<td style="vertical-align: top;">' .
794 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
796 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
808 if ( Hooks
::run( 'ShowSearchHit', array(
809 $this, $result, $terms,
810 &$link, &$redirect, &$section, &$extract,
811 &$score, &$size, &$date, &$related,
814 $html = "<li><div class='mw-search-result-heading'>" .
815 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
816 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
824 * Show results from other wikis
826 * @param SearchResultSet|array $matches
827 * @param string $query
831 protected function showInterwiki( $matches, $query ) {
834 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
835 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
836 $out .= "<ul class='mw-search-iwresults'>\n";
838 // work out custom project captions
839 $customCaptions = array();
840 // format per line <iwprefix>:<caption>
841 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
842 foreach ( $customLines as $line ) {
843 $parts = explode( ":", $line, 2 );
844 if ( count( $parts ) == 2 ) { // validate line
845 $customCaptions[$parts[0]] = $parts[1];
849 if ( !is_array( $matches ) ) {
850 $matches = array( $matches );
853 foreach ( $matches as $set ) {
855 $result = $set->next();
857 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
858 $prev = $result->getInterwikiPrefix();
859 $result = $set->next();
863 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
864 $out .= "</ul></div>\n";
866 // convert the whole thing to desired language variant
867 $out = $wgContLang->convert( $out );
873 * Show single interwiki link
875 * @param SearchResult $result
876 * @param string $lastInterwiki
877 * @param string $query
878 * @param array $customCaptions Interwiki prefix -> caption
882 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
884 if ( $result->isBrokenTitle() ) {
888 $title = $result->getTitle();
890 $titleSnippet = $result->getTitleSnippet();
892 if ( $titleSnippet == '' ) {
893 $titleSnippet = null;
896 $link = Linker
::linkKnown(
901 // format redirect if any
902 $redirectTitle = $result->getRedirectTitle();
903 $redirectText = $result->getRedirectSnippet();
905 if ( !is_null( $redirectTitle ) ) {
906 if ( $redirectText == '' ) {
907 $redirectText = null;
910 $redirect = "<span class='searchalttitle'>" .
911 $this->msg( 'search-redirect' )->rawParams(
912 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
917 // display project name
918 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
919 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
920 // captions from 'search-interwiki-custom'
921 $caption = $customCaptions[$title->getInterwiki()];
923 // default is to show the hostname of the other wiki which might suck
924 // if there are many wikis on one hostname
925 $parsed = wfParseUrl( $title->getFullURL() );
926 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
928 // "more results" link (special page stuff could be localized, but we might not know target lang)
929 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
930 $searchLink = Linker
::linkKnown(
932 $this->msg( 'search-interwiki-more' )->text(),
936 'fulltext' => 'Search'
939 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
940 {$searchLink}</span>{$caption}</div>\n<ul>";
943 $out .= "<li>{$link} {$redirect}</li>\n";
949 * Generates the power search box at [[Special:Search]]
951 * @param string $term Search term
953 * @return string HTML form
955 protected function powerSearchBox( $term, $opts ) {
958 // Groups namespaces into rows according to subject
960 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
961 $subject = MWNamespace
::getSubject( $namespace );
962 if ( !array_key_exists( $subject, $rows ) ) {
963 $rows[$subject] = "";
966 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
968 $name = $this->msg( 'blanknamespace' )->text();
972 Xml
::openElement( 'td' ) .
976 "mw-search-ns{$namespace}",
977 in_array( $namespace, $this->namespaces
)
979 Xml
::closeElement( 'td' );
982 $rows = array_values( $rows );
983 $numRows = count( $rows );
985 // Lays out namespaces in multiple floating two-column tables so they'll
986 // be arranged nicely while still accommodating different screen widths
987 $namespaceTables = '';
988 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
989 $namespaceTables .= Xml
::openElement( 'table' );
991 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
992 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
995 $namespaceTables .= Xml
::closeElement( 'table' );
998 $showSections = array( 'namespaceTables' => $namespaceTables );
1000 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1003 foreach ( $opts as $key => $value ) {
1004 $hidden .= Html
::hidden( $key, $value );
1007 # Stuff to feed saveNamespaces()
1009 $user = $this->getUser();
1010 if ( $user->isLoggedIn() ) {
1011 $remember .= Xml
::checkLabel(
1012 $this->msg( 'powersearch-remember' )->text(),
1014 'mw-search-powersearch-remember',
1016 // The token goes here rather than in a hidden field so it
1017 // is only sent when necessary (not every form submission).
1018 array( 'value' => $user->getEditToken(
1025 // Return final output
1026 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1027 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1028 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1029 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1030 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1031 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1033 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1035 Xml
::closeElement( 'fieldset' );
1041 protected function getSearchProfiles() {
1042 // Builds list of Search Types (profiles)
1043 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1047 'message' => 'searchprofile-articles',
1048 'tooltip' => 'searchprofile-articles-tooltip',
1049 'namespaces' => SearchEngine
::defaultNamespaces(),
1050 'namespace-messages' => SearchEngine
::namespacesAsText(
1051 SearchEngine
::defaultNamespaces()
1055 'message' => 'searchprofile-images',
1056 'tooltip' => 'searchprofile-images-tooltip',
1057 'namespaces' => array( NS_FILE
),
1060 'message' => 'searchprofile-everything',
1061 'tooltip' => 'searchprofile-everything-tooltip',
1062 'namespaces' => $nsAllSet,
1064 'advanced' => array(
1065 'message' => 'searchprofile-advanced',
1066 'tooltip' => 'searchprofile-advanced-tooltip',
1067 'namespaces' => self
::NAMESPACES_CURRENT
,
1071 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
1073 foreach ( $profiles as &$data ) {
1074 if ( !is_array( $data['namespaces'] ) ) {
1077 sort( $data['namespaces'] );
1084 * @param string $term
1087 protected function searchProfileTabs( $term ) {
1088 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1091 if ( $this->startsWithImage( $term ) ) {
1093 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1096 $profiles = $this->getSearchProfiles();
1097 $lang = $this->getLanguage();
1099 // Outputs XML for Search Types
1100 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1101 $out .= Xml
::openElement( 'ul' );
1102 foreach ( $profiles as $id => $profile ) {
1103 if ( !isset( $profile['parameters'] ) ) {
1104 $profile['parameters'] = array();
1106 $profile['parameters']['profile'] = $id;
1108 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1109 $lang->commaList( $profile['namespace-messages'] ) : null;
1113 'class' => $this->profile
=== $id ?
'current' : 'normal'
1115 $this->makeSearchLink(
1118 $this->msg( $profile['message'] )->text(),
1119 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1120 $profile['parameters']
1124 $out .= Xml
::closeElement( 'ul' );
1125 $out .= Xml
::closeElement( 'div' );
1126 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1127 $out .= Xml
::closeElement( 'div' );
1133 * @param string $term Search term
1136 protected function searchOptions( $term ) {
1139 $opts['profile'] = $this->profile
;
1141 if ( $this->isPowerSearch() ) {
1142 $out .= $this->powerSearchBox( $term, $opts );
1145 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1153 * @param string $term
1154 * @param int $resultsShown
1155 * @param int $totalNum
1158 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1159 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1160 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1162 $out .= Html
::input( 'search', $term, 'search', array(
1163 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1165 'autofocus' => trim( $term ) === '',
1166 'class' => 'mw-ui-input mw-ui-input-inline',
1168 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1169 $out .= Html
::submitButton(
1170 $this->msg( 'searchbutton' )->text(),
1171 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1172 array( 'mw-ui-progressive' )
1176 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1177 $top = $this->msg( 'search-showingresults' )
1178 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1179 ->numParams( $resultsShown )
1181 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1182 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1189 * Make a search link with some target namespaces
1191 * @param string $term
1192 * @param array $namespaces Ignored
1193 * @param string $label Link's text
1194 * @param string $tooltip Link's tooltip
1195 * @param array $params Query string parameters
1196 * @return string HTML fragment
1198 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1200 foreach ( $namespaces as $n ) {
1201 $opt['ns' . $n] = 1;
1204 $stParams = array_merge(
1207 'fulltext' => $this->msg( 'search' )->text()
1212 return Xml
::element(
1215 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1223 * Check if query starts with image: prefix
1225 * @param string $term The string to check
1228 protected function startsWithImage( $term ) {
1231 $parts = explode( ':', $term );
1232 if ( count( $parts ) > 1 ) {
1233 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1240 * Check if query starts with all: prefix
1242 * @param string $term The string to check
1245 protected function startsWithAll( $term ) {
1247 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1249 $parts = explode( ':', $term );
1250 if ( count( $parts ) > 1 ) {
1251 return $parts[0] == $allkeyword;
1260 * @return SearchEngine
1262 public function getSearchEngine() {
1263 if ( $this->searchEngine
=== null ) {
1264 $this->searchEngine
= $this->searchEngineType ?
1265 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1268 return $this->searchEngine
;
1272 * Current search profile.
1273 * @return null|string
1275 function getProfile() {
1276 return $this->profile
;
1280 * Current namespaces.
1283 function getNamespaces() {
1284 return $this->namespaces
;
1288 * Users of hook SpecialSearchSetupEngine can use this to
1289 * add more params to links to not lose selection when
1290 * user navigates search results.
1293 * @param string $key
1294 * @param mixed $value
1296 public function setExtraParam( $key, $value ) {
1297 $this->extraParams
[$key] = $value;
1300 protected function getGroupName() {