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.
40 function getProfile() { return $this->profile
; }
43 protected $searchEngine;
45 /// Search engine type, if not default
46 protected $searchEngineType;
49 protected $extraParams = array();
51 /// No idea, apparently used by some other classes
57 protected $limit, $offset;
62 protected $namespaces;
63 function getNamespaces() { return $this->namespaces
; }
68 protected $searchRedirects;
73 protected $didYouMeanHtml, $fulltext;
75 const NAMESPACES_CURRENT
= 'sense';
77 public function __construct() {
78 parent
::__construct( 'Search' );
84 * @param string $par or null
86 public function execute( $par ) {
88 $this->outputHeader();
89 $out = $this->getOutput();
90 $out->allowClickjacking();
91 $out->addModuleStyles( array(
92 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui'
95 // Strip underscores from title parameter; most of the time we'll want
96 // text form here. But don't strip underscores from actual text params!
97 $titleParam = str_replace( '_', ' ', $par );
99 $request = $this->getRequest();
101 // Fetch the search term
102 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
106 $this->searchEngineType
= $request->getVal( 'srbackend' );
108 if ( $request->getVal( 'fulltext' )
109 ||
!is_null( $request->getVal( 'offset' ) )
110 ||
!is_null( $request->getVal( 'searchx' ) )
112 $this->showResults( $search );
114 $this->goResult( $search );
119 * Set up basic search parameters from the request and user settings.
121 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
123 public function load() {
124 $request = $this->getRequest();
125 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
126 $this->mPrefix
= $request->getVal( 'prefix', '' );
128 $user = $this->getUser();
130 # Extract manually requested namespaces
131 $nslist = $this->powerSearch( $request );
132 if ( !count( $nslist ) ) {
133 # Fallback to user preference
134 $nslist = SearchEngine
::userNamespaces( $user );
138 if ( !count( $nslist ) ) {
139 $profile = 'default';
142 $profile = $request->getVal( 'profile', $profile );
143 $profiles = $this->getSearchProfiles();
144 if ( $profile === null ) {
145 // BC with old request format
146 $profile = 'advanced';
147 foreach ( $profiles as $key => $data ) {
148 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
152 $this->namespaces
= $nslist;
153 } elseif ( $profile === 'advanced' ) {
154 $this->namespaces
= $nslist;
156 if ( isset( $profiles[$profile]['namespaces'] ) ) {
157 $this->namespaces
= $profiles[$profile]['namespaces'];
159 // Unknown profile requested
160 $profile = 'default';
161 $this->namespaces
= $profiles['default']['namespaces'];
165 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
166 $default = $request->getBool( 'profile' ) ?
0 : 1;
167 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
168 $this->didYouMeanHtml
= ''; # html of did you mean... link
169 $this->fulltext
= $request->getVal( 'fulltext' );
170 $this->profile
= $profile;
174 * If an exact title match can be found, jump straight ahead to it.
176 * @param $term String
178 public function goResult( $term ) {
179 $this->setupPage( $term );
180 # Try to go to page as entered.
181 $t = Title
::newFromText( $term );
182 # If the string cannot be used to create a title
183 if ( is_null( $t ) ) {
184 $this->showResults( $term );
187 # If there's an exact or very near match, jump right there.
188 $t = SearchEngine
::getNearMatch( $term );
190 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
191 # Hook requested termination
195 if ( !is_null( $t ) ) {
196 $this->getOutput()->redirect( $t->getFullURL() );
199 # No match, generate an edit URL
200 $t = Title
::newFromText( $term );
201 if ( !is_null( $t ) ) {
203 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
204 wfDebugLog( 'nogomatch', $t->getText(), false );
206 # If the feature is enabled, go straight to the edit page
208 $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;
220 wfProfileIn( __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' )
253 wfProfileOut( __METHOD__
);
257 $t = Title
::newFromText( $term );
259 // fetch search results
260 $rewritten = $search->replacePrefixes( $term );
262 $titleMatches = $search->searchTitle( $rewritten );
263 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
264 $textMatches = $search->searchText( $rewritten );
268 if ( $textMatches instanceof Status
) {
269 $textStatus = $textMatches;
273 // did you mean... suggestions
274 if ( $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
275 $st = SpecialPage
::getTitleFor( 'Search' );
277 # mirror Go/Search behavior of original request ..
278 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
280 if ( $this->fulltext
!= null ) {
281 $didYouMeanParams['fulltext'] = $this->fulltext
;
284 $stParams = array_merge(
286 $this->powerSearchOptions()
289 $suggestionSnippet = $textMatches->getSuggestionSnippet();
291 if ( $suggestionSnippet == '' ) {
292 $suggestionSnippet = null;
295 $suggestLink = Linker
::linkKnown(
302 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
305 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
306 # Hook requested termination
307 wfProfileOut( __METHOD__
);
311 // start rendering the page
316 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
318 'action' => $wgScript
323 # This is an awful awful ID name. It's not a table, but we
324 # named it poorly from when this was a table so now we're
326 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
327 $this->shortDialog( $term ) .
328 Xml
::closeElement( 'div' )
331 // Sometimes the search engine knows there are too many hits
332 if ( $titleMatches instanceof SearchResultTooMany
) {
333 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
334 wfProfileOut( __METHOD__
);
338 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
339 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
340 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
341 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
342 $out->addHTML( '</form>' );
343 // Empty query -- straight view of search form
344 wfProfileOut( __METHOD__
);
348 // Get number of results
349 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
350 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
351 // Total initial query matches (possible false positives)
352 $num = $titleMatchesNum +
$textMatchesNum;
354 // Get total actual results (after second filtering, if any)
355 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
356 $titleMatches->getTotalHits() : $titleMatchesNum;
357 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
358 $textMatches->getTotalHits() : $textMatchesNum;
360 // get total number of results if backend can calculate it
362 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
363 $totalRes +
= $titleMatches->getTotalHits();
365 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
366 $totalRes +
= $textMatches->getTotalHits();
369 // show number of results and current offset
370 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
371 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
373 $out->addHtml( Xml
::closeElement( 'form' ) );
374 $out->addHtml( "<div class='searchresults'>" );
377 if ( $num ||
$this->offset
) {
378 // Show the create link ahead
379 $this->showCreateLink( $t, $num );
380 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset
, $this->limit
,
381 $this->powerSearchOptions() +
array( 'search' => $term ),
382 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
384 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
385 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
387 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
390 $out->parserOptions()->setEditSection( false );
391 if ( $titleMatches ) {
392 if ( $numTitleMatches > 0 ) {
393 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
394 $out->addHTML( $this->showMatches( $titleMatches ) );
396 $titleMatches->free();
398 if ( $textMatches && !$textStatus ) {
399 // output appropriate heading
400 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
401 // if no title matches the heading is redundant
402 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
403 } elseif ( $totalRes == 0 ) {
404 # Don't show the 'no text matches' if we received title matches
405 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
407 // show interwiki results if any
408 if ( $textMatches->hasInterwikiResults() ) {
409 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
412 if ( $numTextMatches > 0 ) {
413 $out->addHTML( $this->showMatches( $textMatches ) );
416 $textMatches->free();
420 $out->addHTML( '<div class="error">' .
421 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
423 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
424 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
425 $this->showCreateLink( $t, $num );
428 $out->addHtml( "</div>" );
430 if ( $num ||
$this->offset
) {
431 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
433 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
434 wfProfileOut( __METHOD__
);
439 * @param int $num The number of search results found
441 protected function showCreateLink( $t, $num ) {
442 // show direct page/create link if applicable
444 // Check DBkey !== '' in case of fragment link only.
445 if ( is_null( $t ) ||
$t->getDBkey() === '' ) {
447 // preserve the paragraph for margins etc...
448 $this->getOutput()->addHtml( '<p></p>' );
452 if ( $t->isKnown() ) {
453 $messageName = 'searchmenu-exists';
454 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
455 $messageName = 'searchmenu-new';
457 $messageName = 'searchmenu-new-nocreate';
459 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message
::numParam( $num ) );
460 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
462 // Extensions using the hook might still return an empty $messageName
463 if ( $messageName ) {
464 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
466 // preserve the paragraph for margins etc...
467 $this->getOutput()->addHtml( '<p></p>' );
472 * @param $term string
474 protected function setupPage( $term ) {
475 # Should advanced UI be used?
476 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
477 $out = $this->getOutput();
478 if ( strval( $term ) !== '' ) {
479 $out->setPageTitle( $this->msg( 'searchresults' ) );
480 $out->setHTMLTitle( $this->msg( 'pagetitle' )
481 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term ) )
482 ->inContentLanguage()->text()
485 // add javascript specific to special:search
486 $out->addModules( 'mediawiki.special.search' );
490 * Extract "power search" namespace settings from the request object,
491 * returning a list of index numbers to search.
493 * @param $request WebRequest
496 protected function powerSearch( &$request ) {
498 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
499 if ( $request->getCheck( 'ns' . $ns ) ) {
508 * Reconstruct the 'power search' options for links
512 protected function powerSearchOptions() {
514 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
515 if ( $this->profile
!== 'advanced' ) {
516 $opt['profile'] = $this->profile
;
518 foreach ( $this->namespaces
as $n ) {
522 return $opt +
$this->extraParams
;
526 * Show whole set of results
528 * @param $matches SearchResultSet
532 protected function showMatches( &$matches ) {
534 wfProfileIn( __METHOD__
);
536 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
539 $infoLine = $matches->getInfo();
540 if ( !is_null( $infoLine ) ) {
541 $out .= "\n<!-- {$infoLine} -->\n";
543 $out .= "<ul class='mw-search-results'>\n";
544 $result = $matches->next();
546 $out .= $this->showHit( $result, $terms );
547 $result = $matches->next();
551 // convert the whole thing to desired language variant
552 $out = $wgContLang->convert( $out );
553 wfProfileOut( __METHOD__
);
558 * Format a single hit result
560 * @param $result SearchResult
561 * @param array $terms terms to highlight
565 protected function showHit( $result, $terms ) {
566 wfProfileIn( __METHOD__
);
568 if ( $result->isBrokenTitle() ) {
569 wfProfileOut( __METHOD__
);
570 return "<!-- Broken link in search result -->\n";
573 $t = $result->getTitle();
575 $titleSnippet = $result->getTitleSnippet( $terms );
577 if ( $titleSnippet == '' ) {
578 $titleSnippet = null;
583 wfRunHooks( 'ShowSearchHitTitle',
584 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
586 $link = Linker
::linkKnown(
591 //If page content is not readable, just return the title.
592 //This is not quite safe, but better than showing excerpts from non-readable pages
593 //Note that hiding the entry entirely would screw up paging.
594 if ( !$t->userCan( 'read', $this->getUser() ) ) {
595 wfProfileOut( __METHOD__
);
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 wfProfileOut( __METHOD__
);
604 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
607 // format redirects / relevant sections
608 $redirectTitle = $result->getRedirectTitle();
609 $redirectText = $result->getRedirectSnippet( $terms );
610 $sectionTitle = $result->getSectionTitle();
611 $sectionText = $result->getSectionSnippet( $terms );
614 if ( !is_null( $redirectTitle ) ) {
615 if ( $redirectText == '' ) {
616 $redirectText = null;
619 $redirect = "<span class='searchalttitle'>" .
620 $this->msg( 'search-redirect' )->rawParams(
621 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
627 if ( !is_null( $sectionTitle ) ) {
628 if ( $sectionText == '' ) {
632 $section = "<span class='searchalttitle'>" .
633 $this->msg( 'search-section' )->rawParams(
634 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
638 // format text extract
639 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
641 $lang = $this->getLanguage();
644 if ( is_null( $result->getScore() ) ) {
645 // Search engine doesn't report scoring info
648 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
649 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
653 // format description
654 $byteSize = $result->getByteSize();
655 $wordCount = $result->getWordCount();
656 $timestamp = $result->getTimestamp();
657 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
658 ->numParams( $wordCount )->escaped();
660 if ( $t->getNamespace() == NS_CATEGORY
) {
661 $cat = Category
::newFromTitle( $t );
662 $size = $this->msg( 'search-result-category-size' )
663 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
667 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
669 // link to related articles if supported
671 if ( $result->hasRelated() ) {
672 $st = SpecialPage
::getTitleFor( 'Search' );
673 $stParams = array_merge(
674 $this->powerSearchOptions(),
676 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
677 ':' . $t->getPrefixedText(),
678 'fulltext' => $this->msg( 'search' )->text()
682 $related = ' -- ' . Linker
::linkKnown(
684 $this->msg( 'search-relatedarticle' )->text(),
690 // Include a thumbnail for media files...
691 if ( $t->getNamespace() == NS_FILE
) {
692 $img = wfFindFile( $t );
694 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
696 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
697 wfProfileOut( __METHOD__
);
698 // Float doesn't seem to interact well with the bullets.
699 // Table messes up vertical alignment of the bullets.
700 // Bullets are therefore disabled (didn't look great anyway).
702 '<table class="searchResultImage">' .
704 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
705 $thumb->toHtml( array( 'desc-link' => true ) ) .
707 '<td style="vertical-align: top;">' .
710 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
721 if ( wfRunHooks( 'ShowSearchHit', array(
722 $this, $result, $terms,
723 &$link, &$redirect, &$section, &$extract,
724 &$score, &$size, &$date, &$related,
727 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
728 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
732 wfProfileOut( __METHOD__
);
737 * Show results from other wikis
739 * @param $matches SearchResultSet
740 * @param $query String
744 protected function showInterwiki( $matches, $query ) {
746 wfProfileIn( __METHOD__
);
747 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
749 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
750 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
751 $out .= "<ul class='mw-search-iwresults'>\n";
753 // work out custom project captions
754 $customCaptions = array();
755 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
756 foreach ( $customLines as $line ) {
757 $parts = explode( ":", $line, 2 );
758 if ( count( $parts ) == 2 ) { // validate line
759 $customCaptions[$parts[0]] = $parts[1];
764 $result = $matches->next();
766 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
767 $prev = $result->getInterwikiPrefix();
768 $result = $matches->next();
770 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
771 $out .= "</ul></div>\n";
773 // convert the whole thing to desired language variant
774 $out = $wgContLang->convert( $out );
775 wfProfileOut( __METHOD__
);
780 * Show single interwiki link
782 * @param $result SearchResult
783 * @param $lastInterwiki String
784 * @param $terms Array
785 * @param $query String
786 * @param array $customCaptions iw prefix -> caption
790 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
791 wfProfileIn( __METHOD__
);
793 if ( $result->isBrokenTitle() ) {
794 wfProfileOut( __METHOD__
);
795 return "<!-- Broken link in search result -->\n";
798 $t = $result->getTitle();
800 $titleSnippet = $result->getTitleSnippet( $terms );
802 if ( $titleSnippet == '' ) {
803 $titleSnippet = null;
806 $link = Linker
::linkKnown(
811 // format redirect if any
812 $redirectTitle = $result->getRedirectTitle();
813 $redirectText = $result->getRedirectSnippet( $terms );
815 if ( !is_null( $redirectTitle ) ) {
816 if ( $redirectText == '' ) {
817 $redirectText = null;
820 $redirect = "<span class='searchalttitle'>" .
821 $this->msg( 'search-redirect' )->rawParams(
822 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
827 // display project name
828 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
829 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
830 // captions from 'search-interwiki-custom'
831 $caption = $customCaptions[$t->getInterwiki()];
833 // default is to show the hostname of the other wiki which might suck
834 // if there are many wikis on one hostname
835 $parsed = wfParseUrl( $t->getFullURL() );
836 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
838 // "more results" link (special page stuff could be localized, but we might not know target lang)
839 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
840 $searchLink = Linker
::linkKnown(
842 $this->msg( 'search-interwiki-more' )->text(),
846 'fulltext' => 'Search'
849 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
850 {$searchLink}</span>{$caption}</div>\n<ul>";
853 $out .= "<li>{$link} {$redirect}</li>\n";
854 wfProfileOut( __METHOD__
);
863 protected function getProfileForm( $profile, $term ) {
866 $opts['redirs'] = $this->searchRedirects
;
867 $opts['profile'] = $this->profile
;
869 if ( $profile === 'advanced' ) {
870 return $this->powerSearchBox( $term, $opts );
873 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
879 * Generates the power search box at [[Special:Search]]
881 * @param string $term search term
883 * @return String: HTML form
885 protected function powerSearchBox( $term, $opts ) {
888 // Groups namespaces into rows according to subject
890 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
891 $subject = MWNamespace
::getSubject( $namespace );
892 if ( !array_key_exists( $subject, $rows ) ) {
893 $rows[$subject] = "";
896 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
898 $name = $this->msg( 'blanknamespace' )->text();
903 'td', array( 'style' => 'white-space: nowrap' )
908 "mw-search-ns{$namespace}",
909 in_array( $namespace, $this->namespaces
)
911 Xml
::closeElement( 'td' );
914 $rows = array_values( $rows );
915 $numRows = count( $rows );
917 // Lays out namespaces in multiple floating two-column tables so they'll
918 // be arranged nicely while still accommodating different screen widths
919 $namespaceTables = '';
920 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
921 $namespaceTables .= Xml
::openElement(
923 array( 'cellpadding' => 0, 'cellspacing' => 0 )
926 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
927 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
930 $namespaceTables .= Xml
::closeElement( 'table' );
933 $showSections = array( 'namespaceTables' => $namespaceTables );
935 // Show redirects check only if backend supports it
936 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
937 $showSections['redirects'] =
938 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
941 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
944 unset( $opts['redirs'] );
945 foreach ( $opts as $key => $value ) {
946 $hidden .= Html
::hidden( $key, $value );
948 // Return final output
949 return Xml
::openElement(
951 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
953 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
954 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
955 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
956 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
957 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
959 Xml
::closeElement( 'fieldset' );
965 protected function getSearchProfiles() {
966 // Builds list of Search Types (profiles)
967 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
971 'message' => 'searchprofile-articles',
972 'tooltip' => 'searchprofile-articles-tooltip',
973 'namespaces' => SearchEngine
::defaultNamespaces(),
974 'namespace-messages' => SearchEngine
::namespacesAsText(
975 SearchEngine
::defaultNamespaces()
979 'message' => 'searchprofile-images',
980 'tooltip' => 'searchprofile-images-tooltip',
981 'namespaces' => array( NS_FILE
),
984 'message' => 'searchprofile-project',
985 'tooltip' => 'searchprofile-project-tooltip',
986 'namespaces' => SearchEngine
::helpNamespaces(),
987 'namespace-messages' => SearchEngine
::namespacesAsText(
988 SearchEngine
::helpNamespaces()
992 'message' => 'searchprofile-everything',
993 'tooltip' => 'searchprofile-everything-tooltip',
994 'namespaces' => $nsAllSet,
997 'message' => 'searchprofile-advanced',
998 'tooltip' => 'searchprofile-advanced-tooltip',
999 'namespaces' => self
::NAMESPACES_CURRENT
,
1003 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1005 foreach ( $profiles as &$data ) {
1006 if ( !is_array( $data['namespaces'] ) ) {
1009 sort( $data['namespaces'] );
1017 * @param $resultsShown
1021 protected function formHeader( $term, $resultsShown, $totalNum ) {
1022 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1025 if ( $this->startsWithImage( $term ) ) {
1027 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1030 $profiles = $this->getSearchProfiles();
1031 $lang = $this->getLanguage();
1033 // Outputs XML for Search Types
1034 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1035 $out .= Xml
::openElement( 'ul' );
1036 foreach ( $profiles as $id => $profile ) {
1037 if ( !isset( $profile['parameters'] ) ) {
1038 $profile['parameters'] = array();
1040 $profile['parameters']['profile'] = $id;
1042 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1043 $lang->commaList( $profile['namespace-messages'] ) : null;
1047 'class' => $this->profile
=== $id ?
'current' : 'normal'
1049 $this->makeSearchLink(
1052 $this->msg( $profile['message'] )->text(),
1053 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1054 $profile['parameters']
1058 $out .= Xml
::closeElement( 'ul' );
1059 $out .= Xml
::closeElement( 'div' );
1062 if ( $resultsShown > 0 ) {
1063 if ( $totalNum > 0 ) {
1064 $top = $this->msg( 'showingresultsheader' )
1065 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1066 ->params( wfEscapeWikiText( $term ) )
1067 ->numParams( $resultsShown )
1069 } elseif ( $resultsShown >= $this->limit
) {
1070 $top = $this->msg( 'showingresults' )
1071 ->numParams( $this->limit
, $this->offset +
1 )
1074 $top = $this->msg( 'showingresultsnum' )
1075 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1078 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1079 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1083 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1084 $out .= Xml
::closeElement( 'div' );
1090 * @param $term string
1093 protected function shortDialog( $term ) {
1094 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() );
1095 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1097 $out .= Html
::input( 'search', $term, 'search', array(
1098 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1101 'class' => 'mw-ui-input',
1103 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1104 $out .= Xml
::submitButton(
1105 $this->msg( 'searchbutton' )->text(),
1106 array( 'class' => array( 'mw-ui-button', 'mw-ui-primary' ) )
1108 return $out . $this->didYouMeanHtml
;
1112 * Make a search link with some target namespaces
1114 * @param $term String
1115 * @param array $namespaces ignored
1116 * @param string $label link's text
1117 * @param string $tooltip link's tooltip
1118 * @param array $params query string parameters
1119 * @return String: HTML fragment
1121 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1123 foreach ( $namespaces as $n ) {
1124 $opt['ns' . $n] = 1;
1126 $opt['redirs'] = $this->searchRedirects
;
1128 $stParams = array_merge(
1131 'fulltext' => $this->msg( 'search' )->text()
1136 return Xml
::element(
1139 'href' => $this->getTitle()->getLocalURL( $stParams ),
1147 * Check if query starts with image: prefix
1149 * @param string $term the string to check
1152 protected function startsWithImage( $term ) {
1155 $p = explode( ':', $term );
1156 if ( count( $p ) > 1 ) {
1157 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1163 * Check if query starts with all: prefix
1165 * @param string $term the string to check
1168 protected function startsWithAll( $term ) {
1170 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1172 $p = explode( ':', $term );
1173 if ( count( $p ) > 1 ) {
1174 return $p[0] == $allkeyword;
1182 * @return SearchEngine
1184 public function getSearchEngine() {
1185 if ( $this->searchEngine
=== null ) {
1186 $this->searchEngine
= $this->searchEngineType ?
1187 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1189 return $this->searchEngine
;
1193 * Users of hook SpecialSearchSetupEngine can use this to
1194 * add more params to links to not lose selection when
1195 * user navigates search results.
1201 public function setExtraParam( $key, $value ) {
1202 $this->extraParams
[$key] = $value;
1205 protected function getGroupName() {