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, help, 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.
42 protected $searchEngine;
44 /// Search engine type, if not default
45 protected $searchEngineType;
48 protected $extraParams = array();
50 /// No idea, apparently used by some other classes
56 protected $limit, $offset;
61 protected $namespaces;
66 protected $searchRedirects;
71 protected $didYouMeanHtml, $fulltext;
73 const NAMESPACES_CURRENT
= 'sense';
75 public function __construct() {
76 parent
::__construct( 'Search' );
82 * @param string $par or null
84 public function execute( $par ) {
86 $this->outputHeader();
87 $out = $this->getOutput();
88 $out->allowClickjacking();
89 $out->addModuleStyles( array(
90 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button'
93 // Strip underscores from title parameter; most of the time we'll want
94 // text form here. But don't strip underscores from actual text params!
95 $titleParam = str_replace( '_', ' ', $par );
97 $request = $this->getRequest();
99 // Fetch the search term
100 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
104 $this->searchEngineType
= $request->getVal( 'srbackend' );
106 if ( $request->getVal( 'fulltext' )
107 ||
!is_null( $request->getVal( 'offset' ) )
109 $this->showResults( $search );
111 $this->goResult( $search );
116 * Set up basic search parameters from the request and user settings.
118 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
120 public function load() {
121 $request = $this->getRequest();
122 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20 );
123 $this->mPrefix
= $request->getVal( 'prefix', '' );
125 $user = $this->getUser();
127 # Extract manually requested namespaces
128 $nslist = $this->powerSearch( $request );
129 if ( !count( $nslist ) ) {
130 # Fallback to user preference
131 $nslist = SearchEngine
::userNamespaces( $user );
135 if ( !count( $nslist ) ) {
136 $profile = 'default';
139 $profile = $request->getVal( 'profile', $profile );
140 $profiles = $this->getSearchProfiles();
141 if ( $profile === null ) {
142 // BC with old request format
143 $profile = 'advanced';
144 foreach ( $profiles as $key => $data ) {
145 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
149 $this->namespaces
= $nslist;
150 } elseif ( $profile === 'advanced' ) {
151 $this->namespaces
= $nslist;
153 if ( isset( $profiles[$profile]['namespaces'] ) ) {
154 $this->namespaces
= $profiles[$profile]['namespaces'];
156 // Unknown profile requested
157 $profile = 'default';
158 $this->namespaces
= $profiles['default']['namespaces'];
162 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
163 $default = $request->getBool( 'profile' ) ?
0 : 1;
164 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
165 $this->didYouMeanHtml
= ''; # html of did you mean... link
166 $this->fulltext
= $request->getVal( 'fulltext' );
167 $this->profile
= $profile;
171 * If an exact title match can be found, jump straight ahead to it.
173 * @param $term String
175 public function goResult( $term ) {
176 $this->setupPage( $term );
177 # Try to go to page as entered.
178 $t = Title
::newFromText( $term );
179 # If the string cannot be used to create a title
180 if ( is_null( $t ) ) {
181 $this->showResults( $term );
185 # If there's an exact or very near match, jump right there.
186 $t = SearchEngine
::getNearMatch( $term );
188 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
189 # Hook requested termination
193 if ( !is_null( $t ) ) {
194 $this->getOutput()->redirect( $t->getFullURL() );
198 # No match, generate an edit URL
199 $t = Title
::newFromText( $term );
200 if ( !is_null( $t ) ) {
202 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
203 wfDebugLog( 'nogomatch', $t->getFullText(), 'private' );
205 # If the feature is enabled, go straight to the edit page
207 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
212 $this->showResults( $term );
216 * @param $term String
218 public function showResults( $term ) {
219 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
221 $profile = new ProfileSection( __METHOD__
);
222 $search = $this->getSearchEngine();
223 $search->setLimitOffset( $this->limit
, $this->offset
);
224 $search->setNamespaces( $this->namespaces
);
225 $search->showRedirects
= $this->searchRedirects
; // BC
226 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
227 $search->prefix
= $this->mPrefix
;
228 $term = $search->transformSearchTerm( $term );
230 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
232 $this->setupPage( $term );
234 $out = $this->getOutput();
236 if ( $wgDisableTextSearch ) {
237 if ( $wgSearchForwardUrl ) {
238 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
239 $out->redirect( $url );
242 Xml
::openElement( 'fieldset' ) .
243 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
244 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
245 $this->msg( 'googlesearch' )->rawParams(
246 htmlspecialchars( $term ),
248 $this->msg( 'searchbutton' )->escaped()
250 Xml
::closeElement( 'fieldset' )
257 $t = Title
::newFromText( $term );
258 $showSuggestion = $t === null ||
!$t->isKnown();
259 $search->setShowSuggestion( $showSuggestion );
261 // fetch search results
262 $rewritten = $search->replacePrefixes( $term );
264 $titleMatches = $search->searchTitle( $rewritten );
265 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
266 $textMatches = $search->searchText( $rewritten );
270 if ( $textMatches instanceof Status
) {
271 $textStatus = $textMatches;
275 // did you mean... suggestions
276 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
277 $st = SpecialPage
::getTitleFor( 'Search' );
279 # mirror Go/Search behavior of original request ..
280 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
282 if ( $this->fulltext
!= null ) {
283 $didYouMeanParams['fulltext'] = $this->fulltext
;
286 $stParams = array_merge(
288 $this->powerSearchOptions()
291 $suggestionSnippet = $textMatches->getSuggestionSnippet();
293 if ( $suggestionSnippet == '' ) {
294 $suggestionSnippet = null;
297 $suggestLink = Linker
::linkKnown(
304 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
307 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
308 # Hook requested termination
312 // start rendering the page
317 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
319 'action' => $wgScript
324 # This is an awful awful ID name. It's not a table, but we
325 # named it poorly from when this was a table so now we're
327 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
328 $this->shortDialog( $term ) .
329 Xml
::closeElement( 'div' )
332 // Sometimes the search engine knows there are too many hits
333 if ( $titleMatches instanceof SearchResultTooMany
) {
334 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
339 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
340 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
341 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
342 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
343 $out->addHTML( '</form>' );
345 // Empty query -- straight view of search form
349 // Get number of results
350 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
351 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
352 // Total initial query matches (possible false positives)
353 $num = $titleMatchesNum +
$textMatchesNum;
355 // Get total actual results (after second filtering, if any)
356 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
357 $titleMatches->getTotalHits() : $titleMatchesNum;
358 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
359 $textMatches->getTotalHits() : $textMatchesNum;
361 // get total number of results if backend can calculate it
363 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
364 $totalRes +
= $titleMatches->getTotalHits();
366 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
367 $totalRes +
= $textMatches->getTotalHits();
370 // show number of results and current offset
371 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
372 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
374 $out->addHtml( Xml
::closeElement( 'form' ) );
375 $out->addHtml( "<div class='searchresults'>" );
378 if ( $num ||
$this->offset
) {
379 // Show the create link ahead
380 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
381 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset
, $this->limit
,
382 $this->powerSearchOptions() +
array( 'search' => $term ),
383 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
385 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
386 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
388 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
391 $out->parserOptions()->setEditSection( false );
392 if ( $titleMatches ) {
393 if ( $numTitleMatches > 0 ) {
394 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
395 $out->addHTML( $this->showMatches( $titleMatches ) );
397 $titleMatches->free();
399 if ( $textMatches && !$textStatus ) {
400 // output appropriate heading
401 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
402 // if no title matches the heading is redundant
403 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
404 } elseif ( $totalRes == 0 ) {
405 # Don't show the 'no text matches' if we received title matches
406 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
408 // show interwiki results if any
409 if ( $textMatches->hasInterwikiResults() ) {
410 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
413 if ( $numTextMatches > 0 ) {
414 $out->addHTML( $this->showMatches( $textMatches ) );
417 $textMatches->free();
421 $out->addHTML( '<div class="error">' .
422 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
424 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
425 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
426 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
429 $out->addHtml( "</div>" );
431 if ( $num ||
$this->offset
) {
432 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
434 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
439 * @param int $num The number of search results found
440 * @param $titleMatches null|SearchResultSet results from title search
441 * @param $textMatches null|SearchResultSet results from text search
443 protected function showCreateLink( $t, $num, $titleMatches, $textMatches ) {
444 // show direct page/create link if applicable
446 // Check DBkey !== '' in case of fragment link only.
447 if ( is_null( $t ) ||
$t->getDBkey() === ''
448 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
449 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
452 // preserve the paragraph for margins etc...
453 $this->getOutput()->addHtml( '<p></p>' );
458 if ( $t->isKnown() ) {
459 $messageName = 'searchmenu-exists';
460 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
461 $messageName = 'searchmenu-new';
463 $messageName = 'searchmenu-new-nocreate';
465 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message
::numParam( $num ) );
466 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
468 // Extensions using the hook might still return an empty $messageName
469 if ( $messageName ) {
470 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
472 // preserve the paragraph for margins etc...
473 $this->getOutput()->addHtml( '<p></p>' );
478 * @param $term string
480 protected function setupPage( $term ) {
481 # Should advanced UI be used?
482 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
483 $out = $this->getOutput();
484 if ( strval( $term ) !== '' ) {
485 $out->setPageTitle( $this->msg( 'searchresults' ) );
486 $out->setHTMLTitle( $this->msg( 'pagetitle' )
487 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
488 ->inContentLanguage()->text()
491 // add javascript specific to special:search
492 $out->addModules( 'mediawiki.special.search' );
496 * Extract "power search" namespace settings from the request object,
497 * returning a list of index numbers to search.
499 * @param $request WebRequest
502 protected function powerSearch( &$request ) {
504 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
505 if ( $request->getCheck( 'ns' . $ns ) ) {
514 * Reconstruct the 'power search' options for links
518 protected function powerSearchOptions() {
520 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
521 if ( $this->profile
!== 'advanced' ) {
522 $opt['profile'] = $this->profile
;
524 foreach ( $this->namespaces
as $n ) {
529 return $opt +
$this->extraParams
;
533 * Show whole set of results
535 * @param $matches SearchResultSet
539 protected function showMatches( &$matches ) {
542 $profile = new ProfileSection( __METHOD__
);
543 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
545 $out = "<ul class='mw-search-results'>\n";
546 $result = $matches->next();
548 $out .= $this->showHit( $result, $terms );
549 $result = $matches->next();
553 // convert the whole thing to desired language variant
554 $out = $wgContLang->convert( $out );
560 * Format a single hit result
562 * @param $result SearchResult
563 * @param array $terms terms to highlight
567 protected function showHit( $result, $terms ) {
568 $profile = new ProfileSection( __METHOD__
);
570 if ( $result->isBrokenTitle() ) {
571 return "<!-- Broken link in search result -->\n";
574 $t = $result->getTitle();
576 $titleSnippet = $result->getTitleSnippet( $terms );
578 if ( $titleSnippet == '' ) {
579 $titleSnippet = null;
584 wfRunHooks( 'ShowSearchHitTitle',
585 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
587 $link = Linker
::linkKnown(
592 //If page content is not readable, just return the title.
593 //This is not quite safe, but better than showing excerpts from non-readable pages
594 //Note that hiding the entry entirely would screw up paging.
595 if ( !$t->userCan( 'read', $this->getUser() ) ) {
596 return "<li>{$link}</li>\n";
599 // If the page doesn't *exist*... our search index is out of date.
600 // The least confusing at this point is to drop the result.
601 // You may get less results, but... oh well. :P
602 if ( $result->isMissingRevision() ) {
603 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
606 // format redirects / relevant sections
607 $redirectTitle = $result->getRedirectTitle();
608 $redirectText = $result->getRedirectSnippet( $terms );
609 $sectionTitle = $result->getSectionTitle();
610 $sectionText = $result->getSectionSnippet( $terms );
613 if ( !is_null( $redirectTitle ) ) {
614 if ( $redirectText == '' ) {
615 $redirectText = null;
618 $redirect = "<span class='searchalttitle'>" .
619 $this->msg( 'search-redirect' )->rawParams(
620 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
626 if ( !is_null( $sectionTitle ) ) {
627 if ( $sectionText == '' ) {
631 $section = "<span class='searchalttitle'>" .
632 $this->msg( 'search-section' )->rawParams(
633 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
637 // format text extract
638 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
640 $lang = $this->getLanguage();
643 if ( is_null( $result->getScore() ) ) {
644 // Search engine doesn't report scoring info
647 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
648 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
652 // format description
653 $byteSize = $result->getByteSize();
654 $wordCount = $result->getWordCount();
655 $timestamp = $result->getTimestamp();
656 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
657 ->numParams( $wordCount )->escaped();
659 if ( $t->getNamespace() == NS_CATEGORY
) {
660 $cat = Category
::newFromTitle( $t );
661 $size = $this->msg( 'search-result-category-size' )
662 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
666 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
668 // link to related articles if supported
670 if ( $result->hasRelated() ) {
671 $st = SpecialPage
::getTitleFor( 'Search' );
672 $stParams = array_merge(
673 $this->powerSearchOptions(),
675 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
676 ':' . $t->getPrefixedText(),
677 'fulltext' => $this->msg( 'search' )->text()
681 $related = ' -- ' . Linker
::linkKnown(
683 $this->msg( 'search-relatedarticle' )->text(),
690 // Include a thumbnail for media files...
691 if ( $t->getNamespace() == NS_FILE
) {
692 $img = $result->getFile();
693 $img = $img ?
: wfFindFile( $t );
694 if ( $result->isFileMatch() ) {
695 $fileMatch = "<span class='searchalttitle'>" .
696 $this->msg( 'search-file-match' )->escaped() . "</span>";
699 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
701 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
702 // Float doesn't seem to interact well with the bullets.
703 // Table messes up vertical alignment of the bullets.
704 // Bullets are therefore disabled (didn't look great anyway).
706 '<table class="searchResultImage">' .
708 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
709 $thumb->toHtml( array( 'desc-link' => true ) ) .
711 '<td style="vertical-align: top;">' .
712 "{$link} {$fileMatch}" .
714 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
725 if ( wfRunHooks( 'ShowSearchHit', array(
726 $this, $result, $terms,
727 &$link, &$redirect, &$section, &$extract,
728 &$score, &$size, &$date, &$related,
731 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
732 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
740 * Show results from other wikis
742 * @param $matches SearchResultSet|array
743 * @param $query String
747 protected function showInterwiki( $matches, $query ) {
749 $profile = new ProfileSection( __METHOD__
);
751 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
752 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
753 $out .= "<ul class='mw-search-iwresults'>\n";
755 // work out custom project captions
756 $customCaptions = array();
757 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
758 foreach ( $customLines as $line ) {
759 $parts = explode( ":", $line, 2 );
760 if ( count( $parts ) == 2 ) { // validate line
761 $customCaptions[$parts[0]] = $parts[1];
765 if ( !is_array( $matches ) ) {
766 $matches = array( $matches );
769 foreach ( $matches as $set ) {
771 $result = $set->next();
773 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
774 $prev = $result->getInterwikiPrefix();
775 $result = $set->next();
780 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
781 $out .= "</ul></div>\n";
783 // convert the whole thing to desired language variant
784 $out = $wgContLang->convert( $out );
790 * Show single interwiki link
792 * @param $result SearchResult
793 * @param $lastInterwiki String
794 * @param $query String
795 * @param array $customCaptions iw prefix -> caption
799 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
800 $profile = new ProfileSection( __METHOD__
);
802 if ( $result->isBrokenTitle() ) {
803 return "<!-- Broken link in search result -->\n";
806 $t = $result->getTitle();
808 $titleSnippet = $result->getTitleSnippet();
810 if ( $titleSnippet == '' ) {
811 $titleSnippet = null;
814 $link = Linker
::linkKnown(
819 // format redirect if any
820 $redirectTitle = $result->getRedirectTitle();
821 $redirectText = $result->getRedirectSnippet();
823 if ( !is_null( $redirectTitle ) ) {
824 if ( $redirectText == '' ) {
825 $redirectText = null;
828 $redirect = "<span class='searchalttitle'>" .
829 $this->msg( 'search-redirect' )->rawParams(
830 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
835 // display project name
836 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
837 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
838 // captions from 'search-interwiki-custom'
839 $caption = $customCaptions[$t->getInterwiki()];
841 // default is to show the hostname of the other wiki which might suck
842 // if there are many wikis on one hostname
843 $parsed = wfParseUrl( $t->getFullURL() );
844 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
846 // "more results" link (special page stuff could be localized, but we might not know target lang)
847 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
848 $searchLink = Linker
::linkKnown(
850 $this->msg( 'search-interwiki-more' )->text(),
854 'fulltext' => 'Search'
857 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
858 {$searchLink}</span>{$caption}</div>\n<ul>";
861 $out .= "<li>{$link} {$redirect}</li>\n";
871 protected function getProfileForm( $profile, $term ) {
874 $opts['redirs'] = $this->searchRedirects
;
875 $opts['profile'] = $this->profile
;
877 if ( $profile === 'advanced' ) {
878 return $this->powerSearchBox( $term, $opts );
881 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
888 * Generates the power search box at [[Special:Search]]
890 * @param string $term search term
892 * @return String: HTML form
894 protected function powerSearchBox( $term, $opts ) {
897 // Groups namespaces into rows according to subject
899 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
900 $subject = MWNamespace
::getSubject( $namespace );
901 if ( !array_key_exists( $subject, $rows ) ) {
902 $rows[$subject] = "";
905 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
907 $name = $this->msg( 'blanknamespace' )->text();
912 'td', array( 'style' => 'white-space: nowrap' )
917 "mw-search-ns{$namespace}",
918 in_array( $namespace, $this->namespaces
)
920 Xml
::closeElement( 'td' );
923 $rows = array_values( $rows );
924 $numRows = count( $rows );
926 // Lays out namespaces in multiple floating two-column tables so they'll
927 // be arranged nicely while still accommodating different screen widths
928 $namespaceTables = '';
929 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
930 $namespaceTables .= Xml
::openElement(
932 array( 'cellpadding' => 0, 'cellspacing' => 0 )
935 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
936 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
939 $namespaceTables .= Xml
::closeElement( 'table' );
942 $showSections = array( 'namespaceTables' => $namespaceTables );
944 // Show redirects check only if backend supports it
945 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
946 $showSections['redirects'] =
947 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
950 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
953 unset( $opts['redirs'] );
954 foreach ( $opts as $key => $value ) {
955 $hidden .= Html
::hidden( $key, $value );
958 // Return final output
959 return Xml
::openElement(
961 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
963 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
964 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
965 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
966 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
967 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
969 Xml
::closeElement( 'fieldset' );
975 protected function getSearchProfiles() {
976 // Builds list of Search Types (profiles)
977 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
981 'message' => 'searchprofile-articles',
982 'tooltip' => 'searchprofile-articles-tooltip',
983 'namespaces' => SearchEngine
::defaultNamespaces(),
984 'namespace-messages' => SearchEngine
::namespacesAsText(
985 SearchEngine
::defaultNamespaces()
989 'message' => 'searchprofile-images',
990 'tooltip' => 'searchprofile-images-tooltip',
991 'namespaces' => array( NS_FILE
),
994 'message' => 'searchprofile-project',
995 'tooltip' => 'searchprofile-project-tooltip',
996 'namespaces' => SearchEngine
::helpNamespaces(),
997 'namespace-messages' => SearchEngine
::namespacesAsText(
998 SearchEngine
::helpNamespaces()
1002 'message' => 'searchprofile-everything',
1003 'tooltip' => 'searchprofile-everything-tooltip',
1004 'namespaces' => $nsAllSet,
1006 'advanced' => array(
1007 'message' => 'searchprofile-advanced',
1008 'tooltip' => 'searchprofile-advanced-tooltip',
1009 'namespaces' => self
::NAMESPACES_CURRENT
,
1013 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1015 foreach ( $profiles as &$data ) {
1016 if ( !is_array( $data['namespaces'] ) ) {
1019 sort( $data['namespaces'] );
1027 * @param $resultsShown
1031 protected function formHeader( $term, $resultsShown, $totalNum ) {
1032 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1035 if ( $this->startsWithImage( $term ) ) {
1037 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1040 $profiles = $this->getSearchProfiles();
1041 $lang = $this->getLanguage();
1043 // Outputs XML for Search Types
1044 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1045 $out .= Xml
::openElement( 'ul' );
1046 foreach ( $profiles as $id => $profile ) {
1047 if ( !isset( $profile['parameters'] ) ) {
1048 $profile['parameters'] = array();
1050 $profile['parameters']['profile'] = $id;
1052 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1053 $lang->commaList( $profile['namespace-messages'] ) : null;
1057 'class' => $this->profile
=== $id ?
'current' : 'normal'
1059 $this->makeSearchLink(
1062 $this->msg( $profile['message'] )->text(),
1063 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1064 $profile['parameters']
1068 $out .= Xml
::closeElement( 'ul' );
1069 $out .= Xml
::closeElement( 'div' );
1072 if ( $resultsShown > 0 ) {
1073 if ( $totalNum > 0 ) {
1074 $top = $this->msg( 'showingresultsheader' )
1075 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1076 ->params( wfEscapeWikiText( $term ) )
1077 ->numParams( $resultsShown )
1079 } elseif ( $resultsShown >= $this->limit
) {
1080 $top = $this->msg( 'showingresults' )
1081 ->numParams( $this->limit
, $this->offset +
1 )
1084 $top = $this->msg( 'showingresultsnum' )
1085 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1088 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1089 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1093 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1094 $out .= Xml
::closeElement( 'div' );
1100 * @param $term string
1103 protected function shortDialog( $term ) {
1104 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1105 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1107 $out .= Html
::input( 'search', $term, 'search', array(
1108 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1111 'class' => 'mw-ui-input',
1113 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1114 $out .= Xml
::submitButton(
1115 $this->msg( 'searchbutton' )->text(),
1116 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1119 return $out . $this->didYouMeanHtml
;
1123 * Make a search link with some target namespaces
1125 * @param $term String
1126 * @param array $namespaces ignored
1127 * @param string $label link's text
1128 * @param string $tooltip link's tooltip
1129 * @param array $params query string parameters
1130 * @return String: HTML fragment
1132 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1134 foreach ( $namespaces as $n ) {
1135 $opt['ns' . $n] = 1;
1137 $opt['redirs'] = $this->searchRedirects
;
1139 $stParams = array_merge(
1142 'fulltext' => $this->msg( 'search' )->text()
1147 return Xml
::element(
1150 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1158 * Check if query starts with image: prefix
1160 * @param string $term the string to check
1163 protected function startsWithImage( $term ) {
1166 $p = explode( ':', $term );
1167 if ( count( $p ) > 1 ) {
1168 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1175 * Check if query starts with all: prefix
1177 * @param string $term the string to check
1180 protected function startsWithAll( $term ) {
1182 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1184 $p = explode( ':', $term );
1185 if ( count( $p ) > 1 ) {
1186 return $p[0] == $allkeyword;
1195 * @return SearchEngine
1197 public function getSearchEngine() {
1198 if ( $this->searchEngine
=== null ) {
1199 $this->searchEngine
= $this->searchEngineType ?
1200 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1203 return $this->searchEngine
;
1207 * Current search profile.
1208 * @return null|string
1210 function getProfile() {
1211 return $this->profile
;
1215 * Current namespaces.
1218 function getNamespaces() {
1219 return $this->namespaces
;
1223 * Users of hook SpecialSearchSetupEngine can use this to
1224 * add more params to links to not lose selection when
1225 * user navigates search results.
1231 public function setExtraParam( $key, $value ) {
1232 $this->extraParams
[$key] = $value;
1235 protected function getGroupName() {