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 );
184 # If there's an exact or very near match, jump right there.
185 $t = SearchEngine
::getNearMatch( $term );
187 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
188 # Hook requested termination
192 if ( !is_null( $t ) ) {
193 $this->getOutput()->redirect( $t->getFullURL() );
196 # No match, generate an edit URL
197 $t = Title
::newFromText( $term );
198 if ( !is_null( $t ) ) {
200 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
201 wfDebugLog( 'nogomatch', $t->getFullText(), 'private' );
203 # If the feature is enabled, go straight to the edit page
205 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
209 $this->showResults( $term );
213 * @param $term String
215 public function showResults( $term ) {
216 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
217 wfProfileIn( __METHOD__
);
219 $search = $this->getSearchEngine();
220 $search->setLimitOffset( $this->limit
, $this->offset
);
221 $search->setNamespaces( $this->namespaces
);
222 $search->showRedirects
= $this->searchRedirects
; // BC
223 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
224 $search->prefix
= $this->mPrefix
;
225 $term = $search->transformSearchTerm( $term );
227 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
229 $this->setupPage( $term );
231 $out = $this->getOutput();
233 if ( $wgDisableTextSearch ) {
234 if ( $wgSearchForwardUrl ) {
235 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
236 $out->redirect( $url );
239 Xml
::openElement( 'fieldset' ) .
240 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
241 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
242 $this->msg( 'googlesearch' )->rawParams(
243 htmlspecialchars( $term ),
245 $this->msg( 'searchbutton' )->escaped()
247 Xml
::closeElement( 'fieldset' )
250 wfProfileOut( __METHOD__
);
254 $t = Title
::newFromText( $term );
255 $showSuggestion = $t === null ||
!$t->isKnown();
256 $search->setShowSuggestion( $showSuggestion );
258 // fetch search results
259 $rewritten = $search->replacePrefixes( $term );
261 $titleMatches = $search->searchTitle( $rewritten );
262 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
263 $textMatches = $search->searchText( $rewritten );
267 if ( $textMatches instanceof Status
) {
268 $textStatus = $textMatches;
272 // did you mean... suggestions
273 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
274 $st = SpecialPage
::getTitleFor( 'Search' );
276 # mirror Go/Search behavior of original request ..
277 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
279 if ( $this->fulltext
!= null ) {
280 $didYouMeanParams['fulltext'] = $this->fulltext
;
283 $stParams = array_merge(
285 $this->powerSearchOptions()
288 $suggestionSnippet = $textMatches->getSuggestionSnippet();
290 if ( $suggestionSnippet == '' ) {
291 $suggestionSnippet = null;
294 $suggestLink = Linker
::linkKnown(
301 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
304 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
305 # Hook requested termination
306 wfProfileOut( __METHOD__
);
310 // start rendering the page
315 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
317 'action' => $wgScript
322 # This is an awful awful ID name. It's not a table, but we
323 # named it poorly from when this was a table so now we're
325 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
326 $this->shortDialog( $term ) .
327 Xml
::closeElement( 'div' )
330 // Sometimes the search engine knows there are too many hits
331 if ( $titleMatches instanceof SearchResultTooMany
) {
332 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
333 wfProfileOut( __METHOD__
);
337 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
338 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
339 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
340 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
341 $out->addHTML( '</form>' );
342 // Empty query -- straight view of search form
343 wfProfileOut( __METHOD__
);
347 // Get number of results
348 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
349 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
350 // Total initial query matches (possible false positives)
351 $num = $titleMatchesNum +
$textMatchesNum;
353 // Get total actual results (after second filtering, if any)
354 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
355 $titleMatches->getTotalHits() : $titleMatchesNum;
356 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
357 $textMatches->getTotalHits() : $textMatchesNum;
359 // get total number of results if backend can calculate it
361 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
362 $totalRes +
= $titleMatches->getTotalHits();
364 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
365 $totalRes +
= $textMatches->getTotalHits();
368 // show number of results and current offset
369 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
370 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
372 $out->addHtml( Xml
::closeElement( 'form' ) );
373 $out->addHtml( "<div class='searchresults'>" );
376 if ( $num ||
$this->offset
) {
377 // Show the create link ahead
378 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
379 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset
, $this->limit
,
380 $this->powerSearchOptions() +
array( 'search' => $term ),
381 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
383 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
384 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
386 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
389 $out->parserOptions()->setEditSection( false );
390 if ( $titleMatches ) {
391 if ( $numTitleMatches > 0 ) {
392 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
393 $out->addHTML( $this->showMatches( $titleMatches ) );
395 $titleMatches->free();
397 if ( $textMatches && !$textStatus ) {
398 // output appropriate heading
399 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
400 // if no title matches the heading is redundant
401 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
402 } elseif ( $totalRes == 0 ) {
403 # Don't show the 'no text matches' if we received title matches
404 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
406 // show interwiki results if any
407 if ( $textMatches->hasInterwikiResults() ) {
408 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
411 if ( $numTextMatches > 0 ) {
412 $out->addHTML( $this->showMatches( $textMatches ) );
415 $textMatches->free();
419 $out->addHTML( '<div class="error">' .
420 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
422 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
423 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
424 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
427 $out->addHtml( "</div>" );
429 if ( $num ||
$this->offset
) {
430 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
432 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
433 wfProfileOut( __METHOD__
);
438 * @param int $num The number of search results found
439 * @param $titleMatches null|SearchResultSet results from title search
440 * @param $textMatches null|SearchResultSet results from text search
442 protected function showCreateLink( $t, $num, $titleMatches, $textMatches ) {
443 // show direct page/create link if applicable
445 // Check DBkey !== '' in case of fragment link only.
446 if ( is_null( $t ) ||
$t->getDBkey() === '' ||
447 ( $titleMatches !== null && $titleMatches->searchContainedSyntax() ) ||
448 ( $textMatches !== null && $textMatches->searchContainedSyntax() ) ) {
450 // preserve the paragraph for margins etc...
451 $this->getOutput()->addHtml( '<p></p>' );
455 if ( $t->isKnown() ) {
456 $messageName = 'searchmenu-exists';
457 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
458 $messageName = 'searchmenu-new';
460 $messageName = 'searchmenu-new-nocreate';
462 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message
::numParam( $num ) );
463 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
465 // Extensions using the hook might still return an empty $messageName
466 if ( $messageName ) {
467 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
469 // preserve the paragraph for margins etc...
470 $this->getOutput()->addHtml( '<p></p>' );
475 * @param $term string
477 protected function setupPage( $term ) {
478 # Should advanced UI be used?
479 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
480 $out = $this->getOutput();
481 if ( strval( $term ) !== '' ) {
482 $out->setPageTitle( $this->msg( 'searchresults' ) );
483 $out->setHTMLTitle( $this->msg( 'pagetitle' )
484 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
485 ->inContentLanguage()->text()
488 // add javascript specific to special:search
489 $out->addModules( 'mediawiki.special.search' );
493 * Extract "power search" namespace settings from the request object,
494 * returning a list of index numbers to search.
496 * @param $request WebRequest
499 protected function powerSearch( &$request ) {
501 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
502 if ( $request->getCheck( 'ns' . $ns ) ) {
511 * Reconstruct the 'power search' options for links
515 protected function powerSearchOptions() {
517 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
518 if ( $this->profile
!== 'advanced' ) {
519 $opt['profile'] = $this->profile
;
521 foreach ( $this->namespaces
as $n ) {
525 return $opt +
$this->extraParams
;
529 * Show whole set of results
531 * @param $matches SearchResultSet
535 protected function showMatches( &$matches ) {
537 wfProfileIn( __METHOD__
);
539 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
541 $out = "<ul class='mw-search-results'>\n";
542 $result = $matches->next();
544 $out .= $this->showHit( $result, $terms );
545 $result = $matches->next();
549 // convert the whole thing to desired language variant
550 $out = $wgContLang->convert( $out );
551 wfProfileOut( __METHOD__
);
556 * Format a single hit result
558 * @param $result SearchResult
559 * @param array $terms terms to highlight
563 protected function showHit( $result, $terms ) {
564 wfProfileIn( __METHOD__
);
566 if ( $result->isBrokenTitle() ) {
567 wfProfileOut( __METHOD__
);
568 return "<!-- Broken link in search result -->\n";
571 $t = $result->getTitle();
573 $titleSnippet = $result->getTitleSnippet( $terms );
575 if ( $titleSnippet == '' ) {
576 $titleSnippet = null;
581 wfRunHooks( 'ShowSearchHitTitle',
582 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
584 $link = Linker
::linkKnown(
589 //If page content is not readable, just return the title.
590 //This is not quite safe, but better than showing excerpts from non-readable pages
591 //Note that hiding the entry entirely would screw up paging.
592 if ( !$t->userCan( 'read', $this->getUser() ) ) {
593 wfProfileOut( __METHOD__
);
594 return "<li>{$link}</li>\n";
597 // If the page doesn't *exist*... our search index is out of date.
598 // The least confusing at this point is to drop the result.
599 // You may get less results, but... oh well. :P
600 if ( $result->isMissingRevision() ) {
601 wfProfileOut( __METHOD__
);
602 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
605 // format redirects / relevant sections
606 $redirectTitle = $result->getRedirectTitle();
607 $redirectText = $result->getRedirectSnippet( $terms );
608 $sectionTitle = $result->getSectionTitle();
609 $sectionText = $result->getSectionSnippet( $terms );
612 if ( !is_null( $redirectTitle ) ) {
613 if ( $redirectText == '' ) {
614 $redirectText = null;
617 $redirect = "<span class='searchalttitle'>" .
618 $this->msg( 'search-redirect' )->rawParams(
619 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
625 if ( !is_null( $sectionTitle ) ) {
626 if ( $sectionText == '' ) {
630 $section = "<span class='searchalttitle'>" .
631 $this->msg( 'search-section' )->rawParams(
632 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
636 // format text extract
637 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
639 $lang = $this->getLanguage();
642 if ( is_null( $result->getScore() ) ) {
643 // Search engine doesn't report scoring info
646 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
647 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
651 // format description
652 $byteSize = $result->getByteSize();
653 $wordCount = $result->getWordCount();
654 $timestamp = $result->getTimestamp();
655 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
656 ->numParams( $wordCount )->escaped();
658 if ( $t->getNamespace() == NS_CATEGORY
) {
659 $cat = Category
::newFromTitle( $t );
660 $size = $this->msg( 'search-result-category-size' )
661 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
665 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
667 // link to related articles if supported
669 if ( $result->hasRelated() ) {
670 $st = SpecialPage
::getTitleFor( 'Search' );
671 $stParams = array_merge(
672 $this->powerSearchOptions(),
674 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
675 ':' . $t->getPrefixedText(),
676 'fulltext' => $this->msg( 'search' )->text()
680 $related = ' -- ' . Linker
::linkKnown(
682 $this->msg( 'search-relatedarticle' )->text(),
689 // Include a thumbnail for media files...
690 if ( $t->getNamespace() == NS_FILE
) {
691 $img = $result->getFile();
692 $img = $img ?
: wfFindFile( $t );
693 if ( $result->isFileMatch() ) {
694 $fileMatch = "<span class='searchalttitle'>" .
695 $this->msg( 'search-file-match' )->escaped() . "</span>";
698 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
700 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
701 wfProfileOut( __METHOD__
);
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>" .
736 wfProfileOut( __METHOD__
);
741 * Show results from other wikis
743 * @param $matches SearchResultSet
744 * @param $query String
748 protected function showInterwiki( $matches, $query ) {
750 wfProfileIn( __METHOD__
);
751 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
753 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
754 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
755 $out .= "<ul class='mw-search-iwresults'>\n";
757 // work out custom project captions
758 $customCaptions = array();
759 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
760 foreach ( $customLines as $line ) {
761 $parts = explode( ":", $line, 2 );
762 if ( count( $parts ) == 2 ) { // validate line
763 $customCaptions[$parts[0]] = $parts[1];
768 $result = $matches->next();
770 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
771 $prev = $result->getInterwikiPrefix();
772 $result = $matches->next();
774 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
775 $out .= "</ul></div>\n";
777 // convert the whole thing to desired language variant
778 $out = $wgContLang->convert( $out );
779 wfProfileOut( __METHOD__
);
784 * Show single interwiki link
786 * @param $result SearchResult
787 * @param $lastInterwiki String
788 * @param $terms Array
789 * @param $query String
790 * @param array $customCaptions iw prefix -> caption
794 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
795 wfProfileIn( __METHOD__
);
797 if ( $result->isBrokenTitle() ) {
798 wfProfileOut( __METHOD__
);
799 return "<!-- Broken link in search result -->\n";
802 $t = $result->getTitle();
804 $titleSnippet = $result->getTitleSnippet();
806 if ( $titleSnippet == '' ) {
807 $titleSnippet = null;
810 $link = Linker
::linkKnown(
815 // format redirect if any
816 $redirectTitle = $result->getRedirectTitle();
817 $redirectText = $result->getRedirectSnippet();
819 if ( !is_null( $redirectTitle ) ) {
820 if ( $redirectText == '' ) {
821 $redirectText = null;
824 $redirect = "<span class='searchalttitle'>" .
825 $this->msg( 'search-redirect' )->rawParams(
826 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
831 // display project name
832 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
833 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
834 // captions from 'search-interwiki-custom'
835 $caption = $customCaptions[$t->getInterwiki()];
837 // default is to show the hostname of the other wiki which might suck
838 // if there are many wikis on one hostname
839 $parsed = wfParseUrl( $t->getFullURL() );
840 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
842 // "more results" link (special page stuff could be localized, but we might not know target lang)
843 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
844 $searchLink = Linker
::linkKnown(
846 $this->msg( 'search-interwiki-more' )->text(),
850 'fulltext' => 'Search'
853 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
854 {$searchLink}</span>{$caption}</div>\n<ul>";
857 $out .= "<li>{$link} {$redirect}</li>\n";
858 wfProfileOut( __METHOD__
);
867 protected function getProfileForm( $profile, $term ) {
870 $opts['redirs'] = $this->searchRedirects
;
871 $opts['profile'] = $this->profile
;
873 if ( $profile === 'advanced' ) {
874 return $this->powerSearchBox( $term, $opts );
877 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
883 * Generates the power search box at [[Special:Search]]
885 * @param string $term search term
887 * @return String: HTML form
889 protected function powerSearchBox( $term, $opts ) {
892 // Groups namespaces into rows according to subject
894 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
895 $subject = MWNamespace
::getSubject( $namespace );
896 if ( !array_key_exists( $subject, $rows ) ) {
897 $rows[$subject] = "";
900 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
902 $name = $this->msg( 'blanknamespace' )->text();
907 'td', array( 'style' => 'white-space: nowrap' )
912 "mw-search-ns{$namespace}",
913 in_array( $namespace, $this->namespaces
)
915 Xml
::closeElement( 'td' );
918 $rows = array_values( $rows );
919 $numRows = count( $rows );
921 // Lays out namespaces in multiple floating two-column tables so they'll
922 // be arranged nicely while still accommodating different screen widths
923 $namespaceTables = '';
924 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
925 $namespaceTables .= Xml
::openElement(
927 array( 'cellpadding' => 0, 'cellspacing' => 0 )
930 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
931 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
934 $namespaceTables .= Xml
::closeElement( 'table' );
937 $showSections = array( 'namespaceTables' => $namespaceTables );
939 // Show redirects check only if backend supports it
940 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
941 $showSections['redirects'] =
942 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
945 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
948 unset( $opts['redirs'] );
949 foreach ( $opts as $key => $value ) {
950 $hidden .= Html
::hidden( $key, $value );
952 // Return final output
953 return Xml
::openElement(
955 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
957 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
958 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
959 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
960 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
961 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
963 Xml
::closeElement( 'fieldset' );
969 protected function getSearchProfiles() {
970 // Builds list of Search Types (profiles)
971 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
975 'message' => 'searchprofile-articles',
976 'tooltip' => 'searchprofile-articles-tooltip',
977 'namespaces' => SearchEngine
::defaultNamespaces(),
978 'namespace-messages' => SearchEngine
::namespacesAsText(
979 SearchEngine
::defaultNamespaces()
983 'message' => 'searchprofile-images',
984 'tooltip' => 'searchprofile-images-tooltip',
985 'namespaces' => array( NS_FILE
),
988 'message' => 'searchprofile-project',
989 'tooltip' => 'searchprofile-project-tooltip',
990 'namespaces' => SearchEngine
::helpNamespaces(),
991 'namespace-messages' => SearchEngine
::namespacesAsText(
992 SearchEngine
::helpNamespaces()
996 'message' => 'searchprofile-everything',
997 'tooltip' => 'searchprofile-everything-tooltip',
998 'namespaces' => $nsAllSet,
1000 'advanced' => array(
1001 'message' => 'searchprofile-advanced',
1002 'tooltip' => 'searchprofile-advanced-tooltip',
1003 'namespaces' => self
::NAMESPACES_CURRENT
,
1007 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1009 foreach ( $profiles as &$data ) {
1010 if ( !is_array( $data['namespaces'] ) ) {
1013 sort( $data['namespaces'] );
1021 * @param $resultsShown
1025 protected function formHeader( $term, $resultsShown, $totalNum ) {
1026 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1029 if ( $this->startsWithImage( $term ) ) {
1031 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1034 $profiles = $this->getSearchProfiles();
1035 $lang = $this->getLanguage();
1037 // Outputs XML for Search Types
1038 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1039 $out .= Xml
::openElement( 'ul' );
1040 foreach ( $profiles as $id => $profile ) {
1041 if ( !isset( $profile['parameters'] ) ) {
1042 $profile['parameters'] = array();
1044 $profile['parameters']['profile'] = $id;
1046 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1047 $lang->commaList( $profile['namespace-messages'] ) : null;
1051 'class' => $this->profile
=== $id ?
'current' : 'normal'
1053 $this->makeSearchLink(
1056 $this->msg( $profile['message'] )->text(),
1057 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1058 $profile['parameters']
1062 $out .= Xml
::closeElement( 'ul' );
1063 $out .= Xml
::closeElement( 'div' );
1066 if ( $resultsShown > 0 ) {
1067 if ( $totalNum > 0 ) {
1068 $top = $this->msg( 'showingresultsheader' )
1069 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1070 ->params( wfEscapeWikiText( $term ) )
1071 ->numParams( $resultsShown )
1073 } elseif ( $resultsShown >= $this->limit
) {
1074 $top = $this->msg( 'showingresults' )
1075 ->numParams( $this->limit
, $this->offset +
1 )
1078 $top = $this->msg( 'showingresultsnum' )
1079 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1082 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1083 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1087 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1088 $out .= Xml
::closeElement( 'div' );
1094 * @param $term string
1097 protected function shortDialog( $term ) {
1098 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1099 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1101 $out .= Html
::input( 'search', $term, 'search', array(
1102 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1105 'class' => 'mw-ui-input',
1107 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1108 $out .= Xml
::submitButton(
1109 $this->msg( 'searchbutton' )->text(),
1110 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1112 return $out . $this->didYouMeanHtml
;
1116 * Make a search link with some target namespaces
1118 * @param $term String
1119 * @param array $namespaces ignored
1120 * @param string $label link's text
1121 * @param string $tooltip link's tooltip
1122 * @param array $params query string parameters
1123 * @return String: HTML fragment
1125 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1127 foreach ( $namespaces as $n ) {
1128 $opt['ns' . $n] = 1;
1130 $opt['redirs'] = $this->searchRedirects
;
1132 $stParams = array_merge(
1135 'fulltext' => $this->msg( 'search' )->text()
1140 return Xml
::element(
1143 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1151 * Check if query starts with image: prefix
1153 * @param string $term the string to check
1156 protected function startsWithImage( $term ) {
1159 $p = explode( ':', $term );
1160 if ( count( $p ) > 1 ) {
1161 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1167 * Check if query starts with all: prefix
1169 * @param string $term the string to check
1172 protected function startsWithAll( $term ) {
1174 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1176 $p = explode( ':', $term );
1177 if ( count( $p ) > 1 ) {
1178 return $p[0] == $allkeyword;
1186 * @return SearchEngine
1188 public function getSearchEngine() {
1189 if ( $this->searchEngine
=== null ) {
1190 $this->searchEngine
= $this->searchEngineType ?
1191 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1193 return $this->searchEngine
;
1197 * Current search profile.
1198 * @return null|string
1200 function getProfile() {
1201 return $this->profile
;
1205 * Current namespaces.
1208 function getNamespaces() {
1209 return $this->namespaces
;
1213 * Users of hook SpecialSearchSetupEngine can use this to
1214 * add more params to links to not lose selection when
1215 * user navigates search results.
1221 public function setExtraParam( $key, $value ) {
1222 $this->extraParams
[$key] = $value;
1225 protected function getGroupName() {