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;
46 protected $extraParams = array();
48 /// No idea, apparently used by some other classes
54 protected $limit, $offset;
59 protected $namespaces;
60 function getNamespaces() { return $this->namespaces
; }
65 protected $searchRedirects;
70 protected $didYouMeanHtml, $fulltext;
72 const NAMESPACES_CURRENT
= 'sense';
74 public function __construct() {
75 parent
::__construct( 'Search' );
81 * @param $par String or null
83 public function execute( $par ) {
85 $this->outputHeader();
86 $out = $this->getOutput();
87 $out->allowClickjacking();
88 $out->addModuleStyles( 'mediawiki.special' );
90 // Strip underscores from title parameter; most of the time we'll want
91 // text form here. But don't strip underscores from actual text params!
92 $titleParam = str_replace( '_', ' ', $par );
94 $request = $this->getRequest();
96 // Fetch the search term
97 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
101 if ( $request->getVal( 'fulltext' )
102 ||
!is_null( $request->getVal( 'offset' ) )
103 ||
!is_null( $request->getVal( 'searchx' ) ) )
105 $this->showResults( $search );
107 $this->goResult( $search );
112 * Set up basic search parameters from the request and user settings.
114 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
116 public function load() {
117 $request = $this->getRequest();
118 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
119 $this->mPrefix
= $request->getVal( 'prefix', '' );
121 $user = $this->getUser();
123 # Extract manually requested namespaces
124 $nslist = $this->powerSearch( $request );
125 if ( !count( $nslist ) ) {
126 # Fallback to user preference
127 $nslist = SearchEngine
::userNamespaces( $user );
131 if ( !count( $nslist ) ) {
132 $profile = 'default';
135 $profile = $request->getVal( 'profile', $profile );
136 $profiles = $this->getSearchProfiles();
137 if ( $profile === null ) {
138 // BC with old request format
139 $profile = 'advanced';
140 foreach( $profiles as $key => $data ) {
141 if ( $nslist === $data['namespaces'] && $key !== 'advanced') {
145 $this->namespaces
= $nslist;
146 } elseif ( $profile === 'advanced' ) {
147 $this->namespaces
= $nslist;
149 if ( isset( $profiles[$profile]['namespaces'] ) ) {
150 $this->namespaces
= $profiles[$profile]['namespaces'];
152 // Unknown profile requested
153 $profile = 'default';
154 $this->namespaces
= $profiles['default']['namespaces'];
158 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
159 $default = $request->getBool( 'profile' ) ?
0 : 1;
160 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
161 $this->didYouMeanHtml
= ''; # html of did you mean... link
162 $this->fulltext
= $request->getVal('fulltext');
163 $this->profile
= $profile;
167 * If an exact title match can be found, jump straight ahead to it.
169 * @param $term String
171 public function goResult( $term ) {
172 $this->setupPage( $term );
173 # Try to go to page as entered.
174 $t = Title
::newFromText( $term );
175 # If the string cannot be used to create a title
176 if( is_null( $t ) ) {
177 return $this->showResults( $term );
179 # If there's an exact or very near match, jump right there.
180 $t = SearchEngine
::getNearMatch( $term );
182 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
183 # Hook requested termination
187 if( !is_null( $t ) ) {
188 $this->getOutput()->redirect( $t->getFullURL() );
191 # No match, generate an edit URL
192 $t = Title
::newFromText( $term );
193 if( !is_null( $t ) ) {
195 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
196 wfDebugLog( 'nogomatch', $t->getText(), false );
198 # If the feature is enabled, go straight to the edit page
200 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
204 return $this->showResults( $term );
208 * @param $term String
210 public function showResults( $term ) {
211 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
212 wfProfileIn( __METHOD__
);
214 $search = $this->getSearchEngine();
215 $search->setLimitOffset( $this->limit
, $this->offset
);
216 $search->setNamespaces( $this->namespaces
);
217 $search->showRedirects
= $this->searchRedirects
; // BC
218 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
219 $search->prefix
= $this->mPrefix
;
220 $term = $search->transformSearchTerm($term);
222 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
224 $this->setupPage( $term );
226 $out = $this->getOutput();
228 if ( $wgDisableTextSearch ) {
229 if ( $wgSearchForwardUrl ) {
230 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
231 $out->redirect( $url );
234 Xml
::openElement( 'fieldset' ) .
235 Xml
::element( 'legend', null, wfMsg( 'search-external' ) ) .
236 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
237 wfMsg( 'googlesearch',
238 htmlspecialchars( $term ),
239 htmlspecialchars( 'UTF-8' ),
240 htmlspecialchars( wfMsg( 'searchbutton' ) )
242 Xml
::closeElement( 'fieldset' )
245 wfProfileOut( __METHOD__
);
249 $t = Title
::newFromText( $term );
251 // fetch search results
252 $rewritten = $search->replacePrefixes($term);
254 $titleMatches = $search->searchTitle( $rewritten );
255 if( !( $titleMatches instanceof SearchResultTooMany
) ) {
256 $textMatches = $search->searchText( $rewritten );
259 // did you mean... suggestions
260 if( $textMatches && $textMatches->hasSuggestion() ) {
261 $st = SpecialPage
::getTitleFor( 'Search' );
263 # mirror Go/Search behaviour of original request ..
264 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
266 if( $this->fulltext
!= null ) {
267 $didYouMeanParams['fulltext'] = $this->fulltext
;
270 $stParams = array_merge(
272 $this->powerSearchOptions()
275 $suggestionSnippet = $textMatches->getSuggestionSnippet();
277 if( $suggestionSnippet == '' ) {
278 $suggestionSnippet = null;
281 $suggestLink = Linker
::linkKnown(
288 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
290 // start rendering the page
295 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
297 'action' => $wgScript
302 Xml
::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
303 Xml
::openElement( 'tr' ) .
304 Xml
::openElement( 'td' ) . "\n" .
305 $this->shortDialog( $term ) .
306 Xml
::closeElement('td') .
307 Xml
::closeElement('tr') .
308 Xml
::closeElement('table')
311 // Sometimes the search engine knows there are too many hits
312 if( $titleMatches instanceof SearchResultTooMany
) {
313 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
314 wfProfileOut( __METHOD__
);
318 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE
).':';
319 if( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
320 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
321 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
322 $out->addHTML( '</form>' );
323 // Empty query -- straight view of search form
324 wfProfileOut( __METHOD__
);
328 // Get number of results
329 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
330 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
331 // Total initial query matches (possible false positives)
332 $num = $titleMatchesNum +
$textMatchesNum;
334 // Get total actual results (after second filtering, if any)
335 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
336 $titleMatches->getTotalHits() : $titleMatchesNum;
337 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
338 $textMatches->getTotalHits() : $textMatchesNum;
340 // get total number of results if backend can calculate it
342 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
343 $totalRes +
= $titleMatches->getTotalHits();
344 if($textMatches && !is_null( $textMatches->getTotalHits() ))
345 $totalRes +
= $textMatches->getTotalHits();
347 // show number of results and current offset
348 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
349 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
352 $out->addHtml( Xml
::closeElement( 'form' ) );
353 $out->addHtml( "<div class='searchresults'>" );
356 if( $num ||
$this->offset
) {
357 // Show the create link ahead
358 $this->showCreateLink( $t );
359 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset
, $this->limit
,
360 $this->powerSearchOptions() +
array( 'search' => $term ),
361 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
363 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
364 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
366 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
369 $out->parserOptions()->setEditSection( false );
370 if( $titleMatches ) {
371 if( $numTitleMatches > 0 ) {
372 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
373 $out->addHTML( $this->showMatches( $titleMatches ) );
375 $titleMatches->free();
378 // output appropriate heading
379 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
380 // if no title matches the heading is redundant
381 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
382 } elseif( $totalRes == 0 ) {
383 # Don't show the 'no text matches' if we received title matches
384 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
386 // show interwiki results if any
387 if( $textMatches->hasInterwikiResults() ) {
388 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
391 if( $numTextMatches > 0 ) {
392 $out->addHTML( $this->showMatches( $textMatches ) );
395 $textMatches->free();
398 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
399 $this->showCreateLink( $t );
401 $out->addHtml( "</div>" );
403 if( $num ||
$this->offset
) {
404 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
406 wfProfileOut( __METHOD__
);
412 protected function showCreateLink( $t ) {
413 // show direct page/create link if applicable
415 // Check DBkey !== '' in case of fragment link only.
416 if( is_null( $t ) ||
$t->getDBkey() === '' ) {
418 // preserve the paragraph for margins etc...
419 $this->getOutput()->addHtml( '<p></p>' );
423 if( $t->isKnown() ) {
424 $messageName = 'searchmenu-exists';
425 } elseif( $t->userCan( 'create' ) ) {
426 $messageName = 'searchmenu-new';
428 $messageName = 'searchmenu-new-nocreate';
430 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
431 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
433 // Extensions using the hook might still return an empty $messageName
435 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
437 // preserve the paragraph for margins etc...
438 $this->getOutput()->addHtml( '<p></p>' );
443 * @param $term string
445 protected function setupPage( $term ) {
446 # Should advanced UI be used?
447 $this->searchAdvanced
= ($this->profile
=== 'advanced');
448 $out = $this->getOutput();
449 if( strval( $term ) !== '' ) {
450 $out->setPageTitle( $this->msg( 'searchresults' ) );
451 $out->setHTMLTitle( $this->msg( 'pagetitle', $this->msg( 'searchresults-title', $term )->plain() ) );
453 // add javascript specific to special:search
454 $out->addModules( 'mediawiki.special.search' );
458 * Extract "power search" namespace settings from the request object,
459 * returning a list of index numbers to search.
461 * @param $request WebRequest
464 protected function powerSearch( &$request ) {
466 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
467 if( $request->getCheck( 'ns' . $ns ) ) {
476 * Reconstruct the 'power search' options for links
480 protected function powerSearchOptions() {
482 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
483 if( $this->profile
!== 'advanced' ) {
484 $opt['profile'] = $this->profile
;
486 foreach( $this->namespaces
as $n ) {
490 return $opt +
$this->extraParams
;
494 * Show whole set of results
496 * @param $matches SearchResultSet
500 protected function showMatches( &$matches ) {
502 wfProfileIn( __METHOD__
);
504 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
507 $infoLine = $matches->getInfo();
508 if( !is_null($infoLine) ) {
509 $out .= "\n<!-- {$infoLine} -->\n";
511 $out .= "<ul class='mw-search-results'>\n";
512 $result = $matches->next();
514 $out .= $this->showHit( $result, $terms );
515 $result = $matches->next();
519 // convert the whole thing to desired language variant
520 $out = $wgContLang->convert( $out );
521 wfProfileOut( __METHOD__
);
526 * Format a single hit result
528 * @param $result SearchResult
529 * @param $terms Array: terms to highlight
533 protected function showHit( $result, $terms ) {
534 wfProfileIn( __METHOD__
);
536 if( $result->isBrokenTitle() ) {
537 wfProfileOut( __METHOD__
);
538 return "<!-- Broken link in search result -->\n";
541 $t = $result->getTitle();
543 $titleSnippet = $result->getTitleSnippet($terms);
545 if( $titleSnippet == '' )
546 $titleSnippet = null;
550 wfRunHooks( 'ShowSearchHitTitle',
551 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
553 $link = Linker
::linkKnown(
558 //If page content is not readable, just return the title.
559 //This is not quite safe, but better than showing excerpts from non-readable pages
560 //Note that hiding the entry entirely would screw up paging.
561 if( !$t->userCan( 'read' ) ) {
562 wfProfileOut( __METHOD__
);
563 return "<li>{$link}</li>\n";
566 // If the page doesn't *exist*... our search index is out of date.
567 // The least confusing at this point is to drop the result.
568 // You may get less results, but... oh well. :P
569 if( $result->isMissingRevision() ) {
570 wfProfileOut( __METHOD__
);
571 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
574 // format redirects / relevant sections
575 $redirectTitle = $result->getRedirectTitle();
576 $redirectText = $result->getRedirectSnippet($terms);
577 $sectionTitle = $result->getSectionTitle();
578 $sectionText = $result->getSectionSnippet($terms);
581 if( !is_null($redirectTitle) ) {
582 if( $redirectText == '' )
583 $redirectText = null;
585 $redirect = "<span class='searchalttitle'>" .
598 if( !is_null($sectionTitle) ) {
599 if( $sectionText == '' )
602 $section = "<span class='searchalttitle'>" .
604 'search-section', Linker
::linkKnown(
612 // format text extract
613 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
615 $lang = $this->getLanguage();
618 if( is_null( $result->getScore() ) ) {
619 // Search engine doesn't report scoring info
622 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
623 $score = wfMsg( 'search-result-score', $lang->formatNum( $percent ) )
627 // format description
628 $byteSize = $result->getByteSize();
629 $wordCount = $result->getWordCount();
630 $timestamp = $result->getTimestamp();
632 'search-result-size',
633 array( 'parsemag', 'escape' ),
634 $lang->formatSize( $byteSize ),
635 $lang->formatNum( $wordCount )
638 if( $t->getNamespace() == NS_CATEGORY
) {
639 $cat = Category
::newFromTitle( $t );
641 'search-result-category-size',
642 array( 'parsemag', 'escape' ),
643 $lang->formatNum( $cat->getPageCount() ),
644 $lang->formatNum( $cat->getSubcatCount() ),
645 $lang->formatNum( $cat->getFileCount() )
649 $date = $lang->timeanddate( $timestamp );
651 // link to related articles if supported
653 if( $result->hasRelated() ) {
654 $st = SpecialPage
::getTitleFor( 'Search' );
655 $stParams = array_merge(
656 $this->powerSearchOptions(),
658 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
659 'fulltext' => wfMsg( 'search' )
663 $related = ' -- ' . Linker
::linkKnown(
665 wfMsg('search-relatedarticle'),
671 // Include a thumbnail for media files...
672 if( $t->getNamespace() == NS_FILE
) {
673 $img = wfFindFile( $t );
675 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
677 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
678 wfProfileOut( __METHOD__
);
679 // Float doesn't seem to interact well with the bullets.
680 // Table messes up vertical alignment of the bullets.
681 // Bullets are therefore disabled (didn't look great anyway).
683 '<table class="searchResultImage">' .
685 '<td width="120" align="center" valign="top">' .
686 $thumb->toHtml( array( 'desc-link' => true ) ) .
688 '<td valign="top">' .
691 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
700 wfProfileOut( __METHOD__
);
701 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
702 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
708 * Show results from other wikis
710 * @param $matches SearchResultSet
711 * @param $query String
715 protected function showInterwiki( &$matches, $query ) {
717 wfProfileIn( __METHOD__
);
718 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
720 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
721 wfMsg('search-interwiki-caption')."</div>\n";
722 $out .= "<ul class='mw-search-iwresults'>\n";
724 // work out custom project captions
725 $customCaptions = array();
726 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
727 foreach($customLines as $line) {
728 $parts = explode(":",$line,2);
729 if(count($parts) == 2) // validate line
730 $customCaptions[$parts[0]] = $parts[1];
734 $result = $matches->next();
736 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
737 $prev = $result->getInterwikiPrefix();
738 $result = $matches->next();
740 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
741 $out .= "</ul></div>\n";
743 // convert the whole thing to desired language variant
744 $out = $wgContLang->convert( $out );
745 wfProfileOut( __METHOD__
);
750 * Show single interwiki link
752 * @param $result SearchResult
753 * @param $lastInterwiki String
754 * @param $terms Array
755 * @param $query String
756 * @param $customCaptions Array: iw prefix -> caption
760 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
761 wfProfileIn( __METHOD__
);
763 if( $result->isBrokenTitle() ) {
764 wfProfileOut( __METHOD__
);
765 return "<!-- Broken link in search result -->\n";
768 $t = $result->getTitle();
770 $titleSnippet = $result->getTitleSnippet($terms);
772 if( $titleSnippet == '' )
773 $titleSnippet = null;
775 $link = Linker
::linkKnown(
780 // format redirect if any
781 $redirectTitle = $result->getRedirectTitle();
782 $redirectText = $result->getRedirectSnippet($terms);
784 if( !is_null($redirectTitle) ) {
785 if( $redirectText == '' )
786 $redirectText = null;
788 $redirect = "<span class='searchalttitle'>" .
800 // display project name
801 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()) {
802 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
803 // captions from 'search-interwiki-custom'
804 $caption = $customCaptions[$t->getInterwiki()];
806 // default is to show the hostname of the other wiki which might suck
807 // if there are many wikis on one hostname
808 $parsed = wfParseUrl( $t->getFullURL() );
809 $caption = wfMsg('search-interwiki-default', $parsed['host']);
811 // "more results" link (special page stuff could be localized, but we might not know target lang)
812 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
813 $searchLink = Linker
::linkKnown(
815 wfMsg('search-interwiki-more'),
819 'fulltext' => 'Search'
822 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
823 {$searchLink}</span>{$caption}</div>\n<ul>";
826 $out .= "<li>{$link} {$redirect}</li>\n";
827 wfProfileOut( __METHOD__
);
836 protected function getProfileForm( $profile, $term ) {
839 $opts['redirs'] = $this->searchRedirects
;
840 $opts['profile'] = $this->profile
;
842 if ( $profile === 'advanced' ) {
843 return $this->powerSearchBox( $term, $opts );
846 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
852 * Generates the power search box at [[Special:Search]]
854 * @param $term String: search term
856 * @return String: HTML form
858 protected function powerSearchBox( $term, $opts ) {
859 // Groups namespaces into rows according to subject
861 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
862 $subject = MWNamespace
::getSubject( $namespace );
863 if( !array_key_exists( $subject, $rows ) ) {
864 $rows[$subject] = "";
866 $name = str_replace( '_', ' ', $name );
868 $name = wfMsg( 'blanknamespace' );
872 'td', array( 'style' => 'white-space: nowrap' )
877 "mw-search-ns{$namespace}",
878 in_array( $namespace, $this->namespaces
)
880 Xml
::closeElement( 'td' );
882 $rows = array_values( $rows );
883 $numRows = count( $rows );
885 // Lays out namespaces in multiple floating two-column tables so they'll
886 // be arranged nicely while still accommodating different screen widths
887 $namespaceTables = '';
888 for( $i = 0; $i < $numRows; $i +
= 4 ) {
889 $namespaceTables .= Xml
::openElement(
891 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
893 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
894 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
896 $namespaceTables .= Xml
::closeElement( 'table' );
899 $showSections = array( 'namespaceTables' => $namespaceTables );
901 // Show redirects check only if backend supports it
902 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
903 $showSections['redirects'] =
904 Xml
::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects
);
907 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
910 unset( $opts['redirs'] );
911 foreach( $opts as $key => $value ) {
912 $hidden .= Html
::hidden( $key, $value );
914 // Return final output
918 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
920 Xml
::element( 'legend', null, wfMsg('powersearch-legend') ) .
921 Xml
::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
924 array( 'id' => 'mw-search-togglebox' ),
925 Xml
::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
930 'id' => 'mw-search-toggleall',
931 'value' => wfMsg( 'powersearch-toggleall' )
938 'id' => 'mw-search-togglenone',
939 'value' => wfMsg( 'powersearch-togglenone' )
943 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
944 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
946 Xml
::closeElement( 'fieldset' );
952 protected function getSearchProfiles() {
953 // Builds list of Search Types (profiles)
954 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
958 'message' => 'searchprofile-articles',
959 'tooltip' => 'searchprofile-articles-tooltip',
960 'namespaces' => SearchEngine
::defaultNamespaces(),
961 'namespace-messages' => SearchEngine
::namespacesAsText(
962 SearchEngine
::defaultNamespaces()
966 'message' => 'searchprofile-images',
967 'tooltip' => 'searchprofile-images-tooltip',
968 'namespaces' => array( NS_FILE
),
971 'message' => 'searchprofile-project',
972 'tooltip' => 'searchprofile-project-tooltip',
973 'namespaces' => SearchEngine
::helpNamespaces(),
974 'namespace-messages' => SearchEngine
::namespacesAsText(
975 SearchEngine
::helpNamespaces()
979 'message' => 'searchprofile-everything',
980 'tooltip' => 'searchprofile-everything-tooltip',
981 'namespaces' => $nsAllSet,
984 'message' => 'searchprofile-advanced',
985 'tooltip' => 'searchprofile-advanced-tooltip',
986 'namespaces' => self
::NAMESPACES_CURRENT
,
990 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
992 foreach( $profiles as &$data ) {
993 if ( !is_array( $data['namespaces'] ) ) continue;
994 sort( $data['namespaces'] );
1002 * @param $resultsShown
1006 protected function formHeader( $term, $resultsShown, $totalNum ) {
1007 $out = Xml
::openElement('div', array( 'class' => 'mw-search-formheader' ) );
1010 if( $this->startsWithImage( $term ) ) {
1012 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1015 $profiles = $this->getSearchProfiles();
1016 $lang = $this->getLanguage();
1018 // Outputs XML for Search Types
1019 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1020 $out .= Xml
::openElement( 'ul' );
1021 foreach ( $profiles as $id => $profile ) {
1022 if ( !isset( $profile['parameters'] ) ) {
1023 $profile['parameters'] = array();
1025 $profile['parameters']['profile'] = $id;
1027 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1028 $lang->commaList( $profile['namespace-messages'] ) : null;
1032 'class' => $this->profile
=== $id ?
'current' : 'normal'
1034 $this->makeSearchLink(
1037 wfMsg( $profile['message'] ),
1038 wfMsg( $profile['tooltip'], $tooltipParam ),
1039 $profile['parameters']
1043 $out .= Xml
::closeElement( 'ul' );
1044 $out .= Xml
::closeElement('div') ;
1047 if ( $resultsShown > 0 ) {
1048 if ( $totalNum > 0 ){
1049 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
1050 $lang->formatNum( $this->offset +
1 ),
1051 $lang->formatNum( $this->offset +
$resultsShown ),
1052 $lang->formatNum( $totalNum ),
1053 wfEscapeWikiText( $term ),
1054 $lang->formatNum( $resultsShown )
1056 } elseif ( $resultsShown >= $this->limit
) {
1057 $top = wfMsgExt( 'showingresults', array( 'parseinline' ),
1058 $lang->formatNum( $this->limit
),
1059 $lang->formatNum( $this->offset +
1 )
1062 $top = wfMsgExt( 'showingresultsnum', array( 'parseinline' ),
1063 $lang->formatNum( $this->limit
),
1064 $lang->formatNum( $this->offset +
1 ),
1065 $lang->formatNum( $resultsShown )
1068 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1069 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1073 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1074 $out .= Xml
::closeElement('div');
1080 * @param $term string
1083 protected function shortDialog( $term ) {
1084 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() );
1085 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1087 $out .= Html
::input( 'search', $term, 'search', array(
1088 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1092 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1093 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1094 return $out . $this->didYouMeanHtml
;
1098 * Make a search link with some target namespaces
1100 * @param $term String
1101 * @param $namespaces Array ignored
1102 * @param $label String: link's text
1103 * @param $tooltip String: link's tooltip
1104 * @param $params Array: query string parameters
1105 * @return String: HTML fragment
1107 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1109 foreach( $namespaces as $n ) {
1110 $opt['ns' . $n] = 1;
1112 $opt['redirs'] = $this->searchRedirects
;
1114 $stParams = array_merge(
1117 'fulltext' => wfMsg( 'search' )
1122 return Xml
::element(
1125 'href' => $this->getTitle()->getLocalURL( $stParams ),
1126 'title' => $tooltip),
1132 * Check if query starts with image: prefix
1134 * @param $term String: the string to check
1137 protected function startsWithImage( $term ) {
1140 $p = explode( ':', $term );
1141 if( count( $p ) > 1 ) {
1142 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1148 * Check if query starts with all: prefix
1150 * @param $term String: the string to check
1153 protected function startsWithAll( $term ) {
1155 $allkeyword = wfMsgForContent('searchall');
1157 $p = explode( ':', $term );
1158 if( count( $p ) > 1 ) {
1159 return $p[0] == $allkeyword;
1167 * @return SearchEngine
1169 public function getSearchEngine() {
1170 if ( $this->searchEngine
=== null ) {
1171 $this->searchEngine
= SearchEngine
::create();
1173 return $this->searchEngine
;
1177 * Users of hook SpecialSearchSetupEngine can use this to
1178 * add more params to links to not lose selection when
1179 * user navigates search results.
1185 public function setExtraParam( $key, $value ) {
1186 $this->extraParams
[$key] = $value;